interplane.Get Omega
Read in your language

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

branch main Branches Tags History

aien-sovereign-core-mv / crates / aien-mcp / tests / trace.rs

366 lines · 11650 bytes Raw Blame History
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! Correlation trace events from the effect lane (#398), through the public API.
17//! Events are observational: these tests also check that nothing sensitive is in them.
18use std::sync::atomic::{AtomicUsize, Ordering};
19use std::sync::Arc;
20
21use aien_capability::{
22 Digest32, EffectId, JNodeId, ProviderId, ToolDescriptor, ToolEffects, WorldId,
23};
24use aien_mcp::memory::MemoryWire;
25use aien_mcp::{
26 receipt_digest, ApprovalDesk, AuthorityContext, AuthorityDecision, CallOutcome,
27 EffectAuthority, EffectIntent, EffectLane, EffectReceipt, EffectScope, McpBroker,
28 SpeculativeLane,
29};
30use aien_trace::{
31 EffectCertainty, EventKind, EventStatus, MemorySink, TraceEvent, TraceId, TraceSink,
32};
33use serde_json::{json, Value};
34
35const SECRET_ARG: &str = "SECRET-ARGUMENT-VALUE-1";
36const SECRET_OUT: &str = "SECRET-OUTPUT-VALUE-2";
37
38struct Fixed(AuthorityDecision);
39impl EffectAuthority for Fixed {
40 fn authorize(&self, _: &EffectIntent, _: &AuthorityContext) -> AuthorityDecision {
41 self.0.clone()
42 }
43}
44
45struct H {
46 broker: McpBroker,
47 lane: EffectLane,
48 desk: ApprovalDesk,
49 sink: Arc<MemorySink>,
50 calls: Arc<AtomicUsize>,
51 intent: EffectIntent,
52}
53
54fn scope(label: &str) -> EffectScope {
55 EffectScope {
56 world_id: WorldId(7),
57 winning_jnode: JNodeId(1),
58 idempotency_key: EffectId::from_label(label),
59 }
60}
61
62async fn harness(outcome: CallOutcome) -> H {
63 let calls = Arc::new(AtomicUsize::new(0));
64 let c = calls.clone();
65 let tool = ToolDescriptor::new("send", ToolEffects::WORLD_MUTATION, Digest32::of(b"send"));
66 let wire = MemoryWire::new(vec![tool], move |_, _| {
67 c.fetch_add(1, Ordering::SeqCst);
68 outcome.clone()
69 });
70 let broker = McpBroker::new();
71 let provider = ProviderId::new("mail");
72 broker
73 .admit(provider.clone(), Arc::new(wire))
74 .await
75 .unwrap();
76 let live = SpeculativeLane::new(broker.clone())
77 .discovery_snapshot(&provider)
78 .await
79 .unwrap()
80 .catalog_digest;
81 let sink = Arc::new(MemorySink::new());
82 let dynsink: Arc<dyn TraceSink> = sink.clone();
83 let lane = EffectLane::new(broker.clone())
84 .with_clock(Arc::new(|| 1))
85 .with_trace(dynsink, TraceId::derive(1, 2, 3), Some(41));
86 H {
87 lane,
88 desk: ApprovalDesk::new(broker.clone()),
89 broker,
90 sink,
91 calls,
92 intent: EffectIntent {
93 provider,
94 tool_name: "send".into(),
95 arguments: json!({"body": SECRET_ARG}),
96 capability_digest: live,
97 },
98 }
99}
100
101fn finished() -> CallOutcome {
102 CallOutcome::Finished(json!({"result": SECRET_OUT}))
103}
104
105fn is_hex64(s: &str) -> bool {
106 s.len() == 64
107 && s.bytes()
108 .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
109}
110
111#[tokio::test]
112async fn allow_then_finished_gives_ok_events_with_receipt_digest() {
113 let h = harness(finished()).await;
114 let r = h
115 .lane
116 .authorize_and_execute(
117 h.intent.clone(),
118 scope("a"),
119 &Fixed(AuthorityDecision::Allow),
120 )
121 .await
122 .unwrap();
123 let ev = h.sink.drain();
124 assert_eq!(ev.len(), 2);
125 assert_eq!(ev[0].kind, EventKind::AuthorityDecided);
126 assert_eq!(ev[0].status, EventStatus::Ok);
127 assert_eq!(ev[0].parent_event_id, Some(41));
128 assert_eq!(ev[0].ids.world_id, Some(7));
129 assert_eq!(
130 ev[0].ids.tool_request_id.as_ref().unwrap().as_str(),
131 "mail:send"
132 );
133 assert!(is_hex64(
134 ev[0].refs.intent_digest.as_ref().unwrap().as_str()
135 ));
136 assert_eq!(ev[1].kind, EventKind::EffectExecuted);
137 assert_eq!(ev[1].status, EventStatus::Ok);
138 assert_eq!(
139 ev[1].effect_certainty,
140 Some(EffectCertainty::EffectOccurred)
141 );
142 let d = ev[1].refs.effect_receipt_digest.as_ref().unwrap().as_str();
143 assert!(is_hex64(d));
144 let want: String = receipt_digest(&r)
145 .iter()
146 .map(|b| format!("{b:02x}"))
147 .collect();
148 assert_eq!(d, want);
149}
150
151#[tokio::test]
152async fn deny_contain_and_stale_are_rejected_and_nothing_runs() {
153 let h = harness(finished()).await;
154 let _ = h.lane.authorize(
155 h.intent.clone(),
156 scope("d"),
157 &Fixed(AuthorityDecision::Deny("no".into())),
158 );
159 let _ = h.lane.authorize(
160 h.intent.clone(),
161 scope("c"),
162 &Fixed(AuthorityDecision::Contain("x".into())),
163 );
164 let mut stale = h.intent.clone();
165 stale.capability_digest = Digest32::of(b"old");
166 let _ = h
167 .lane
168 .authorize(stale, scope("s"), &Fixed(AuthorityDecision::Allow));
169 let ev = h.sink.drain();
170 assert_eq!(ev.len(), 3);
171 assert!(ev.iter().all(|e| e.status == EventStatus::Rejected));
172 assert_eq!(ev[0].note, None);
173 assert_eq!(ev[1].note.as_ref().unwrap().as_str(), "contained");
174 assert_eq!(ev[2].note.as_ref().unwrap().as_str(), "stale_intent");
175 assert_eq!(h.calls.load(Ordering::SeqCst), 0);
176}
177
178#[tokio::test]
179async fn require_approval_is_approval_pending_then_grant_id_appears() {
180 let h = harness(finished()).await;
181 let auth = Fixed(AuthorityDecision::RequireApproval("human".into()));
182 assert!(h
183 .lane
184 .authorize(h.intent.clone(), scope("p"), &auth)
185 .is_err());
186 let ev = h.sink.drain();
187 assert_eq!(ev[0].status, EventStatus::ApprovalPending);
188 assert_eq!(ev[0].ids.grant_id, None);
189
190 let grant = h.desk.issue(&h.intent, scope("p"), 100);
191 h.lane
192 .authorize_and_execute_approved(h.intent.clone(), scope("p"), &auth, &grant, 1)
193 .await
194 .unwrap();
195 let ev = h.sink.drain();
196 assert_eq!(ev[0].status, EventStatus::Ok);
197 assert!(is_hex64(ev[0].ids.grant_id.as_ref().unwrap().as_str()));
198 assert_eq!(ev[1].ids.grant_id, ev[0].ids.grant_id);
199
200 // Spending the grant for another effect is refused and named.
201 let other = scope("other");
202 assert!(h
203 .lane
204 .authorize_approved(h.intent.clone(), other, &auth, &grant, 1)
205 .is_err());
206 let ev = h.sink.drain();
207 assert_eq!(ev[0].status, EventStatus::Rejected);
208 assert!(ev[0].note.is_some());
209}
210
211#[tokio::test]
212async fn uncertain_provider_gives_uncertain_status_and_certainty() {
213 let h = harness(CallOutcome::Uncertain).await;
214 let r = h
215 .lane
216 .authorize_and_execute(
217 h.intent.clone(),
218 scope("u"),
219 &Fixed(AuthorityDecision::Allow),
220 )
221 .await;
222 assert!(r.is_err());
223 let ev = h.sink.drain();
224 assert_eq!(ev[1].kind, EventKind::EffectExecuted);
225 assert_eq!(ev[1].status, EventStatus::Uncertain);
226 assert_eq!(ev[1].effect_certainty, Some(EffectCertainty::Uncertain));
227 assert_eq!(ev[1].refs.effect_receipt_digest, None);
228}
229
230#[tokio::test]
231async fn rejected_provider_call_is_no_effect() {
232 let h = harness(CallOutcome::Rejected("bad".into())).await;
233 let _ = h
234 .lane
235 .authorize_and_execute(
236 h.intent.clone(),
237 scope("r"),
238 &Fixed(AuthorityDecision::Allow),
239 )
240 .await;
241 let ev = h.sink.drain();
242 assert_eq!(ev[1].status, EventStatus::Rejected);
243 assert_eq!(ev[1].effect_certainty, Some(EffectCertainty::NoEffect));
244}
245
246#[tokio::test]
247async fn second_execute_is_a_ledger_replay_without_a_second_call() {
248 let h = harness(finished()).await;
249 let allow = Fixed(AuthorityDecision::Allow);
250 let first = h
251 .lane
252 .authorize_and_execute(h.intent.clone(), scope("k"), &allow)
253 .await
254 .unwrap();
255 let second = h
256 .lane
257 .authorize_and_execute(h.intent.clone(), scope("k"), &allow)
258 .await
259 .unwrap();
260 assert_eq!(first, second);
261 assert_eq!(h.calls.load(Ordering::SeqCst), 1);
262 let ev = h.sink.drain();
263 let execs: Vec<&TraceEvent> = ev
264 .iter()
265 .filter(|e| e.kind == EventKind::EffectExecuted)
266 .collect();
267 assert_eq!(execs.len(), 2);
268 assert_eq!(execs[0].note, None);
269 assert_eq!(execs[1].note.as_ref().unwrap().as_str(), "ledger_replay");
270 assert_eq!(execs[1].status, EventStatus::Ok);
271 assert_eq!(
272 execs[0].refs.effect_receipt_digest,
273 execs[1].refs.effect_receipt_digest
274 );
275}
276
277#[tokio::test]
278async fn no_event_carries_arguments_outputs_or_forbidden_keys() {
279 let h = harness(finished()).await;
280 let allow = Fixed(AuthorityDecision::Allow);
281 for (i, a) in [
282 AuthorityDecision::Allow,
283 AuthorityDecision::Deny("no".into()),
284 AuthorityDecision::RequireApproval("h".into()),
285 ]
286 .into_iter()
287 .enumerate()
288 {
289 let _ = h
290 .lane
291 .authorize_and_execute(h.intent.clone(), scope(&format!("j{i}")), &Fixed(a))
292 .await;
293 }
294 let _ = allow;
295 let ev = h.sink.drain();
296 assert!(ev.len() >= 4);
297 let text = serde_json::to_string(&ev).unwrap();
298 assert!(!text.contains(SECRET_ARG));
299 assert!(!text.contains(SECRET_OUT));
300 fn keys(v: &Value, out: &mut Vec<String>) {
301 match v {
302 Value::Object(m) => {
303 for (k, v) in m {
304 out.push(k.clone());
305 keys(v, out);
306 }
307 }
308 Value::Array(a) => a.iter().for_each(|v| keys(v, out)),
309 _ => {}
310 }
311 }
312 let mut ks = Vec::new();
313 keys(&serde_json::to_value(&ev).unwrap(), &mut ks);
314 for k in ks {
315 for bad in ["arguments", "output", "prompt", "content"] {
316 assert!(!k.contains(bad), "key {k}");
317 }
318 }
319}
320
321#[tokio::test]
322async fn default_lane_emits_nothing_and_still_works() {
323 let h = harness(finished()).await;
324 let plain = EffectLane::new(h.broker.clone());
325 let r = plain
326 .authorize_and_execute(
327 h.intent.clone(),
328 scope("n"),
329 &Fixed(AuthorityDecision::Allow),
330 )
331 .await;
332 assert!(r.is_ok());
333 assert!(h.sink.drain().is_empty());
334}
335
336fn receipt() -> EffectReceipt {
337 EffectReceipt {
338 effect_id: EffectId::from_label("e"),
339 world_id: WorldId(1),
340 winning_jnode: JNodeId(2),
341 policy_digest: Digest32::of(b"p"),
342 provider: ProviderId::new("mail"),
343 tool_name: "send".into(),
344 capability_digest: Digest32::of(b"c"),
345 output: json!({"b": 1, "a": [1, 2]}),
346 }
347}
348
349#[test]
350fn receipt_digest_depends_on_output_and_tool_name_but_not_key_order() {
351 let base = receipt();
352 let d = receipt_digest(&base);
353 assert_eq!(d, receipt_digest(&base.clone()));
354 let mut o = base.clone();
355 o.output = json!({"b": 2, "a": [1, 2]});
356 assert_ne!(d, receipt_digest(&o));
357 let mut t = base.clone();
358 t.tool_name = "send2".into();
359 assert_ne!(d, receipt_digest(&t));
360 let mut w = base.clone();
361 w.world_id = WorldId(9);
362 assert_ne!(d, receipt_digest(&w));
363 let mut k = base.clone();
364 k.output = serde_json::from_str(r#"{"a":[1,2],"b":1}"#).unwrap();
365 assert_eq!(d, receipt_digest(&k));
366}