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/patches/82185bcaea6feec2 # 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 ## GitHub aien-dev/aien-sovereign-core-mv#400 (code only) closed derived `82185bcaea6feec2` #400 Imported from GitHub aien-dev/aien-sovereign-core-mv#400 (code only) GitHub's metadata for this pull request is unavailable: its state is DERIVED from the commits (merged: the head is reachable from this project's main; open: GitHub kept a merge ref; else closed). Base `4d02ebfc0c8057ccfd1077f8d653e8aee1475e3c` · Head `34f45cab0130a77792a04452a70291a708dacbe9` ### Apply it ``` git checkout -b patch-82185bcaea6feec2 4d02ebfc0c8057ccfd1077f8d653e8aee1475e3c curl -fsSL https://interplane.io/drakestapleton/aien-sovereign-core-mv/patches/82185bcaea6feec2.patch | git am ``` Raw patch (mbox) · Diff ### Provenance This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record: ``` github-import 1 aien-dev/aien-sovereign-core-mv 400 34f45cab0130a77792a04452a70291a708dacbe9 ``` ``` {"kind":"github-import","owner":"aien-dev","repo":"aien-sovereign-core-mv","number":400,"url":"https://github.com/aien-dev/aien-sovereign-core-mv/pull/400","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:37:05Z","metadata":"unavailable","state_derived":true} ``` ### Changes ``` diff --git a/.crumb b/.crumb index fbfd35e8..2205e5e2 100644 --- a/.crumb +++ b/.crumb @@ -77,14 +77,14 @@ } ], "children_root": "sha256:e5ff31069bcf711289819b6c09c3c96378cb1367e38f236992f113ca6a2dac23", - "compiled_at": "2026-10-10T16:50:00Z", + "compiled_at": "2026-10-10T17:04:40Z", "compiler": "crumb-compile/1", - "digest": "sha256:367e68fdd05b6357ab8cc868135b1926a4697a14f1365c713c45d61d79fc5480", + "digest": "sha256:e097fde04915a02bd1dc024b33bd001f2af475f527fac582bf05f06c008d0a31", "evidence_files": 187, "evidence_root": "sha256:27ee0353cb4d4aae2b7dbce2bfe0d9f4ef2a94cd7a4555b84684d59372503280", - "files": 2387, - "generated_at_commit": "95d0773c09b30fd5e523092546fb1b00d473f68f", - "source_tree": "sha256:72f369e76abb7f598db29e5cd1c6c56febd97176a6cdf4ffd4657af51e6e7985" + "files": 2396, + "generated_at_commit": "b27c73a512430ce23f512cb18fe7ef08a9b1a315", + "source_tree": "sha256:24c4bdbd170c67887034e1d7bd85f586bbb2347627de8dfe0b9e28ee0c412e92" } }, "history": [], diff --git a/Cargo.lock b/Cargo.lock index f6234199..c66d8e20 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -233,6 +233,7 @@ name = "aien-mcp" version = "0.1.0" dependencies = [ "aien-capability", + "aien-trace", "async-trait", "rmcp", "serde_json", @@ -339,6 +340,7 @@ dependencies = [ "aien-runtime", "aien-scheduler", "aien-security", + "aien-trace", "async-trait", "cortex-rs", "libc", @@ -400,6 +402,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-mcp/Cargo.toml b/crates/aien-mcp/Cargo.toml index e6d6b76c..6ce42e83 100644 --- a/crates/aien-mcp/Cargo.toml +++ b/crates/aien-mcp/Cargo.toml @@ -7,6 +7,7 @@ description = "MCP session manager. Discovery and speculative calls are separate [dependencies] aien-capability = { path = "../aien-capability" } +aien-trace = { path = "../aien-trace" } async-trait = "0.1" rmcp = { version = "3.4.0", features = ["client", "server", "transport-async-rw"] } serde_json = "1.0" diff --git a/crates/aien-mcp/src/broker.rs b/crates/aien-mcp/src/broker.rs index 6ad814ac..41607386 100644 --- a/crates/aien-mcp/src/broker.rs +++ b/crates/aien-mcp/src/broker.rs @@ -6,6 +6,10 @@ use aien_capability::{ catalog_digest, speculation_safe, Digest32, EffectId, JNodeId, ProviderId, ToolDescriptor, ToolEffects, WorldId, }; +use aien_trace::{ + now_unix_ms, BoundedId, BoundedNote, CorrelationIds, EffectCertainty, EventKind, EventStatus, + EvidenceRefs, NullSink, TraceEvent, TraceId, TraceSink, +}; use serde_json::Value; use crate::approval::{ApprovalError, ApprovalGrant, ApprovalRecord, GrantState, Reservation}; @@ -247,6 +251,122 @@ pub struct EffectLane { broker: McpBroker, exposure: Option, clock: Option, + trace: LaneTrace, +} + +/// Correlation tap of one lane. Observational: it never changes a verdict. +#[derive(Clone)] +struct LaneTrace { + sink: Arc, + trace_id: TraceId, + parent: Option, +} + +impl LaneTrace { + fn off() -> Self { + Self { + sink: Arc::new(NullSink), + trace_id: TraceId([0; 16]), + parent: None, + } + } + + fn enabled(&self) -> bool { + self.sink.enabled() + } + + fn emit( + &self, + kind: EventKind, + status: EventStatus, + certainty: Option, + ids: CorrelationIds, + refs: EvidenceRefs, + note: Option<&str>, + ) { + self.sink.emit(TraceEvent { + trace_id: self.trace_id, + event_id: self.sink.next_event_id(), + parent_event_id: self.parent, + at_unix_ms: now_unix_ms(), + kind, + status, + effect_certainty: certainty, + ids, + refs, + note: note.map(BoundedNote::new), + }); + } +} + +const STALE_INTENT: &str = "intent was staged against a stale catalog"; +const NOT_ADMITTED: &str = "provider is not admitted"; + +fn hex(bytes: &[u8]) -> String { + const H: &[u8; 16] = b"0123456789abcdef"; + let mut s = String::with_capacity(bytes.len() * 2); + for b in bytes { + s.push(H[(b >> 4) as usize] as char); + s.push(H[(b & 15) as usize] as char); + } + s +} + +fn put_str(out: &mut Vec, s: &str) { + out.extend_from_slice(&(s.len() as u64).to_le_bytes()); + out.extend_from_slice(s.as_bytes()); +} + +// Canonical, length-prefixed encoding of a JSON value: object keys sorted, so the +// result does not depend on serde_json's map order feature. +fn put_value(out: &mut Vec, v: &Value) { + match v { + Value::Null => out.push(0), + Value::Bool(b) => out.extend_from_slice(&[1, *b as u8]), + Value::Number(n) => { + out.push(2); + put_str(out, &n.to_string()); + } + Value::String(s) => { + out.push(3); + put_str(out, s); + } + Value::Array(a) => { + out.push(4); + out.extend_from_slice(&(a.len() as u64).to_le_bytes()); + for x in a { + put_value(out, x); + } + } + Value::Object(m) => { + out.push(5); + out.extend_from_slice(&(m.len() as u64).to_le_bytes()); + let mut keys: Vec<&String> = m.keys().collect(); + keys.sort(); + for k in keys { + put_str(out, k); + put_value(out, &m[k]); + } + } + } +} + +/// SHA-256 over a canonical encoding of every receipt field: a domain tag, then fixed-width +/// ids and digests, then length-prefixed strings, then the output value with sorted object +/// keys. A trace carries this digest, never the output itself. The independent receipt +/// verifier, not this digest, governs whether a receipt is believed. +pub fn receipt_digest(r: &EffectReceipt) -> [u8; 32] { + let mut b = Vec::new(); + b.extend_from_slice(b"aien-mcp.effect-receipt.v1\0"); + b.extend_from_slice(&r.effect_id.0); + b.extend_from_slice(&r.world_id.0.to_le_bytes()); + b.extend_from_slice(&r.winning_jnode.0.to_le_bytes()); + b.extend_from_slice(&r.policy_digest.0); + put_str(&mut b, r.provider.as_str()); + put_str(&mut b, &r.tool_name); + b.extend_from_slice(&r.capability_digest.0); + put_value(&mut b, &r.output); + Digest32::of(&b).0 } /// Host-supplied time source, in the same unit as `now` and `expires_at`. @@ -258,6 +378,7 @@ impl EffectLane { broker, exposure: None, clock: None, + trace: LaneTrace::off(), } } @@ -280,6 +401,26 @@ impl EffectLane { broker: self.broker.clone(), exposure: Some(exposure), clock: self.clock.clone(), + trace: self.trace.clone(), + } + } + + /// Attach a correlation trace (observational only). Every `authority_decided` and + /// `effect_executed` event of this lane becomes a child of `parent_event` in `trace_id`. Events + /// carry digests and ids, never arguments or outputs. The default is a `NullSink`. + pub fn with_trace( + self, + sink: Arc, + trace_id: TraceId, + parent_event: Option, + ) -> Self { + Self { + trace: LaneTrace { + sink, + trace_id, + parent: parent_event, + }, + ..self } } @@ -322,22 +463,76 @@ impl EffectLane { scope: EffectScope, authority: &dyn EffectAuthority, approval: Option<(&ApprovalGrant, u64)>, + ) -> Result, AuthorityOutcome> { + if !self.trace.enabled() { + return self.authorize_core(intent, scope, authority, approval); + } + let digest = intent_digest(&intent); + let mut ids = self.effect_ids(&intent.provider, &intent.tool_name, scope.world_id); + let presented = approval.map(|(g, _)| hex(&g.id().0)); + let result = self.authorize_core(intent, scope, authority, approval); + let (status, note): (EventStatus, Option<&str>) = match &result { + Ok(_) => (EventStatus::Ok, None), + Err(AuthorityOutcome::Pending { .. }) => (EventStatus::ApprovalPending, None), + Err(AuthorityOutcome::Denied(r)) if r == STALE_INTENT => { + (EventStatus::Rejected, Some("stale_intent")) + } + Err(AuthorityOutcome::Denied(r)) if r == NOT_ADMITTED => { + (EventStatus::Rejected, Some("provider_not_admitted")) + } + Err(AuthorityOutcome::Denied(_)) => (EventStatus::Rejected, None), + Err(AuthorityOutcome::Contained(_)) => (EventStatus::Rejected, Some("contained")), + Err(AuthorityOutcome::Approval(e)) => (EventStatus::Rejected, Some(approval_name(e))), + Err(AuthorityOutcome::Execution(_)) => (EventStatus::Failed, None), + }; + let grant = match &result { + Ok(e) => e.approval_id().map(|d| hex(&d.0)), + Err(_) => presented, + }; + if let Some(grant) = grant { + ids.grant_id = Some(BoundedId::new(&grant)); + } + let refs = EvidenceRefs { + intent_digest: aien_trace::Digest::new(&hex(&digest.0)).ok(), + ..Default::default() + }; + self.trace + .emit(EventKind::AuthorityDecided, status, None, ids, refs, note); + result + } + + fn effect_ids(&self, provider: &ProviderId, tool: &str, world: WorldId) -> CorrelationIds { + let mut name = String::with_capacity(provider.as_str().len() + 1 + tool.len()); + name.push_str(provider.as_str()); + name.push(':'); + name.push_str(tool); + CorrelationIds { + world_id: Some(world.0), + tool_request_id: Some(BoundedId::new(&name)), + ..Default::default() + } + } + + fn authorize_core( + &self, + intent: EffectIntent, + scope: EffectScope, + authority: &dyn EffectAuthority, + approval: Option<(&ApprovalGrant, u64)>, ) -> Result, AuthorityOutcome> { let (descriptor, live) = { let inner = self.broker.lock(); let session = inner .sessions .get(intent.provider.as_str()) - .ok_or_else(|| AuthorityOutcome::Denied("provider is not admitted".into()))?; + .ok_or_else(|| AuthorityOutcome::Denied(NOT_ADMITTED.into()))?; ( find_tool(session, &intent.tool_name).cloned(), session.catalog_digest, ) }; if intent.capability_digest != live { - return Err(AuthorityOutcome::Denied( - "intent was staged against a stale catalog".into(), - )); + return Err(AuthorityOutcome::Denied(STALE_INTENT.into())); } let ctx = AuthorityContext::new(scope, descriptor, live, self.exposure.clone()); let decision = authority.authorize(&intent, &ctx); @@ -407,6 +602,11 @@ impl EffectLane { now: u64, ) -> Result { if let Some(existing) = self.replay_of(grant, &intent, &scope) { + if self.trace.enabled() { + let mut ids = self.effect_ids(&intent.provider, &intent.tool_name, scope.world_id); + ids.grant_id = Some(BoundedId::new(&hex(&grant.id().0))); + self.trace_execution(&existing, true, ids, Some(intent_digest(&intent))); + } return existing.map_err(AuthorityOutcome::Execution); } let effect = self.authorize_approved(intent, scope, authority, grant, now)?; @@ -482,6 +682,70 @@ impl EffectLane { pub async fn execute_effect( &self, effect: AuthorizedEffect, + ) -> Result { + if !self.trace.enabled() { + return self.execute_core(effect, &mut false).await; + } + let mut ids = self.effect_ids( + &effect.intent().provider, + &effect.intent().tool_name, + effect.world_id(), + ); + ids.grant_id = effect.approval_id().map(|d| BoundedId::new(&hex(&d.0))); + let digest = intent_digest(effect.intent()); + let mut replay = false; + let result = self.execute_core(effect, &mut replay).await; + self.trace_execution(&result, replay, ids, Some(digest)); + result + } + + fn trace_execution( + &self, + result: &Result, + replay: bool, + ids: CorrelationIds, + intent: Option, + ) { + let mut refs = EvidenceRefs { + intent_digest: intent.and_then(|d| aien_trace::Digest::new(&hex(&d.0)).ok()), + ..Default::default() + }; + let (status, certainty, note) = match result { + Ok(receipt) => { + refs.effect_receipt_digest = + aien_trace::Digest::new(&hex(&receipt_digest(receipt))).ok(); + let note = replay.then_some("ledger_replay"); + (EventStatus::Ok, Some(EffectCertainty::EffectOccurred), note) + } + Err(Error::Rejected(_)) => { + (EventStatus::Rejected, Some(EffectCertainty::NoEffect), None) + } + Err(Error::ReconciliationRequired) => ( + EventStatus::Uncertain, + Some(EffectCertainty::Uncertain), + None, + ), + Err(Error::EffectInFlight) => (EventStatus::Rejected, None, Some("in_flight")), + Err(_) => ( + EventStatus::Rejected, + Some(EffectCertainty::NoEffect), + Some("refused"), + ), + }; + self.trace.emit( + EventKind::EffectExecuted, + status, + certainty, + ids, + refs, + note, + ); + } + + async fn execute_core( + &self, + effect: AuthorizedEffect, + replay: &mut bool, ) -> Result { let key = effect.idempotency_key(); let provider = effect.intent().provider.clone(); @@ -498,7 +762,10 @@ impl EffectLane { return Err(Error::IdempotencyConflict); } return match &existing.entry { - LedgerEntry::Completed(receipt) => Ok(receipt.clone()), + LedgerEntry::Completed(receipt) => { + *replay = true; + Ok(receipt.clone()) + } LedgerEntry::Uncertain => Err(Error::ReconciliationRequired), LedgerEntry::InFlight => Err(Error::EffectInFlight), }; @@ -589,3 +856,14 @@ fn identity(intent: &EffectIntent, world_id: WorldId, winning_jnode: JNodeId) -> fn find_tool<'a>(session: &'a McpSession, name: &str) -> Option<&'a ToolDescriptor> { session.tools.iter().find(|tool| tool.name() == name) } + +fn approval_name(e: &ApprovalError) -> &'static str { + match e { + ApprovalError::Unknown => "approval_unknown", + ApprovalError::Mismatch => "approval_mismatch", + ApprovalError::Consumed => "approval_consumed", + ApprovalError::Reserved => "approval_reserved", + ApprovalError::Expired => "approval_expired", + ApprovalError::Revoked => "approval_revoked", + } +} diff --git a/crates/aien-mcp/src/lib.rs b/crates/aien-mcp/src/lib.rs index 721680eb..bb2f78d1 100644 --- a/crates/aien-mcp/src/lib.rs +++ b/crates/aien-mcp/src/lib.rs @@ -29,7 +29,9 @@ pub use authority::{ intent_digest, AuthorityContext, AuthorityDecision, AuthorityOutcome, EffectAuthority, EffectClassAuthority, EffectScope, Exposure, TrustLevel, }; -pub use broker::{Clock, EffectLane, McpBroker, SpeculativeLane, SpeculativeToolCall}; +pub use broker::{ + receipt_digest, Clock, EffectLane, McpBroker, SpeculativeLane, SpeculativeToolCall, +}; pub use effect::{AuthorizedEffect, EffectIntent, EffectReceipt, ToolResult}; pub use error::Error; pub use session::SessionManager; diff --git a/crates/aien-mcp/tests/trace.rs b/crates/aien-mcp/tests/trace.rs new file mode 100644 index 00000000..5d4ff9af --- /dev/null +++ b/crates/aien-mcp/tests/trace.rs @@ -0,0 +1,351 @@ +//! Correlation trace events from the effect lane (#398), through the public API. +//! Events are observational: these tests also check that nothing sensitive is in them. +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Arc; + +use aien_capability::{ + Digest32, EffectId, JNodeId, ProviderId, ToolDescriptor, ToolEffects, WorldId, +}; +use aien_mcp::memory::MemoryWire; +use aien_mcp::{ + receipt_digest, ApprovalDesk, AuthorityContext, AuthorityDecision, CallOutcome, + EffectAuthority, EffectIntent, EffectLane, EffectReceipt, EffectScope, McpBroker, + SpeculativeLane, +}; +use aien_trace::{ + EffectCertainty, EventKind, EventStatus, MemorySink, TraceEvent, TraceId, TraceSink, +}; +use serde_json::{json, Value}; + +const SECRET_ARG: &str = "SECRET-ARGUMENT-VALUE-1"; +const SECRET_OUT: &str = "SECRET-OUTPUT-VALUE-2"; + +struct Fixed(AuthorityDecision); +impl EffectAuthority for Fixed { + fn authorize(&self, _: &EffectIntent, _: &AuthorityContext) -> AuthorityDecision { + self.0.clone() + } +} + +struct H { + broker: McpBroker, + lane: EffectLane, + desk: ApprovalDesk, + sink: Arc, + calls: Arc, + intent: EffectIntent, +} + +fn scope(label: &str) -> EffectScope { + EffectScope { + world_id: WorldId(7), + winning_jnode: JNodeId(1), + idempotency_key: EffectId::from_label(label), + } +} + +async fn harness(outcome: CallOutcome) -> H { + let calls = Arc::new(AtomicUsize::new(0)); + let c = calls.clone(); + let tool = ToolDescriptor::new("send", ToolEffects::WORLD_MUTATION, Digest32::of(b"send")); + let wire = MemoryWire::new(vec![tool], move |_, _| { + c.fetch_add(1, Ordering::SeqCst); + outcome.clone() + }); + let broker = McpBroker::new(); + let provider = ProviderId::new("mail"); + broker + .admit(provider.clone(), Arc::new(wire)) + .await + .unwrap(); + let live = SpeculativeLane::new(broker.clone()) + .discovery_snapshot(&provider) + .await + .unwrap() + .catalog_digest; + let sink = Arc::new(MemorySink::new()); + let dynsink: Arc = sink.clone(); + let lane = EffectLane::new(broker.clone()) + .with_clock(Arc::new(|| 1)) + .with_trace(dynsink, TraceId::derive(1, 2, 3), Some(41)); + H { + lane, + desk: ApprovalDesk::new(broker.clone()), + broker, + sink, + calls, + intent: EffectIntent { + provider, + tool_name: "send".into(), + arguments: json!({"body": SECRET_ARG}), + capability_digest: live, + }, + } +} + +fn finished() -> CallOutcome { + CallOutcome::Finished(json!({"result": SECRET_OUT})) +} + +fn is_hex64(s: &str) -> bool { + s.len() == 64 + && s.bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) +} + +#[tokio::test] +async fn allow_then_finished_gives_ok_events_with_receipt_digest() { + let h = harness(finished()).await; + let r = h + .lane + .authorize_and_execute( + h.intent.clone(), + scope("a"), + &Fixed(AuthorityDecision::Allow), + ) + .await + .unwrap(); + let ev = h.sink.drain(); + assert_eq!(ev.len(), 2); + assert_eq!(ev[0].kind, EventKind::AuthorityDecided); + assert_eq!(ev[0].status, EventStatus::Ok); + assert_eq!(ev[0].parent_event_id, Some(41)); + assert_eq!(ev[0].ids.world_id, Some(7)); + assert_eq!( + ev[0].ids.tool_request_id.as_ref().unwrap().as_str(), + "mail:send" + ); + assert!(is_hex64( + ev[0].refs.intent_digest.as_ref().unwrap().as_str() + )); + assert_eq!(ev[1].kind, EventKind::EffectExecuted); + assert_eq!(ev[1].status, EventStatus::Ok); + assert_eq!( + ev[1].effect_certainty, + Some(EffectCertainty::EffectOccurred) + ); + let d = ev[1].refs.effect_receipt_digest.as_ref().unwrap().as_str(); + assert!(is_hex64(d)); + let want: String = receipt_digest(&r) + .iter() + .map(|b| format!("{b:02x}")) + .collect(); + assert_eq!(d, want); +} + +#[tokio::test] +async fn deny_contain_and_stale_are_rejected_and_nothing_runs() { + let h = harness(finished()).await; + let _ = h.lane.authorize( + h.intent.clone(), + scope("d"), + &Fixed(AuthorityDecision::Deny("no".into())), + ); + let _ = h.lane.authorize( + h.intent.clone(), + scope("c"), + &Fixed(AuthorityDecision::Contain("x".into())), + ); + let mut stale = h.intent.clone(); + stale.capability_digest = Digest32::of(b"old"); + let _ = h + .lane + .authorize(stale, scope("s"), &Fixed(AuthorityDecision::Allow)); + let ev = h.sink.drain(); + assert_eq!(ev.len(), 3); + assert!(ev.iter().all(|e| e.status == EventStatus::Rejected)); + assert_eq!(ev[0].note, None); + assert_eq!(ev[1].note.as_ref().unwrap().as_str(), "contained"); + assert_eq!(ev[2].note.as_ref().unwrap().as_str(), "stale_intent"); + assert_eq!(h.calls.load(Ordering::SeqCst), 0); +} + +#[tokio::test] +async fn require_approval_is_approval_pending_then_grant_id_appears() { + let h = harness(finished()).await; + let auth = Fixed(AuthorityDecision::RequireApproval("human".into())); + assert!(h + .lane + .authorize(h.intent.clone(), scope("p"), &auth) + .is_err()); + let ev = h.sink.drain(); + assert_eq!(ev[0].status, EventStatus::ApprovalPending); + assert_eq!(ev[0].ids.grant_id, None); + + let grant = h.desk.issue(&h.intent, scope("p"), 100); + h.lane + .authorize_and_execute_approved(h.intent.clone(), scope("p"), &auth, &grant, 1) + .await + .unwrap(); + let ev = h.sink.drain(); + assert_eq!(ev[0].status, EventStatus::Ok); + assert!(is_hex64(ev[0].ids.grant_id.as_ref().unwrap().as_str())); + assert_eq!(ev[1].ids.grant_id, ev[0].ids.grant_id); + + // Spending the grant for another effect is refused and named. + let other = scope("other"); + assert!(h + .lane + .authorize_approved(h.intent.clone(), other, &auth, &grant, 1) + .is_err()); + let ev = h.sink.drain(); + assert_eq!(ev[0].status, EventStatus::Rejected); + assert!(ev[0].note.is_some()); +} + +#[tokio::test] +async fn uncertain_provider_gives_uncertain_status_and_certainty() { + let h = harness(CallOutcome::Uncertain).await; + let r = h + .lane + .authorize_and_execute( + h.intent.clone(), + scope("u"), + &Fixed(AuthorityDecision::Allow), + ) + .await; + assert!(r.is_err()); + let ev = h.sink.drain(); + assert_eq!(ev[1].kind, EventKind::EffectExecuted); + assert_eq!(ev[1].status, EventStatus::Uncertain); + assert_eq!(ev[1].effect_certainty, Some(EffectCertainty::Uncertain)); + assert_eq!(ev[1].refs.effect_receipt_digest, None); +} + +#[tokio::test] +async fn rejected_provider_call_is_no_effect() { + let h = harness(CallOutcome::Rejected("bad".into())).await; + let _ = h + .lane + .authorize_and_execute( + h.intent.clone(), + scope("r"), + &Fixed(AuthorityDecision::Allow), + ) + .await; + let ev = h.sink.drain(); + assert_eq!(ev[1].status, EventStatus::Rejected); + assert_eq!(ev[1].effect_certainty, Some(EffectCertainty::NoEffect)); +} + +#[tokio::test] +async fn second_execute_is_a_ledger_replay_without_a_second_call() { + let h = harness(finished()).await; + let allow = Fixed(AuthorityDecision::Allow); + let first = h + .lane + .authorize_and_execute(h.intent.clone(), scope("k"), &allow) + .await + .unwrap(); + let second = h + .lane + .authorize_and_execute(h.intent.clone(), scope("k"), &allow) + .await + .unwrap(); + assert_eq!(first, second); + assert_eq!(h.calls.load(Ordering::SeqCst), 1); + let ev = h.sink.drain(); + let execs: Vec<&TraceEvent> = ev + .iter() + .filter(|e| e.kind == EventKind::EffectExecuted) + .collect(); + assert_eq!(execs.len(), 2); + assert_eq!(execs[0].note, None); + assert_eq!(execs[1].note.as_ref().unwrap().as_str(), "ledger_replay"); + assert_eq!(execs[1].status, EventStatus::Ok); + assert_eq!( + execs[0].refs.effect_receipt_digest, + execs[1].refs.effect_receipt_digest + ); +} + +#[tokio::test] +async fn no_event_carries_arguments_outputs_or_forbidden_keys() { + let h = harness(finished()).await; + let allow = Fixed(AuthorityDecision::Allow); + for (i, a) in [ + AuthorityDecision::Allow, + AuthorityDecision::Deny("no".into()), + AuthorityDecision::RequireApproval("h".into()), + ] + .into_iter() + .enumerate() + { + let _ = h + .lane + .authorize_and_execute(h.intent.clone(), scope(&format!("j{i}")), &Fixed(a)) + .await; + } + let _ = allow; + let ev = h.sink.drain(); + assert!(ev.len() >= 4); + let text = serde_json::to_string(&ev).unwrap(); + assert!(!text.contains(SECRET_ARG)); + assert!(!text.contains(SECRET_OUT)); + fn keys(v: &Value, out: &mut Vec) { + match v { + Value::Object(m) => { + for (k, v) in m { + out.push(k.clone()); + keys(v, out); + } + } + Value::Array(a) => a.iter().for_each(|v| keys(v, out)), + _ => {} + } + } + let mut ks = Vec::new(); + keys(&serde_json::to_value(&ev).unwrap(), &mut ks); + for k in ks { + for bad in ["arguments", "output", "prompt", "content"] { + assert!(!k.contains(bad), "key {k}"); + } + } +} + +#[tokio::test] +async fn default_lane_emits_nothing_and_still_works() { + let h = harness(finished()).await; + let plain = EffectLane::new(h.broker.clone()); + let r = plain + .authorize_and_execute( + h.intent.clone(), + scope("n"), + &Fixed(AuthorityDecision::Allow), + ) + .await; + assert!(r.is_ok()); + assert!(h.sink.drain().is_empty()); +} + +fn receipt() -> EffectReceipt { + EffectReceipt { + effect_id: EffectId::from_label("e"), + world_id: WorldId(1), + winning_jnode: JNodeId(2), + policy_digest: Digest32::of(b"p"), + provider: ProviderId::new("mail"), + tool_name: "send".into(), + capability_digest: Digest32::of(b"c"), + output: json!({"b": 1, "a": [1, 2]}), + } +} + +#[test] +fn receipt_digest_depends_on_output_and_tool_name_but_not_key_order() { + let base = receipt(); + let d = receipt_digest(&base); + assert_eq!(d, receipt_digest(&base.clone())); + let mut o = base.clone(); + o.output = json!({"b": 2, "a": [1, 2]}); + assert_ne!(d, receipt_digest(&o)); + let mut t = base.clone(); + t.tool_name = "send2".into(); + assert_ne!(d, receipt_digest(&t)); + let mut w = base.clone(); + w.world_id = WorldId(9); + assert_ne!(d, receipt_digest(&w)); + let mut k = base.clone(); + k.output = serde_json::from_str(r#"{"a":[1,2],"b":1}"#).unwrap(); + assert_eq!(d, receipt_digest(&k)); +} diff --git a/crates/aien-runtime/Cargo.toml b/crates/aien-runtime/Cargo.toml index d7e8cd3b..a71da99c 100644 --- a/crates/aien-runtime/Cargo.toml +++ b/crates/aien-runtime/Cargo.toml @@ -11,6 +11,7 @@ description = "Canonical single-process runtime spine for AIEN persistent branch aien-platform = { path = "../aien-platform" } aien-kv-cache = { path = "../aien-kv-cache" } aien-scheduler = { path = "../aien-scheduler" } +aien-trace = { path = "../aien-trace" } aien-abi-core = { path = "../aien-abi-core" } aien-inference-abi = { path = "../aien-inference-abi" } aien-security = { path = "../aien-security" } diff --git a/crates/aien-runtime/src/effects.rs b/crates/aien-runtime/src/effects.rs index e66385be..4b16586f 100644 --- a/crates/aien-runtime/src/effects.rs +++ b/crates/aien-runtime/src/effects.rs @@ -1332,10 +1332,77 @@ pub fn mint_grant(b: &ComposeBridge, req: &MintRequest) -> ControlResponse { /// desk key, a MAC over other fields, or a reused nonce is refused and /// NOTHING is written. With the switch OFF the proof is ignored (legacy /// behaviour: OS-user authentication only). +/// The refusal name out of a `Refusal` display string, or "error" for any +/// other error text. Used only for trace notes (#398); never for decisions. +fn refusal_name(e: &str) -> &str { + e.strip_prefix("EFFECT_REFUSED ") + .and_then(|rest| rest.split(':').next()) + .map(str::trim) + .filter(|n| !n.is_empty()) + .unwrap_or("error") +} + +/// Emits one correlation event for a control response (#398): `Ok` with the +/// note's record id in `id_slot`, `Rejected` with the refusal name for a +/// refusal, `Failed` for any other error. Observational only. +fn trace_response( + b: &ComposeBridge, + kind: aien_trace::EventKind, + r: &ControlResponse, + mut ids: aien_trace::CorrelationIds, + id_slot: fn(&mut aien_trace::CorrelationIds, u64), + certainty_ok: Option, +) { + use aien_trace::EventStatus; + let (status, certainty, note) = match r { + ControlResponse::ComposeNoted(n) => { + id_slot(&mut ids, n.id); + (EventStatus::Ok, certainty_ok, "") + } + ControlResponse::Error(e) if e.starts_with("EFFECT_REFUSED ") => ( + EventStatus::Rejected, + Some(aien_trace::EffectCertainty::NoEffect), + refusal_name(e), + ), + ControlResponse::Error(_) => (EventStatus::Failed, None, "error"), + _ => (EventStatus::Malformed, None, "unexpected_response"), + }; + b.trace_event( + kind, + status, + certainty, + ids, + aien_trace::EvidenceRefs::default(), + note, + ); +} + pub fn authorize( b: &ComposeBridge, req: &MintRequest, proof: Option<&crate::control::DeskProof>, +) -> ControlResponse { + let r = authorize_inner(b, req, proof); + if b.trace_enabled() { + trace_response( + b, + aien_trace::EventKind::AuthorityDecided, + &r, + aien_trace::CorrelationIds { + decision_id: Some(aien_trace::BoundedId::new(&req.cx_promotion.to_string())), + ..Default::default() + }, + |ids, id| ids.grant_id = Some(aien_trace::BoundedId::new(&id.to_string())), + Some(aien_trace::EffectCertainty::NoEffect), + ); + } + r +} + +fn authorize_inner( + b: &ComposeBridge, + req: &MintRequest, + proof: Option<&crate::control::DeskProof>, ) -> ControlResponse { if let Err(e) = reconcile_gate(b) { return ControlResponse::Error(e); @@ -1590,6 +1657,24 @@ fn intent_prior(l: &Ledger, req: &IntentRequest) -> IntentRead { /// ComposeEffectIntent: every check of 2.3 and the durable intent, in one /// step under the home lock. The answer's id is the intent. pub fn open_intent(b: &ComposeBridge, req: &IntentRequest) -> ControlResponse { + let r = open_intent_inner(b, req); + if b.trace_enabled() { + trace_response( + b, + aien_trace::EventKind::ToolRequested, + &r, + aien_trace::CorrelationIds { + grant_id: Some(aien_trace::BoundedId::new(&req.authorization.to_string())), + ..Default::default() + }, + |ids, id| ids.tool_request_id = Some(aien_trace::BoundedId::new(&id.to_string())), + Some(aien_trace::EffectCertainty::NoEffect), + ); + } + r +} + +fn open_intent_inner(b: &ComposeBridge, req: &IntentRequest) -> ControlResponse { if let Err(e) = reconcile_gate(b) { return ControlResponse::Error(e); } @@ -1642,7 +1727,10 @@ pub fn ack(b: &ComposeBridge, intent: u64, reported: &Value) -> ControlResponse if let Err(e) = reconcile_gate(b) { return ControlResponse::Error(e); } - noted(b.with_home(|home| { + // The settled state, for the trace event only (#398). + let mut settled: Option = None; + let mut grant: Option = None; + let r = noted(b.with_home(|home| { let views = host_views(home)?; let l = Ledger::from_records(&views).map_err(|r| r.to_string())?; let row = l @@ -1657,6 +1745,8 @@ pub fn ack(b: &ComposeBridge, intent: u64, reported: &Value) -> ControlResponse )); } let (st, disk) = confined_world_state(&l, row); + settled = Some(st.name().to_string()); + grant = Some(row.authorization); let mut text = json!({ "phase": PHASE_ACK, "intent": intent, "authorization": row.authorization, "tool": "write_file", "path": row.path, "content_sha256": row.content_sha256, @@ -1665,7 +1755,51 @@ pub fn ack(b: &ComposeBridge, intent: u64, reported: &Value) -> ControlResponse }); stamp(&mut text, &views, intent); append(home, NoteKind::Effect, &[intent, row.authorization], &text) - })) + })); + // Correlation only (#398): the settled state of this intent as the ledger + // judged it. DONE is the only `effect_occurred`; NOT_DONE is `no_effect`; + // UNRESOLVED stays `uncertain` and nothing reading a trace may retry it. + if b.trace_enabled() { + use aien_trace::{EffectCertainty, EventStatus}; + let (status, certainty, note) = match (&r, settled.as_deref()) { + (ControlResponse::ComposeNoted(_), Some("DONE")) => ( + EventStatus::Ok, + Some(EffectCertainty::EffectOccurred), + "DONE", + ), + // NOT_DONE: the world check says the effect did not happen, so it is a + // definite no-effect outcome (C2 `rejected`), not `failed` (ran and + // errored). + (ControlResponse::ComposeNoted(_), Some("NOT_DONE")) => ( + EventStatus::Rejected, + Some(EffectCertainty::NoEffect), + "NOT_DONE", + ), + (ControlResponse::ComposeNoted(_), _) => ( + EventStatus::Uncertain, + Some(EffectCertainty::Uncertain), + "UNRESOLVED", + ), + (ControlResponse::Error(e), _) if e.starts_with("EFFECT_REFUSED ") => { + (EventStatus::Rejected, None, refusal_name(e)) + } + (ControlResponse::Error(_), _) => (EventStatus::Failed, None, "error"), + _ => (EventStatus::Malformed, None, "unexpected_response"), + }; + b.trace_event( + aien_trace::EventKind::EffectExecuted, + status, + certainty, + aien_trace::CorrelationIds { + tool_request_id: Some(aien_trace::BoundedId::new(&intent.to_string())), + grant_id: grant.map(|g| aien_trace::BoundedId::new(&g.to_string())), + ..Default::default() + }, + aien_trace::EvidenceRefs::default(), + note, + ); + } + r } /// Reconcile every unsettled intent whose executor is gone, or record one @@ -1775,7 +1909,7 @@ pub fn reconcile( outcomes: out, }) }); - match r { + let out = match r { Ok(r) => { // A full reconcile that completed lifts the refusal of 2.5; a // single declaration does not. @@ -1785,7 +1919,29 @@ pub fn reconcile( ControlResponse::ComposeReconciled(Box::new(r)) } Err(e) => ControlResponse::Error(e), + }; + // Correlation only (#398): one event per reconcile call. `by` is a short + // caller label ("reconcile@start", an operator name), never free text + // from a model; the note is bounded anyway. + if b.trace_enabled() { + let (status, note) = match &out { + ControlResponse::ComposeReconciled(_) => (aien_trace::EventStatus::Ok, by), + ControlResponse::Error(_) => (aien_trace::EventStatus::Failed, "reconcile_failed"), + _ => (aien_trace::EventStatus::Malformed, "unexpected_response"), + }; + b.trace_event( + aien_trace::EventKind::ResultReceived, + status, + None, + aien_trace::CorrelationIds { + tool_request_id: declare.map(|d| aien_trace::BoundedId::new(&d.intent.to_string())), + ..Default::default() + }, + aien_trace::EvidenceRefs::default(), + note, + ); } + out } /// ComposeControl: stop, resume, revoke (ACCEPTANCE-v2 2.5, 2.6). @@ -1911,6 +2067,111 @@ pub fn reconcile_at_start(b: &ComposeBridge) -> String { mod tests { use super::*; + #[test] + fn refusal_name_reads_only_the_name() { + assert_eq!( + refusal_name("EFFECT_REFUSED NotAuthorized: needs an approver"), + "NotAuthorized" + ); + assert_eq!(refusal_name("EFFECT_REFUSED Revoked: grant #3"), "Revoked"); + assert_eq!(refusal_name("EFFECT_REFUSED : odd"), "error"); + assert_eq!(refusal_name("compose home refused: journal"), "error"); + assert_eq!(refusal_name(""), "error"); + } + + /// #398: the compose spine emits correlation events for authority, intent, + /// ack and reconcile outcomes; refusals carry only the refusal name, and no + /// event carries goal, proposal or path text. + #[test] + fn compose_spine_emits_correlation_events_without_content() { + use aien_trace::{EffectCertainty, EventKind, EventStatus, MemorySink}; + let _home = crate::home_guard::home_slot(); + if !aien_omega_compose::LINKED { + eprintln!("NOT_RUN: stub compose build"); + return; + } + let t = tempfile::tempdir().unwrap(); + let proposer: crate::spine::ComposeProposer = + std::sync::Arc::new(|_: &str, _: std::time::Duration| { + Ok(crate::spine::Generation::default()) + }); + let sink = std::sync::Arc::new(MemorySink::new()); + let b = ComposeBridge::new(t.path().join("compose"), proposer, "test:trace") + .with_trace_sink(sink.clone()); + // Start-up reconcile on an empty home: one result_received event. + let _ = reconcile_at_start(&b); + // Refused authorization: no approver. + let r = authorize( + &b, + &MintRequest { + cx_promotion: 7, + proposal_sha256: "00".repeat(32), + workspace: t.path().display().to_string(), + approver: " ".into(), + constraints: vec![], + }, + None, + ); + assert!( + matches!(r, ControlResponse::Error(ref e) if e.contains("NotAuthorized")), + "{r:?}" + ); + // Ack of an intent that does not exist: plain error, never a certainty. + let r = ack(&b, 999, &json!({"wrote": true})); + assert!(matches!(r, ControlResponse::Error(_)), "{r:?}"); + let events = sink.drain(); + let kinds: Vec = events.iter().map(|e| e.kind).collect(); + assert!( + kinds.contains(&EventKind::AuthorityDecided) + && kinds.contains(&EventKind::EffectExecuted), + "{kinds:?}" + ); + let auth = events + .iter() + .find(|e| e.kind == EventKind::AuthorityDecided) + .unwrap(); + assert_eq!(auth.status, EventStatus::Rejected); + assert_eq!(auth.effect_certainty, Some(EffectCertainty::NoEffect)); + assert_eq!( + auth.note.as_ref().map(|n| n.as_str()), + Some("NotAuthorized") + ); + assert_eq!(auth.ids.decision_id.as_ref().map(|d| d.as_str()), Some("7")); + let eff = events + .iter() + .find(|e| e.kind == EventKind::EffectExecuted) + .unwrap(); + assert_eq!(eff.status, EventStatus::Failed); + assert_eq!(eff.effect_certainty, None); + assert_eq!( + eff.ids.tool_request_id.as_ref().map(|d| d.as_str()), + Some("999") + ); + // One trace id, one root, every other event a child of it. + let root = events + .iter() + .filter(|e| e.parent_event_id.is_none()) + .count(); + assert_eq!(root, 1, "{events:?}"); + let root_id = events + .iter() + .find(|e| e.parent_event_id.is_none()) + .unwrap() + .event_id; + assert!(events.iter().all(|e| e.trace_id == b.trace_id())); + assert!(events + .iter() + .filter(|e| e.event_id != root_id) + .all(|e| e.parent_event_id == Some(root_id))); + // No content: the serialized events never carry the workspace path or + // the proposal digest, only ids, kinds, statuses and refusal names. + let text = serde_json::to_string(&events).unwrap(); + assert!(!text.contains(&t.path().display().to_string()), "{text}"); + assert!(!text.contains(&"00".repeat(32)), "{text}"); + let tree = aien_trace::reconstruct(&events).unwrap(); + assert_eq!(tree.len(), events.len()); + } + fn rec(id: u64, note: &str, text: Value) -> ComposeRecordView { ComposeRecordView { id, @@ -2170,7 +2431,9 @@ mod tests { "write_compose_commit", "write_approved_grant", "authorize", + "authorize_inner", "open_intent", + "open_intent_inner", "ack", "check_reserved_note", ]; @@ -2183,7 +2446,15 @@ mod tests { // Inside the writers that also decide, the only mention is the stamp // call (or the reserved-field refusal), never a read of the fields. for (f, line) in &hits { - if ["authorize", "open_intent", "ack"].contains(&f.as_str()) { + if [ + "authorize", + "authorize_inner", + "open_intent", + "open_intent_inner", + "ack", + ] + .contains(&f.as_str()) + { assert!( line.starts_with("stamp(&mut text, &views, "), "{f} touches provenance other than by stamp: {line}" diff --git a/crates/aien-runtime/src/lib.rs b/crates/aien-runtime/src/lib.rs index 655a546c..4ac72cc7 100644 --- a/crates/aien-runtime/src/lib.rs +++ b/crates/aien-runtime/src/lib.rs @@ -20,6 +20,7 @@ pub mod server; pub mod shared_kv; pub mod spine; pub mod swarm; +pub mod trace_observer; pub mod world; /// Test-only: one slot per process for tests that open a compose home (omega allows 4 handles). diff --git a/crates/aien-runtime/src/server.rs b/crates/aien-runtime/src/server.rs index bafb3020..1ff66220 100644 --- a/crates/aien-runtime/src/server.rs +++ b/crates/aien-runtime/src/server.rs @@ -244,6 +244,11 @@ impl AienRuntimeServer { .expect("compose override") .clone(); let identity = self.identity.lock().expect("identity lock").clone(); + // Correlation trace exporter (#398): on only when AIEN_TRACE_JSONL names + // a file. Off, the bridge keeps a NullSink and emits nothing. The flusher + // handle lives until the end of `run`, after the compose home closes, + // so the last events are written at shutdown. + let (trace_sink, _trace_flusher) = trace_sink_from_env(); let compose = match compose_dir_from_env() { _ if preset.is_some() => preset, Ok(dir) => Some(Arc::new( @@ -261,7 +266,8 @@ impl AienRuntimeServer { self.tokenizer.clone(), tokio::runtime::Handle::current(), )?) - .with_authorize_requires_desk(authorize_desk), + .with_authorize_requires_desk(authorize_desk) + .with_trace_sink(trace_sink), )), Err(e) => { tracing::warn!("compose bridge disabled: {e}"); @@ -1060,6 +1066,25 @@ async fn handle_connection( } } +/// The correlation trace sink for this daemon (#398). `AIEN_TRACE_JSONL=` +/// turns on a bounded append-only JSON-lines exporter (4096 queued events, +/// drops counted and reported as `trace_dropped`, flushed every 250 ms and +/// once more when the returned handle drops). Unset or empty: `NullSink`. +/// Never fails the daemon: an unwritable file only loses trace lines. +pub fn trace_sink_from_env() -> ( + Arc, + Option, +) { + match std::env::var("AIEN_TRACE_JSONL") { + Ok(path) if !path.trim().is_empty() => { + let sink = Arc::new(aien_trace::BoundedJsonlSink::new(path.trim())); + let flusher = sink.spawn_flusher(std::time::Duration::from_millis(250)); + tracing::info!(path = %sink.path().display(), "trace exporter on (AIEN_TRACE_JSONL)"); + (sink, Some(flusher)) + } + _ => (Arc::new(aien_trace::NullSink), None), + } +} #[cfg(test)] mod generation_record_tests { use super::*; diff --git a/crates/aien-runtime/src/spine.rs b/crates/aien-runtime/src/spine.rs index 667d2aba..13bbf411 100644 --- a/crates/aien-runtime/src/spine.rs +++ b/crates/aien-runtime/src/spine.rs @@ -2124,6 +2124,15 @@ pub struct ComposeBridge { crate::generation::DaemonStart, )>, >, + /// Correlation trace (sovereign-core #398). Observational only: events + /// carry ids and digests, never prompts, proposals or file contents, and + /// nothing reads them to decide. `NullSink` by default (tracing off). + trace: Arc, + /// One trace id per bridge (per daemon start and compose home). + trace_id: aien_trace::TraceId, + /// Event id of the first event this bridge emitted; the parent of all its + /// later events. 0 until the first event. + trace_root: std::sync::atomic::AtomicU64, } impl ComposeBridge { @@ -2138,9 +2147,70 @@ impl ComposeBridge { closed: std::sync::atomic::AtomicBool::new(false), authorize_requires_desk: true, identity: std::sync::Mutex::new(None), + trace: Arc::new(aien_trace::NullSink), + trace_id: aien_trace::TraceId::derive( + aien_trace::now_unix_ms(), + u64::from(std::process::id()), + 0, + ), + trace_root: std::sync::atomic::AtomicU64::new(0), } } + /// Installs the correlation trace sink (#398). Default `NullSink`. + pub fn with_trace_sink(mut self, sink: Arc) -> Self { + self.trace = sink; + self + } + + /// This bridge's trace id (correlation key, not a secret). + pub fn trace_id(&self) -> aien_trace::TraceId { + self.trace_id + } + + /// True when a trace sink is installed. Call sites check this before + /// building ids so that a disabled sink costs no allocation. + pub(crate) fn trace_enabled(&self) -> bool { + self.trace.enabled() + } + + /// Emits one correlation event for this bridge. The first event becomes + /// the root; every later one is its child. With the sink disabled this + /// allocates nothing and reads no clock (callers build the ids only after + /// `trace_enabled`). Returns the event id (0 if off). + pub(crate) fn trace_event( + &self, + kind: aien_trace::EventKind, + status: aien_trace::EventStatus, + effect_certainty: Option, + ids: aien_trace::CorrelationIds, + refs: aien_trace::EvidenceRefs, + note: &str, + ) -> u64 { + use std::sync::atomic::Ordering; + if !self.trace.enabled() { + return 0; + } + let id = self.trace.next_event_id(); + let parent = self + .trace_root + .compare_exchange(0, id, Ordering::AcqRel, Ordering::Acquire) + .err(); + self.trace.emit(aien_trace::TraceEvent { + trace_id: self.trace_id, + event_id: id, + parent_event_id: parent, + at_unix_ms: aien_trace::now_unix_ms(), + kind, + status, + effect_certainty, + ids, + refs, + note: (!note.is_empty()).then(|| aien_trace::BoundedNote::new(note)), + }); + id + } + /// Use `doc_proposer` (its own token cap) for full-document tasks. pub fn with_doc_proposer(mut self, doc_proposer: ComposeProposer) -> Self { self.doc_proposer = Some(doc_proposer); @@ -2600,6 +2670,32 @@ impl ComposeBridge { })?; compose_commit = Some(id); } + // Correlation only (#398): the turn happened, what record names it, + // and whether it committed. No proposal text, no goal text. + if self.trace_enabled() { + self.trace_event( + aien_trace::EventKind::ModelTurn, + if proposer_error.is_some() { + aien_trace::EventStatus::Failed + } else { + aien_trace::EventStatus::Ok + }, + None, + aien_trace::CorrelationIds { + generation_record, + decision_id: compose_commit.map(|c| aien_trace::BoundedId::new(&c.to_string())), + ..Default::default() + }, + aien_trace::EvidenceRefs::default(), + if proposer_error.is_some() { + "proposer_error" + } else if committed { + "compose_commit" + } else { + "uncommitted" + }, + ); + } Ok(ComposeTaskReport { compose_commit, generation_record, diff --git a/crates/aien-runtime/src/swarm.rs b/crates/aien-runtime/src/swarm.rs index 687a4f9a..01453e02 100644 --- a/crates/aien-runtime/src/swarm.rs +++ b/crates/aien-runtime/src/swarm.rs @@ -4,8 +4,12 @@ use crate::sequence::{SequenceArena, SequenceId, SequenceState}; use crate::world::WorldStore; use aien_kv_cache::{AienKvManager, PrefillGateError}; +use aien_trace::{ + CorrelationIds, EventKind, EventStatus, EvidenceRefs, NullSink, TraceEvent, TraceId, TraceSink, +}; use serde::{Deserialize, Serialize}; use std::collections::HashMap; +use std::sync::Arc; #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] pub enum SwarmState { @@ -41,10 +45,18 @@ pub struct SwarmRecord { pub finished_branches: Vec, pub state: SwarmState, pub created_at: u64, + /// Id of the `swarm_launched` trace event (the parent of this swarm's + /// other trace events). Correlation only; `None` in old records. + #[serde(default)] + pub trace_root_event: Option, } pub struct SwarmManager { swarms: HashMap, + /// Correlation trace sink. `NullSink` by default (tracing off). + trace: Arc, + /// swarm id -> trace id, derived at launch from (root world, swarm id). + trace_ids: HashMap, next_swarm_id: u64, /// PREFILL-GATE: swarms whose root prompt has not been prefilled yet /// (swarm id -> root prompt). Branch KV is forked from the root only after @@ -62,11 +74,50 @@ impl SwarmManager { pub fn new() -> Self { Self { swarms: HashMap::new(), + trace: Arc::new(NullSink), + trace_ids: HashMap::new(), next_swarm_id: 1, pending_root_prefill: HashMap::new(), } } + /// Installs the correlation trace sink. The default is `NullSink`. + pub fn set_trace_sink(&mut self, sink: Arc) { + self.trace = sink; + } + + /// Trace id of a launched swarm: `TraceId::derive(root_world_id, swarm_id, 0)`. + pub fn trace_id(&self, swarm_id: u64) -> Option { + self.trace_ids.get(&swarm_id).copied() + } + + fn trace_event( + &self, + trace_id: TraceId, + parent: Option, + kind: EventKind, + status: EventStatus, + ids: CorrelationIds, + ) -> u64 { + if !self.trace.enabled() { + return 0; + } + let event_id = self.trace.next_event_id(); + self.trace.emit(TraceEvent { + trace_id, + event_id, + parent_event_id: parent, + at_unix_ms: aien_trace::now_unix_ms(), + kind, + status, + effect_certainty: None, + ids, + refs: EvidenceRefs::default(), + note: None, + }); + event_id + } + /// Launches a swarm: creates root sequence, preallocates root KV blocks, and forks N branches. pub fn launch_swarm( &mut self, @@ -97,6 +148,19 @@ impl SwarmManager { // 2. Allocate root prompt blocks in physical KV manager. This reserves // and zeroes blocks only (PrefillState::Allocated); no K/V is computed. + let trace_id = TraceId::derive(root_world_id, swarm_id, 0); + let root_event = self.trace_event( + trace_id, + None, + EventKind::SwarmLaunched, + EventStatus::Ok, + CorrelationIds { + swarm_id: Some(swarm_id), + world_id: Some(root_world_id), + root_sequence_id: Some(root_seq.as_u64()), + ..Default::default() + }, + ); let root_u64 = root_seq.as_u64(); kv.allocate_sequence(root_u64, prompt_tokens)?; @@ -119,6 +183,19 @@ impl SwarmManager { // Waiting on the root prefill, not decoding. child.state = SequenceState::Prefill; } + self.trace_event( + trace_id, + Some(root_event), + EventKind::BranchForked, + EventStatus::Ok, + CorrelationIds { + swarm_id: Some(swarm_id), + world_id: Some(child_world), + root_sequence_id: Some(root_seq.as_u64()), + sequence_id: Some(child_seq.as_u64()), + ..Default::default() + }, + ); branch_sequences.push(child_seq); branch_worlds.push(child_world); } @@ -134,7 +211,9 @@ impl SwarmManager { finished_branches: Vec::new(), state: SwarmState::Running, created_at: timestamp, + trace_root_event: Some(root_event), }; + self.trace_ids.insert(swarm_id, trace_id); self.swarms.insert(swarm_id, record); Ok(swarm_id) @@ -262,6 +341,19 @@ impl SwarmManager { let mut released = Vec::with_capacity(swarm.branch_sequences.len() + 1); released.push(swarm.root_sequence_id.as_u64()); released.extend(swarm.branch_sequences.iter().map(|b| b.as_u64())); + let root_event = swarm.trace_root_event; + if let Some(trace_id) = self.trace_ids.get(&swarm_id).copied() { + self.trace_event( + trace_id, + root_event, + EventKind::SwarmCancelled, + EventStatus::Cancelled, + CorrelationIds { + swarm_id: Some(swarm_id), + ..Default::default() + }, + ); + } Ok(released) } @@ -285,6 +377,20 @@ impl SwarmManager { .then_some(*id) }); let swarm_id = swarm_id?; + if let Some(trace_id) = self.trace_ids.get(&swarm_id).copied() { + let root_event = self.swarms.get(&swarm_id).and_then(|s| s.trace_root_event); + self.trace_event( + trace_id, + root_event, + EventKind::SequenceFinished, + EventStatus::Ok, + CorrelationIds { + swarm_id: Some(swarm_id), + sequence_id: Some(seq_id.as_u64()), + ..Default::default() + }, + ); + } let swarm = self .swarms diff --git a/crates/aien-runtime/src/trace_observer.rs b/crates/aien-runtime/src/trace_observer.rs new file mode 100644 index 00000000..d72ac44c --- /dev/null +++ b/crates/aien-runtime/src/trace_observer.rs @@ -0,0 +1,85 @@ +//! Correlation tap on the scheduler's admit/preempt decision (#398). +//! +//! Implements the scheduler's read-only `DecisionObserver`. For each +//! `AdmitPreemptRecord` it emits `sequence_admitted` for every queue head the +//! scheduler admitted (`AdmittedPrefill` or `AdmittedDecode` in +//! `alternatives.admission_examined`) and `sequence_preempted` for every id in +//! `choice.preempted`. Only sequences registered through +//! [`TraceDecisionObserver::register`] produce events; unknown sequences are +//! skipped without allocating. Observational only: it never changes a +//! scheduling decision, and it copies ids, never prompt or token data. + +use aien_scheduler::dual_observer::{AdmissionVerdict, AdmitPreemptRecord, DecisionObserver}; +use aien_trace::{ + now_unix_ms, CorrelationIds, EventKind, EventStatus, EvidenceRefs, TraceEvent, TraceId, + TraceSink, +}; +use parking_lot::Mutex; +use std::collections::HashMap; +use std::sync::Arc; + +pub struct TraceDecisionObserver { + sink: Arc, + /// sequence (packed u64) -> (trace id, parent event id) + trace_for_sequence: Mutex>, +} + +impl TraceDecisionObserver { + pub fn new(sink: Arc) -> Self { + Self { + sink, + trace_for_sequence: Mutex::new(HashMap::new()), + } + } + + /// Opt a sequence in. `parent` is the event its scheduler events hang under. + pub fn register(&self, seq: u64, trace: TraceId, parent: u64) { + self.trace_for_sequence.lock().insert(seq, (trace, parent)); + } + + /// Forget a sequence (after it finished or was cancelled). + pub fn unregister(&self, seq: u64) { + self.trace_for_sequence.lock().remove(&seq); + } + + fn emit(&self, seq: u64, kind: EventKind, step_id: u64) { + let Some((trace_id, parent)) = self.trace_for_sequence.lock().get(&seq).copied() else { + return; + }; + self.sink.emit(TraceEvent { + trace_id, + event_id: self.sink.next_event_id(), + parent_event_id: Some(parent), + at_unix_ms: now_unix_ms(), + kind, + status: EventStatus::Ok, + effect_certainty: None, + ids: CorrelationIds { + sequence_id: Some(seq), + step_id: Some(step_id), + ..Default::default() + }, + refs: EvidenceRefs::default(), + note: None, + }); + } +} + +impl DecisionObserver for TraceDecisionObserver { + fn observe_admit_preempt(&self, record: &AdmitPreemptRecord) { + if !self.sink.enabled() { + return; + } + for c in &record.alternatives.admission_examined { + if matches!( + c.verdict, + AdmissionVerdict::AdmittedDecode | AdmissionVerdict::AdmittedPrefill { .. } + ) { + self.emit(c.seq.to_u64(), EventKind::SequenceAdmitted, record.step_id); + } + } + for s in &record.choice.preempted { + self.emit(s.to_u64(), EventKind::SequencePreempted, record.step_id); + } + } +} diff --git a/crates/aien-runtime/tests/swarm_trace_test.rs b/crates/aien-runtime/tests/swarm_trace_test.rs new file mode 100644 index 00000000..2e32e7b3 --- /dev/null +++ b/crates/aien-runtime/tests/swarm_trace_test.rs @@ -0,0 +1,227 @@ +//! Swarm and scheduler correlation trace events (#398), end to end on the real spine. +//! Events are observational: they never change scheduling, KV or world handling. + +use std::path::PathBuf; +use std::sync::{Arc, OnceLock}; +use std::time::{SystemTime, UNIX_EPOCH}; + +use aien_inference_abi::{ + ModelConfig, NativeTransformerBackend, ReferenceCpuBackend, TransformerWeights, +}; +use aien_runtime::shared_kv::{build_shared_kv_runtime, SharedKvSizing}; +use aien_runtime::spine::AienRuntimeSpine; +use aien_runtime::swarm::SwarmConfig; +use aien_scheduler::SchedulerConfig; + +const PROMPT: [u32; 6] = [5, 17, 42, 3, 88, 61]; + +fn model_config() -> ModelConfig { + ModelConfig { + model_id: "trace-reference".to_string(), + max_sequence_length: 256, + block_size: 4, + num_layers: 3, + num_heads: 4, + head_dim: 8, + num_kv_heads: 2, + hidden_dim: 32, + intermediate_dim: 64, + vocab_size: 97, + rms_norm_eps: 1e-5, + rope_theta: 10000.0, + rope_scaling: None, + tie_word_embeddings: false, + eos_token_ids: Vec::new(), + qk_norm: false, + } +} + +fn scheduler_config() -> SchedulerConfig { + SchedulerConfig { + max_batch_size: 32, + max_batch_tokens: 2048, + max_prefill_tokens: 1024, + prefill_chunk_size: 128, + chunk_prefill: true, + watermark_blocks: 2, + } +} + +fn swarm_config(branches: usize, max_tokens: usize) -> SwarmConfig { + SwarmConfig { + model_handle: 1, + branch_count: branches, + max_active_sequences: branches, + max_tokens_per_branch: max_tokens, + root_world_id: 0, + priority: 1, + } +} + +/// One fresh controller state directory per test process. +fn fresh_state_dir() -> &'static PathBuf { + static DIR: OnceLock = OnceLock::new(); + DIR.get_or_init(|| { + let nanos = SystemTime::now() + .duration_since(UNIX_EPOCH) + .expect("clock after epoch") + .as_nanos(); + let dir = + std::env::temp_dir().join(format!("aien-trace-test-{}-{}", std::process::id(), nanos)); + std::fs::create_dir_all(&dir).expect("create fresh state dir"); + std::env::set_var("AIEN_RUNTIME_STATE_DIR", &dir); + dir + }) +} + +fn build(branches: usize) -> (AienRuntimeSpine, NativeTransformerBackend) { + fresh_state_dir(); + let weights = TransformerWeights::reference_test_weights(&model_config()); + build_shared_kv_runtime( + weights, + Arc::new(ReferenceCpuBackend::new()), + scheduler_config(), + SharedKvSizing { + arena_capacity: branches + 16, + total_blocks: (branches + 16) * 4, + }, + ) + .expect("build shared KV runtime") +} + +async fn run_to_completion(spine: &mut AienRuntimeSpine, backend: &mut NativeTransformerBackend) { + let mut steps = 0; + while (spine.scheduler.running_count() > 0 || spine.scheduler.waiting_count() > 0) + && steps < 500 + { + steps += 1; + spine.step(backend).await.expect("spine step"); + } +} + +use aien_runtime::control::{ControlCommand, ControlEnvelope, ControlResponse}; +use aien_runtime::trace_observer::TraceDecisionObserver; +use aien_trace::{reconstruct, EventKind, EventStatus, MemorySink, TraceEvent, TraceSink}; + +fn count(ev: &[TraceEvent], k: EventKind) -> usize { + ev.iter().filter(|e| e.kind == k).count() +} + +#[tokio::test] +async fn three_branch_swarm_reconstructs_with_valid_parents() { + let (mut spine, mut backend) = build(3); + let sink = Arc::new(MemorySink::new()); + spine.swarm_manager.set_trace_sink(sink.clone()); + let swarm_id = spine + .launch_swarm(swarm_config(3, 3), &PROMPT) + .expect("launch"); + run_to_completion(&mut spine, &mut backend).await; + + let ev = sink.drain(); + assert_eq!(count(&ev, EventKind::SwarmLaunched), 1); + assert_eq!(count(&ev, EventKind::BranchForked), 3); + assert_eq!(count(&ev, EventKind::SequenceFinished), 3); + assert_eq!(count(&ev, EventKind::SwarmCancelled), 0); + + let tree = reconstruct(&ev).expect("every parent valid, one trace"); + assert_eq!(tree.roots().len(), 1); + let root = tree.roots()[0]; + assert_eq!(tree.get(root).unwrap().kind, EventKind::SwarmLaunched); + assert_eq!(tree.get(root).unwrap().ids.swarm_id, Some(swarm_id)); + assert_eq!(tree.children(root).len(), 6); + let record = spine.swarm_manager.get_swarm(swarm_id).unwrap(); + assert_eq!(record.trace_root_event, Some(root)); + assert_eq!(spine.swarm_manager.trace_id(swarm_id), Some(ev[0].trace_id)); + // Each branch id appears in a fork and in a finish event. + for b in &record.branch_sequences { + let id = b.as_u64(); + for kind in [EventKind::BranchForked, EventKind::SequenceFinished] { + assert!(ev + .iter() + .any(|e| e.kind == kind && e.ids.sequence_id == Some(id))); + } + } + let a: Vec = tree.chronological().iter().map(|e| e.event_id).collect(); + let b: Vec = tree.chronological().iter().map(|e| e.event_id).collect(); + assert_eq!(a, b, "chronological order is stable"); + assert_eq!(a.len(), ev.len()); + let keys: Vec<(u64, u64)> = tree + .chronological() + .iter() + .map(|e| (e.at_unix_ms, e.event_id)) + .collect(); + assert!(keys.windows(2).all(|w| w[0] <= w[1])); +} + +#[tokio::test] +async fn cancelled_swarm_emits_swarm_cancelled() { + let (mut spine, mut backend) = build(3); + let sink = Arc::new(MemorySink::new()); + spine.swarm_manager.set_trace_sink(sink.clone()); + let swarm_id = spine + .launch_swarm(swarm_config(3, 16), &PROMPT) + .expect("launch"); + spine.step(&mut backend).await.expect("prefill step"); + spine.step(&mut backend).await.expect("first decode step"); + + let resp = spine.handle_control_command(ControlEnvelope { + protocol_version: 1, + request_id: 1, + operation_id: 0x398, + operator_session: 1, + command: ControlCommand::CancelSwarm(swarm_id), + }); + assert!( + matches!(resp, ControlResponse::SwarmCancelled { .. }), + "{resp:?}" + ); + + let ev = sink.drain(); + let cancelled: Vec<&TraceEvent> = ev + .iter() + .filter(|e| e.kind == EventKind::SwarmCancelled) + .collect(); + assert_eq!(cancelled.len(), 1); + assert_eq!(cancelled[0].status, EventStatus::Cancelled); + assert_eq!(cancelled[0].ids.swarm_id, Some(swarm_id)); + assert!(reconstruct(&ev).is_ok()); +} + +#[tokio::test] +async fn scheduler_tap_emits_admitted_for_registered_sequences_only() { + let (mut spine, mut backend) = build(3); + let sink = Arc::new(MemorySink::new()); + spine.swarm_manager.set_trace_sink(sink.clone()); + let dynsink: Arc = sink.clone(); + let observer = Arc::new(TraceDecisionObserver::new(dynsink)); + spine + .scheduler + .set_decision_observer(Some(observer.clone())); + + let swarm_id = spine + .launch_swarm(swarm_config(3, 3), &PROMPT) + .expect("launch"); + let trace = spine.swarm_manager.trace_id(swarm_id).unwrap(); + let record = spine.swarm_manager.get_swarm(swarm_id).unwrap().clone(); + let root_event = record.trace_root_event.unwrap(); + // Register only the first branch. + let watched = record.branch_sequences[0].as_u64(); + observer.register(watched, trace, root_event); + run_to_completion(&mut spine, &mut backend).await; + + let ev = sink.drain(); + let admitted: Vec<&TraceEvent> = ev + .iter() + .filter(|e| e.kind == EventKind::SequenceAdmitted) + .collect(); + assert!( + !admitted.is_empty(), + "the registered branch is admitted at least once" + ); + assert!(admitted.iter().all(|e| e.ids.sequence_id == Some(watched))); + assert!(admitted + .iter() + .all(|e| e.parent_event_id == Some(root_event))); + assert!(admitted.iter().all(|e| e.ids.step_id.is_some())); + assert!(reconstruct(&ev).is_ok()); +} diff --git a/crates/aien-runtime/tests/trace_overhead_benchmark.rs b/crates/aien-runtime/tests/trace_overhead_benchmark.rs new file mode 100644 index 00000000..0946b06b --- /dev/null +++ b/crates/aien-runtime/tests/trace_overhead_benchmark.rs @@ -0,0 +1,135 @@ +//! Overhead of the swarm trace events (#398). Run by hand: +//! `cargo test -p aien-runtime --release --test trace_overhead_benchmark -- --ignored --nocapture` +//! Prints one line per run; asserts nothing about timing. + +use std::path::PathBuf; +use std::sync::{Arc, OnceLock}; +use std::time::{SystemTime, UNIX_EPOCH}; + +use aien_inference_abi::{ + ModelConfig, NativeTransformerBackend, ReferenceCpuBackend, TransformerWeights, +}; +use aien_runtime::shared_kv::{build_shared_kv_runtime, SharedKvSizing}; +use aien_runtime::spine::AienRuntimeSpine; +use aien_runtime::swarm::SwarmConfig; +use aien_scheduler::SchedulerConfig; + +const PROMPT: [u32; 6] = [5, 17, 42, 3, 88, 61]; + +fn model_config() -> ModelConfig { + ModelConfig { + model_id: "trace-reference".to_string(), + max_sequence_length: 256, + block_size: 4, + num_layers: 3, + num_heads: 4, + head_dim: 8, + num_kv_heads: 2, + hidden_dim: 32, + intermediate_dim: 64, + vocab_size: 97, + rms_norm_eps: 1e-5, + rope_theta: 10000.0, + rope_scaling: None, + tie_word_embeddings: false, + eos_token_ids: Vec::new(), + qk_norm: false, + } +} + +fn scheduler_config() -> SchedulerConfig { + SchedulerConfig { + max_batch_size: 32, + max_batch_tokens: 2048, + max_prefill_tokens: 1024, + prefill_chunk_size: 128, + chunk_prefill: true, + watermark_blocks: 2, + } +} + +fn swarm_config(branches: usize, max_tokens: usize) -> SwarmConfig { + SwarmConfig { + model_handle: 1, + branch_count: branches, + max_active_sequences: branches, + max_tokens_per_branch: max_tokens, + root_world_id: 0, + priority: 1, + } +} + +/// One fresh controller state directory per test process. +fn fresh_state_dir() -> &'static PathBuf { + static DIR: OnceLock = OnceLock::new(); + DIR.get_or_init(|| { + let nanos = SystemTime::now() + .duration_since(UNIX_EPOCH) + .expect("clock after epoch") + .as_nanos(); + let dir = + std::env::temp_dir().join(format!("aien-trace-test-{}-{}", std::process::id(), nanos)); + std::fs::create_dir_all(&dir).expect("create fresh state dir"); + std::env::set_var("AIEN_RUNTIME_STATE_DIR", &dir); + dir + }) +} + +fn build(branches: usize) -> (AienRuntimeSpine, NativeTransformerBackend) { + fresh_state_dir(); + let weights = TransformerWeights::reference_test_weights(&model_config()); + build_shared_kv_runtime( + weights, + Arc::new(ReferenceCpuBackend::new()), + scheduler_config(), + SharedKvSizing { + arena_capacity: branches + 16, + total_blocks: (branches + 16) * 4, + }, + ) + .expect("build shared KV runtime") +} + +async fn run_to_completion(spine: &mut AienRuntimeSpine, backend: &mut NativeTransformerBackend) { + let mut steps = 0; + while (spine.scheduler.running_count() > 0 || spine.scheduler.waiting_count() > 0) + && steps < 500 + { + steps += 1; + spine.step(backend).await.expect("spine step"); + } +} + +use aien_trace::{MemorySink, NullSink, TraceSink}; + +const BRANCHES: usize = 64; + +async fn run(kind: &str, sink: Arc) { + let (mut spine, mut backend) = build(BRANCHES); + spine.swarm_manager.set_trace_sink(sink); + let t = std::time::Instant::now(); + spine + .launch_swarm(swarm_config(BRANCHES, 3), &PROMPT) + .expect("launch"); + run_to_completion(&mut spine, &mut backend).await; + println!( + "TRACE_OVERHEAD kind={kind} branches={BRANCHES} elapsed_ms={:.3}", + t.elapsed().as_secs_f64() * 1000.0 + ); + assert_eq!( + spine.scheduler.metrics().finished_requests as usize, + BRANCHES + ); +} + +#[tokio::test] +#[ignore] +async fn trace_overhead_null_sink() { + run("null", Arc::new(NullSink)).await; +} + +#[tokio::test] +#[ignore] +async fn trace_overhead_memory_sink() { + run("memory", Arc::new(MemorySink::new())).await; +} 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..f9a5b7e4 --- /dev/null +++ b/crates/aien-trace/src/lib.rs @@ -0,0 +1,1255 @@ +//! 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()) +} + +/// Wall clock in unix milliseconds (0 if the clock is before the epoch). +pub fn now_unix_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 { + /// False for sinks that discard everything, so callers can skip building events. + fn enabled(&self) -> bool { + true + } + 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 enabled(&self) -> bool { + false + } + 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, +} + +/// Refuses an export path that is a symbolic link, so nothing is written +/// through a link planted at the configured path. An absent path is fine (the +/// file is created). Metadata errors other than "absent" are returned. +fn refuse_symlink(path: &Path) -> std::io::Result<()> { + match std::fs::symlink_metadata(path) { + Ok(m) if m.file_type().is_symlink() => Err(std::io::Error::new( + std::io::ErrorKind::InvalidInput, + "trace export path is a symbolic link", + )), + Ok(_) => Ok(()), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()), + Err(e) => Err(e), + } +} + +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 path must not be a + /// symbolic link (a link is refused and the batch counted as dropped); the + /// file is created with mode 0o600 on unix and set back to 0o600 on every + /// flush. 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_unix_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 = refuse_symlink(&self.path) + .and_then(|()| opts.open(&self.path)) + .and_then(|mut f| { + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + f.set_permissions(std::fs::Permissions::from_mode(0o600))?; + } + 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 { + if !self.sink.enabled() { + return 0; + } + 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_unix_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_unix_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); + } + + #[cfg(unix)] + #[test] + fn symlink_path_is_refused_and_mode_is_reset_on_every_flush() { + use std::os::unix::fs::PermissionsExt; + // A link planted at the export path: nothing is written through it, + // the batch is counted as dropped, the target stays empty. + let target = tmp("symlink-target"); + std::fs::write(&target, b"").unwrap(); + let link = tmp("symlink"); + std::os::unix::fs::symlink(&target, &link).unwrap(); + let sink = BoundedJsonlSink::new(&link); + let t = TraceId::derive(1, 2, 3); + sink.emit(TraceEvent { + trace_id: t, + event_id: sink.next_event_id(), + parent_event_id: None, + at_unix_ms: 1, + kind: EventKind::SwarmLaunched, + status: EventStatus::Ok, + effect_certainty: None, + ids: CorrelationIds::default(), + refs: EvidenceRefs::default(), + note: None, + }); + assert!(sink.flush().is_err()); + assert_eq!(std::fs::read(&target).unwrap().len(), 0); + assert_eq!(sink.dropped_total(), 1); + let _ = std::fs::remove_file(&link); + let _ = std::fs::remove_file(&target); + + // A pre-existing file with a wide mode is narrowed to 0o600 on flush. + let path = tmp("mode"); + std::fs::write(&path, b"").unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap(); + let sink = BoundedJsonlSink::new(&path); + sink.emit(TraceEvent { + trace_id: t, + event_id: sink.next_event_id(), + parent_event_id: None, + at_unix_ms: 1, + kind: EventKind::SwarmLaunched, + status: EventStatus::Ok, + effect_certainty: None, + ids: CorrelationIds::default(), + refs: EvidenceRefs::default(), + note: None, + }); + sink.flush().unwrap(); + assert_eq!( + std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, + 0o600 + ); + assert_eq!(std::fs::read_to_string(&path).unwrap().lines().count(), 1); + 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("\"