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
GitHub aien-dev/aien-sovereign-core-mv#549 (code only)
Fetch it
curl -fsSL https://interplane.io/drakestapleton/aien-sovereign-core-mv/patches/047a745e84dc645d.bundle -o 047a745e84dc645d.bundle git fetch 047a745e84dc645d.bundle refs/pull/549/head
Provenance
github-import 1
aien-dev/aien-sovereign-core-mv
549
2db3be3edf2bf20bbef68e993580c5967c7bc0d5
{"kind":"github-import","owner":"aien-dev","repo":"aien-sovereign-core-mv","number":549,"url":"https://github.com/aien-dev/aien-sovereign-core-mv/pull/549","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:37:27Z","metadata":"unavailable","state_derived":true}
Changes
diff --git a/.crumb b/.crumb index e987dd6d..dad5cb69 100644 --- a/.crumb +++ b/.crumb @@ -101,7 +101,7 @@ }, { "digest": "02da31bc5e62df634962dded0755fa258e72011582658da2b12db450246d77ee", - "last_commit": "4204406", + "last_commit": "7d8c7b7", "name": "scripts", "purpose": "" }, @@ -119,14 +119,14 @@ } ], "children_root": "sha256:262c05d9c8ff17d17bc0dcef128f78b79376793a6fbbfe7bbd4398464bc75824", - "compiled_at": "2026-10-16T02:06:21Z", + "compiled_at": "2026-10-16T02:31:40Z", "compiler": "crumb-compile/1", - "digest": "sha256:c37f5c8ab1dedf1908111fad60d01b5e8c930d96cb09ff3e6ce65eea8d744eda", + "digest": "sha256:99d6da5e06eae997a4b71444d2430508030732f77dfe2ec93fca91bd833ef66b", "evidence_files": 1561, "evidence_root": "sha256:a315b980314448faf057152edf0a20aa28310d8ab4277d22762100ff444e3fa1", - "files": 5831, - "generated_at_commit": "68870a2239f2c8651385fd4d03729a20286cc954", - "source_tree": "sha256:c6598a6db9d3d69df88928f999fc64868fbb77068677c23fe27dc9959ad89bc9" + "files": 5834, + "generated_at_commit": "c01a3b0bb1c3da552f7a9cbc7db5bfc874f93f7f", + "source_tree": "sha256:43555d01cc68d93a650e82bcb792bfc95dd73ff4a423456708e952aa685d9e0f" } }, "history": [], diff --git a/Cargo.lock b/Cargo.lock index 2a21d2c4..4b5aba0b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -429,6 +429,7 @@ dependencies = [ "aien-omega-compose", "aien-omega-gpu", "aien-platform", + "aien-proof", "aien-runtime", "aien-scheduler", "aien-security", @@ -440,6 +441,7 @@ dependencies = [ "serde", "serde_json", "sha2 0.10.9", + "spark-harness", "tempfile", "thiserror 1.0.69", "tokio", diff --git a/crates/aien-runtime/Cargo.toml b/crates/aien-runtime/Cargo.toml index a6b3b453..33599751 100644 --- a/crates/aien-runtime/Cargo.toml +++ b/crates/aien-runtime/Cargo.toml @@ -21,6 +21,9 @@ aien-omega-compose = { path = "../aien-omega-compose" } aien-allen = { path = "../aien-allen" } aien-allen-profile = { path = "../aien-allen-profile" } aien-allen-memory = { path = "../aien-allen-memory" } +# Headstart M3 (#537): only with feature `provisional-prep`; absent from default builds. +spark-harness = { path = "../spark-harness", optional = true } +aien-proof = { path = "../aien-proof", optional = true } tokio = { version = "1.37", features = ["full"] } parking_lot = "0.12" @@ -40,6 +43,10 @@ fault-hold = [] # Test seams that bypass the reserved-record guard (`note_unchecked`, # `with_compose_bridge`). Enabled only by dev-dependencies, never by the daemon. test-support = [] +# Headstart M3 (#537): the opt-in provisional preparation adapter and final +# commit fence (src/provisional.rs). Default off: the default build compiles +# none of it and links neither spark-harness nor aien-proof. +provisional-prep = ["dep:spark-harness", "dep:aien-proof"] [dev-dependencies] aien-omega-gpu = { path = "../aien-omega-gpu" } diff --git a/crates/aien-runtime/src/lib.rs b/crates/aien-runtime/src/lib.rs index 9bd2fc3a..7b264dfb 100644 --- a/crates/aien-runtime/src/lib.rs +++ b/crates/aien-runtime/src/lib.rs @@ -16,6 +16,9 @@ pub mod generation; pub mod kv_residency; pub mod objective; pub mod persona; +/// Headstart M3 (#537): opt-in provisional preparation and final commit fence. +#[cfg(feature = "provisional-prep")] +pub mod provisional; pub mod requirements; mod requirements_extract; pub mod rsi; diff --git a/crates/aien-runtime/src/provisional.rs b/crates/aien-runtime/src/provisional.rs new file mode 100644 index 00000000..99bdba27 --- /dev/null +++ b/crates/aien-runtime/src/provisional.rs @@ -0,0 +1,1330 @@ +//! Provisional engineering preparation in front of the canonical compose +//! path (Headstart M3, issue #537). Compiled only with cargo feature +//! `provisional-prep` (default off); the default build has no trace of it and +//! the control ABI (`crate::control`) is the same in both builds: no command, +//! field or response is added. With the feature, a daemon given an adapter +//! (`AienRuntimeServer::with_prep_adapter`) sends a `ComposeApprovedProposal` +//! or `ComposeAuthorize` request through the fence only when +//! [`PrepAdapter::bind_approval`] bound it to a task generation; every other +//! request runs the original call unchanged. A binding is a journaled M2 +//! `BindApproval` event, so it survives a daemon restart (the replayed +//! scheduler still fences the request). M2 drops the bindings of a task only +//! when its commit ended (`Committed` or `CommitUncertain`) and refuses a +//! binding to such a task; the request is then unbound again, the daemon +//! runs it as the original call and the canonical durable guards decide (see +//! Duplicates below). An `Aborted` task (cancelled, failed, lease expired, a +//! failed commit, or an abort cascaded from an ancestor) keeps its bindings, +//! so its bound requests are refused (`NotCommittable`); after a retry they +//! name a superseded generation and are refused (`StaleGeneration`) until +//! they are bound again. A bound request never falls back to the unfenced +//! call while its task may still commit. Each task holds at most +//! `MAX_APPROVAL_BINDINGS_PER_TASK` keys; a new key past that is refused. +//! +//! Two halves: +//! +//! 1. Early preparation. [`PrepAdapter::prepare`] runs exactly one whitelisted +//! operation, [`PrepOperation::ComposePlanPreview`], for a task the M2 +//! scheduler (`spark_harness::scheduler`) has dispatched as `Provisional`. +//! It maps to [`OperationClass::ReadOnlyAnalysis`], so the M2 gate +//! `may_start` allows it on an interface-verified producer. The operation +//! is `compose::rederive::task_decision`: it reads the workspace to build +//! the compose prompt and destination for a goal and never writes +//! (bridge.rs `gather_inputs` doc: "Never writes"). No compose home is +//! opened, no model runs, no tool is called, nothing goes to the network. +//! The only output is an in-memory [`PreparationResult`] bound to each +//! producer's source commit, generation, artifact digest and the receipt +//! id the store verified. +//! +//! 2. Final commit fence. [`PrepAdapter::submit_approved`] (World commit +//! through `approved::ProposerHook::submit`) and +//! [`PrepAdapter::authorize`] (`effects::authorize_with_objective`, the +//! `ComposeAuthorize` path) run the existing call only when, for the +//! task's current generation: the M2 task is `Committable`, M2 +//! `may_finalize` passes (every producer final-verified, recursively), and +//! the task's own M1 completion receipt verifies (`verify_final`, which is +//! M1 `verify_completion`). The fence is a prerequisite only. Desk MAC, +//! AEGIS verify, the replay ledger, the effect ledger and the World commit +//! stay inside the unchanged calls and still decide. +//! +//! One task generation has one fenced call. Each bound flow has exactly +//! one durable step this daemon takes for it, so that step is the fence: +//! - `ComposeApprovedProposal` (`submit_approved`): the proposer hook +//! runs the World commit and writes its own grant in the same call +//! (approved.rs `submit`, `write_approved_grant`); it writes no +//! `compose_commit` record (compose/bridge.rs `run_task_inner` writes +//! one only when `approved_text` is None), so no later +//! `ComposeAuthorize` can mint against it. +//! - `RunComposeTask` then `ComposeAuthorize`: the run is a model call +//! this adapter does not fence (see Duplicates); its compose-commit +//! record is what `ComposeAuthorize` mints against (effects.rs). The +//! grant (`authorize`) is the fenced call, from `Committable`. +//! Both start from `Committable` with the same checks. +//! +//! No check-to-commit window, and no lock held across the call. The fence +//! checks run in one critical section that holds (a) the adapter mutex, the +//! only way to deliver a scheduler event, and (b) the harness store's +//! interface and completion locks (`<store>/interfaces/.lock`, +//! `<store>/completions/.lock`, the same aien-proof flock files +//! `publish_interface` and `complete_verified_workflow` take). The same +//! critical section ends with the journaled M2 `BeginCommit`, which moves +//! the task to `Committing` and freezes its generation, +//! its own completion claim and every producer's completion claim. That +//! event is the decision point. Both locks are then released and the +//! existing call runs. While the task is `Committing`, M2 refuses every +//! event that would change what was checked (`SchedError::CommitInProgress` +//! for a revoke, cancel, failure, proof change or new generation of the +//! task or any ancestor; a second commit in the same dependency chain), and +//! the M2 audit and lease expiry defer theirs. Store writes after the +//! decision cannot change the call: it runs on the proof taken under the +//! locks and never re-reads the store. The call's result is journaled as +//! `CommitOutcome` (`Committed`, `Failed` which aborts the task, or +//! `Uncertain` which is terminal); consumers are revoked on the last two. A +//! panic is recorded as `Uncertain`. A replay that finds a `Committing` task +//! with no outcome marks it `CommitUncertain` and never runs it again (the +//! approved replay ledger's rule for an in-flight claim). Heartbeats, other +//! fences and harness writers in every process proceed while a call runs. +//! +//! Refused events are not lost: an event M2 refuses with `CommitInProgress` +//! through [`PrepAdapter::deliver`] is queued ([`Delivered::Deferred`], at +//! most [`DEFERRED_CAPACITY`]; a full queue refuses the event with +//! [`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 +//! ([`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 +//! every drain or discard that changed it. A queue that cannot be written +//! refuses the event ([`DeliverError::DeferredJournal`]); a failed rewrite +//! after a drain is reported ([`Fenced::deferred_error`]) and the next +//! rewrite replaces it. On open, after the M2 audit settled every +//! interrupted commit, the journaled events are delivered again in order, so +//! a revoke or cancel deferred by a commit that never recorded its outcome +//! 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 +//! 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 +//! the M2 journal lock (`<journal>.lock`, held for the adapter's life; a +//! second open of the same journal is refused) and only then reads the +//! sidecar, whose name extends the journal's full file name, so distinct +//! journals never share one. +//! +//! Duplicates: a second fenced call for the same (task, generation) is +//! refused before the existing call runs ([`FenceError::AlreadySubmitted`] +//! in this process; M2 also refuses a second `BeginCommit` once the task +//! left `Committable`, across restarts too because it is journaled). +//! Across restarts the existing durable guards +//! decide: the approved replay ledger (`approved_replay::claim`) refuses a +//! claimed approval for ever and answers an exact retry with +//! `ALREADY_COMMITTED` without a second run; `ComposeAuthorize` refuses a +//! used desk nonce and a live or spent grant (effects.rs `AlreadyAuthorized`, +//! `AlreadySpent`). A model `RunComposeTask` run has no such durable guard, +//! so this adapter does not offer it. +//! +//! Invalidation: after every delivered event, preparation results whose task +//! is no longer active at the generation they were made for are dropped. M2 +//! returns consumers of a failed, cancelled, restarted or changed producer to +//! `Blocked` at a new generation (or `Aborted`), so their results go. A +//! result is also refused, not stored, when the task moved while the +//! operation ran. Results are never journaled: a restart discards them all. +//! +//! Resources: preparation runs on the caller's thread without the adapter +//! mutex, the compose home lock or the runtime spine lock. Only a +//! `Provisional` task with a live lease may prepare, and at most one +//! preparation per task is in flight, so concurrent preparations are bounded +//! by the M2 permits (`ResourceLimits::max_concurrency`). With +//! `ProvisionalConfig::enabled` false (the default) M2 dispatches a consumer +//! only after every producer is final, which is the sequential order. +//! +//! Not in scope: aien-trace is not used (observation is optional); no new +//! receipt type; AEGIS, World, KV and inference scheduling are unchanged. +//! spark-harness gains only the M2 `Committing` state and the +//! `BeginCommit`, `CommitOutcome` and `BindApproval` events. + +use crate::approved::{ApprovedComposeReport, ApprovedProposal, ApprovedRefusal, ProposerHook}; +use crate::compose::ComposeBridge; +use crate::control::{ControlResponse, DeskProof}; +use crate::effects::MintRequest; +use aien_proof::lock::FileLock; +use parking_lot::Mutex; +use serde::Serialize; +use sha2::{Digest, Sha256}; +use spark_harness::completion::CONSUMED_DIR; +use spark_harness::execution::TaskState; +use spark_harness::readiness::{ + verify_final, ArtifactReadiness, OperationClass, ReadinessLevel, INTERFACE_DIR, +}; +use spark_harness::scheduler::{ + Clock, CommitResult, Event, EventKind, Outcome, PermitPool, ProvisionalConfig, SchedError, + Scheduler, +}; +use std::collections::{BTreeMap, BTreeSet, VecDeque}; +use std::fmt; +use std::path::{Path, PathBuf}; + +/// The whitelist of early preparation operations. One entry. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum PrepOperation { + /// `compose::rederive::task_decision(goal, workspace)`: the compose + /// prompt and destination a goal would get. Reads the workspace only. + ComposePlanPreview, +} + +impl PrepOperation { + /// The M2 operation class the scheduler gates this operation as. + pub fn class(self) -> OperationClass { + match self { + PrepOperation::ComposePlanPreview => OperationClass::ReadOnlyAnalysis, + } + } + + pub fn as_str(self) -> &'static str { + match self { + PrepOperation::ComposePlanPreview => "compose_plan_preview", + } + } +} + +/// One producer artifact a result or a fence decision rests on, copied from +/// a store-verified [`ArtifactReadiness`]. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct ReadinessBinding { + pub producer_task: String, + pub source_commit: String, + pub producer_generation: u64, + pub artifact_digest: String, + pub receipt_id: String, + pub level: ReadinessLevel, +} + +impl From<&ArtifactReadiness> for ReadinessBinding { + fn from(r: &ArtifactReadiness) -> Self { + ReadinessBinding { + producer_task: r.producer_task().to_string(), + source_commit: r.source_commit().to_string(), + producer_generation: r.producer_generation(), + artifact_digest: r.artifact_digest().to_string(), + receipt_id: r.receipt_id().to_string(), + level: r.level(), + } + } +} + +/// A provisional preparation result. Built only by [`PrepAdapter::prepare`]; +/// no public constructor and no `Deserialize`. It authorizes nothing. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct PreparationResult { + task: String, + generation: u64, + operation: PrepOperation, + class: OperationClass, + plan_sha256: String, + destination: Option<String>, + bindings: Vec<ReadinessBinding>, +} + +impl PreparationResult { + pub fn task(&self) -> &str { + &self.task + } + pub fn generation(&self) -> u64 { + self.generation + } + pub fn operation(&self) -> PrepOperation { + self.operation + } + pub fn class(&self) -> OperationClass { + self.class + } + /// sha256 hex of the compose prompt the goal would get. + pub fn plan_sha256(&self) -> &str { + &self.plan_sha256 + } + pub fn destination(&self) -> Option<&str> { + self.destination.as_deref() + } + pub fn bindings(&self) -> &[ReadinessBinding] { + &self.bindings + } + /// True when at least one producer was only interface-verified. + pub fn is_provisional(&self) -> bool { + self.bindings + .iter() + .any(|b| b.level != ReadinessLevel::FinalVerified) + } +} + +/// What the fence verified, inside the same critical section as the call. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct FenceProof { + pub task: String, + pub generation: u64, + /// The task's own M1 completion. + pub completion: ReadinessBinding, + /// Every producer, final-verified (M2 `may_finalize`). + pub producers: Vec<ReadinessBinding>, +} + +/// The existing call's own answer, plus the fence proof it ran under. The +/// answer may still be a refusal: the fence does not decide authorization. +#[derive(Debug)] +pub struct Fenced<T> { + pub proof: FenceProof, + pub outcome: T, + /// How the M2 task ended (`CommitOutcome`), classified from `outcome`. + pub result: CommitResult, + /// Set when journaling the outcome failed: the task then stays + /// `Committing` (never re-run) until a restart marks it + /// `CommitUncertain`. + pub record_error: Option<SchedError>, + /// Deferred events delivered again right after the outcome. + pub redelivered: Vec<Redelivered>, + /// Set when rewriting the deferred sidecar after the drain failed. The + /// sidecar then still lists events M2 already applied; replaying them + /// on open is a duplicate, or a stale generation that stays queued + /// until discarded. The next rewrite replaces it. + pub deferred_error: Option<String>, +} + +/// Most events [`PrepAdapter::deliver`] holds back while commits run. +pub const DEFERRED_CAPACITY: usize = 64; + +/// Largest deferred sidecar [`PrepAdapter::open`] reads, in bytes. +pub const DEFERRED_MAX_BYTES: u64 = 4 * 1024 * 1024; + +/// Suffix of the deferred-event sidecar, appended to the journal's full +/// file name. A journal whose name ends with it is refused by +/// [`PrepAdapter::open`], so no journal is another journal's sidecar. +pub const DEFERRED_SUFFIX: &str = ".deferred"; + +/// The deferred-event sidecar of the M2 journal `journal`: +/// `<journal>.deferred`. Distinct journal paths give distinct sidecars. +pub fn deferred_journal_path(journal: &Path) -> PathBuf { + let mut name = journal.as_os_str().to_os_string(); + name.push(DEFERRED_SUFFIX); + PathBuf::from(name) +} + +/// What [`PrepAdapter::deliver`] did with an event. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Delivered { + /// M2 applied it, or recognised a duplicate. + Applied(Outcome), + /// M2 refused it because `committing` is committing. It is queued (at + /// position `queued`, from 1) and delivered again right after that + /// commit's outcome is recorded. + Deferred { committing: String, queued: usize }, +} + +#[derive(Debug)] +pub enum DeliverError { + Scheduler(SchedError), + /// `BeginCommit`, `CommitOutcome` and `BindApproval` go only through the + /// fence and [`PrepAdapter::bind_approval`]. + FenceOnly(&'static str), + /// The deferred queue is full: the event was not queued and not + /// applied; deliver it again later. + DeferredFull { + committing: String, + capacity: usize, + }, + /// The deferred sidecar could not be written: the event was not queued + /// and not applied; deliver it again later. + DeferredJournal(String), +} + +impl fmt::Display for DeliverError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + DeliverError::Scheduler(e) => write!(f, "DELIVER_REFUSED Scheduler: {e}"), + DeliverError::FenceOnly(k) => write!( + f, + "DELIVER_REFUSED FenceOnly: {k} events are delivered only by the fence" + ), + DeliverError::DeferredFull { + committing, + capacity, + } => write!( + f, + "DELIVER_REFUSED DeferredFull: task '{committing}' is committing and {capacity} events already wait; nothing was queued" + ), + DeliverError::DeferredJournal(e) => write!( + f, + "DELIVER_REFUSED DeferredJournal: the deferred queue could not be journaled ({e}); nothing was queued" + ), + } + } +} + +impl std::error::Error for DeliverError {} + +/// One deferred event delivered again after a commit outcome. +#[derive(Debug)] +pub struct Redelivered { + pub id: String, + pub result: Result<Outcome, SchedError>, +} + +#[derive(Debug)] +pub enum PrepError { + Scheduler(SchedError), + /// The caller's generation is not the task's current one. + StaleGeneration { + task: String, + expected: u64, + current: Option<u64>, + }, + /// A preparation for this task is already running. + Busy(String), + /// The task moved (revoked, cancelled, re-dispatched) while the + /// operation ran; the result was discarded. + Revoked { + task: String, + detail: String, + }, + /// The operation itself refused (for example a workspace escape). + Operation(String), +} + +impl fmt::Display for PrepError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + PrepError::Scheduler(e) => write!(f, "PREP_REFUSED Scheduler: {e}"), + PrepError::StaleGeneration { + task, + expected, + current, + } => write!( + f, + "PREP_REFUSED StaleGeneration: task '{task}' asked at generation {expected}, scheduler has {current:?}" + ), + PrepError::Busy(t) => write!(f, "PREP_REFUSED Busy: task '{t}' is already preparing"), + PrepError::Revoked { task, detail } => { + write!(f, "PREP_REFUSED Revoked: task '{task}': {detail}; result discarded") + } + PrepError::Operation(e) => write!(f, "PREP_REFUSED Operation: {e}"), + } + } +} + +impl std::error::Error for PrepError {} + +#[derive(Debug)] +pub enum FenceError { + /// M2 refused (`may_finalize`, unknown task). + Scheduler(SchedError), + StaleGeneration { + task: String, + expected: u64, + current: Option<u64>, + }, + NotCommittable { + task: String, + state: TaskState, + }, + /// The task has no accepted M1 completion for its current generation. + NoCompletion(String), + /// The task's own M1 completion receipt no longer verifies. + CompletionInvalid { + task: String, + error: String, + }, + /// This process already ran the fenced call for this task generation. + AlreadySubmitted { + task: String, + generation: u64, + }, + StoreLock(String), +} + +impl fmt::Display for FenceError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + FenceError::Scheduler(e) => write!(f, "FENCE_REFUSED Scheduler: {e}"), + FenceError::StaleGeneration { + task, + expected, + current, + } => write!( + f, + "FENCE_REFUSED StaleGeneration: task '{task}' asked at generation {expected}, scheduler has {current:?}" + ), + FenceError::NotCommittable { task, state } => write!( + f, + "FENCE_REFUSED NotCommittable: task '{task}' is {}", + state.as_str() + ), + FenceError::NoCompletion(t) => { + write!(f, "FENCE_REFUSED NoCompletion: task '{t}' has no accepted M1 completion") + } + FenceError::CompletionInvalid { task, error } => { + write!(f, "FENCE_REFUSED CompletionInvalid: task '{task}': {error}") + } + FenceError::AlreadySubmitted { task, generation } => write!( + f, + "FENCE_REFUSED AlreadySubmitted: task '{task}' generation {generation} already ran its fenced call" + ), + FenceError::StoreLock(e) => write!(f, "FENCE_REFUSED StoreLock: {e}"), + } + } +} + +impl std::error::Error for FenceError {} + +#[cfg(feature = "test-support")] +type PrepHook = std::sync::Arc<dyn Fn(&str) + Send + Sync>; + +struct Inner { + sched: Scheduler, + prepared: BTreeMap<String, PreparationResult>, + in_flight: BTreeSet<String>, + submitted: BTreeSet<(String, u64)>, + /// Events M2 refused with `CommitInProgress`, oldest first. + deferred: VecDeque<Event>, + /// Where `deferred` is journaled (journaled schedulers only). + deferred_path: Option<PathBuf>, + /// What replaying the journaled deferred events on open did. + replayed: Vec<Redelivered>, +} + +impl Inner { + fn current_generation(&self, task: &str, expected: u64) -> Result<(), Option<u64>> { + match self.sched.generation(task) { + Some(g) if g == expected => Ok(()), + other => Err(other), + } + } + + /// Drop every result whose task is no longer active at its generation. + fn prune(&mut self) { + let sched = &self.sched; + self.prepared.retain(|task, r| { + sched + .task(task) + .is_some_and(|t| t.state.is_active() && t.generation == r.generation) + }); + } + + /// Deliver every deferred event again, oldest first. Only an event M2 + /// applied or answered as a duplicate leaves the queue; 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 + /// that failed, is returned too. + fn redeliver(&mut self) -> (Vec<Redelivered>, Option<String>) { + let mut out = Vec::new(); + let mut keep = VecDeque::new(); + let before = self.deferred.len(); + while let Some(ev) = self.deferred.pop_front() { + match self.sched.deliver(ev.clone()) { + Err(SchedError::CommitInProgress { .. }) => keep.push_back(ev), + Ok(o) => out.push(Redelivered { + id: ev.id, + result: Ok(o), + }), + Err(e) => { + out.push(Redelivered { + id: ev.id.clone(), + result: Err(e), + }); + keep.push_back(ev); + } + } + } + self.deferred = keep; + self.prune(); + let error = if self.deferred.len() == before { + None + } else { + self.persist_deferred().err() + }; + (out, error) + } + + /// Rewrite the sidecar from `deferred` (no-op without a journal). + fn persist_deferred(&self) -> Result<(), String> { + let Some(path) = &self.deferred_path else { + return Ok(()); + }; + let mut buf = String::new(); + for ev in &self.deferred { + buf.push_str(&serde_json::to_string(ev).map_err(|e| e.to_string())?); + buf.push('\n'); + } + write_atomic(path, buf.as_bytes()).map_err(|e| format!("{}: {e}", path.display())) + } +} + +/// Temp file in the same directory, fsync, rename over `path`, fsync the +/// directory. The temp file is removed on failure. +fn write_atomic(path: &Path, bytes: &[u8]) -> std::io::Result<()> { + use std::io::Write; + let dir = path.parent().ok_or_else(|| { + std::io::Error::new( + std::io::ErrorKind::InvalidInput, + "sidecar has no parent dir", + ) + })?; + let name = path + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_default(); + let tmp = dir.join(format!(".{name}.tmp-{}", std::process::id())); + let result = (|| -> std::io::Result<()> { + let mut f = std::fs::File::create(&tmp)?; + f.write_all(bytes)?; + f.sync_all()?; + std::fs::rename(&tmp, path)?; + std::fs::File::open(dir)?.sync_all() + })(); + if result.is_err() { + let _ = std::fs::remove_file(&tmp); + } + result +} + +/// Read the deferred sidecar: absent is empty; anything that does not +/// parse, is too large, holds too many events or holds a fence-only event +/// is an error. +fn read_deferred(path: &Path) -> Result<VecDeque<Event>, SchedError> { + let bad = |what: String| SchedError::Journal(format!("{}: {what}", path.display())); + let len = match std::fs::metadata(path) { + Ok(m) => m.len(), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(VecDeque::new()), + Err(e) => return Err(bad(e.to_string())), + }; + if len > DEFERRED_MAX_BYTES { + return Err(bad(format!( + "{len} bytes, more than the {DEFERRED_MAX_BYTES} a deferred queue may hold" + ))); + } + let text = std::fs::read_to_string(path).map_err(|e| bad(e.to_string()))?; + let mut out = VecDeque::new(); + for (n, line) in text.lines().enumerate() { + if out.len() == DEFERRED_CAPACITY { + return Err(bad(format!( + "more than {DEFERRED_CAPACITY} deferred events" + ))); + } + let ev: Event = + serde_json::from_str(line).map_err(|e| bad(format!("line {}: {e}", n + 1)))?; + if fence_only(&ev.kind).is_some() { + return Err(bad(format!("line {}: a fence-only event", n + 1))); + } + out.push_back(ev); + } + Ok(out) +} + +/// `journal` with its directory (created if missing) and, when it exists, +/// the file itself resolved to canonical form, so every path to one journal +/// names the same lock file and sidecar. A name ending with +/// [`DEFERRED_SUFFIX`] is refused. +fn canonical_journal(journal: &Path) -> Result<PathBuf, SchedError> { + let bad = |what: String| SchedError::Journal(format!("{}: {what}", journal.display())); + let name = journal + .file_name() + .ok_or_else(|| bad("a journal path needs a file name".to_string()))?; + let dir = journal + .parent() + .filter(|d| !d.as_os_str().is_empty()) + .unwrap_or(Path::new(".")); + std::fs::create_dir_all(dir).map_err(|e| bad(e.to_string()))?; + let dir = std::fs::canonicalize(dir).map_err(|e| bad(e.to_string()))?; + let path = match std::fs::canonicalize(dir.join(name)) { + Ok(p) => p, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => dir.join(name), + Err(e) => return Err(bad(e.to_string())), + }; + if path + .as_os_str() + .to_string_lossy() + .ends_with(DEFERRED_SUFFIX) + { + return Err(bad(format!( + "a journal name may not end with {DEFERRED_SUFFIX}, the deferred sidecar suffix" + ))); + } + Ok(path) +} + +/// The fence's own event kinds, which only the fence delivers. +fn fence_only(kind: &EventKind) -> Option<&'static str> { + match kind { + EventKind::BeginCommit { .. } => Some("begin_commit"), + EventKind::CommitOutcome { .. } => Some("commit_outcome"), + EventKind::BindApproval { .. } => Some("bind_approval"), + _ => None, + } +} + +/// The adapter: owns the M2 scheduler for engineering tasks and fences the +/// existing compose commit calls. Share it behind an `Arc`; every method +/// takes `&self`. +pub struct PrepAdapter { + inner: Mutex<Inner>, + store: PathBuf, + #[cfg(feature = "test-support")] + prep_hook: Mutex<Option<PrepHook>>, + #[cfg(feature = "test-support")] + begin_hook: Mutex<Option<PrepHook>>, +} + +impl PrepAdapter { + fn with_scheduler(sched: Scheduler, store: &Path, deferred_path: Option<PathBuf>) -> Self { + PrepAdapter { + inner: Mutex::new(Inner { + sched, + prepared: BTreeMap::new(), + in_flight: BTreeSet::new(), + submitted: BTreeSet::new(), + deferred: VecDeque::new(), + deferred_path, + replayed: Vec::new(), + }), + store: store.to_path_buf(), + #[cfg(feature = "test-support")] + prep_hook: Mutex::new(None), + #[cfg(feature = "test-support")] + begin_hook: Mutex::new(None), + } + } + + /// In-memory scheduler over the harness store `store` + /// (`HarnessEngine::completion_store`). + pub fn new(cfg: ProvisionalConfig, store: &Path, clock: Clock) -> Result<Self, SchedError> { + Ok(Self::with_scheduler( + Scheduler::new(cfg, store, clock)?, + store, + None, + )) + } + + /// Journaled scheduler: create or replay `journal`, then run the M2 + /// audit before anything can use it (it settles every interrupted + /// commit as `CommitUncertain`), then deliver the journaled deferred + /// events again ([`PrepAdapter::take_replayed_deferred`]). Returns the + /// tasks the audit revoked. No preparation result survives: they are + /// never journaled. + pub fn open( + cfg: ProvisionalConfig, + store: &Path, + journal: &Path, + clock: Clock, + ) -> Result<(Self, Vec<String>), SchedError> { + let journal = canonical_journal(journal)?; + let (unaudited, _report) = Scheduler::open(cfg, store, &journal, clock)?; + // The M2 journal lock is held from here on, for the adapter's life: + // no other adapter reads or writes this sidecar. + let path = deferred_journal_path(&journal); + let deferred = read_deferred(&path)?; + let (sched, revoked) = unaudited.audit()?; + let adapter = Self::with_scheduler(sched, store, Some(path)); + { + let mut g = adapter.inner.lock(); + g.deferred = deferred; + // No commit is running after the audit, so every event is + // delivered; the refused ones stay queued, and the sidecar is + // rewritten if anything left. If that rewrite fails the open + // fails: the next open replays the same events. M2 answers the + // ones already applied as duplicates, or, once their generation + // moved on, refuses them as stale; refused ones stay queued. + let (replayed, error) = g.redeliver(); + if let Some(e) = error { + return Err(SchedError::Journal(e)); + } + g.replayed = replayed; + } + Ok((adapter, revoked)) + } + + /// What delivering the journaled deferred events on open did, oldest + /// first. Taken once; later calls return nothing. + pub fn take_replayed_deferred(&self) -> Vec<Redelivered> { + std::mem::take(&mut self.inner.lock().replayed) + } + + /// The runtime enable flag: M2 `ProvisionalConfig::enabled` (default + /// false, which is sequential dispatch). + pub fn enabled(&self) -> bool { + self.inner.lock().sched.config().enabled + } + + /// Deliver one M2 event, then drop the preparation results it + /// invalidated. An event M2 refuses because a commit is running is + /// queued and delivered again after that commit's outcome (see the + /// module docs). The fence's own event kinds are refused here. + pub fn deliver(&self, event: Event) -> Result<Delivered, DeliverError> { + if let Some(kind) = fence_only(&event.kind) { + return Err(DeliverError::FenceOnly(kind)); + } + let mut g = self.inner.lock(); + let r = g.sched.deliver(event.clone()); + g.prune(); + match r { + Ok(o) => Ok(Delivered::Applied(o)), + Err(SchedError::CommitInProgress { committing, .. }) => { + if let Some(i) = g.deferred.iter().position(|e| e.id == event.id) { + return if g.deferred[i] == event { + Ok(Delivered::Deferred { + committing, + queued: i + 1, + }) + } else { + Err(DeliverError::Scheduler(SchedError::EventIdConflict( + event.id, + ))) + }; + } + if g.deferred.len() >= DEFERRED_CAPACITY { + return Err(DeliverError::DeferredFull { + committing, + capacity: DEFERRED_CAPACITY, + }); + } + g.deferred.push_back(event); + // Journaled before `Deferred` is returned, so a crash + // before the drain still delivers it on the next open. + if let Err(e) = g.persist_deferred() { + g.deferred.pop_back(); + return Err(DeliverError::DeferredJournal(e)); + } + Ok(Delivered::Deferred { + committing, + queued: g.deferred.len(), + }) + } + Err(e) => Err(DeliverError::Scheduler(e)), + } + } + + /// How many deferred events are queued: waiting for a commit outcome, + /// or refused on redelivery and kept until discarded. + pub fn deferred_len(&self) -> usize { + self.inner.lock().deferred.len() + } + + /// The queued deferred events, oldest first. + pub fn deferred_events(&self) -> Vec<Event> { + self.inner.lock().deferred.iter().cloned().collect() + } + + /// Remove the queued deferred event `id` (the caller's decision about + /// an event M2 keeps refusing) and rewrite the sidecar. `Ok(None)` when + /// no such event is queued. If the rewrite fails the event stays queued + /// and the error is returned. + pub fn discard_deferred(&self, id: &str) -> Result<Option<Event>, DeliverError> { + let mut g = self.inner.lock(); + let Some(i) = g.deferred.iter().position(|e| e.id == id) else { + return Ok(None); + }; + let ev = g.deferred.remove(i).expect("position is in range"); + if let Err(e) = g.persist_deferred() { + g.deferred.insert(i, ev); + return Err(DeliverError::DeferredJournal(e)); + } + Ok(Some(ev)) + } + + /// Read-only access to the scheduler (state, generations, invariants, + /// timing trace). Holds the adapter mutex while `f` runs. + pub fn inspect<T>(&self, f: impl FnOnce(&Scheduler) -> T) -> T { + f(&self.inner.lock().sched) + } + + pub fn state(&self, task: &str) -> Option<TaskState> { + self.inner.lock().sched.state(task) + } + + pub fn generation(&self, task: &str) -> Option<u64> { + self.inner.lock().sched.generation(task) + } + + pub fn permits_in_use(&self) -> PermitPool { + self.inner.lock().sched.permits_in_use() + } + + /// The task's current preparation result, if it is still valid. + pub fn prepared(&self, task: &str) -> Option<PreparationResult> { + self.inner.lock().prepared.get(task).cloned() + } + + /// Test seam: called between the admission check and the operation, + /// outside the adapter mutex. + #[cfg(feature = "test-support")] + pub fn set_prep_hook(&self, hook: Option<PrepHook>) { + *self.prep_hook.lock() = hook; + } + + /// Run the whitelisted operation for `task` at `generation`. Admission: + /// current generation, no preparation in flight for the task, and M2 + /// `may_start(task, ReadOnlyAnalysis)` (a `Provisional` task with a live + /// lease, every producer bound at its current generation and + /// store-verified at a level that permits the class). The operation runs + /// outside the mutex; the result is stored only if the task is still at + /// the same generation and `may_start` passes again, both checked under + /// the mutex that stores it. + pub fn prepare( + &self, + task: &str, + generation: u64, + goal: &str, + workspace: &Path, + ) -> Result<PreparationResult, PrepError> { + let op = PrepOperation::ComposePlanPreview; + { + let mut g = self.inner.lock(); + g.current_generation(task, generation).map_err(|current| { + PrepError::StaleGeneration { + task: task.to_string(), + expected: generation, + current, + } + })?; + if g.in_flight.contains(task) { + return Err(PrepError::Busy(task.to_string())); + } + g.sched + .may_start(task, op.class()) + .map_err(PrepError::Scheduler)?; + g.in_flight.insert(task.to_string()); + } + #[cfg(feature = "test-support")] + { + let hook = self.prep_hook.lock().clone(); + if let Some(h) = hook { + h(task); + } + } + let out = plan_preview(goal, workspace); + let mut g = self.inner.lock(); + g.in_flight.remove(task); + let (plan_sha256, destination) = out.map_err(PrepError::Operation)?; + let revoked = |detail: String| PrepError::Revoked { + task: task.to_string(), + detail, + }; + g.current_generation(task, generation).map_err(|current| { + revoked(format!( + "generation moved from {generation} to {current:?} during preparation" + )) + })?; + // No separate binding comparison: M2 sets a task's bindings only when + // it dispatches it, and leaving `Provisional` always moves the task to + // a new generation first, so an unchanged generation means unchanged + // bindings. The readiness recorded below is the fresh one. + let readiness = g + .sched + .may_start(task, op.class()) + .map_err(|e| revoked(e.to_string()))?; + let result = PreparationResult { + task: task.to_string(), + generation, + operation: op, + class: op.class(), + plan_sha256, + destination, + bindings: readiness.iter().map(ReadinessBinding::from).collect(), + }; + g.prepared.insert(task.to_string(), result.clone()); + Ok(result) + } + + /// The harness store locks every interface and completion writer takes. + fn store_locks(&self) -> Result<[FileLock; 2], FenceError> { + let lock = |dir: &str| { + let d = self.store.join(dir); + std::fs::create_dir_all(&d) + .and_then(|_| FileLock::acquire(&d.join(".lock"))) + .map_err(|e| FenceError::StoreLock(format!("{}: {e}", d.display()))) + }; + Ok([lock(INTERFACE_DIR)?, lock(CONSUMED_DIR)?]) + } + + /// The fence (see the module docs). Under the adapter mutex and the store + /// locks: every check, then the journaled M2 `BeginCommit`, which moves + /// the task to `Committing` and freezes its inputs. Both locks are + /// released before `commit` runs. Its result, classified by `classify`, + /// is journaled as the M2 `CommitOutcome`, and the deferred events are + /// delivered again. A panic in `commit` is recorded as `Uncertain` and + /// then resumed. + fn fenced<T>( + &self, + task: &str, + generation: u64, + commit: impl FnOnce(&FenceProof) -> T, + classify: impl FnOnce(&T) -> CommitResult, + ) -> Result<Fenced<T>, FenceError> { + let proof = self.begin_commit(task, generation)?; + let ran = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| commit(&proof))); + let result = match &ran { + Ok(v) => classify(v), + Err(_) => CommitResult::Uncertain { + reason: "the fenced call panicked".to_string(), + }, + }; + let (recorded, redelivered, deferred_error) = + self.record_outcome(task, generation, result.clone()); + match ran { + Ok(outcome) => Ok(Fenced { + proof, + outcome, + result, + record_error: recorded.err(), + redelivered, + deferred_error, + }), + Err(panic) => std::panic::resume_unwind(panic), + } + } + + /// Check and transition, atomically: the fence checks and the journaled + /// `BeginCommit` under the adapter mutex and both store locks. + fn begin_commit(&self, task: &str, generation: u64) -> Result<FenceProof, FenceError> { + let mut g = self.inner.lock(); + let _store = self.store_locks()?; + let key = (task.to_string(), generation); + let submitted = || FenceError::AlreadySubmitted { + task: task.to_string(), + generation, + }; + if g.submitted.contains(&key) { + return Err(submitted()); + } + g.current_generation(task, generation) + .map_err(|current| FenceError::StaleGeneration { + task: task.to_string(), + expected: generation, + current, + })?; + let entry = g + .sched + .task(task) + .ok_or_else(|| FenceError::Scheduler(SchedError::UnknownTask(task.to_string())))?; + if entry.state != TaskState::Committable { + return Err(FenceError::NotCommittable { + task: task.to_string(), + state: entry.state, + }); + } + let claim = entry + .completion + .clone() + .ok_or_else(|| FenceError::NoCompletion(task.to_string()))?; + let mut inputs = BTreeMap::new(); + for p in entry.bindings.keys() { + let c = g.sched.task(p).and_then(|t| t.completion.clone()); + inputs.insert( + p.clone(), + c.ok_or_else(|| FenceError::NoCompletion(p.clone()))?, + ); + } + let producers = g.sched.may_finalize(task).map_err(FenceError::Scheduler)?; + let own = verify_final(&self.store, task, generation, &claim).map_err(|e| { + FenceError::CompletionInvalid { + task: task.to_string(), + error: e.to_string(), + } + })?; + #[cfg(feature = "test-support")] + if let Some(hook) = self.begin_hook.lock().clone() { + hook(task); + } + let begin = Event { + id: event_id("begin", task, generation), + kind: EventKind::BeginCommit { + task: task.to_string(), + generation, + completion: claim, + producers: inputs, + }, + }; + // M2 re-runs `may_finalize` and `verify_final` here + // (still under both locks), checks the inputs equal its state, + // refuses a second commit in the same chain, and journals the + // transition. + match g.sched.deliver(begin).map_err(FenceError::Scheduler)? { + Outcome::Applied(_) => {} + Outcome::Duplicate => return Err(submitted()), + } + // Spent before the call: a call that fails or panics is not retried + // at this generation (fail closed). + g.submitted.insert(key); + g.prune(); + Ok(FenceProof { + task: task.to_string(), + generation, + completion: ReadinessBinding::from(&own), + producers: producers.iter().map(ReadinessBinding::from).collect(), + }) + } + + /// Journal the commit outcome, then deliver the deferred events again, + /// under one lock. If journaling fails the task stays `Committing` + /// (frozen, never re-run) until a restart settles it as + /// `CommitUncertain`, and the deferred events refused by it stay queued + /// (in the sidecar too, so that open delivers them after the settle). + fn record_outcome( + &self, + task: &str, + generation: u64, + outcome: CommitResult, + ) -> (Result<(), SchedError>, Vec<Redelivered>, Option<String>) { + let mut g = self.inner.lock(); + let r = g.sched.deliver(Event { + id: event_id("outcome", task, generation), + kind: EventKind::CommitOutcome { + task: task.to_string(), + generation, + outcome, + }, + }); + g.prune(); + let (redelivered, deferred_error) = g.redeliver(); + (r.map(|_| ()), redelivered, deferred_error) + } + + /// Fenced `ComposeApprovedProposal`: the existing proposer hook (verify, + /// desk MAC, replay claim, compose run with AEGIS verify and World + /// commit, grant) runs unchanged once the fence passes. + pub fn submit_approved( + &self, + task: &str, + generation: u64, + hook: &ProposerHook, + proposal: &ApprovedProposal, + workspace: &str, + ) -> Result<Fenced<Result<ApprovedComposeReport, Box<ApprovedRefusal>>>, FenceError> { + self.fenced( + task, + generation, + |_| hook.submit(proposal, workspace), + classify_approved, + ) + } + + /// Fenced `ComposeAuthorize`, the grant against a compose commit an + /// unfenced `RunComposeTask` recorded: the existing grant minting (desk + /// MAC, compose-commit record match, confinement, nonce and grant + /// replay rules) runs unchanged once the fence passes. + pub fn authorize( + &self, + task: &str, + generation: u64, + bridge: &ComposeBridge, + req: &MintRequest, + desk_proof: Option<&DeskProof>, + objective_id: Option<&str>, + ) -> Result<Fenced<ControlResponse>, FenceError> { + self.fenced( + task, + generation, + |_| crate::effects::authorize_with_objective(bridge, req, desk_proof, objective_id), + classify_authorize, + ) + } + + /// Bind a control request to the M2 task generation whose fence it must + /// pass, as a journaled M2 `BindApproval`, so the binding survives a + /// restart. Only bound requests are fenced; the daemon runs every other + /// request exactly as before. A later binding for the same key replaces + /// the earlier one. M2 refuses a stale generation, a task whose commit + /// ended and a new key past the task's `MAX_APPROVAL_BINDINGS_PER_TASK`; + /// it drops the binding only when the task's commit ends (an aborted or + /// retried task keeps it, see the module docs). + pub fn bind_approval( + &self, + key: FenceKey, + task: &str, + generation: u64, + ) -> Result<Outcome, SchedError> { + let encoded = key.encoded(); + // Task ids hold no control characters, so the NUL separator keeps + // (key, task) pairs distinct. + let id = event_id("bind", &format!("{encoded}\0{task}"), generation); + let mut g = self.inner.lock(); + let r = g.sched.deliver(Event { + id, + kind: EventKind::BindApproval { + key: encoded, + task: task.to_string(), + generation, + }, + }); + g.prune(); + r + } + + /// The task generation `key` is bound to, if any (M2 state, so it + /// includes bindings replayed from the journal). + pub fn binding(&self, key: &FenceKey) -> Option<(String, u64)> { + let g = self.inner.lock(); + let b = g.sched.approval(&key.encoded())?; + Some((b.task.clone(), b.generation)) + } + + /// Daemon entry for `ComposeApprovedProposal`. None when the approval is + /// not bound (the caller runs the original call). A fence refusal is a + /// `FENCE_REFUSED` error and nothing runs. + pub fn route_approved( + &self, + bridge: &std::sync::Arc<ComposeBridge>, + proposal: &ApprovedProposal, + workspace: &str, + ) -> Option<ControlResponse> { + let (task, generation) = self.binding(&FenceKey::Approval(proposal.approval_id.clone()))?; + let hook = ProposerHook::new(bridge.clone()); + Some( + match self.submit_approved(&task, generation, &hook, proposal, workspace) { + Ok(f) => match f.outcome { + Ok(r) => ControlResponse::ComposeApprovedResult(Box::new(r)), + Err(r) => ControlResponse::ComposeApprovedRefused(r), + }, + Err(e) => ControlResponse::Error(e.to_string()), + }, + ) + } + + /// Daemon entry for `ComposeAuthorize`, keyed by the proposal digest. + /// None when it is not bound (the caller runs the original call). + pub fn route_authorize( + &self, + bridge: &ComposeBridge, + req: &MintRequest, + desk_proof: Option<&DeskProof>, + objective_id: Option<&str>, + ) -> Option<ControlResponse> { + let (task, generation) = self.binding(&FenceKey::Proposal(req.proposal_sha256.clone()))?; + Some( + match self.authorize(&task, generation, bridge, req, desk_proof, objective_id) { + Ok(f) => f.outcome, + Err(e) => ControlResponse::Error(e.to_string()), + }, + ) + } + + /// Test seam: the fence around an arbitrary call, so a test can act + /// while the call runs. `classify` maps its result to the outcome M2 + /// records. + #[cfg(feature = "test-support")] + pub fn fenced_for_tests<T>( + &self, + task: &str, + generation: u64, + commit: impl FnOnce(&FenceProof) -> T, + classify: impl FnOnce(&T) -> CommitResult, + ) -> Result<Fenced<T>, FenceError> { + self.fenced(task, generation, commit, classify) + } + + /// Test seam: called inside `begin_commit` after every check and before + /// the journaled `BeginCommit`, with the adapter mutex and both store + /// locks held. + #[cfg(feature = "test-support")] + pub fn set_begin_hook(&self, hook: Option<PrepHook>) { + *self.begin_hook.lock() = hook; + } +} + +/// Which control request a binding fences. +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] +pub enum FenceKey { + /// `ComposeApprovedProposal`, by `ApprovedProposal::approval_id`. + Approval(String), + /// `ComposeAuthorize`, by `MintRequest::proposal_sha256`. + Proposal(String), +} + +impl FenceKey { + /// The M2 binding key: the request kind and its id. + pub fn encoded(&self) -> String { + match self { + FenceKey::Approval(id) => format!("approval:{id}"), + FenceKey::Proposal(sha) => format!("proposal:{sha}"), + } + } +} + +/// A scheduler event id for this task generation: a fixed prefix and a +/// digest, so any task id fits the M2 identifier limit. +fn event_id(kind: &str, task: &str, generation: u64) -> String { + let mut h = Sha256::new(); + h.update(task.as_bytes()); + h.update([0]); + h.update(generation.to_be_bytes()); + let hex: String = h.finalize().iter().map(|b| format!("{b:02x}")).collect(); + format!("m3-{kind}-{hex}") +} + +/// What an approved submission did. Ok: committed (`COMMITTED`, or +/// `ALREADY_COMMITTED` for an exact retry). A refusal without a replay +/// claim came before `approved_replay::claim` (approved.rs `submit`: +/// verify, desk MAC, confinement, bound requirements): nothing durable. +/// `NotCommitted`: the ledger recorded `fail` (the World did not commit). +/// Anything else after a claim may have reached the World: uncertain. +pub fn classify_approved(r: &Result<ApprovedComposeReport, Box<ApprovedRefusal>>) -> CommitResult { + match r { + Ok(report) => CommitResult::Committed { + detail: report.state.clone(), + }, + Err(e) if e.replay_claim.is_none() || e.name == "NotCommitted" => CommitResult::Failed { + reason: e.to_string(), + }, + Err(e) => CommitResult::Uncertain { + reason: e.to_string(), + }, + } +} + +/// What `ComposeAuthorize` did. `ComposeNoted`: the grant was written. +/// `EFFECT_REFUSED`: refused by name before the only write (effects.rs +/// `authorize_inner`, every refusal precedes its `append`): nothing durable. +/// Any other error (for example a failed `append` or re-read) may have +/// written: uncertain. +pub fn classify_authorize(r: &ControlResponse) -> CommitResult { + match r { + ControlResponse::ComposeNoted(n) => CommitResult::Committed { + detail: format!("grant {}", n.id), + }, + ControlResponse::Error(e) if e.starts_with("EFFECT_REFUSED ") => { + CommitResult::Failed { reason: e.clone() } + } + other => CommitResult::Uncertain { + reason: format!("{other:?}").chars().take(512).collect(), + }, + } +} + +/// The whitelisted operation: compose prompt digest and destination. +fn plan_preview(goal: &str, workspace: &Path) -> Result<(String, Option<String>), String> { + let ((prompt, _edit, _kind), destination) = + crate::compose::rederive::task_decision(goal, workspace)?; + let digest = Sha256::digest(prompt.as_bytes()); + let hex: String = digest.iter().map(|b| format!("{b:02x}")).collect(); + Ok((hex, destination)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_whitelist_is_one_reversible_preparation_class() { + let op = PrepOperation::ComposePlanPreview; + assert_eq!(op.class(), OperationClass::ReadOnlyAnalysis); + assert!(op.class().is_reversible_preparation()); + assert!(ReadinessLevel::InterfaceVerified.permits(op.class())); + assert_eq!(op.as_str(), "compose_plan_preview"); + } +} diff --git a/crates/aien-runtime/src/server.rs b/crates/aien-runtime/src/server.rs index 68f38470..181ea4a8 100644 --- a/crates/aien-runtime/src/server.rs +++ b/crates/aien-runtime/src/server.rs @@ -83,6 +83,10 @@ pub struct AienRuntimeServer { /// = no generation record, see crate::generation). identity: std::sync::Mutex<Option<Arc<ModelIdentity>>>, started: DaemonStart, + /// Headstart M3 (#537): the provisional preparation adapter whose fence + /// bound compose commit requests pass (see `with_prep_adapter`). + #[cfg(feature = "provisional-prep")] + prep: std::sync::Mutex<Option<Arc<crate::provisional::PrepAdapter>>>, } /// NEXT-PHASE-1 v4 declared warm-up prompt (ACCEPTANCE-v4 Section 2(2)): @@ -111,9 +115,22 @@ impl AienRuntimeServer { compose_override: std::sync::Mutex::new(None), identity: std::sync::Mutex::new(None), started: DaemonStart::now(), + #[cfg(feature = "provisional-prep")] + prep: std::sync::Mutex::new(None), } } + /// Headstart M3 (#537): send `ComposeApprovedProposal` and + /// `ComposeAuthorize` requests that `adapter` has bound + /// (`PrepAdapter::bind_approval`) through its final commit fence. Unbound + /// requests run the original call unchanged. Without this call (the + /// default) nothing is fenced. + #[cfg(feature = "provisional-prep")] + pub fn with_prep_adapter(self, adapter: Arc<crate::provisional::PrepAdapter>) -> Self { + *self.prep.lock().expect("prep adapter") = Some(adapter); + self + } + /// Test seam: serve compose commands from `bridge` (for example one with a /// fixed proposer) instead of the bridge built from the environment and /// the loaded model. The daemon binary never calls this. @@ -294,6 +311,8 @@ impl AienRuntimeServer { .expect("compose override") .clone(); let identity = self.identity.lock().expect("identity lock").clone(); + #[cfg(feature = "provisional-prep")] + let prep = self.prep.lock().expect("prep adapter").clone(); // Correlation trace exporter (#398): on only when AIEN_TRACE_JSONL names // a file. Off, the bridge keeps a NullSink and emits nothing. The flusher // handle lives until the end of `run`, after the compose home closes, @@ -413,7 +432,10 @@ impl AienRuntimeServer { let identity_conn = identity.clone(); let started = self.started; let probe_conn = probe.clone(); + #[cfg(feature = "provisional-prep")] + let prep_conn = prep.clone(); tokio::spawn(async move { + #[cfg(not(feature = "provisional-prep"))] handle_connection( stream, spine_conn, @@ -424,6 +446,18 @@ impl AienRuntimeServer { (identity_conn, started), ) .await; + #[cfg(feature = "provisional-prep")] + handle_connection( + stream, + spine_conn, + is_running_conn, + notify_conn, + tokenizer_conn, + compose_conn, + (identity_conn, started), + prep_conn, + ) + .await; if let Some(line) = probe_conn.as_ref().and_then(|p| p.after_request()) { println!(" {line}"); } @@ -897,6 +931,7 @@ async fn stream_turn( } } +#[cfg_attr(feature = "provisional-prep", allow(clippy::too_many_arguments))] async fn handle_connection( stream: UnixStream, spine: Arc<Mutex<AienRuntimeSpine>>, @@ -905,6 +940,7 @@ async fn handle_connection( tokenizer: Arc<RwLock<Option<ChatTokenizer>>>, compose: Option<Arc<ComposeBridge>>, (identity, started): (Option<Arc<ModelIdentity>>, DaemonStart), + #[cfg(feature = "provisional-prep")] prep: Option<Arc<crate::provisional::PrepAdapter>>, ) { let (reader, mut writer) = stream.into_split(); let mut buf_reader = BufReader::new(reader); @@ -1002,7 +1038,16 @@ async fn handle_connection( }; let proof = desk_proof.clone(); let objective = objective_id.clone(); + #[cfg(feature = "provisional-prep")] + let fence = prep.clone(); Some(Box::new(move |b: &Arc<ComposeBridge>| { + // Headstart M3: a bound request passes the fence instead. + #[cfg(feature = "provisional-prep")] + if let Some(r) = fence.as_ref().and_then(|a| { + a.route_authorize(b, &req, proof.as_ref(), objective.as_deref()) + }) { + return r; + } crate::effects::authorize_with_objective( b, &req, @@ -1061,7 +1106,14 @@ async fn handle_connection( ref workspace, } => { let (p, w) = (proposal.clone(), workspace.clone()); + #[cfg(feature = "provisional-prep")] + let fence = prep.clone(); Some(Box::new(move |b: &Arc<ComposeBridge>| { + // Headstart M3: a bound request passes the fence instead. + #[cfg(feature = "provisional-prep")] + if let Some(r) = fence.as_ref().and_then(|a| a.route_approved(b, &p, &w)) { + return r; + } match crate::approved::ProposerHook::new(b.clone()).submit(&p, &w) { Ok(r) => ControlResponse::ComposeApprovedResult(Box::new(r)), Err(r) => ControlResponse::ComposeApprovedRefused(r), diff --git a/crates/aien-runtime/tests/provisional_prep_test.rs b/crates/aien-runtime/tests/provisional_prep_test.rs new file mode 100644 index 00000000..59f7beb3 --- /dev/null +++ b/crates/aien-runtime/tests/provisional_prep_test.rs @@ -0,0 +1,2841 @@ +//! Headstart M3 (#537): provisional engineering preparation and the final +//! commit fence (crate::provisional). Compiled only with +//! `--features provisional-prep`; without it this binary holds no tests. +//! +//! The M2 scheduler and the M1/M2 harness store are real (spark-harness, +//! shipped workflow and eval definitions). The World commit is the real +//! approved-proposal path; tests that need it to commit run fully only in a +//! linked build (cfg compose_linked) and check the stub refusal otherwise. +//! Timing lines start with `M3-TIMING` (run with `--nocapture`). +#![cfg(feature = "provisional-prep")] + +#[path = "support/home_guard.rs"] +mod home_guard; + +use aien_omega_compose::hex; +use aien_runtime::approved::{ + ApprovedComposeReport, ApprovedProposal, ApprovedRefusal, ProposerHook, +}; +use aien_runtime::approved_auth::{desk_key_path, AuthorizeBinding, DeskKey}; +use aien_runtime::control::{ControlCommand, ControlResponse, DeskProof}; +use aien_runtime::effects::MintRequest; +use aien_runtime::provisional::{ + classify_approved, classify_authorize, deferred_journal_path, DeliverError, Delivered, + FenceError, FenceKey, PrepAdapter, PrepError, PrepOperation, DEFERRED_CAPACITY, + DEFERRED_MAX_BYTES, +}; +use aien_runtime::{ComposeBridge, ComposeProposer}; +use serde_json::{json, Value}; +use sha2::{Digest, Sha256}; +use spark_harness::completion::CompletionSubmission; +use spark_harness::execution::TaskState; +use spark_harness::readiness::{InterfaceSubmission, OperationClass, ProofClaim, ReadinessLevel}; +use spark_harness::scheduler::{ + Clock, CommitResult, Effects, Event, EventKind, Outcome, ProvisionalConfig, ResourceLimits, + ResourceRequest, SchedError, +}; +use spark_harness::{HarnessEngine, WorkflowState}; +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{mpsc, Arc}; +use std::time::{Duration, Instant}; + +const COMMIT: &str = "1111111111111111111111111111111111111111"; +const PATH: &str = "NOTES.md"; +const CONTENT: &str = "approved after the producers were final\n"; +const GOAL: &str = "Write NOTES.md: one line about the parser interface"; + +// ---------- harness store and scheduler ---------- + +fn fixed_receipt_clock() -> u64 { + 1_760_000_000 +} + +fn cfg(enabled: bool, max_concurrency: u32) -> ProvisionalConfig { + ProvisionalConfig { + enabled, + queue_capacity: 8, + limits: ResourceLimits { + cpu_slots: 8, + memory_bytes: 1 << 30, + max_concurrency, + }, + lease_ttl: 1_000_000, + dedup_window: 64, + } +} + +fn clock(t: &Arc<AtomicU64>) -> Clock { + let t = Arc::clone(t); + Box::new(move || t.load(Ordering::SeqCst)) +} + +fn copy_definitions(dir: &Path) { + let src = Path::new(env!("CARGO_MANIFEST_DIR")).join("../spark-harness"); + std::fs::create_dir_all(dir.join("schemas")).unwrap(); + for f in ["workflows.json", "evals.json"] { + std::fs::copy(src.join(f), dir.join(f)).unwrap(); + } + for e in std::fs::read_dir(src.join("schemas")).unwrap() { + let e = e.unwrap(); + std::fs::copy(e.path(), dir.join("schemas").join(e.file_name())).unwrap(); + } +} + +fn artifact(task: &str) -> Value { + json!({ + "bug": format!("Parser rejects valid token sequence in {task}"), + "reproduction_steps": ["Run parser test"], + "failure_evidence": "thread panicked at line 42", + "regression_test": "tests::test_parser", + "diff_summary": "Fixed token parser logic", + "retest_evidence": "All tests passing cleanly" + }) +} + +/// One adapter, its harness store, a compose home and a workspace, all in +/// one temp dir: `<tmp>/harness`, `<tmp>/compose`, `<tmp>/ws`. +struct H { + tmp: tempfile::TempDir, + engine: HarnessEngine, + ticks: Arc<AtomicU64>, + adapter: Arc<PrepAdapter>, + n: u64, +} + +impl H { + fn new(c: ProvisionalConfig) -> Self { + Self::build(c, false) + } + + fn journaled(c: ProvisionalConfig) -> Self { + Self::build(c, true) + } + + fn build(c: ProvisionalConfig, journaled: bool) -> Self { + let tmp = tempfile::tempdir().unwrap(); + let hd = tmp.path().join("harness"); + copy_definitions(&hd); + std::fs::create_dir_all(tmp.path().join("ws")).unwrap(); + let mut engine = HarnessEngine::load(&hd).expect("shipped definitions load"); + engine.completion_clock = fixed_receipt_clock; + let ticks = Arc::new(AtomicU64::new(0)); + let adapter = if journaled { + let (a, revoked) = PrepAdapter::open( + c, + &engine.completion_store, + &tmp.path().join("journal.jsonl"), + clock(&ticks), + ) + .unwrap(); + assert!(revoked.is_empty()); + a + } else { + PrepAdapter::new(c, &engine.completion_store, clock(&ticks)).unwrap() + }; + H { + tmp, + engine, + ticks, + adapter: Arc::new(adapter), + n: 0, + } + } + + /// A daemon restart: drop the adapter, replay its journal, audit. + fn restart(&mut self, c: ProvisionalConfig) -> Vec<String> { + let placeholder = + PrepAdapter::new(c.clone(), &self.engine.completion_store, clock(&self.ticks)).unwrap(); + drop(std::mem::replace(&mut self.adapter, Arc::new(placeholder))); + self.ticks.store(0, Ordering::SeqCst); + let (a, revoked) = PrepAdapter::open( + c, + &self.engine.completion_store, + &self.tmp.path().join("journal.jsonl"), + clock(&self.ticks), + ) + .unwrap(); + self.adapter = Arc::new(a); + revoked + } + + fn ws(&self) -> PathBuf { + self.tmp.path().join("ws") + } + + fn deliver(&mut self, kind: EventKind) -> Result<Delivered, DeliverError> { + self.n += 1; + self.ticks.fetch_add(10, Ordering::SeqCst); + let r = self.adapter.deliver(Event { + id: format!("ev-{}", self.n), + kind, + }); + self.adapter.inspect(|s| s.check_invariants()).unwrap(); + r + } + + /// An event no commit holds back: applied, or refused by M2. + fn send(&mut self, kind: EventKind) -> Result<Outcome, SchedError> { + match self.deliver(kind) { + Ok(Delivered::Applied(o)) => Ok(o), + Err(DeliverError::Scheduler(e)) => Err(e), + other => panic!("not applied or refused by M2: {other:?}"), + } + } + + fn ok(&mut self, kind: EventKind) -> Effects { + match self.send(kind.clone()) { + Ok(Outcome::Applied(fx)) => fx, + other => panic!("{kind:?} not applied: {other:?}"), + } + } + + fn gen(&self, task: &str) -> u64 { + self.adapter.generation(task).unwrap() + } + + fn state(&self, task: &str) -> TaskState { + self.adapter.state(task).unwrap() + } + + fn register(&mut self, task: &str, producers: &[&str]) -> Effects { + self.ok(EventKind::RegisterTask { + task: task.into(), + resources: ResourceRequest { + cpu_slots: 1, + memory_bytes: 1 << 20, + }, + producers: producers.iter().map(|p| p.to_string()).collect(), + }) + } + + fn mint_interface(&self, task: &str, version: u32) -> ProofClaim { + self.engine + .publish_interface(&InterfaceSubmission { + task_id: task.into(), + generation: self.gen(task), + source_commit: COMMIT.into(), + interface: json!({ "task": task, "api_version": version }), + }) + .unwrap() + .claim() + } + + fn publish(&mut self, task: &str, version: u32) -> (ProofClaim, Effects) { + let claim = self.mint_interface(task, version); + let generation = self.gen(task); + let fx = self.ok(EventKind::InterfacePublished { + task: task.into(), + generation, + claim: claim.clone(), + }); + (claim, fx) + } + + fn mint_completion(&self, task: &str) -> ProofClaim { + let mut wf = WorkflowState { + id: format!("wf-{task}"), + workflow_type: "engineering_fix".into(), + current_state: "review".into(), + history: Vec::new(), + created_at: "2026-10-15T00:00:00Z".into(), + }; + let rec = self + .engine + .complete_verified_workflow( + &mut wf, + &CompletionSubmission { + task_id: task.into(), + generation: self.gen(task), + source_commit: COMMIT.into(), + artifact: artifact(task), + }, + ) + .unwrap(); + ProofClaim { + receipt_id: rec.receipt_id, + commit: rec.source_commit, + digest: rec.artifact_digest, + } + } + + fn work_done(&mut self, task: &str) { + let generation = self.gen(task); + self.ok(EventKind::WorkDone { + task: task.into(), + generation, + result_digest: format!("result-of-{task}"), + }); + } + + fn finalize(&mut self, task: &str) { + let generation = self.gen(task); + self.ok(EventKind::Finalize { + task: task.into(), + generation, + }); + } + + fn complete(&mut self, task: &str) -> ProofClaim { + let claim = self.mint_completion(task); + let generation = self.gen(task); + self.ok(EventKind::CompletionVerified { + task: task.into(), + generation, + claim: claim.clone(), + }); + claim + } + + /// Work done, finalize, M1 completion: the task is final and committable. + fn finish(&mut self, task: &str) { + self.work_done(task); + self.finalize(task); + self.complete(task); + assert_eq!(self.state(task), TaskState::Committable); + } + + fn prepare( + &self, + task: &str, + ) -> Result<aien_runtime::provisional::PreparationResult, PrepError> { + self.adapter.prepare(task, self.gen(task), GOAL, &self.ws()) + } +} + +// ---------- compose home and approvals ---------- + +fn model_never_called() -> ComposeProposer { + Arc::new(|_: &str, _: Duration| panic!("the model proposer ran on the approved path")) +} + +fn sha(b: &[u8]) -> String { + hex(&Sha256::digest(b)) +} + +fn interplane_sha(path: &str, content: &str) -> String { + let s = format!( + "{{\"content\":{},\"path\":{}}}", + serde_json::to_string(content).unwrap(), + serde_json::to_string(path).unwrap() + ); + sha(s.as_bytes()) +} + +struct Compose { + bridge: Arc<ComposeBridge>, + hook: ProposerHook, + ws: String, +} + +impl Compose { + fn new(h: &H) -> Self { + DeskKey::create(&desk_key_path(&h.tmp.path().join("compose"))).unwrap(); + Self::reopen(h) + } + + /// A fresh bridge on the same compose home and desk key (a daemon restart). + fn reopen(h: &H) -> Self { + let bridge = Arc::new(ComposeBridge::new( + h.tmp.path().join("compose"), + model_never_called(), + "test:model-never-called", + )); + let hook = ProposerHook::new(bridge.clone()); + Compose { + bridge, + hook, + ws: h.ws().display().to_string(), + } + } + + /// An approval sealed with this home's desk key. + fn approval(&self, request: &str) -> ApprovedProposal { + let mut p = ApprovedProposal { + request_id: request.into(), + trace_id: format!("trace-{request}"), + approval_id: format!("appr-{request}"), + approver: "interplane-host".into(), + path: PATH.into(), + content: CONTENT.into(), + approved_proposal_sha256: interplane_sha(PATH, CONTENT), + content_sha256: sha(CONTENT.as_bytes()), + approval_mac: String::new(), + requirements: Some(String::new()), + requirements_mac: String::new(), + requirements_base: None, + }; + DeskKey::load(&desk_key_path(self.bridge.dir())) + .unwrap() + .seal(&mut p, Path::new(&self.ws)); + p + } +} + +type Submit = Result<ApprovedComposeReport, Box<ApprovedRefusal>>; + +/// The canonical path's answer for a valid approval: COMMITTED when linked, +/// the stub refusal otherwise. Returns the report when linked. +fn committed_or_stub(r: Submit) -> Option<ApprovedComposeReport> { + if !aien_omega_compose::LINKED { + let e = r.expect_err("stub build must refuse"); + assert!( + e.refused_by == "REPLAY_REFUSED" || e.name == "ComposeError", + "{e}" + ); + return None; + } + let r = r.unwrap_or_else(|e| panic!("want COMMITTED, got {e}")); + assert_eq!(r.state, "COMMITTED"); + let t = r.task.as_ref().expect("a compose run"); + assert!(t.committed && t.cx_promotion != 0, "{t:?}"); + Some(r) +} + +/// Every file under `dir` with its sha256, for "nothing was written" checks. +fn tree(dir: &Path) -> BTreeMap<PathBuf, String> { + let mut out = BTreeMap::new(); + let mut stack = vec![dir.to_path_buf()]; + while let Some(d) = stack.pop() { + let Ok(rd) = std::fs::read_dir(&d) else { + continue; + }; + for e in rd.flatten() { + let p = e.path(); + if p.is_dir() { + stack.push(p); + } else { + out.insert(p.clone(), sha(&std::fs::read(&p).unwrap_or_default())); + } + } + } + out +} + +/// Classifier for `fenced_for_tests`: the call committed. +fn committed<T>(_: &T) -> CommitResult { + CommitResult::Committed { + detail: "test".into(), + } +} + +fn fence_err<T: std::fmt::Debug>(r: Result<T, FenceError>) -> FenceError { + match r { + Err(e) => e, + Ok(v) => panic!("the fence let a call through: {v:?}"), + } +} + +// ---------- tests ---------- + +#[test] +fn the_one_whitelisted_operation_is_read_only_analysis() { + let op = PrepOperation::ComposePlanPreview; + assert_eq!(op.class(), OperationClass::ReadOnlyAnalysis); + for c in OperationClass::ALL { + if c != OperationClass::ReadOnlyAnalysis { + assert_ne!(op.class(), c); + } + } +} + +struct Timing { + critical_ms: f64, + overlap_ms: f64, + prep_ms: f64, + prep_started_before_producer_final: bool, +} + +const PRODUCER_WORK: Duration = Duration::from_millis(60); +const PREP_LOAD: Duration = Duration::from_millis(40); + +fn ms(d: Duration) -> f64 { + d.as_secs_f64() * 1000.0 +} + +/// Producer A (60 ms of simulated work on another thread) and consumer B, +/// whose preparation is the real whitelisted operation plus 40 ms of +/// simulated preparation load (the test hook, outside the adapter mutex). +/// Ends with B's fenced World commit through the approved path. +fn two_stage(enabled: bool) -> Timing { + let mut h = H::new(cfg(enabled, 4)); + let c = Compose::new(&h); + h.adapter + .set_prep_hook(Some(Arc::new(|_: &str| std::thread::sleep(PREP_LOAD)))); + h.register("a", &[]); + h.register("b", &["a"]); + h.publish("a", 1); + let t0 = Instant::now(); + let producer = std::thread::spawn(move || { + std::thread::sleep(PRODUCER_WORK); + Instant::now() + }); + let mut prep = None; + if enabled { + assert_eq!(h.state("b"), TaskState::Provisional); + let s = Instant::now(); + let r = h.prepare("b").expect("early preparation"); + assert!(r.is_provisional(), "bound to an interface, not a final"); + prep = Some((s, Instant::now())); + } else { + assert_eq!(h.state("b"), TaskState::Blocked); + assert!(matches!( + h.prepare("b"), + Err(PrepError::Scheduler(SchedError::WrongState { .. })) + )); + } + let producer_end = producer.join().unwrap(); + h.finish("a"); + if !enabled { + assert_eq!(h.state("b"), TaskState::Provisional); + let s = Instant::now(); + let r = h.prepare("b").expect("sequential preparation"); + assert!(!r.is_provisional()); + prep = Some((s, Instant::now())); + } + h.finish("b"); + let _home = home_guard::home_slot(); + let g = h.gen("b"); + let out = h + .adapter + .submit_approved("b", g, &c.hook, &c.approval("req-two"), &c.ws) + .expect("fence passes"); + committed_or_stub(out.outcome); + let end = Instant::now(); + let (ps, pe) = prep.unwrap(); + let overlap = pe.min(producer_end).saturating_duration_since(ps.max(t0)); + Timing { + critical_ms: ms(end - t0), + overlap_ms: ms(overlap), + prep_ms: ms(pe - ps), + prep_started_before_producer_final: ps < producer_end, + } +} + +#[test] +fn two_stage_overlap_measured_against_the_sequential_fallback() { + let on = two_stage(true); + let off = two_stage(false); + for (name, t) in [("enabled", &on), ("disabled", &off)] { + eprintln!( + "M3-TIMING two_stage {name}: critical_path_ms={:.2} prep_ms={:.2} overlap_ms={:.2} producer_work_ms={} prep_load_ms={} linked={}", + t.critical_ms, + t.prep_ms, + t.overlap_ms, + PRODUCER_WORK.as_millis(), + PREP_LOAD.as_millis(), + aien_omega_compose::LINKED + ); + } + assert!(on.prep_started_before_producer_final && on.overlap_ms > 0.0); + assert!(!off.prep_started_before_producer_final); + assert_eq!(off.overlap_ms, 0.0, "disabled means no early start"); +} + +#[test] +fn three_stage_chain_prepares_two_consumers_while_the_root_runs() { + let _home = home_guard::home_slot(); + let mut h = H::new(cfg(true, 4)); + let c = Compose::new(&h); + h.register("a", &[]); + h.register("b", &["a"]); + h.register("c", &["b"]); + let (ia, _) = h.publish("a", 1); + assert_eq!(h.state("b"), TaskState::Provisional); + let (ib, _) = h.publish("b", 1); + assert_eq!(h.state("c"), TaskState::Provisional); + let t0 = Instant::now(); + let rb = h.prepare("b").unwrap(); + let rc = h.prepare("c").unwrap(); + eprintln!( + "M3-TIMING three_stage: two preparations while the root is not final took {:.3} ms", + ms(t0.elapsed()) + ); + assert_eq!(h.state("a"), TaskState::Provisional, "root still running"); + // Each result is bound to its producer's interface receipt. + let b0 = &rb.bindings()[0]; + assert_eq!( + (b0.producer_task.as_str(), b0.receipt_id.as_str()), + ("a", ia.receipt_id.as_str()) + ); + assert_eq!( + (b0.source_commit.as_str(), b0.artifact_digest.as_str()), + (COMMIT, ia.digest.as_str()) + ); + assert_eq!(b0.producer_generation, 1); + assert_eq!(b0.level, ReadinessLevel::InterfaceVerified); + assert_eq!(rc.bindings()[0].receipt_id, ib.receipt_id); + assert_eq!(rc.operation(), PrepOperation::ComposePlanPreview); + assert_eq!(rc.class(), OperationClass::ReadOnlyAnalysis); + assert_eq!(rc.plan_sha256().len(), 64); + // The fence refuses C until the whole chain is final. + let gc = h.gen("c"); + let p = c.approval("req-three"); + assert!(matches!( + fence_err(h.adapter.submit_approved("c", gc, &c.hook, &p, &c.ws)), + FenceError::NotCommittable { .. } + )); + h.finish("a"); + h.finish("b"); + h.work_done("c"); + h.finalize("c"); + // Committable but without its own M1 completion: still refused. + assert!(matches!( + fence_err(h.adapter.submit_approved("c", gc, &c.hook, &p, &c.ws)), + FenceError::NoCompletion(_) + )); + h.complete("c"); + let out = h + .adapter + .submit_approved("c", gc, &c.hook, &p, &c.ws) + .expect("fence passes once A, B and C are final"); + assert_eq!(out.proof.producers.len(), 1); + assert_eq!(out.proof.producers[0].level, ReadinessLevel::FinalVerified); + assert_eq!(out.proof.completion.level, ReadinessLevel::FinalVerified); + committed_or_stub(out.outcome); +} + +#[test] +fn failed_producer_discards_the_dependent_result() { + let mut h = H::new(cfg(true, 4)); + h.register("a", &[]); + h.register("b", &["a"]); + h.publish("a", 1); + h.prepare("b").unwrap(); + assert!(h.adapter.prepared("b").is_some()); + h.ok(EventKind::ProducerFailed { + task: "a".into(), + generation: 1, + reason: "tests failed".into(), + }); + assert_eq!((h.state("b"), h.gen("b")), (TaskState::Blocked, 2)); + assert!(h.adapter.prepared("b").is_none(), "result discarded"); + assert!(matches!( + h.adapter.prepare("b", 1, GOAL, &h.ws()), + Err(PrepError::StaleGeneration { .. }) + )); + assert!(matches!( + fence_err(h.adapter.fenced_for_tests("b", 1, |_| (), committed)), + FenceError::StaleGeneration { .. } + )); +} + +#[test] +fn completed_producer_upgrades_the_binding_to_final() { + let mut h = H::new(cfg(true, 4)); + h.register("a", &[]); + h.register("b", &["a"]); + h.publish("a", 1); + assert!(h.prepare("b").unwrap().is_provisional()); + h.finish("a"); + let r = h.prepare("b").unwrap(); + assert!(!r.is_provisional()); + assert_eq!(r.bindings()[0].level, ReadinessLevel::FinalVerified); +} + +#[test] +fn changed_interface_revokes_and_rebinds_to_the_new_receipt() { + let mut h = H::new(cfg(true, 4)); + h.register("a", &[]); + h.register("b", &["a"]); + let (v1, _) = h.publish("a", 1); + assert_eq!( + h.prepare("b").unwrap().bindings()[0].receipt_id, + v1.receipt_id + ); + let (v2, fx) = h.publish("a", 2); + assert_ne!(v1.receipt_id, v2.receipt_id); + assert!(fx.revoked.contains(&"b".to_string())); + assert!(h.adapter.prepared("b").is_none()); + assert_eq!((h.state("b"), h.gen("b")), (TaskState::Provisional, 2)); + let r = h.prepare("b").unwrap(); + assert_eq!( + (r.generation(), r.bindings()[0].receipt_id.as_str()), + (2, v2.receipt_id.as_str()) + ); +} + +#[test] +fn new_producer_generation_makes_old_generations_stale() { + let mut h = H::new(cfg(true, 4)); + h.register("a", &[]); + h.register("b", &["a"]); + h.publish("a", 1); + h.prepare("b").unwrap(); + h.ok(EventKind::NewGeneration { + task: "a".into(), + generation: 2, + }); + assert!(h.adapter.prepared("b").is_none()); + assert_eq!(h.gen("b"), 2); + for g in [1, 3] { + assert!(matches!( + h.adapter.prepare("b", g, GOAL, &h.ws()), + Err(PrepError::StaleGeneration { .. }) + )); + } +} + +#[test] +fn cancellation_discards_results_and_refuses_preparation() { + let mut h = H::new(cfg(true, 4)); + h.register("a", &[]); + h.register("b", &["a"]); + h.publish("a", 1); + h.prepare("b").unwrap(); + h.ok(EventKind::Cancel { + task: "a".into(), + generation: 1, + }); + assert_eq!(h.state("b"), TaskState::Aborted); + assert!(h.adapter.prepared("b").is_none()); + assert!(matches!( + h.prepare("b"), + Err(PrepError::Scheduler(SchedError::WrongState { .. })) + )); +} + +#[test] +fn duplicate_event_is_a_noop_and_keeps_the_result() { + let mut h = H::new(cfg(true, 4)); + h.register("a", &[]); + h.register("b", &["a"]); + let claim = h.mint_interface("a", 1); + let ev = Event { + id: "publish-a".into(), + kind: EventKind::InterfacePublished { + task: "a".into(), + generation: 1, + claim, + }, + }; + assert!(matches!( + h.adapter.deliver(ev.clone()), + Ok(Delivered::Applied(Outcome::Applied(_))) + )); + let r = h.prepare("b").unwrap(); + assert_eq!( + h.adapter.deliver(ev).unwrap(), + Delivered::Applied(Outcome::Duplicate) + ); + assert_eq!(h.adapter.prepared("b"), Some(r)); + assert_eq!(h.gen("b"), 1); +} + +#[test] +fn invalid_receipts_are_refused_by_the_event_gate_and_the_fence() { + let mut h = H::new(cfg(true, 4)); + h.register("a", &[]); + h.register("b", &["a"]); + // A claim naming no stored receipt never reaches the scheduler. + let forged = ProofClaim { + receipt_id: "ab".repeat(32), + commit: COMMIT.into(), + digest: "cd".repeat(32), + }; + assert!(matches!( + h.send(EventKind::InterfacePublished { + task: "a".into(), + generation: 1, + claim: forged, + }), + Err(SchedError::Proof { .. }) + )); + assert_eq!(h.state("b"), TaskState::Blocked); + h.publish("a", 1); + h.finish("a"); + h.finish("b"); + // Tamper with B's own M1 receipt in the store after it was accepted. + let rid = h + .adapter + .inspect(|s| s.task("b").unwrap().completion.clone().unwrap().receipt_id); + let file = h + .engine + .completion_store + .join(aien_proof::evidence::RECEIPT_DIR) + .join(format!("{rid}.json")); + let original = std::fs::read(&file).unwrap(); + let text = String::from_utf8(original.clone()).unwrap(); + std::fs::write(&file, text.replacen("spark-harness", "spark-harnesz", 1)).unwrap(); + let mut ran = false; + assert!(matches!( + fence_err( + h.adapter + .fenced_for_tests("b", 1, |_| ran = true, committed) + ), + FenceError::CompletionInvalid { .. } + )); + assert!(!ran); + std::fs::write(&file, &original).unwrap(); + // Tamper with the producer's receipt instead: M2 may_finalize refuses. + let ra = h + .adapter + .inspect(|s| s.task("a").unwrap().completion.clone().unwrap().receipt_id); + let fa = file.with_file_name(format!("{ra}.json")); + let oa = std::fs::read(&fa).unwrap(); + std::fs::write( + &fa, + String::from_utf8(oa.clone()) + .unwrap() + .replacen("spark-harness", "spark-harnesz", 1), + ) + .unwrap(); + assert!(matches!( + fence_err( + h.adapter + .fenced_for_tests("b", 1, |_| ran = true, committed) + ), + FenceError::Scheduler(SchedError::Proof { .. }) + )); + assert!(!ran); + std::fs::write(&fa, &oa).unwrap(); + h.adapter + .fenced_for_tests("b", 1, |_| ran = true, committed) + .unwrap(); + assert!(ran); +} + +#[test] +fn early_fence_alone_commits_nothing_and_writes_nothing() { + let _home = home_guard::home_slot(); + let mut h = H::new(cfg(true, 4)); + let c = Compose::new(&h); + let mut ws_file = std::fs::File::create(h.ws().join("parser.md")).unwrap(); + std::io::Write::write_all(&mut ws_file, b"# Parser\n").unwrap(); + h.register("a", &[]); + h.register("b", &["a"]); + h.publish("a", 1); + let p = c.approval("req-early"); + let compose_dir = c.bridge.dir().to_path_buf(); + let before = (tree(&h.ws()), tree(&compose_dir)); + // The early gate passes and preparation runs ... + let r = h.prepare("b").unwrap(); + assert!(r.is_provisional()); + // ... but no commit or grant path is reachable from it. + let g = h.gen("b"); + { + assert!(matches!( + fence_err(h.adapter.submit_approved("b", g, &c.hook, &p, &c.ws)), + FenceError::NotCommittable { + state: TaskState::Provisional, + .. + } + )); + let req = MintRequest { + cx_promotion: 1, + proposal_sha256: sha(b"x"), + workspace: c.ws.clone(), + approver: "drake".into(), + constraints: vec![], + }; + assert!(matches!( + fence_err(h.adapter.authorize("b", g, &c.bridge, &req, None, None)), + FenceError::NotCommittable { + state: TaskState::Provisional, + .. + } + )); + } + h.work_done("b"); + assert!(matches!( + fence_err( + h.adapter + .submit_approved("b", h.gen("b"), &c.hook, &p, &c.ws) + ), + FenceError::NotCommittable { + state: TaskState::AwaitingFinalProof, + .. + } + )); + assert_eq!( + (tree(&h.ws()), tree(&compose_dir)), + before, + "preparation and refused fences wrote nothing" + ); + assert!(!h.ws().join(PATH).exists()); + // The same approval commits once the chain is final: the fence refused it. + h.finish("a"); + h.finalize("b"); + h.complete("b"); + let out = h + .adapter + .submit_approved("b", h.gen("b"), &c.hook, &p, &c.ws) + .unwrap(); + committed_or_stub(out.outcome); + assert!( + !h.ws().join(PATH).exists(), + "a World commit is not an effect" + ); +} + +#[test] +fn unauthorized_effects_are_still_refused_by_the_canonical_path() { + let _home = home_guard::home_slot(); + let mut h = H::new(cfg(true, 4)); + let c = Compose::new(&h); + h.register("a", &[]); + h.register("b", &["a"]); + h.publish("a", 1); + h.finish("a"); + h.finish("b"); + // The fence passes; the desk MAC does not. + let mut p = c.approval("req-forged"); + p.approver = "drake".into(); + let out = h + .adapter + .submit_approved("b", 1, &c.hook, &p, &c.ws) + .expect("fence passes"); + let e = out.outcome.expect_err("unauthenticated approval"); + assert_eq!( + (e.refused_by.as_str(), e.name.as_str()), + ("PROPOSAL_REFUSED", "Unauthenticated") + ); + // Refused before any replay claim: nothing durable, the task aborts. + assert!(matches!(out.result, CommitResult::Failed { .. })); + assert_eq!(h.state("b"), TaskState::Aborted); + assert!(!h.ws().join(PATH).exists()); + // ComposeAuthorize through the fence, no desk proof and no compose + // commit: refused by the existing authorize rules. + h.register("d", &["a"]); + h.finish("d"); + let req = MintRequest { + cx_promotion: 1, + proposal_sha256: sha(b"never committed"), + workspace: c.ws.clone(), + approver: "drake".into(), + constraints: vec![], + }; + let out = h + .adapter + .authorize("d", 1, &c.bridge, &req, None, None) + .expect("fence passes"); + match out.outcome { + ControlResponse::Error(e) => { + if aien_omega_compose::LINKED { + assert!(e.contains("DeskMacRequired"), "{e}"); + } + } + other => panic!("authorize must refuse: {other:?}"), + } +} + +#[test] +fn duplicate_commit_is_refused_and_a_restart_does_not_run_it_again() { + let _home = home_guard::home_slot(); + let c0 = cfg(true, 4); + let mut h = H::journaled(c0.clone()); + let c = Compose::new(&h); + h.register("a", &[]); + h.register("b", &["a"]); + h.publish("a", 1); + h.prepare("b").unwrap(); + h.finish("a"); + h.finish("b"); + let p = c.approval("req-dup"); + let first = h + .adapter + .submit_approved("b", 1, &c.hook, &p, &c.ws) + .unwrap(); + // The stub refuses the replay claim itself (no claim was made, nothing + // ran): recorded as failed, the task aborts. + let want = if aien_omega_compose::LINKED { + assert!(matches!(first.result, CommitResult::Committed { .. })); + TaskState::Committed + } else { + match &first.result { + CommitResult::Failed { reason } => assert!( + reason.starts_with("REPLAY_REFUSED Journal: ") + && reason.ends_with("is not linked (stub build)"), + "{reason}" + ), + other => panic!("want Failed, got {other:?}"), + } + TaskState::Aborted + }; + assert!(first.record_error.is_none()); + let report = committed_or_stub(first.outcome); + assert_eq!(h.state("b"), want); + // Same process, same task generation: refused before the hook runs. + assert!(matches!( + fence_err(h.adapter.submit_approved("b", 1, &c.hook, &p, &c.ws)), + FenceError::AlreadySubmitted { .. } + )); + // Restart: the journal replays the outcome, the audit passes, no result + // survives. + let revoked = h.restart(c0); + c.bridge.close(); + drop(c); + let c = Compose::reopen(&h); + assert!(revoked.is_empty(), "{revoked:?}"); + assert_eq!(h.state("b"), want); + assert!(h.adapter.prepared("b").is_none()); + // The new process has no in-memory record of the call, but the journaled + // outcome refuses a second run before the hook. + match fence_err(h.adapter.submit_approved("b", 1, &c.hook, &p, &c.ws)) { + FenceError::NotCommittable { state, .. } => assert_eq!(state, want), + other => panic!("want NotCommittable, got {other}"), + } + // Under the fence, the durable replay ledger still answers an exact retry + // without a second compose run. + let again = c.hook.submit(&p, &c.ws); + if let Some(first) = report { + let r = again.expect("an exact retry gets the original result"); + assert_eq!(r.state, "ALREADY_COMMITTED"); + assert!(r.task.is_none(), "nothing ran again"); + assert_eq!(r.replay_claim, first.replay_claim); + assert_eq!(r.grant_links, first.grant_links); + } else { + let e = again.expect_err("stub build must refuse the retry"); + assert_eq!( + (e.refused_by.as_str(), e.name.as_str(), e.replay_claim), + ("REPLAY_REFUSED", "Journal", None), + "{e}" + ); + } +} + +#[test] +fn restart_with_a_provisional_task_drops_the_result_and_prepares_again() { + let c0 = cfg(true, 4); + let mut h = H::journaled(c0.clone()); + h.register("a", &[]); + h.register("b", &["a"]); + h.publish("a", 1); + let r = h.prepare("b").unwrap(); + let revoked = h.restart(c0); + assert!(revoked.is_empty()); + assert_eq!(h.state("b"), TaskState::Provisional); + assert!( + h.adapter.prepared("b").is_none(), + "results are never journaled" + ); + let again = h.prepare("b").unwrap(); + assert_eq!(again.plan_sha256(), r.plan_sha256()); + // A producer receipt removed from the store while the daemon was down: + // the audit revokes the consumer at replay. + let c1 = cfg(true, 4); + let rid = h + .adapter + .inspect(|s| s.task("a").unwrap().interface.clone().unwrap().receipt_id); + std::fs::remove_file( + h.engine + .completion_store + .join(aien_proof::evidence::RECEIPT_DIR) + .join(format!("{rid}.json")), + ) + .unwrap(); + let revoked = h.restart(c1); + assert!(revoked.contains(&"a".to_string()), "{revoked:?}"); + assert_eq!(h.state("b"), TaskState::Blocked); +} + +#[test] +fn revocation_during_preparation_discards_the_result() { + let mut h = H::new(cfg(true, 4)); + h.register("a", &[]); + h.register("b", &["a"]); + h.publish("a", 1); + let adapter = Arc::clone(&h.adapter); + h.adapter.set_prep_hook(Some(Arc::new(move |_: &str| { + adapter + .deliver(Event { + id: "fail-a-mid-prep".into(), + kind: EventKind::ProducerFailed { + task: "a".into(), + generation: 1, + reason: "failed while b prepared".into(), + }, + }) + .unwrap(); + }))); + assert!(matches!(h.prepare("b"), Err(PrepError::Revoked { .. }))); + assert!(h.adapter.prepared("b").is_none()); + assert_eq!(h.state("b"), TaskState::Blocked); +} + +#[test] +fn an_interface_change_during_preparation_refuses_the_old_generation() { + let mut h = H::new(cfg(true, 4)); + h.register("a", &[]); + h.register("b", &["a"]); + h.publish("a", 1); + let store_dir = h.tmp.path().join("harness"); + let adapter = Arc::clone(&h.adapter); + // While b's operation runs, a publishes a new interface (store write, + // then the M2 event). + h.adapter.set_prep_hook(Some(Arc::new(move |_: &str| { + let mut e = HarnessEngine::load(&store_dir).unwrap(); + e.completion_clock = fixed_receipt_clock; + let v2 = e + .publish_interface(&InterfaceSubmission { + task_id: "a".into(), + generation: 1, + source_commit: COMMIT.into(), + interface: json!({ "task": "a", "api_version": 2 }), + }) + .unwrap() + .claim(); + adapter + .deliver(Event { + id: "republish-a-mid-prep".into(), + kind: EventKind::InterfacePublished { + task: "a".into(), + generation: 1, + claim: v2, + }, + }) + .unwrap(); + }))); + // b is revoked and dispatched again at generation 2 before the operation + // ends, so M2 would admit it again: only the generation recheck refuses + // the result made against the old interface. + assert!(matches!(h.prepare("b"), Err(PrepError::Revoked { .. }))); + assert_eq!((h.state("b"), h.gen("b")), (TaskState::Provisional, 2)); + assert!(h.adapter.prepared("b").is_none()); + h.adapter.set_prep_hook(None); + assert_eq!(h.prepare("b").unwrap().generation(), 2); +} + +#[test] +fn a_producer_receipt_that_stops_verifying_during_preparation_refuses_the_result() { + let mut h = H::new(cfg(true, 4)); + h.register("a", &[]); + h.register("b", &["a"]); + let (v1, _) = h.publish("a", 1); + let gen_b = h.gen("b"); + let file = h + .engine + .completion_store + .join(aien_proof::evidence::RECEIPT_DIR) + .join(format!("{}.json", v1.receipt_id)); + let original = std::fs::read(&file).unwrap(); + let (f2, o2) = (file.clone(), original.clone()); + // No event: the producer's receipt is altered in the store while b's + // operation runs, so only the post-operation M2 check can see it. + h.adapter.set_prep_hook(Some(Arc::new(move |_: &str| { + let text = String::from_utf8(o2.clone()).unwrap(); + std::fs::write(&f2, text.replacen("spark-harness", "spark-harnesz", 1)).unwrap(); + }))); + assert!(matches!(h.prepare("b"), Err(PrepError::Revoked { .. }))); + assert_eq!((h.state("b"), h.gen("b")), (TaskState::Provisional, gen_b)); + assert!(h.adapter.prepared("b").is_none()); + h.adapter.set_prep_hook(None); + std::fs::write(&file, &original).unwrap(); + h.prepare("b").unwrap(); +} + +#[test] +fn a_producer_completing_during_preparation_is_recorded_as_final() { + let mut h = H::new(cfg(true, 4)); + h.register("a", &[]); + h.register("b", &["a"]); + h.publish("a", 1); + h.work_done("a"); + h.finalize("a"); + let claim = h.mint_completion("a"); + let gen_b = h.gen("b"); + let adapter = Arc::clone(&h.adapter); + h.adapter.set_prep_hook(Some(Arc::new(move |_: &str| { + adapter + .deliver(Event { + id: "complete-a-mid-prep".into(), + kind: EventKind::CompletionVerified { + task: "a".into(), + generation: 1, + claim: claim.clone(), + }, + }) + .unwrap(); + }))); + // Admitted on the interface, the producer went final while the + // operation ran. Nothing was revoked, so the consumer keeps its + // generation, and the stored result carries the readiness re-checked + // after the operation (final), never the admission-time one. + let r = h.prepare("b").unwrap(); + assert_eq!((h.state("b"), h.gen("b")), (TaskState::Provisional, gen_b)); + assert!(!r.is_provisional()); + assert_eq!(r.bindings()[0].level, ReadinessLevel::FinalVerified); + let stored = h.adapter.prepared("b").unwrap(); + assert_eq!(stored.bindings()[0].level, ReadinessLevel::FinalVerified); +} + +#[test] +fn one_preparation_per_task_at_a_time() { + let mut h = H::new(cfg(true, 4)); + h.register("a", &[]); + h.register("b", &["a"]); + h.publish("a", 1); + let (entered_tx, entered_rx) = mpsc::channel::<()>(); + let (release_tx, release_rx) = mpsc::channel::<()>(); + let release_rx = std::sync::Mutex::new(release_rx); + let calls = AtomicU64::new(0); + // Only the first call parks; a second admitted call would run straight + // through and fail the Busy assertion below instead of deadlocking. + h.adapter.set_prep_hook(Some(Arc::new(move |_: &str| { + if calls.fetch_add(1, Ordering::SeqCst) == 0 { + entered_tx.send(()).unwrap(); + let _ = release_rx + .lock() + .unwrap() + .recv_timeout(Duration::from_secs(10)); + } + }))); + let (a2, ws) = (Arc::clone(&h.adapter), h.ws()); + let first = std::thread::spawn(move || a2.prepare("b", 1, GOAL, &ws).map(|_| ())); + entered_rx.recv().unwrap(); + assert!(matches!(h.prepare("b"), Err(PrepError::Busy(_)))); + release_tx.send(()).unwrap(); + first.join().unwrap().unwrap(); + h.adapter.set_prep_hook(None); + h.prepare("b").unwrap(); +} + +#[test] +fn concurrency_is_bounded_by_the_m2_permits() { + let mut h = H::new(cfg(true, 1)); + h.register("a", &[]); + h.register("b", &["a"]); + h.register("c", &["a"]); + h.publish("a", 1); + // A holds the only permit: neither consumer may prepare yet. + assert_eq!(h.adapter.permits_in_use().running, 1); + for t in ["b", "c"] { + assert_eq!(h.state(t), TaskState::Blocked); + assert!(h.prepare(t).is_err()); + } + h.work_done("a"); + // One consumer at a time, in task-id order. + assert_eq!( + (h.state("b"), h.state("c")), + (TaskState::Provisional, TaskState::Blocked) + ); + h.prepare("b").unwrap(); + assert!(h.prepare("c").is_err()); + h.work_done("b"); + assert_eq!(h.state("c"), TaskState::Provisional); + h.prepare("c").unwrap(); + assert!(h.adapter.permits_in_use().running <= 1); +} + +#[test] +fn the_commit_decision_freezes_the_inputs_without_holding_any_lock() { + let mut h = H::new(cfg(true, 4)); + h.register("a", &[]); + h.register("b", &["a"]); + h.publish("a", 1); + h.finish("a"); + h.finish("b"); + // An unrelated task with a live lease, heartbeating during the call. + h.register("x", &[]); + assert_eq!(h.state("x"), TaskState::Provisional); + let adapter = Arc::clone(&h.adapter); + let store_dir = h.tmp.path().join("harness"); + let wait = Duration::from_secs(10); + let fenced = h.adapter.fenced_for_tests( + "b", + 1, + |_| { + let during = adapter.state("b"); + // Each probe runs on its own thread and must finish while the + // call is still running: neither the adapter mutex nor a store + // lock is held. + let (tx, rx) = mpsc::channel(); + let a2 = Arc::clone(&adapter); + let t = tx.clone(); + std::thread::spawn(move || { + let r = a2.deliver(Event { + id: "revoke-a-during-commit".into(), + kind: EventKind::Revoke { + task: "a".into(), + generation: 1, + reason: "interface withdrawn".into(), + }, + }); + t.send(format!("revoke {r:?}")).unwrap(); + }); + let revoke = rx.recv_timeout(wait).expect("revoke blocked by the call"); + let a3 = Arc::clone(&adapter); + let t = tx.clone(); + std::thread::spawn(move || { + let r = a3.deliver(Event { + id: "beat-x-during-commit".into(), + kind: EventKind::Heartbeat { + task: "x".into(), + generation: 1, + beat: 1, + }, + }); + t.send(format!("beat {r:?}")).unwrap(); + }); + let beat = rx + .recv_timeout(wait) + .expect("heartbeat blocked by the call"); + std::thread::spawn(move || { + let mut e = HarnessEngine::load(&store_dir).unwrap(); + e.completion_clock = fixed_receipt_clock; + let r = e.publish_interface(&InterfaceSubmission { + task_id: "a".into(), + generation: 1, + source_commit: COMMIT.into(), + interface: json!({ "task": "a", "api_version": 9 }), + }); + tx.send(format!("store {:?}", r.map(|_| ()))).unwrap(); + }); + let store = rx + .recv_timeout(wait) + .expect("store writer blocked by the call"); + // A second fence for the same task generation while the first + // call runs: refused as already submitted, and it never runs. + let a4 = Arc::clone(&adapter); + let (tx2, rx2) = mpsc::channel(); + std::thread::spawn(move || { + let r = a4.fenced_for_tests("b", 1, |_| (), committed); + tx2.send(format!("{:?}", r.map(|_| "ran"))).unwrap(); + }); + let second = rx2 + .recv_timeout(wait) + .expect("second fence blocked by the call"); + (during, revoke, beat, store, second) + }, + committed, + ); + let out = fenced.expect("fence passes"); + let (during, revoke, beat, store, second) = out.outcome; + assert!(second.starts_with("Err(AlreadySubmitted"), "{second}"); + assert_eq!(during, Some(TaskState::Committing)); + assert!( + revoke.starts_with("revoke Ok(Deferred") && revoke.contains("committing: \"b\""), + "an upstream revoke must be held back while committing: {revoke}" + ); + assert!(beat.contains("Ok(Applied(Applied"), "{beat}"); + assert_eq!(store, "store Ok(())"); + assert_eq!(out.result, committed(&())); + assert!(out.record_error.is_none()); + assert_eq!((h.state("b"), h.gen("b")), (TaskState::Committed, 1)); + // After the outcome the held-back revoke applied, and stopped at the + // committed task. + assert_eq!(out.redelivered.len(), 1); + assert_eq!(out.redelivered[0].id, "revoke-a-during-commit"); + assert!( + matches!(out.redelivered[0].result, Ok(Outcome::Applied(_))), + "{:?}", + out.redelivered[0].result + ); + assert_eq!(h.adapter.deferred_len(), 0); + assert_eq!((h.state("b"), h.gen("b")), (TaskState::Committed, 1)); + assert!(matches!( + fence_err(h.adapter.fenced_for_tests("b", 1, |_| (), committed)), + FenceError::AlreadySubmitted { .. } + )); +} + +#[test] +fn a_panicking_commit_is_uncertain_and_never_runs_again() { + let mut h = H::new(cfg(true, 4)); + h.register("a", &[]); + h.register("b", &["a"]); + h.register("c", &["b"]); + h.publish("a", 1); + h.publish("b", 1); + h.finish("a"); + h.finish("b"); + assert_eq!(h.state("c"), TaskState::Provisional); + 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"), committed) + })); + assert!(r.is_err(), "the panic is resumed"); + assert_eq!(h.state("b"), TaskState::CommitUncertain); + assert_eq!(h.state("c"), TaskState::Blocked, "consumers revoked"); + let mut ran = false; + assert!(matches!( + fence_err( + h.adapter + .fenced_for_tests("b", 1, |_| ran = true, committed) + ), + FenceError::AlreadySubmitted { .. } + )); + assert!(!ran); +} + +#[test] +fn a_failed_commit_aborts_the_task_and_a_new_generation_may_commit() { + let mut h = H::new(cfg(true, 4)); + h.register("a", &[]); + h.register("b", &["a"]); + h.publish("a", 1); + h.finish("a"); + h.finish("b"); + let failed = |_: &()| CommitResult::Failed { + reason: "refused before any write".into(), + }; + let out = h.adapter.fenced_for_tests("b", 1, |_| (), failed).unwrap(); + assert!(matches!(out.result, CommitResult::Failed { .. })); + assert_eq!(h.state("b"), TaskState::Aborted); + h.ok(EventKind::Retry { + task: "b".into(), + generation: 1, + }); + assert_eq!(h.gen("b"), 2); + h.finish("b"); + let out = h + .adapter + .fenced_for_tests("b", 2, |_| (), committed) + .unwrap(); + assert!(out.record_error.is_none()); + assert_eq!(h.state("b"), TaskState::Committed); +} + +#[test] +fn outcomes_are_classified_conservatively() { + let refusal = |name: &str, claim: Option<u64>| { + let e = ApprovedRefusal { + refused_by: "REPLAY_REFUSED".into(), + name: name.into(), + detail: "d".into(), + request_id: "r".into(), + trace_id: "t".into(), + approval_id: "a".into(), + replay_claim: claim, + }; + classify_approved(&Err(Box::new(e))) + }; + assert!(matches!( + refusal("Unauthenticated", None), + CommitResult::Failed { .. } + )); + assert!(matches!( + refusal("NotCommitted", Some(3)), + CommitResult::Failed { .. } + )); + assert!(matches!( + refusal("ComposeError", Some(3)), + CommitResult::Uncertain { .. } + )); + assert!(matches!( + refusal("Mismatch", Some(3)), + CommitResult::Uncertain { .. } + )); + assert!(matches!( + refusal("GrantNotWritten", Some(3)), + CommitResult::Uncertain { .. } + )); + let e = |s: &str| classify_authorize(&ControlResponse::Error(s.into())); + assert!(matches!( + e("EFFECT_REFUSED DeskMacRequired: none"), + CommitResult::Failed { .. } + )); + assert!(matches!( + e("effect record: re-read 7: io"), + CommitResult::Uncertain { .. } + )); + assert!(matches!( + classify_authorize(&ControlResponse::ComposeNoted( + aien_runtime::control::ComposeNoteReport { + machine_id: "m".into(), + id: 7, + kind: "authorization".into(), + digest: "d".into(), + text_sha256: "s".into(), + links: vec![], + } + )), + CommitResult::Committed { .. } + )); +} + +#[test] +fn disabled_flag_is_the_default_and_sequential() { + assert!(!ProvisionalConfig::default().enabled); + let mut h = H::new(cfg(false, 4)); + assert!(!h.adapter.enabled()); + h.register("a", &[]); + h.register("b", &["a"]); + h.publish("a", 1); + assert_eq!(h.state("b"), TaskState::Blocked); + assert!(h.prepare("b").is_err()); + h.finish("a"); + let r = h.prepare("b").unwrap(); + assert!(!r.is_provisional()); +} + +// ---------- through the daemon socket ---------- + +async fn daemon( + socket: &Path, + bridge: Arc<ComposeBridge>, + adapter: Arc<PrepAdapter>, +) -> ( + aien_runtime::client::AienRuntimeClient, + tokio::task::JoinHandle<Result<(), String>>, +) { + let cfg = aien_scheduler::SchedulerConfig { + max_batch_size: 8, + max_batch_tokens: 1024, + prefill_chunk_size: 64, + watermark_blocks: 4, + chunk_prefill: true, + max_prefill_tokens: 1024, + }; + let spine = aien_runtime::spine::AienRuntimeSpine::new( + 64, + cfg, + aien_kv_cache::create_shared_kv_manager(256, 16), + ); + let server = aien_runtime::server::AienRuntimeServer::new(spine, socket) + .with_compose_bridge(bridge) + .with_prep_adapter(adapter); + let handle = tokio::spawn(async move { + server + .run(aien_inference_abi::MockInferenceBackend::new(1)) + .await + }); + let client = aien_runtime::client::AienRuntimeClient::new(socket); + for _ in 0..250 { + if client.is_alive().await { + return (client, handle); + } + if handle.is_finished() { + panic!("daemon stopped: {:?}", handle.await); + } + tokio::time::sleep(Duration::from_millis(20)).await; + } + panic!("daemon did not come up"); +} + +fn fence_refused(r: &ControlResponse, name: &str) -> bool { + matches!(r, ControlResponse::Error(e) if e.starts_with(&format!("FENCE_REFUSED {name}"))) +} + +/// The original `ComposeApprovedProposal` answer: a result or a refusal from +/// the canonical path, never a fence error. +fn canonical_approved(r: &ControlResponse) -> bool { + matches!( + r, + ControlResponse::ComposeApprovedResult(_) | ControlResponse::ComposeApprovedRefused(_) + ) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn the_daemon_fences_bound_requests_and_runs_unbound_ones_unchanged() { + let _home = home_guard::home_slot(); + let mut h = H::new(cfg(true, 4)); + let c = Compose::new(&h); + let socket = h.tmp.path().join("d.sock"); + let (client, server) = daemon(&socket, c.bridge.clone(), h.adapter.clone()).await; + let send = |cmd: ControlCommand| { + let client = &client; + async move { client.send_command(cmd).await.unwrap() } + }; + let approved = |p: &ApprovedProposal| ControlCommand::ComposeApprovedProposal { + proposal: p.clone(), + workspace: c.ws.clone(), + }; + let authorize = |digest: &str| ControlCommand::ComposeAuthorize { + cx_promotion: 1, + proposal_sha256: digest.into(), + workspace: c.ws.clone(), + approver: "drake".into(), + constraints: vec![], + desk_proof: None, + objective_id: None, + }; + + // Early overlap: B prepares while its producer A is only interface + // verified. + h.register("a", &[]); + h.register("b", &["a"]); + h.publish("a", 1); + assert!(h.prepare("b").unwrap().is_provisional()); + let bound = c.approval("req-bound"); + let free = c.approval("req-free"); + let commit_key = FenceKey::Approval(bound.approval_id.clone()); + let grant_key = FenceKey::Proposal(sha(b"bound grant")); + h.adapter.bind_approval(commit_key.clone(), "b", 1).unwrap(); + h.adapter.bind_approval(grant_key.clone(), "b", 1).unwrap(); + assert!(h + .adapter + .binding(&FenceKey::Approval(free.approval_id.clone())) + .is_none()); + + // Bound, while B is provisional: the fence refuses both kinds and + // nothing runs. + let compose_dir = c.bridge.dir().to_path_buf(); + let before = (tree(&h.ws()), tree(&compose_dir)); + let r = send(approved(&bound)).await; + assert!(fence_refused(&r, "NotCommittable"), "{r:?}"); + let r = send(authorize(&sha(b"bound grant"))).await; + assert!(fence_refused(&r, "NotCommittable"), "{r:?}"); + assert_eq!( + (tree(&h.ws()), tree(&compose_dir)), + before, + "a fenced request wrote nothing" + ); + assert_eq!(h.state("b"), TaskState::Provisional); + + // Unbound: the original calls run, whatever the M2 state. + let r = send(authorize(&sha(b"never committed"))).await; + match &r { + ControlResponse::Error(e) if aien_omega_compose::LINKED => { + assert!(e.starts_with("EFFECT_REFUSED DeskMacRequired"), "{e}") + } + ControlResponse::Error(e) => assert!( + e.starts_with("compose home ") && e.ends_with("is not linked (stub build)"), + "{e}" + ), + other => panic!("the canonical authorize must refuse: {other:?}"), + } + let r = send(approved(&free)).await; + assert!(canonical_approved(&r), "{r:?}"); + assert_eq!( + h.state("b"), + TaskState::Provisional, + "unbound runs touch no task" + ); + + // Once A and B are final the bound approval passes the fence and the + // canonical path decides: the World commit and its own grant, in one + // fenced call. + h.finish("a"); + h.finish("b"); + let r = send(approved(&bound)).await; + assert!(canonical_approved(&r), "{r:?}"); + let report = match &r { + ControlResponse::ComposeApprovedResult(rep) if aien_omega_compose::LINKED => { + assert_eq!(rep.state, "COMMITTED"); + Some(rep.clone()) + } + // The stub refuses the replay claim itself: nothing durable. + ControlResponse::ComposeApprovedRefused(_) if !aien_omega_compose::LINKED => None, + other => panic!("unexpected answer: {other:?}"), + }; + let Some(report) = report else { + // The refusal is classified `Failed`: B is aborted and keeps both + // bindings, so a resend is fenced and never reaches the canonical + // path unfenced. + assert_eq!(h.state("b"), TaskState::Aborted); + assert_eq!(h.adapter.binding(&commit_key), Some(("b".into(), 1))); + assert_eq!(h.adapter.binding(&grant_key), Some(("b".into(), 1))); + let r = send(approved(&bound)).await; + assert!(fence_refused(&r, "AlreadySubmitted"), "{r:?}"); + let r = send(authorize(&sha(b"bound grant"))).await; + assert!(fence_refused(&r, "AlreadySubmitted"), "{r:?}"); + assert_eq!(h.state("b"), TaskState::Aborted); + let _ = client.send_command(ControlCommand::Shutdown).await; + let _ = tokio::time::timeout(Duration::from_secs(5), server).await; + return; + }; + // B committed, so M2 dropped both of its bindings. + assert!(h.adapter.binding(&commit_key).is_none()); + assert!(h.adapter.binding(&grant_key).is_none()); + assert_eq!(h.adapter.inspect(|s| s.approvals_len()), 0); + assert_eq!(h.state("b"), TaskState::Committed); + assert!(report.approved_grant.is_some(), "{report:?}"); + // An exact retry goes to the canonical path, whose replay ledger + // answers it without a second run. + let r = send(approved(&bound)).await; + match &r { + ControlResponse::ComposeApprovedResult(rep) => { + assert_eq!(rep.state, "ALREADY_COMMITTED"); + assert!(rep.task.is_none(), "nothing ran again"); + } + other => panic!("want ALREADY_COMMITTED, got {other:?}"), + } + // No later grant stage exists for this flow. M2 refuses to bind one to + // the ended task, and the canonical mint refuses a desk-signed grant + // against the approved commit: the approved path writes no + // `compose_commit` record (compose/bridge.rs `run_task_inner`), which + // `ComposeAuthorize` requires (effects.rs). + let digest = report.compose_proposal_sha256.clone(); + let cx = report.grant_links[0]; + let late = h + .adapter + .bind_approval(FenceKey::Proposal(digest.clone()), "b", 1); + assert!( + matches!(late, Err(SchedError::WrongState { .. })), + "{late:?}" + ); + let key = DeskKey::load(&desk_key_path(c.bridge.dir())).unwrap(); + let nonce = format!("m3-grant-{cx}"); + let mac = key.sign_authorize(&AuthorizeBinding { + cx_promotion: cx, + proposal_sha256: digest.clone(), + path: PATH.into(), + content_sha256: sha(CONTENT.as_bytes()), + workspace: c.ws.clone(), + approver: "drake".into(), + constraints: vec![], + nonce: nonce.clone(), + desk_key_id: key.id().into(), + }); + let r = send(ControlCommand::ComposeAuthorize { + cx_promotion: cx, + proposal_sha256: digest, + workspace: c.ws.clone(), + approver: "drake".into(), + constraints: vec![], + desk_proof: Some(DeskProof { nonce, mac }), + objective_id: None, + }) + .await; + match &r { + ControlResponse::Error(e) => { + assert!(e.starts_with("EFFECT_REFUSED NotAuthorized"), "{e}") + } + other => panic!("want the canonical NotAuthorized refusal, got {other:?}"), + } + assert_eq!(h.state("b"), TaskState::Committed); + // In process the generation is spent. + assert!(matches!( + fence_err(h.adapter.submit_approved("b", 1, &c.hook, &bound, &c.ws)), + FenceError::AlreadySubmitted { .. } + )); + + let _ = client.send_command(ControlCommand::Shutdown).await; + let _ = tokio::time::timeout(Duration::from_secs(5), server).await; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn an_aborted_task_keeps_its_bound_requests_fenced_until_retried_and_bound_again() { + let _home = home_guard::home_slot(); + let mut h = H::new(cfg(true, 4)); + let c = Compose::new(&h); + let socket = h.tmp.path().join("d.sock"); + let (client, server) = daemon(&socket, c.bridge.clone(), h.adapter.clone()).await; + let send = |cmd: ControlCommand| { + let client = &client; + async move { client.send_command(cmd).await.unwrap() } + }; + let authorize = |digest: &str| ControlCommand::ComposeAuthorize { + cx_promotion: 1, + proposal_sha256: digest.into(), + workspace: c.ws.clone(), + approver: "drake".into(), + constraints: vec![], + desk_proof: None, + objective_id: None, + }; + // The canonical call's own refusal (no desk MAC, or the stub), never a + // fence error: what an unfenced run answers. + let canonical = |r: &ControlResponse| matches!(r, ControlResponse::Error(e) if !e.starts_with("FENCE_REFUSED")); + let r = send(authorize(&sha(b"never bound"))).await; + assert!(canonical(&r), "control, unbound: {r:?}"); + + // (a) Cancel, producer failure and lease expiry: the binding stays and + // the request is refused. + type Abort = fn(&mut H, &str); + let aborts: [(&str, Abort); 3] = [ + ("cancel", |h, t| { + let generation = h.gen(t); + h.ok(EventKind::Cancel { + task: t.into(), + generation, + }); + }), + ("producer failed", |h, t| { + let generation = h.gen(t); + h.ok(EventKind::ProducerFailed { + task: t.into(), + generation, + reason: "test".into(), + }); + }), + ("lease expired", |h, t| { + // The producer finishes first, so only b's provisional lease + // runs out (a running producer's expiry would revoke b instead). + h.finish(&t.replacen('b', "a", 1)); + h.ticks.fetch_add(2_000_000, Ordering::SeqCst); + h.ok(EventKind::Tick); + }), + ]; + for (i, (how, abort)) in aborts.into_iter().enumerate() { + let (a, b) = (format!("a{i}"), format!("b{i}")); + h.register(&a, &[]); + h.register(&b, &[a.as_str()]); + h.publish(&a, 1); + assert_eq!(h.state(&b), TaskState::Provisional, "{how}"); + let digest = sha(how.as_bytes()); + h.adapter + .bind_approval(FenceKey::Proposal(digest.clone()), &b, 1) + .unwrap(); + abort(&mut h, &b); + assert_eq!(h.state(&b), TaskState::Aborted, "{how}"); + let r = send(authorize(&digest)).await; + assert!(fence_refused(&r, "NotCommittable"), "{how}: {r:?}"); + } + + // (b) A committable task is cancelled, retried and committable again: + // the old binding refuses until the request is bound at the new + // generation, and then the request runs through the fence. + h.register("p", &[]); + h.register("q", &["p"]); + h.publish("p", 1); + h.finish("p"); + h.finish("q"); + let digest = sha(b"retried grant"); + let key = FenceKey::Proposal(digest.clone()); + h.adapter.bind_approval(key.clone(), "q", 1).unwrap(); + h.ok(EventKind::Cancel { + task: "q".into(), + generation: 1, + }); + let r = send(authorize(&digest)).await; + assert!(fence_refused(&r, "NotCommittable"), "{r:?}"); + h.ok(EventKind::Retry { + task: "q".into(), + generation: 1, + }); + h.finish("q"); + assert_eq!(h.gen("q"), 2); + let r = send(authorize(&digest)).await; + assert!(fence_refused(&r, "StaleGeneration"), "{r:?}"); + assert_eq!(h.state("q"), TaskState::Committable); + h.adapter.bind_approval(key.clone(), "q", 2).unwrap(); + let r = send(authorize(&digest)).await; + assert!(canonical(&r), "bound again, it runs fenced: {r:?}"); + if aien_omega_compose::LINKED { + // The canonical refusal (no desk MAC) is a failed commit: q is + // aborted, keeps the binding, and a resend stays fenced. + assert_eq!(h.state("q"), TaskState::Aborted); + assert_eq!(h.adapter.binding(&key), Some(("q".into(), 2))); + let r = send(authorize(&digest)).await; + assert!(fence_refused(&r, "AlreadySubmitted"), "{r:?}"); + } else { + // The stub answer is not an EFFECT_REFUSED: uncertain, terminal. + assert_eq!(h.state("q"), TaskState::CommitUncertain); + assert!(h.adapter.binding(&key).is_none()); + } + + let _ = client.send_command(ControlCommand::Shutdown).await; + let _ = tokio::time::timeout(Duration::from_secs(5), server).await; +} + +// The model proposal of the `RunComposeTask` flow, as in +// provenance_link_test.rs. +const RUN_GOAL: &str = "write the note"; +const RUN_PROPOSAL: &str = "filename: NOTES.md\nkeep every change inside the workspace\n"; +const RUN_CONTENT: &str = "keep every change inside the workspace\n"; + +fn model_proposer() -> ComposeProposer { + Arc::new(|_: &str, _: Duration| { + Ok(aien_runtime::compose::Generation { + text: RUN_PROPOSAL.to_string(), + tokens: 3, + finish_reason: Some("eos".into()), + token_ids: Some(vec![11, 12, 13]), + prompt_tokens: Some(5), + prompt_ids_sha256: Some(aien_runtime::compose::token_ids_sha256(&[1, 2, 3, 4, 5])), + decoding: Some(aien_inference_abi::DecodeObservation { + greedy_tokens: 3, + ..Default::default() + }), + ops: Some(aien_inference_abi::OpEvidence { + backend: "reference-cpu".into(), + native_fallbacks: 0, + reference_runs: 0, + report: "OP_REPORT native=[] reference=[] native_fallbacks=[] reference_runs=[]" + .into(), + gpu_executions: None, + }), + }) + }) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_bound_grant_after_an_unfenced_compose_run_mints_through_the_fence() { + let _home = home_guard::home_slot(); + let mut h = H::new(cfg(true, 4)); + let home = h.tmp.path().join("compose"); + DeskKey::create(&desk_key_path(&home)).unwrap(); + let bridge = Arc::new(ComposeBridge::new( + home.clone(), + model_proposer(), + "test:m3-model", + )); + let ws = std::fs::canonicalize(h.ws()).unwrap().display().to_string(); + let socket = h.tmp.path().join("g.sock"); + let (client, server) = daemon(&socket, bridge.clone(), h.adapter.clone()).await; + let send = |cmd: ControlCommand| { + let client = &client; + async move { client.send_command(cmd).await.unwrap() } + }; + h.register("a", &[]); + h.register("b", &["a"]); + h.publish("a", 1); + let digest = sha(RUN_PROPOSAL.as_bytes()); + let key = FenceKey::Proposal(digest.clone()); + h.adapter.bind_approval(key.clone(), "b", 1).unwrap(); + + // The model run has no binding kind: it runs unfenced, whatever B's + // state, and records the compose commit the grant needs. + let r = send(ControlCommand::RunComposeTask { + context: None, + goal: RUN_GOAL.into(), + workspace: ws.clone(), + }) + .await; + let cx = match &r { + ControlResponse::ComposeTaskResult(rep) if aien_omega_compose::LINKED => { + let v = serde_json::to_value(&**rep).unwrap(); + assert_eq!(v["committed"], true, "{v}"); + assert!(v["compose_commit"].as_u64().is_some(), "{v}"); + v["cx_promotion"].as_u64().unwrap() + } + ControlResponse::Error(e) if !aien_omega_compose::LINKED => { + assert!(e.ends_with("is not linked (stub build)"), "{e}"); + 1 + } + other => panic!("unexpected run answer: {other:?}"), + }; + assert_eq!(h.state("b"), TaskState::Provisional); + let desk = DeskKey::load(&desk_key_path(&home)).unwrap(); + let grant = |nonce: &str| { + let mac = desk.sign_authorize(&AuthorizeBinding { + cx_promotion: cx, + proposal_sha256: digest.clone(), + path: PATH.into(), + content_sha256: sha(RUN_CONTENT.as_bytes()), + workspace: ws.clone(), + approver: "drake".into(), + constraints: vec![], + nonce: nonce.into(), + desk_key_id: desk.id().into(), + }); + ControlCommand::ComposeAuthorize { + cx_promotion: cx, + proposal_sha256: digest.clone(), + workspace: ws.clone(), + approver: "drake".into(), + constraints: vec![], + desk_proof: Some(DeskProof { + nonce: nonce.into(), + mac, + }), + objective_id: None, + } + }; + + // Bound, while B is provisional: the grant is the fenced call and is + // refused; nothing is written. + let before = (tree(Path::new(&ws)), tree(&home)); + let r = send(grant("m3-run-early")).await; + assert!(fence_refused(&r, "NotCommittable"), "{r:?}"); + assert_eq!( + (tree(Path::new(&ws)), tree(&home)), + before, + "a fenced grant wrote nothing" + ); + + // Final: the grant passes the fence and the canonical mint decides. + h.finish("a"); + h.finish("b"); + let r = send(grant("m3-run-final")).await; + if aien_omega_compose::LINKED { + match &r { + ControlResponse::ComposeNoted(_) => {} + other => panic!("want the grant minted, got {other:?}"), + } + assert_eq!(h.state("b"), TaskState::Committed); + } else { + match &r { + ControlResponse::Error(e) => assert!( + e.starts_with("compose home ") && e.ends_with("is not linked (stub build)"), + "{e}" + ), + other => panic!("the stub authorize must refuse: {other:?}"), + } + // 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}") + } + ControlResponse::Error(e) => assert!(e.ends_with("is not linked (stub build)"), "{e}"), + other => panic!("a second grant must be refused: {other:?}"), + } + + let _ = client.send_command(ControlCommand::Shutdown).await; + let _ = tokio::time::timeout(Duration::from_secs(5), server).await; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_binding_survives_a_daemon_restart_and_the_request_stays_fenced() { + let _home = home_guard::home_slot(); + let c0 = cfg(true, 4); + let mut h = H::journaled(c0.clone()); + let c = Compose::new(&h); + h.register("a", &[]); + h.register("b", &["a"]); + h.publish("a", 1); + let bound = c.approval("req-bound-restart"); + let free = c.approval("req-free-restart"); + let key = FenceKey::Approval(bound.approval_id.clone()); + h.adapter.bind_approval(key.clone(), "b", 1).unwrap(); + // The daemon restarts: a new adapter replays the journal. + let revoked = h.restart(c0); + assert!(revoked.is_empty(), "{revoked:?}"); + assert_eq!(h.adapter.binding(&key), Some(("b".to_string(), 1))); + let socket = h.tmp.path().join("r.sock"); + let (client, server) = daemon(&socket, c.bridge.clone(), h.adapter.clone()).await; + let compose_dir = c.bridge.dir().to_path_buf(); + let before = (tree(&h.ws()), tree(&compose_dir)); + let r = client + .send_command(ControlCommand::ComposeApprovedProposal { + proposal: bound.clone(), + workspace: c.ws.clone(), + }) + .await + .unwrap(); + assert!(fence_refused(&r, "NotCommittable"), "{r:?}"); + assert_eq!( + (tree(&h.ws()), tree(&compose_dir)), + before, + "the restarted daemon still fenced the bound request" + ); + // Control: an unbound approval runs the original call after the restart. + let r = client + .send_command(ControlCommand::ComposeApprovedProposal { + proposal: free, + workspace: c.ws.clone(), + }) + .await + .unwrap(); + assert!(canonical_approved(&r), "{r:?}"); + let _ = client.send_command(ControlCommand::Shutdown).await; + let _ = tokio::time::timeout(Duration::from_secs(5), server).await; +} + +#[test] +fn a_restart_during_a_commit_is_uncertain_and_never_runs_it_again() { + let mut h = H::journaled(cfg(true, 4)); + h.register("a", &[]); + h.register("b", &["a"]); + h.register("c", &["b"]); + h.publish("a", 1); + h.publish("b", 1); + h.finish("a"); + h.finish("b"); + assert_eq!(h.state("c"), TaskState::Provisional); + let journal = h.tmp.path().join("journal.jsonl"); + let copy = h.tmp.path().join("journal-mid-commit.jsonl"); + let store = h.engine.completion_store.clone(); + let ticks = Arc::clone(&h.ticks); + // The daemon dies while the commit runs: its journal at that moment is + // opened by a new process. + let out = h + .adapter + .fenced_for_tests( + "b", + 1, + |_| { + std::fs::copy(&journal, ©).unwrap(); + // The audit's own revocations: settling the interrupted + // commit is not one of them (its consumers are revoked by + // the settled outcome itself, checked below). + let (a, _audit) = + PrepAdapter::open(cfg(true, 4), &store, ©, clock(&ticks)).unwrap(); + let mut ran = false; + let again = a.fenced_for_tests("b", 1, |_| ran = true, committed).err(); + (a.state("b"), a.generation("c"), again, ran) + }, + committed, + ) + .unwrap(); + let (state, gen_c, again, ran) = out.outcome; + assert_eq!(state, Some(TaskState::CommitUncertain)); + assert_eq!(gen_c, Some(2), "the consumer was revoked"); + assert!( + matches!( + again, + Some(FenceError::NotCommittable { + state: TaskState::CommitUncertain, + .. + }) + ), + "{again:?}" + ); + assert!(!ran, "the restarted process ran nothing"); + // The process that did not die records its outcome as usual. + assert_eq!(h.state("b"), TaskState::Committed); +} + +#[test] +fn a_revoke_during_a_commit_is_applied_after_the_outcome() { + let mut h = H::new(cfg(true, 4)); + h.register("a", &[]); + h.register("b", &["a"]); + h.register("d", &["a"]); + h.publish("a", 1); + h.finish("a"); + h.finish("b"); + assert_eq!(h.state("d"), TaskState::Provisional); + h.prepare("d").unwrap(); + let adapter = Arc::clone(&h.adapter); + let revoke = |id: &str, reason: &str| Event { + id: id.into(), + kind: EventKind::Revoke { + task: "a".into(), + generation: 1, + reason: reason.into(), + }, + }; + let out = h + .adapter + .fenced_for_tests( + "b", + 1, + |_| { + let first = adapter.deliver(revoke("revoke-a", "withdrawn")); + let again = adapter.deliver(revoke("revoke-a", "withdrawn")); + let conflict = adapter.deliver(revoke("revoke-a", "other reason")); + let d = ( + adapter.state("d"), + adapter.generation("d"), + adapter.prepared("d").is_some(), + ); + (first, again, conflict, d, adapter.deferred_len()) + }, + committed, + ) + .unwrap(); + let (first, again, conflict, d, queued) = out.outcome; + let deferred = Delivered::Deferred { + committing: "b".into(), + queued: 1, + }; + assert_eq!(first.unwrap(), deferred); + assert_eq!(again.unwrap(), deferred, "a redelivery is not queued twice"); + assert!( + matches!( + conflict, + Err(DeliverError::Scheduler(SchedError::EventIdConflict(_))) + ), + "{conflict:?}" + ); + assert_eq!( + d, + (Some(TaskState::Provisional), Some(1), true), + "nothing applied while b commits" + ); + assert_eq!(queued, 1); + // After the outcome: the revoke applied and invalidated the other + // consumer; the committed task is not reached. + assert_eq!(out.redelivered.len(), 1); + assert_eq!(out.redelivered[0].id, "revoke-a"); + match &out.redelivered[0].result { + Ok(Outcome::Applied(fx)) => assert!(fx.revoked.contains(&"d".to_string()), "{fx:?}"), + other => panic!("want the revoke applied, got {other:?}"), + } + assert_eq!(h.adapter.deferred_len(), 0); + assert_eq!(h.gen("d"), 2); + assert!( + h.adapter.prepared("d").is_none(), + "the result was discarded" + ); + assert_eq!((h.state("b"), h.gen("b")), (TaskState::Committed, 1)); +} + +#[test] +fn an_event_held_by_another_running_commit_stays_queued() { + let mut h = H::new(cfg(true, 8)); + // Two independent chains: a -> b and x -> y. + for (p, c) in [("a", "b"), ("x", "y")] { + h.register(p, &[]); + h.register(c, &[p]); + h.publish(p, 1); + h.finish(p); + h.finish(c); + } + let adapter = Arc::clone(&h.adapter); + let out = h + .adapter + .fenced_for_tests( + "y", + 1, + |_| { + // Held back by y's commit. + let held = adapter.deliver(Event { + id: "revoke-x".into(), + kind: EventKind::Revoke { + task: "x".into(), + generation: 1, + reason: "withdrawn".into(), + }, + }); + // b's whole commit runs and ends while y still commits: its + // drain must keep the event y still refuses. + let b = adapter + .fenced_for_tests("b", 1, |_| (), committed) + .map(|f| f.redelivered.len()); + (held, b, adapter.deferred_len(), adapter.generation("x")) + }, + committed, + ) + .unwrap(); + let (held, b, queued, gen_x) = out.outcome; + assert!( + matches!(held, Ok(Delivered::Deferred { ref committing, .. }) if committing == "y"), + "{held:?}" + ); + assert_eq!(b.unwrap(), 0, "nothing was reported by b's drain"); + assert_eq!((queued, gen_x), (1, Some(1)), "still queued, not applied"); + // y's outcome delivers it. + assert_eq!(out.redelivered.len(), 1); + assert_eq!(out.redelivered[0].id, "revoke-x"); + assert!(matches!(out.redelivered[0].result, Ok(Outcome::Applied(_)))); + assert_eq!(h.adapter.deferred_len(), 0); + assert_eq!( + (h.state("b"), h.state("y")), + (TaskState::Committed, TaskState::Committed) + ); +} + +#[test] +fn the_deferred_queue_is_bounded_and_fails_closed() { + let mut h = H::new(cfg(true, 4)); + h.register("a", &[]); + h.register("b", &["a"]); + h.publish("a", 1); + h.finish("a"); + h.finish("b"); + let adapter = Arc::clone(&h.adapter); + let out = h + .adapter + .fenced_for_tests( + "b", + 1, + |_| { + let mut answers = Vec::new(); + for i in 0..=DEFERRED_CAPACITY { + answers.push(adapter.deliver(Event { + id: format!("revoke-{i}"), + kind: EventKind::Revoke { + task: "a".into(), + generation: 1, + reason: format!("withdrawn {i}"), + }, + })); + } + answers + }, + committed, + ) + .unwrap(); + for (i, a) in out.outcome[..DEFERRED_CAPACITY].iter().enumerate() { + match a { + Ok(Delivered::Deferred { queued, .. }) => assert_eq!(*queued, i + 1), + other => panic!("event {i}: want Deferred, got {other:?}"), + } + } + match &out.outcome[DEFERRED_CAPACITY] { + Err(DeliverError::DeferredFull { + committing, + capacity, + }) => assert_eq!((committing.as_str(), *capacity), ("b", DEFERRED_CAPACITY)), + other => panic!("want DeferredFull, got {other:?}"), + } + // Every queued event is delivered again and reported, oldest first; the + // refused one was never queued. + let ids: Vec<String> = out.redelivered.iter().map(|r| r.id.clone()).collect(); + let want: Vec<String> = (0..DEFERRED_CAPACITY) + .map(|i| format!("revoke-{i}")) + .collect(); + assert_eq!(ids, want); + assert!(matches!(out.redelivered[0].result, Ok(Outcome::Applied(_)))); + // The first revoke moved a to generation 2, so the rest are refused as + // stale. Refused redeliveries are kept (never dropped) until discarded. + assert!(out.redelivered[1..] + .iter() + .all(|r| matches!(r.result, Err(SchedError::StaleGeneration { .. })))); + assert_eq!(h.adapter.deferred_len(), DEFERRED_CAPACITY - 1); + assert_eq!(h.state("b"), TaskState::Committed); +} + +#[test] +fn the_fence_events_are_refused_by_deliver() { + let mut h = H::new(cfg(true, 4)); + h.register("a", &[]); + h.register("b", &["a"]); + h.publish("a", 1); + h.finish("a"); + h.finish("b"); + let claim = h + .adapter + .inspect(|s| s.task("b").unwrap().completion.clone().unwrap()); + let kinds = [ + ( + "begin_commit", + EventKind::BeginCommit { + task: "b".into(), + generation: 1, + completion: claim, + producers: BTreeMap::new(), + }, + ), + ( + "commit_outcome", + EventKind::CommitOutcome { + task: "b".into(), + generation: 1, + outcome: committed(&()), + }, + ), + ( + "bind_approval", + EventKind::BindApproval { + key: "approval:x".into(), + task: "b".into(), + generation: 1, + }, + ), + ]; + for (name, kind) in kinds { + match h.deliver(kind) { + Err(DeliverError::FenceOnly(k)) => assert_eq!(k, name), + other => panic!("{name}: want FenceOnly, got {other:?}"), + } + } + assert_eq!(h.state("b"), TaskState::Committable); + assert!(h.adapter.binding(&FenceKey::Approval("x".into())).is_none()); + // Control: an ordinary event is delivered. + assert!(matches!( + h.deliver(EventKind::Tick), + Ok(Delivered::Applied(_)) + )); +} + +#[test] +fn begin_commit_holds_the_store_writers_out() { + let mut h = H::new(cfg(true, 4)); + h.register("a", &[]); + h.register("b", &["a"]); + h.publish("a", 1); + h.finish("a"); + h.finish("b"); + let store_dir = h.tmp.path().join("harness"); + // A writer for a task M2 does not know: it takes the same store lock + // but changes nothing the fence verifies. + let writer = move |version: u32| { + let (tx, rx) = mpsc::channel(); + let dir = store_dir.clone(); + std::thread::spawn(move || { + let mut e = HarnessEngine::load(&dir).unwrap(); + e.completion_clock = fixed_receipt_clock; + let r = e.publish_interface(&InterfaceSubmission { + task_id: "outside".into(), + generation: 1, + source_commit: COMMIT.into(), + interface: json!({ "task": "outside", "api_version": version }), + }); + tx.send(r.map(|_| ()).map_err(|e| e.to_string())).unwrap(); + }); + rx + }; + // Control: with no fence running, the writer finishes at once. + writer(7) + .recv_timeout(Duration::from_secs(10)) + .expect("writer runs") + .unwrap(); + let (entered_tx, entered_rx) = mpsc::channel::<()>(); + let (release_tx, release_rx) = mpsc::channel::<()>(); + let release_rx = std::sync::Mutex::new(release_rx); + let entered_tx = std::sync::Mutex::new(entered_tx); + h.adapter.set_begin_hook(Some(Arc::new(move |_: &str| { + entered_tx.lock().unwrap().send(()).unwrap(); + let _ = release_rx + .lock() + .unwrap() + .recv_timeout(Duration::from_secs(10)); + }))); + let a2 = Arc::clone(&h.adapter); + let fence = std::thread::spawn(move || { + a2.fenced_for_tests("b", 1, |_| (), committed) + .map(|f| f.result) + .map_err(|e| e.to_string()) + }); + entered_rx + .recv_timeout(Duration::from_secs(10)) + .expect("the fence reached its hook"); + // Inside begin_commit, between the checks and the journaled transition: + // a store writer must wait. + let rx = writer(8); + assert!( + matches!( + rx.recv_timeout(Duration::from_millis(300)), + Err(mpsc::RecvTimeoutError::Timeout) + ), + "a store writer ran inside begin_commit" + ); + release_tx.send(()).unwrap(); + rx.recv_timeout(Duration::from_secs(10)) + .expect("the writer runs once the fence releases its locks") + .unwrap(); + assert_eq!(fence.join().unwrap().unwrap(), committed(&())); + h.adapter.set_begin_hook(None); +} + +// ---------- the journaled deferred queue ---------- + +fn revoke_a(id: &str) -> Event { + Event { + id: id.into(), + kind: EventKind::Revoke { + task: "a".into(), + generation: 1, + reason: "withdrawn".into(), + }, + } +} + +#[test] +fn a_revoke_deferred_by_a_commit_that_crashed_is_applied_on_open() { + let mut h = H::journaled(cfg(true, 4)); + h.register("a", &[]); + h.register("b", &["a"]); + h.register("d", &["a"]); + h.publish("a", 1); + h.finish("a"); + h.finish("b"); + assert_eq!(h.state("d"), TaskState::Provisional); + let journal = h.tmp.path().join("journal.jsonl"); + let sidecar = deferred_journal_path(&journal); + let copy = h.tmp.path().join("journal-crash.jsonl"); + let bare = h.tmp.path().join("journal-crash-no-sidecar.jsonl"); + let store = h.engine.completion_store.clone(); + let ticks = Arc::clone(&h.ticks); + let adapter = Arc::clone(&h.adapter); + let out = h + .adapter + .fenced_for_tests( + "b", + 1, + |_| { + let deferred = adapter.deliver(revoke_a("revoke-a")); + // The daemon dies here, before the drain: the journal and + // its sidecar as they are now. + std::fs::copy(&journal, ©).unwrap(); + std::fs::copy(&sidecar, deferred_journal_path(©)).unwrap(); + std::fs::copy(&journal, &bare).unwrap(); + let (a, _audit) = + PrepAdapter::open(cfg(true, 4), &store, ©, clock(&ticks)).unwrap(); + let replayed = a.take_replayed_deferred(); + let again = a.take_replayed_deferred().len(); + let reopened = ( + a.state("b"), + a.generation("d"), + a.deferred_len(), + std::fs::read_to_string(deferred_journal_path(©)).unwrap(), + ); + // Negative control: the same crash without the sidecar + // loses the revoke. + let (n, _audit) = + PrepAdapter::open(cfg(true, 4), &store, &bare, clock(&ticks)).unwrap(); + let control = (n.generation("d"), n.take_replayed_deferred().len()); + (deferred, replayed, again, reopened, control) + }, + committed, + ) + .unwrap(); + let (deferred, replayed, again, reopened, control) = out.outcome; + assert!( + matches!(deferred, Ok(Delivered::Deferred { ref committing, .. }) if committing == "b"), + "{deferred:?}" + ); + // Reopened: the interrupted commit settled first, then the revoke. + assert_eq!(replayed.len(), 1); + assert_eq!(replayed[0].id, "revoke-a"); + match &replayed[0].result { + Ok(Outcome::Applied(fx)) => assert!(fx.revoked.contains(&"d".to_string()), "{fx:?}"), + other => panic!("want the revoke applied, got {other:?}"), + } + assert_eq!(again, 0, "taken once"); + assert_eq!( + reopened, + (Some(TaskState::CommitUncertain), Some(2), 0, String::new()) + ); + assert_eq!(control, (Some(1), 0)); + // The process that did not die drained it as usual and emptied the + // sidecar. + assert_eq!(out.redelivered.len(), 1); + assert!(out.deferred_error.is_none()); + assert_eq!(h.gen("d"), 2); + assert_eq!(std::fs::read_to_string(&sidecar).unwrap(), ""); + // A second open of the drained journal replays nothing. + drop(adapter); + let n = h.restart(cfg(true, 4)); + assert!(n.is_empty(), "{n:?}"); + assert!(h.adapter.take_replayed_deferred().is_empty()); + assert_eq!(h.gen("d"), 2); +} + +#[test] +fn a_bad_deferred_sidecar_fails_the_open() { + let h = H::journaled(cfg(true, 4)); + let copy = h.tmp.path().join("journal-copy.jsonl"); + std::fs::copy(h.tmp.path().join("journal.jsonl"), ©).unwrap(); + let side = deferred_journal_path(©); + let store = h.engine.completion_store.clone(); + let ticks = Arc::clone(&h.ticks); + let open = || PrepAdapter::open(cfg(true, 4), &store, ©, clock(&ticks)); + let lines = |events: Vec<Event>| -> String { + events + .iter() + .map(|e| serde_json::to_string(e).unwrap() + "\n") + .collect() + }; + let revokes = + |n: usize| -> Vec<Event> { (0..n).map(|i| revoke_a(&format!("revoke-{i}"))).collect() }; + let bind = Event { + id: "bind-x".into(), + kind: EventKind::BindApproval { + key: "approval:x".into(), + task: "a".into(), + generation: 1, + }, + }; + let reason = "r".repeat(DEFERRED_MAX_BYTES as usize / DEFERRED_CAPACITY + 1); + let large: Vec<Event> = (0..DEFERRED_CAPACITY) + .map(|i| Event { + id: format!("large-{i}"), + kind: EventKind::Revoke { + task: "a".into(), + generation: 1, + reason: reason.clone(), + }, + }) + .collect(); + for (what, text) in [ + ("not json", "not json\n".to_string()), + ("over the cap", lines(revokes(DEFERRED_CAPACITY + 1))), + ("fence-only", lines(vec![bind])), + // Well-formed and under the event cap, but over the byte cap. + ("too large", lines(large)), + ] { + std::fs::write(&side, text).unwrap(); + match open() { + Err(SchedError::Journal(e)) => assert!(e.contains("deferred"), "{what}: {e}"), + Err(e) => panic!("{what}: want a journal error, got {e}"), + Ok(_) => panic!("{what}: the open must fail"), + } + } + // Control: exactly the cap opens and every event is delivered. Each is + // refused here (no task is registered), reported, and kept queued and + // journaled until it is discarded. + let full = lines(revokes(DEFERRED_CAPACITY)); + std::fs::write(&side, &full).unwrap(); + let (a, _) = open().unwrap(); + let replayed = a.take_replayed_deferred(); + assert_eq!(replayed.len(), DEFERRED_CAPACITY); + assert!(replayed + .iter() + .all(|r| matches!(r.result, Err(SchedError::UnknownTask(_))))); + assert_eq!(a.deferred_len(), DEFERRED_CAPACITY); + assert_eq!(std::fs::read_to_string(&side).unwrap(), full); + for i in 0..DEFERRED_CAPACITY { + let id = format!("revoke-{i}"); + let ev = a.discard_deferred(&id).unwrap().expect("queued"); + assert_eq!(ev.id, id); + } + assert_eq!(a.deferred_len(), 0); + assert_eq!(std::fs::read_to_string(&side).unwrap(), ""); +} + +#[test] +fn a_deferred_event_that_cannot_be_journaled_is_refused() { + 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")); + // A non-empty directory where the sidecar goes: the rename fails. + std::fs::create_dir_all(side.join("block")).unwrap(); + let adapter = Arc::clone(&h.adapter); + let out = h + .adapter + .fenced_for_tests( + "b", + 1, + |_| { + ( + adapter.deliver(revoke_a("revoke-a")), + adapter.deferred_len(), + ) + }, + committed, + ) + .unwrap(); + let (r, queued) = out.outcome; + assert!(matches!(r, Err(DeliverError::DeferredJournal(_))), "{r:?}"); + assert_eq!(queued, 0, "nothing was queued"); + assert!(out.redelivered.is_empty()); + assert_eq!(h.gen("a"), 1, "and nothing applied"); + // Control: with the sidecar writable the same event applies. + std::fs::remove_dir_all(&side).unwrap(); + assert!(matches!( + h.adapter.deliver(revoke_a("revoke-a")), + Ok(Delivered::Applied(_)) + )); + assert_eq!(h.gen("a"), 2); +} + +#[test] +fn a_failed_sidecar_rewrite_after_the_drain_is_reported() { + let mut h = H::journaled(cfg(true, 4)); + h.register("a", &[]); + h.register("b", &["a"]); + h.register("d", &["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, + |_| { + let r = adapter.deliver(revoke_a("revoke-a")); + // The sidecar becomes unwritable before the drain. + std::fs::remove_file(&side).unwrap(); + std::fs::create_dir_all(side.join("block")).unwrap(); + r + }, + committed, + ) + .unwrap(); + assert!(matches!(out.outcome, Ok(Delivered::Deferred { .. }))); + // The revoke still applied; the failed rewrite is reported. + assert_eq!(out.redelivered.len(), 1); + assert!(matches!(out.redelivered[0].result, Ok(Outcome::Applied(_)))); + assert_eq!(h.gen("d"), 2); + let e = out.deferred_error.expect("the rewrite failure is reported"); + assert!(e.contains("deferred"), "{e}"); +} + +#[test] +fn an_open_whose_sidecar_cannot_be_rewritten_fails() { + let mut h = H::journaled(cfg(true, 4)); + // a is registered, so the deferred revoke applies on open and the + // sidecar must be rewritten without it. + h.register("a", &[]); + let dir = h.tmp.path().join("ro"); + std::fs::create_dir_all(&dir).unwrap(); + let copy = dir.join("j.jsonl"); + std::fs::copy(h.tmp.path().join("journal.jsonl"), ©).unwrap(); + let side = deferred_journal_path(©); + std::fs::write( + &side, + serde_json::to_string(&revoke_a("revoke-a")).unwrap() + "\n", + ) + .unwrap(); + let store = h.engine.completion_store.clone(); + let ticks = Arc::clone(&h.ticks); + let open = || PrepAdapter::open(cfg(true, 4), &store, ©, clock(&ticks)); + // A directory where the rewrite's temp file goes: the journal opens and + // locks as usual, only the sidecar rewrite fails. + let blocker = dir.join(format!(".j.jsonl.deferred.tmp-{}", std::process::id())); + std::fs::create_dir_all(blocker.join("x")).unwrap(); + match open() { + Err(SchedError::Journal(e)) => assert!(e.contains("j.jsonl.deferred"), "{e}"), + Err(e) => panic!("want the sidecar rewrite error, got {e}"), + Ok(_) => panic!("the open must fail when the sidecar cannot be rewritten"), + } + // 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. + std::fs::remove_dir_all(&blocker).unwrap(); + let (a, _) = open().unwrap(); + assert_eq!(a.generation("a"), Some(2)); + let replayed = a.take_replayed_deferred(); + assert_eq!(replayed.len(), 1); + assert!( + matches!(replayed[0].result, Err(SchedError::StaleGeneration { .. })), + "{:?}", + replayed[0].result + ); + assert_eq!(a.deferred_len(), 1); + assert!(a.discard_deferred("revoke-a").unwrap().is_some()); + assert_eq!(std::fs::read_to_string(&side).unwrap(), ""); +} + +#[test] +fn a_refused_redelivery_stays_queued_until_discarded() { + 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")); + // A cancel of b while b commits is refused with CommitInProgress and + // deferred. + let cancel_b = Event { + id: "cancel-b".into(), + kind: EventKind::Cancel { + task: "b".into(), + generation: 1, + }, + }; + let line = serde_json::to_string(&cancel_b).unwrap() + "\n"; + let adapter = Arc::clone(&h.adapter); + let ev = cancel_b.clone(); + let out = h + .adapter + .fenced_for_tests("b", 1, |_| adapter.deliver(ev), committed) + .unwrap(); + assert!( + matches!(out.outcome, Ok(Delivered::Deferred { ref committing, .. }) if committing == "b"), + "{:?}", + out.outcome + ); + // Redelivered after the commit: b is committed, so the cancel is + // refused (a committed task cannot abort). It is reported and kept, in memory and in the sidecar. + assert_eq!(h.state("b"), TaskState::Committed); + assert_eq!(out.redelivered.len(), 1); + assert!( + matches!(out.redelivered[0].result, Err(SchedError::Transition(_))), + "{:?}", + out.redelivered[0].result + ); + assert!(out.deferred_error.is_none()); + let queued: Vec<String> = h + .adapter + .deferred_events() + .into_iter() + .map(|e| e.id) + .collect(); + assert_eq!(queued, vec!["cancel-b".to_string()]); + assert_eq!(std::fs::read_to_string(&side).unwrap(), line); + // A restart replays it again: refused again, still kept. + drop(adapter); + h.restart(cfg(true, 4)); + let replayed = h.adapter.take_replayed_deferred(); + assert_eq!(replayed.len(), 1); + assert_eq!(replayed[0].id, "cancel-b"); + assert!( + matches!(replayed[0].result, Err(SchedError::Transition(_))), + "{:?}", + replayed[0].result + ); + assert_eq!(h.adapter.deferred_len(), 1); + assert_eq!(std::fs::read_to_string(&side).unwrap(), line); + // Only an explicit discard removes it, and the removal is journaled. + assert!(h.adapter.discard_deferred("unknown").unwrap().is_none()); + assert_eq!(h.adapter.deferred_len(), 1); + let gone = h.adapter.discard_deferred("cancel-b").unwrap(); + assert_eq!(gone.map(|e| e.id), Some("cancel-b".to_string())); + assert_eq!(h.adapter.deferred_len(), 0); + assert_eq!(std::fs::read_to_string(&side).unwrap(), ""); + assert!(h.adapter.discard_deferred("cancel-b").unwrap().is_none()); + h.restart(cfg(true, 4)); + assert!(h.adapter.take_replayed_deferred().is_empty()); +} + +#[test] +fn a_discard_that_cannot_be_journaled_keeps_the_event() { + let h = H::journaled(cfg(true, 4)); + let copy = h.tmp.path().join("journal-copy.jsonl"); + std::fs::copy(h.tmp.path().join("journal.jsonl"), ©).unwrap(); + let side = deferred_journal_path(©); + let line = serde_json::to_string(&revoke_a("revoke-a")).unwrap() + "\n"; + std::fs::write(&side, &line).unwrap(); + let store = h.engine.completion_store.clone(); + let (a, _) = PrepAdapter::open(cfg(true, 4), &store, ©, clock(&h.ticks)).unwrap(); + // No task a: refused and kept. + assert_eq!(a.deferred_len(), 1); + std::fs::remove_file(&side).unwrap(); + std::fs::create_dir_all(side.join("block")).unwrap(); + assert!(matches!( + a.discard_deferred("revoke-a"), + Err(DeliverError::DeferredJournal(_)) + )); + assert_eq!(a.deferred_len(), 1, "the failed discard keeps the event"); + // Control: writable again, the discard succeeds. + std::fs::remove_dir_all(&side).unwrap(); + assert!(a.discard_deferred("revoke-a").unwrap().is_some()); + assert_eq!(a.deferred_len(), 0); + assert_eq!(std::fs::read_to_string(&side).unwrap(), ""); +} + +#[test] +fn a_second_adapter_on_the_same_journal_is_refused() { + let mut h = H::journaled(cfg(true, 4)); + h.register("a", &[]); + let journal = h.tmp.path().join("journal.jsonl"); + let side = deferred_journal_path(&journal); + let line = serde_json::to_string(&revoke_a("revoke-x")).unwrap() + "\n"; + std::fs::write(&side, &line).unwrap(); + let store = h.engine.completion_store.clone(); + let ticks = Arc::clone(&h.ticks); + let open = |p: &Path| PrepAdapter::open(cfg(true, 4), &store, p, clock(&ticks)); + let held = |what: &str, r: Result<(PrepAdapter, Vec<String>), SchedError>| match r { + Err(SchedError::Journal(e)) => { + assert!(e.contains("held by another process"), "{what}: {e}") + } + Err(e) => panic!("{what}: want the journal lock error, got {e}"), + Ok(_) => panic!("{what}: a second adapter on one journal must be refused"), + }; + // The same path, a symlink to the file, a path through a symlinked + // directory and a path with a `..` step all name the one journal. + let link = h.tmp.path().join("link.jsonl"); + std::os::unix::fs::symlink(&journal, &link).unwrap(); + let dir_link = h.tmp.path().join("dirlink"); + std::os::unix::fs::symlink(h.tmp.path(), &dir_link).unwrap(); + std::fs::create_dir_all(h.tmp.path().join("sub")).unwrap(); + held("same path", open(&journal)); + held("file symlink", open(&link)); + held("dir symlink", open(&dir_link.join("journal.jsonl"))); + held("dot-dot", open(&h.tmp.path().join("sub/../journal.jsonl"))); + // None of the refused opens read or rewrote the first adapter's + // sidecar, and the first adapter still works. + assert_eq!(std::fs::read_to_string(&side).unwrap(), line); + assert_eq!(h.gen("a"), 1); + // Negative control: a different journal in the same directory opens, + // with its own sidecar. + let other = h.tmp.path().join("journal.log"); + assert_ne!(deferred_journal_path(&other), side); + let (o, _) = open(&other).unwrap(); + assert_eq!(o.deferred_len(), 0); + drop(o); + // Once the first adapter is gone the symlinked path opens the journal, + // and that adapter alone delivers the sidecar it now owns. + drop(h.adapter); + let (b, _) = open(&link).unwrap(); + let replayed = b.take_replayed_deferred(); + assert_eq!(replayed.len(), 1); + assert_eq!(replayed[0].id, "revoke-x"); + assert!(matches!(replayed[0].result, Ok(Outcome::Applied(_)))); + assert_eq!(b.generation("a"), Some(2)); + assert_eq!(std::fs::read_to_string(&side).unwrap(), ""); +} + +#[test] +fn a_journal_named_like_a_sidecar_is_refused() { + let h = H::journaled(cfg(true, 4)); + let tmp = &h.tmp; + let store = h.engine.completion_store.clone(); + let ticks = Arc::clone(&h.ticks); + let bad = tmp.path().join("x.deferred"); + match PrepAdapter::open(cfg(true, 4), &store, &bad, clock(&ticks)) { + Err(SchedError::Journal(e)) => assert!(e.contains(".deferred"), "{e}"), + Err(e) => panic!("want a journal error, got {e}"), + Ok(_) => panic!("a journal ending in .deferred must be refused"), + } + assert!(!bad.exists(), "nothing was created"); + // Negative control: the same directory, a plain name. + let good = tmp.path().join("x.jsonl"); + assert!(PrepAdapter::open(cfg(true, 4), &store, &good, clock(&ticks)).is_ok()); + assert_eq!( + deferred_journal_path(&good), + tmp.path().join("x.jsonl.deferred") + ); +} diff --git a/crates/spark-harness/src/execution.rs b/crates/spark-harness/src/execution.rs index 2795af0b..3284f734 100644 --- a/crates/spark-harness/src/execution.rs +++ b/crates/spark-harness/src/execution.rs @@ -5,13 +5,22 @@ //! Blocked --dispatch--> Provisional --work done--> AwaitingFinalProof --finalize--> Committable //! ^ | | | //! +------ revoke --------+---------------------------+-------------------------------+ -//! any non-Aborted --cancel / failure / lease expiry--> Aborted --retry--> Blocked +//! any of the first four --cancel / failure / lease expiry--> Aborted --retry--> Blocked +//! +//! Committable --begin commit--> Committing --outcome--> Committed | CommitUncertain | Aborted //! ``` //! -//! There is no `Committed` state. `Committable` means "every dependency is -//! final-verified for its current generation"; committing is done by the -//! existing effect/World machinery in aien-runtime, which this crate does not -//! touch. +//! `Committable` means "every dependency is final-verified for its current +//! generation". Committing itself is done by the existing effect/World +//! machinery in aien-runtime, which this crate does not touch. The optional +//! `Committing` state (Headstart M3, issue #537) lets a caller record that +//! it is about to run such a commit: a journaled `BeginCommit` freezes the +//! task's generation and the producer completions it was checked against, +//! and a journaled `CommitOutcome` ends it. While a task is `Committing`, +//! every event that would revoke, cancel, fail or re-generate it (directly +//! or through an upstream producer) is refused. A `Committing` task found +//! after a restart has no recorded outcome and becomes `CommitUncertain`; +//! it is never run again. `Committed` and `CommitUncertain` are terminal. //! //! Revocation returns a task to `Blocked` rather than `Aborted`. The task did //! nothing wrong: an upstream producer failed, changed its interface or @@ -21,8 +30,7 @@ //! failure, cancellation, lost lease). //! //! Only `Provisional` holds resource permits. Leaving `Provisional` releases -//! them, so `Blocked`, `AwaitingFinalProof`, `Committable` and `Aborted` -//! tasks hold none. +//! them, so every other state holds none. use serde::{Deserialize, Serialize}; use std::fmt; @@ -34,6 +42,13 @@ pub enum TaskState { AwaitingFinalProof, Committable, Aborted, + /// A commit of this task's result is running (see the module docs). + Committing, + /// The commit reported success. Terminal. + Committed, + /// The commit's outcome is unknown (it may have reached the World). + /// Terminal: never run again; an operator resolves it. + CommitUncertain, } impl TaskState { @@ -44,9 +59,26 @@ impl TaskState { TaskState::AwaitingFinalProof => "awaiting_final_proof", TaskState::Committable => "committable", TaskState::Aborted => "aborted", + TaskState::Committing => "committing", + TaskState::Committed => "committed", + TaskState::CommitUncertain => "commit_uncertain", } } + /// `Committed` or `CommitUncertain`: the task is done and no upstream + /// change reaches it or, through it, its consumers. + pub fn is_commit_terminal(self) -> bool { + matches!(self, TaskState::Committed | TaskState::CommitUncertain) + } + + /// A completion that consumers may treat as final. + pub fn is_final(self) -> bool { + matches!( + self, + TaskState::Committable | TaskState::Committing | TaskState::Committed + ) + } + /// States whose work or proof is built on upstream artifacts and must be /// revoked when upstream changes. pub fn is_active(self) -> bool { @@ -95,6 +127,8 @@ pub fn check_transition(from: TaskState, to: TaskState) -> Result<(), IllegalTra Aborted ) | (Aborted, Blocked) + | (Committable, Committing) + | (Committing, Committed | CommitUncertain | Aborted) ); if ok { Ok(()) @@ -118,6 +152,15 @@ mod tests { (Aborted, Committable), (Committable, Provisional), (Blocked, Blocked), + (AwaitingFinalProof, Committing), + (Committing, Blocked), + (Committing, Committable), + (Committed, Blocked), + (Committed, Aborted), + (Committed, Committing), + (CommitUncertain, Blocked), + (CommitUncertain, Aborted), + (CommitUncertain, Committing), ] { assert!(check_transition(from, to).is_err(), "{from:?} -> {to:?}"); } @@ -127,6 +170,10 @@ mod tests { (AwaitingFinalProof, Committable), (Committable, Blocked), (Aborted, Blocked), + (Committable, Committing), + (Committing, Committed), + (Committing, CommitUncertain), + (Committing, Aborted), ] { assert!(check_transition(from, to).is_ok(), "{from:?} -> {to:?}"); } diff --git a/crates/spark-harness/src/scheduler/core.rs b/crates/spark-harness/src/scheduler/core.rs index 0e3cbae8..e5783b97 100644 --- a/crates/spark-harness/src/scheduler/core.rs +++ b/crates/spark-harness/src/scheduler/core.rs @@ -99,6 +99,80 @@ pub enum EventKind { }, /// Lets time pass: expires leases. Tick, + /// `Committable -> Committing` (Headstart M3, issue #537). Freezes the + /// task at `generation` with its own accepted completion and every + /// producer's accepted completion, all of which must equal the current + /// state and verify in the store. Refused when another commit is + /// running in the same dependency chain. + BeginCommit { + task: String, + generation: u64, + completion: ProofClaim, + producers: BTreeMap<String, ProofClaim>, + }, + /// Ends a `Committing` task with the wrapped call's outcome. + CommitOutcome { + task: String, + generation: u64, + outcome: CommitResult, + }, + /// Bind an external request `key` (opaque to M2, at most + /// [`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. + BindApproval { + key: String, + task: String, + generation: u64, + }, +} + +/// Most request keys [`EventKind::BindApproval`] holds for one task. +pub const MAX_APPROVAL_BINDINGS_PER_TASK: usize = 64; +/// Longest request key [`EventKind::BindApproval`] accepts, in bytes. +pub const MAX_APPROVAL_KEY_LEN: usize = 512; + +/// One bound request: the task generation whose commit fence it must pass. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct ApprovalBinding { + pub task: String, + 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. +fn binding_ended(state: TaskState) -> bool { + matches!(state, TaskState::Committed | TaskState::CommitUncertain) +} + +/// How a commit ended. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "result", rename_all = "snake_case", deny_unknown_fields)] +pub enum CommitResult { + /// The commit succeeded: `Committed`. + Committed { detail: String }, + /// The commit was refused before any durable effect: `Aborted` + /// (retryable at the next generation); consumers are revoked. + Failed { reason: String }, + /// The outcome is unknown: `CommitUncertain`, never run again; + /// consumers are revoked. + Uncertain { reason: String }, +} + +/// What a `BeginCommit` froze. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct CommitInputs { + pub completion: ProofClaim, + pub producers: BTreeMap<String, ProofClaim>, + pub began_at: u64, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] @@ -160,6 +234,9 @@ pub struct TaskEntry { pub queued: bool, pub last_reason: Option<String>, pub timing: TaskTiming, + /// Set by `BeginCommit`; kept after the outcome as the record of what + /// the commit was checked against. + pub commit: Option<CommitInputs>, } impl TaskEntry { @@ -177,11 +254,14 @@ impl TaskEntry { queued: false, last_reason: None, timing: TaskTiming::new(at), + commit: None, } } + /// Final for consumers: `Committable`, `Committing` or `Committed` + /// with an accepted completion. pub(crate) fn final_ready(&self) -> bool { - self.state == TaskState::Committable && self.completion.is_some() + self.state.is_final() && self.completion.is_some() } pub(crate) fn interface_ready(&self) -> bool { @@ -209,6 +289,8 @@ pub struct Core { pub(crate) pool: PermitPool, /// Bounded memory of applied event ids (`dedup.rs`). pub(crate) seen: Seen, + /// Bound requests by key ([`EventKind::BindApproval`]). + pub(crate) approvals: BTreeMap<String, ApprovalBinding>, pub(crate) seq: u64, pub(crate) last_at: u64, } @@ -347,7 +429,8 @@ impl Core { reason: &str, fx: &mut Effects, ) -> Result<(), SchedError> { - for d in self.graph.descendants(producer) { + self.guard_descendants(producer)?; + for d in self.affected(producer) { let t = self.task(&d)?; if t.state.is_active() { let next = t.generation + 1; @@ -360,6 +443,74 @@ impl Core { Ok(()) } + /// Descendants of `id` that an upstream change reaches, breadth-first, + /// excluding `id`. A `Committed` or `CommitUncertain` task is done: it + /// is neither returned nor walked through (its consumers are reached + /// only along other paths). + pub(crate) fn affected(&self, id: &str) -> Vec<String> { + let mut seen = std::collections::BTreeSet::new(); + let mut out = Vec::new(); + let mut q: VecDeque<&String> = self.graph.consumers_of(id).collect(); + while let Some(n) = q.pop_front() { + if !seen.insert(n.clone()) { + continue; + } + if self + .tasks + .get(n) + .is_some_and(|t| t.state.is_commit_terminal()) + { + continue; + } + out.push(n.clone()); + q.extend(self.graph.consumers_of(n)); + } + out + } + + /// The `Committing` task an upstream change of `id` would reach. + fn committing_below(&self, id: &str) -> Option<String> { + self.affected(id) + .into_iter() + .find(|d| self.tasks.get(d).map(|t| t.state) == Some(TaskState::Committing)) + } + + fn guard_descendants(&self, id: &str) -> Result<(), SchedError> { + match self.committing_below(id) { + Some(committing) => Err(SchedError::CommitInProgress { + task: id.to_string(), + committing, + }), + None => Ok(()), + } + } + + /// Refuse an event that would change `id` itself while it is + /// `Committing`, or reach a `Committing` task below it. + pub(crate) fn guard_commit(&self, id: &str) -> Result<(), SchedError> { + if self.task(id)?.state == TaskState::Committing { + return Err(SchedError::CommitInProgress { + task: id.to_string(), + committing: id.to_string(), + }); + } + self.guard_descendants(id) + } + + /// A `Committing` task in the same chain as `id` (upstream or + /// downstream along [`Core::affected`] paths), other than `id`. + fn commit_in_chain(&self, id: &str) -> Option<String> { + if let Some(c) = self.committing_below(id) { + return Some(c); + } + self.tasks + .iter() + .filter(|(other, t)| t.state == TaskState::Committing && other.as_str() != id) + .map(|(other, _)| other) + .find(|other| self.affected(other).iter().any(|d| d == id)) + .cloned() + } + fn eligible(&self, cfg: &ProvisionalConfig, id: &str) -> bool { let Some(t) = self.tasks.get(id) else { return false; @@ -540,6 +691,7 @@ impl Core { |s| s != TaskState::Aborted, "start a new generation (use retry)", )?; + self.guard_commit(task)?; self.reset_to_blocked(task, *generation, at, "new generation", &mut fx)?; self.revoke_descendants(task, at, "producer new generation", &mut fx)?; } @@ -550,6 +702,7 @@ impl Core { } => { self.require_generation(task, *generation)?; self.require_state(task, |s| s != TaskState::Aborted, "fail")?; + self.guard_commit(task)?; self.abort(task, at, &format!("failed: {reason}"), &mut fx)?; self.revoke_descendants(task, at, "producer failed", &mut fx)?; } @@ -610,8 +763,9 @@ impl Core { EventKind::Cancel { task, generation } => { self.require_generation(task, *generation)?; self.require_state(task, |s| s != TaskState::Aborted, "cancel")?; + self.guard_commit(task)?; self.abort(task, at, "cancelled", &mut fx)?; - for d in self.graph.descendants(task) { + for d in self.affected(task) { if self.task(&d)?.state != TaskState::Aborted { self.abort(&d, at, &format!("ancestor '{task}' cancelled"), &mut fx)?; } @@ -657,6 +811,9 @@ impl Core { .iter() .filter(|(_, t)| t.state == TaskState::Provisional && !t.lease_valid(at)) .map(|(id, _)| id.clone()) + // An expiry that would reach a running commit waits for + // its outcome (a later Tick expires it). + .filter(|id| self.guard_commit(id).is_ok()) .collect(); for id in expired { if self.task(&id)?.state == TaskState::Provisional { @@ -665,8 +822,127 @@ impl Core { } } } + EventKind::BeginCommit { + task, + generation, + completion, + producers, + } => { + self.require_generation(task, *generation)?; + self.require_state(task, |s| s == TaskState::Committable, "begin a commit")?; + if let Some(committing) = self.commit_in_chain(task) { + return Err(SchedError::CommitInProgress { + task: task.clone(), + committing, + }); + } + if self.task(task)?.completion.as_ref() != Some(completion) { + return Err(bad(format!( + "begin_commit completion for '{task}' is not its accepted completion" + ))); + } + let expected: Vec<&String> = self.graph.producers_of(task).collect(); + if expected.len() != producers.len() + || expected.iter().any(|p| !producers.contains_key(*p)) + { + return Err(bad(format!( + "begin_commit for '{task}' must name exactly its producers" + ))); + } + for (p, claim) in producers { + let pt = self.task(p)?; + // A producer that is itself committing is refused above. + if !matches!(pt.state, TaskState::Committable | TaskState::Committed) + || pt.completion.as_ref() != Some(claim) + { + return Err(SchedError::ProducerNotFinal { + producer: p.clone(), + detail: format!( + "state {}, completion differs from the begin_commit input: {}", + pt.state.as_str(), + pt.completion.as_ref() != Some(claim) + ), + }); + } + } + self.set_state(task, TaskState::Committing, at)?; + self.task_mut(task)?.commit = Some(CommitInputs { + completion: completion.clone(), + producers: producers.clone(), + began_at: at, + }); + } + EventKind::CommitOutcome { + task, + generation, + outcome, + } => { + self.require_generation(task, *generation)?; + self.require_state( + task, + |s| s == TaskState::Committing, + "record a commit outcome", + )?; + // BeginCommit refused any second commit in this chain, so + // no Committing task is reachable from here. + match outcome { + CommitResult::Committed { detail } => { + self.set_state(task, TaskState::Committed, at)?; + self.task_mut(task)?.last_reason = Some(format!("committed: {detail}")); + } + CommitResult::Failed { reason } => { + self.abort(task, at, &format!("commit failed: {reason}"), &mut fx)?; + self.revoke_descendants(task, at, "producer commit failed", &mut fx)?; + } + CommitResult::Uncertain { reason } => { + self.revoke_descendants(task, at, "producer commit uncertain", &mut fx)?; + self.set_state(task, TaskState::CommitUncertain, at)?; + self.task_mut(task)?.last_reason = + Some(format!("commit uncertain: {reason}")); + } + } + } + EventKind::BindApproval { + key, + task, + generation, + } => { + if key.is_empty() || key.len() > MAX_APPROVAL_KEY_LEN { + return Err(bad(format!( + "bind_approval key must be 1 to {MAX_APPROVAL_KEY_LEN} bytes" + ))); + } + self.require_generation(task, *generation)?; + self.require_state( + task, + |s| !binding_ended(s), + "bind a request to a task that already ended", + )?; + 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, + }); + } + self.approvals.insert( + key.clone(), + ApprovalBinding { + task: task.clone(), + generation: *generation, + }, + ); + } } 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. + let tasks = &self.tasks; + self.approvals + .retain(|_, b| tasks.get(&b.task).is_some_and(|t| !binding_ended(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/src/scheduler/dedup.rs b/crates/spark-harness/src/scheduler/dedup.rs index b9bf72c9..05843f8b 100644 --- a/crates/spark-harness/src/scheduler/dedup.rs +++ b/crates/spark-harness/src/scheduler/dedup.rs @@ -54,6 +54,15 @@ pub(crate) fn generation_scope(kind: &EventKind) -> Option<(&str, u64)> { | EventKind::Retry { task, generation } | EventKind::Revoke { task, generation, .. + } + | EventKind::BeginCommit { + task, generation, .. + } + | EventKind::CommitOutcome { + task, generation, .. + } + | EventKind::BindApproval { + task, generation, .. } => Some((task.as_str(), *generation)), EventKind::RegisterTask { .. } | EventKind::AddDependency { .. } diff --git a/crates/spark-harness/src/scheduler/error.rs b/crates/spark-harness/src/scheduler/error.rs index 6b5d4f04..5c4bd270 100644 --- a/crates/spark-harness/src/scheduler/error.rs +++ b/crates/spark-harness/src/scheduler/error.rs @@ -68,6 +68,20 @@ pub enum SchedError { error: CompletionError, }, Journal(String), + /// The event would revoke, cancel, fail or re-generate a `Committing` + /// task (`committing`), directly or through `task` upstream of it, or + /// would start a second commit in the same dependency chain. Deliver it + /// again after the commit outcome is recorded. + CommitInProgress { + task: String, + committing: String, + }, + /// A new request key would exceed the task's share of the + /// bound-request table. + BindingsFull { + task: String, + capacity: usize, + }, } impl fmt::Display for SchedError { @@ -132,6 +146,14 @@ impl fmt::Display for SchedError { write!(f, "proof for '{task}' failed re-verification: {error}") } SchedError::Journal(m) => write!(f, "journal: {m}"), + SchedError::CommitInProgress { task, committing } => write!( + f, + "task '{committing}' is committing; '{task}' cannot change it until its outcome is recorded" + ), + SchedError::BindingsFull { task, capacity } => write!( + f, + "task '{task}' holds its maximum of {capacity} bound request keys; no new key is bound" + ), } } } diff --git a/crates/spark-harness/src/scheduler/gates.rs b/crates/spark-harness/src/scheduler/gates.rs index ae14f9a7..0d0151d9 100644 --- a/crates/spark-harness/src/scheduler/gates.rs +++ b/crates/spark-harness/src/scheduler/gates.rs @@ -6,7 +6,7 @@ //! (which records what was accepted earlier) only says which receipt to //! re-check; it is never the authority on its own. -use super::core::{Binding, BindingLevel, EventKind, Revocation, TaskEntry}; +use super::core::{Binding, BindingLevel, CommitResult, EventKind, Revocation, TaskEntry}; use super::error::SchedError; use super::{Event, Outcome, Scheduler, RESERVED_ID_PREFIX}; use crate::completion::CompletionError; @@ -44,6 +44,18 @@ impl Scheduler { self.core.require_generation(task, *generation)?; self.may_finalize(task)?; } + EventKind::BeginCommit { + task, + generation, + completion, + .. + } => { + // Every producer re-verified (recursively), then the task's + // own completion; `apply` checks the claims equal the state. + self.core.require_generation(task, *generation)?; + self.may_finalize(task)?; + verify_final(&self.store, task, *generation, completion).map_err(proof(task))?; + } _ => {} } Ok(()) @@ -121,10 +133,12 @@ impl Scheduler { )); } let t = self.core.task(task)?; + // A producer (depth > 0) may also be frozen in `Committing`. if !matches!( t.state, TaskState::AwaitingFinalProof | TaskState::Committable - ) { + ) && !(depth > 0 && t.state == TaskState::Committing) + { return Err(SchedError::WrongState { task: task.to_string(), state: t.state, @@ -158,7 +172,11 @@ impl Scheduler { } }; let r = verify_final(&self.store, p, pt.generation, claim).map_err(proof(p))?; - self.finalize_check(p, depth)?; + // A committed producer is done: its own completion is the proof, + // and its upstream may have moved on since (see `Core::affected`). + if pt.state != TaskState::Committed { + self.finalize_check(p, depth)?; + } Ok(r) } @@ -245,7 +263,12 @@ impl Scheduler { .producers_of(id) .try_for_each(|p| self.bound_readiness(id, t, p).map(|_| ())), TaskState::Committable => self.may_finalize(id).map(|_| ()), - TaskState::Blocked | TaskState::Aborted => Ok(()), + // Frozen or done: not re-checked (see `audit`). + TaskState::Blocked + | TaskState::Aborted + | TaskState::Committing + | TaskState::Committed + | TaskState::CommitUncertain => Ok(()), }; if let Err(e) = check { out.push(revocation(id, e)); @@ -265,12 +288,20 @@ impl Scheduler { /// after all of its revocations, so no consumer is dispatched against a /// claim the same round is about to revoke. Each round revokes at least /// one active task; the round count is capped as a backstop. + /// + /// A revocation that would reach a `Committing` task is deferred (left + /// out of the batch): the commit was checked against the store when it + /// began, and a later audit catches the change once the outcome is in. pub fn audit(&mut self) -> Result<Vec<String>, SchedError> { let mut revoked = Vec::new(); + let ready = |s: &Self, mut b: Vec<Revocation>| { + b.retain(|r| s.core.guard_commit(&r.task).is_ok()); + b + }; for _ in 0..=2 * self.core.tasks.len() { - let mut batch = self.own_claim_failures(); + let mut batch = ready(self, self.own_claim_failures()); if batch.is_empty() { - batch = self.binding_failures(); + batch = ready(self, self.binding_failures()); } if batch.is_empty() { return Ok(revoked); @@ -287,6 +318,35 @@ impl Scheduler { "audit did not converge; refusing to continue".to_string(), )) } + + /// After a replay: every task still `Committing` lost its outcome with + /// the old process. Its commit may or may not have reached the World, so + /// it becomes `CommitUncertain` through a journaled `CommitOutcome` and + /// is never run again (as `approved_replay` treats an in-flight claim). + /// Returns those tasks. + pub(crate) fn settle_interrupted_commits(&mut self) -> Result<Vec<String>, SchedError> { + let open: Vec<(String, u64)> = self + .core + .tasks + .iter() + .filter(|(_, t)| t.state == TaskState::Committing) + .map(|(id, t)| (id.clone(), t.generation)) + .collect(); + for (task, generation) in &open { + let event = Event { + id: format!("{RESERVED_ID_PREFIX}commit-uncertain-{}", self.core.seq + 1), + kind: EventKind::CommitOutcome { + task: task.clone(), + generation: *generation, + outcome: CommitResult::Uncertain { + reason: "restarted while committing; no outcome was recorded".to_string(), + }, + }, + }; + self.deliver_unchecked(event)?; + } + Ok(open.into_iter().map(|(t, _)| t).collect()) + } } fn revocation(task: &str, e: SchedError) -> Revocation { diff --git a/crates/spark-harness/src/scheduler/mod.rs b/crates/spark-harness/src/scheduler/mod.rs index 869c99ab..d24579fe 100644 --- a/crates/spark-harness/src/scheduler/mod.rs +++ b/crates/spark-harness/src/scheduler/mod.rs @@ -68,7 +68,8 @@ pub mod timing; mod unit_tests; pub use self::core::{ - Binding, BindingLevel, Effects, Event, EventKind, JournalEntry, Revocation, TaskEntry, + ApprovalBinding, Binding, BindingLevel, CommitInputs, CommitResult, Effects, Event, EventKind, + JournalEntry, Revocation, TaskEntry, MAX_APPROVAL_BINDINGS_PER_TASK, MAX_APPROVAL_KEY_LEN, }; pub use self::error::SchedError; pub use self::permits::{PermitPool, ResourceLimits, ResourceRequest}; @@ -178,9 +179,12 @@ pub struct Unaudited { } impl Unaudited { - /// Re-verify every replayed active task against the store, revoke the - /// ones that fail, and hand out the scheduler. + /// Mark every replayed `Committing` task `CommitUncertain` (its outcome + /// was lost; it is never run again), re-verify every replayed active + /// task against the store, revoke the ones that fail, and hand out the + /// scheduler. pub fn audit(mut self) -> Result<(Scheduler, Vec<String>), SchedError> { + self.sched.settle_interrupted_commits()?; let revoked = self.sched.audit()?; Ok((self.sched, revoked)) } @@ -299,6 +303,16 @@ impl Scheduler { self.task(id).map(|t| t.generation) } + /// The fence a bound request key must pass ([`EventKind::BindApproval`]). + pub fn approval(&self, key: &str) -> Option<&ApprovalBinding> { + self.core.approvals.get(key) + } + + /// How many request keys are bound. + pub fn approvals_len(&self) -> usize { + self.core.approvals.len() + } + pub fn queue(&self) -> Vec<String> { self.core.queue.iter().cloned().collect() } diff --git a/crates/spark-harness/src/scheduler/timing.rs b/crates/spark-harness/src/scheduler/timing.rs index c31bf274..bdeb2c51 100644 --- a/crates/spark-harness/src/scheduler/timing.rs +++ b/crates/spark-harness/src/scheduler/timing.rs @@ -39,7 +39,11 @@ impl TaskTiming { TaskState::Blocked => self.blocked += spent, TaskState::Provisional => self.provisional += spent, TaskState::AwaitingFinalProof => self.awaiting_final_proof += spent, - TaskState::Committable | TaskState::Aborted => {} + TaskState::Committable + | TaskState::Aborted + | TaskState::Committing + | TaskState::Committed + | TaskState::CommitUncertain => {} } self.since = at; } diff --git a/crates/spark-harness/tests/provisional_commit.rs b/crates/spark-harness/tests/provisional_commit.rs new file mode 100644 index 00000000..dc2ff309 --- /dev/null +++ b/crates/spark-harness/tests/provisional_commit.rs @@ -0,0 +1,728 @@ +//! Headstart M3 (#537): the `Committing` state. A journaled `BeginCommit` +//! freezes a `Committable` task and its inputs; nothing upstream may change +//! them until a `CommitOutcome` is recorded; a replay that finds no outcome +//! marks the task `CommitUncertain` and never runs it again. Bound request +//! keys are journaled, kept while a task is aborted or retried, and dropped +//! when its commit ended. + +mod common; + +use common::{enabled, H}; +use spark_harness::execution::TaskState; +use spark_harness::readiness::ProofClaim; +use spark_harness::scheduler::{ + CommitResult, Effects, EventKind, Outcome, SchedError, MAX_APPROVAL_BINDINGS_PER_TASK, + MAX_APPROVAL_KEY_LEN, RESERVED_ID_PREFIX, +}; +use std::collections::BTreeMap; + +fn remove_receipt(h: &H, receipt_id: &str) { + std::fs::remove_file( + h.engine + .completion_store + .join("receipts") + .join(format!("{receipt_id}.json")), + ) + .unwrap(); +} + +fn completion(h: &H, task: &str) -> ProofClaim { + h.sched.task(task).unwrap().completion.clone().unwrap() +} + +/// `BeginCommit` built from the task's current accepted state. +fn begin_kind(h: &H, task: &str) -> EventKind { + let producers: BTreeMap<String, ProofClaim> = h + .sched + .task(task) + .unwrap() + .bindings + .keys() + .map(|p| (p.clone(), completion(h, p))) + .collect(); + EventKind::BeginCommit { + task: task.into(), + generation: h.generation(task), + completion: completion(h, task), + producers, + } +} + +fn begin(h: &mut H, task: &str) -> Result<Outcome, SchedError> { + h.advance(10); + let kind = begin_kind(h, task); + h.send(kind) +} + +fn outcome(h: &mut H, task: &str, outcome: CommitResult) -> Effects { + let generation = h.generation(task); + h.ok(EventKind::CommitOutcome { + task: task.into(), + generation, + outcome, + }) +} + +fn committed() -> CommitResult { + CommitResult::Committed { + detail: "test".into(), + } +} + +fn in_progress(r: &Result<Outcome, SchedError>, committing: &str) -> bool { + matches!(r, Err(SchedError::CommitInProgress { committing: c, .. }) if c == committing) +} + +/// a -> b -> c with a and b final. c is still provisional. +fn chain() -> H { + let mut h = H::new(enabled()); + h.register("a", 1, &[]); + h.register("b", 1, &["a"]); + h.register("c", 1, &["b"]); + h.publish("a", 1); + h.publish("b", 1); + h.finish("a"); + h.finish("b"); + assert_eq!(h.sched.state("b"), Some(TaskState::Committable)); + assert_eq!(h.sched.state("c"), Some(TaskState::Provisional)); + h +} + +#[test] +fn begin_commit_freezes_the_inputs_and_the_outcome_ends_it() { + let mut h = chain(); + let gen_b = h.generation("b"); + assert!(matches!(begin(&mut h, "b"), Ok(Outcome::Applied(_)))); + assert_eq!(h.sched.state("b"), Some(TaskState::Committing)); + let inputs = h.sched.task("b").unwrap().commit.clone().unwrap(); + assert_eq!(inputs.completion, completion(&h, "b")); + assert_eq!(inputs.producers.get("a"), Some(&completion(&h, "a"))); + // The consumer keeps working against the committing producer. + assert_eq!(h.sched.state("c"), Some(TaskState::Provisional)); + outcome(&mut h, "b", committed()); + assert_eq!(h.sched.state("b"), Some(TaskState::Committed)); + assert_eq!(h.generation("b"), gen_b); + // Done: a second begin is refused, as is a second outcome. + assert!(matches!( + begin(&mut h, "b"), + Err(SchedError::WrongState { .. }) + )); + let r = h.send(EventKind::CommitOutcome { + task: "b".into(), + generation: gen_b, + outcome: committed(), + }); + assert!(matches!(r, Err(SchedError::WrongState { .. })), "{r:?}"); +} + +#[test] +fn while_committing_upstream_and_own_changes_are_refused() { + let mut h = chain(); + let gen_a = h.generation("a"); + let gen_b = h.generation("b"); + begin(&mut h, "b").unwrap(); + let refused_on_a = [ + EventKind::Revoke { + task: "a".into(), + generation: gen_a, + reason: "test".into(), + }, + EventKind::Cancel { + task: "a".into(), + generation: gen_a, + }, + EventKind::NewGeneration { + task: "a".into(), + generation: gen_a + 1, + }, + EventKind::ProducerFailed { + task: "a".into(), + generation: gen_a, + reason: "test".into(), + }, + EventKind::InterfacePublished { + task: "a".into(), + generation: gen_a, + claim: h.mint_interface("a", 2), + }, + ]; + for kind in refused_on_a { + let r = h.send(kind.clone()); + assert!(in_progress(&r, "b"), "{kind:?}: {r:?}"); + } + let refused_on_b = [ + EventKind::Cancel { + task: "b".into(), + generation: gen_b, + }, + EventKind::NewGeneration { + task: "b".into(), + generation: gen_b + 1, + }, + EventKind::ProducerFailed { + task: "b".into(), + generation: gen_b, + reason: "test".into(), + }, + ]; + for kind in refused_on_b { + let r = h.send(kind.clone()); + assert!(in_progress(&r, "b"), "{kind:?}: {r:?}"); + } + // Revoke needs an active task; Committing is not one. + let r = h.send(EventKind::Revoke { + task: "b".into(), + generation: gen_b, + reason: "test".into(), + }); + assert!(matches!(r, Err(SchedError::WrongState { .. })), "{r:?}"); + assert_eq!(h.sched.state("a"), Some(TaskState::Committable)); + assert_eq!(h.sched.state("b"), Some(TaskState::Committing)); + assert_eq!(h.generation("a"), gen_a); + assert_eq!(h.generation("b"), gen_b); + + // Once the outcome is in, the same revoke is accepted and does not + // reach the committed task. + outcome(&mut h, "b", committed()); + let fx = h.ok(EventKind::Revoke { + task: "a".into(), + generation: gen_a, + reason: "test".into(), + }); + assert!(!fx.revoked.contains(&"b".to_string()), "{fx:?}"); + assert_eq!(h.sched.state("b"), Some(TaskState::Committed)); + assert_eq!(h.sched.state("c"), Some(TaskState::Provisional)); +} + +#[test] +fn without_a_commit_the_same_revoke_reaches_the_consumer() { + // Negative control for the test above. + let mut h = chain(); + let gen_a = h.generation("a"); + let gen_b = h.generation("b"); + h.ok(EventKind::Revoke { + task: "a".into(), + generation: gen_a, + reason: "test".into(), + }); + assert_eq!(h.sched.state("b"), Some(TaskState::Blocked)); + assert_eq!(h.generation("b"), gen_b + 1); +} + +#[test] +fn begin_commit_refuses_inputs_that_differ_from_the_state() { + let mut h = chain(); + let good = begin_kind(&h, "b"); + let EventKind::BeginCommit { + generation, + completion: own, + producers, + .. + } = good.clone() + else { + unreachable!() + }; + let mut other = own.clone(); + other.digest = format!("{}0", other.digest); + let with = + |completion: ProofClaim, producers: BTreeMap<String, ProofClaim>| EventKind::BeginCommit { + task: "b".into(), + generation, + completion, + producers, + }; + let mut missing = producers.clone(); + missing.clear(); + let mut extra = producers.clone(); + extra.insert("c".into(), own.clone()); + let mut wrong_producer = producers.clone(); + wrong_producer.insert("a".into(), other.clone()); + let cases = [ + ("own completion", with(other.clone(), producers.clone())), + ("no producers", with(own.clone(), missing)), + ("extra producer", with(own.clone(), extra)), + ("producer claim", with(own.clone(), wrong_producer)), + ( + "stale generation", + EventKind::BeginCommit { + task: "b".into(), + generation: generation + 1, + completion: own.clone(), + producers: producers.clone(), + }, + ), + ]; + for (what, kind) in cases { + let r = h.send(kind); + assert!(r.is_err(), "{what}: {r:?}"); + assert_eq!(h.sched.state("b"), Some(TaskState::Committable), "{what}"); + } + // Not committable yet. + let r = h.send(EventKind::BeginCommit { + task: "c".into(), + generation: h.generation("c"), + completion: own.clone(), + producers: BTreeMap::from([("b".to_string(), completion(&h, "b"))]), + }); + assert!(matches!(r, Err(SchedError::WrongState { .. })), "{r:?}"); + // A producer receipt that no longer verifies. + remove_receipt(&h, &completion(&h, "a").receipt_id); + let r = h.send(good.clone()); + assert!( + matches!(r, Err(SchedError::Proof { ref task, .. }) if task == "a"), + "{r:?}" + ); + assert_eq!(h.sched.state("b"), Some(TaskState::Committable)); +} + +#[test] +fn begin_commit_accepts_the_matching_inputs() { + // Positive control for the refusals above. + let mut h = chain(); + let kind = begin_kind(&h, "b"); + assert!(matches!(h.send(kind), Ok(Outcome::Applied(_)))); +} + +#[test] +fn only_one_commit_runs_per_dependency_chain() { + let mut h = chain(); + h.register("x", 1, &[]); + h.publish("x", 1); + h.finish("x"); + // c becomes committable too. + h.publish("c", 1); + h.finish("c"); + begin(&mut h, "b").unwrap(); + // Below and above b: refused. + assert!(in_progress(&begin(&mut h, "c"), "b")); + assert!(in_progress(&begin(&mut h, "a"), "b")); + // An unrelated task commits at the same time. + assert!(begin(&mut h, "x").is_ok()); + outcome(&mut h, "b", committed()); + // a is upstream of a committed task only: it may commit now. + assert!(begin(&mut h, "c").is_ok()); + assert!(begin(&mut h, "a").is_ok()); +} + +#[test] +fn failed_commit_aborts_retryably_and_revokes_consumers() { + let mut h = chain(); + let gen_b = h.generation("b"); + let gen_c = h.generation("c"); + begin(&mut h, "b").unwrap(); + outcome( + &mut h, + "b", + CommitResult::Failed { + reason: "refused".into(), + }, + ); + assert_eq!(h.sched.state("b"), Some(TaskState::Aborted)); + assert_eq!(h.sched.state("c"), Some(TaskState::Blocked)); + assert_eq!(h.generation("c"), gen_c + 1); + h.ok(EventKind::Retry { + task: "b".into(), + generation: gen_b, + }); + assert_eq!(h.generation("b"), gen_b + 1); +} + +#[test] +fn uncertain_commit_is_terminal_and_revokes_consumers() { + let mut h = chain(); + let gen_b = h.generation("b"); + let gen_c = h.generation("c"); + begin(&mut h, "b").unwrap(); + outcome( + &mut h, + "b", + CommitResult::Uncertain { + reason: "transport".into(), + }, + ); + assert_eq!(h.sched.state("b"), Some(TaskState::CommitUncertain)); + assert_eq!(h.sched.state("c"), Some(TaskState::Blocked)); + assert_eq!(h.generation("c"), gen_c + 1); + for kind in [ + EventKind::Retry { + task: "b".into(), + generation: gen_b, + }, + EventKind::Cancel { + task: "b".into(), + generation: gen_b, + }, + EventKind::NewGeneration { + task: "b".into(), + generation: gen_b + 1, + }, + ] { + let r = h.send(kind.clone()); + assert!(r.is_err(), "{kind:?}: {r:?}"); + assert_eq!(h.sched.state("b"), Some(TaskState::CommitUncertain)); + } + assert!(begin(&mut h, "b").is_err()); +} + +#[test] +fn replayed_commit_without_an_outcome_becomes_uncertain_and_never_reruns() { + let mut h = H::journaled(enabled()); + h.register("a", 1, &[]); + h.register("b", 1, &["a"]); + h.register("c", 1, &["b"]); + h.publish("a", 1); + h.publish("b", 1); + h.finish("a"); + h.finish("b"); + let gen_c = h.generation("c"); + begin(&mut h, "b").unwrap(); + // Crash before the outcome. + h.restart(enabled()).unwrap(); + assert_eq!(h.sched.state("b"), Some(TaskState::CommitUncertain)); + assert_eq!(h.sched.state("c"), Some(TaskState::Blocked)); + assert_eq!(h.generation("c"), gen_c + 1); + let journal = std::fs::read_to_string(h.fx.journal()).unwrap(); + assert!(journal.contains(&format!("{RESERVED_ID_PREFIX}commit-uncertain-"))); + // Neither a new begin nor a late outcome is accepted. + assert!(begin(&mut h, "b").is_err()); + let r = h.send(EventKind::CommitOutcome { + task: "b".into(), + generation: h.generation("b"), + outcome: committed(), + }); + assert!(matches!(r, Err(SchedError::WrongState { .. })), "{r:?}"); + // A second restart settles nothing new. + let lines = std::fs::read_to_string(h.fx.journal()) + .unwrap() + .lines() + .count(); + h.restart(enabled()).unwrap(); + assert_eq!(h.sched.state("b"), Some(TaskState::CommitUncertain)); + assert_eq!( + std::fs::read_to_string(h.fx.journal()) + .unwrap() + .lines() + .count(), + lines + ); +} + +#[test] +fn replayed_commit_with_an_outcome_keeps_it() { + // Negative control: a recorded outcome survives the restart unchanged. + let mut h = H::journaled(enabled()); + h.register("a", 1, &[]); + h.publish("a", 1); + h.finish("a"); + begin(&mut h, "a").unwrap(); + outcome(&mut h, "a", committed()); + let snap = h.sched.snapshot(); + h.restart(enabled()).unwrap(); + assert_eq!(h.sched.state("a"), Some(TaskState::Committed)); + assert_eq!(h.sched.snapshot()["tasks"], snap["tasks"]); +} + +#[test] +fn audit_defers_a_revocation_that_would_reach_a_running_commit() { + let mut h = chain(); + begin(&mut h, "b").unwrap(); + remove_receipt(&h, &completion(&h, "a").receipt_id); + let revoked = h.sched.audit().unwrap(); + assert!(revoked.is_empty(), "{revoked:?}"); + assert_eq!(h.sched.state("a"), Some(TaskState::Committable)); + assert_eq!(h.sched.state("b"), Some(TaskState::Committing)); + // After the outcome the deferred revocation goes through and stops at + // the committed task. + outcome(&mut h, "b", committed()); + let revoked = h.sched.audit().unwrap(); + assert!(revoked.contains(&"a".to_string()), "{revoked:?}"); + assert_eq!(h.sched.state("b"), Some(TaskState::Committed)); +} + +#[test] +fn audit_without_a_commit_revokes_the_whole_chain() { + // Negative control for the deferral above. + let mut h = chain(); + remove_receipt(&h, &completion(&h, "a").receipt_id); + let revoked = h.sched.audit().unwrap(); + assert!(revoked.contains(&"a".to_string()), "{revoked:?}"); + assert_eq!(h.sched.state("b"), Some(TaskState::Blocked)); +} + +#[test] +fn begin_commit_redelivery_is_a_duplicate() { + let mut h = chain(); + h.advance(10); + let kind = begin_kind(&h, "b"); + let event = spark_harness::scheduler::Event { + id: "begin-b".into(), + kind, + }; + assert!(matches!( + h.sched.deliver(event.clone()), + Ok(Outcome::Applied(_)) + )); + let r = h.sched.deliver(event); + assert!(matches!(r, Ok(Outcome::Duplicate)), "{r:?}"); + assert_eq!(h.sched.state("b"), Some(TaskState::Committing)); +} + +// ---------- bound request keys ---------- + +fn bind(h: &mut H, key: &str, task: &str) -> Result<Outcome, SchedError> { + h.advance(1); + let generation = h.generation(task); + h.send(EventKind::BindApproval { + key: key.into(), + task: task.into(), + generation, + }) +} + +fn bound(h: &H, key: &str) -> Option<(String, u64)> { + h.sched + .approval(key) + .map(|b| (b.task.clone(), b.generation)) +} + +fn wrong_state(r: &Result<Outcome, SchedError>) -> bool { + matches!(r, Err(SchedError::WrongState { .. })) +} + +fn cancel(h: &mut H, task: &str) { + let generation = h.generation(task); + h.ok(EventKind::Cancel { + task: task.into(), + generation, + }); +} + +fn retry(h: &mut H, task: &str) { + let generation = h.generation(task); + h.ok(EventKind::Retry { + task: task.into(), + generation, + }); +} + +#[test] +fn bindings_survive_a_replay_and_are_dropped_when_the_task_commits() { + let mut h = H::journaled(enabled()); + h.register("a", 1, &[]); + h.register("b", 1, &["a"]); + let gen_b = h.generation("b"); + bind(&mut h, "approval:x", "b").unwrap(); + bind(&mut h, "proposal:y", "b").unwrap(); + h.restart(enabled()).unwrap(); + assert_eq!(bound(&h, "approval:x"), Some(("b".into(), gen_b))); + assert_eq!(bound(&h, "proposal:y"), Some(("b".into(), gen_b))); + h.publish("a", 1); + h.finish("a"); + h.finish("b"); + begin(&mut h, "b").unwrap(); + // Running: still bound. + assert_eq!(h.sched.approvals_len(), 2); + outcome(&mut h, "b", committed()); + assert_eq!(h.sched.approvals_len(), 0); + h.restart(enabled()).unwrap(); + assert_eq!(h.sched.approvals_len(), 0); +} + +#[test] +fn bindings_are_dropped_only_when_the_commit_ended() { + for (result, ended, kept) in [ + ( + CommitResult::Failed { + reason: "refused".into(), + }, + TaskState::Aborted, + true, + ), + ( + CommitResult::Uncertain { + reason: "transport".into(), + }, + TaskState::CommitUncertain, + false, + ), + (committed(), TaskState::Committed, false), + ] { + let mut h = chain(); + let gen_b = h.generation("b"); + bind(&mut h, "approval:x", "b").unwrap(); + // A consumer's binding is kept: the consumer is revoked to + // `Blocked`, which is not an end. + bind(&mut h, "approval:c", "c").unwrap(); + begin(&mut h, "b").unwrap(); + outcome(&mut h, "b", result.clone()); + assert_eq!(h.sched.state("b"), Some(ended), "{result:?}"); + let want = kept.then(|| ("b".to_string(), gen_b)); + assert_eq!(bound(&h, "approval:x"), want, "{result:?}"); + assert!(bound(&h, "approval:c").is_some(), "{result:?}"); + } +} + +#[test] +fn an_aborted_task_keeps_its_bindings_however_it_aborted() { + // Cancel, producer failure and lease expiry abort c (provisional); a + // failed commit aborts b. Each keeps the binding at the same + // generation, so the bound request stays fenced (`NotCommittable`). + type Abort = fn(&mut H); + let aborts: [(&str, &str, Abort); 4] = [ + ("cancel", "c", |h| cancel(h, "c")), + ("producer failed", "c", |h| { + let generation = h.generation("c"); + h.ok(EventKind::ProducerFailed { + task: "c".into(), + generation, + reason: "test".into(), + }); + }), + ("lease expired", "c", |h| { + h.advance(5_000); + h.ok(EventKind::Tick); + }), + ("commit failed", "b", |h| { + begin(h, "b").unwrap(); + outcome( + h, + "b", + CommitResult::Failed { + reason: "EFFECT_REFUSED".into(), + }, + ); + }), + ]; + for (how, task, abort) in aborts { + let mut h = chain(); + let generation = h.generation(task); + bind(&mut h, "approval:x", task).unwrap(); + abort(&mut h); + assert_eq!(h.sched.state(task), Some(TaskState::Aborted), "{how}"); + assert_eq!(h.generation(task), generation, "{how}"); + assert_eq!( + bound(&h, "approval:x"), + Some((task.to_string(), generation)), + "{how}" + ); + } +} + +#[test] +fn a_cancel_keeps_the_bindings_of_every_task_it_aborts() { + let mut h = H::journaled(enabled()); + h.register("a", 1, &[]); + h.register("b", 1, &["a"]); + bind(&mut h, "approval:a", "a").unwrap(); + bind(&mut h, "approval:b", "b").unwrap(); + cancel(&mut h, "a"); + assert_eq!(h.sched.state("b"), Some(TaskState::Aborted)); + assert_eq!(h.sched.approvals_len(), 2); + h.restart(enabled()).unwrap(); + assert_eq!(h.sched.approvals_len(), 2); + assert_eq!(bound(&h, "approval:b"), Some(("b".into(), 1))); +} + +#[test] +fn a_retry_keeps_the_old_binding_until_the_request_is_bound_again() { + let mut h = chain(); + let generation = h.generation("c"); + bind(&mut h, "approval:x", "c").unwrap(); + cancel(&mut h, "c"); + retry(&mut h, "c"); + assert_eq!(h.generation("c"), generation + 1); + // Still bound, at the superseded generation: the fence refuses it + // (`StaleGeneration`) instead of the request running unfenced. + assert_eq!(bound(&h, "approval:x"), Some(("c".into(), generation))); + bind(&mut h, "approval:x", "c").unwrap(); + assert_eq!(bound(&h, "approval:x"), Some(("c".into(), generation + 1))); + assert_eq!(h.sched.approvals_len(), 1); +} + +#[test] +fn bind_refuses_bad_keys_stale_generations_and_ended_commits() { + let mut h = chain(); + let gen_b = h.generation("b"); + for key in [String::new(), "k".repeat(MAX_APPROVAL_KEY_LEN + 1)] { + let r = bind(&mut h, &key, "b"); + assert!(matches!(r, Err(SchedError::InvalidEvent(_))), "{r:?}"); + } + assert!(bind(&mut h, &"k".repeat(MAX_APPROVAL_KEY_LEN), "b").is_ok()); + let r = h.send(EventKind::BindApproval { + key: "approval:old".into(), + task: "b".into(), + generation: gen_b + 1, + }); + assert!( + matches!(r, Err(SchedError::FutureGeneration { .. })), + "{r:?}" + ); + // Committing is not an end: a bind is accepted. + begin(&mut h, "b").unwrap(); + assert!(bind(&mut h, "approval:during", "b").is_ok()); + outcome(&mut h, "b", committed()); + assert!(wrong_state(&bind(&mut h, "approval:late", "b"))); + assert_eq!(bound(&h, "approval:late"), None); + + let mut h = chain(); + begin(&mut h, "b").unwrap(); + outcome( + &mut h, + "b", + CommitResult::Uncertain { + reason: "transport".into(), + }, + ); + assert!(wrong_state(&bind(&mut h, "approval:late", "b"))); + assert_eq!(h.sched.approvals_len(), 0); + // Aborted is not an end: a request may be bound to it (and is refused + // by the fence until a retry and a new bind). + cancel(&mut h, "c"); + assert!(bind(&mut h, "approval:aborted", "c").is_ok()); + assert_eq!(h.sched.approvals_len(), 1); +} + +#[test] +fn the_binding_table_is_bounded_per_task_and_fails_closed() { + let mut h = chain(); + for i in 0..MAX_APPROVAL_BINDINGS_PER_TASK { + bind(&mut h, &format!("approval:{i}"), "c").unwrap(); + } + assert_eq!(h.sched.approvals_len(), MAX_APPROVAL_BINDINGS_PER_TASK); + let r = bind(&mut h, "approval:one-more", "c"); + assert!( + matches!(r, Err(SchedError::BindingsFull { ref task, .. }) if task == "c"), + "{r:?}" + ); + assert_eq!(bound(&h, "approval:one-more"), None); + // Rebinding a key c holds replaces it. + assert!(bind(&mut h, "approval:0", "c").is_ok()); + assert_eq!(h.sched.approvals_len(), MAX_APPROVAL_BINDINGS_PER_TASK); +} + +#[test] +fn aborted_tasks_cannot_exhaust_the_table_for_other_tasks() { + let mut h = chain(); + h.register("x", 1, &[]); + for i in 0..MAX_APPROVAL_BINDINGS_PER_TASK { + bind(&mut h, &format!("approval:c-{i}"), "c").unwrap(); + } + cancel(&mut h, "c"); + // c keeps its full share while aborted and after a retry. + 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:?}"); + // Its own keys may be bound again at the new generation. + assert!(bind(&mut h, "approval:c-0", "c").is_ok()); + // 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(); + } + assert_eq!(h.sched.approvals_len(), 2 * MAX_APPROVAL_BINDINGS_PER_TASK); + let r = bind(&mut h, "approval:x-new", "x"); + assert!( + matches!(r, Err(SchedError::BindingsFull { ref task, .. }) if task == "x"), + "{r:?}" + ); +}