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
aien-sovereign-core-mv / crates / aien-mcp / tests / two_phase.rs
| 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 | //! Two-phase approval spend (issue #206), through the public API only: reserve at mint, commit in |
| 17 | //! `execute_effect`, release when the minted effect is dropped or cancelled un-executed. |
| 18 | use std::sync::atomic::{AtomicUsize, Ordering}; |
| 19 | use std::sync::{Arc, Barrier, Mutex}; |
| 20 | |
| 21 | use aien_capability::{ |
| 22 | Digest32, EffectId, JNodeId, ProviderId, ToolDescriptor, ToolEffects, WorldId, |
| 23 | }; |
| 24 | use aien_mcp::memory::MemoryWire; |
| 25 | use aien_mcp::{ |
| 26 | ApprovalDesk, ApprovalError, ApprovalGrant, AuthorityOutcome, CallOutcome, |
| 27 | EffectClassAuthority, EffectIntent, EffectLane, EffectScope, Error, GrantStatus, McpBroker, |
| 28 | SpeculativeLane, |
| 29 | }; |
| 30 | use serde_json::json; |
| 31 | |
| 32 | struct H { |
| 33 | lane: EffectLane, |
| 34 | desk: ApprovalDesk, |
| 35 | calls: Arc<AtomicUsize>, |
| 36 | intent: EffectIntent, |
| 37 | broker: McpBroker, |
| 38 | provider: ProviderId, |
| 39 | } |
| 40 | |
| 41 | fn scope(label: &str) -> EffectScope { |
| 42 | EffectScope { |
| 43 | world_id: WorldId(1), |
| 44 | winning_jnode: JNodeId(1), |
| 45 | idempotency_key: EffectId::from_label(label), |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | async fn harness() -> H { |
| 50 | let calls = Arc::new(AtomicUsize::new(0)); |
| 51 | let c = calls.clone(); |
| 52 | let tool = ToolDescriptor::new("t", ToolEffects::WORLD_MUTATION, Digest32::of(b"t")); |
| 53 | let wire = MemoryWire::new(vec![tool], move |_, _| { |
| 54 | let n = c.fetch_add(1, Ordering::SeqCst); |
| 55 | CallOutcome::Finished(json!({"done": true, "n": n})) |
| 56 | }); |
| 57 | let broker = McpBroker::new(); |
| 58 | let provider = ProviderId::new("p"); |
| 59 | broker |
| 60 | .admit(provider.clone(), Arc::new(wire)) |
| 61 | .await |
| 62 | .unwrap(); |
| 63 | let live = SpeculativeLane::new(broker.clone()) |
| 64 | .discovery_snapshot(&provider) |
| 65 | .await |
| 66 | .unwrap() |
| 67 | .catalog_digest; |
| 68 | let intent = EffectIntent { |
| 69 | provider: provider.clone(), |
| 70 | tool_name: "t".into(), |
| 71 | arguments: json!({"a": 1}), |
| 72 | capability_digest: live, |
| 73 | }; |
| 74 | H { |
| 75 | lane: EffectLane::new(broker.clone()).with_clock(Arc::new(|| 1)), |
| 76 | desk: ApprovalDesk::new(broker.clone()), |
| 77 | broker, |
| 78 | calls, |
| 79 | intent, |
| 80 | provider, |
| 81 | } |
| 82 | } |
| 83 | |
| 84 | fn mint( |
| 85 | h: &H, |
| 86 | label: &str, |
| 87 | g: &ApprovalGrant, |
| 88 | now: u64, |
| 89 | ) -> Result<aien_mcp::AuthorizedEffect<EffectIntent>, AuthorityOutcome> { |
| 90 | h.lane.authorize_approved( |
| 91 | h.intent.clone(), |
| 92 | scope(label), |
| 93 | &EffectClassAuthority, |
| 94 | g, |
| 95 | now, |
| 96 | ) |
| 97 | } |
| 98 | |
| 99 | fn approval(e: AuthorityOutcome) -> ApprovalError { |
| 100 | match e { |
| 101 | AuthorityOutcome::Approval(a) => a, |
| 102 | other => panic!("expected Approval, got {other:?}"), |
| 103 | } |
| 104 | } |
| 105 | |
| 106 | #[tokio::test] |
| 107 | async fn refused_after_mint_keeps_grant_usable() { |
| 108 | let h = harness().await; |
| 109 | let g = h.desk.issue(&h.intent, scope("a"), 100); |
| 110 | // The host mints, then its own checks refuse and it drops the effect. |
| 111 | let effect = mint(&h, "a", &g, 1).unwrap(); |
| 112 | assert_eq!(h.desk.status(&g), Some(GrantStatus::Reserved)); |
| 113 | drop(effect); |
| 114 | assert_eq!(h.desk.status(&g), Some(GrantStatus::Available)); |
| 115 | // The same grant still buys exactly one run. |
| 116 | let r = h |
| 117 | .lane |
| 118 | .authorize_and_execute_approved(h.intent.clone(), scope("a"), &EffectClassAuthority, &g, 2) |
| 119 | .await |
| 120 | .unwrap(); |
| 121 | assert_eq!(r.output["done"], json!(true)); |
| 122 | assert_eq!(h.calls.load(Ordering::SeqCst), 1); |
| 123 | } |
| 124 | |
| 125 | #[tokio::test] |
| 126 | async fn dropped_effect_releases_and_records_why() { |
| 127 | let h = harness().await; |
| 128 | let g = h.desk.issue(&h.intent, scope("d"), 100); |
| 129 | assert_eq!(h.desk.release_reason(&g), None); |
| 130 | drop(mint(&h, "d", &g, 1).unwrap()); |
| 131 | assert_eq!(h.desk.status(&g), Some(GrantStatus::Available)); |
| 132 | assert_eq!( |
| 133 | h.desk.release_reason(&g).as_deref(), |
| 134 | Some("dropped before execute_effect") |
| 135 | ); |
| 136 | assert_eq!(h.calls.load(Ordering::SeqCst), 0); |
| 137 | assert!(mint(&h, "d", &g, 1).is_ok()); |
| 138 | } |
| 139 | |
| 140 | #[tokio::test] |
| 141 | async fn explicit_cancel_releases_with_a_reason_and_kills_clones() { |
| 142 | let h = harness().await; |
| 143 | let g = h.desk.issue(&h.intent, scope("c"), 100); |
| 144 | let effect = mint(&h, "c", &g, 1).unwrap(); |
| 145 | assert_eq!(effect.approval_id(), Some(g.approval_id())); |
| 146 | let clone = effect.clone(); |
| 147 | effect.cancel("digest check refused"); |
| 148 | assert_eq!(h.desk.status(&g), Some(GrantStatus::Available)); |
| 149 | assert_eq!( |
| 150 | h.desk.release_reason(&g).as_deref(), |
| 151 | Some("digest check refused") |
| 152 | ); |
| 153 | // A surviving clone must not run on a grant that was given back. |
| 154 | assert_eq!( |
| 155 | h.lane.execute_effect(clone).await.unwrap_err(), |
| 156 | Error::ApprovalNotReserved |
| 157 | ); |
| 158 | assert_eq!(h.calls.load(Ordering::SeqCst), 0); |
| 159 | // Dropping the dead clone did not disturb a later reservation. |
| 160 | let again = mint(&h, "c", &g, 1).unwrap(); |
| 161 | assert_eq!(h.desk.status(&g), Some(GrantStatus::Reserved)); |
| 162 | drop(again); |
| 163 | } |
| 164 | |
| 165 | #[tokio::test] |
| 166 | async fn stale_cancel_cannot_release_a_later_reservation() { |
| 167 | let h = harness().await; |
| 168 | let g = h.desk.issue(&h.intent, scope("s"), 100); |
| 169 | let first = mint(&h, "s", &g, 1).unwrap(); |
| 170 | let stale = first.clone(); |
| 171 | first.cancel("first"); |
| 172 | let second = mint(&h, "s", &g, 1).unwrap(); |
| 173 | stale.cancel("late"); |
| 174 | assert_eq!(h.desk.status(&g), Some(GrantStatus::Reserved)); |
| 175 | h.lane.execute_effect(second).await.unwrap(); |
| 176 | assert_eq!(h.calls.load(Ordering::SeqCst), 1); |
| 177 | } |
| 178 | |
| 179 | #[tokio::test] |
| 180 | async fn double_mint_while_reserved_is_refused() { |
| 181 | let h = harness().await; |
| 182 | let g = h.desk.issue(&h.intent, scope("m"), 100); |
| 183 | let held = mint(&h, "m", &g, 1).unwrap(); |
| 184 | assert_eq!( |
| 185 | approval(mint(&h, "m", &g, 1).unwrap_err()), |
| 186 | ApprovalError::Reserved |
| 187 | ); |
| 188 | // The desk cannot withdraw a grant an effect is holding. |
| 189 | assert!(!h.desk.revoke(&g)); |
| 190 | drop(held); |
| 191 | assert!(h.desk.revoke(&g)); |
| 192 | assert_eq!( |
| 193 | approval(mint(&h, "m", &g, 1).unwrap_err()), |
| 194 | ApprovalError::Revoked |
| 195 | ); |
| 196 | assert_eq!(h.desk.status(&g), Some(GrantStatus::Revoked)); |
| 197 | } |
| 198 | |
| 199 | #[tokio::test] |
| 200 | async fn execute_commits_once() { |
| 201 | let h = harness().await; |
| 202 | let g = h.desk.issue(&h.intent, scope("e"), 100); |
| 203 | let effect = mint(&h, "e", &g, 1).unwrap(); |
| 204 | h.lane.execute_effect(effect).await.unwrap(); |
| 205 | assert_eq!(h.desk.status(&g), Some(GrantStatus::Spent)); |
| 206 | assert_eq!(h.calls.load(Ordering::SeqCst), 1); |
| 207 | // Spent is final: no release by drop, and no second mint. |
| 208 | assert_eq!( |
| 209 | approval(mint(&h, "e", &g, 1).unwrap_err()), |
| 210 | ApprovalError::Consumed |
| 211 | ); |
| 212 | assert_eq!(h.desk.status(&g), Some(GrantStatus::Spent)); |
| 213 | assert_eq!(h.desk.release_reason(&g), None); |
| 214 | } |
| 215 | |
| 216 | #[tokio::test] |
| 217 | async fn replay_after_execute_returns_the_original_receipt() { |
| 218 | let h = harness().await; |
| 219 | let g = h.desk.issue(&h.intent, scope("r"), 100); |
| 220 | let first = h |
| 221 | .lane |
| 222 | .authorize_and_execute_approved(h.intent.clone(), scope("r"), &EffectClassAuthority, &g, 1) |
| 223 | .await |
| 224 | .unwrap(); |
| 225 | let again = h |
| 226 | .lane |
| 227 | .authorize_and_execute_approved( |
| 228 | h.intent.clone(), |
| 229 | scope("r"), |
| 230 | &EffectClassAuthority, |
| 231 | &g, |
| 232 | 10_000, |
| 233 | ) |
| 234 | .await |
| 235 | .unwrap(); |
| 236 | assert_eq!(first, again); |
| 237 | assert_eq!(h.calls.load(Ordering::SeqCst), 1); |
| 238 | assert_eq!(h.desk.status(&g), Some(GrantStatus::Spent)); |
| 239 | } |
| 240 | |
| 241 | #[tokio::test] |
| 242 | async fn expired_grant_released_then_remint_is_refused() { |
| 243 | let h = harness().await; |
| 244 | let g = h.desk.issue(&h.intent, scope("x"), 10); |
| 245 | drop(mint(&h, "x", &g, 1).unwrap()); |
| 246 | assert_eq!(h.desk.status(&g), Some(GrantStatus::Available)); |
| 247 | assert_eq!( |
| 248 | approval(mint(&h, "x", &g, 10).unwrap_err()), |
| 249 | ApprovalError::Expired |
| 250 | ); |
| 251 | assert_eq!(h.calls.load(Ordering::SeqCst), 0); |
| 252 | } |
| 253 | |
| 254 | #[tokio::test] |
| 255 | async fn refusal_inside_execute_effect_before_dispatch_releases() { |
| 256 | let h = harness().await; |
| 257 | let g = h.desk.issue(&h.intent, scope("z"), 100); |
| 258 | let effect = mint(&h, "z", &g, 1).unwrap(); |
| 259 | // The catalog moves between mint and execute: execute_effect refuses as stale. |
| 260 | let tool = ToolDescriptor::new("t", ToolEffects::WORLD_MUTATION, Digest32::of(b"t2")); |
| 261 | h.broker |
| 262 | .replace_catalog(&h.provider, vec![tool]) |
| 263 | .await |
| 264 | .unwrap(); |
| 265 | assert_eq!( |
| 266 | h.lane.execute_effect(effect).await.unwrap_err(), |
| 267 | Error::StaleCapability |
| 268 | ); |
| 269 | assert_eq!(h.calls.load(Ordering::SeqCst), 0); |
| 270 | assert_eq!(h.desk.status(&g), Some(GrantStatus::Available)); |
| 271 | } |
| 272 | |
| 273 | #[test] |
| 274 | fn concurrent_mint_race_has_one_winner() { |
| 275 | let rt = tokio::runtime::Builder::new_current_thread() |
| 276 | .build() |
| 277 | .unwrap(); |
| 278 | let h = rt.block_on(harness()); |
| 279 | let g = h.desk.issue(&h.intent, scope("race"), 100); |
| 280 | let barrier = Barrier::new(2); |
| 281 | let wins = AtomicUsize::new(0); |
| 282 | let reserved = AtomicUsize::new(0); |
| 283 | let held = Mutex::new(Vec::new()); |
| 284 | std::thread::scope(|s| { |
| 285 | for _ in 0..2 { |
| 286 | s.spawn(|| { |
| 287 | barrier.wait(); |
| 288 | match mint(&h, "race", &g, 1) { |
| 289 | Ok(e) => { |
| 290 | held.lock().unwrap().push(e); |
| 291 | wins.fetch_add(1, Ordering::SeqCst); |
| 292 | } |
| 293 | Err(AuthorityOutcome::Approval(ApprovalError::Reserved)) => { |
| 294 | reserved.fetch_add(1, Ordering::SeqCst); |
| 295 | } |
| 296 | Err(other) => panic!("unexpected {other:?}"), |
| 297 | } |
| 298 | }); |
| 299 | } |
| 300 | }); |
| 301 | assert_eq!(wins.load(Ordering::SeqCst), 1); |
| 302 | assert_eq!(reserved.load(Ordering::SeqCst), 1); |
| 303 | assert_eq!(h.desk.status(&g), Some(GrantStatus::Reserved)); |
| 304 | } |
| 305 | |
| 306 | #[tokio::test] |
| 307 | async fn grant_from_another_broker_has_no_status() { |
| 308 | let h = harness().await; |
| 309 | let other = harness().await; |
| 310 | let g = other.desk.issue(&other.intent, scope("o"), 100); |
| 311 | assert_eq!(h.desk.status(&g), None); |
| 312 | } |
| 313 | |
| 314 | #[tokio::test] |
| 315 | async fn held_effect_past_expiry_is_refused_at_commit_and_released() { |
| 316 | let h = harness().await; |
| 317 | let clock = Arc::new(std::sync::atomic::AtomicU64::new(1)); |
| 318 | let c = clock.clone(); |
| 319 | let lane = h |
| 320 | .lane |
| 321 | .with_clock(Arc::new(move || c.load(Ordering::SeqCst))); |
| 322 | let g = h.desk.issue(&h.intent, scope("exp"), 10); |
| 323 | let effect = lane |
| 324 | .authorize_approved(h.intent.clone(), scope("exp"), &EffectClassAuthority, &g, 1) |
| 325 | .unwrap(); |
| 326 | assert_eq!(h.desk.status(&g), Some(GrantStatus::Reserved)); |
| 327 | clock.store(10, Ordering::SeqCst); |
| 328 | assert_eq!( |
| 329 | lane.execute_effect(effect).await.unwrap_err(), |
| 330 | Error::ApprovalExpired |
| 331 | ); |
| 332 | assert_eq!(h.calls.load(Ordering::SeqCst), 0); |
| 333 | assert_eq!(h.desk.status(&g), Some(GrantStatus::Available)); |
| 334 | assert_eq!( |
| 335 | h.desk.release_reason(&g).as_deref(), |
| 336 | Some("expired before execute") |
| 337 | ); |
| 338 | assert_eq!( |
| 339 | approval(mint(&h, "exp", &g, 10).unwrap_err()), |
| 340 | ApprovalError::Expired |
| 341 | ); |
| 342 | } |
| 343 | |
| 344 | #[tokio::test] |
| 345 | async fn clock_before_expiry_still_commits() { |
| 346 | let h = harness().await; |
| 347 | let lane = h.lane.with_clock(Arc::new(|| 5)); |
| 348 | let g = h.desk.issue(&h.intent, scope("ok"), 10); |
| 349 | let effect = lane |
| 350 | .authorize_approved(h.intent.clone(), scope("ok"), &EffectClassAuthority, &g, 1) |
| 351 | .unwrap(); |
| 352 | lane.execute_effect(effect).await.unwrap(); |
| 353 | assert_eq!(h.desk.status(&g), Some(GrantStatus::Spent)); |
| 354 | } |
| 355 | |
| 356 | #[tokio::test] |
| 357 | async fn provider_panic_after_commit_leaves_the_grant_spent_and_never_reruns() { |
| 358 | let calls = Arc::new(AtomicUsize::new(0)); |
| 359 | let c = calls.clone(); |
| 360 | let tool = ToolDescriptor::new("t", ToolEffects::WORLD_MUTATION, Digest32::of(b"t")); |
| 361 | let wire = MemoryWire::new(vec![tool], move |_, _| { |
| 362 | c.fetch_add(1, Ordering::SeqCst); |
| 363 | panic!("provider blew up"); |
| 364 | }); |
| 365 | let broker = McpBroker::new(); |
| 366 | let provider = ProviderId::new("p"); |
| 367 | broker |
| 368 | .admit(provider.clone(), Arc::new(wire)) |
| 369 | .await |
| 370 | .unwrap(); |
| 371 | let live = SpeculativeLane::new(broker.clone()) |
| 372 | .discovery_snapshot(&provider) |
| 373 | .await |
| 374 | .unwrap() |
| 375 | .catalog_digest; |
| 376 | let intent = EffectIntent { |
| 377 | provider, |
| 378 | tool_name: "t".into(), |
| 379 | arguments: json!({"a": 1}), |
| 380 | capability_digest: live, |
| 381 | }; |
| 382 | let lane = EffectLane::new(broker.clone()).with_clock(Arc::new(|| 1)); |
| 383 | let desk = ApprovalDesk::new(broker); |
| 384 | let g = desk.issue(&intent, scope("pan"), 100); |
| 385 | let (l2, i2, g2) = (lane.clone(), intent.clone(), g.clone()); |
| 386 | let joined = std::thread::spawn(move || { |
| 387 | let rt = tokio::runtime::Builder::new_current_thread() |
| 388 | .build() |
| 389 | .unwrap(); |
| 390 | let _ = rt.block_on(l2.authorize_and_execute_approved( |
| 391 | i2, |
| 392 | scope("pan"), |
| 393 | &EffectClassAuthority, |
| 394 | &g2, |
| 395 | 1, |
| 396 | )); |
| 397 | }) |
| 398 | .join(); |
| 399 | assert!(joined.is_err(), "provider panic must propagate"); |
| 400 | assert_eq!(desk.status(&g), Some(GrantStatus::Spent)); |
| 401 | let again = lane |
| 402 | .authorize_and_execute_approved(intent, scope("pan"), &EffectClassAuthority, &g, 1) |
| 403 | .await |
| 404 | .unwrap_err(); |
| 405 | assert_eq!(again, AuthorityOutcome::Execution(Error::EffectInFlight)); |
| 406 | assert_eq!(calls.load(Ordering::SeqCst), 1); |
| 407 | } |
| 408 | |
| 409 | #[tokio::test] |
| 410 | async fn reserved_effect_on_a_lane_without_a_clock_fails_closed_and_releases() { |
| 411 | let h = harness().await; |
| 412 | let no_clock = EffectLane::new(h.broker.clone()); |
| 413 | let g = h.desk.issue(&h.intent, scope("nc"), 100); |
| 414 | let effect = no_clock |
| 415 | .authorize_approved(h.intent.clone(), scope("nc"), &EffectClassAuthority, &g, 1) |
| 416 | .unwrap(); |
| 417 | assert_eq!( |
| 418 | no_clock.execute_effect(effect).await.unwrap_err(), |
| 419 | Error::ApprovalClockMissing |
| 420 | ); |
| 421 | assert_eq!(h.calls.load(Ordering::SeqCst), 0); |
| 422 | assert_eq!(h.desk.status(&g), Some(GrantStatus::Available)); |
| 423 | assert_eq!( |
| 424 | h.desk.release_reason(&g).as_deref(), |
| 425 | Some("no clock: expiry cannot be checked") |
| 426 | ); |
| 427 | // The same grant runs once on a lane that has a clock. |
| 428 | h.lane |
| 429 | .authorize_and_execute_approved(h.intent.clone(), scope("nc"), &EffectClassAuthority, &g, 1) |
| 430 | .await |
| 431 | .unwrap(); |
| 432 | assert_eq!(h.calls.load(Ordering::SeqCst), 1); |
| 433 | } |
| 434 | |
| 435 | #[tokio::test] |
| 436 | async fn effect_without_a_reservation_runs_on_a_lane_without_a_clock() { |
| 437 | let h = harness().await; |
| 438 | let no_clock = EffectLane::new(h.broker.clone()); |
| 439 | // Allow verdict: no grant involved, so no clock is needed. |
| 440 | struct AllowAll; |
| 441 | impl aien_mcp::EffectAuthority for AllowAll { |
| 442 | fn authorize( |
| 443 | &self, |
| 444 | _: &EffectIntent, |
| 445 | _: &aien_mcp::AuthorityContext, |
| 446 | ) -> aien_mcp::AuthorityDecision { |
| 447 | aien_mcp::AuthorityDecision::Allow |
| 448 | } |
| 449 | } |
| 450 | let r = no_clock |
| 451 | .authorize_and_execute(h.intent.clone(), scope("na"), &AllowAll) |
| 452 | .await |
| 453 | .unwrap(); |
| 454 | assert_eq!(r.output["done"], json!(true)); |
| 455 | assert_eq!(h.calls.load(Ordering::SeqCst), 1); |
| 456 | } |