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/3fc2fcef7bb844f7 # 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#609 (code only) closed derived `3fc2fcef7bb844f7` #609 Imported from GitHub aien-dev/aien-sovereign-core-mv#609 (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 `12e71aad80fda23a428317d11b0dac02d1c777f1` · Head `ad975aec00e15b6d7fca8e5dd382c81863b2824e` ### Fetch it A git bundle of the pull request's head, 9499 bytes. ``` curl -fsSL https://interplane.io/drakestapleton/aien-sovereign-core-mv/patches/3fc2fcef7bb844f7.bundle -o 3fc2fcef7bb844f7.bundle git fetch 3fc2fcef7bb844f7.bundle refs/pull/609/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 609 ad975aec00e15b6d7fca8e5dd382c81863b2824e ``` ``` {"kind":"github-import","owner":"aien-dev","repo":"aien-sovereign-core-mv","number":609,"url":"https://github.com/aien-dev/aien-sovereign-core-mv/pull/609","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:37:39Z","metadata":"unavailable","state_derived":true} ``` ### Changes ``` diff --git a/.crumb b/.crumb index d38130fb..9e3c0f50 100644 --- a/.crumb +++ b/.crumb @@ -119,14 +119,14 @@ } ], "children_root": "sha256:111edf8bf001ed434f7dacbc6d8ab9d75f6bda2cd909d01264fb42bbe38b1d74", - "compiled_at": "2026-10-17T11:58:09Z", + "compiled_at": "2026-10-18T14:44:17Z", "compiler": "crumb-compile/1", - "digest": "sha256:90138b1fd1cf3ffa4f762b157930e959f2bea50c41351c40b41330ae9edff05b", + "digest": "sha256:e25f553e4729f8446a4c0df113a2f58de01ba0893115b0e7a5df54b83cda4273", "evidence_files": 1578, "evidence_root": "sha256:135e27a1a0704c4a8371cd2c1eb555f2b5beec61c212949b029a5457418a7160", "files": 5891, - "generated_at_commit": "6fb606867d2cd502b9475cd2ff0cc85ab40b16c9", - "source_tree": "sha256:7ac140a01c7f7ef0cc9f91a7cf9ea94fb063f8ca7f24365f185b9da5b2ed26b9" + "generated_at_commit": "3561561bbf3d175e0d2ece4663486ae04f2278a4", + "source_tree": "sha256:ddc3f1c4d8bae3536bbcb63944fe11ce3523b527cb85c3f3fba2b5f7aa3a89fe" } }, "history": [], diff --git a/crates/aien-runtime/src/provisional.rs b/crates/aien-runtime/src/provisional.rs index 99bdba27..9f45f8d7 100644 --- a/crates/aien-runtime/src/provisional.rs +++ b/crates/aien-runtime/src/provisional.rs @@ -90,14 +90,20 @@ //! [`DeliverError::DeferredFull`] and queues nothing) and delivered again //! right after the commit outcome is recorded, under the same mutex, before //! any other event or fence. What each redelivery did is returned in -//! [`Fenced::redelivered`]. Only an event M2 applied (or answered as a -//! duplicate) leaves the queue: one still refused by another running commit, -//! and one M2 refuses for any other reason (a stale generation, a wrong -//! state, a journal write failure), stays queued and journaled, so a revoke -//! or cancel is never dropped without a decision. It is delivered again -//! after every later outcome and on every open, and it holds a queue slot -//! until the caller removes it ([`PrepAdapter::discard_deferred`]); a full -//! queue refuses new deferrals (fail closed). With a journaled scheduler +//! [`Fenced::redelivered`]. An event M2 applied (or answered as a +//! duplicate) leaves the queue. So does one M2 refuses as a stale +//! generation ([`SchedError::StaleGeneration`]): generations only grow, so +//! that event can never apply, and keeping it would hold a queue slot for +//! good (after [`DEFERRED_CAPACITY`] such events every delivery during a +//! commit would fail). It is reported with its refusal and +//! [`Redelivered::dropped`] set, which is the decision. One still refused +//! by another running commit stays queued silently, and one M2 refuses for +//! any other reason (a wrong state, a journal write failure, an unknown +//! task) stays queued and journaled, so a revoke or cancel is never dropped +//! without a decision. It is delivered again after every later outcome and +//! on every open, and it holds a queue slot until the caller removes it +//! ([`PrepAdapter::discard_deferred`]); a full queue refuses new deferrals +//! (fail closed). With a journaled scheduler //! ([`PrepAdapter::open`]) the queue is journaled in a sidecar next to the M2 //! journal ([`deferred_journal_path`]): rewritten atomically (temp file, //! fsync, rename, directory fsync) before `Deferred` is returned and after @@ -110,7 +116,7 @@ //! still lands after it ([`PrepAdapter::take_replayed_deferred`] returns //! what each did). An event that was already applied before the crash is a //! duplicate, or a stale generation once its task moved on (spark-harness -//! `scheduler/dedup.rs`); the second stays queued until discarded. A sidecar +//! `scheduler/dedup.rs`); the second is reported and dropped. A sidecar //! that does not parse, holds more than [`DEFERRED_CAPACITY`] events or //! holds a fence-only event fails the open. One adapter owns a journal and //! its sidecar: open resolves the journal path to its canonical form, takes @@ -374,6 +380,11 @@ impl std::error::Error for DeliverError {} pub struct Redelivered { pub id: String, pub result: Result, + /// The event left the queue although M2 refused it: the refusal was + /// [`SchedError::StaleGeneration`], which no later delivery can change. + /// False for an applied event (it left the queue because it landed) and + /// for every other refusal (the event stays queued). + pub dropped: bool, } #[derive(Debug)] @@ -516,8 +527,9 @@ impl Inner { }); } - /// Deliver every deferred event again, oldest first. Only an event M2 - /// applied or answered as a duplicate leaves the queue; one still + /// Deliver every deferred event again, oldest first. An event M2 + /// applied or answered as a duplicate leaves the queue, and so does one + /// refused as a stale generation (reported, `dropped`); one still /// refused by a running commit stays queued silently, and one refused /// for any other reason stays queued and is returned with its refusal. /// The sidecar is rewritten when anything left the queue; the error, if @@ -532,11 +544,18 @@ impl Inner { Ok(o) => out.push(Redelivered { id: ev.id, result: Ok(o), + dropped: false, + }), + Err(e @ SchedError::StaleGeneration { .. }) => out.push(Redelivered { + id: ev.id, + result: Err(e), + dropped: true, }), Err(e) => { out.push(Redelivered { id: ev.id.clone(), result: Err(e), + dropped: false, }); keep.push_back(ev); } diff --git a/crates/aien-runtime/tests/provisional_prep_test.rs b/crates/aien-runtime/tests/provisional_prep_test.rs index 26d0ecbe..5889f7a1 100644 --- a/crates/aien-runtime/tests/provisional_prep_test.rs +++ b/crates/aien-runtime/tests/provisional_prep_test.rs @@ -1930,8 +1930,12 @@ async fn an_aborted_task_keeps_its_bound_requests_fenced_until_retried_and_bound assert!(fence_refused(&r, "AlreadySubmitted"), "{r:?}"); } else { // The stub answer is not an EFFECT_REFUSED: uncertain, terminal. + // The binding is kept, so a resend is refused by the fence instead + // of running unfenced. assert_eq!(h.state("q"), TaskState::CommitUncertain); - assert!(h.adapter.binding(&key).is_none()); + assert_eq!(h.adapter.binding(&key), Some(("q".into(), 2))); + let r = send(authorize(&digest)).await; + assert!(fence_refused(&r, "AlreadySubmitted"), "{r:?}"); } let _ = client.send_command(ControlCommand::Shutdown).await; @@ -2075,15 +2079,20 @@ async fn a_bound_grant_after_an_unfenced_compose_run_mints_through_the_fence() { // Not an `EFFECT_REFUSED`: classified uncertain (fail closed). assert_eq!(h.state("b"), TaskState::CommitUncertain); } - // B ended: the binding is dropped and the retry is the original call. - assert!(h.adapter.binding(&key).is_none()); let r = send(grant("m3-run-final")).await; - match &r { - ControlResponse::Error(e) if aien_omega_compose::LINKED => { - assert!(e.starts_with("EFFECT_REFUSED "), "{e}") + if aien_omega_compose::LINKED { + // B committed: the binding is dropped and the retry is the original + // call, which the replay ledger refuses. + assert!(h.adapter.binding(&key).is_none()); + match &r { + ControlResponse::Error(e) => assert!(e.starts_with("EFFECT_REFUSED "), "{e}"), + other => panic!("a second grant must be refused: {other:?}"), } - ControlResponse::Error(e) => assert!(e.ends_with("is not linked (stub build)"), "{e}"), - other => panic!("a second grant must be refused: {other:?}"), + } else { + // B is uncertain: the binding is kept for good, so the retry stays + // fenced and is refused (the task ended) instead of running unfenced. + assert_eq!(h.adapter.binding(&key), Some(("b".into(), 1))); + assert!(fence_refused(&r, "AlreadySubmitted"), "{r:?}"); } let _ = client.send_command(ControlCommand::Shutdown).await; @@ -2374,15 +2383,125 @@ fn the_deferred_queue_is_bounded_and_fails_closed() { .collect(); assert_eq!(ids, want); assert!(matches!(out.redelivered[0].result, Ok(Outcome::Applied(_)))); + assert!(!out.redelivered[0].dropped); // The first revoke moved a to generation 2, so the rest are refused as - // stale. Refused redeliveries are kept (never dropped) until discarded. + // stale. A stale event can never apply (generations only grow), so each + // is reported as dropped and leaves the queue: the queue is empty again + // instead of holding 63 dead slots. assert!(out.redelivered[1..] .iter() - .all(|r| matches!(r.result, Err(SchedError::StaleGeneration { .. })))); - assert_eq!(h.adapter.deferred_len(), DEFERRED_CAPACITY - 1); + .all(|r| { matches!(r.result, Err(SchedError::StaleGeneration { .. })) && r.dropped })); + assert_eq!(h.adapter.deferred_len(), 0); assert_eq!(h.state("b"), TaskState::Committed); } +#[test] +fn a_stale_deferred_event_is_dropped_and_leaves_the_sidecar() { + let mut h = H::journaled(cfg(true, 4)); + h.register("a", &[]); + h.register("b", &["a"]); + h.publish("a", 1); + h.finish("a"); + h.finish("b"); + let side = deferred_journal_path(&h.tmp.path().join("journal.jsonl")); + let adapter = Arc::clone(&h.adapter); + let out = h + .adapter + .fenced_for_tests( + "b", + 1, + |_| { + ( + adapter.deliver(revoke_a("revoke-first")), + adapter.deliver(revoke_a("revoke-second")), + ) + }, + committed, + ) + .unwrap(); + assert!(matches!( + out.outcome.0, + Ok(Delivered::Deferred { queued: 1, .. }) + )); + assert!(matches!( + out.outcome.1, + Ok(Delivered::Deferred { queued: 2, .. }) + )); + // The first revoke applies (a moves to generation 2); the second names + // generation 1 and is stale for good: reported, dropped, and gone from + // the sidecar, so the queue has its slot back. + assert_eq!(out.redelivered.len(), 2); + assert_eq!(out.redelivered[0].id, "revoke-first"); + assert!(matches!(out.redelivered[0].result, Ok(Outcome::Applied(_)))); + assert!(!out.redelivered[0].dropped); + assert_eq!(out.redelivered[1].id, "revoke-second"); + assert!( + matches!( + out.redelivered[1].result, + Err(SchedError::StaleGeneration { ref task, submitted: 1, current: 2 }) if task == "a" + ), + "{:?}", + out.redelivered[1].result + ); + assert!(out.redelivered[1].dropped); + assert!(out.deferred_error.is_none()); + assert_eq!(h.adapter.deferred_len(), 0); + assert_eq!(std::fs::read_to_string(&side).unwrap(), ""); + assert_eq!(h.gen("a"), 2); + // A restart replays nothing: the drop was journaled. + drop(adapter); + h.restart(cfg(true, 4)); + assert!(h.adapter.take_replayed_deferred().is_empty()); + assert_eq!(h.adapter.deferred_len(), 0); +} + +#[test] +fn an_uncertain_commit_keeps_the_binding_so_the_request_stays_fenced() { + let mut h = H::journaled(cfg(true, 4)); + h.register("a", &[]); + h.register("b", &["a"]); + h.publish("a", 1); + h.finish("a"); + h.finish("b"); + let key = FenceKey::Approval("approval-uncertain".into()); + h.adapter.bind_approval(key.clone(), "b", 1).unwrap(); + let adapter = Arc::clone(&h.adapter); + let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + adapter.fenced_for_tests( + "b", + 1, + |_| panic!("commit blew up before any write"), + committed, + ) + })); + assert!(r.is_err(), "the panic is resumed"); + assert_eq!(h.state("b"), TaskState::CommitUncertain); + // The binding is kept: the daemon still routes this request through the + // fence, and the fence refuses it (the task ended) instead of letting + // the same request run unfenced. Only a new key, never bound, runs as + // the original call. + assert_eq!(h.adapter.binding(&key), Some(("b".to_string(), 1))); + let mut ran = false; + assert!(matches!( + fence_err( + h.adapter + .fenced_for_tests("b", 1, |_| ran = true, committed) + ), + FenceError::AlreadySubmitted { .. } + )); + assert!(!ran); + assert!(matches!( + h.adapter + .bind_approval(FenceKey::Approval("approval-late".into()), "b", 1), + Err(SchedError::WrongState { .. }) + )); + // The binding survives a restart along with the terminal state. + drop(adapter); + h.restart(cfg(true, 4)); + assert_eq!(h.state("b"), TaskState::CommitUncertain); + assert_eq!(h.adapter.binding(&key), Some(("b".to_string(), 1))); +} + #[test] fn the_fence_events_are_refused_by_deliver() { let mut h = H::new(cfg(true, 4)); @@ -2777,8 +2896,8 @@ fn an_open_whose_sidecar_cannot_be_rewritten_fails() { } // Control: without the blocker, the same open succeeds. The failed // open had journaled the revoke before its rewrite failed, so a is at - // generation 2 once, and the redelivered copy is refused as stale and - // kept (never dropped) until it is discarded. + // generation 2 once, and the redelivered copy is refused as stale, + // reported, and dropped (it can never apply); the sidecar is empty. std::fs::remove_dir_all(&blocker).unwrap(); let (a, _) = open().unwrap(); assert_eq!(a.generation("a"), Some(2)); @@ -2789,8 +2908,9 @@ fn an_open_whose_sidecar_cannot_be_rewritten_fails() { "{:?}", replayed[0].result ); - assert_eq!(a.deferred_len(), 1); - assert!(a.discard_deferred("revoke-a").unwrap().is_some()); + assert!(replayed[0].dropped); + assert_eq!(a.deferred_len(), 0); + assert!(a.discard_deferred("revoke-a").unwrap().is_none()); assert_eq!(std::fs::read_to_string(&side).unwrap(), ""); } diff --git a/crates/spark-harness/src/scheduler/core.rs b/crates/spark-harness/src/scheduler/core.rs index e5783b97..5084cb9f 100644 --- a/crates/spark-harness/src/scheduler/core.rs +++ b/crates/spark-harness/src/scheduler/core.rs @@ -120,13 +120,23 @@ pub enum EventKind { /// [`MAX_APPROVAL_KEY_LEN`] bytes) to the commit fence of `task` at /// `generation`. A later bind of the same key replaces it. Refused for /// a task whose commit ended (`Committed`, `CommitUncertain`). Every - /// binding of a task is dropped when the task reaches one of those - /// states, and only then: an `Aborted` task keeps its bindings, and so - /// does a retried or revoked one (the binding then names a superseded - /// generation), so the request stays fenced until it is bound again. - /// Each task holds at most [`MAX_APPROVAL_BINDINGS_PER_TASK`] keys; a - /// new key beyond that is refused, so one task cannot take another - /// task's slots and the table is bounded by the number of tasks. + /// binding of a task is dropped when the task is `Committed`, and only + /// then: an `Aborted` task keeps its bindings, and so does a retried or + /// revoked one (the binding then names a superseded generation), so the + /// request stays fenced until it is bound again. A `CommitUncertain` + /// task keeps its bindings too, for good: whether its commit landed is + /// unknown, so a bound request delivered again is refused by the fence + /// (the task is terminal) instead of running unfenced; only a request + /// under a new key, which nobody bound, runs as the original call. + /// Each task holds at most [`MAX_APPROVAL_BINDINGS_PER_TASK`] keys, so + /// one task cannot take another task's slots and the table is bounded + /// by the number of tasks. A new key for a full task reclaims one of + /// the task's bindings at a superseded generation (the lowest + /// generation, then the lowest key, so a replay reclaims the same one); + /// the request that key named is then unbound, and its fence was + /// already a refusal (`StaleGeneration`). A full task whose bindings + /// are all at its current generation refuses the new key + /// (`BindingsFull`). BindApproval { key: String, task: String, @@ -146,13 +156,23 @@ pub struct ApprovalBinding { pub generation: u64, } -/// A task in one of these states has run its commit, for good: it holds no -/// request binding. `Aborted` is not one of them: a cancelled, failed or -/// expired task may be retried, and its bound requests must stay fenced. +/// A task in one of these states has run its commit, for good: no request +/// may be bound to it any more. `Aborted` is not one of them: a cancelled, +/// failed or expired task may be retried, and its bound requests must stay +/// fenced. fn binding_ended(state: TaskState) -> bool { matches!(state, TaskState::Committed | TaskState::CommitUncertain) } +/// A task in this state holds no request binding: its commit landed, so a +/// bound request delivered again would be a duplicate the durable ledgers +/// answer. `CommitUncertain` is not one of them: whether that commit landed +/// is unknown, so its bound requests stay fenced (and refused, the task +/// being terminal) rather than running unfenced. +fn bindings_released(state: TaskState) -> bool { + matches!(state, TaskState::Committed) +} + /// How a commit ended. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(tag = "result", rename_all = "snake_case", deny_unknown_fields)] @@ -921,10 +941,27 @@ impl Core { let rebind = self.approvals.get(key).is_some_and(|b| b.task == *task); let held = self.approvals.values().filter(|b| b.task == *task).count(); if !rebind && held >= MAX_APPROVAL_BINDINGS_PER_TASK { - return Err(SchedError::BindingsFull { - task: task.clone(), - capacity: MAX_APPROVAL_BINDINGS_PER_TASK, - }); + // Reclaim one binding at a superseded generation: + // lowest generation, then lowest key (BTreeMap order), + // so a replay reclaims the same one. + let current = self.task(task)?.generation; + let superseded = self + .approvals + .iter() + .filter(|(_, b)| b.task == *task && b.generation < current) + .min_by_key(|(k, b)| (b.generation, (*k).clone())) + .map(|(k, _)| k.clone()); + match superseded { + Some(k) => { + self.approvals.remove(&k); + } + None => { + return Err(SchedError::BindingsFull { + task: task.clone(), + capacity: MAX_APPROVAL_BINDINGS_PER_TASK, + }) + } + } } self.approvals.insert( key.clone(), @@ -936,13 +973,16 @@ impl Core { } } self.pump(cfg, at, &mut fx)?; - // Every binding of a task whose commit ended (committed or - // uncertain, by this event or by a cascade from it) is dropped. - // Aborted tasks keep theirs (see `binding_ended`). Deterministic, so - // a replay rebuilds the same table. + // Every binding of a task whose commit landed (by this event or by + // a cascade from it) is dropped. Aborted and uncertain tasks keep + // theirs (see `bindings_released`). Deterministic, so a replay + // rebuilds the same table. let tasks = &self.tasks; - self.approvals - .retain(|_, b| tasks.get(&b.task).is_some_and(|t| !binding_ended(t.state))); + self.approvals.retain(|_, b| { + tasks + .get(&b.task) + .is_some_and(|t| !bindings_released(t.state)) + }); self.seen .record(&e.id, payload_digest(&e.kind), &e.kind, cfg.dedup_window); let tasks = &self.tasks; diff --git a/crates/spark-harness/tests/provisional_commit.rs b/crates/spark-harness/tests/provisional_commit.rs index dc2ff309..6af47df1 100644 --- a/crates/spark-harness/tests/provisional_commit.rs +++ b/crates/spark-harness/tests/provisional_commit.rs @@ -529,7 +529,11 @@ fn bindings_survive_a_replay_and_are_dropped_when_the_task_commits() { } #[test] -fn bindings_are_dropped_only_when_the_commit_ended() { +fn bindings_are_dropped_only_when_the_commit_landed() { + // Aborted keeps the binding (the task may be retried); uncertain keeps + // it too (whether the commit landed is unknown, so the bound request + // stays fenced and refused instead of running unfenced); only a landed + // commit releases it. for (result, ended, kept) in [ ( CommitResult::Failed { @@ -543,7 +547,7 @@ fn bindings_are_dropped_only_when_the_commit_ended() { reason: "transport".into(), }, TaskState::CommitUncertain, - false, + true, ), (committed(), TaskState::Committed, false), ] { @@ -562,6 +566,42 @@ fn bindings_are_dropped_only_when_the_commit_ended() { } } +#[test] +fn an_uncertain_commit_keeps_its_bindings_for_good_and_takes_no_new_one() { + let mut h = H::journaled(enabled()); + h.register("a", 1, &[]); + h.register("b", 1, &["a"]); + h.publish("a", 1); + h.finish("a"); + h.finish("b"); + let gen_b = h.generation("b"); + bind(&mut h, "approval:x", "b").unwrap(); + begin(&mut h, "b").unwrap(); + outcome( + &mut h, + "b", + CommitResult::Uncertain { + reason: "the fenced call panicked".into(), + }, + ); + assert_eq!(h.sched.state("b"), Some(TaskState::CommitUncertain)); + // The bound request stays bound to the terminal generation, so a fence + // on it is a refusal (`AlreadySubmitted` / wrong state), never an + // unfenced run. A new key cannot be bound to the task. + assert_eq!(bound(&h, "approval:x"), Some(("b".into(), gen_b))); + assert!(wrong_state(&bind(&mut h, "approval:new", "b"))); + assert_eq!(bound(&h, "approval:new"), None); + assert!(begin(&mut h, "b").is_err()); + // Rebinding the held key is refused too: the task ended. + assert!(wrong_state(&bind(&mut h, "approval:x", "b"))); + assert_eq!(bound(&h, "approval:x"), Some(("b".into(), gen_b))); + // A replay rebuilds the same table. + h.restart(enabled()).unwrap(); + assert_eq!(h.sched.state("b"), Some(TaskState::CommitUncertain)); + assert_eq!(bound(&h, "approval:x"), Some(("b".into(), gen_b))); + assert_eq!(h.sched.approvals_len(), 1); +} + #[test] fn an_aborted_task_keeps_its_bindings_however_it_aborted() { // Cancel, producer failure and lease expiry abort c (provisional); a @@ -708,13 +748,17 @@ fn aborted_tasks_cannot_exhaust_the_table_for_other_tasks() { bind(&mut h, &format!("approval:c-{i}"), "c").unwrap(); } cancel(&mut h, "c"); - // c keeps its full share while aborted and after a retry. + // c keeps its full share while aborted and after a retry. A new key + // for the retried task reclaims one superseded binding (see + // `a_full_task_reclaims_its_superseded_bindings_oldest_first`), so the + // share stays at the cap. retry(&mut h, "c"); assert_eq!(h.sched.approvals_len(), MAX_APPROVAL_BINDINGS_PER_TASK); - let r = bind(&mut h, "approval:c-new", "c"); - assert!(matches!(r, Err(SchedError::BindingsFull { .. })), "{r:?}"); + assert!(bind(&mut h, "approval:c-new", "c").is_ok()); + assert_eq!(h.sched.approvals_len(), MAX_APPROVAL_BINDINGS_PER_TASK); // Its own keys may be bound again at the new generation. - assert!(bind(&mut h, "approval:c-0", "c").is_ok()); + assert!(bind(&mut h, "approval:c-1", "c").is_ok()); + assert_eq!(h.sched.approvals_len(), MAX_APPROVAL_BINDINGS_PER_TASK); // An unrelated task still gets its whole share. for i in 0..MAX_APPROVAL_BINDINGS_PER_TASK { bind(&mut h, &format!("approval:x-{i}"), "x").unwrap(); @@ -726,3 +770,63 @@ fn aborted_tasks_cannot_exhaust_the_table_for_other_tasks() { "{r:?}" ); } + +#[test] +fn a_full_task_reclaims_its_superseded_bindings_oldest_first() { + let mut h = H::journaled(enabled()); + h.register("a", 1, &[]); + h.register("c", 1, &["a"]); + let g1 = h.generation("c"); + for i in 0..MAX_APPROVAL_BINDINGS_PER_TASK { + bind(&mut h, &format!("approval:c-{i}"), "c").unwrap(); + } + // Full at the current generation: a new key is refused, nothing moves. + let r = bind(&mut h, "approval:c-new", "c"); + assert!(matches!(r, Err(SchedError::BindingsFull { .. })), "{r:?}"); + assert_eq!(h.sched.approvals_len(), MAX_APPROVAL_BINDINGS_PER_TASK); + // Retried: every binding now names the superseded generation g1. + cancel(&mut h, "c"); + retry(&mut h, "c"); + let g2 = h.generation("c"); + assert_eq!(g2, g1 + 1); + // A new key reclaims the lowest superseded key (BTreeMap order: + // "approval:c-0", then "approval:c-1", then "approval:c-10"). + bind(&mut h, "approval:c-new", "c").unwrap(); + assert_eq!(bound(&h, "approval:c-0"), None); + assert_eq!(bound(&h, "approval:c-new"), Some(("c".into(), g2))); + assert_eq!(h.sched.approvals_len(), MAX_APPROVAL_BINDINGS_PER_TASK); + bind(&mut h, "approval:c-newer", "c").unwrap(); + assert_eq!(bound(&h, "approval:c-1"), None); + assert_eq!(bound(&h, "approval:c-10"), Some(("c".into(), g1))); + assert_eq!(h.sched.approvals_len(), MAX_APPROVAL_BINDINGS_PER_TASK); + // Rebinding a held key moves it to g2 without reclaiming anything. + bind(&mut h, "approval:c-10", "c").unwrap(); + assert_eq!(bound(&h, "approval:c-10"), Some(("c".into(), g2))); + assert_eq!(h.sched.approvals_len(), MAX_APPROVAL_BINDINGS_PER_TASK); + // Reclaim never touches another task's bindings. + h.register("x", 1, &[]); + bind(&mut h, "approval:x-0", "x").unwrap(); + bind(&mut h, "approval:c-newest", "c").unwrap(); + assert_eq!(bound(&h, "approval:x-0"), Some(("x".into(), 1))); + assert_eq!(bound(&h, "approval:c-11"), None); + // A replay reclaims the same bindings. + let table: Vec<(String, Option<(String, u64)>)> = ["c-0", "c-1", "c-10", "c-11", "c-12"] + .iter() + .map(|k| (format!("approval:{k}"), bound(&h, &format!("approval:{k}")))) + .collect(); + h.restart(enabled()).unwrap(); + for (key, want) in table { + assert_eq!(bound(&h, &key), want, "{key}"); + } + assert_eq!(h.sched.approvals_len(), MAX_APPROVAL_BINDINGS_PER_TASK + 1); + // Once every binding is at the current generation again, the cap + // refuses new keys as before. + for i in 0..MAX_APPROVAL_BINDINGS_PER_TASK { + let key = format!("approval:c-{i}"); + if bound(&h, &key).is_some_and(|(_, g)| g == g1) { + bind(&mut h, &key, "c").unwrap(); + } + } + let r = bind(&mut h, "approval:c-last", "c"); + assert!(matches!(r, Err(SchedError::BindingsFull { .. })), "{r:?}"); +} diff --git a/docs/headstart/ROLLOUT.md b/docs/headstart/ROLLOUT.md index 543b718f..ca095c48 100644 --- a/docs/headstart/ROLLOUT.md +++ b/docs/headstart/ROLLOUT.md @@ -71,10 +71,10 @@ still decide. | State or error | Cause | What happens | Who clears it | | --- | --- | --- | --- | -| `SchedError::BindingsFull` | a task already holds `MAX_APPROVAL_BINDINGS_PER_TASK` (64, `crates/spark-harness/src/scheduler/core.rs`) approval keys | the new binding is refused; nothing is fenced or run for it | the caller (fewer keys, or a new generation) | -| `DeliverError::DeferredFull` | a commit is running and `DEFERRED_CAPACITY` (64, `crates/aien-runtime/src/provisional.rs`) events already wait | the event is refused and nothing is queued | the caller redelivers after the commit ends; queued events that stay refused hold a slot until `PrepAdapter::discard_deferred` | +| `SchedError::BindingsFull` | a task already holds `MAX_APPROVAL_BINDINGS_PER_TASK` (64, `crates/spark-harness/src/scheduler/core.rs`) approval keys, all at its current generation | the new binding is refused; nothing is fenced or run for it. A full task whose keys include bindings at a superseded generation (left by retries) is not refused: the new key reclaims the lowest superseded one (lowest generation, then lowest key), deterministically, so retries cannot exhaust the task (`a_full_task_reclaims_its_superseded_bindings_oldest_first`) | the caller (fewer keys, or a new generation) | +| `DeliverError::DeferredFull` | a commit is running and `DEFERRED_CAPACITY` (64, `crates/aien-runtime/src/provisional.rs`) events already wait | the event is refused and nothing is queued | the caller redelivers after the commit ends; a queued event refused as `StaleGeneration` on redelivery is reported (`Redelivered::dropped`) and dropped, since it can never apply; one refused for any other reason holds a slot until `PrepAdapter::discard_deferred` | | `SchedError::CommitInProgress` | an event would change a task (or an ancestor) that is `Committing`, or a second commit in the same chain | through `deliver` the event is queued and redelivered after the outcome | automatic | -| `CommitUncertain` | the commit call panicked, or a restart found a `Committing` task with no recorded outcome | terminal: never run again, consumers revoked, bindings dropped (later requests run as the original call and the durable ledgers decide) | **an operator**: check the World and the approved replay ledger to learn whether the effect landed; M2 has no retry from this state (`Retry` needs `Aborted`) | +| `CommitUncertain` | the commit call panicked, or a restart found a `Committing` task with no recorded outcome | terminal: never run again, consumers revoked, bindings kept for good (a bound request delivered again is refused by the fence, `AlreadySubmitted`, instead of running unfenced; only a request under a new key, which nobody bound, runs as the original call, and the durable ledgers decide; `an_uncertain_commit_keeps_the_binding_so_the_request_stays_fenced`) | **an operator**: check the World and the approved replay ledger to learn whether the effect landed; M2 has no retry from this state (`Retry` needs `Aborted`) | | `FenceError::NotCommittable`, `NoCompletion`, `CompletionInvalid`, `StaleGeneration`, `AlreadySubmitted` | the fence checks failed | the call does not run | the workflow (finish the task, or bind again at the new generation) | ## 5. Restart semantics ```