From c1566b2f62daba0b13d555821a70b21d5e1513c2 Mon Sep 17 00:00:00 2001 From: aien Date: Sat, 10 Oct 2026 10:53:20 -0500 Subject: [PATCH 1/9] docs: inventory of trace join keys for #398 Co-authored-by: Drake Stapleton Co-Authored-By: Claude Fable 5.1 --- docs/plans/tracing/INVENTORY-398.md | 79 +++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 docs/plans/tracing/INVENTORY-398.md diff --git a/docs/plans/tracing/INVENTORY-398.md b/docs/plans/tracing/INVENTORY-398.md new file mode 100644 index 00000000..536d2496 --- /dev/null +++ b/docs/plans/tracing/INVENTORY-398.md @@ -0,0 +1,79 @@ +# Inventory for #398: ids and recording sites a correlation trace can join on + +Read from main at the branch point. Line numbers are from that checkout. Roles: +AUTH = authorization (decides whether something may run), EVID = evidence +(records what happened), NEITHER = bookkeeping or an observation tap. +A trace event is NEITHER by design: it points at AUTH and EVID, never replaces them. + +## Scheduler (`crates/aien-scheduler`) +| Site | What | Role | +|---|---|---| +| `src/sequence.rs:11` `SequenceId {slot: u32, generation: u32}`; packed u64 via `from_u64` / `Into` (`:50`, `:56`) | Per-sequence id, slot plus generation. Layout in doc comment at `:8`. | NEITHER | +| `src/lib.rs:82` `step_id` field, set `:99`, stamped into the batch `:399`, incremented `:433` and `:961` | Scheduler step counter, local to one scheduler instance. Not unique across restarts. | NEITHER | +| `src/lib.rs:61` `SchedulerMetrics` (counters only; `admitted_requests` bumped `:229`, `:256`; `preempted_requests` `:499`, `:1104`; `finished_requests` `:1108`, `:1154`; `total_steps` `:1181`) | Aggregates. No per-sequence or per-swarm key, so it cannot be joined on. | NEITHER | +| `src/lib.rs:157` `submit_request` returns `SequenceId`; `:261` `fork_sequence`; `:286` `fork_subagent` | Admission entry points. Natural place for `sequence_admitted`. | NEITHER | +| `src/lib.rs:108` `set_decision_observer`; call site `:424` | Read-only tap, once per `build_scheduled_batch`, `None` by default. | NEITHER | +| `src/dual_observer.rs:239` `DecisionObserver::observe_admit_preempt(&AdmitPreemptRecord)`; record `:215` carries `step_id` and, via `AdmissionCandidate.seq` (`:150`), the `SequenceId` of admission candidates | Decision record of the DUAL experiment. Observation only; return type is `()`. | EVID for scheduler choices (DUAL), not for tool authority | + +## Swarm (`crates/aien-runtime/src/swarm.rs`) +| Site | What | Role | +|---|---|---| +| `:80` `swarm_id` from `next_swarm_id` (starts 1, `:65`), returned by `launch_swarm` (`:71`) | Per-process counter. Resets on daemon restart (UNVERIFIED whether it is ever persisted; no persistence seen in this file). | NEITHER | +| `:31` `SwarmRecord {id, root_sequence_id, branch_sequences, branch_worlds, finished_branches, state}`; `SwarmState` `:11` | Swarm to sequence to world mapping. | NEITHER | +| `:84`, `:116`, `:117` root world id, `fork_world`, `arena.fork` | World ids and branch `SequenceId`s are created together at fork. Branch KV is forked later by `fork_branches_from_ready_root` (`:172`). | NEITHER | +| `:221` `cancel_swarm`; `:274` `note_sequence_finished` | Cancel and natural completion. Both drop branch worlds. No event is recorded today. | NEITHER | +| `src/spine.rs:309` `AienRuntimeSpine::launch_swarm`; `:193`-`:210` finish path: `SequenceId::from_u64(request_id)` then `note_sequence_finished` | The `request_id` of a finished stream IS the packed sequence id here. | NEITHER | +| `src/client.rs:108` `cancel_swarm` sends `ControlCommand::CancelSwarm(swarm_id)` | Control entry for cancel. | NEITHER | + +## Generation record (`crates/aien-runtime/src/generation.rs`) +| Site | What | Role | +|---|---|---| +| `:12` `GENERATION` marker; `:125` `build_record` | Daemon-authored note in the compose ledger: model and tokenizer sha256, prompt/output token-id hashes, finish reason, daemon pid/start, `request_id` and `operation_id`. Doc (`:1`-`:8`): "EVIDENCE ONLY", no grant, intent or effect decision reads it. | EVID | +| `:41` `request_id`, `:42` `operation_id` | "Caller-asserted: the client chooses the envelope ids; recorded, not trusted" (`:139`). Do not treat as proof of identity. | EVID (untrusted field) | +| `:168` `PROVENANCE`, `:180` `Provenance {generation_record: Option, allen_agent, stale_generation, note}` | Link from a commit/grant/intent/ack to the generation record id (a compose ledger record id). Reserved key; no ledger reader parses it for decisions (`:171`). | EVID | +| `src/spine.rs:2651` `write_task_generation`, used `:2579`; `Provenance::new` `:2580` | Where the generation record id is minted for a run. | EVID | + +## MCP broker (`crates/aien-mcp`) +| Site | What | Role | +|---|---|---| +| `src/wire.rs:8` `CallOutcome {Finished(Value), Rejected(String), Uncertain}` | Provider answer. `Uncertain` means the request may have reached the server and is never resent. | EVID (provider side) | +| `src/effect.rs:9` `EffectIntent {provider, tool_name, arguments, capability_digest}` | What is to be run. Carries arguments, so a trace must not copy it. | NEITHER | +| `src/authority.rs:149` `intent_digest(&EffectIntent) -> Digest32` | Digest naming one intent. Join key to approval and ledger. | NEITHER (name only) | +| `src/authority.rs:25` `AuthorityDecision {Allow, AllowRestricted, RequireApproval, Deny, Contain}`; `:133` `AuthorityOutcome {Pending, Approval, Denied, Contained, Execution}` | Policy verdict and the reasons nothing ran. | AUTH | +| `src/broker.rs:293` `EffectLane::authorize`; `:308` `authorize_approved`; `:344` policy digest computed | Mints `AuthorizedEffect`; the only production mint. | AUTH | +| `src/effect.rs:64` `AuthorizedEffect` (private fields; `approval_id()` `:76`, `world_id()` `:99`, `winning_jnode()` `:103`, `policy_digest()` `:107`, `idempotency_key()` `:115`) | Capability token in the type system. Cannot be built from a trace. | AUTH | +| `src/approval.rs:105` `ApprovalDesk::issue`; grant id = `Digest32::of(counter ++ intent_digest ++ idempotency_key)` (`:112`-`:118`); `ApprovalGrant::id()` `:86` is crate-private | Approval grant id (32 bytes). Counter is per broker. | AUTH | +| `src/broker.rs:32` `LedgerEntry {InFlight, Completed(EffectReceipt), Uncertain}`; row keyed by `EffectId`, bound to `EffectIdentity {intent digest, world_id, winning_jnode}` (`:43`) | In-memory idempotency ledger. | EVID (in memory only, UNVERIFIED whether persisted elsewhere) | +| `src/broker.rs:485` execute; receipt built `:544` | `EffectReceipt {effect_id, world_id, winning_jnode, policy_digest, provider, tool_name, capability_digest, output}` (`effect.rs:25`). `Finished` stores Completed, `Uncertain` or transport error stores Uncertain and returns `ReconciliationRequired`, `Rejected` removes the row. | EVID | +| No `EffectReceipt` digest function seen in `effect.rs` or `broker.rs`. Receipt digest for a trace is UNVERIFIED: must be defined by the instrumenter (for example over a canonical encoding) or taken from the Interplane receipt verifier. | | | + +## Compose daemon (`crates/aien-runtime/src/spine.rs`, `effects.rs`) +All ids below are compose ledger record ids (u64, one append-only journal), not hashes. +| Stage | Site | Role | +|---|---|---| +| Proposal and commit | `spine.rs:2438` `run_task_inner`; model run; commit record `effects.rs:1277` `write_compose_commit`, called `spine.rs:2581`, stamped with `Provenance` | EVID (commit claim) | +| Mint grant | `effects.rs:1335` `authorize` (`ComposeAuthorize`), `:1326` `mint_grant`; also `write_approved_grant` `:1182` for approved compose | AUTH | +| Open intent | `effects.rs:1592` `open_intent`; text has `phase: "intent"`, `authorization: ` (`:1626`) | AUTH check, then EVID of the intent record | +| Execute and ack | `effects.rs:1641` `ack`; phase `ack` (`:14`); links `[intent, authorization]` | EVID (executor report plus world state) | +| Record mark | `spine.rs:2058` `advance_mark`; called after commit `:2598`, and on `:2364`, `:2546`, `:2714`, `:2972`; types in `cortex_mark.rs:123` `MarkRefusal` | EVID (tamper evidence for the journal) | +| Reconcile | `effects.rs:1673` `reconcile`, phase `reconcile` (`:15`), `:1858` `reconcile_at_start`; gate `:705` `reconcile_gate`; `spine.rs:2385` `set_reconcile_failed` | EVID, and a gate that refuses effect commands | +| Effect states | `effects.rs:52` `EffectState {Open, Done, NotDone, Unresolved}` | EVID | + +Refusal names (`effects.rs:85`, text `EFFECT_REFUSED : detail`), verified by grep of +`Refusal::new` call sites: Stopped, NotAuthorized, AlreadySpent, ReconciliationRequired, +Revoked, Stale, ReconcileFailed, NotRegular, MissingParent, CorruptLedger, Unreadable, +OutsideWorkspace, DeskMacRequired, Replayed, AlreadyAuthorized. Mark errors (`spine.rs`): +E_MARK, E_MARK_TRUNCATED, E_MARK_DIGEST, E_MARK_WRITE; also E_REPLAY (`spine.rs:2334`). +All are AUTH outcomes (a refusal), mapped by a trace to a status, never reinterpreted. + +## Join keys +| Link | Key | Notes | +|---|---|---| +| swarm to branch/root | `swarm_id` (u64), `SequenceId` as u64 | `SwarmRecord` `swarm.rs:31` | +| sequence to world | `world_id` (u64) | fork time, `swarm.rs:116` | +| sequence to scheduler step | `step_id` (u64) | `AdmitPreemptRecord.step_id`; per scheduler instance | +| sequence to stream/generation | `request_id` equals packed `SequenceId` on the finish path (`spine.rs:193`) | generation `request_id` is caller-asserted | +| model turn to commit/grant/intent/ack | `generation_record` (ledger id) via `Provenance` | evidence only | +| proposal to grant to intent to ack | ledger record ids: `authorization` field, `links` | `effects.rs:1626` | +| tool request to approval to receipt | `intent_digest`, approval grant id (`approval_id()`), `EffectId` idempotency key, `world_id`, `winning_jnode` | `broker.rs:43` | +| AIEN to Interplane | UNVERIFIED: no Interplane id exists in this repo yet; coordinate with interplane#97 | trace id is minted here and handed over | From 0b936ba113a8bbe5fab7092949f7ce012650db1f Mon Sep 17 00:00:00 2001 From: aien Date: Sat, 10 Oct 2026 10:55:12 -0500 Subject: [PATCH 2/9] feat(aien-trace): correlation-only trace events, bounded sinks, reconstruction (#398) Co-authored-by: Drake Stapleton Co-Authored-By: Claude Fable 5.1 --- Cargo.lock | 8 + Cargo.toml | 1 + crates/aien-trace/Cargo.toml | 16 + crates/aien-trace/README.md | 57 ++ crates/aien-trace/src/lib.rs | 1162 ++++++++++++++++++++++++++++++++++ 5 files changed, 1244 insertions(+) create mode 100644 crates/aien-trace/Cargo.toml create mode 100644 crates/aien-trace/README.md create mode 100644 crates/aien-trace/src/lib.rs diff --git a/Cargo.lock b/Cargo.lock index f6234199..313fe068 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -400,6 +400,14 @@ dependencies = [ "sha2 0.10.9", ] +[[package]] +name = "aien-trace" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", +] + [[package]] name = "android_system_properties" version = "0.1.6" diff --git a/Cargo.toml b/Cargo.toml index 8a1019ba..2b458394 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -40,6 +40,7 @@ members = [ "crates/crumbs", "crates/aien-closure", "crates/aien-switchboard", + "crates/aien-trace", "crates/aien-dual-observation", "crates/aien-allen", "crates/aien-allen-profile", diff --git a/crates/aien-trace/Cargo.toml b/crates/aien-trace/Cargo.toml new file mode 100644 index 00000000..54272a6c --- /dev/null +++ b/crates/aien-trace/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "aien-trace" +description = "Correlation-only execution trace events: ids, bounded sinks and run reconstruction. Observational, never evidence or authorization." +version.workspace = true +edition.workspace = true +license.workspace = true +authors.workspace = true +repository.workspace = true + +[dependencies] +serde = { version = "1", features = ["derive"] } +serde_json = "1" + +[lib] +name = "aien_trace" +path = "src/lib.rs" diff --git a/crates/aien-trace/README.md b/crates/aien-trace/README.md new file mode 100644 index 00000000..4df939de --- /dev/null +++ b/crates/aien-trace/README.md @@ -0,0 +1,57 @@ +# aien-trace + +Correlation-only execution trace for AIEN (aien-sovereign-core#398). + +## What it is + +Typed events (`TraceEvent`) that say "this boundary was crossed" and carry the +ids needed to join a swarm, its sequences, model turns, tool decisions, effect +results and Interplane messages into one run. It is observational. It is not +evidence and it is not authorization: the effect receipt ledger, the compose +ledger, the generation record and the independent receipt verifier keep +governing. Events point at those artifacts by digest or relative path. +A trace id is a correlation key, never a secret and never a proof. + +## Default + +`NullSink` discards everything and is the default. Tracing is off until a +caller installs another sink. The crate starts no thread unless +`BoundedJsonlSink::spawn_flusher` is called. + +## Cardinality + +One event per boundary crossing: swarm launch, branch fork, sequence +admit/preempt/finish, model turn, tool request, authority decision, effect +execution, result, cancel, timeout. Bounded by sequences times stages. There +are no per-token or per-kernel events, so GPU hot paths are untouched. + +## Buffering and backpressure + +`BoundedJsonlSink` holds a bounded queue (default 4096 events). `emit` takes a +mutex only for one push and does no I/O. When the queue is full the event is +dropped and counted. The next `flush` appends one `trace_dropped` event whose +note says how many were dropped. `dropped_total()` is the lifetime count. +Security-critical records live in the ledgers, not here, so dropping a trace +event never loses evidence. + +## Retention + +Append-only JSONL, one object per line, created with mode 0600 on unix. The +operator rotates or deletes files. The crate deletes nothing. + +## What is never exported + +No prompts, tool arguments, model output, memory items or secrets. Enforced by +type: the only free text is `BoundedNote` (64 bytes, control characters and +`<` `>` removed). Ids are `BoundedId` (64 characters, small alphabet), digests +are hex, paths are relative without `..`. Deserialization applies the same +rules, so edited files cannot widen a field. + +## Rebuilding one run + +Read the JSONL lines into `Vec` and call `reconstruct(&events)`. +It checks one trace id, unique event ids and a valid parent for every child, +then gives `Tree::children(id)` and `Tree::chronological()`. Statuses map to +the AEGIS failure vocabulary plus `ok`; `uncertain` means the request may have +reached the server and is never retried automatically. To verify anything, +follow the digest or path to the independent artifact. diff --git a/crates/aien-trace/src/lib.rs b/crates/aien-trace/src/lib.rs new file mode 100644 index 00000000..4bdff227 --- /dev/null +++ b/crates/aien-trace/src/lib.rs @@ -0,0 +1,1162 @@ +//! Correlation-only execution trace for AIEN (aien-sovereign-core#398). +//! +//! A trace event says "this boundary was crossed, with these ids". It is +//! OBSERVATIONAL. It is not evidence and it is not authorization: the +//! `EffectReceipt` ledger, the compose ledger, the generation record and the +//! independent receipt verifier keep governing. An event only points at those +//! artifacts by digest or relative path. +//! +//! Privacy is enforced by type. This crate never carries prompts, tool +//! arguments, model output or memory items. The only free text is +//! [`BoundedNote`] (64 bytes, sanitized). Every other string is a +//! [`BoundedId`] (64 chars from a small alphabet), a [`Digest`] (hex) or a +//! [`RelPath`] (relative, no `..`). Deserialization re-applies the same rules, +//! so a tampered file cannot smuggle a longer or wider field through. +//! +//! The default sink is [`NullSink`]: tracing is off unless a caller installs +//! another sink. + +use std::collections::{HashMap, VecDeque}; +use std::fmt; +use std::fs::OpenOptions; +use std::io::Write; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::mpsc::{self, RecvTimeoutError}; +use std::sync::{Arc, Mutex, MutexGuard}; +use std::thread::JoinHandle; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use serde::{Deserialize, Serialize}; + +/// Longest accepted [`BoundedId`], in characters. +pub const MAX_ID_CHARS: usize = 64; +/// Longest accepted [`BoundedNote`], in bytes. +pub const MAX_NOTE_BYTES: usize = 64; +/// Default queue capacity of [`BoundedJsonlSink`]. +pub const DEFAULT_CAPACITY: usize = 4096; +const MAX_DIGEST_CHARS: usize = 128; +const MAX_PATH_BYTES: usize = 256; + +/// Errors of this crate. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum TraceError { + /// Not 32 lowercase-or-uppercase hex characters. + BadTraceId, + /// A digest was empty, too long or not hex. + BadDigest, + /// A path was absolute, contained `..`, or was empty or too long. + BadPath, + /// An event names a parent that is not in the set. + MissingParent { event_id: u64, parent: u64 }, + /// The events do not all share one trace id. + MixedTraceIds, + /// Two events share an event id. + DuplicateEvent(u64), + /// No events given. + Empty, +} + +impl fmt::Display for TraceError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::BadTraceId => write!(f, "trace id must be 32 hex characters"), + Self::BadDigest => write!(f, "digest must be 1..=128 hex characters"), + Self::BadPath => write!(f, "path must be relative, without `..`"), + Self::MissingParent { event_id, parent } => { + write!(f, "event {event_id} names missing parent {parent}") + } + Self::MixedTraceIds => write!(f, "events belong to more than one trace"), + Self::DuplicateEvent(id) => write!(f, "duplicate event id {id}"), + Self::Empty => write!(f, "no events"), + } + } +} + +impl std::error::Error for TraceError {} + +fn lock(m: &Mutex) -> MutexGuard<'_, T> { + m.lock().unwrap_or_else(|e| e.into_inner()) +} + +fn now_ms() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_millis() as u64) + .unwrap_or(0) +} + +fn mix64(mut x: u64) -> u64 { + // splitmix64 finalizer. + x = x.wrapping_add(0x9E37_79B9_7F4A_7C15); + x = (x ^ (x >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + x = (x ^ (x >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + x ^ (x >> 31) +} + +/// 16-byte run identifier. +/// +/// A correlation key only. It is NEVER a secret and NEVER a proof: anyone can +/// compute or copy one, so nothing may be authorized or believed because a +/// trace id matches. +#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct TraceId(pub [u8; 16]); + +impl TraceId { + /// Mixes the inputs with splitmix64 applied twice per half. Deterministic: + /// the same inputs give the same id. Not a cryptographic hash. + pub fn derive(seed_a: u64, seed_b: u64, counter: u64) -> Self { + let hi = mix64(mix64(seed_a) ^ counter); + let lo = mix64(mix64(seed_b ^ hi) ^ counter.rotate_left(32)); + let mut out = [0u8; 16]; + out[..8].copy_from_slice(&hi.to_be_bytes()); + out[8..].copy_from_slice(&lo.to_be_bytes()); + Self(out) + } + + /// 32 lowercase hex characters. + pub fn to_hex(&self) -> String { + const H: &[u8; 16] = b"0123456789abcdef"; + let mut s = String::with_capacity(32); + for b in self.0 { + s.push(H[(b >> 4) as usize] as char); + s.push(H[(b & 15) as usize] as char); + } + s + } + + /// Parses 32 hex characters (either case). + pub fn parse_hex(s: &str) -> Result { + let b = s.as_bytes(); + if b.len() != 32 { + return Err(TraceError::BadTraceId); + } + let nib = |c: u8| match c { + b'0'..=b'9' => Ok(c - b'0'), + b'a'..=b'f' => Ok(c - b'a' + 10), + b'A'..=b'F' => Ok(c - b'A' + 10), + _ => Err(TraceError::BadTraceId), + }; + let mut out = [0u8; 16]; + for i in 0..16 { + out[i] = (nib(b[2 * i])? << 4) | nib(b[2 * i + 1])?; + } + Ok(Self(out)) + } +} + +impl fmt::Display for TraceId { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.to_hex()) + } +} + +impl fmt::Debug for TraceId { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "TraceId({})", self.to_hex()) + } +} + +impl Serialize for TraceId { + fn serialize(&self, s: S) -> Result { + s.serialize_str(&self.to_hex()) + } +} + +impl<'de> Deserialize<'de> for TraceId { + fn deserialize>(d: D) -> Result { + let s = String::deserialize(d)?; + Self::parse_hex(&s).map_err(serde::de::Error::custom) + } +} + +/// What boundary was crossed. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +#[non_exhaustive] +pub enum EventKind { + SwarmLaunched, + BranchForked, + SequenceAdmitted, + SequencePreempted, + SequenceFinished, + SwarmCancelled, + ModelTurn, + ToolRequested, + AuthorityDecided, + EffectExecuted, + ResultReceived, + Failure, + Cancelled, + TimedOut, + InterplaneRequest, + TraceDropped, +} + +/// Terminal or current state of the boundary. +/// +/// One to one with the AEGIS `FailureClass` vocabulary (Rejected, +/// Unavailable, Timeout, Cancelled, Uncertain, Failed, Malformed, +/// ApprovalPending) plus `ok` for success. `rejected` also covers Interplane +/// decisions `denied`, `not_found` and `invalid`. `approval_pending` is not a +/// failure and is terminal for the attempt. `uncertain` maps to aien-mcp +/// `CallOutcome::Uncertain`: the request may have reached the server, and it +/// is never retried automatically. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +#[non_exhaustive] +pub enum EventStatus { + Ok, + Rejected, + Unavailable, + TimedOut, + Cancelled, + Uncertain, + Failed, + Malformed, + ApprovalPending, +} + +/// Whether an external effect happened, as far as the recorder knows. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +#[non_exhaustive] +pub enum EffectCertainty { + NoEffect, + Uncertain, + EffectOccurred, +} + +/// Short identifier: at most 64 characters from `[A-Za-z0-9._:-]`; anything +/// else is dropped, extra length is cut. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(from = "String", into = "String")] +pub struct BoundedId(String); + +impl BoundedId { + pub fn new(s: &str) -> Self { + Self( + s.chars() + .filter(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | ':' | '-')) + .take(MAX_ID_CHARS) + .collect(), + ) + } + pub fn as_str(&self) -> &str { + &self.0 + } +} +impl From for BoundedId { + fn from(s: String) -> Self { + Self::new(&s) + } +} +impl From for String { + fn from(b: BoundedId) -> Self { + b.0 + } +} + +/// The ONLY free-text field of an event. Control characters, `<` and `>` are +/// removed, then the text is cut to 64 bytes on a character boundary. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(from = "String", into = "String")] +pub struct BoundedNote(String); + +impl BoundedNote { + pub fn new(s: &str) -> Self { + let mut out = String::new(); + for c in s + .chars() + .filter(|c| !c.is_control() && *c != '<' && *c != '>') + { + if out.len() + c.len_utf8() > MAX_NOTE_BYTES { + break; + } + out.push(c); + } + Self(out) + } + pub fn as_str(&self) -> &str { + &self.0 + } +} +impl From for BoundedNote { + fn from(s: String) -> Self { + Self::new(&s) + } +} +impl From for String { + fn from(b: BoundedNote) -> Self { + b.0 + } +} + +/// Hex digest, 1..=128 characters. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(try_from = "String", into = "String")] +pub struct Digest(String); + +impl Digest { + pub fn new(s: &str) -> Result { + if s.is_empty() || s.len() > MAX_DIGEST_CHARS || !s.bytes().all(|b| b.is_ascii_hexdigit()) { + return Err(TraceError::BadDigest); + } + Ok(Self(s.to_ascii_lowercase())) + } + pub fn as_str(&self) -> &str { + &self.0 + } +} +impl TryFrom for Digest { + type Error = TraceError; + fn try_from(s: String) -> Result { + Self::new(&s) + } +} +impl From for String { + fn from(d: Digest) -> Self { + d.0 + } +} + +/// Relative path: not absolute, no `..` component, no NUL, at most 256 bytes. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(try_from = "String", into = "String")] +pub struct RelPath(String); + +impl RelPath { + pub fn new(s: &str) -> Result { + let bad = s.is_empty() + || s.len() > MAX_PATH_BYTES + || s.contains('\0') + || s.starts_with('/') + || s.starts_with('\\') + || s.as_bytes().get(1) == Some(&b':') + || s.split(['/', '\\']).any(|p| p == ".."); + if bad { + return Err(TraceError::BadPath); + } + Ok(Self(s.to_string())) + } + pub fn as_str(&self) -> &str { + &self.0 + } +} +impl TryFrom for RelPath { + type Error = TraceError; + fn try_from(s: String) -> Result { + Self::new(&s) + } +} +impl From for String { + fn from(p: RelPath) -> Self { + p.0 + } +} + +/// Ids a trace can join on. All optional. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct CorrelationIds { + pub swarm_id: Option, + pub world_id: Option, + pub root_sequence_id: Option, + pub sequence_id: Option, + pub step_id: Option, + pub model_turn: Option, + pub tool_request_id: Option, + pub decision_id: Option, + pub grant_id: Option, + pub generation_record: Option, + pub interplane_trace_id: Option, + pub interplane_message_id: Option, + pub interplane_request_id: Option, +} + +/// Pointers to independent proof artifacts. A pointer is not proof. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct EvidenceRefs { + pub effect_receipt_digest: Option, + pub result_digest: Option, + pub provenance_record: Option, + pub intent_digest: Option, +} + +impl EvidenceRefs { + pub fn with_effect_receipt_digest(mut self, hex: &str) -> Result { + self.effect_receipt_digest = Some(Digest::new(hex)?); + Ok(self) + } + pub fn with_result_digest(mut self, hex: &str) -> Result { + self.result_digest = Some(Digest::new(hex)?); + Ok(self) + } + pub fn with_intent_digest(mut self, hex: &str) -> Result { + self.intent_digest = Some(Digest::new(hex)?); + Ok(self) + } + /// Refuses absolute paths and `..`. + pub fn with_provenance_record(mut self, path: &str) -> Result { + self.provenance_record = Some(RelPath::new(path)?); + Ok(self) + } +} + +/// One boundary crossing. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct TraceEvent { + pub trace_id: TraceId, + /// Monotonic per sink. + pub event_id: u64, + pub parent_event_id: Option, + pub at_unix_ms: u64, + pub kind: EventKind, + pub status: EventStatus, + #[serde(default)] + pub effect_certainty: Option, + #[serde(default)] + pub ids: CorrelationIds, + #[serde(default)] + pub refs: EvidenceRefs, + #[serde(default)] + pub note: Option, +} + +/// Destination of events. Implementations must never block the caller for I/O. +pub trait TraceSink: Send + Sync { + fn emit(&self, event: TraceEvent); + fn next_event_id(&self) -> u64; +} + +/// Discards everything. The default everywhere. +#[derive(Debug, Default)] +pub struct NullSink; + +impl TraceSink for NullSink { + fn emit(&self, _event: TraceEvent) {} + fn next_event_id(&self) -> u64 { + 0 + } +} + +/// Keeps events in memory. For tests. +#[derive(Debug, Default)] +pub struct MemorySink { + events: Mutex>, + next: AtomicU64, +} + +impl MemorySink { + pub fn new() -> Self { + Self::default() + } + pub fn drain(&self) -> Vec { + std::mem::take(&mut *lock(&self.events)) + } +} + +impl TraceSink for MemorySink { + fn emit(&self, event: TraceEvent) { + lock(&self.events).push(event); + } + fn next_event_id(&self) -> u64 { + self.next.fetch_add(1, Ordering::Relaxed) + 1 + } +} + +/// Bounded in-memory queue flushed to an append-only JSONL file. +/// +/// `emit` takes a mutex only for one queue push and never does I/O. When the +/// queue is full the event is dropped and counted; the next `flush` appends one +/// `trace_dropped` event saying how many. No thread runs unless +/// [`BoundedJsonlSink::spawn_flusher`] is called. +#[derive(Debug)] +pub struct BoundedJsonlSink { + path: PathBuf, + capacity: usize, + queue: Mutex>, + next: AtomicU64, + dropped: AtomicU64, + dropped_total: AtomicU64, + last_trace: Mutex, +} + +impl BoundedJsonlSink { + pub fn new(path: impl Into) -> Self { + Self::with_capacity(path, DEFAULT_CAPACITY) + } + + pub fn with_capacity(path: impl Into, capacity: usize) -> Self { + let capacity = capacity.max(1); + Self { + path: path.into(), + capacity, + queue: Mutex::new(VecDeque::with_capacity(capacity)), + next: AtomicU64::new(0), + dropped: AtomicU64::new(0), + dropped_total: AtomicU64::new(0), + last_trace: Mutex::new(TraceId([0; 16])), + } + } + + /// Lifetime number of dropped events. + pub fn dropped_total(&self) -> u64 { + self.dropped_total.load(Ordering::Relaxed) + } + + pub fn path(&self) -> &Path { + &self.path + } + + /// Appends queued events, one JSON object per line. The file is created + /// with mode 0o600 on unix. After drops, one `trace_dropped` event follows. + pub fn flush(&self) -> std::io::Result<()> { + let batch: Vec = lock(&self.queue).drain(..).collect(); + let pending = self.dropped.swap(0, Ordering::Relaxed); + if batch.is_empty() && pending == 0 { + return Ok(()); + } + let mut lines = Vec::new(); + for e in &batch { + serde_json::to_writer(&mut lines, e).map_err(std::io::Error::other)?; + lines.push(b'\n'); + } + if pending > 0 { + let trace_id = batch + .last() + .map(|e| e.trace_id) + .unwrap_or(*lock(&self.last_trace)); + let marker = TraceEvent { + trace_id, + event_id: self.next_event_id(), + parent_event_id: None, + at_unix_ms: now_ms(), + kind: EventKind::TraceDropped, + status: EventStatus::Ok, + effect_certainty: None, + ids: CorrelationIds::default(), + refs: EvidenceRefs::default(), + note: Some(BoundedNote::new(&format!("dropped {pending} events"))), + }; + serde_json::to_writer(&mut lines, &marker).map_err(std::io::Error::other)?; + lines.push(b'\n'); + } + let mut opts = OpenOptions::new(); + opts.create(true).append(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + opts.mode(0o600); + } + let result = opts.open(&self.path).and_then(|mut f| f.write_all(&lines)); + if result.is_err() { + // Not written: report the loss instead of hiding it. + let lost = batch.len() as u64 + pending; + self.dropped.fetch_add(lost, Ordering::Relaxed); + self.dropped_total + .fetch_add(batch.len() as u64, Ordering::Relaxed); + } + result + } + + /// Starts a thread that flushes every `interval` and once more on stop. + pub fn spawn_flusher(self: &Arc, interval: Duration) -> FlusherHandle { + let sink = Arc::clone(self); + let (tx, rx) = mpsc::channel::<()>(); + let join = std::thread::spawn(move || loop { + match rx.recv_timeout(interval) { + Err(RecvTimeoutError::Timeout) => { + let _ = sink.flush(); + } + _ => { + let _ = sink.flush(); + break; + } + } + }); + FlusherHandle { + stop: Some(tx), + join: Some(join), + } + } +} + +impl TraceSink for BoundedJsonlSink { + fn emit(&self, event: TraceEvent) { + let mut q = lock(&self.queue); + if q.len() >= self.capacity { + drop(q); + self.dropped.fetch_add(1, Ordering::Relaxed); + self.dropped_total.fetch_add(1, Ordering::Relaxed); + return; + } + q.push_back(event); + } + fn next_event_id(&self) -> u64 { + self.next.fetch_add(1, Ordering::Relaxed) + 1 + } +} + +/// Handle of the flusher thread. Dropping it stops the thread. +#[derive(Debug)] +pub struct FlusherHandle { + stop: Option>, + join: Option>, +} + +impl FlusherHandle { + /// Stops the thread after one last flush. + pub fn stop(mut self) { + self.shutdown(); + } + fn shutdown(&mut self) { + self.stop.take(); + if let Some(j) = self.join.take() { + let _ = j.join(); + } + } +} + +impl Drop for FlusherHandle { + fn drop(&mut self) { + self.shutdown(); + } +} + +/// Emits events of one trace with correct parent links. +#[derive(Clone)] +pub struct TraceContext { + trace_id: TraceId, + sink: Arc, + last: Arc, +} + +const NO_EVENT: u64 = u64::MAX; + +impl TraceContext { + pub fn new(trace_id: TraceId, sink: Arc) -> Self { + Self { + trace_id, + sink, + last: Arc::new(AtomicU64::new(NO_EVENT)), + } + } + + pub fn trace_id(&self) -> TraceId { + self.trace_id + } + + /// Id of the most recent event emitted through this context, if any. + pub fn last_event_id(&self) -> Option { + match self.last.load(Ordering::Relaxed) { + NO_EVENT => None, + v => Some(v), + } + } + + fn put( + &self, + parent: Option, + kind: EventKind, + status: EventStatus, + ids: CorrelationIds, + refs: EvidenceRefs, + note: Option, + ) -> u64 { + let id = self.sink.next_event_id(); + self.sink.emit(TraceEvent { + trace_id: self.trace_id, + event_id: id, + parent_event_id: parent, + at_unix_ms: now_ms(), + kind, + status, + effect_certainty: None, + ids, + refs, + note, + }); + self.last.store(id, Ordering::Relaxed); + id + } + + /// First event: no parent. + pub fn root( + &self, + kind: EventKind, + status: EventStatus, + ids: CorrelationIds, + refs: EvidenceRefs, + note: Option, + ) -> u64 { + self.put(None, kind, status, ids, refs, note) + } + + /// Child of the most recent event of this context. + pub fn child( + &self, + kind: EventKind, + status: EventStatus, + ids: CorrelationIds, + refs: EvidenceRefs, + note: Option, + ) -> u64 { + self.put(self.last_event_id(), kind, status, ids, refs, note) + } + + /// Child of a named event, for fan-out and across task boundaries. + pub fn child_of( + &self, + parent: u64, + kind: EventKind, + status: EventStatus, + ids: CorrelationIds, + refs: EvidenceRefs, + note: Option, + ) -> u64 { + self.put(Some(parent), kind, status, ids, refs, note) + } +} + +/// Parent/child tree of one trace. +#[derive(Debug)] +pub struct Tree { + events: Vec, + children: HashMap>, + roots: Vec, +} + +impl Tree { + /// Events sorted by `(at_unix_ms, event_id)`. + pub fn chronological(&self) -> Vec<&TraceEvent> { + let mut v: Vec<&TraceEvent> = self.events.iter().collect(); + v.sort_by_key(|e| (e.at_unix_ms, e.event_id)); + v + } + /// Event ids whose parent is `id`, in event id order. + pub fn children(&self, id: u64) -> &[u64] { + self.children.get(&id).map(Vec::as_slice).unwrap_or(&[]) + } + /// Events without a parent. + pub fn roots(&self) -> &[u64] { + &self.roots + } + pub fn get(&self, id: u64) -> Option<&TraceEvent> { + self.events.iter().find(|e| e.event_id == id) + } + pub fn len(&self) -> usize { + self.events.len() + } + pub fn is_empty(&self) -> bool { + self.events.is_empty() + } +} + +/// Builds the tree of one trace. Fails on mixed trace ids, duplicate event +/// ids, or a parent that is not in the set. +pub fn reconstruct(events: &[TraceEvent]) -> Result { + let first = events.first().ok_or(TraceError::Empty)?; + let mut ids = HashMap::new(); + for e in events { + if e.trace_id != first.trace_id { + return Err(TraceError::MixedTraceIds); + } + if ids.insert(e.event_id, ()).is_some() { + return Err(TraceError::DuplicateEvent(e.event_id)); + } + } + let mut children: HashMap> = HashMap::new(); + let mut roots = Vec::new(); + for e in events { + match e.parent_event_id { + None => roots.push(e.event_id), + Some(p) if ids.contains_key(&p) => children.entry(p).or_default().push(e.event_id), + Some(p) => { + return Err(TraceError::MissingParent { + event_id: e.event_id, + parent: p, + }) + } + } + } + roots.sort_unstable(); + for v in children.values_mut() { + v.sort_unstable(); + } + Ok(Tree { + events: events.to_vec(), + children, + roots, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::Value; + + const ALL_STATUS: [EventStatus; 9] = [ + EventStatus::Ok, + EventStatus::Rejected, + EventStatus::Unavailable, + EventStatus::TimedOut, + EventStatus::Cancelled, + EventStatus::Uncertain, + EventStatus::Failed, + EventStatus::Malformed, + EventStatus::ApprovalPending, + ]; + + fn tmp(name: &str) -> PathBuf { + static N: AtomicU64 = AtomicU64::new(0); + std::env::temp_dir().join(format!( + "aien-trace-{name}-{}-{}-{}.jsonl", + std::process::id(), + N.fetch_add(1, Ordering::Relaxed), + now_ms() + )) + } + + fn ev(trace: TraceId, id: u64, parent: Option) -> TraceEvent { + TraceEvent { + trace_id: trace, + event_id: id, + parent_event_id: parent, + at_unix_ms: id, + kind: EventKind::ModelTurn, + status: EventStatus::Ok, + effect_certainty: None, + ids: CorrelationIds::default(), + refs: EvidenceRefs::default(), + note: None, + } + } + + #[test] + fn hex_round_trip_and_derive_is_deterministic() { + let a = TraceId::derive(1, 2, 3); + assert_eq!(a, TraceId::derive(1, 2, 3)); + assert_ne!(a, TraceId::derive(1, 2, 4)); + assert_ne!(a, TraceId::derive(2, 1, 3)); + let h = a.to_hex(); + assert_eq!(h.len(), 32); + assert!(h + .bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))); + assert_eq!(TraceId::parse_hex(&h).unwrap(), a); + assert_eq!(format!("{a}"), h); + assert!(TraceId::parse_hex("zz").is_err()); + assert!(TraceId::parse_hex(&"g".repeat(32)).is_err()); + } + + #[test] + fn status_strings_are_distinct_and_exact() { + let mut got: Vec = ALL_STATUS + .iter() + .map(|s| { + serde_json::to_value(s) + .unwrap() + .as_str() + .unwrap() + .to_string() + }) + .collect(); + got.sort(); + let mut want: Vec = [ + "ok", + "rejected", + "unavailable", + "timed_out", + "cancelled", + "uncertain", + "failed", + "malformed", + "approval_pending", + ] + .iter() + .map(|s| s.to_string()) + .collect(); + want.sort(); + assert_eq!(got, want); + let mut dedup = got.clone(); + dedup.dedup(); + assert_eq!(dedup.len(), 9); + let c: Vec = [ + EffectCertainty::NoEffect, + EffectCertainty::Uncertain, + EffectCertainty::EffectOccurred, + ] + .iter() + .map(|s| { + serde_json::to_value(s) + .unwrap() + .as_str() + .unwrap() + .to_string() + }) + .collect(); + assert_eq!(c, ["no_effect", "uncertain", "effect_occurred"]); + } + + #[test] + fn fan_out_reconstructs_with_valid_parents() { + let sink = Arc::new(MemorySink::new()); + let ctx = TraceContext::new(TraceId::derive(7, 8, 1), sink.clone()); + let root = ctx.root( + EventKind::SwarmLaunched, + EventStatus::Ok, + CorrelationIds { + swarm_id: Some(1), + ..Default::default() + }, + EvidenceRefs::default(), + None, + ); + let mut tool_events = Vec::new(); + for b in 0..3u64 { + let branch = ctx.child_of( + root, + EventKind::BranchForked, + EventStatus::Ok, + CorrelationIds { + sequence_id: Some(b), + ..Default::default() + }, + EvidenceRefs::default(), + None, + ); + let t = ctx.child( + EventKind::ToolRequested, + EventStatus::Ok, + CorrelationIds::default(), + EvidenceRefs::default(), + None, + ); + let d = ctx.child( + EventKind::AuthorityDecided, + EventStatus::ApprovalPending, + CorrelationIds::default(), + EvidenceRefs::default(), + None, + ); + tool_events.push((branch, t, d)); + } + let events = sink.drain(); + assert_eq!(events.len(), 10); + let tree = reconstruct(&events).unwrap(); + assert_eq!(tree.roots(), &[root]); + assert_eq!(tree.children(root).len(), 3); + for (branch, t, d) in tool_events { + assert_eq!(tree.get(t).unwrap().parent_event_id, Some(branch)); + assert_eq!(tree.get(d).unwrap().parent_event_id, Some(t)); + assert_eq!(tree.children(branch), &[t]); + } + let order: Vec = tree.chronological().iter().map(|e| e.event_id).collect(); + let mut sorted = order.clone(); + sorted.sort(); + assert_eq!(order, sorted); + } + + #[test] + fn reconstruct_rejects_missing_parent_and_mixed_traces() { + let t = TraceId::derive(1, 1, 1); + let evs = vec![ev(t, 1, None), ev(t, 2, Some(9))]; + assert_eq!( + reconstruct(&evs).unwrap_err(), + TraceError::MissingParent { + event_id: 2, + parent: 9 + } + ); + let evs = vec![ev(t, 1, None), ev(TraceId::derive(2, 2, 2), 2, Some(1))]; + assert_eq!(reconstruct(&evs).unwrap_err(), TraceError::MixedTraceIds); + assert_eq!(reconstruct(&[]).unwrap_err(), TraceError::Empty); + } + + #[test] + fn jsonl_round_trip() { + let path = tmp("rt"); + let sink = Arc::new(BoundedJsonlSink::new(&path)); + let ctx = TraceContext::new(TraceId::derive(3, 3, 3), sink.clone()); + let r = ctx.root( + EventKind::SwarmLaunched, + EventStatus::Ok, + CorrelationIds::default(), + EvidenceRefs::default(), + None, + ); + ctx.child( + EventKind::EffectExecuted, + EventStatus::Uncertain, + CorrelationIds { + tool_request_id: Some(BoundedId::new("req-1")), + ..Default::default() + }, + EvidenceRefs::default() + .with_intent_digest("ABCDEF01") + .unwrap(), + Some(BoundedNote::new("may have reached server")), + ); + sink.flush().unwrap(); + let text = std::fs::read_to_string(&path).unwrap(); + let events: Vec = text + .lines() + .map(|l| serde_json::from_str(l).unwrap()) + .collect(); + assert_eq!(events.len(), 2); + assert_eq!(events[0].event_id, r); + assert_eq!( + events[1].refs.intent_digest.as_ref().unwrap().as_str(), + "abcdef01" + ); + assert_eq!(events[1].status, EventStatus::Uncertain); + assert!(reconstruct(&events).is_ok()); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + assert_eq!( + std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, + 0o600 + ); + } + let _ = std::fs::remove_file(&path); + } + + #[test] + fn overflow_counts_drops_and_writes_one_marker() { + let path = tmp("drop"); + let sink = BoundedJsonlSink::with_capacity(&path, 4); + let t = TraceId::derive(4, 4, 4); + for i in 0..10u64 { + sink.emit(ev( + t, + sink.next_event_id(), + if i == 0 { None } else { Some(1) }, + )); + } + assert_eq!(sink.dropped_total(), 6); + sink.flush().unwrap(); + let text = std::fs::read_to_string(&path).unwrap(); + let events: Vec = text + .lines() + .map(|l| serde_json::from_str(l).unwrap()) + .collect(); + let drops: Vec<_> = events + .iter() + .filter(|e| e.kind == EventKind::TraceDropped) + .collect(); + assert_eq!(drops.len(), 1); + assert_eq!(drops[0].note.as_ref().unwrap().as_str(), "dropped 6 events"); + assert_eq!(events.len(), 5); + // Counter reset: a second flush adds no marker. + sink.flush().unwrap(); + assert_eq!(std::fs::read_to_string(&path).unwrap().lines().count(), 5); + assert_eq!(sink.dropped_total(), 6); + let _ = std::fs::remove_file(&path); + } + + #[test] + fn flusher_writes_on_stop() { + let path = tmp("flusher"); + let sink = Arc::new(BoundedJsonlSink::new(&path)); + let h = sink.spawn_flusher(Duration::from_secs(3600)); + sink.emit(ev(TraceId::derive(5, 5, 5), sink.next_event_id(), None)); + h.stop(); + assert_eq!(std::fs::read_to_string(&path).unwrap().lines().count(), 1); + let _ = std::fs::remove_file(&path); + } + + #[test] + fn note_strips_and_truncates_on_char_boundary() { + let n = BoundedNote::new("ac\u{0}d\ne\u{7f}f"); + assert_eq!(n.as_str(), "abcdef"); + // 63 ASCII bytes then a 2-byte char: the cut must fall before it. + let s = format!("{}\u{e9}z", "x".repeat(63)); + let n = BoundedNote::new(&s); + assert_eq!(n.as_str().len(), 63); + assert!(n.as_str().chars().all(|c| c == 'x')); + let s = format!("{}\u{e9}", "x".repeat(62)); + assert_eq!(BoundedNote::new(&s).as_str().len(), 64); + // Deserialization re-applies the rule. + let back: BoundedNote = serde_json::from_str("\"