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 / binding.rs

474 lines · 16478 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//! L3-AUTH negative controls: what an approval binds, what the ledger binds, and what a faulty
17//! provider can and cannot cause. Public API only. Every assertion that matters counts provider
18//! executions (`calls`), not return values.
19use std::sync::atomic::{AtomicUsize, Ordering};
20use std::sync::Arc;
21
22use aien_capability::{
23 Digest32, EffectId, JNodeId, ProviderId, ToolDescriptor, ToolEffects, WorldId,
24};
25use aien_mcp::memory::MemoryWire;
26use aien_mcp::{
27 ApprovalDesk, ApprovalError, AuthorityOutcome, CallOutcome, EffectClassAuthority, EffectIntent,
28 EffectLane, EffectScope, Error, McpBroker, McpWire, SpeculativeLane,
29};
30use serde_json::{json, Value};
31
32fn scope(label: &str) -> EffectScope {
33 EffectScope {
34 world_id: WorldId(1),
35 winning_jnode: JNodeId(1),
36 idempotency_key: EffectId::from_label(label),
37 }
38}
39
40struct H {
41 broker: McpBroker,
42 lane: EffectLane,
43 desk: ApprovalDesk,
44 calls: Arc<AtomicUsize>,
45 provider: ProviderId,
46 digest: Digest32,
47}
48
49impl H {
50 fn intent(&self, tool: &str, arguments: Value) -> EffectIntent {
51 EffectIntent {
52 provider: self.provider.clone(),
53 tool_name: tool.into(),
54 arguments,
55 capability_digest: self.digest,
56 }
57 }
58}
59
60/// Provider with a write-class tool `w`, a second write-class tool `x`, and a local-ephemeral
61/// tool `e` (which `EffectClassAuthority` allows without approval). `wire` decides every call.
62async fn harness_with(wire: Arc<dyn McpWire>, calls: Arc<AtomicUsize>) -> H {
63 let broker = McpBroker::new();
64 let provider = ProviderId::new("p");
65 broker.admit(provider.clone(), wire).await.unwrap();
66 let digest = SpeculativeLane::new(broker.clone())
67 .discovery_snapshot(&provider)
68 .await
69 .unwrap()
70 .catalog_digest;
71 H {
72 lane: EffectLane::new(broker.clone()).with_clock(std::sync::Arc::new(|| 1)),
73 desk: ApprovalDesk::new(broker.clone()),
74 broker,
75 calls,
76 provider,
77 digest,
78 }
79}
80
81fn tools() -> Vec<ToolDescriptor> {
82 vec![
83 ToolDescriptor::new("w", ToolEffects::WORLD_MUTATION, Digest32::of(b"w")),
84 ToolDescriptor::new("x", ToolEffects::WORLD_MUTATION, Digest32::of(b"x")),
85 ToolDescriptor::new("e", ToolEffects::LOCAL_EPHEMERAL, Digest32::of(b"e")),
86 ]
87}
88
89async fn harness(outcome: CallOutcome) -> H {
90 let calls = Arc::new(AtomicUsize::new(0));
91 let c = calls.clone();
92 let wire = MemoryWire::new(tools(), move |_, _| {
93 c.fetch_add(1, Ordering::SeqCst);
94 outcome.clone()
95 });
96 harness_with(Arc::new(wire), calls).await
97}
98
99fn approval(e: AuthorityOutcome) -> ApprovalError {
100 match e {
101 AuthorityOutcome::Approval(a) => a,
102 other => panic!("expected Approval, got {other:?}"),
103 }
104}
105
106// ---- what a grant binds ----
107
108#[tokio::test]
109async fn grant_is_bound_to_the_winning_jnode() {
110 let h = harness(CallOutcome::Finished(json!({"ok": true}))).await;
111 let intent = h.intent("w", json!({"a": 1}));
112 let g = h.desk.issue(&intent, scope("j"), 100);
113 let mut other = scope("j");
114 other.winning_jnode = JNodeId(2);
115 let e = h
116 .lane
117 .authorize_approved(intent.clone(), other, &EffectClassAuthority, &g, 1)
118 .unwrap_err();
119 assert_eq!(approval(e), ApprovalError::Mismatch);
120 assert_eq!(h.calls.load(Ordering::SeqCst), 0);
121 // Not burned: the named effect still runs, once.
122 let r = h
123 .lane
124 .authorize_and_execute_approved(intent, scope("j"), &EffectClassAuthority, &g, 1)
125 .await;
126 assert!(r.is_ok());
127 assert_eq!(h.calls.load(Ordering::SeqCst), 1);
128}
129
130#[tokio::test]
131async fn grant_is_bound_to_the_tool() {
132 let h = harness(CallOutcome::Finished(json!({"ok": true}))).await;
133 let g = h
134 .desk
135 .issue(&h.intent("w", json!({"a": 1})), scope("t"), 100);
136 // Same arguments, same key, same catalog, other tool of the same effect class.
137 let e = h
138 .lane
139 .authorize_and_execute_approved(
140 h.intent("x", json!({"a": 1})),
141 scope("t"),
142 &EffectClassAuthority,
143 &g,
144 1,
145 )
146 .await
147 .unwrap_err();
148 assert_eq!(approval(e), ApprovalError::Mismatch);
149 assert_eq!(h.calls.load(Ordering::SeqCst), 0);
150}
151
152// ---- single use under concurrency ----
153
154#[tokio::test]
155async fn one_grant_spent_from_many_threads_mints_exactly_once() {
156 let h = harness(CallOutcome::Finished(json!({"ok": true}))).await;
157 let intent = h.intent("w", json!({"a": 1}));
158 let g = h.desk.issue(&intent, scope("race"), 100);
159 let minted = AtomicUsize::new(0);
160 let refused = AtomicUsize::new(0);
161 // Winners are kept alive: a dropped effect would release the grant for the next thread.
162 let held = std::sync::Mutex::new(Vec::new());
163 std::thread::scope(|s| {
164 for _ in 0..16 {
165 s.spawn(|| {
166 match h.lane.authorize_approved(
167 intent.clone(),
168 scope("race"),
169 &EffectClassAuthority,
170 &g,
171 1,
172 ) {
173 Ok(e) => {
174 held.lock().unwrap().push(e);
175 minted.fetch_add(1, Ordering::SeqCst)
176 }
177 Err(AuthorityOutcome::Approval(ApprovalError::Reserved)) => {
178 refused.fetch_add(1, Ordering::SeqCst)
179 }
180 Err(other) => panic!("unexpected {other:?}"),
181 };
182 });
183 }
184 });
185 assert_eq!(minted.load(Ordering::SeqCst), 1);
186 assert_eq!(refused.load(Ordering::SeqCst), 15);
187}
188
189#[test]
190fn one_grant_executed_from_many_threads_reaches_the_provider_once() {
191 let rt = tokio::runtime::Builder::new_current_thread()
192 .build()
193 .unwrap();
194 let h = rt.block_on(harness(CallOutcome::Finished(json!({"ok": true}))));
195 let intent = h.intent("w", json!({"a": 1}));
196 let g = h.desk.issue(&intent, scope("race2"), 100);
197 let receipts = std::sync::Mutex::new(Vec::new());
198 std::thread::scope(|s| {
199 for _ in 0..16 {
200 s.spawn(|| {
201 let rt = tokio::runtime::Builder::new_current_thread()
202 .build()
203 .unwrap();
204 let r = rt.block_on(h.lane.authorize_and_execute_approved(
205 intent.clone(),
206 scope("race2"),
207 &EffectClassAuthority,
208 &g,
209 1,
210 ));
211 if let Ok(rc) = r {
212 receipts.lock().unwrap().push(rc);
213 }
214 });
215 }
216 });
217 assert_eq!(h.calls.load(Ordering::SeqCst), 1, "provider reached once");
218 // Every success is the one effect's receipt.
219 let receipts = receipts.into_inner().unwrap();
220 assert!(!receipts.is_empty());
221 assert!(receipts.windows(2).all(|w| w[0] == w[1]));
222}
223
224// ---- provider faults are never success ----
225
226struct Faulty {
227 calls: Arc<AtomicUsize>,
228}
229
230#[async_trait::async_trait]
231impl McpWire for Faulty {
232 async fn list_tools(&self) -> Result<Vec<ToolDescriptor>, Error> {
233 Ok(tools())
234 }
235 async fn call_tool(&self, _: &str, _: &Value) -> Result<CallOutcome, Error> {
236 self.calls.fetch_add(1, Ordering::SeqCst);
237 Err(Error::Transport("connection reset".into()))
238 }
239}
240
241#[tokio::test]
242async fn transport_error_is_uncertain_never_success_and_never_retried() {
243 let calls = Arc::new(AtomicUsize::new(0));
244 let h = harness_with(
245 Arc::new(Faulty {
246 calls: calls.clone(),
247 }),
248 calls.clone(),
249 )
250 .await;
251 let intent = h.intent("w", json!({"a": 1}));
252 let g = h.desk.issue(&intent, scope("f"), 100);
253 let first = h
254 .lane
255 .authorize_and_execute_approved(intent.clone(), scope("f"), &EffectClassAuthority, &g, 1)
256 .await
257 .unwrap_err();
258 assert_eq!(
259 first,
260 AuthorityOutcome::Execution(Error::ReconciliationRequired)
261 );
262 // The same effect again (same grant: replay path) and a fresh grant (same key): both are told
263 // to reconcile, and the provider is not touched a second time.
264 let again = h
265 .lane
266 .authorize_and_execute_approved(intent.clone(), scope("f"), &EffectClassAuthority, &g, 1)
267 .await
268 .unwrap_err();
269 assert_eq!(
270 again,
271 AuthorityOutcome::Execution(Error::ReconciliationRequired)
272 );
273 let g2 = h.desk.issue(&intent, scope("f"), 100);
274 let fresh = h
275 .lane
276 .authorize_and_execute_approved(intent, scope("f"), &EffectClassAuthority, &g2, 1)
277 .await
278 .unwrap_err();
279 assert_eq!(
280 fresh,
281 AuthorityOutcome::Execution(Error::ReconciliationRequired)
282 );
283 assert_eq!(calls.load(Ordering::SeqCst), 1);
284}
285
286#[tokio::test]
287async fn provider_rejection_is_an_error_and_the_spent_grant_stays_spent() {
288 let h = harness(CallOutcome::Rejected("no such directory".into())).await;
289 let intent = h.intent("w", json!({"a": 1}));
290 let g = h.desk.issue(&intent, scope("rj"), 100);
291 let e = h
292 .lane
293 .authorize_and_execute_approved(intent.clone(), scope("rj"), &EffectClassAuthority, &g, 1)
294 .await
295 .unwrap_err();
296 assert_eq!(
297 e,
298 AuthorityOutcome::Execution(Error::Rejected("no such directory".into()))
299 );
300 // One approval bought one attempt. The same grant cannot buy a second.
301 let e = h
302 .lane
303 .authorize_and_execute_approved(intent, scope("rj"), &EffectClassAuthority, &g, 1)
304 .await
305 .unwrap_err();
306 assert_eq!(approval(e), ApprovalError::Consumed);
307 assert_eq!(h.calls.load(Ordering::SeqCst), 1);
308}
309
310// ---- the ledger binds the effect, not just the key ----
311
312#[tokio::test]
313async fn a_reused_idempotency_key_never_reports_success_for_a_different_effect() {
314 let h = harness(CallOutcome::Finished(json!({"done": true}))).await;
315 let a = EffectClassAuthority;
316 // `e` is allowed without approval, so this is the plain `authorize_and_execute` path.
317 let first = h
318 .lane
319 .authorize_and_execute(h.intent("e", json!({"n": 1})), scope("k"), &a)
320 .await
321 .unwrap();
322 assert_eq!(first.tool_name, "e");
323 assert_eq!(h.calls.load(Ordering::SeqCst), 1);
324 // A different request under the same key did not run, so it must not come back as a receipt.
325 let other = h
326 .lane
327 .authorize_and_execute(h.intent("e", json!({"n": 2})), scope("k"), &a)
328 .await;
329 assert!(
330 matches!(
331 other,
332 Err(AuthorityOutcome::Execution(Error::IdempotencyConflict))
333 ),
334 "{other:?}"
335 );
336 assert_eq!(h.calls.load(Ordering::SeqCst), 1, "second effect never ran");
337 // The identical request is still an ordinary replay.
338 let same = h
339 .lane
340 .authorize_and_execute(h.intent("e", json!({"n": 1})), scope("k"), &a)
341 .await
342 .unwrap();
343 assert_eq!(same, first);
344 assert_eq!(h.calls.load(Ordering::SeqCst), 1);
345 let _ = &h.broker;
346}
347
348#[tokio::test]
349async fn a_key_names_one_effect_in_one_world() {
350 let h = harness(CallOutcome::Finished(json!({"done": true}))).await;
351 let a = EffectClassAuthority;
352 let intent = h.intent("e", json!({"n": 1}));
353 h.lane
354 .authorize_and_execute(intent.clone(), scope("w1"), &a)
355 .await
356 .unwrap();
357 // Same effect and key, other world: not a replay, and no receipt that names world 1.
358 let mut other = scope("w1");
359 other.world_id = WorldId(2);
360 let r = h.lane.authorize_and_execute(intent, other, &a).await;
361 assert!(
362 matches!(
363 r,
364 Err(AuthorityOutcome::Execution(Error::IdempotencyConflict))
365 ),
366 "{r:?}"
367 );
368 assert_eq!(h.calls.load(Ordering::SeqCst), 1);
369}
370
371#[tokio::test]
372async fn an_approved_effect_cannot_borrow_the_receipt_of_an_earlier_effect_on_its_key() {
373 let h = harness(CallOutcome::Finished(json!({"done": true}))).await;
374 let a = EffectClassAuthority;
375 // Key `shared` is first used by an allowed effect.
376 h.lane
377 .authorize_and_execute(h.intent("e", json!({"n": 1})), scope("shared"), &a)
378 .await
379 .unwrap();
380 // A different, approval-class effect is then approved under the same key.
381 let write = h.intent("w", json!({"path": "x"}));
382 let g = h.desk.issue(&write, scope("shared"), 100);
383 let r = h
384 .lane
385 .authorize_and_execute_approved(write.clone(), scope("shared"), &a, &g, 1)
386 .await;
387 assert!(
388 matches!(
389 r,
390 Err(AuthorityOutcome::Execution(Error::IdempotencyConflict))
391 ),
392 "{r:?}"
393 );
394 assert_eq!(h.calls.load(Ordering::SeqCst), 1, "the write never ran");
395 // The grant was spent at mint and the conflict does not hand out a receipt on replay either.
396 let again = h
397 .lane
398 .authorize_and_execute_approved(write, scope("shared"), &a, &g, 1)
399 .await;
400 assert!(
401 matches!(
402 again,
403 Err(AuthorityOutcome::Execution(Error::IdempotencyConflict))
404 ),
405 "{again:?}"
406 );
407 assert_eq!(h.calls.load(Ordering::SeqCst), 1);
408}
409
410// ---- cancellation: a withdrawn grant is dead ----
411
412#[tokio::test]
413async fn a_revoked_grant_cannot_be_spent_and_runs_nothing() {
414 let h = harness(CallOutcome::Finished(json!({"ok": true}))).await;
415 let intent = h.intent("w", json!({"a": 1}));
416 let g = h.desk.issue(&intent, scope("rv"), 100);
417 assert!(h.desk.revoke(&g));
418 assert!(h.desk.revoke(&g), "revoking twice is still revoked");
419 let e = h
420 .lane
421 .authorize_approved(intent.clone(), scope("rv"), &EffectClassAuthority, &g, 1)
422 .unwrap_err();
423 assert_eq!(approval(e), ApprovalError::Revoked);
424 let e = h
425 .lane
426 .authorize_and_execute_approved(intent, scope("rv"), &EffectClassAuthority, &g, 1)
427 .await
428 .unwrap_err();
429 assert_eq!(approval(e), ApprovalError::Revoked);
430 assert_eq!(h.calls.load(Ordering::SeqCst), 0);
431}
432
433#[tokio::test]
434async fn a_spent_or_foreign_grant_cannot_be_revoked() {
435 let h = harness(CallOutcome::Finished(json!({"ok": true}))).await;
436 let intent = h.intent("w", json!({"a": 1}));
437 let g = h.desk.issue(&intent, scope("sp"), 100);
438 let r = h
439 .lane
440 .authorize_and_execute_approved(intent.clone(), scope("sp"), &EffectClassAuthority, &g, 1)
441 .await
442 .unwrap();
443 // Too late: the effect ran. Revoke says so and the replay still returns the one receipt.
444 assert!(!h.desk.revoke(&g));
445 let again = h
446 .lane
447 .authorize_and_execute_approved(intent, scope("sp"), &EffectClassAuthority, &g, 1)
448 .await
449 .unwrap();
450 assert_eq!(r, again);
451 assert_eq!(h.calls.load(Ordering::SeqCst), 1);
452 // A grant from another desk is not this desk's to revoke.
453 let other = harness(CallOutcome::Finished(json!({}))).await;
454 let foreign = other
455 .desk
456 .issue(&other.intent("w", json!({})), scope("f"), 100);
457 assert!(!h.desk.revoke(&foreign));
458 assert!(other.desk.revoke(&foreign));
459}
460
461#[tokio::test]
462async fn revoking_one_grant_leaves_another_for_the_same_effect_usable() {
463 let h = harness(CallOutcome::Finished(json!({"ok": true}))).await;
464 let intent = h.intent("w", json!({"a": 1}));
465 let dead = h.desk.issue(&intent, scope("two"), 100);
466 let live = h.desk.issue(&intent, scope("two"), 100);
467 assert!(h.desk.revoke(&dead));
468 let r = h
469 .lane
470 .authorize_and_execute_approved(intent, scope("two"), &EffectClassAuthority, &live, 1)
471 .await;
472 assert!(r.is_ok());
473 assert_eq!(h.calls.load(Ordering::SeqCst), 1);
474}