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/b145603d32516128 # 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#260 (code only) closed derived `b145603d32516128` #260 Imported from GitHub aien-dev/aien-sovereign-core-mv#260 (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 `4441cef108640e528d7bfd57dda2b663198f4f5c` · Head `06743a9f5a3a0c261da1252f043567b9e02aa172` ### Fetch it A git bundle of the pull request's head, 15155 bytes. ``` curl -fsSL https://interplane.io/drakestapleton/aien-sovereign-core-mv/patches/b145603d32516128.bundle -o b145603d32516128.bundle git fetch b145603d32516128.bundle refs/pull/260/head ``` Raw bundle · 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 260 06743a9f5a3a0c261da1252f043567b9e02aa172 ``` ``` {"kind":"github-import","owner":"aien-dev","repo":"aien-sovereign-core-mv","number":260,"url":"https://github.com/aien-dev/aien-sovereign-core-mv/pull/260","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:36:34Z","metadata":"unavailable","state_derived":true} ``` ### Changes ``` diff --git a/.crumb b/.crumb index cfb92961..10eb59cc 100644 --- a/.crumb +++ b/.crumb @@ -65,7 +65,7 @@ "children": [ { "digest": "f95432625ccdd27c1732e380e4ddb227483bdce00f37fb0effd5a5fddfea149b", - "last_commit": "296c4ac", + "last_commit": "a86b662", "name": "scripts", "purpose": "" }, @@ -77,14 +77,14 @@ } ], "children_root": "sha256:4ff1a56b7c8ac606ad5709f2ba1141f16055c34f5f242ac491233dca20d5153e", - "compiled_at": "2026-10-07T02:28:51Z", + "compiled_at": "2026-10-07T02:40:59Z", "compiler": "crumb-compile/1", - "digest": "sha256:c88267011968f9cb535404f2ef822ab1b45d9bb8ba4e6fe675f41fe556f5ef1a", + "digest": "sha256:cb6be9b645974d7cc42c4a3d07da2a3d97f07e7c3ca7340cafb7108f3ef569ab", "evidence_files": 155, "evidence_root": "sha256:ff6dddfecfcc02cea55f46acaccc7eaecd27557209e98c3d5616ec02bdde31db", - "files": 1085, - "generated_at_commit": "9119485e6358f70ba463997290e0f3be51aecb24", - "source_tree": "sha256:82e81635d7499a85183325c1968485dbdfb9a2c805869de9fdba13a8317e5239" + "files": 1086, + "generated_at_commit": "acc9bcaea011ead2a69f29abb81b08123d2637d2", + "source_tree": "sha256:b6d670077598943ca7f60c3ee69989d5b6984e967513944d457146aaf353ad2d" } }, "history": [], diff --git a/crates/aien-mcp/src/approval.rs b/crates/aien-mcp/src/approval.rs index 6faf72d9..16dab699 100644 --- a/crates/aien-mcp/src/approval.rs +++ b/crates/aien-mcp/src/approval.rs @@ -3,8 +3,19 @@ //! When an [`crate::EffectAuthority`] answers `RequireApproval`, a host approver (a human or an //! approval service, holding an [`ApprovalDesk`]) may issue one [`ApprovalGrant`]. The grant is //! bound to one effect identity: the intent digest (tool, arguments, catalog), the idempotency -//! key, the world and the winning J-node. [`crate::EffectLane::authorize_approved`] spends the -//! grant when it mints the `AuthorizedEffect`. A second mint with the same grant is refused. +//! key, the world and the winning J-node. Spending is two-phase: +//! +//! 1. [`crate::EffectLane::authorize_approved`] *reserves* the grant when it mints the +//! `AuthorizedEffect`. While reserved, no other mint can use it ([`ApprovalError::Reserved`]). +//! 2. [`crate::EffectLane::execute_effect`] *commits* the reservation just before the provider is +//! called: the grant is now spent for good ([`ApprovalError::Consumed`]). +//! 3. If the `AuthorizedEffect` is dropped without running, or cancelled with +//! [`crate::AuthorizedEffect::cancel`], the reservation is *released*: the grant is available +//! again, and expiry, revocation and the effect binding are re-checked at the next mint. +//! +//! Limit: the broker keeps grant state in memory only. A restart forgets every grant (each is +//! `Unknown` afterwards), so a reserved or spent grant can never run twice across a restart; the +//! approver must issue a new one. //! //! Replay of a finished request does not need a second approval: the existing effect ledger //! (keyed by the idempotency key) already returns the original receipt, and @@ -16,10 +27,12 @@ //! //! Expiry uses a host-supplied `now` and `expires_at` in the same unit. The crate reads no clock. +use std::sync::atomic::{AtomicBool, Ordering}; + use aien_capability::{Digest32, EffectId, JNodeId, WorldId}; use crate::authority::{intent_digest, EffectScope}; -use crate::broker::McpBroker; +use crate::broker::{Inner, McpBroker}; use crate::EffectIntent; /// Why an approval could not be spent. @@ -29,8 +42,11 @@ pub enum ApprovalError { Unknown, /// The grant is bound to a different effect than the one presented. Nothing is spent. Mismatch, - /// The grant was already spent by an earlier mint. + /// The grant was already spent: an effect minted from it reached `execute_effect`. Consumed, + /// The grant is reserved by a live `AuthorizedEffect` that has not run yet. It becomes + /// usable again if that effect is dropped or cancelled un-executed. + Reserved, /// `now` is at or past `expires_at`. Nothing is spent. Expired, /// The approver withdrew the grant with [`ApprovalDesk::revoke`] before it was spent. @@ -52,8 +68,9 @@ pub(crate) struct ApprovalRecord { pub(crate) world_id: WorldId, pub(crate) winning_jnode: JNodeId, pub(crate) expires_at: u64, - pub(crate) consumed: bool, + pub(crate) state: GrantState, pub(crate) revoked: bool, + pub(crate) release_reason: Option, } impl ApprovalRecord { @@ -106,8 +123,9 @@ impl ApprovalDesk { world_id: scope.world_id, winning_jnode: scope.winning_jnode, expires_at, - consumed: false, + state: GrantState::Available, revoked: false, + release_reason: None, }, ); ApprovalGrant { id } @@ -119,7 +137,7 @@ impl ApprovalDesk { pub fn revoke(&self, grant: &ApprovalGrant) -> bool { let mut inner = self.broker.lock(); match inner.approvals.get_mut(&grant.id()) { - Some(record) if !record.consumed => { + Some(record) if record.state == GrantState::Available => { record.revoked = true; true } @@ -127,3 +145,138 @@ impl ApprovalDesk { } } } + +/// Where a grant is in its life. Private: hosts see [`GrantStatus`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum GrantState { + Available, + /// Held by the `AuthorizedEffect` carrying this reservation token. + Reserved(u64), + Spent, +} + +/// What a host can ask about a grant with [`ApprovalDesk::status`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum GrantStatus { + /// Unspent and unreserved. It may still be expired; expiry is judged at mint against the + /// host's `now`. + Available, + /// A live `AuthorizedEffect` holds it and has not run. + Reserved, + /// An effect minted from it reached `execute_effect`. Final. + Spent, + /// The approver withdrew it before it was spent. + Revoked, +} + +/// The broker-side hold a minted effect carries. Shared by clones of the effect (`Arc`), so the +/// grant is released when the last clone is dropped un-executed, or when any clone cancels. +pub(crate) struct Reservation { + broker: McpBroker, + grant: Digest32, + token: u64, + finished: AtomicBool, +} + +impl std::fmt::Debug for Reservation { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Reservation") + .field("token", &self.token) + .finish_non_exhaustive() + } +} + +impl Reservation { + pub(crate) fn new(broker: McpBroker, grant: Digest32, token: u64) -> Self { + Self { + broker, + grant, + token, + finished: AtomicBool::new(false), + } + } + + pub(crate) fn grant_id(&self) -> Digest32 { + self.grant + } + + /// Make the spend final. The caller already holds the broker lock (`inner`). Fails if the + /// reservation was released (cancelled) first. + pub(crate) fn commit_locked( + &self, + inner: &mut Inner, + now: Option, + ) -> Result<(), crate::Error> { + match inner.approvals.get_mut(&self.grant) { + Some(r) if r.state == GrantState::Reserved(self.token) => { + // Fail closed: without a clock expiry cannot be checked, so an approved effect + // does not run. The grant is given back. + let Some(now) = now else { + r.state = GrantState::Available; + r.release_reason = Some("no clock: expiry cannot be checked".to_string()); + self.finished.store(true, Ordering::SeqCst); + return Err(crate::Error::ApprovalClockMissing); + }; + if now >= r.expires_at { + // Fail closed: give the grant back (a later mint refuses it as Expired). + r.state = GrantState::Available; + r.release_reason = Some("expired before execute".to_string()); + self.finished.store(true, Ordering::SeqCst); + return Err(crate::Error::ApprovalExpired); + } + r.state = GrantState::Spent; + self.finished.store(true, Ordering::SeqCst); + Ok(()) + } + _ => Err(crate::Error::ApprovalNotReserved), + } + } + + /// Give the grant back. Idempotent; a no-op after commit or an earlier release. + pub(crate) fn release(&self, reason: &str) { + if self.finished.swap(true, Ordering::SeqCst) { + return; + } + let mut inner = self.broker.lock(); + if let Some(r) = inner.approvals.get_mut(&self.grant) { + if r.state == GrantState::Reserved(self.token) { + r.state = GrantState::Available; + r.release_reason = Some(reason.to_string()); + } + } + } +} + +impl Drop for Reservation { + fn drop(&mut self) { + self.release("dropped before execute_effect"); + } +} + +impl ApprovalGrant { + /// Stable id of this grant (a digest). Hosts may use it as a correlation handle; it carries + /// no authority, since spending needs the broker's own record. + pub fn approval_id(&self) -> Digest32 { + self.id + } +} + +impl ApprovalDesk { + /// Current status of `grant`, or `None` if this desk never issued it. + pub fn status(&self, grant: &ApprovalGrant) -> Option { + let inner = self.broker.lock(); + let r = inner.approvals.get(&grant.id())?; + Some(match r.state { + GrantState::Spent => GrantStatus::Spent, + GrantState::Reserved(_) => GrantStatus::Reserved, + GrantState::Available if r.revoked => GrantStatus::Revoked, + GrantState::Available => GrantStatus::Available, + }) + } + + /// Why the grant was last released (`None` if it never was, or this desk did not issue it). + pub fn release_reason(&self, grant: &ApprovalGrant) -> Option { + let inner = self.broker.lock(); + inner.approvals.get(&grant.id())?.release_reason.clone() + } +} diff --git a/crates/aien-mcp/src/broker.rs b/crates/aien-mcp/src/broker.rs index dc00adac..6ad814ac 100644 --- a/crates/aien-mcp/src/broker.rs +++ b/crates/aien-mcp/src/broker.rs @@ -8,12 +8,12 @@ use aien_capability::{ }; use serde_json::Value; -use crate::approval::{ApprovalError, ApprovalGrant, ApprovalRecord}; +use crate::approval::{ApprovalError, ApprovalGrant, ApprovalRecord, GrantState, Reservation}; use crate::authority::{ intent_digest, AuthorityContext, AuthorityDecision, AuthorityOutcome, EffectAuthority, EffectScope, Exposure, }; -use crate::effect::mint; +use crate::effect::{mint, mint_reserved}; use crate::{ AuthorizedEffect, CallOutcome, CapabilitySnapshot, EffectIntent, EffectReceipt, Error, McpWire, ToolResult, @@ -55,6 +55,7 @@ pub(crate) struct Inner { ledger: HashMap, pub(crate) approvals: HashMap, pub(crate) next_approval: u64, + pub(crate) next_reservation: u64, } /// Owns admitted MCP sessions and the idempotency ledger. @@ -71,6 +72,7 @@ impl McpBroker { ledger: HashMap::new(), approvals: HashMap::new(), next_approval: 0, + next_reservation: 0, })), } } @@ -244,13 +246,29 @@ pub struct SpeculativeToolCall { pub struct EffectLane { broker: McpBroker, exposure: Option, + clock: Option, } +/// Host-supplied time source, in the same unit as `now` and `expires_at`. +pub type Clock = Arc u64 + Send + Sync>; + impl EffectLane { pub fn new(broker: McpBroker) -> Self { Self { broker, exposure: None, + clock: None, + } + } + + /// A lane whose `execute_effect` re-checks approval expiry at commit using `clock`. The crate + /// reads no wall clock itself. A lane without a clock refuses to run any effect that holds an + /// approval reservation (`Error::ApprovalClockMissing`) and releases the grant. Effects + /// without a reservation do not need a clock. + pub fn with_clock(&self, clock: Clock) -> Self { + Self { + clock: Some(clock), + ..self.clone() } } @@ -261,6 +279,7 @@ impl EffectLane { Self { broker: self.broker.clone(), exposure: Some(exposure), + clock: self.clock.clone(), } } @@ -343,15 +362,17 @@ impl EffectLane { reason, }); }; - self.spend(grant, &intent, &scope, now) + let reservation = self + .reserve(grant, &intent, &scope, now) .map_err(AuthorityOutcome::Approval)?; - Ok(mint( + Ok(mint_reserved( intent, scope.world_id, scope.winning_jnode, policy_digest, live, scope.idempotency_key, + reservation, )) } AuthorityDecision::Deny(reason) => Err(AuthorityOutcome::Denied(reason)), @@ -403,7 +424,7 @@ impl EffectLane { ) -> Option> { let inner = self.broker.lock(); let record = inner.approvals.get(&grant.id())?; - if !record.consumed || !record.binds(intent, scope) { + if record.state != GrantState::Spent || !record.binds(intent, scope) { return None; } let row = inner.ledger.get(&scope.idempotency_key)?; @@ -417,14 +438,15 @@ impl EffectLane { } } - /// Check and spend `grant` atomically under the broker lock. - fn spend( + /// Check and reserve `grant` atomically under the broker lock. The returned reservation is + /// committed by `execute_effect` and released if the effect is dropped or cancelled. + fn reserve( &self, grant: &ApprovalGrant, intent: &EffectIntent, scope: &EffectScope, now: u64, - ) -> Result<(), ApprovalError> { + ) -> Result { let mut inner = self.broker.lock(); let record = inner .approvals @@ -433,8 +455,10 @@ impl EffectLane { if !record.binds(intent, scope) { return Err(ApprovalError::Mismatch); } - if record.consumed { - return Err(ApprovalError::Consumed); + match record.state { + GrantState::Spent => return Err(ApprovalError::Consumed), + GrantState::Reserved(_) => return Err(ApprovalError::Reserved), + GrantState::Available => {} } if record.revoked { return Err(ApprovalError::Revoked); @@ -442,8 +466,17 @@ impl EffectLane { if now >= record.expires_at { return Err(ApprovalError::Expired); } - record.consumed = true; - Ok(()) + let token = { + inner.next_reservation = inner.next_reservation.saturating_add(1); + inner.next_reservation + }; + let record = inner + .approvals + .get_mut(&grant.id()) + .ok_or(ApprovalError::Unknown)?; + record.state = GrantState::Reserved(token); + record.release_reason = None; + Ok(Reservation::new(self.broker.clone(), grant.id(), token)) } pub async fn execute_effect( @@ -488,6 +521,12 @@ impl EffectLane { } session.wire.clone() }; + // Point of no return: the provider is about to be called. Until here a refusal drops + // the effect and releases its grant; from here the grant is spent. + if let Some(reservation) = effect.reservation() { + let now = self.clock.as_ref().map(|c| c()); + reservation.commit_locked(&mut inner, now)?; + } inner.ledger.insert( key, LedgerRow { diff --git a/crates/aien-mcp/src/effect.rs b/crates/aien-mcp/src/effect.rs index 49f1d7dc..6372e909 100644 --- a/crates/aien-mcp/src/effect.rs +++ b/crates/aien-mcp/src/effect.rs @@ -1,3 +1,6 @@ +use std::sync::Arc; + +use crate::approval::Reservation; use aien_capability::{Digest32, EffectId, JNodeId, ProviderId, WorldId}; use serde_json::Value; @@ -65,9 +68,30 @@ pub struct AuthorizedEffect { policy_digest: Digest32, capability_digest: Digest32, idempotency_key: EffectId, + reservation: Option>, } impl AuthorizedEffect { + /// Id of the approval grant this effect holds, if it was minted by `authorize_approved`. + pub fn approval_id(&self) -> Option { + self.reservation.as_ref().map(|r| r.grant_id()) + } + + /// Give up this effect without running it. If it holds an approval grant, the grant is + /// released (usable again once re-checked at the next mint) and `reason` is recorded + /// ([`crate::ApprovalDesk::release_reason`]). Dropping the effect has the same release with a + /// fixed reason. Clones share the hold: after a cancel, a clone cannot be executed with the + /// grant (`Error::ApprovalNotReserved`). + pub fn cancel(self, reason: &str) { + if let Some(r) = &self.reservation { + r.release(reason); + } + } + + pub(crate) fn reservation(&self) -> Option<&Reservation> { + self.reservation.as_deref() + } + pub fn intent(&self) -> &T { &self.intent } @@ -110,6 +134,7 @@ pub(crate) fn authorize_for_test( policy_digest, capability_digest, idempotency_key, + reservation: None, } } @@ -130,5 +155,28 @@ pub(crate) fn mint( policy_digest, capability_digest, idempotency_key, + reservation: None, } } + +/// Production mint for an effect that holds a reserved approval grant. +pub(crate) fn mint_reserved( + intent: T, + world_id: WorldId, + winning_jnode: JNodeId, + policy_digest: Digest32, + capability_digest: Digest32, + idempotency_key: EffectId, + reservation: Reservation, +) -> AuthorizedEffect { + let mut effect = mint( + intent, + world_id, + winning_jnode, + policy_digest, + capability_digest, + idempotency_key, + ); + effect.reservation = Some(Arc::new(reservation)); + effect +} diff --git a/crates/aien-mcp/src/error.rs b/crates/aien-mcp/src/error.rs index 8d7ee694..f709b61d 100644 --- a/crates/aien-mcp/src/error.rs +++ b/crates/aien-mcp/src/error.rs @@ -27,4 +27,12 @@ pub enum Error { UnclassifiedTool(String), #[error("mcp transport failed: {0}")] Transport(String), + #[error("approval is no longer reserved for this effect (it was cancelled)")] + ApprovalNotReserved, + #[error("approval expired before the effect could run; nothing was called")] + ApprovalExpired, + #[error( + "approved effect needs a clock to check expiry; build the lane with EffectLane::with_clock" + )] + ApprovalClockMissing, } diff --git a/crates/aien-mcp/src/lib.rs b/crates/aien-mcp/src/lib.rs index fbfbfba9..721680eb 100644 --- a/crates/aien-mcp/src/lib.rs +++ b/crates/aien-mcp/src/lib.rs @@ -24,12 +24,12 @@ mod transport_tests; #[cfg(test)] pub(crate) use effect::authorize_for_test; -pub use approval::{ApprovalDesk, ApprovalError, ApprovalGrant}; +pub use approval::{ApprovalDesk, ApprovalError, ApprovalGrant, GrantStatus}; pub use authority::{ intent_digest, AuthorityContext, AuthorityDecision, AuthorityOutcome, EffectAuthority, EffectClassAuthority, EffectScope, Exposure, TrustLevel, }; -pub use broker::{EffectLane, McpBroker, SpeculativeLane, SpeculativeToolCall}; +pub use broker::{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/approval.rs b/crates/aien-mcp/tests/approval.rs index 6ec88a59..32a95725 100644 --- a/crates/aien-mcp/tests/approval.rs +++ b/crates/aien-mcp/tests/approval.rs @@ -62,7 +62,7 @@ async fn harness() -> H { capability_digest: live, }; H { - lane: EffectLane::new(broker.clone()), + lane: EffectLane::new(broker.clone()).with_clock(std::sync::Arc::new(|| 1)), desk: ApprovalDesk::new(broker.clone()), broker, calls, @@ -95,20 +95,28 @@ async fn second_mint_with_the_same_grant_is_refused() { let h = harness().await; let g = h.desk.issue(&h.intent, scope("b"), 100); let a = EffectClassAuthority; - assert!(h + // Hold the minted effect: a dropped one would release the grant (see tests/two_phase.rs). + let held = h .lane .authorize_approved(h.intent.clone(), scope("b"), &a, &g, 1) - .is_ok()); + .unwrap(); let err = h .lane .authorize_approved(h.intent.clone(), scope("b"), &a, &g, 1) .unwrap_err(); - assert_eq!(approval(err), ApprovalError::Consumed); + assert_eq!(approval(err), ApprovalError::Reserved); // A cloned grant is the same grant. let err = h .lane .authorize_approved(h.intent.clone(), scope("b"), &a, &g.clone(), 1) .unwrap_err(); + assert_eq!(approval(err), ApprovalError::Reserved); + // Once the held effect runs, the grant is spent for good. + h.lane.execute_effect(held).await.unwrap(); + let err = h + .lane + .authorize_approved(h.intent.clone(), scope("b"), &a, &g, 1) + .unwrap_err(); assert_eq!(approval(err), ApprovalError::Consumed); } diff --git a/crates/aien-mcp/tests/binding.rs b/crates/aien-mcp/tests/binding.rs index 0acc330f..11c8640f 100644 --- a/crates/aien-mcp/tests/binding.rs +++ b/crates/aien-mcp/tests/binding.rs @@ -54,7 +54,7 @@ async fn harness_with(wire: Arc, calls: Arc) -> H { .unwrap() .catalog_digest; H { - lane: EffectLane::new(broker.clone()), + lane: EffectLane::new(broker.clone()).with_clock(std::sync::Arc::new(|| 1)), desk: ApprovalDesk::new(broker.clone()), broker, calls, @@ -143,6 +143,8 @@ async fn one_grant_spent_from_many_threads_mints_exactly_once() { let g = h.desk.issue(&intent, scope("race"), 100); let minted = AtomicUsize::new(0); let refused = AtomicUsize::new(0); + // Winners are kept alive: a dropped effect would release the grant for the next thread. + let held = std::sync::Mutex::new(Vec::new()); std::thread::scope(|s| { for _ in 0..16 { s.spawn(|| { @@ -153,8 +155,11 @@ async fn one_grant_spent_from_many_threads_mints_exactly_once() { &g, 1, ) { - Ok(_) => minted.fetch_add(1, Ordering::SeqCst), - Err(AuthorityOutcome::Approval(ApprovalError::Consumed)) => { + Ok(e) => { + held.lock().unwrap().push(e); + minted.fetch_add(1, Ordering::SeqCst) + } + Err(AuthorityOutcome::Approval(ApprovalError::Reserved)) => { refused.fetch_add(1, Ordering::SeqCst) } Err(other) => panic!("unexpected {other:?}"), diff --git a/crates/aien-mcp/tests/two_phase.rs b/crates/aien-mcp/tests/two_phase.rs new file mode 100644 index 00000000..67ee7dfb --- /dev/null +++ b/crates/aien-mcp/tests/two_phase.rs @@ -0,0 +1,441 @@ +//! Two-phase approval spend (issue #206), through the public API only: reserve at mint, commit in +//! `execute_effect`, release when the minted effect is dropped or cancelled un-executed. +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, Barrier, Mutex}; + +use aien_capability::{ + Digest32, EffectId, JNodeId, ProviderId, ToolDescriptor, ToolEffects, WorldId, +}; +use aien_mcp::memory::MemoryWire; +use aien_mcp::{ + ApprovalDesk, ApprovalError, ApprovalGrant, AuthorityOutcome, CallOutcome, + EffectClassAuthority, EffectIntent, EffectLane, EffectScope, Error, GrantStatus, McpBroker, + SpeculativeLane, +}; +use serde_json::json; + +struct H { + lane: EffectLane, + desk: ApprovalDesk, + calls: Arc, + intent: EffectIntent, + broker: McpBroker, + provider: ProviderId, +} + +fn scope(label: &str) -> EffectScope { + EffectScope { + world_id: WorldId(1), + winning_jnode: JNodeId(1), + idempotency_key: EffectId::from_label(label), + } +} + +async fn harness() -> H { + let calls = Arc::new(AtomicUsize::new(0)); + let c = calls.clone(); + let tool = ToolDescriptor::new("t", ToolEffects::WORLD_MUTATION, Digest32::of(b"t")); + let wire = MemoryWire::new(vec![tool], move |_, _| { + let n = c.fetch_add(1, Ordering::SeqCst); + CallOutcome::Finished(json!({"done": true, "n": n})) + }); + let broker = McpBroker::new(); + let provider = ProviderId::new("p"); + broker + .admit(provider.clone(), Arc::new(wire)) + .await + .unwrap(); + let live = SpeculativeLane::new(broker.clone()) + .discovery_snapshot(&provider) + .await + .unwrap() + .catalog_digest; + let intent = EffectIntent { + provider: provider.clone(), + tool_name: "t".into(), + arguments: json!({"a": 1}), + capability_digest: live, + }; + H { + lane: EffectLane::new(broker.clone()).with_clock(Arc::new(|| 1)), + desk: ApprovalDesk::new(broker.clone()), + broker, + calls, + intent, + provider, + } +} + +fn mint( + h: &H, + label: &str, + g: &ApprovalGrant, + now: u64, +) -> Result, AuthorityOutcome> { + h.lane.authorize_approved( + h.intent.clone(), + scope(label), + &EffectClassAuthority, + g, + now, + ) +} + +fn approval(e: AuthorityOutcome) -> ApprovalError { + match e { + AuthorityOutcome::Approval(a) => a, + other => panic!("expected Approval, got {other:?}"), + } +} + +#[tokio::test] +async fn refused_after_mint_keeps_grant_usable() { + let h = harness().await; + let g = h.desk.issue(&h.intent, scope("a"), 100); + // The host mints, then its own checks refuse and it drops the effect. + let effect = mint(&h, "a", &g, 1).unwrap(); + assert_eq!(h.desk.status(&g), Some(GrantStatus::Reserved)); + drop(effect); + assert_eq!(h.desk.status(&g), Some(GrantStatus::Available)); + // The same grant still buys exactly one run. + let r = h + .lane + .authorize_and_execute_approved(h.intent.clone(), scope("a"), &EffectClassAuthority, &g, 2) + .await + .unwrap(); + assert_eq!(r.output["done"], json!(true)); + assert_eq!(h.calls.load(Ordering::SeqCst), 1); +} + +#[tokio::test] +async fn dropped_effect_releases_and_records_why() { + let h = harness().await; + let g = h.desk.issue(&h.intent, scope("d"), 100); + assert_eq!(h.desk.release_reason(&g), None); + drop(mint(&h, "d", &g, 1).unwrap()); + assert_eq!(h.desk.status(&g), Some(GrantStatus::Available)); + assert_eq!( + h.desk.release_reason(&g).as_deref(), + Some("dropped before execute_effect") + ); + assert_eq!(h.calls.load(Ordering::SeqCst), 0); + assert!(mint(&h, "d", &g, 1).is_ok()); +} + +#[tokio::test] +async fn explicit_cancel_releases_with_a_reason_and_kills_clones() { + let h = harness().await; + let g = h.desk.issue(&h.intent, scope("c"), 100); + let effect = mint(&h, "c", &g, 1).unwrap(); + assert_eq!(effect.approval_id(), Some(g.approval_id())); + let clone = effect.clone(); + effect.cancel("digest check refused"); + assert_eq!(h.desk.status(&g), Some(GrantStatus::Available)); + assert_eq!( + h.desk.release_reason(&g).as_deref(), + Some("digest check refused") + ); + // A surviving clone must not run on a grant that was given back. + assert_eq!( + h.lane.execute_effect(clone).await.unwrap_err(), + Error::ApprovalNotReserved + ); + assert_eq!(h.calls.load(Ordering::SeqCst), 0); + // Dropping the dead clone did not disturb a later reservation. + let again = mint(&h, "c", &g, 1).unwrap(); + assert_eq!(h.desk.status(&g), Some(GrantStatus::Reserved)); + drop(again); +} + +#[tokio::test] +async fn stale_cancel_cannot_release_a_later_reservation() { + let h = harness().await; + let g = h.desk.issue(&h.intent, scope("s"), 100); + let first = mint(&h, "s", &g, 1).unwrap(); + let stale = first.clone(); + first.cancel("first"); + let second = mint(&h, "s", &g, 1).unwrap(); + stale.cancel("late"); + assert_eq!(h.desk.status(&g), Some(GrantStatus::Reserved)); + h.lane.execute_effect(second).await.unwrap(); + assert_eq!(h.calls.load(Ordering::SeqCst), 1); +} + +#[tokio::test] +async fn double_mint_while_reserved_is_refused() { + let h = harness().await; + let g = h.desk.issue(&h.intent, scope("m"), 100); + let held = mint(&h, "m", &g, 1).unwrap(); + assert_eq!( + approval(mint(&h, "m", &g, 1).unwrap_err()), + ApprovalError::Reserved + ); + // The desk cannot withdraw a grant an effect is holding. + assert!(!h.desk.revoke(&g)); + drop(held); + assert!(h.desk.revoke(&g)); + assert_eq!( + approval(mint(&h, "m", &g, 1).unwrap_err()), + ApprovalError::Revoked + ); + assert_eq!(h.desk.status(&g), Some(GrantStatus::Revoked)); +} + +#[tokio::test] +async fn execute_commits_once() { + let h = harness().await; + let g = h.desk.issue(&h.intent, scope("e"), 100); + let effect = mint(&h, "e", &g, 1).unwrap(); + h.lane.execute_effect(effect).await.unwrap(); + assert_eq!(h.desk.status(&g), Some(GrantStatus::Spent)); + assert_eq!(h.calls.load(Ordering::SeqCst), 1); + // Spent is final: no release by drop, and no second mint. + assert_eq!( + approval(mint(&h, "e", &g, 1).unwrap_err()), + ApprovalError::Consumed + ); + assert_eq!(h.desk.status(&g), Some(GrantStatus::Spent)); + assert_eq!(h.desk.release_reason(&g), None); +} + +#[tokio::test] +async fn replay_after_execute_returns_the_original_receipt() { + let h = harness().await; + let g = h.desk.issue(&h.intent, scope("r"), 100); + let first = h + .lane + .authorize_and_execute_approved(h.intent.clone(), scope("r"), &EffectClassAuthority, &g, 1) + .await + .unwrap(); + let again = h + .lane + .authorize_and_execute_approved( + h.intent.clone(), + scope("r"), + &EffectClassAuthority, + &g, + 10_000, + ) + .await + .unwrap(); + assert_eq!(first, again); + assert_eq!(h.calls.load(Ordering::SeqCst), 1); + assert_eq!(h.desk.status(&g), Some(GrantStatus::Spent)); +} + +#[tokio::test] +async fn expired_grant_released_then_remint_is_refused() { + let h = harness().await; + let g = h.desk.issue(&h.intent, scope("x"), 10); + drop(mint(&h, "x", &g, 1).unwrap()); + assert_eq!(h.desk.status(&g), Some(GrantStatus::Available)); + assert_eq!( + approval(mint(&h, "x", &g, 10).unwrap_err()), + ApprovalError::Expired + ); + assert_eq!(h.calls.load(Ordering::SeqCst), 0); +} + +#[tokio::test] +async fn refusal_inside_execute_effect_before_dispatch_releases() { + let h = harness().await; + let g = h.desk.issue(&h.intent, scope("z"), 100); + let effect = mint(&h, "z", &g, 1).unwrap(); + // The catalog moves between mint and execute: execute_effect refuses as stale. + let tool = ToolDescriptor::new("t", ToolEffects::WORLD_MUTATION, Digest32::of(b"t2")); + h.broker + .replace_catalog(&h.provider, vec![tool]) + .await + .unwrap(); + assert_eq!( + h.lane.execute_effect(effect).await.unwrap_err(), + Error::StaleCapability + ); + assert_eq!(h.calls.load(Ordering::SeqCst), 0); + assert_eq!(h.desk.status(&g), Some(GrantStatus::Available)); +} + +#[test] +fn concurrent_mint_race_has_one_winner() { + let rt = tokio::runtime::Builder::new_current_thread() + .build() + .unwrap(); + let h = rt.block_on(harness()); + let g = h.desk.issue(&h.intent, scope("race"), 100); + let barrier = Barrier::new(2); + let wins = AtomicUsize::new(0); + let reserved = AtomicUsize::new(0); + let held = Mutex::new(Vec::new()); + std::thread::scope(|s| { + for _ in 0..2 { + s.spawn(|| { + barrier.wait(); + match mint(&h, "race", &g, 1) { + Ok(e) => { + held.lock().unwrap().push(e); + wins.fetch_add(1, Ordering::SeqCst); + } + Err(AuthorityOutcome::Approval(ApprovalError::Reserved)) => { + reserved.fetch_add(1, Ordering::SeqCst); + } + Err(other) => panic!("unexpected {other:?}"), + } + }); + } + }); + assert_eq!(wins.load(Ordering::SeqCst), 1); + assert_eq!(reserved.load(Ordering::SeqCst), 1); + assert_eq!(h.desk.status(&g), Some(GrantStatus::Reserved)); +} + +#[tokio::test] +async fn grant_from_another_broker_has_no_status() { + let h = harness().await; + let other = harness().await; + let g = other.desk.issue(&other.intent, scope("o"), 100); + assert_eq!(h.desk.status(&g), None); +} + +#[tokio::test] +async fn held_effect_past_expiry_is_refused_at_commit_and_released() { + let h = harness().await; + let clock = Arc::new(std::sync::atomic::AtomicU64::new(1)); + let c = clock.clone(); + let lane = h + .lane + .with_clock(Arc::new(move || c.load(Ordering::SeqCst))); + let g = h.desk.issue(&h.intent, scope("exp"), 10); + let effect = lane + .authorize_approved(h.intent.clone(), scope("exp"), &EffectClassAuthority, &g, 1) + .unwrap(); + assert_eq!(h.desk.status(&g), Some(GrantStatus::Reserved)); + clock.store(10, Ordering::SeqCst); + assert_eq!( + lane.execute_effect(effect).await.unwrap_err(), + Error::ApprovalExpired + ); + assert_eq!(h.calls.load(Ordering::SeqCst), 0); + assert_eq!(h.desk.status(&g), Some(GrantStatus::Available)); + assert_eq!( + h.desk.release_reason(&g).as_deref(), + Some("expired before execute") + ); + assert_eq!( + approval(mint(&h, "exp", &g, 10).unwrap_err()), + ApprovalError::Expired + ); +} + +#[tokio::test] +async fn clock_before_expiry_still_commits() { + let h = harness().await; + let lane = h.lane.with_clock(Arc::new(|| 5)); + let g = h.desk.issue(&h.intent, scope("ok"), 10); + let effect = lane + .authorize_approved(h.intent.clone(), scope("ok"), &EffectClassAuthority, &g, 1) + .unwrap(); + lane.execute_effect(effect).await.unwrap(); + assert_eq!(h.desk.status(&g), Some(GrantStatus::Spent)); +} + +#[tokio::test] +async fn provider_panic_after_commit_leaves_the_grant_spent_and_never_reruns() { + let calls = Arc::new(AtomicUsize::new(0)); + let c = calls.clone(); + let tool = ToolDescriptor::new("t", ToolEffects::WORLD_MUTATION, Digest32::of(b"t")); + let wire = MemoryWire::new(vec![tool], move |_, _| { + c.fetch_add(1, Ordering::SeqCst); + panic!("provider blew up"); + }); + let broker = McpBroker::new(); + let provider = ProviderId::new("p"); + broker + .admit(provider.clone(), Arc::new(wire)) + .await + .unwrap(); + let live = SpeculativeLane::new(broker.clone()) + .discovery_snapshot(&provider) + .await + .unwrap() + .catalog_digest; + let intent = EffectIntent { + provider, + tool_name: "t".into(), + arguments: json!({"a": 1}), + capability_digest: live, + }; + let lane = EffectLane::new(broker.clone()).with_clock(Arc::new(|| 1)); + let desk = ApprovalDesk::new(broker); + let g = desk.issue(&intent, scope("pan"), 100); + let (l2, i2, g2) = (lane.clone(), intent.clone(), g.clone()); + let joined = std::thread::spawn(move || { + let rt = tokio::runtime::Builder::new_current_thread() + .build() + .unwrap(); + let _ = rt.block_on(l2.authorize_and_execute_approved( + i2, + scope("pan"), + &EffectClassAuthority, + &g2, + 1, + )); + }) + .join(); + assert!(joined.is_err(), "provider panic must propagate"); + assert_eq!(desk.status(&g), Some(GrantStatus::Spent)); + let again = lane + .authorize_and_execute_approved(intent, scope("pan"), &EffectClassAuthority, &g, 1) + .await + .unwrap_err(); + assert_eq!(again, AuthorityOutcome::Execution(Error::EffectInFlight)); + assert_eq!(calls.load(Ordering::SeqCst), 1); +} + +#[tokio::test] +async fn reserved_effect_on_a_lane_without_a_clock_fails_closed_and_releases() { + let h = harness().await; + let no_clock = EffectLane::new(h.broker.clone()); + let g = h.desk.issue(&h.intent, scope("nc"), 100); + let effect = no_clock + .authorize_approved(h.intent.clone(), scope("nc"), &EffectClassAuthority, &g, 1) + .unwrap(); + assert_eq!( + no_clock.execute_effect(effect).await.unwrap_err(), + Error::ApprovalClockMissing + ); + assert_eq!(h.calls.load(Ordering::SeqCst), 0); + assert_eq!(h.desk.status(&g), Some(GrantStatus::Available)); + assert_eq!( + h.desk.release_reason(&g).as_deref(), + Some("no clock: expiry cannot be checked") + ); + // The same grant runs once on a lane that has a clock. + h.lane + .authorize_and_execute_approved(h.intent.clone(), scope("nc"), &EffectClassAuthority, &g, 1) + .await + .unwrap(); + assert_eq!(h.calls.load(Ordering::SeqCst), 1); +} + +#[tokio::test] +async fn effect_without_a_reservation_runs_on_a_lane_without_a_clock() { + let h = harness().await; + let no_clock = EffectLane::new(h.broker.clone()); + // Allow verdict: no grant involved, so no clock is needed. + struct AllowAll; + impl aien_mcp::EffectAuthority for AllowAll { + fn authorize( + &self, + _: &EffectIntent, + _: &aien_mcp::AuthorityContext, + ) -> aien_mcp::AuthorityDecision { + aien_mcp::AuthorityDecision::Allow + } + } + let r = no_clock + .authorize_and_execute(h.intent.clone(), scope("na"), &AllowAll) + .await + .unwrap(); + assert_eq!(r.output["done"], json!(true)); + assert_eq!(h.calls.load(Ordering::SeqCst), 1); +} ```