Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aien-sovereign-core-mv/blob/main/crates/aien-trace/src/lib.rs # aien-sovereign-core-mv AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aien-sovereign-core-mv / crates / aien-trace / src / lib.rs` 1270 lines ยท 40745 bytes Raw Blame History 1 // SPDX-License-Identifier: Apache-2.0 2 // Copyright 2026 Drake Stapleton (AIEN / aien-dev) 3 // 4 // Licensed under the Apache License, Version 2.0 (the "License"); 5 // you may not use this file except in compliance with the License. 6 // You may obtain a copy of the License at 7 // 8 // http://www.apache.org/licenses/LICENSE-2.0 9 // 10 // Unless required by applicable law or agreed to in writing, software 11 // distributed under the License is distributed on an "AS IS" BASIS, 12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 // See the License for the specific language governing permissions and 14 // limitations under the License. 15 16 //! Correlation-only execution trace for AIEN (aien-sovereign-core#398). 17 //! 18 //! A trace event says "this boundary was crossed, with these ids". It is 19 //! OBSERVATIONAL. It is not evidence and it is not authorization: the 20 //! `EffectReceipt` ledger, the compose ledger, the generation record and the 21 //! independent receipt verifier keep governing. An event only points at those 22 //! artifacts by digest or relative path. 23 //! 24 //! Privacy is enforced by type. This crate never carries prompts, tool 25 //! arguments, model output or memory items. The only free text is 26 //! [`BoundedNote`] (64 bytes, sanitized). Every other string is a 27 //! [`BoundedId`] (64 chars from a small alphabet), a [`Digest`] (hex) or a 28 //! [`RelPath`] (relative, no `..`). Deserialization re-applies the same rules, 29 //! so a tampered file cannot smuggle a longer or wider field through. 30 //! 31 //! The default sink is [`NullSink`]: tracing is off unless a caller installs 32 //! another sink. 33 34 use std::collections::{HashMap, VecDeque}; 35 use std::fmt; 36 use std::fs::OpenOptions; 37 use std::io::Write; 38 use std::path::{Path, PathBuf}; 39 use std::sync::atomic::{AtomicU64, Ordering}; 40 use std::sync::mpsc::{self, RecvTimeoutError}; 41 use std::sync::{Arc, Mutex, MutexGuard}; 42 use std::thread::JoinHandle; 43 use std::time::{Duration, SystemTime, UNIX_EPOCH}; 44 45 use serde::{Deserialize, Serialize}; 46 47 /// Longest accepted [`BoundedId`], in characters. 48 pub const MAX_ID_CHARS: usize = 64; 49 /// Longest accepted [`BoundedNote`], in bytes. 50 pub const MAX_NOTE_BYTES: usize = 64; 51 /// Default queue capacity of [`BoundedJsonlSink`]. 52 pub const DEFAULT_CAPACITY: usize = 4096; 53 const MAX_DIGEST_CHARS: usize = 128; 54 const MAX_PATH_BYTES: usize = 256; 55 56 /// Errors of this crate. 57 #[derive(Debug, Clone, PartialEq, Eq)] 58 pub enum TraceError { 59 /// Not 32 lowercase-or-uppercase hex characters. 60 BadTraceId, 61 /// A digest was empty, too long or not hex. 62 BadDigest, 63 /// A path was absolute, contained `..`, or was empty or too long. 64 BadPath, 65 /// An event names a parent that is not in the set. 66 MissingParent { event_id: u64, parent: u64 }, 67 /// The events do not all share one trace id. 68 MixedTraceIds, 69 /// Two events share an event id. 70 DuplicateEvent(u64), 71 /// No events given. 72 Empty, 73 } 74 75 impl fmt::Display for TraceError { 76 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 77 match self { 78 Self::BadTraceId => write!(f, "trace id must be 32 hex characters"), 79 Self::BadDigest => write!(f, "digest must be 1..=128 hex characters"), 80 Self::BadPath => write!(f, "path must be relative, without `..`"), 81 Self::MissingParent { event_id, parent } => { 82 write!(f, "event {event_id} names missing parent {parent}") 83 } 84 Self::MixedTraceIds => write!(f, "events belong to more than one trace"), 85 Self::DuplicateEvent(id) => write!(f, "duplicate event id {id}"), 86 Self::Empty => write!(f, "no events"), 87 } 88 } 89 } 90 91 impl std::error::Error for TraceError {} 92 93 fn lock(m: &Mutex) -> MutexGuard<'_, T> { 94 m.lock().unwrap_or_else(|e| e.into_inner()) 95 } 96 97 /// Wall clock in unix milliseconds (0 if the clock is before the epoch). 98 pub fn now_unix_ms() -> u64 { 99 SystemTime::now() 100 .duration_since(UNIX_EPOCH) 101 .map(|d| d.as_millis() as u64) 102 .unwrap_or(0) 103 } 104 105 fn mix64(mut x: u64) -> u64 { 106 // splitmix64 finalizer. 107 x = x.wrapping_add(0x9E37_79B9_7F4A_7C15); 108 x = (x ^ (x >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); 109 x = (x ^ (x >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); 110 x ^ (x >> 31) 111 } 112 113 /// 16-byte run identifier. 114 /// 115 /// A correlation key only. It is NEVER a secret and NEVER a proof: anyone can 116 /// compute or copy one, so nothing may be authorized or believed because a 117 /// trace id matches. 118 #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] 119 pub struct TraceId(pub [u8; 16]); 120 121 impl TraceId { 122 /// Mixes the inputs with splitmix64 applied twice per half. Deterministic: 123 /// the same inputs give the same id. Not a cryptographic hash. 124 pub fn derive(seed_a: u64, seed_b: u64, counter: u64) -> Self { 125 let hi = mix64(mix64(seed_a) ^ counter); 126 let lo = mix64(mix64(seed_b ^ hi) ^ counter.rotate_left(32)); 127 let mut out = [0u8; 16]; 128 out[..8].copy_from_slice(&hi.to_be_bytes()); 129 out[8..].copy_from_slice(&lo.to_be_bytes()); 130 Self(out) 131 } 132 133 /// 32 lowercase hex characters. 134 pub fn to_hex(&self) -> String { 135 const H: &[u8; 16] = b"`0123456789abcdef`"; 136 let mut s = String::with_capacity(32); 137 for b in self.0 { 138 s.push(H[(b >> 4) as usize] as char); 139 s.push(H[(b & 15) as usize] as char); 140 } 141 s 142 } 143 144 /// Parses 32 hex characters (either case). 145 pub fn parse_hex(s: &str) -> Result { 146 let b = s.as_bytes(); 147 if b.len() != 32 { 148 return Err(TraceError::BadTraceId); 149 } 150 let nib = |c: u8| match c { 151 b'0'..=b'9' => Ok(c - b'0'), 152 b'a'..=b'f' => Ok(c - b'a' + 10), 153 b'A'..=b'F' => Ok(c - b'A' + 10), 154 _ => Err(TraceError::BadTraceId), 155 }; 156 let mut out = [0u8; 16]; 157 for i in 0..16 { 158 out[i] = (nib(b[2 * i])? << 4) | nib(b[2 * i + 1])?; 159 } 160 Ok(Self(out)) 161 } 162 } 163 164 impl fmt::Display for TraceId { 165 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 166 f.write_str(&self.to_hex()) 167 } 168 } 169 170 impl fmt::Debug for TraceId { 171 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 172 write!(f, "TraceId({})", self.to_hex()) 173 } 174 } 175 176 impl Serialize for TraceId { 177 fn serialize(&self, s: S) -> Result { 178 s.serialize_str(&self.to_hex()) 179 } 180 } 181 182 impl<'de> Deserialize<'de> for TraceId { 183 fn deserialize>(d: D) -> Result { 184 let s = String::deserialize(d)?; 185 Self::parse_hex(&s).map_err(serde::de::Error::custom) 186 } 187 } 188 189 /// What boundary was crossed. 190 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] 191 #[serde(rename_all = "snake_case")] 192 #[non_exhaustive] 193 pub enum EventKind { 194 SwarmLaunched, 195 BranchForked, 196 SequenceAdmitted, 197 SequencePreempted, 198 SequenceFinished, 199 SwarmCancelled, 200 ModelTurn, 201 ToolRequested, 202 AuthorityDecided, 203 EffectExecuted, 204 ResultReceived, 205 Failure, 206 Cancelled, 207 TimedOut, 208 InterplaneRequest, 209 TraceDropped, 210 } 211 212 /// Terminal or current state of the boundary. 213 /// 214 /// One to one with the AEGIS `FailureClass` vocabulary (Rejected, 215 /// Unavailable, Timeout, Cancelled, Uncertain, Failed, Malformed, 216 /// ApprovalPending) plus `ok` for success. `rejected` also covers Interplane 217 /// decisions `denied`, `not_found` and `invalid`. `approval_pending` is not a 218 /// failure and is terminal for the attempt. `uncertain` maps to aien-mcp 219 /// `CallOutcome::Uncertain`: the request may have reached the server, and it 220 /// is never retried automatically. 221 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] 222 #[serde(rename_all = "snake_case")] 223 #[non_exhaustive] 224 pub enum EventStatus { 225 Ok, 226 Rejected, 227 Unavailable, 228 TimedOut, 229 Cancelled, 230 Uncertain, 231 Failed, 232 Malformed, 233 ApprovalPending, 234 } 235 236 /// Whether an external effect happened, as far as the recorder knows. 237 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] 238 #[serde(rename_all = "snake_case")] 239 #[non_exhaustive] 240 pub enum EffectCertainty { 241 NoEffect, 242 Uncertain, 243 EffectOccurred, 244 } 245 246 /// Short identifier: at most 64 characters from `[A-Za-z0-9._:-]`; anything 247 /// else is dropped, extra length is cut. 248 #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] 249 #[serde(from = "String", into = "String")] 250 pub struct BoundedId(String); 251 252 impl BoundedId { 253 pub fn new(s: &str) -> Self { 254 Self( 255 s.chars() 256 .filter(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | ':' | '-')) 257 .take(MAX_ID_CHARS) 258 .collect(), 259 ) 260 } 261 pub fn as_str(&self) -> &str { 262 &self.0 263 } 264 } 265 impl From for BoundedId { 266 fn from(s: String) -> Self { 267 Self::new(&s) 268 } 269 } 270 impl From for String { 271 fn from(b: BoundedId) -> Self { 272 b.0 273 } 274 } 275 276 /// The ONLY free-text field of an event. Control characters, `<` and `>` are 277 /// removed, then the text is cut to 64 bytes on a character boundary. 278 #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] 279 #[serde(from = "String", into = "String")] 280 pub struct BoundedNote(String); 281 282 impl BoundedNote { 283 pub fn new(s: &str) -> Self { 284 let mut out = String::new(); 285 for c in s 286 .chars() 287 .filter(|c| !c.is_control() && *c != '<' && *c != '>') 288 { 289 if out.len() + c.len_utf8() > MAX_NOTE_BYTES { 290 break; 291 } 292 out.push(c); 293 } 294 Self(out) 295 } 296 pub fn as_str(&self) -> &str { 297 &self.0 298 } 299 } 300 impl From for BoundedNote { 301 fn from(s: String) -> Self { 302 Self::new(&s) 303 } 304 } 305 impl From for String { 306 fn from(b: BoundedNote) -> Self { 307 b.0 308 } 309 } 310 311 /// Hex digest, 1..=128 characters. 312 #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] 313 #[serde(try_from = "String", into = "String")] 314 pub struct Digest(String); 315 316 impl Digest { 317 pub fn new(s: &str) -> Result { 318 if s.is_empty() || s.len() > MAX_DIGEST_CHARS || !s.bytes().all(|b| b.is_ascii_hexdigit()) { 319 return Err(TraceError::BadDigest); 320 } 321 Ok(Self(s.to_ascii_lowercase())) 322 } 323 pub fn as_str(&self) -> &str { 324 &self.0 325 } 326 } 327 impl TryFrom for Digest { 328 type Error = TraceError; 329 fn try_from(s: String) -> Result { 330 Self::new(&s) 331 } 332 } 333 impl From for String { 334 fn from(d: Digest) -> Self { 335 d.0 336 } 337 } 338 339 /// Relative path: not absolute, no `..` component, no NUL, at most 256 bytes. 340 #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] 341 #[serde(try_from = "String", into = "String")] 342 pub struct RelPath(String); 343 344 impl RelPath { 345 pub fn new(s: &str) -> Result { 346 let bad = s.is_empty() 347 || s.len() > MAX_PATH_BYTES 348 || s.contains('\0') 349 || s.starts_with('/') 350 || s.starts_with('\\') 351 || s.as_bytes().get(1) == Some(&b':') 352 || s.split(['/', '\\']).any(|p| p == ".."); 353 if bad { 354 return Err(TraceError::BadPath); 355 } 356 Ok(Self(s.to_string())) 357 } 358 pub fn as_str(&self) -> &str { 359 &self.0 360 } 361 } 362 impl TryFrom for RelPath { 363 type Error = TraceError; 364 fn try_from(s: String) -> Result { 365 Self::new(&s) 366 } 367 } 368 impl From for String { 369 fn from(p: RelPath) -> Self { 370 p.0 371 } 372 } 373 374 /// Ids a trace can join on. All optional. 375 #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] 376 #[serde(default)] 377 pub struct CorrelationIds { 378 pub swarm_id: Option, 379 pub world_id: Option, 380 pub root_sequence_id: Option, 381 pub sequence_id: Option, 382 pub step_id: Option, 383 pub model_turn: Option, 384 pub tool_request_id: Option, 385 pub decision_id: Option, 386 pub grant_id: Option, 387 pub generation_record: Option, 388 pub interplane_trace_id: Option, 389 pub interplane_message_id: Option, 390 pub interplane_request_id: Option, 391 } 392 393 /// Pointers to independent proof artifacts. A pointer is not proof. 394 #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] 395 #[serde(default)] 396 pub struct EvidenceRefs { 397 pub effect_receipt_digest: Option, 398 pub result_digest: Option, 399 pub provenance_record: Option, 400 pub intent_digest: Option, 401 } 402 403 impl EvidenceRefs { 404 pub fn with_effect_receipt_digest(mut self, hex: &str) -> Result { 405 self.effect_receipt_digest = Some(Digest::new(hex)?); 406 Ok(self) 407 } 408 pub fn with_result_digest(mut self, hex: &str) -> Result { 409 self.result_digest = Some(Digest::new(hex)?); 410 Ok(self) 411 } 412 pub fn with_intent_digest(mut self, hex: &str) -> Result { 413 self.intent_digest = Some(Digest::new(hex)?); 414 Ok(self) 415 } 416 /// Refuses absolute paths and `..`. 417 pub fn with_provenance_record(mut self, path: &str) -> Result { 418 self.provenance_record = Some(RelPath::new(path)?); 419 Ok(self) 420 } 421 } 422 423 /// One boundary crossing. 424 #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] 425 pub struct TraceEvent { 426 pub trace_id: TraceId, 427 /// Monotonic per sink. 428 pub event_id: u64, 429 pub parent_event_id: Option, 430 pub at_unix_ms: u64, 431 pub kind: EventKind, 432 pub status: EventStatus, 433 #[serde(default)] 434 pub effect_certainty: Option, 435 #[serde(default)] 436 pub ids: CorrelationIds, 437 #[serde(default)] 438 pub refs: EvidenceRefs, 439 #[serde(default)] 440 pub note: Option, 441 } 442 443 /// Destination of events. Implementations must never block the caller for I/O. 444 pub trait TraceSink: Send + Sync { 445 /// False for sinks that discard everything, so callers can skip building events. 446 fn enabled(&self) -> bool { 447 true 448 } 449 fn emit(&self, event: TraceEvent); 450 fn next_event_id(&self) -> u64; 451 } 452 453 /// Discards everything. The default everywhere. 454 #[derive(Debug, Default)] 455 pub struct NullSink; 456 457 impl TraceSink for NullSink { 458 fn enabled(&self) -> bool { 459 false 460 } 461 fn emit(&self, _event: TraceEvent) {} 462 fn next_event_id(&self) -> u64 { 463 0 464 } 465 } 466 467 /// Keeps events in memory. For tests. 468 #[derive(Debug, Default)] 469 pub struct MemorySink { 470 events: Mutex>, 471 next: AtomicU64, 472 } 473 474 impl MemorySink { 475 pub fn new() -> Self { 476 Self::default() 477 } 478 pub fn drain(&self) -> Vec { 479 std::mem::take(&mut *lock(&self.events)) 480 } 481 } 482 483 impl TraceSink for MemorySink { 484 fn emit(&self, event: TraceEvent) { 485 lock(&self.events).push(event); 486 } 487 fn next_event_id(&self) -> u64 { 488 self.next.fetch_add(1, Ordering::Relaxed) + 1 489 } 490 } 491 492 /// Bounded in-memory queue flushed to an append-only JSONL file. 493 /// 494 /// `emit` takes a mutex only for one queue push and never does I/O. When the 495 /// queue is full the event is dropped and counted; the next `flush` appends one 496 /// `trace_dropped` event saying how many. No thread runs unless 497 /// [`BoundedJsonlSink::spawn_flusher`] is called. 498 #[derive(Debug)] 499 pub struct BoundedJsonlSink { 500 path: PathBuf, 501 capacity: usize, 502 queue: Mutex>, 503 next: AtomicU64, 504 dropped: AtomicU64, 505 dropped_total: AtomicU64, 506 last_trace: Mutex, 507 } 508 509 /// Refuses an export path that is a symbolic link, so nothing is written 510 /// through a link planted at the configured path. An absent path is fine (the 511 /// file is created). Metadata errors other than "absent" are returned. 512 fn refuse_symlink(path: &Path) -> std::io::Result<()> { 513 match std::fs::symlink_metadata(path) { 514 Ok(m) if m.file_type().is_symlink() => Err(std::io::Error::new( 515 std::io::ErrorKind::InvalidInput, 516 "trace export path is a symbolic link", 517 )), 518 Ok(_) => Ok(()), 519 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()), 520 Err(e) => Err(e), 521 } 522 } 523 524 impl BoundedJsonlSink { 525 pub fn new(path: impl Into) -> Self { 526 Self::with_capacity(path, DEFAULT_CAPACITY) 527 } 528 529 pub fn with_capacity(path: impl Into, capacity: usize) -> Self { 530 let capacity = capacity.max(1); 531 Self { 532 path: path.into(), 533 capacity, 534 queue: Mutex::new(VecDeque::with_capacity(capacity)), 535 next: AtomicU64::new(0), 536 dropped: AtomicU64::new(0), 537 dropped_total: AtomicU64::new(0), 538 last_trace: Mutex::new(TraceId([0; 16])), 539 } 540 } 541 542 /// Lifetime number of dropped events. 543 pub fn dropped_total(&self) -> u64 { 544 self.dropped_total.load(Ordering::Relaxed) 545 } 546 547 pub fn path(&self) -> &Path { 548 &self.path 549 } 550 551 /// Appends queued events, one JSON object per line. The path must not be a 552 /// symbolic link (a link is refused and the batch counted as dropped); the 553 /// file is created with mode 0o600 on unix and set back to 0o600 on every 554 /// flush. After drops, one `trace_dropped` event follows. 555 pub fn flush(&self) -> std::io::Result<()> { 556 let batch: Vec = lock(&self.queue).drain(..).collect(); 557 let pending = self.dropped.swap(0, Ordering::Relaxed); 558 if batch.is_empty() && pending == 0 { 559 return Ok(()); 560 } 561 let mut lines = Vec::new(); 562 for e in &batch { 563 serde_json::to_writer(&mut lines, e).map_err(std::io::Error::other)?; 564 lines.push(b'\n'); 565 } 566 if pending > 0 { 567 let trace_id = batch 568 .last() 569 .map(|e| e.trace_id) 570 .unwrap_or(*lock(&self.last_trace)); 571 let marker = TraceEvent { 572 trace_id, 573 event_id: self.next_event_id(), 574 parent_event_id: None, 575 at_unix_ms: now_unix_ms(), 576 kind: EventKind::TraceDropped, 577 status: EventStatus::Ok, 578 effect_certainty: None, 579 ids: CorrelationIds::default(), 580 refs: EvidenceRefs::default(), 581 note: Some(BoundedNote::new(&format!("dropped {pending} events"))), 582 }; 583 serde_json::to_writer(&mut lines, &marker).map_err(std::io::Error::other)?; 584 lines.push(b'\n'); 585 } 586 let mut opts = OpenOptions::new(); 587 opts.create(true).append(true); 588 #[cfg(unix)] 589 { 590 use std::os::unix::fs::OpenOptionsExt; 591 opts.mode(0o600); 592 } 593 let result = refuse_symlink(&self.path) 594 .and_then(|()| opts.open(&self.path)) 595 .and_then(|mut f| { 596 #[cfg(unix)] 597 { 598 use std::os::unix::fs::PermissionsExt; 599 f.set_permissions(std::fs::Permissions::from_mode(0o600))?; 600 } 601 f.write_all(&lines) 602 }); 603 if result.is_err() { 604 // Not written: report the loss instead of hiding it. 605 let lost = batch.len() as u64 + pending; 606 self.dropped.fetch_add(lost, Ordering::Relaxed); 607 self.dropped_total 608 .fetch_add(batch.len() as u64, Ordering::Relaxed); 609 } 610 result 611 } 612 613 /// Starts a thread that flushes every `interval` and once more on stop. 614 pub fn spawn_flusher(self: &Arc, interval: Duration) -> FlusherHandle { 615 let sink = Arc::clone(self); 616 let (tx, rx) = mpsc::channel::<()>(); 617 let join = std::thread::spawn(move || loop { 618 match rx.recv_timeout(interval) { 619 Err(RecvTimeoutError::Timeout) => { 620 let _ = sink.flush(); 621 } 622 _ => { 623 let _ = sink.flush(); 624 break; 625 } 626 } 627 }); 628 FlusherHandle { 629 stop: Some(tx), 630 join: Some(join), 631 } 632 } 633 } 634 635 impl TraceSink for BoundedJsonlSink { 636 fn emit(&self, event: TraceEvent) { 637 let mut q = lock(&self.queue); 638 if q.len() >= self.capacity { 639 drop(q); 640 self.dropped.fetch_add(1, Ordering::Relaxed); 641 self.dropped_total.fetch_add(1, Ordering::Relaxed); 642 return; 643 } 644 q.push_back(event); 645 } 646 fn next_event_id(&self) -> u64 { 647 self.next.fetch_add(1, Ordering::Relaxed) + 1 648 } 649 } 650 651 /// Handle of the flusher thread. Dropping it stops the thread. 652 #[derive(Debug)] 653 pub struct FlusherHandle { 654 stop: Option>, 655 join: Option>, 656 } 657 658 impl FlusherHandle { 659 /// Stops the thread after one last flush. 660 pub fn stop(mut self) { 661 self.shutdown(); 662 } 663 fn shutdown(&mut self) { 664 self.stop.take(); 665 if let Some(j) = self.join.take() { 666 let _ = j.join(); 667 } 668 } 669 } 670 671 impl Drop for FlusherHandle { 672 fn drop(&mut self) { 673 self.shutdown(); 674 } 675 } 676 677 /// Emits events of one trace with correct parent links. 678 #[derive(Clone)] 679 pub struct TraceContext { 680 trace_id: TraceId, 681 sink: Arc, 682 last: Arc, 683 } 684 685 const NO_EVENT: u64 = u64::MAX; 686 687 impl TraceContext { 688 pub fn new(trace_id: TraceId, sink: Arc) -> Self { 689 Self { 690 trace_id, 691 sink, 692 last: Arc::new(AtomicU64::new(NO_EVENT)), 693 } 694 } 695 696 pub fn trace_id(&self) -> TraceId { 697 self.trace_id 698 } 699 700 /// Id of the most recent event emitted through this context, if any. 701 pub fn last_event_id(&self) -> Option { 702 match self.last.load(Ordering::Relaxed) { 703 NO_EVENT => None, 704 v => Some(v), 705 } 706 } 707 708 fn put( 709 &self, 710 parent: Option, 711 kind: EventKind, 712 status: EventStatus, 713 ids: CorrelationIds, 714 refs: EvidenceRefs, 715 note: Option, 716 ) -> u64 { 717 if !self.sink.enabled() { 718 return 0; 719 } 720 let id = self.sink.next_event_id(); 721 self.sink.emit(TraceEvent { 722 trace_id: self.trace_id, 723 event_id: id, 724 parent_event_id: parent, 725 at_unix_ms: now_unix_ms(), 726 kind, 727 status, 728 effect_certainty: None, 729 ids, 730 refs, 731 note, 732 }); 733 self.last.store(id, Ordering::Relaxed); 734 id 735 } 736 737 /// First event: no parent. 738 pub fn root( 739 &self, 740 kind: EventKind, 741 status: EventStatus, 742 ids: CorrelationIds, 743 refs: EvidenceRefs, 744 note: Option, 745 ) -> u64 { 746 self.put(None, kind, status, ids, refs, note) 747 } 748 749 /// Child of the most recent event of this context. 750 pub fn child( 751 &self, 752 kind: EventKind, 753 status: EventStatus, 754 ids: CorrelationIds, 755 refs: EvidenceRefs, 756 note: Option, 757 ) -> u64 { 758 self.put(self.last_event_id(), kind, status, ids, refs, note) 759 } 760 761 /// Child of a named event, for fan-out and across task boundaries. 762 pub fn child_of( 763 &self, 764 parent: u64, 765 kind: EventKind, 766 status: EventStatus, 767 ids: CorrelationIds, 768 refs: EvidenceRefs, 769 note: Option, 770 ) -> u64 { 771 self.put(Some(parent), kind, status, ids, refs, note) 772 } 773 } 774 775 /// Parent/child tree of one trace. 776 #[derive(Debug)] 777 pub struct Tree { 778 events: Vec, 779 children: HashMap>, 780 roots: Vec, 781 } 782 783 impl Tree { 784 /// Events sorted by `(at_unix_ms, event_id)`. 785 pub fn chronological(&self) -> Vec<&TraceEvent> { 786 let mut v: Vec<&TraceEvent> = self.events.iter().collect(); 787 v.sort_by_key(|e| (e.at_unix_ms, e.event_id)); 788 v 789 } 790 /// Event ids whose parent is `id`, in event id order. 791 pub fn children(&self, id: u64) -> &[u64] { 792 self.children.get(&id).map(Vec::as_slice).unwrap_or(&[]) 793 } 794 /// Events without a parent. 795 pub fn roots(&self) -> &[u64] { 796 &self.roots 797 } 798 pub fn get(&self, id: u64) -> Option<&TraceEvent> { 799 self.events.iter().find(|e| e.event_id == id) 800 } 801 pub fn len(&self) -> usize { 802 self.events.len() 803 } 804 pub fn is_empty(&self) -> bool { 805 self.events.is_empty() 806 } 807 } 808 809 /// Builds the tree of one trace. Fails on mixed trace ids, duplicate event 810 /// ids, or a parent that is not in the set. 811 pub fn reconstruct(events: &[TraceEvent]) -> Result { 812 let first = events.first().ok_or(TraceError::Empty)?; 813 let mut ids = HashMap::new(); 814 for e in events { 815 if e.trace_id != first.trace_id { 816 return Err(TraceError::MixedTraceIds); 817 } 818 if ids.insert(e.event_id, ()).is_some() { 819 return Err(TraceError::DuplicateEvent(e.event_id)); 820 } 821 } 822 let mut children: HashMap> = HashMap::new(); 823 let mut roots = Vec::new(); 824 for e in events { 825 match e.parent_event_id { 826 None => roots.push(e.event_id), 827 Some(p) if ids.contains_key(&p) => children.entry(p).or_default().push(e.event_id), 828 Some(p) => { 829 return Err(TraceError::MissingParent { 830 event_id: e.event_id, 831 parent: p, 832 }) 833 } 834 } 835 } 836 roots.sort_unstable(); 837 for v in children.values_mut() { 838 v.sort_unstable(); 839 } 840 Ok(Tree { 841 events: events.to_vec(), 842 children, 843 roots, 844 }) 845 } 846 847 #[cfg(test)] 848 mod tests { 849 use super::*; 850 use serde_json::Value; 851 852 const ALL_STATUS: [EventStatus; 9] = [ 853 EventStatus::Ok, 854 EventStatus::Rejected, 855 EventStatus::Unavailable, 856 EventStatus::TimedOut, 857 EventStatus::Cancelled, 858 EventStatus::Uncertain, 859 EventStatus::Failed, 860 EventStatus::Malformed, 861 EventStatus::ApprovalPending, 862 ]; 863 864 fn tmp(name: &str) -> PathBuf { 865 static N: AtomicU64 = AtomicU64::new(0); 866 std::env::temp_dir().join(format!( 867 "aien-trace-{name}-{}-{}-{}.jsonl", 868 std::process::id(), 869 N.fetch_add(1, Ordering::Relaxed), 870 now_unix_ms() 871 )) 872 } 873 874 fn ev(trace: TraceId, id: u64, parent: Option) -> TraceEvent { 875 TraceEvent { 876 trace_id: trace, 877 event_id: id, 878 parent_event_id: parent, 879 at_unix_ms: id, 880 kind: EventKind::ModelTurn, 881 status: EventStatus::Ok, 882 effect_certainty: None, 883 ids: CorrelationIds::default(), 884 refs: EvidenceRefs::default(), 885 note: None, 886 } 887 } 888 889 #[test] 890 fn hex_round_trip_and_derive_is_deterministic() { 891 let a = TraceId::derive(1, 2, 3); 892 assert_eq!(a, TraceId::derive(1, 2, 3)); 893 assert_ne!(a, TraceId::derive(1, 2, 4)); 894 assert_ne!(a, TraceId::derive(2, 1, 3)); 895 let h = a.to_hex(); 896 assert_eq!(h.len(), 32); 897 assert!(h 898 .bytes() 899 .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))); 900 assert_eq!(TraceId::parse_hex(&h).unwrap(), a); 901 assert_eq!(format!("{a}"), h); 902 assert!(TraceId::parse_hex("zz").is_err()); 903 assert!(TraceId::parse_hex(&"g".repeat(32)).is_err()); 904 } 905 906 #[test] 907 fn status_strings_are_distinct_and_exact() { 908 let mut got: Vec = ALL_STATUS 909 .iter() 910 .map(|s| { 911 serde_json::to_value(s) 912 .unwrap() 913 .as_str() 914 .unwrap() 915 .to_string() 916 }) 917 .collect(); 918 got.sort(); 919 let mut want: Vec = [ 920 "ok", 921 "rejected", 922 "unavailable", 923 "timed_out", 924 "cancelled", 925 "uncertain", 926 "failed", 927 "malformed", 928 "approval_pending", 929 ] 930 .iter() 931 .map(|s| s.to_string()) 932 .collect(); 933 want.sort(); 934 assert_eq!(got, want); 935 let mut dedup = got.clone(); 936 dedup.dedup(); 937 assert_eq!(dedup.len(), 9); 938 let c: Vec = [ 939 EffectCertainty::NoEffect, 940 EffectCertainty::Uncertain, 941 EffectCertainty::EffectOccurred, 942 ] 943 .iter() 944 .map(|s| { 945 serde_json::to_value(s) 946 .unwrap() 947 .as_str() 948 .unwrap() 949 .to_string() 950 }) 951 .collect(); 952 assert_eq!(c, ["no_effect", "uncertain", "effect_occurred"]); 953 } 954 955 #[test] 956 fn fan_out_reconstructs_with_valid_parents() { 957 let sink = Arc::new(MemorySink::new()); 958 let ctx = TraceContext::new(TraceId::derive(7, 8, 1), sink.clone()); 959 let root = ctx.root( 960 EventKind::SwarmLaunched, 961 EventStatus::Ok, 962 CorrelationIds { 963 swarm_id: Some(1), 964 ..Default::default() 965 }, 966 EvidenceRefs::default(), 967 None, 968 ); 969 let mut tool_events = Vec::new(); 970 for b in 0..3u64 { 971 let branch = ctx.child_of( 972 root, 973 EventKind::BranchForked, 974 EventStatus::Ok, 975 CorrelationIds { 976 sequence_id: Some(b), 977 ..Default::default() 978 }, 979 EvidenceRefs::default(), 980 None, 981 ); 982 let t = ctx.child( 983 EventKind::ToolRequested, 984 EventStatus::Ok, 985 CorrelationIds::default(), 986 EvidenceRefs::default(), 987 None, 988 ); 989 let d = ctx.child( 990 EventKind::AuthorityDecided, 991 EventStatus::ApprovalPending, 992 CorrelationIds::default(), 993 EvidenceRefs::default(), 994 None, 995 ); 996 tool_events.push((branch, t, d)); 997 } 998 let events = sink.drain(); 999 assert_eq!(events.len(), 10); 1000 let tree = reconstruct(&events).unwrap(); 1001 assert_eq!(tree.roots(), &[root]); 1002 assert_eq!(tree.children(root).len(), 3); 1003 for (branch, t, d) in tool_events { 1004 assert_eq!(tree.get(t).unwrap().parent_event_id, Some(branch)); 1005 assert_eq!(tree.get(d).unwrap().parent_event_id, Some(t)); 1006 assert_eq!(tree.children(branch), &[t]); 1007 } 1008 let order: Vec = tree.chronological().iter().map(|e| e.event_id).collect(); 1009 let mut sorted = order.clone(); 1010 sorted.sort(); 1011 assert_eq!(order, sorted); 1012 } 1013 1014 #[test] 1015 fn reconstruct_rejects_missing_parent_and_mixed_traces() { 1016 let t = TraceId::derive(1, 1, 1); 1017 let evs = vec![ev(t, 1, None), ev(t, 2, Some(9))]; 1018 assert_eq!( 1019 reconstruct(&evs).unwrap_err(), 1020 TraceError::MissingParent { 1021 event_id: 2, 1022 parent: 9 1023 } 1024 ); 1025 let evs = vec![ev(t, 1, None), ev(TraceId::derive(2, 2, 2), 2, Some(1))]; 1026 assert_eq!(reconstruct(&evs).unwrap_err(), TraceError::MixedTraceIds); 1027 assert_eq!(reconstruct(&[]).unwrap_err(), TraceError::Empty); 1028 } 1029 1030 #[test] 1031 fn jsonl_round_trip() { 1032 let path = tmp("rt"); 1033 let sink = Arc::new(BoundedJsonlSink::new(&path)); 1034 let ctx = TraceContext::new(TraceId::derive(3, 3, 3), sink.clone()); 1035 let r = ctx.root( 1036 EventKind::SwarmLaunched, 1037 EventStatus::Ok, 1038 CorrelationIds::default(), 1039 EvidenceRefs::default(), 1040 None, 1041 ); 1042 ctx.child( 1043 EventKind::EffectExecuted, 1044 EventStatus::Uncertain, 1045 CorrelationIds { 1046 tool_request_id: Some(BoundedId::new("req-1")), 1047 ..Default::default() 1048 }, 1049 EvidenceRefs::default() 1050 .with_intent_digest("ABCDEF01") 1051 .unwrap(), 1052 Some(BoundedNote::new("may have reached server")), 1053 ); 1054 sink.flush().unwrap(); 1055 let text = std::fs::read_to_string(&path).unwrap(); 1056 let events: Vec = text 1057 .lines() 1058 .map(|l| serde_json::from_str(l).unwrap()) 1059 .collect(); 1060 assert_eq!(events.len(), 2); 1061 assert_eq!(events[0].event_id, r); 1062 assert_eq!( 1063 events[1].refs.intent_digest.as_ref().unwrap().as_str(), 1064 "`abcdef01`" 1065 ); 1066 assert_eq!(events[1].status, EventStatus::Uncertain); 1067 assert!(reconstruct(&events).is_ok()); 1068 #[cfg(unix)] 1069 { 1070 use std::os::unix::fs::PermissionsExt; 1071 assert_eq!( 1072 std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 1073 0o600 1074 ); 1075 } 1076 let _ = std::fs::remove_file(&path); 1077 } 1078 1079 #[cfg(unix)] 1080 #[test] 1081 fn symlink_path_is_refused_and_mode_is_reset_on_every_flush() { 1082 use std::os::unix::fs::PermissionsExt; 1083 // A link planted at the export path: nothing is written through it, 1084 // the batch is counted as dropped, the target stays empty. 1085 let target = tmp("symlink-target"); 1086 std::fs::write(&target, b"").unwrap(); 1087 let link = tmp("symlink"); 1088 std::os::unix::fs::symlink(&target, &link).unwrap(); 1089 let sink = BoundedJsonlSink::new(&link); 1090 let t = TraceId::derive(1, 2, 3); 1091 sink.emit(TraceEvent { 1092 trace_id: t, 1093 event_id: sink.next_event_id(), 1094 parent_event_id: None, 1095 at_unix_ms: 1, 1096 kind: EventKind::SwarmLaunched, 1097 status: EventStatus::Ok, 1098 effect_certainty: None, 1099 ids: CorrelationIds::default(), 1100 refs: EvidenceRefs::default(), 1101 note: None, 1102 }); 1103 assert!(sink.flush().is_err()); 1104 assert_eq!(std::fs::read(&target).unwrap().len(), 0); 1105 assert_eq!(sink.dropped_total(), 1); 1106 let _ = std::fs::remove_file(&link); 1107 let _ = std::fs::remove_file(&target); 1108 1109 // A pre-existing file with a wide mode is narrowed to 0o600 on flush. 1110 let path = tmp("mode"); 1111 std::fs::write(&path, b"").unwrap(); 1112 std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap(); 1113 let sink = BoundedJsonlSink::new(&path); 1114 sink.emit(TraceEvent { 1115 trace_id: t, 1116 event_id: sink.next_event_id(), 1117 parent_event_id: None, 1118 at_unix_ms: 1, 1119 kind: EventKind::SwarmLaunched, 1120 status: EventStatus::Ok, 1121 effect_certainty: None, 1122 ids: CorrelationIds::default(), 1123 refs: EvidenceRefs::default(), 1124 note: None, 1125 }); 1126 sink.flush().unwrap(); 1127 assert_eq!( 1128 std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 1129 0o600 1130 ); 1131 assert_eq!(std::fs::read_to_string(&path).unwrap().lines().count(), 1); 1132 let _ = std::fs::remove_file(&path); 1133 } 1134 1135 #[test] 1136 fn overflow_counts_drops_and_writes_one_marker() { 1137 let path = tmp("drop"); 1138 let sink = BoundedJsonlSink::with_capacity(&path, 4); 1139 let t = TraceId::derive(4, 4, 4); 1140 for i in 0..10u64 { 1141 sink.emit(ev( 1142 t, 1143 sink.next_event_id(), 1144 if i == 0 { None } else { Some(1) }, 1145 )); 1146 } 1147 assert_eq!(sink.dropped_total(), 6); 1148 sink.flush().unwrap(); 1149 let text = std::fs::read_to_string(&path).unwrap(); 1150 let events: Vec = text 1151 .lines() 1152 .map(|l| serde_json::from_str(l).unwrap()) 1153 .collect(); 1154 let drops: Vec<_> = events 1155 .iter() 1156 .filter(|e| e.kind == EventKind::TraceDropped) 1157 .collect(); 1158 assert_eq!(drops.len(), 1); 1159 assert_eq!(drops[0].note.as_ref().unwrap().as_str(), "dropped 6 events"); 1160 assert_eq!(events.len(), 5); 1161 // Counter reset: a second flush adds no marker. 1162 sink.flush().unwrap(); 1163 assert_eq!(std::fs::read_to_string(&path).unwrap().lines().count(), 5); 1164 assert_eq!(sink.dropped_total(), 6); 1165 let _ = std::fs::remove_file(&path); 1166 } 1167 1168 #[test] 1169 fn flusher_writes_on_stop() { 1170 let path = tmp("flusher"); 1171 let sink = Arc::new(BoundedJsonlSink::new(&path)); 1172 let h = sink.spawn_flusher(Duration::from_secs(3600)); 1173 sink.emit(ev(TraceId::derive(5, 5, 5), sink.next_event_id(), None)); 1174 h.stop(); 1175 assert_eq!(std::fs::read_to_string(&path).unwrap().lines().count(), 1); 1176 let _ = std::fs::remove_file(&path); 1177 } 1178 1179 #[test] 1180 fn note_strips_and_truncates_on_char_boundary() { 1181 let n = BoundedNote::new("ac\u{0}d\ne\u{7f}f"); 1182 assert_eq!(n.as_str(), "abcdef"); 1183 // 63 ASCII bytes then a 2-byte char: the cut must fall before it. 1184 let s = format!("{}\u{e9}z", "x".repeat(63)); 1185 let n = BoundedNote::new(&s); 1186 assert_eq!(n.as_str().len(), 63); 1187 assert!(n.as_str().chars().all(|c| c == 'x')); 1188 let s = format!("{}\u{e9}", "x".repeat(62)); 1189 assert_eq!(BoundedNote::new(&s).as_str().len(), 64); 1190 // Deserialization re-applies the rule. 1191 let back: BoundedNote = serde_json::from_str("\"