Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aien-sovereign-core-mv/patches/27d9f9ff92ee94bc # aien-sovereign-core-mv AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers ## GitHub aien-dev/aien-sovereign-core-mv#547 (code only) closed derived `27d9f9ff92ee94bc` #547 Imported from GitHub aien-dev/aien-sovereign-core-mv#547 (code only) GitHub's metadata for this pull request is unavailable: its state is DERIVED from the commits (merged: the head is reachable from this project's main; open: GitHub kept a merge ref; else closed). Base `f87b63bf26fdd66583a58b7b4d97cf701bace144` · Head `9e1c44637f498a0fb15c2a780c2c5c4b9889897d` ### Fetch it A git bundle of the pull request's head, 61168 bytes. ``` curl -fsSL https://interplane.io/drakestapleton/aien-sovereign-core-mv/patches/27d9f9ff92ee94bc.bundle -o 27d9f9ff92ee94bc.bundle git fetch 27d9f9ff92ee94bc.bundle refs/pull/547/head ``` Raw bundle · Diff ### Provenance This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record: ``` github-import 1 aien-dev/aien-sovereign-core-mv 547 9e1c44637f498a0fb15c2a780c2c5c4b9889897d ``` ``` {"kind":"github-import","owner":"aien-dev","repo":"aien-sovereign-core-mv","number":547,"url":"https://github.com/aien-dev/aien-sovereign-core-mv/pull/547","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:37:26Z","metadata":"unavailable","state_derived":true} ``` ### Changes ``` diff --git a/.crumb b/.crumb index a57b3184..407df7d0 100644 --- a/.crumb +++ b/.crumb @@ -119,14 +119,14 @@ } ], "children_root": "sha256:22ba08424be303f48fdc592bf8bb3ef42b8975b20f549de3f07f05158e97268e", - "compiled_at": "2026-10-15T20:20:30Z", + "compiled_at": "2026-10-15T20:42:09Z", "compiler": "crumb-compile/1", - "digest": "sha256:b9d35dcc2b0f7b4c24d3d896d81ab15b6a60deb5c873bcb7f9ec96c1bf6e2fec", + "digest": "sha256:5804af76e48ce4978179eeb36191fa0fc1efa1f9cfc67291a5b3ef8e73ff4ac9", "evidence_files": 1539, "evidence_root": "sha256:1ea69f2206ca8c2bc38782b87e820d32349fe45e89927ec2f17f2675c9b077e7", - "files": 5503, - "generated_at_commit": "5b421ae6edbe3f57439773b2f862303f0de672f1", - "source_tree": "sha256:de86a16710df53b4d14f50bffb1e3434439bbcc544bc2eeaa6149d58220e280d" + "files": 5519, + "generated_at_commit": "661f52e96ec36334aff04921831d795e14216ab3", + "source_tree": "sha256:25759151e4cabc9b434095609cd16a9ad4d1c2c85b5227c418be5e22eb674bdf" } }, "history": [], diff --git a/crates/spark-harness/src/completion.rs b/crates/spark-harness/src/completion.rs index e336b485..14b836b0 100644 --- a/crates/spark-harness/src/completion.rs +++ b/crates/spark-harness/src/completion.rs @@ -337,14 +337,14 @@ pub fn artifact_digest(artifact: &Value) -> String { } /// File name key for a task's consumed record (task IDs are free text). -fn task_key(task_id: &str) -> String { +pub(crate) fn task_key(task_id: &str) -> String { let mut h = blake3::Hasher::new(); h.update(b"spark-harness-task\0"); h.update(task_id.as_bytes()); h.finalize().to_hex().to_string() } -fn check_identifier(what: &str, value: &str) -> Result<(), CompletionError> { +pub(crate) fn check_identifier(what: &str, value: &str) -> Result<(), CompletionError> { if value.is_empty() || value.trim() != value { return Err(CompletionError::InvalidSubmission(format!( "{what} must be non-empty with no leading or trailing whitespace" @@ -375,7 +375,7 @@ fn collect_strings<'a>(v: &'a Value, path: String, out: &mut Vec<(String, &'a st } } -fn host_identity() -> String { +pub(crate) fn host_identity() -> String { let from_proc = fs::read_to_string("/proc/sys/kernel/hostname") .map(|s| s.trim().to_string()) .unwrap_or_default(); @@ -423,10 +423,22 @@ fn read_consumed(path: &Path, task_id: &str) -> Result, C /// still be lost on power failure). A resubmission of the same generation /// is then refused as a duplicate. fn write_consumed(path: &Path, rec: &ConsumedRecord) -> Result<(), CompletionError> { - let store_err = |e: String| CompletionError::Store(e); - let dir = path - .parent() - .ok_or_else(|| store_err("consumed record has no parent dir".to_string()))?; + let text = serde_json::to_vec_pretty(rec).map_err(|e| CompletionError::Store(e.to_string()))?; + write_atomic(path, &text).map_err(|e| { + CompletionError::Store(format!( + "cannot write consumed record {}: {e}", + path.display() + )) + }) +} + +/// Atomic replace used by the consumed and interface records: write a temp +/// file in the same directory, append a newline, fsync it, rename it over +/// `path`, fsync the directory. The temp file is removed on failure. +pub(crate) fn write_atomic(path: &Path, bytes: &[u8]) -> std::io::Result<()> { + let dir = path.parent().ok_or_else(|| { + std::io::Error::new(std::io::ErrorKind::InvalidInput, "record has no parent dir") + })?; let name = path .file_name() .map(|n| n.to_string_lossy().into_owned()) @@ -436,23 +448,18 @@ fn write_consumed(path: &Path, rec: &ConsumedRecord) -> Result<(), CompletionErr std::process::id(), uuid::Uuid::new_v4() )); - let text = serde_json::to_vec_pretty(rec).map_err(|e| store_err(e.to_string()))?; let result = (|| -> std::io::Result<()> { let mut f = fs::File::create(&tmp)?; - f.write_all(&text)?; + f.write_all(bytes)?; f.write_all(b"\n")?; f.sync_all()?; fs::rename(&tmp, path)?; fs::File::open(dir)?.sync_all() })(); - if let Err(e) = result { + if result.is_err() { let _ = fs::remove_file(&tmp); - return Err(store_err(format!( - "cannot write consumed record {}: {e}", - path.display() - ))); } - Ok(()) + result } fn failed_assertion(id: String, expected: &str, observed: String) -> Assertion { @@ -731,7 +738,7 @@ impl HarnessEngine { } } -fn single_ref<'a>(refs: &'a [String], prefix: &str) -> Result<&'a str, CompletionError> { +pub(crate) fn single_ref<'a>(refs: &'a [String], prefix: &str) -> Result<&'a str, CompletionError> { let found: Vec<&str> = refs.iter().filter_map(|r| r.strip_prefix(prefix)).collect(); match found.as_slice() { [one] => Ok(one), @@ -742,7 +749,11 @@ fn single_ref<'a>(refs: &'a [String], prefix: &str) -> Result<&'a str, Completio } } -fn require(field: &'static str, expected: &str, found: &str) -> Result<(), CompletionError> { +pub(crate) fn require( + field: &'static str, + expected: &str, + found: &str, +) -> Result<(), CompletionError> { if expected == found { Ok(()) } else { diff --git a/crates/spark-harness/src/dependency.rs b/crates/spark-harness/src/dependency.rs new file mode 100644 index 00000000..afc97b0d --- /dev/null +++ b/crates/spark-harness/src/dependency.rs @@ -0,0 +1,190 @@ +//! Producer/consumer dependency graph (Headstart M2, issue #535). +//! +//! Nodes are task ids. An edge `producer -> consumer` means the consumer +//! needs the producer's artifact. Every insert is checked: unknown nodes, +//! self edges, duplicate edges and edges that would close a cycle are +//! refused, so the graph is always a DAG. Iteration order is the byte order +//! of task ids (BTreeMap/BTreeSet), which keeps scheduling deterministic. + +use serde::Serialize; +use std::collections::{BTreeMap, BTreeSet, VecDeque}; +use std::fmt; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum GraphError { + DuplicateNode(String), + MissingNode(String), + SelfEdge(String), + DuplicateEdge { + producer: String, + consumer: String, + }, + /// Adding the edge would close this cycle (first and last node equal). + Cycle(Vec), +} + +impl fmt::Display for GraphError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + GraphError::DuplicateNode(n) => write!(f, "task '{n}' already exists"), + GraphError::MissingNode(n) => write!(f, "task '{n}' does not exist"), + GraphError::SelfEdge(n) => write!(f, "task '{n}' cannot depend on itself"), + GraphError::DuplicateEdge { producer, consumer } => { + write!(f, "edge {producer} -> {consumer} already exists") + } + GraphError::Cycle(path) => write!(f, "edge would close cycle {}", path.join(" -> ")), + } + } +} + +impl std::error::Error for GraphError {} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)] +pub struct DependencyGraph { + /// consumer -> producers + producers: BTreeMap>, + /// producer -> consumers + consumers: BTreeMap>, +} + +impl DependencyGraph { + pub fn contains(&self, id: &str) -> bool { + self.producers.contains_key(id) + } + + pub fn add_node(&mut self, id: &str) -> Result<(), GraphError> { + if self.contains(id) { + return Err(GraphError::DuplicateNode(id.to_string())); + } + self.producers.insert(id.to_string(), BTreeSet::new()); + self.consumers.insert(id.to_string(), BTreeSet::new()); + Ok(()) + } + + /// Check an edge without inserting it. + pub fn check_edge(&self, producer: &str, consumer: &str) -> Result<(), GraphError> { + for n in [producer, consumer] { + if !self.contains(n) { + return Err(GraphError::MissingNode(n.to_string())); + } + } + if producer == consumer { + return Err(GraphError::SelfEdge(producer.to_string())); + } + if self.consumers[producer].contains(consumer) { + return Err(GraphError::DuplicateEdge { + producer: producer.to_string(), + consumer: consumer.to_string(), + }); + } + // The new edge closes a cycle iff the producer is reachable from + // the consumer along existing edges. + if let Some(mut path) = self.path(consumer, producer) { + path.push(consumer.to_string()); + return Err(GraphError::Cycle(path)); + } + Ok(()) + } + + pub fn add_edge(&mut self, producer: &str, consumer: &str) -> Result<(), GraphError> { + self.check_edge(producer, consumer)?; + self.consumers + .get_mut(producer) + .map(|s| s.insert(consumer.to_string())); + self.producers + .get_mut(consumer) + .map(|s| s.insert(producer.to_string())); + Ok(()) + } + + pub fn producers_of(&self, id: &str) -> impl Iterator { + self.producers.get(id).into_iter().flatten() + } + + pub fn consumers_of(&self, id: &str) -> impl Iterator { + self.consumers.get(id).into_iter().flatten() + } + + /// Every task reachable from `id` along producer -> consumer edges, in + /// breadth-first order, excluding `id`. + pub fn descendants(&self, id: &str) -> Vec { + let mut seen = BTreeSet::new(); + let mut out = Vec::new(); + let mut q: VecDeque<&String> = self.consumers_of(id).collect(); + while let Some(n) = q.pop_front() { + if seen.insert(n.clone()) { + out.push(n.clone()); + q.extend(self.consumers_of(n)); + } + } + out + } + + /// A path `from -> ... -> to` along existing edges, if one exists. + fn path(&self, from: &str, to: &str) -> Option> { + let mut parent: BTreeMap<&str, &str> = BTreeMap::new(); + let mut q = VecDeque::from([from]); + let mut seen = BTreeSet::from([from]); + while let Some(n) = q.pop_front() { + if n == to { + let mut path = vec![to.to_string()]; + let mut cur = to; + while let Some(p) = parent.get(cur) { + path.push(p.to_string()); + cur = p; + } + path.reverse(); + return Some(path); + } + for c in self.consumers_of(n) { + if seen.insert(c.as_str()) { + parent.insert(c.as_str(), n); + q.push_back(c.as_str()); + } + } + } + None + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn graph(nodes: &[&str]) -> DependencyGraph { + let mut g = DependencyGraph::default(); + for n in nodes { + g.add_node(n).unwrap(); + } + g + } + + #[test] + fn refuses_cycles_missing_nodes_and_duplicates() { + let mut g = graph(&["a", "b", "c"]); + g.add_edge("a", "b").unwrap(); + g.add_edge("b", "c").unwrap(); + assert_eq!( + g.add_edge("c", "a"), + Err(GraphError::Cycle(vec![ + "a".into(), + "b".into(), + "c".into(), + "a".into() + ])) + ); + assert_eq!(g.add_edge("a", "a"), Err(GraphError::SelfEdge("a".into()))); + assert_eq!( + g.add_edge("a", "z"), + Err(GraphError::MissingNode("z".into())) + ); + assert!(matches!( + g.add_edge("a", "b"), + Err(GraphError::DuplicateEdge { .. }) + )); + assert_eq!(g.add_node("a"), Err(GraphError::DuplicateNode("a".into()))); + // A diamond is fine. + g.add_edge("a", "c").unwrap(); + assert_eq!(g.descendants("a"), vec!["b".to_string(), "c".to_string()]); + } +} diff --git a/crates/spark-harness/src/execution.rs b/crates/spark-harness/src/execution.rs new file mode 100644 index 00000000..2795af0b --- /dev/null +++ b/crates/spark-harness/src/execution.rs @@ -0,0 +1,134 @@ +//! Task execution states for the provisional scheduler (Headstart M2, +//! issue #535). +//! +//! ```text +//! Blocked --dispatch--> Provisional --work done--> AwaitingFinalProof --finalize--> Committable +//! ^ | | | +//! +------ revoke --------+---------------------------+-------------------------------+ +//! any non-Aborted --cancel / failure / lease expiry--> Aborted --retry--> Blocked +//! ``` +//! +//! 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. +//! +//! Revocation returns a task to `Blocked` rather than `Aborted`. The task did +//! nothing wrong: an upstream producer failed, changed its interface or +//! started a new generation. Its provisional result is discarded and it waits +//! to be dispatched again against the new upstream state, without a manual +//! retry. A task fails into `Aborted` only for its own reasons (its own +//! failure, cancellation, lost lease). +//! +//! Only `Provisional` holds resource permits. Leaving `Provisional` releases +//! them, so `Blocked`, `AwaitingFinalProof`, `Committable` and `Aborted` +//! tasks hold none. + +use serde::{Deserialize, Serialize}; +use std::fmt; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +pub enum TaskState { + Blocked, + Provisional, + AwaitingFinalProof, + Committable, + Aborted, +} + +impl TaskState { + pub fn as_str(self) -> &'static str { + match self { + TaskState::Blocked => "blocked", + TaskState::Provisional => "provisional", + TaskState::AwaitingFinalProof => "awaiting_final_proof", + TaskState::Committable => "committable", + TaskState::Aborted => "aborted", + } + } + + /// States whose work or proof is built on upstream artifacts and must be + /// revoked when upstream changes. + pub fn is_active(self) -> bool { + matches!( + self, + TaskState::Provisional | TaskState::AwaitingFinalProof | TaskState::Committable + ) + } + + /// Only a running task holds resource permits. + pub fn holds_permits(self) -> bool { + self == TaskState::Provisional + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct IllegalTransition { + pub from: TaskState, + pub to: TaskState, +} + +impl fmt::Display for IllegalTransition { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + f, + "illegal task transition {} -> {}", + self.from.as_str(), + self.to.as_str() + ) + } +} + +impl std::error::Error for IllegalTransition {} + +/// The complete transition table. Anything not listed is refused. +pub fn check_transition(from: TaskState, to: TaskState) -> Result<(), IllegalTransition> { + use TaskState::*; + let ok = matches!( + (from, to), + (Blocked, Provisional) + | (Provisional, AwaitingFinalProof) + | (AwaitingFinalProof, Committable) + | (Provisional | AwaitingFinalProof | Committable, Blocked) + | ( + Blocked | Provisional | AwaitingFinalProof | Committable, + Aborted + ) + | (Aborted, Blocked) + ); + if ok { + Ok(()) + } else { + Err(IllegalTransition { from, to }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use TaskState::*; + + #[test] + fn table_refuses_shortcuts() { + for (from, to) in [ + (Blocked, AwaitingFinalProof), + (Blocked, Committable), + (Provisional, Committable), + (Aborted, Provisional), + (Aborted, Committable), + (Committable, Provisional), + (Blocked, Blocked), + ] { + assert!(check_transition(from, to).is_err(), "{from:?} -> {to:?}"); + } + for (from, to) in [ + (Blocked, Provisional), + (Provisional, AwaitingFinalProof), + (AwaitingFinalProof, Committable), + (Committable, Blocked), + (Aborted, Blocked), + ] { + assert!(check_transition(from, to).is_ok(), "{from:?} -> {to:?}"); + } + } +} diff --git a/crates/spark-harness/src/journal.rs b/crates/spark-harness/src/journal.rs new file mode 100644 index 00000000..e0ac8385 --- /dev/null +++ b/crates/spark-harness/src/journal.rs @@ -0,0 +1,160 @@ +//! Append-only JSON-lines journal (Headstart M2, issue #535). +//! +//! Why this and not an existing store: the repo's durable stores are the +//! aien-proof receipt store (immutable receipts, content addressed) and the +//! M1 consumed records (one atomically replaced file per task). Neither fits +//! an ordered event history, so the scheduler keeps its own journal. It +//! persists only scheduler events; proofs stay in the harness store and are +//! re-verified, never copied into the journal as authority. +//! +//! Format: line 1 is a header (format name, version, scheduler config); every +//! further line is one JSON event. Each append is a single `write_all` of +//! `json + "\n"` on an `O_APPEND` file followed by `sync_all`. +//! +//! Crash handling: +//! - A final segment with no trailing newline is a torn write. It is ignored +//! and truncated away on open (then fsynced), so the next append starts on +//! a clean line. Truncation happens only after the header and every +//! complete line validated; a refused journal is not modified. +//! - A newline-terminated line that does not parse is corruption, not a torn +//! write (a torn write is always a prefix of one line), and open fails +//! closed. +//! - If an append fails, the file is truncated back to its previous length. +//! If that also fails the journal refuses every further append. +//! - One process at a time: the journal holds an exclusive `flock` on +//! `.lock` for its lifetime. + +use aien_proof::lock::FileLock; +use serde::de::DeserializeOwned; +use serde::Serialize; +use serde_json::Value; +use std::fs::{self, File, OpenOptions}; +use std::io::Write; +use std::path::{Path, PathBuf}; + +pub struct Journal { + file: File, + path: PathBuf, + len: u64, + poisoned: bool, + _lock: FileLock, +} + +/// Result of opening a journal. +pub struct Opened { + pub journal: Journal, + pub entries: Vec, + /// Bytes of a torn final line that were dropped (0 if none). + pub torn_bytes: usize, +} + +fn sync_dir(path: &Path) -> std::io::Result<()> { + match path.parent() { + Some(dir) if !dir.as_os_str().is_empty() => File::open(dir)?.sync_all(), + _ => Ok(()), + } +} + +impl Journal { + /// Open `path`, creating it with `header` when missing, and replay its + /// entries. An existing journal must carry exactly `header`. + pub fn open(path: &Path, header: &Value) -> Result, String> { + let lock_path = PathBuf::from(format!("{}.lock", path.display())); + if let Some(dir) = path.parent().filter(|d| !d.as_os_str().is_empty()) { + fs::create_dir_all(dir).map_err(|e| format!("cannot create {}: {e}", dir.display()))?; + } + let lock = FileLock::try_acquire(&lock_path) + .map_err(|e| format!("cannot lock journal: {e}"))? + .ok_or_else(|| format!("journal {} is held by another process", path.display()))?; + let bytes = match fs::read(path) { + Ok(b) => b, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Vec::new(), + Err(e) => return Err(format!("cannot read journal {}: {e}", path.display())), + }; + let complete = bytes.iter().rposition(|b| *b == b'\n').map_or(0, |i| i + 1); + let torn_bytes = bytes.len() - complete; + // Validate everything before touching the file: a journal that is + // refused (wrong header, corrupt line) is left exactly as found. + let text = std::str::from_utf8(&bytes[..complete]) + .map_err(|e| format!("journal {} is not UTF-8: {e}", path.display()))?; + let mut lines = text.lines(); + let fresh = match lines.next() { + None => true, + Some(first) => { + let found: Value = serde_json::from_str(first) + .map_err(|e| format!("journal header unreadable: {e}"))?; + if &found != header { + return Err(format!( + "journal header mismatch: journal has {found}, expected {header}" + )); + } + false + } + }; + let mut entries = Vec::new(); + for (i, line) in lines.enumerate() { + let entry = serde_json::from_str(line) + .map_err(|e| format!("journal line {} is corrupt, refusing: {e}", i + 2))?; + entries.push(entry); + } + let file = OpenOptions::new() + .create(true) + .append(true) + .open(path) + .map_err(|e| format!("cannot open journal {}: {e}", path.display()))?; + if torn_bytes > 0 { + file.set_len(complete as u64) + .and_then(|_| file.sync_all()) + .map_err(|e| format!("cannot truncate torn journal tail: {e}"))?; + } + let mut journal = Journal { + file, + path: path.to_path_buf(), + len: complete as u64, + poisoned: false, + _lock: lock, + }; + if fresh { + journal.append(header)?; + sync_dir(path).map_err(|e| format!("cannot fsync journal dir: {e}"))?; + } + Ok(Opened { + journal, + entries, + torn_bytes, + }) + } + + /// Append one entry as a single line and fsync it. + pub fn append(&mut self, entry: &T) -> Result<(), String> { + if self.poisoned { + return Err("journal is poisoned after a failed rollback".to_string()); + } + let mut line = serde_json::to_vec(entry).map_err(|e| e.to_string())?; + line.push(b'\n'); + let written = self + .file + .write_all(&line) + .and_then(|_| self.file.sync_all()); + match written { + Ok(()) => { + self.len += line.len() as u64; + Ok(()) + } + Err(e) => { + if self + .file + .set_len(self.len) + .and_then(|_| self.file.sync_all()) + .is_err() + { + self.poisoned = true; + } + Err(format!( + "journal append to {} failed: {e}", + self.path.display() + )) + } + } + } +} diff --git a/crates/spark-harness/src/lib.rs b/crates/spark-harness/src/lib.rs index d187562d..abf0ad00 100644 --- a/crates/spark-harness/src/lib.rs +++ b/crates/spark-harness/src/lib.rs @@ -5,6 +5,11 @@ use std::collections::HashMap; use std::path::{Path, PathBuf}; pub mod completion; +pub mod dependency; +pub mod execution; +pub mod journal; +pub mod readiness; +pub mod scheduler; /// The terminal workflow state. Since Headstart M1 (#533) it is reachable /// only through [`HarnessEngine::complete_verified_workflow`], never through diff --git a/crates/spark-harness/src/readiness.rs b/crates/spark-harness/src/readiness.rs new file mode 100644 index 00000000..575c7a6c --- /dev/null +++ b/crates/spark-harness/src/readiness.rs @@ -0,0 +1,566 @@ +//! Artifact readiness and operation classes (Headstart M2, issue #535). +//! +//! A producer task can make its output ready for consumers at two levels: +//! +//! - [`ReadinessLevel::InterfaceVerified`]: the producer published an +//! immutable interface artifact through [`HarnessEngine::publish_interface`]. +//! The harness recomputes the digest itself, mints an aien-proof receipt of +//! kind [`INTERFACE_KIND`] (distinct from the M1 completion kind) and records +//! it as the task's current interface. Consumers may only run the reversible, +//! sandboxed [`OperationClass`] entries against it. +//! - [`ReadinessLevel::FinalVerified`]: M1 [`verify_completion`] passes for the +//! producer's current generation. +//! +//! [`ReadinessLevel::Revoked`] permits nothing. +//! +//! An [`ArtifactReadiness`] can only be built by [`verify_interface`] or +//! [`verify_final`], which re-read the receipt from the harness store. It has +//! no public constructor and no `Deserialize`, so a caller cannot hand the +//! scheduler a readiness value, a receipt or a pass flag. +//! +//! The same trust limits as M1 apply (see `completion.rs` module docs): +//! receipts are unsigned, so authenticity rests on ownership of the store +//! plus recomputation of the receipt identity and every binding. + +use crate::completion::{ + artifact_digest, check_identifier, host_identity, require, single_ref, task_key, + verify_completion, write_atomic, CompletionError, +}; +use crate::HarnessEngine; +use aien_proof::evidence::{self, Assertion, Mutation, Receipt, Tier, Verdict}; +use aien_proof::lock::FileLock; +use serde::{Deserialize, Deserializer, Serialize, Serializer}; +use serde_json::Value; +use std::fmt; +use std::fs; +use std::path::Path; + +/// Receipt `kind` for published interface artifacts. +pub const INTERFACE_KIND: &str = "spark-harness-interface"; +/// Honest tier: host-executed deterministic checks. +pub const INTERFACE_TIER: Tier = Tier::HostTest; +/// Subdirectory of the harness store holding current interface records. +pub const INTERFACE_DIR: &str = "interfaces"; +const ASSERTION_SOURCE: &str = "spark-harness"; + +/// Closed set of operation classes a scheduled task may ask to run. +/// +/// Only [`OperationClass::is_reversible_preparation`] classes may run while a +/// dependency is merely interface-verified. Every match on this enum is +/// exhaustive on purpose: a new class must be classified explicitly. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum OperationClass { + /// Reading sources and artifacts, no writes outside scratch space. + ReadOnlyAnalysis, + /// Builds or tests in a throwaway sandbox whose output is discarded on + /// revocation. + SandboxedCheck, + /// Committing work (World commit). Irreversible. + Commit, + /// Publishing an artifact others may consume. Irreversible. + Publish, + /// Mutating persistent state. Irreversible. + PersistentMutation, + /// Any effect outside the host (network, devices, people). Irreversible. + ExternalEffect, +} + +impl OperationClass { + pub const ALL: [OperationClass; 6] = [ + OperationClass::ReadOnlyAnalysis, + OperationClass::SandboxedCheck, + OperationClass::Commit, + OperationClass::Publish, + OperationClass::PersistentMutation, + OperationClass::ExternalEffect, + ]; + + pub fn as_str(self) -> &'static str { + match self { + OperationClass::ReadOnlyAnalysis => "read_only_analysis", + OperationClass::SandboxedCheck => "sandboxed_check", + OperationClass::Commit => "commit", + OperationClass::Publish => "publish", + OperationClass::PersistentMutation => "persistent_mutation", + OperationClass::ExternalEffect => "external_effect", + } + } + + /// Exact, case-sensitive match. Anything else is unknown and refused. + pub fn parse(s: &str) -> Result { + OperationClass::ALL + .into_iter() + .find(|op| op.as_str() == s) + .ok_or_else(|| UnknownOperation(s.to_string())) + } + + /// True only for classes whose effects stay inside a sandbox and can be + /// thrown away when the interface they used is revoked. + pub fn is_reversible_preparation(self) -> bool { + match self { + OperationClass::ReadOnlyAnalysis | OperationClass::SandboxedCheck => true, + OperationClass::Commit + | OperationClass::Publish + | OperationClass::PersistentMutation + | OperationClass::ExternalEffect => false, + } + } +} + +/// An operation name that is not in [`OperationClass`]. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct UnknownOperation(pub String); + +impl fmt::Display for UnknownOperation { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "unknown operation class {:?}, refused", self.0) + } +} + +impl std::error::Error for UnknownOperation {} + +impl Serialize for OperationClass { + fn serialize(&self, s: S) -> Result { + s.serialize_str(self.as_str()) + } +} + +impl<'de> Deserialize<'de> for OperationClass { + fn deserialize>(d: D) -> Result { + let s = String::deserialize(d)?; + OperationClass::parse(&s).map_err(serde::de::Error::custom) + } +} + +/// How far a producer's output may be trusted by its consumers. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +pub enum ReadinessLevel { + InterfaceVerified, + FinalVerified, + Revoked, +} + +impl ReadinessLevel { + /// The single place that decides which operations a level allows. + pub fn permits(self, op: OperationClass) -> bool { + match self { + ReadinessLevel::FinalVerified => true, + ReadinessLevel::InterfaceVerified => op.is_reversible_preparation(), + ReadinessLevel::Revoked => false, + } + } +} + +/// Proof pointer carried by scheduler events: which harness receipt, for +/// which source commit and artifact digest. It is only a claim; the store is +/// re-read and every field re-checked before it is believed. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ProofClaim { + pub receipt_id: String, + pub commit: String, + pub digest: String, +} + +/// Verified readiness of one producer artifact. Built only by +/// [`verify_interface`] and [`verify_final`]. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct ArtifactReadiness { + producer_task: String, + source_commit: String, + producer_generation: u64, + artifact_digest: String, + receipt_id: String, + level: ReadinessLevel, +} + +impl ArtifactReadiness { + pub fn producer_task(&self) -> &str { + &self.producer_task + } + pub fn source_commit(&self) -> &str { + &self.source_commit + } + pub fn producer_generation(&self) -> u64 { + self.producer_generation + } + pub fn artifact_digest(&self) -> &str { + &self.artifact_digest + } + pub fn receipt_id(&self) -> &str { + &self.receipt_id + } + pub fn level(&self) -> ReadinessLevel { + self.level + } + pub fn permits(&self, op: OperationClass) -> bool { + self.level.permits(op) + } + /// The same bindings, downgraded to [`ReadinessLevel::Revoked`]. + pub fn revoked(mut self) -> Self { + self.level = ReadinessLevel::Revoked; + self + } +} + +/// What a producer submits to publish an interface. No receipt, digest or +/// flag field exists; unknown fields are rejected. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct InterfaceSubmission { + pub task_id: String, + pub generation: u64, + /// 40 or 64 lowercase hex, checked by aien-proof `check_commit`. + pub source_commit: String, + /// The interface artifact. Must be a non-empty JSON object. + pub interface: Value, +} + +/// Durable record naming the task's current interface receipt. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct InterfaceRecord { + pub task_id: String, + pub generation: u64, + pub receipt_id: String, + pub source_commit: String, + pub artifact_digest: String, +} + +impl InterfaceRecord { + pub fn claim(&self) -> ProofClaim { + ProofClaim { + receipt_id: self.receipt_id.clone(), + commit: self.source_commit.clone(), + digest: self.artifact_digest.clone(), + } + } +} + +fn record_path(store: &Path, task_id: &str) -> std::path::PathBuf { + store + .join(INTERFACE_DIR) + .join(format!("{}.json", task_key(task_id))) +} + +fn read_record(path: &Path, task_id: &str) -> Result, CompletionError> { + let bytes = match fs::read(path) { + Ok(b) => b, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(e) => { + return Err(CompletionError::Store(format!( + "cannot read interface record {}: {e}", + path.display() + ))) + } + }; + let rec: InterfaceRecord = serde_json::from_slice(&bytes).map_err(|e| { + CompletionError::Store(format!( + "interface record {} is malformed, refusing: {e}", + path.display() + )) + })?; + if rec.task_id != task_id { + return Err(CompletionError::Store(format!( + "interface record {} belongs to task '{}', not '{task_id}'", + path.display(), + rec.task_id + ))); + } + Ok(Some(rec)) +} + +fn pass(id: &str, expected: &str, observed: String) -> Assertion { + Assertion { + id: id.to_string(), + expected: expected.to_string(), + observed, + pass: true, + source: ASSERTION_SOURCE.to_string(), + note: String::new(), + } +} + +impl HarnessEngine { + fn mint_interface_receipt( + &self, + sub: &InterfaceSubmission, + digest: &str, + keys: usize, + ) -> Result { + let assertions = vec![ + pass( + "interface:shape", + "interface is a non-empty JSON object", + format!("object with {keys} key(s)"), + ), + pass( + "interface:digest", + "digest recomputed by the harness", + format!("blake3:{digest}"), + ), + ]; + let assertion_bytes = + serde_json::to_vec(&assertions).map_err(|e| CompletionError::Store(e.to_string()))?; + let repo = if self.completion_repo.trim().is_empty() { + crate::UNSPECIFIED_REPO.to_string() + } else { + self.completion_repo.clone() + }; + let mut r = Receipt { + schema: evidence::SCHEMA.to_string(), + version: evidence::SCHEMA_VERSION, + id: String::new(), + kind: INTERFACE_KIND.to_string(), + tier: INTERFACE_TIER, + result: Verdict::Pass, + timestamp: (self.completion_clock)(), + repo, + commit: sub.source_commit.clone(), + dirty: false, + toolchain: format!("spark-harness {}", env!("CARGO_PKG_VERSION")), + procedure: "spark-harness publish_interface".to_string(), + machine: host_identity(), + env_class: INTERFACE_TIER.as_str().to_string(), + input_artifacts: Vec::new(), + output_artifacts: vec![format!("blake3:{digest}")], + assertions, + dependencies: Vec::new(), + declared_mutation: Mutation::None, + observed_mutation: Mutation::None, + authority: String::new(), + output_digest: blake3::hash(&assertion_bytes).to_hex().to_string(), + external_refs: vec![ + format!("task:{}", sub.task_id), + format!("generation:{}", sub.generation), + ], + ledger: None, + lease: None, + required_features: Vec::new(), + reserved: String::new(), + }; + r.id = evidence::receipt_id(&r).map_err(CompletionError::Store)?; + Ok(r) + } + + /// Publish an immutable interface artifact for `sub.task_id` at + /// `sub.generation`. The harness computes the digest, mints and stores a + /// receipt of kind [`INTERFACE_KIND`], and records it as the task's + /// current interface. + /// + /// - A lower generation than the recorded one is refused as stale. + /// - The same generation and digest returns the existing record and + /// mints nothing (idempotent). + /// - The same generation with a different digest is an interface change: + /// a new receipt replaces the record, and the old receipt stops + /// verifying. The scheduler revokes consumers bound to the old one. + pub fn publish_interface( + &self, + sub: &InterfaceSubmission, + ) -> Result { + check_identifier("task_id", &sub.task_id)?; + evidence::check_commit(&sub.source_commit).map_err(CompletionError::InvalidSubmission)?; + let keys = match &sub.interface { + Value::Object(m) if !m.is_empty() => m.len(), + _ => { + return Err(CompletionError::InvalidSubmission( + "interface must be a non-empty JSON object".to_string(), + )) + } + }; + let digest = artifact_digest(&sub.interface); + let dir = self.completion_store.join(INTERFACE_DIR); + fs::create_dir_all(&dir) + .map_err(|e| CompletionError::Store(format!("cannot create {}: {e}", dir.display())))?; + let _lock = FileLock::acquire(&dir.join(".lock")) + .map_err(|e| CompletionError::Store(format!("cannot lock interface store: {e}")))?; + let path = record_path(&self.completion_store, &sub.task_id); + if let Some(prev) = read_record(&path, &sub.task_id)? { + if sub.generation < prev.generation { + return Err(CompletionError::StaleGeneration { + task_id: sub.task_id.clone(), + submitted: sub.generation, + recorded: prev.generation, + }); + } + if sub.generation == prev.generation + && prev.artifact_digest == digest + && prev.source_commit == sub.source_commit + { + return Ok(prev); + } + } + let receipt = self.mint_interface_receipt(sub, &digest, keys)?; + let receipt_id = evidence::store_receipt(&self.completion_store, &receipt) + .map_err(CompletionError::Store)?; + let rec = InterfaceRecord { + task_id: sub.task_id.clone(), + generation: sub.generation, + receipt_id, + source_commit: sub.source_commit.clone(), + artifact_digest: digest, + }; + let text = + serde_json::to_vec_pretty(&rec).map_err(|e| CompletionError::Store(e.to_string()))?; + write_atomic(&path, &text).map_err(|e| { + CompletionError::Store(format!( + "cannot write interface record {}: {e}", + path.display() + )) + })?; + Ok(rec) + } +} + +/// Read the task's current interface record from the store, if any. +pub fn current_interface( + store: &Path, + task_id: &str, +) -> Result, CompletionError> { + read_record(&record_path(store, task_id), task_id) +} + +/// Re-read and check an interface receipt: identity recomputes, PASS, +/// kind [`INTERFACE_KIND`], tier, commit, digest, task and generation all +/// match, and the task's interface record names exactly this receipt. +pub fn verify_interface( + store: &Path, + task_id: &str, + generation: u64, + claim: &ProofClaim, +) -> Result { + let receipt = evidence::load_receipt(store, &claim.receipt_id) + .map_err(CompletionError::ReceiptInvalid)?; + let path = store + .join(evidence::RECEIPT_DIR) + .join(format!("{}.json", receipt.id)); + let bytes = fs::read(&path) + .map_err(|e| CompletionError::ReceiptInvalid(format!("{}: {e}", path.display())))?; + let (again, report) = + evidence::verify_bytes(&bytes).map_err(CompletionError::ReceiptInvalid)?; + if again != receipt { + return Err(CompletionError::ReceiptInvalid( + "receipt file changed while being verified".to_string(), + )); + } + if receipt.result != Verdict::Pass || !report.ok() { + return Err(CompletionError::NotPass(format!( + "{} ({})", + receipt.result.as_str(), + report.reasons.join("; ") + ))); + } + require("kind", INTERFACE_KIND, &receipt.kind)?; + require("tier", INTERFACE_TIER.as_str(), receipt.tier.as_str())?; + require("commit", &claim.commit, &receipt.commit)?; + let digest_hex = claim + .digest + .strip_prefix("blake3:") + .unwrap_or(&claim.digest) + .to_ascii_lowercase(); + require( + "artifact_digest", + &format!("blake3:{digest_hex}"), + &receipt.output_artifacts.join(","), + )?; + require( + "task", + task_id, + single_ref(&receipt.external_refs, "task:")?, + )?; + require( + "generation", + &generation.to_string(), + single_ref(&receipt.external_refs, "generation:")?, + )?; + let current = current_interface(store, task_id)?.ok_or_else(|| { + CompletionError::NotCurrentCompletion(format!( + "no interface record for task '{task_id}'; receipt {} is an orphan", + receipt.id + )) + })?; + if current.receipt_id != receipt.id + || current.generation != generation + || current.artifact_digest != digest_hex + { + return Err(CompletionError::NotCurrentCompletion(format!( + "task '{task_id}' current interface is generation {} receipt {}; receipt {} is not it", + current.generation, current.receipt_id, receipt.id + ))); + } + Ok(ArtifactReadiness { + producer_task: task_id.to_string(), + source_commit: receipt.commit, + producer_generation: generation, + artifact_digest: digest_hex, + receipt_id: receipt.id, + level: ReadinessLevel::InterfaceVerified, + }) +} + +/// M1 [`verify_completion`] for the producer's generation, as readiness. +pub fn verify_final( + store: &Path, + task_id: &str, + generation: u64, + claim: &ProofClaim, +) -> Result { + let v = verify_completion( + store, + &claim.receipt_id, + task_id, + generation, + &claim.commit, + &claim.digest, + )?; + Ok(ArtifactReadiness { + producer_task: v.task_id, + source_commit: v.source_commit, + producer_generation: v.generation, + artifact_digest: v.artifact_digest, + receipt_id: v.receipt_id, + level: ReadinessLevel::FinalVerified, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parse_is_exact_and_closed() { + for op in OperationClass::ALL { + assert_eq!(OperationClass::parse(op.as_str()), Ok(op)); + } + for bad in [ + "", + "Commit", + "read-only-analysis", + " commit", + "sandboxed_check ", + "rm", + ] { + assert!( + OperationClass::parse(bad).is_err(), + "{bad:?} must be unknown" + ); + } + let err = serde_json::from_str::("\"deploy\""); + assert!(err.is_err()); + } + + #[test] + fn levels_permit_only_what_they_should() { + for op in OperationClass::ALL { + assert!(ReadinessLevel::FinalVerified.permits(op)); + assert!(!ReadinessLevel::Revoked.permits(op)); + assert_eq!( + ReadinessLevel::InterfaceVerified.permits(op), + matches!( + op, + OperationClass::ReadOnlyAnalysis | OperationClass::SandboxedCheck + ) + ); + } + } +} diff --git a/crates/spark-harness/src/scheduler/core.rs b/crates/spark-harness/src/scheduler/core.rs new file mode 100644 index 00000000..0e3cbae8 --- /dev/null +++ b/crates/spark-harness/src/scheduler/core.rs @@ -0,0 +1,677 @@ +//! Pure scheduler state and event application. +//! +//! [`Core::apply`] is deterministic: it reads only the current state, the +//! config and the journal entry (including the entry's recorded time). It +//! never touches the harness store or the clock. That is what lets a journal +//! replay rebuild the exact same state. Store checks happen before an event +//! is journaled (`gates.rs`) and again at every `may_start` / `may_finalize`. + +use super::dedup::Seen; +use super::error::SchedError; +use super::permits::{PermitPool, ResourceRequest}; +use super::timing::TaskTiming; +use super::ProvisionalConfig; +use crate::completion::{artifact_digest, check_identifier}; +use crate::dependency::DependencyGraph; +use crate::execution::{check_transition, TaskState}; +use crate::readiness::ProofClaim; +use serde::{Deserialize, Serialize}; +use std::collections::{BTreeMap, VecDeque}; + +/// Everything the scheduler can be told. Producer proof events carry only a +/// [`ProofClaim`] pointer; the receipt itself is re-read from the store. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)] +pub enum EventKind { + /// Register a task with its producers. A task with no producers is + /// eligible at once, so dependencies are declared here, atomically. + RegisterTask { + task: String, + resources: ResourceRequest, + producers: Vec, + }, + /// Add a producer to a task that is still `Blocked`. + AddDependency { + producer: String, + consumer: String, + }, + InterfacePublished { + task: String, + generation: u64, + claim: ProofClaim, + }, + CompletionVerified { + task: String, + generation: u64, + claim: ProofClaim, + }, + /// The producer's body or interface changed and work restarts at a new, + /// higher generation. + NewGeneration { + task: String, + generation: u64, + }, + ProducerFailed { + task: String, + generation: u64, + reason: String, + }, + /// The task's provisional work finished. `result_digest` names the + /// provisional result, which is discarded on revocation. + WorkDone { + task: String, + generation: u64, + result_digest: String, + }, + // The task-directed events below carry the task's current generation, + // like the proof events above: a redelivery after the task moved on is + // refused as stale, so duplicate detection never depends on a window. + Finalize { + task: String, + generation: u64, + }, + /// `beat` must rise with every heartbeat of one lease (start at 1), so + /// a redelivered heartbeat is refused without remembering its id. + Heartbeat { + task: String, + generation: u64, + beat: u64, + }, + Cancel { + task: String, + generation: u64, + }, + /// `generation` is the aborted generation; the retry runs at the next. + Retry { + task: String, + generation: u64, + }, + Revoke { + task: String, + generation: u64, + reason: String, + }, + /// Emitted only by `Scheduler::audit` (callers cannot deliver it): + /// revoke every listed task that is still active, then dispatch once, + /// so no consumer is dispatched between two audit revocations. + AuditRevoke { + revocations: Vec, + }, + /// Lets time pass: expires leases. + Tick, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Revocation { + pub task: String, + pub reason: String, +} + +/// One delivered event. Duplicate delivery is detected by `id`. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Event { + pub id: String, + pub kind: EventKind, +} + +/// One journal line: the accepted event plus its sequence number and the +/// monotonic time it was applied at. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct JournalEntry { + pub seq: u64, + pub id: String, + pub at: u64, + pub kind: EventKind, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +pub enum BindingLevel { + Interface, + Final, +} + +/// Which producer artifact a consumer was dispatched against. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct Binding { + pub generation: u64, + pub level: BindingLevel, + pub claim: ProofClaim, +} + +/// Scheduler view of one task. Returned by shared reference only. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct TaskEntry { + pub state: TaskState, + /// This task's own producer generation. Starts at 1, only increases. + pub generation: u64, + pub resources: ResourceRequest, + /// Accepted interface claim for the current generation. + pub interface: Option, + /// Accepted M1 completion claim for the current generation. + pub completion: Option, + pub bindings: BTreeMap, + pub lease_expires_at: Option, + /// Highest heartbeat beat accepted for the current lease. + pub last_beat: u64, + pub provisional_result: Option, + pub queued: bool, + pub last_reason: Option, + pub timing: TaskTiming, +} + +impl TaskEntry { + pub(crate) fn new(resources: ResourceRequest, at: u64) -> Self { + TaskEntry { + state: TaskState::Blocked, + generation: 1, + resources, + interface: None, + completion: None, + bindings: BTreeMap::new(), + lease_expires_at: None, + last_beat: 0, + provisional_result: None, + queued: false, + last_reason: None, + timing: TaskTiming::new(at), + } + } + + pub(crate) fn final_ready(&self) -> bool { + self.state == TaskState::Committable && self.completion.is_some() + } + + pub(crate) fn interface_ready(&self) -> bool { + self.state.is_active() && self.interface.is_some() + } + + fn lease_valid(&self, at: u64) -> bool { + self.lease_expires_at.is_some_and(|exp| at < exp) + } +} + +/// What applying an event did. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)] +pub struct Effects { + pub dispatched: Vec, + pub revoked: Vec, + pub aborted: Vec, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)] +pub struct Core { + pub(crate) graph: DependencyGraph, + pub(crate) tasks: BTreeMap, + pub(crate) queue: VecDeque, + pub(crate) pool: PermitPool, + /// Bounded memory of applied event ids (`dedup.rs`). + pub(crate) seen: Seen, + pub(crate) seq: u64, + pub(crate) last_at: u64, +} + +pub(crate) fn payload_digest(kind: &EventKind) -> String { + artifact_digest(&serde_json::to_value(kind).unwrap_or_default()) +} + +fn bad(m: impl Into) -> SchedError { + SchedError::InvalidEvent(m.into()) +} + +impl Core { + pub(crate) fn task(&self, id: &str) -> Result<&TaskEntry, SchedError> { + self.tasks + .get(id) + .ok_or_else(|| SchedError::UnknownTask(id.to_string())) + } + + fn task_mut(&mut self, id: &str) -> Result<&mut TaskEntry, SchedError> { + self.tasks + .get_mut(id) + .ok_or_else(|| SchedError::UnknownTask(id.to_string())) + } + + pub(crate) fn require_generation(&self, id: &str, generation: u64) -> Result<(), SchedError> { + let current = self.task(id)?.generation; + let (task, submitted) = (id.to_string(), generation); + match generation.cmp(¤t) { + std::cmp::Ordering::Less => Err(SchedError::StaleGeneration { + task, + submitted, + current, + }), + std::cmp::Ordering::Greater => Err(SchedError::FutureGeneration { + task, + submitted, + current, + }), + std::cmp::Ordering::Equal => Ok(()), + } + } + + fn require_state( + &self, + id: &str, + ok: impl Fn(TaskState) -> bool, + action: &'static str, + ) -> Result<(), SchedError> { + let state = self.task(id)?.state; + if ok(state) { + Ok(()) + } else { + Err(SchedError::WrongState { + task: id.to_string(), + state, + action, + }) + } + } + + /// The only place a task changes state. Leaving `Provisional` releases + /// the task's permits and lease. + fn set_state(&mut self, id: &str, to: TaskState, at: u64) -> Result<(), SchedError> { + let Core { tasks, pool, .. } = self; + let t = tasks + .get_mut(id) + .ok_or_else(|| SchedError::UnknownTask(id.to_string()))?; + check_transition(t.state, to)?; + t.timing.close(t.state, at); + if t.state.holds_permits() && !to.holds_permits() { + pool.release(t.resources); + t.lease_expires_at = None; + } + t.state = to; + Ok(()) + } + + fn dequeue(&mut self, id: &str) { + if let Some(t) = self.tasks.get_mut(id) { + if t.queued { + t.queued = false; + self.queue.retain(|q| q != id); + } + } + } + + fn clear_work(t: &mut TaskEntry, reason: &str) { + t.interface = None; + t.completion = None; + t.bindings.clear(); + t.provisional_result = None; + t.last_reason = Some(reason.to_string()); + } + + fn reset_to_blocked( + &mut self, + id: &str, + generation: u64, + at: u64, + reason: &str, + fx: &mut Effects, + ) -> Result<(), SchedError> { + if self.task(id)?.state != TaskState::Blocked { + self.set_state(id, TaskState::Blocked, at)?; + } + let t = self.task_mut(id)?; + t.generation = generation; + t.timing.revocations += 1; + Self::clear_work(t, reason); + fx.revoked.push(id.to_string()); + Ok(()) + } + + fn abort( + &mut self, + id: &str, + at: u64, + reason: &str, + fx: &mut Effects, + ) -> Result<(), SchedError> { + self.dequeue(id); + self.set_state(id, TaskState::Aborted, at)?; + Self::clear_work(self.task_mut(id)?, reason); + fx.aborted.push(id.to_string()); + Ok(()) + } + + /// Return every active descendant of `producer` to `Blocked` at a new + /// generation and discard its provisional result. Queued descendants + /// leave the queue and are re-checked by [`Core::pump`]. + fn revoke_descendants( + &mut self, + producer: &str, + at: u64, + reason: &str, + fx: &mut Effects, + ) -> Result<(), SchedError> { + for d in self.graph.descendants(producer) { + let t = self.task(&d)?; + if t.state.is_active() { + let next = t.generation + 1; + let why = format!("{reason} (upstream '{producer}')"); + self.reset_to_blocked(&d, next, at, &why, fx)?; + } else { + self.dequeue(&d); + } + } + Ok(()) + } + + fn eligible(&self, cfg: &ProvisionalConfig, id: &str) -> bool { + let Some(t) = self.tasks.get(id) else { + return false; + }; + t.state == TaskState::Blocked + && self.graph.producers_of(id).all(|p| { + self.tasks + .get(p) + .is_some_and(|pt| pt.final_ready() || (cfg.enabled && pt.interface_ready())) + }) + } + + fn bindings_for(&self, id: &str) -> BTreeMap { + let mut out = BTreeMap::new(); + for p in self.graph.producers_of(id) { + let Some(pt) = self.tasks.get(p) else { + continue; + }; + let (level, claim) = if pt.final_ready() { + (BindingLevel::Final, pt.completion.clone()) + } else { + (BindingLevel::Interface, pt.interface.clone()) + }; + if let Some(claim) = claim { + out.insert( + p.clone(), + Binding { + generation: pt.generation, + level, + claim, + }, + ); + } + } + out + } + + /// Fill the bounded ready queue in task-id order, then dispatch from its + /// head while permits allow (head-of-line, no reordering). + fn pump( + &mut self, + cfg: &ProvisionalConfig, + at: u64, + fx: &mut Effects, + ) -> Result<(), SchedError> { + loop { + let stale: Vec = self + .queue + .iter() + .filter(|id| !self.eligible(cfg, id)) + .cloned() + .collect(); + for id in stale { + self.dequeue(&id); + } + let ready: Vec = self + .tasks + .iter() + .filter(|(id, t)| !t.queued && self.eligible(cfg, id)) + .map(|(id, _)| id.clone()) + .collect(); + for id in ready { + if self.queue.len() >= cfg.queue_capacity { + break; + } + self.queue.push_back(id.clone()); + self.task_mut(&id)?.queued = true; + } + let mut progressed = false; + while let Some(head) = self.queue.front().cloned() { + let req = self.task(&head)?.resources; + if !self.pool.try_acquire(&cfg.limits, req) { + break; + } + self.queue.pop_front(); + let bindings = self.bindings_for(&head); + self.set_state(&head, TaskState::Provisional, at)?; + let t = self.task_mut(&head)?; + t.queued = false; + t.bindings = bindings; + t.lease_expires_at = Some(at.saturating_add(cfg.lease_ttl)); + // One lease per generation: leaving Provisional always ends + // in a new generation before the next dispatch. + t.last_beat = 0; + t.timing.dispatches += 1; + t.timing.first_dispatch_at.get_or_insert(at); + fx.dispatched.push(head); + progressed = true; + } + if !progressed { + return Ok(()); + } + } + } + + /// Apply one journal entry. On error the caller discards this copy of + /// the state, so a refused event changes nothing. + pub(crate) fn apply( + &mut self, + cfg: &ProvisionalConfig, + e: &JournalEntry, + ) -> Result { + if e.seq != self.seq + 1 { + return Err(bad(format!( + "sequence {} out of order, expected {}", + e.seq, + self.seq + 1 + ))); + } + if self.seen.contains(&e.id) { + return Err(SchedError::EventIdConflict(e.id.clone())); + } + if e.at < self.last_at { + return Err(bad("event time is earlier than the previous event")); + } + self.last_at = e.at; + let at = e.at; + let mut fx = Effects::default(); + match &e.kind { + EventKind::RegisterTask { + task, + resources, + producers, + } => { + check_identifier("task", task).map_err(|err| bad(err.to_string()))?; + if !cfg.limits.admits(*resources) { + return Err(SchedError::ExceedsCapacity(task.clone())); + } + self.graph.add_node(task)?; + for p in producers { + self.graph.add_edge(p, task)?; + } + self.tasks + .insert(task.clone(), TaskEntry::new(*resources, at)); + } + EventKind::AddDependency { producer, consumer } => { + self.graph.check_edge(producer, consumer)?; + self.require_state(consumer, |s| s == TaskState::Blocked, "gain a dependency")?; + self.graph.add_edge(producer, consumer)?; + self.dequeue(consumer); + } + EventKind::InterfacePublished { + task, + generation, + claim, + } + | EventKind::CompletionVerified { + task, + generation, + claim, + } => { + let is_interface = matches!(e.kind, EventKind::InterfacePublished { .. }); + self.require_generation(task, *generation)?; + self.require_state(task, TaskState::is_active, "publish proof")?; + let t = self.task_mut(task)?; + let slot = if is_interface { + &mut t.interface + } else { + &mut t.completion + }; + let changed = slot.is_some() && slot.as_ref() != Some(claim); + *slot = Some(claim.clone()); + if changed { + self.revoke_descendants(task, at, "producer proof changed", &mut fx)?; + } + } + EventKind::NewGeneration { task, generation } => { + let current = self.task(task)?.generation; + if *generation <= current { + return Err(SchedError::StaleGeneration { + task: task.clone(), + submitted: *generation, + current, + }); + } + self.require_state( + task, + |s| s != TaskState::Aborted, + "start a new generation (use retry)", + )?; + self.reset_to_blocked(task, *generation, at, "new generation", &mut fx)?; + self.revoke_descendants(task, at, "producer new generation", &mut fx)?; + } + EventKind::ProducerFailed { + task, + generation, + reason, + } => { + self.require_generation(task, *generation)?; + self.require_state(task, |s| s != TaskState::Aborted, "fail")?; + self.abort(task, at, &format!("failed: {reason}"), &mut fx)?; + self.revoke_descendants(task, at, "producer failed", &mut fx)?; + } + EventKind::WorkDone { + task, + generation, + result_digest, + } => { + self.require_generation(task, *generation)?; + self.require_state(task, |s| s == TaskState::Provisional, "report work done")?; + if !self.task(task)?.lease_valid(at) { + return Err(SchedError::LeaseExpired(task.clone())); + } + if result_digest.is_empty() { + return Err(bad("result_digest is empty")); + } + self.set_state(task, TaskState::AwaitingFinalProof, at)?; + self.task_mut(task)?.provisional_result = Some(result_digest.clone()); + } + EventKind::Finalize { task, generation } => { + self.require_generation(task, *generation)?; + self.require_state(task, |s| s == TaskState::AwaitingFinalProof, "finalize")?; + for p in self.graph.producers_of(task) { + let pt = self.task(p)?; + let bound = self.task(task)?.bindings.get(p).map(|b| b.generation); + if bound != Some(pt.generation) || !pt.final_ready() { + return Err(SchedError::ProducerNotFinal { + producer: p.clone(), + detail: "not committable with a completion at the bound generation" + .to_string(), + }); + } + } + self.set_state(task, TaskState::Committable, at)?; + self.task_mut(task)?.timing.committable_at = Some(at); + } + EventKind::Heartbeat { + task, + generation, + beat, + } => { + self.require_generation(task, *generation)?; + self.require_state(task, |s| s == TaskState::Provisional, "heartbeat")?; + let t = self.task_mut(task)?; + if !t.lease_valid(at) { + return Err(SchedError::LeaseExpired(task.clone())); + } + if *beat <= t.last_beat { + return Err(SchedError::StaleHeartbeat { + task: task.clone(), + beat: *beat, + last: t.last_beat, + }); + } + t.last_beat = *beat; + t.lease_expires_at = Some(at.saturating_add(cfg.lease_ttl)); + } + EventKind::Cancel { task, generation } => { + self.require_generation(task, *generation)?; + self.require_state(task, |s| s != TaskState::Aborted, "cancel")?; + self.abort(task, at, "cancelled", &mut fx)?; + for d in self.graph.descendants(task) { + if self.task(&d)?.state != TaskState::Aborted { + self.abort(&d, at, &format!("ancestor '{task}' cancelled"), &mut fx)?; + } + } + } + EventKind::Retry { task, generation } => { + self.require_generation(task, *generation)?; + self.require_state(task, |s| s == TaskState::Aborted, "retry")?; + self.set_state(task, TaskState::Blocked, at)?; + let t = self.task_mut(task)?; + t.generation += 1; + Self::clear_work(t, "retry"); + } + EventKind::Revoke { + task, + generation, + reason, + } => { + self.require_generation(task, *generation)?; + self.require_state(task, TaskState::is_active, "be revoked")?; + let next = self.task(task)?.generation + 1; + self.reset_to_blocked(task, next, at, reason, &mut fx)?; + self.revoke_descendants(task, at, reason, &mut fx)?; + } + EventKind::AuditRevoke { revocations } => { + let first = revocations + .first() + .ok_or_else(|| bad("empty audit revoke"))?; + self.require_state(&first.task, TaskState::is_active, "be revoked")?; + for r in revocations { + // Earlier entries may already have revoked this one. + let t = self.task(&r.task)?; + if t.state.is_active() { + let next = t.generation + 1; + self.reset_to_blocked(&r.task, next, at, &r.reason, &mut fx)?; + self.revoke_descendants(&r.task, at, &r.reason, &mut fx)?; + } + } + } + EventKind::Tick => { + let expired: Vec = self + .tasks + .iter() + .filter(|(_, t)| t.state == TaskState::Provisional && !t.lease_valid(at)) + .map(|(id, _)| id.clone()) + .collect(); + for id in expired { + if self.task(&id)?.state == TaskState::Provisional { + self.abort(&id, at, "lease expired", &mut fx)?; + self.revoke_descendants(&id, at, "producer lease expired", &mut fx)?; + } + } + } + } + self.pump(cfg, at, &mut fx)?; + self.seen + .record(&e.id, payload_digest(&e.kind), &e.kind, cfg.dedup_window); + let tasks = &self.tasks; + self.seen.prune(|t| tasks.get(t).map(|x| x.generation)); + self.seq = e.seq; + Ok(fx) + } +} diff --git a/crates/spark-harness/src/scheduler/dedup.rs b/crates/spark-harness/src/scheduler/dedup.rs new file mode 100644 index 00000000..b9bf72c9 --- /dev/null +++ b/crates/spark-harness/src/scheduler/dedup.rs @@ -0,0 +1,112 @@ +//! Bounded memory of applied event ids, for idempotent redelivery. +//! +//! Two scopes keep it bounded: +//! - Every task-directed event carries the task's generation and is +//! remembered under that task and generation. When the task moves to a +//! higher generation the older buckets are dropped: a redelivery of such +//! an event is then refused as a stale generation instead of reported as +//! a duplicate, and either way it changes nothing. Each of these events +//! happens at most a few times per generation, so a bucket stays small. +//! - The rest is remembered in a FIFO window of +//! `ProvisionalConfig::dedup_window` ids, and each stays safe when a +//! redelivery arrives after its id left the window: `RegisterTask` and +//! `AddDependency` are refused (duplicate node or edge), `Heartbeat` is +//! refused because its beat number is not above the last accepted one +//! (heartbeats are the one task-directed event that repeats without +//! bound, so they are not kept per generation), a repeated `Tick` only +//! re-checks leases, and `AuditRevoke` ids are reserved and never +//! redelivered. +//! +//! Pruning is deterministic, so a journal replay rebuilds the same memory. + +use super::core::EventKind; +use serde::Serialize; +use std::collections::{BTreeMap, VecDeque}; + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)] +pub struct Seen { + /// id -> payload digest for every remembered event. + ids: BTreeMap, + /// task -> generation -> ids of generation-bound events. + by_task: BTreeMap>>, + /// ids of generation-free events, oldest first. + window: VecDeque, +} + +/// The task and generation an event is bound to, if any. +pub(crate) fn generation_scope(kind: &EventKind) -> Option<(&str, u64)> { + match kind { + EventKind::InterfacePublished { + task, generation, .. + } + | EventKind::CompletionVerified { + task, generation, .. + } + | EventKind::NewGeneration { task, generation } + | EventKind::ProducerFailed { + task, generation, .. + } + | EventKind::WorkDone { + task, generation, .. + } + | EventKind::Finalize { task, generation } + | EventKind::Cancel { task, generation } + | EventKind::Retry { task, generation } + | EventKind::Revoke { + task, generation, .. + } => Some((task.as_str(), *generation)), + EventKind::RegisterTask { .. } + | EventKind::AddDependency { .. } + | EventKind::Heartbeat { .. } + | EventKind::AuditRevoke { .. } + | EventKind::Tick => None, + } +} + +impl Seen { + pub fn get(&self, id: &str) -> Option<&String> { + self.ids.get(id) + } + + pub fn contains(&self, id: &str) -> bool { + self.ids.contains_key(id) + } + + pub fn len(&self) -> usize { + self.ids.len() + } + + pub(crate) fn record(&mut self, id: &str, digest: String, kind: &EventKind, window: usize) { + self.ids.insert(id.to_string(), digest); + match generation_scope(kind) { + Some((task, generation)) => self + .by_task + .entry(task.to_string()) + .or_default() + .entry(generation) + .or_default() + .push(id.to_string()), + None => { + self.window.push_back(id.to_string()); + while self.window.len() > window { + if let Some(old) = self.window.pop_front() { + self.ids.remove(&old); + } + } + } + } + } + + /// Forget generation-bound ids below each task's current generation. + pub(crate) fn prune(&mut self, current: impl Fn(&str) -> Option) { + let Seen { ids, by_task, .. } = self; + for (task, gens) in by_task.iter_mut() { + let Some(now) = current(task) else { continue }; + let keep = gens.split_off(&now); + for old in std::mem::replace(gens, keep).into_values().flatten() { + ids.remove(&old); + } + } + by_task.retain(|_, gens| !gens.is_empty()); + } +} diff --git a/crates/spark-harness/src/scheduler/error.rs b/crates/spark-harness/src/scheduler/error.rs new file mode 100644 index 00000000..6b5d4f04 --- /dev/null +++ b/crates/spark-harness/src/scheduler/error.rs @@ -0,0 +1,151 @@ +//! Every way the provisional scheduler refuses an event or a gate query. + +use crate::completion::CompletionError; +use crate::dependency::GraphError; +use crate::execution::{IllegalTransition, TaskState}; +use crate::readiness::{OperationClass, ReadinessLevel, UnknownOperation}; +use std::fmt; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum SchedError { + InvalidEvent(String), + UnknownTask(String), + Graph(GraphError), + /// The task can never run: its request exceeds the whole budget. + ExceedsCapacity(String), + /// The event refers to a generation older than the task's current one. + StaleGeneration { + task: String, + submitted: u64, + current: u64, + }, + /// The event refers to a generation the scheduler has not reached. + FutureGeneration { + task: String, + submitted: u64, + current: u64, + }, + /// The task is in a state where this event or query is not allowed. + WrongState { + task: String, + state: TaskState, + action: &'static str, + }, + Transition(IllegalTransition), + LeaseExpired(String), + /// A heartbeat whose beat number is not above the last accepted one + /// for the current lease (a redelivery or a reordered beat). + StaleHeartbeat { + task: String, + beat: u64, + last: u64, + }, + /// The same event id was delivered with a different payload. + EventIdConflict(String), + UnknownOperation(UnknownOperation), + /// The producer's verified readiness does not allow this operation. + NotPermitted { + task: String, + op: OperationClass, + producer: String, + level: ReadinessLevel, + }, + /// The consumer has no binding to the producer (it was not dispatched + /// against it), or the binding is for an older generation. + StaleBinding { + task: String, + producer: String, + detail: String, + }, + /// A producer is not final-verified for its current generation. + ProducerNotFinal { + producer: String, + detail: String, + }, + /// Re-verification from the harness store failed. + Proof { + task: String, + error: CompletionError, + }, + Journal(String), +} + +impl fmt::Display for SchedError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + SchedError::InvalidEvent(m) => write!(f, "invalid event: {m}"), + SchedError::UnknownTask(t) => write!(f, "unknown task '{t}'"), + SchedError::Graph(e) => write!(f, "dependency graph: {e}"), + SchedError::ExceedsCapacity(t) => { + write!(f, "task '{t}' requests more than the whole resource budget") + } + SchedError::StaleGeneration { + task, + submitted, + current, + } => write!( + f, + "stale generation for '{task}': event {submitted}, current {current}" + ), + SchedError::FutureGeneration { + task, + submitted, + current, + } => write!( + f, + "unknown future generation for '{task}': event {submitted}, current {current}" + ), + SchedError::WrongState { + task, + state, + action, + } => write!(f, "task '{task}' is {}; cannot {action}", state.as_str()), + SchedError::Transition(e) => write!(f, "{e}"), + SchedError::LeaseExpired(t) => write!(f, "lease of task '{t}' expired"), + SchedError::StaleHeartbeat { task, beat, last } => write!( + f, + "heartbeat {beat} for task '{task}' is not above the last accepted beat {last}" + ), + SchedError::EventIdConflict(id) => { + write!(f, "event id '{id}' was already used for a different event") + } + SchedError::UnknownOperation(e) => write!(f, "{e}"), + SchedError::NotPermitted { + task, + op, + producer, + level, + } => write!( + f, + "task '{task}' may not run '{}': producer '{producer}' is only {level:?}", + op.as_str() + ), + SchedError::StaleBinding { + task, + producer, + detail, + } => write!(f, "task '{task}' binding to '{producer}': {detail}"), + SchedError::ProducerNotFinal { producer, detail } => { + write!(f, "producer '{producer}' is not final-verified: {detail}") + } + SchedError::Proof { task, error } => { + write!(f, "proof for '{task}' failed re-verification: {error}") + } + SchedError::Journal(m) => write!(f, "journal: {m}"), + } + } +} + +impl std::error::Error for SchedError {} + +impl From for SchedError { + fn from(e: GraphError) -> Self { + SchedError::Graph(e) + } +} + +impl From for SchedError { + fn from(e: IllegalTransition) -> Self { + SchedError::Transition(e) + } +} diff --git a/crates/spark-harness/src/scheduler/gates.rs b/crates/spark-harness/src/scheduler/gates.rs new file mode 100644 index 00000000..ae14f9a7 --- /dev/null +++ b/crates/spark-harness/src/scheduler/gates.rs @@ -0,0 +1,297 @@ +//! Store-backed gates: `may_start`, `may_finalize`, event proof checks and +//! the post-replay audit. +//! +//! Every gate re-reads receipts from the harness store and compares them +//! with the producers' current generations at call time. Scheduler state +//! (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::error::SchedError; +use super::{Event, Outcome, Scheduler, RESERVED_ID_PREFIX}; +use crate::completion::CompletionError; +use crate::execution::TaskState; +use crate::readiness::{verify_final, verify_interface, ArtifactReadiness, OperationClass}; + +fn proof(task: &str) -> impl Fn(CompletionError) -> SchedError + '_ { + move |error| SchedError::Proof { + task: task.to_string(), + error, + } +} + +impl Scheduler { + /// Checks that need the store, run before an event is journaled. + pub(crate) fn verify_proofs(&self, kind: &EventKind) -> Result<(), SchedError> { + match kind { + EventKind::InterfacePublished { + task, + generation, + claim, + } => { + self.core.require_generation(task, *generation)?; + verify_interface(&self.store, task, *generation, claim).map_err(proof(task))?; + } + EventKind::CompletionVerified { + task, + generation, + claim, + } => { + self.core.require_generation(task, *generation)?; + verify_final(&self.store, task, *generation, claim).map_err(proof(task))?; + } + EventKind::Finalize { task, generation } => { + self.core.require_generation(task, *generation)?; + self.may_finalize(task)?; + } + _ => {} + } + Ok(()) + } + + /// May `task` run `op` right now? Requires a `Provisional` task with a + /// live lease, a binding to every producer at the producer's current + /// generation, and a store-verified readiness for each producer whose + /// level permits `op`. Irreversible classes therefore need every + /// producer final-verified. A grant only says the dependencies allow + /// the operation; authorization and World commit stay with AEGIS and + /// aien-runtime. + pub fn may_start( + &self, + task: &str, + op: OperationClass, + ) -> Result, SchedError> { + let t = self.core.task(task)?; + if t.state != TaskState::Provisional { + return Err(SchedError::WrongState { + task: task.to_string(), + state: t.state, + action: "start an operation", + }); + } + let now = self.now(); + if !t.lease_expires_at.is_some_and(|exp| now < exp) { + return Err(SchedError::LeaseExpired(task.to_string())); + } + let mut out = Vec::new(); + for p in self.core.graph.producers_of(task) { + let r = self.bound_readiness(task, t, p)?; + if !r.permits(op) { + return Err(SchedError::NotPermitted { + task: task.to_string(), + op, + producer: p.clone(), + level: r.level(), + }); + } + out.push(r); + } + Ok(out) + } + + /// [`Scheduler::may_start`] for an operation name from outside (MCP, + /// config, CLI). Any name that is not an [`OperationClass`] is refused. + pub fn may_start_named( + &self, + task: &str, + op: &str, + ) -> Result, SchedError> { + let op = OperationClass::parse(op).map_err(SchedError::UnknownOperation)?; + self.may_start(task, op) + } + + /// May `task` become (or stay) `Committable`? Requires the task to be + /// `AwaitingFinalProof` or `Committable`, every binding at the producer's + /// current generation, an interface binding whose receipt still verifies + /// (no interface change), and every producer final-verified: M1 + /// completion verifies for its current generation, the producer is + /// `Committable`, and the same check passes for its own producers. + pub fn may_finalize(&self, task: &str) -> Result, SchedError> { + self.finalize_check(task, 0) + } + + fn finalize_check( + &self, + task: &str, + depth: usize, + ) -> Result, SchedError> { + if depth > self.core.tasks.len() { + return Err(SchedError::InvalidEvent( + "dependency recursion deeper than the task count".to_string(), + )); + } + let t = self.core.task(task)?; + if !matches!( + t.state, + TaskState::AwaitingFinalProof | TaskState::Committable + ) { + return Err(SchedError::WrongState { + task: task.to_string(), + state: t.state, + action: "finalize", + }); + } + let mut out = Vec::new(); + for p in self.core.graph.producers_of(task) { + let b = self.binding(task, t, p)?; + if b.level == BindingLevel::Interface { + verify_interface(&self.store, p, b.generation, &b.claim).map_err(proof(p))?; + } + out.push(self.producer_final(p, depth + 1)?); + } + Ok(out) + } + + fn producer_final(&self, p: &str, depth: usize) -> Result { + let pt = self.core.task(p)?; + let claim = match (&pt.completion, pt.final_ready()) { + (Some(c), true) => c, + _ => { + return Err(SchedError::ProducerNotFinal { + producer: p.to_string(), + detail: format!( + "state {}, completion accepted: {}", + pt.state.as_str(), + pt.completion.is_some() + ), + }) + } + }; + let r = verify_final(&self.store, p, pt.generation, claim).map_err(proof(p))?; + self.finalize_check(p, depth)?; + Ok(r) + } + + fn binding<'a>( + &self, + task: &str, + t: &'a TaskEntry, + p: &str, + ) -> Result<&'a Binding, SchedError> { + let stale = |detail: String| SchedError::StaleBinding { + task: task.to_string(), + producer: p.to_string(), + detail, + }; + let current = self.core.task(p)?.generation; + let b = t + .bindings + .get(p) + .ok_or_else(|| stale("no binding".to_string()))?; + if b.generation != current { + return Err(stale(format!( + "bound to generation {}, producer is at {current}", + b.generation + ))); + } + Ok(b) + } + + /// Re-verified readiness of producer `p` as `task` is bound to it. An + /// interface binding is upgraded to final when the producer is final and + /// that proof verifies; if the upgrade fails the interface level (the + /// more restrictive one) is returned. + fn bound_readiness( + &self, + task: &str, + t: &TaskEntry, + p: &str, + ) -> Result { + let b = self.binding(task, t, p)?; + match b.level { + BindingLevel::Interface => { + let r = + verify_interface(&self.store, p, b.generation, &b.claim).map_err(proof(p))?; + if self.core.task(p)?.final_ready() { + if let Ok(f) = self.producer_final(p, 1) { + return Ok(f); + } + } + Ok(r) + } + BindingLevel::Final => self.producer_final(p, 1), + } + } + + /// Active tasks whose own accepted interface or completion claim no + /// longer verifies. + fn own_claim_failures(&self) -> Vec { + let mut out = Vec::new(); + for (id, t) in self.core.tasks.iter().filter(|(_, t)| t.state.is_active()) { + let g = t.generation; + let i = t + .interface + .as_ref() + .map(|c| verify_interface(&self.store, id, g, c)); + let f = t + .completion + .as_ref() + .map(|c| verify_final(&self.store, id, g, c)); + if let Some(e) = [i, f].into_iter().flatten().find_map(Result::err) { + out.push(revocation(id, proof(id)(e))); + } + } + out + } + + /// Active tasks whose bindings or finalize check no longer verify. + fn binding_failures(&self) -> Vec { + let mut out = Vec::new(); + for (id, t) in &self.core.tasks { + let check = match t.state { + TaskState::Provisional | TaskState::AwaitingFinalProof => self + .core + .graph + .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(()), + }; + if let Err(e) = check { + out.push(revocation(id, e)); + } + } + out + } + + /// Re-verify every active task against the store and revoke the ones + /// that no longer verify. Run whenever the store may have changed; a + /// replayed journal must pass through it (see [`super::Unaudited`]). + /// Returns the revoked tasks. + /// + /// Each round is one journaled `AuditRevoke`: first every task whose own + /// claim fails (which cascades to its consumers), and only when there + /// are none, every task whose bindings fail. One batch dispatches once, + /// 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. + pub fn audit(&mut self) -> Result, SchedError> { + let mut revoked = Vec::new(); + for _ in 0..=2 * self.core.tasks.len() { + let mut batch = self.own_claim_failures(); + if batch.is_empty() { + batch = self.binding_failures(); + } + if batch.is_empty() { + return Ok(revoked); + } + let event = Event { + id: format!("{RESERVED_ID_PREFIX}audit-{}", self.core.seq + 1), + kind: EventKind::AuditRevoke { revocations: batch }, + }; + if let Outcome::Applied(fx) = self.deliver_unchecked(event)? { + revoked.extend(fx.revoked); + } + } + Err(SchedError::InvalidEvent( + "audit did not converge; refusing to continue".to_string(), + )) + } +} + +fn revocation(task: &str, e: SchedError) -> Revocation { + Revocation { + task: task.to_string(), + reason: format!("audit: {e}"), + } +} diff --git a/crates/spark-harness/src/scheduler/mod.rs b/crates/spark-harness/src/scheduler/mod.rs new file mode 100644 index 00000000..869c99ab --- /dev/null +++ b/crates/spark-harness/src/scheduler/mod.rs @@ -0,0 +1,388 @@ +//! Provisional dependency scheduler (Headstart M2, issue #535). +//! +//! Lets a consumer task start reversible, sandboxed preparation as soon as +//! its producers publish a harness-verified interface, while final +//! completion waits for every producer's M1 verified completion. This is an +//! engineering-workflow scheduler only; it does not touch inference +//! scheduling, KV/prefill fences, aien-trace or World commit. +//! +//! Opt-in: [`ProvisionalConfig::enabled`] defaults to `false`. Disabled means +//! no early start: a consumer stays `Blocked` until every producer is +//! final-verified and `Committable`, which is plain sequential behavior. No +//! existing spark-harness API or MCP tool uses this module. +//! +//! Model: +//! - Tasks and producer -> consumer edges form a cycle-checked DAG +//! (`dependency.rs`). Task states and the transition table live in +//! `execution.rs`. +//! - Everything is an [`Event`] with a caller-chosen id. Redelivering the +//! same id with the same payload is a no-op ([`Outcome::Duplicate`]); the +//! same id with a different payload is refused. +//! - [`Scheduler::deliver`] runs the store checks for the event, applies it +//! to a copy of the state, journals it, then swaps the copy in. A refused +//! event changes nothing and is not journaled. +//! - Producers have monotonic generations. Events for an older generation are +//! refused as stale. A producer failure, a changed interface or completion +//! at the same generation, a new generation, a lost lease or a revocation +//! returns every active descendant to `Blocked` at a new generation and +//! discards its provisional result. +//! - A bounded ready queue feeds dispatch. Dispatch takes CPU, memory and +//! concurrency permits all at once and grants a lease; only `Provisional` +//! tasks hold permits. +//! +//! Persistence choice: an append-only JSON-lines journal (`journal.rs`) of +//! accepted events, opened with [`Scheduler::open`]. Replay re-applies the +//! events through the same pure state machine, using the times recorded in +//! the journal, so it rebuilds the same state (and the same timing trace). +//! Replay does not re-read the store, so `open` returns an [`Unaudited`] +//! handle whose only method is `audit`: no event, dispatch or gate query +//! can run on replayed state until every active task was re-verified +//! against the store. After that every `may_start` and `may_finalize` +//! still re-verifies at call time. A task becomes `Committable` only +//! through a journaled `Finalize` event, which is journaled only after +//! `may_finalize` passed, so replay cannot turn an unfinished provisional +//! task into a committable one. The journal is trusted like the store +//! itself (filesystem ownership); it is not signed. +//! +//! Time after a restart: a new process gets a new clock, so `open` rebases +//! it onto the last journaled time (`now = last_at + clock() - clock_at_open`). +//! Leases of workers that died with the old process therefore expire at +//! most `lease_ttl` ticks after the restart. The downtime itself is not +//! counted. +//! +//! Cost per event: `deliver` applies the event to a copy of the state so a +//! refused event changes nothing. The copy is O(tasks + edges + +//! `dedup_window`), the same order as the dispatch scan every event already +//! does; `deliver_cost_is_small_next_to_the_journal_fsync` (ignored test) +//! measures it. Journal compaction (a snapshot header so replay does not +//! start from the first event) is a follow-up; until then the journal and +//! replay time grow with the event count. + +pub mod core; +mod dedup; +pub mod error; +mod gates; +pub mod permits; +pub mod timing; +#[cfg(test)] +mod unit_tests; + +pub use self::core::{ + Binding, BindingLevel, Effects, Event, EventKind, JournalEntry, Revocation, TaskEntry, +}; +pub use self::error::SchedError; +pub use self::permits::{PermitPool, ResourceLimits, ResourceRequest}; + +use self::core::{payload_digest, Core}; +use crate::completion::check_identifier; +use crate::execution::TaskState; +use crate::journal::Journal; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; +use std::path::{Path, PathBuf}; + +/// Monotonic clock in ticks. Injected so tests are deterministic. +pub type Clock = Box u64 + Send + Sync>; + +/// Nanoseconds since this clock was created, from `std::time::Instant`. +/// A new process starts a new base; [`Scheduler::open`] rebases it onto +/// the last journaled time (see the module docs). +pub fn monotonic_clock() -> Clock { + let start = std::time::Instant::now(); + Box::new(move || u64::try_from(start.elapsed().as_nanos()).unwrap_or(u64::MAX)) +} + +pub const JOURNAL_FORMAT: &str = "spark-harness-provisional-journal"; +/// Version 2: task-directed events carry a generation and heartbeats a +/// beat number. A version 1 journal +/// fails the header check on open and is never replayed. +pub const JOURNAL_VERSION: u64 = 2; +pub const TRACE_SCHEMA: &str = "spark-harness-provisional-trace"; +/// Event ids starting with this are reserved for events the scheduler +/// emits itself (the audit). [`Scheduler::deliver`] refuses them. +pub const RESERVED_ID_PREFIX: &str = "spark-harness:"; + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ProvisionalConfig { + /// Allow early start on interface-verified producers. Default `false`. + pub enabled: bool, + /// Maximum ready-queue length (at least 1). + pub queue_capacity: usize, + pub limits: ResourceLimits, + /// Lease length in clock ticks (at least 1). + pub lease_ttl: u64, + /// How many generation-free event ids are remembered for duplicate + /// detection (at least 1). See `dedup.rs`. + pub dedup_window: usize, +} + +impl Default for ProvisionalConfig { + fn default() -> Self { + ProvisionalConfig { + enabled: false, + queue_capacity: 64, + limits: ResourceLimits::default(), + lease_ttl: 300_000_000_000, + dedup_window: 4096, + } + } +} + +impl ProvisionalConfig { + fn validate(&self) -> Result<(), SchedError> { + if self.queue_capacity == 0 + || self.lease_ttl == 0 + || self.limits.max_concurrency == 0 + || self.dedup_window == 0 + { + return Err(SchedError::InvalidEvent( + "config needs queue_capacity, lease_ttl, max_concurrency and dedup_window of at least 1" + .to_string(), + )); + } + Ok(()) + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub enum Outcome { + Applied(Effects), + /// The event id was already applied with the same payload. + Duplicate, +} + +/// What [`Scheduler::open`] found in the journal. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ReplayReport { + pub entries: usize, + pub torn_bytes: usize, +} + +pub struct Scheduler { + cfg: ProvisionalConfig, + store: PathBuf, + clock: Clock, + /// `now = clock_base + clock() - clock_origin` (see the module docs). + clock_base: u64, + clock_origin: u64, + core: Core, + journal: Option, +} + +/// A replayed scheduler that has not been checked against the store yet. +/// Its only method is [`Unaudited::audit`]. +#[must_use = "a replayed scheduler is usable only after audit()"] +pub struct Unaudited { + sched: Scheduler, +} + +impl Unaudited { + /// 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), SchedError> { + let revoked = self.sched.audit()?; + Ok((self.sched, revoked)) + } +} + +impl Scheduler { + /// In-memory scheduler (no journal). `store` is the harness store that + /// holds interface and completion receipts (`HarnessEngine::completion_store`). + pub fn new(cfg: ProvisionalConfig, store: &Path, clock: Clock) -> Result { + cfg.validate()?; + Ok(Scheduler { + cfg, + store: store.to_path_buf(), + clock, + clock_base: 0, + clock_origin: 0, + core: Core::default(), + journal: None, + }) + } + + /// Journaled scheduler: create `journal` or replay it. The journal's + /// header must carry the same config, because dispatch depends on it. + /// The replayed state must pass [`Unaudited::audit`] before use. + pub fn open( + cfg: ProvisionalConfig, + store: &Path, + journal: &Path, + clock: Clock, + ) -> Result<(Unaudited, ReplayReport), SchedError> { + let mut s = Scheduler::new(cfg, store, clock)?; + let header = + json!({ "format": JOURNAL_FORMAT, "version": JOURNAL_VERSION, "config": s.cfg }); + let opened = + Journal::open::(journal, &header).map_err(SchedError::Journal)?; + for entry in &opened.entries { + s.core.apply(&s.cfg, entry).map_err(|e| { + SchedError::Journal(format!("replay of entry {} failed: {e}", entry.seq)) + })?; + } + if !opened.entries.is_empty() { + s.clock_base = s.core.last_at; + s.clock_origin = (s.clock)(); + } + let report = ReplayReport { + entries: opened.entries.len(), + torn_bytes: opened.torn_bytes, + }; + s.journal = Some(opened.journal); + Ok((Unaudited { sched: s }, report)) + } + + pub fn config(&self) -> &ProvisionalConfig { + &self.cfg + } + + fn now(&self) -> u64 { + let elapsed = (self.clock)().saturating_sub(self.clock_origin); + self.clock_base + .saturating_add(elapsed) + .max(self.core.last_at) + } + + /// Validate, journal and apply one event. See the module docs. Ids with + /// [`RESERVED_ID_PREFIX`] and `AuditRevoke` events are refused: only + /// the scheduler emits those. + pub fn deliver(&mut self, event: Event) -> Result { + if event.id.starts_with(RESERVED_ID_PREFIX) { + return Err(SchedError::InvalidEvent(format!( + "event ids starting with '{RESERVED_ID_PREFIX}' are reserved" + ))); + } + if matches!(event.kind, EventKind::AuditRevoke { .. }) { + return Err(SchedError::InvalidEvent( + "audit_revoke is emitted only by audit()".to_string(), + )); + } + self.deliver_unchecked(event) + } + + pub(crate) fn deliver_unchecked(&mut self, event: Event) -> Result { + check_identifier("event id", &event.id) + .map_err(|e| SchedError::InvalidEvent(e.to_string()))?; + if let Some(prev) = self.core.seen.get(&event.id) { + return if *prev == payload_digest(&event.kind) { + Ok(Outcome::Duplicate) + } else { + Err(SchedError::EventIdConflict(event.id)) + }; + } + self.verify_proofs(&event.kind)?; + let entry = JournalEntry { + seq: self.core.seq + 1, + id: event.id, + at: self.now(), + kind: event.kind, + }; + let mut next = self.core.clone(); + let fx = next.apply(&self.cfg, &entry)?; + if let Some(j) = self.journal.as_mut() { + j.append(&entry).map_err(SchedError::Journal)?; + } + self.core = next; + Ok(Outcome::Applied(fx)) + } + + pub fn task(&self, id: &str) -> Option<&TaskEntry> { + self.core.tasks.get(id) + } + + pub fn state(&self, id: &str) -> Option { + self.task(id).map(|t| t.state) + } + + pub fn generation(&self, id: &str) -> Option { + self.task(id).map(|t| t.generation) + } + + pub fn queue(&self) -> Vec { + self.core.queue.iter().cloned().collect() + } + + pub fn permits_in_use(&self) -> PermitPool { + self.core.pool + } + + /// How many event ids are remembered for duplicate detection. + pub fn remembered_event_ids(&self) -> usize { + self.core.seen.len() + } + + /// Full scheduler state as JSON, for replay comparisons and debugging. + pub fn snapshot(&self) -> Value { + serde_json::to_value(&self.core).unwrap_or(Value::Null) + } + + /// Structural invariants. Tests call this after every step. + pub fn check_invariants(&self) -> Result<(), String> { + let mut pool = PermitPool::default(); + for (id, t) in &self.core.tasks { + if t.state.holds_permits() { + pool.running += 1; + pool.cpu_in_use += t.resources.cpu_slots; + pool.memory_in_use += t.resources.memory_bytes; + if self.core.graph.producers_of(id).count() != t.bindings.len() { + return Err(format!("running task '{id}' lacks a producer binding")); + } + } else if t.lease_expires_at.is_some() { + return Err(format!( + "task '{id}' is {} but holds a lease", + t.state.as_str() + )); + } + let in_queue = self.core.queue.iter().any(|q| q == id); + if t.queued != in_queue || (in_queue && t.state != TaskState::Blocked) { + return Err(format!("task '{id}' queue flag disagrees with the queue")); + } + } + if pool != self.core.pool { + return Err(format!( + "permits in use {:?} differ from running tasks {:?}", + self.core.pool, pool + )); + } + if self.core.queue.len() > self.cfg.queue_capacity { + return Err("ready queue exceeds its bound".to_string()); + } + Ok(()) + } + + /// Per-task blocked and provisional time as of the last event, for the + /// M6 A/B analysis. Derived only from journaled event times. + pub fn timing_trace(&self) -> Value { + let now = self.core.last_at; + let tasks: Vec = self + .core + .tasks + .iter() + .map(|(id, t)| { + let timing = t.timing.as_of(t.state, now); + json!({ + "task": id, + "state": t.state.as_str(), + "generation": t.generation, + "blocked": timing.blocked, + "provisional": timing.provisional, + "awaiting_final_proof": timing.awaiting_final_proof, + "registered_at": timing.registered_at, + "first_dispatch_at": timing.first_dispatch_at, + "committable_at": timing.committable_at, + "dispatches": timing.dispatches, + "revocations": timing.revocations, + }) + }) + .collect(); + json!({ + "schema": TRACE_SCHEMA, + "version": 1, + "enabled": self.cfg.enabled, + "clock": "injected monotonic clock ticks", + "as_of": now, + "tasks": tasks, + }) + } +} diff --git a/crates/spark-harness/src/scheduler/permits.rs b/crates/spark-harness/src/scheduler/permits.rs new file mode 100644 index 00000000..eee679e7 --- /dev/null +++ b/crates/spark-harness/src/scheduler/permits.rs @@ -0,0 +1,70 @@ +//! Resource permits: CPU slots, memory bytes and a concurrency count. +//! +//! A task acquires all three at dispatch or none of them. Permits are held +//! exactly while the task is `Provisional` (see `execution.rs`). + +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ResourceLimits { + pub cpu_slots: u32, + pub memory_bytes: u64, + pub max_concurrency: u32, +} + +impl Default for ResourceLimits { + fn default() -> Self { + ResourceLimits { + cpu_slots: 4, + memory_bytes: 8 << 30, + max_concurrency: 4, + } + } +} + +/// What one task needs while it runs. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ResourceRequest { + pub cpu_slots: u32, + pub memory_bytes: u64, +} + +impl ResourceLimits { + /// Could this request ever run, with the whole budget free? + pub fn admits(&self, req: ResourceRequest) -> bool { + self.max_concurrency >= 1 + && req.cpu_slots <= self.cpu_slots + && req.memory_bytes <= self.memory_bytes + } +} + +/// Permits currently handed out. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)] +pub struct PermitPool { + pub cpu_in_use: u32, + pub memory_in_use: u64, + pub running: u32, +} + +impl PermitPool { + /// Take all permits for `req`, or none. + pub fn try_acquire(&mut self, limits: &ResourceLimits, req: ResourceRequest) -> bool { + let fits = self.running < limits.max_concurrency + && self.cpu_in_use.saturating_add(req.cpu_slots) <= limits.cpu_slots + && self.memory_in_use.saturating_add(req.memory_bytes) <= limits.memory_bytes; + if fits { + self.running += 1; + self.cpu_in_use += req.cpu_slots; + self.memory_in_use += req.memory_bytes; + } + fits + } + + pub fn release(&mut self, req: ResourceRequest) { + self.running = self.running.saturating_sub(1); + self.cpu_in_use = self.cpu_in_use.saturating_sub(req.cpu_slots); + self.memory_in_use = self.memory_in_use.saturating_sub(req.memory_bytes); + } +} diff --git a/crates/spark-harness/src/scheduler/timing.rs b/crates/spark-harness/src/scheduler/timing.rs new file mode 100644 index 00000000..c31bf274 --- /dev/null +++ b/crates/spark-harness/src/scheduler/timing.rs @@ -0,0 +1,53 @@ +//! Per-task timing from the scheduler's monotonic clock, for the M6 A/B +//! analysis. Times are clock ticks as returned by the injected clock (the +//! default clock counts nanoseconds). Every value is derived from event +//! times recorded in the journal, so a replay reproduces the trace exactly. + +use crate::execution::TaskState; +use serde::Serialize; + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)] +pub struct TaskTiming { + /// Ticks spent `Blocked` (including waiting in the ready queue). + pub blocked: u64, + /// Ticks spent `Provisional` (running, holding permits). + pub provisional: u64, + /// Ticks spent `AwaitingFinalProof`. + pub awaiting_final_proof: u64, + pub registered_at: u64, + pub first_dispatch_at: Option, + pub committable_at: Option, + pub dispatches: u32, + pub revocations: u32, + /// Start of the current state. + pub since: u64, +} + +impl TaskTiming { + pub fn new(at: u64) -> Self { + TaskTiming { + registered_at: at, + since: at, + ..TaskTiming::default() + } + } + + /// Charge the time since the last transition to `state`. + pub fn close(&mut self, state: TaskState, at: u64) { + let spent = at.saturating_sub(self.since); + match state { + TaskState::Blocked => self.blocked += spent, + TaskState::Provisional => self.provisional += spent, + TaskState::AwaitingFinalProof => self.awaiting_final_proof += spent, + TaskState::Committable | TaskState::Aborted => {} + } + self.since = at; + } + + /// Totals as of `now`, counting the open interval in the current state. + pub fn as_of(&self, state: TaskState, now: u64) -> TaskTiming { + let mut t = self.clone(); + t.close(state, now); + t + } +} diff --git a/crates/spark-harness/src/scheduler/unit_tests.rs b/crates/spark-harness/src/scheduler/unit_tests.rs new file mode 100644 index 00000000..fcad8901 --- /dev/null +++ b/crates/spark-harness/src/scheduler/unit_tests.rs @@ -0,0 +1,131 @@ +//! Guards that no event sequence reaches (defense in depth), tested on a +//! hand-built state. + +use super::core::{Binding, BindingLevel, TaskEntry}; +use super::{ProvisionalConfig, ResourceRequest, SchedError, Scheduler}; +use crate::execution::TaskState; +use crate::readiness::{OperationClass, ProofClaim}; +use std::path::Path; + +fn req() -> ResourceRequest { + ResourceRequest { + cpu_slots: 1, + memory_bytes: 1, + } +} + +/// Producer `p` at generation 2; consumer `c` in `state`, still bound to +/// generation 1. Revocation always clears such a binding, so only a +/// corrupted state can carry one. +fn stale_binding(state: TaskState) -> Scheduler { + let cfg = ProvisionalConfig { + enabled: true, + ..ProvisionalConfig::default() + }; + let store = Path::new("/nonexistent/spark-harness-m2-unit-store"); + let mut s = Scheduler::new(cfg, store, Box::new(|| 100)).unwrap(); + s.core.graph.add_node("p").unwrap(); + s.core.graph.add_node("c").unwrap(); + s.core.graph.add_edge("p", "c").unwrap(); + let mut p = TaskEntry::new(req(), 0); + p.generation = 2; + let mut c = TaskEntry::new(req(), 0); + c.state = state; + c.lease_expires_at = Some(1_000); + c.bindings.insert( + "p".to_string(), + Binding { + generation: 1, + level: BindingLevel::Interface, + claim: ProofClaim { + receipt_id: "r".to_string(), + commit: "c".to_string(), + digest: "d".to_string(), + }, + }, + ); + s.core.tasks.insert("p".to_string(), p); + s.core.tasks.insert("c".to_string(), c); + s +} + +#[test] +fn binding_to_an_old_producer_generation_is_refused() { + let s = stale_binding(TaskState::Provisional); + let r = s.may_start("c", OperationClass::ReadOnlyAnalysis); + assert!(matches!(r, Err(SchedError::StaleBinding { .. })), "{r:?}"); + let s = stale_binding(TaskState::AwaitingFinalProof); + let r = s.may_finalize("c"); + assert!(matches!(r, Err(SchedError::StaleBinding { .. })), "{r:?}"); +} + +/// Measures the whole-state copy `deliver` makes per event, next to the +/// full in-memory deliver (copy + apply + dispatch scan) and one journal +/// append with fsync. Run with +/// `cargo test --release -p spark-harness --lib -- --ignored --nocapture` +/// (task count from `M2_COST_TASKS`, default 2000). +#[test] +#[ignore] +fn deliver_cost_is_small_next_to_the_journal_fsync() { + use super::{Event, EventKind}; + use std::time::Instant; + let tasks: usize = std::env::var("M2_COST_TASKS") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(2_000); + const N: u32 = 200; + let cfg = ProvisionalConfig { + enabled: true, + ..ProvisionalConfig::default() + }; + let store = Path::new("/nonexistent/spark-harness-m2-unit-store"); + let mut s = Scheduler::new(cfg, store, Box::new(|| 1)).unwrap(); + for i in 0..tasks { + let producers = if i == 0 { + vec![] + } else { + vec!["t0".to_string()] + }; + let kind = EventKind::RegisterTask { + task: format!("t{i}"), + resources: req(), + producers, + }; + s.deliver(Event { + id: format!("reg-{i}"), + kind, + }) + .unwrap(); + } + let start = Instant::now(); + for _ in 0..N { + std::hint::black_box(s.core.clone()); + } + let copy = start.elapsed() / N; + let start = Instant::now(); + for i in 0..N { + let ev = Event { + id: format!("tick-{i}"), + kind: EventKind::Tick, + }; + s.deliver(ev).unwrap(); + } + let deliver = start.elapsed() / N; + let dir = std::env::temp_dir().join(format!("spark-harness-m2-cost-{}", uuid::Uuid::new_v4())); + let header = serde_json::json!({ "format": "cost" }); + let mut j = crate::journal::Journal::open::(&dir.join("j.jsonl"), &header) + .unwrap() + .journal; + let line = serde_json::json!({ "seq": 1, "id": "tick", "at": 1, "kind": { "type": "tick" } }); + let start = Instant::now(); + for _ in 0..N { + j.append(&line).unwrap(); + } + let fsync = start.elapsed() / N; + drop(j); + let _ = std::fs::remove_dir_all(&dir); + println!( + "M2_DELIVER_COST tasks={tasks} state_copy={copy:?} in_memory_deliver={deliver:?} \ + journal_append_fsync={fsync:?}" + ); +} diff --git a/crates/spark-harness/tests/common/mod.rs b/crates/spark-harness/tests/common/mod.rs new file mode 100644 index 00000000..d00f922e --- /dev/null +++ b/crates/spark-harness/tests/common/mod.rs @@ -0,0 +1,304 @@ +//! Shared fixtures for the Headstart M2 scheduler tests. Deterministic: +//! a fixed receipt clock and a manual monotonic scheduler clock. +#![allow(dead_code)] + +use serde_json::{json, Value}; +use spark_harness::completion::CompletionSubmission; +use spark_harness::readiness::{InterfaceSubmission, ProofClaim}; +use spark_harness::scheduler::{ + Clock, Effects, Event, EventKind, Outcome, ProvisionalConfig, ResourceLimits, ResourceRequest, + SchedError, Scheduler, +}; +use spark_harness::{HarnessEngine, WorkflowState}; +use std::fs; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::Arc; + +pub const COMMIT: &str = "1111111111111111111111111111111111111111"; + +fn fixed_receipt_clock() -> u64 { + 1_760_000_000 +} + +/// Temp copy of the shipped definitions, removed on drop. +pub struct Fixture { + pub dir: PathBuf, +} + +impl Fixture { + pub fn new() -> Self { + let dir = std::env::temp_dir().join(format!("spark-harness-m2-{}", uuid::Uuid::new_v4())); + let src = Path::new(env!("CARGO_MANIFEST_DIR")); + fs::create_dir_all(dir.join("schemas")).unwrap(); + for f in ["workflows.json", "evals.json"] { + fs::copy(src.join(f), dir.join(f)).unwrap(); + } + for entry in fs::read_dir(src.join("schemas")).unwrap() { + let entry = entry.unwrap(); + fs::copy(entry.path(), dir.join("schemas").join(entry.file_name())).unwrap(); + } + Fixture { dir } + } + + pub fn engine(&self) -> HarnessEngine { + let mut e = HarnessEngine::load(&self.dir).expect("shipped definitions load"); + e.completion_clock = fixed_receipt_clock; + e + } + + pub fn journal(&self) -> PathBuf { + self.dir.join("sched").join("journal.jsonl") + } +} + +impl Drop for Fixture { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.dir); + } +} + +pub fn clock(ticks: &Arc) -> Clock { + let t = Arc::clone(ticks); + Box::new(move || t.load(Ordering::SeqCst)) +} + +pub fn enabled() -> ProvisionalConfig { + ProvisionalConfig { + enabled: true, + queue_capacity: 8, + limits: ResourceLimits { + cpu_slots: 8, + memory_bytes: 1 << 30, + max_concurrency: 8, + }, + lease_ttl: 1_000, + dedup_window: 64, + } +} + +pub fn req(cpu: u32) -> ResourceRequest { + ResourceRequest { + cpu_slots: cpu, + memory_bytes: 1 << 20, + } +} + +pub fn engineering_fix_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 scheduler plus the harness engine whose store it verifies against. +pub struct H { + pub fx: Fixture, + pub engine: HarnessEngine, + pub ticks: Arc, + pub sched: Scheduler, + n: u64, +} + +impl H { + pub fn new(cfg: ProvisionalConfig) -> Self { + let fx = Fixture::new(); + let engine = fx.engine(); + let ticks = Arc::new(AtomicU64::new(0)); + let sched = Scheduler::new(cfg, &engine.completion_store, clock(&ticks)).unwrap(); + H { + fx, + engine, + ticks, + sched, + n: 0, + } + } + + pub fn journaled(cfg: ProvisionalConfig) -> Self { + let fx = Fixture::new(); + let engine = fx.engine(); + let ticks = Arc::new(AtomicU64::new(0)); + let (unaudited, report) = + Scheduler::open(cfg, &engine.completion_store, &fx.journal(), clock(&ticks)).unwrap(); + assert_eq!(report.entries, 0); + let (sched, revoked) = unaudited.audit().unwrap(); + assert!(revoked.is_empty()); + H { + fx, + engine, + ticks, + sched, + n: 0, + } + } + + /// Drop the scheduler (closing the journal), replay it from disk and + /// audit it. Returns the torn bytes dropped and the tasks the audit + /// revoked. + pub fn reopen(&mut self, cfg: ProvisionalConfig) -> Result<(usize, Vec), SchedError> { + let placeholder = Scheduler::new( + cfg.clone(), + &self.engine.completion_store, + clock(&self.ticks), + )?; + drop(std::mem::replace(&mut self.sched, placeholder)); + let (unaudited, report) = Scheduler::open( + cfg, + &self.engine.completion_store, + &self.fx.journal(), + clock(&self.ticks), + )?; + let (sched, revoked) = unaudited.audit()?; + self.sched = sched; + Ok((report.torn_bytes, revoked)) + } + + /// Simulate a process restart: the new process's clock starts at 0. + pub fn restart(&mut self, cfg: ProvisionalConfig) -> Result<(usize, Vec), SchedError> { + self.ticks.store(0, Ordering::SeqCst); + self.reopen(cfg) + } + + pub fn advance(&self, d: u64) { + self.ticks.fetch_add(d, Ordering::SeqCst); + } + + pub fn next_id(&mut self) -> String { + self.n += 1; + format!("ev-{}", self.n) + } + + /// Deliver with a fresh id; check invariants either way. + pub fn send(&mut self, kind: EventKind) -> Result { + let id = self.next_id(); + let r = self.sched.deliver(Event { id, kind }); + self.sched.check_invariants().unwrap(); + r + } + + pub fn ok(&mut self, kind: EventKind) -> Effects { + self.advance(10); + match self.send(kind.clone()) { + Ok(Outcome::Applied(fx)) => fx, + other => panic!("event {kind:?} not applied: {other:?}"), + } + } + + pub fn register(&mut self, task: &str, cpu: u32, producers: &[&str]) -> Effects { + self.ok(EventKind::RegisterTask { + task: task.into(), + resources: req(cpu), + producers: producers.iter().map(|p| p.to_string()).collect(), + }) + } + + pub fn edge(&mut self, producer: &str, consumer: &str) { + self.ok(EventKind::AddDependency { + producer: producer.into(), + consumer: consumer.into(), + }); + } + + pub fn generation(&self, task: &str) -> u64 { + self.sched.generation(task).unwrap() + } + + /// Mint an interface receipt in the harness store (not delivered). + pub fn mint_interface(&self, task: &str, version: u32) -> ProofClaim { + self.engine + .publish_interface(&InterfaceSubmission { + task_id: task.into(), + generation: self.generation(task), + source_commit: COMMIT.into(), + interface: json!({ "task": task, "api_version": version }), + }) + .unwrap() + .claim() + } + + pub fn publish(&mut self, task: &str, version: u32) -> (ProofClaim, Effects) { + let claim = self.mint_interface(task, version); + let generation = self.generation(task); + let fx = self.ok(EventKind::InterfacePublished { + task: task.into(), + generation, + claim: claim.clone(), + }); + (claim, fx) + } + + /// Run the M1 verified completion for the task's current generation. + pub 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.generation(task), + source_commit: COMMIT.into(), + artifact: engineering_fix_artifact(task), + }, + ) + .unwrap(); + ProofClaim { + receipt_id: rec.receipt_id, + commit: rec.source_commit, + digest: rec.artifact_digest, + } + } + + pub fn complete(&mut self, task: &str) -> ProofClaim { + let claim = self.mint_completion(task); + let generation = self.generation(task); + self.ok(EventKind::CompletionVerified { + task: task.into(), + generation, + claim: claim.clone(), + }); + claim + } + + pub fn work_done(&mut self, task: &str) -> Effects { + let generation = self.generation(task); + self.ok(EventKind::WorkDone { + task: task.into(), + generation, + result_digest: format!("result-of-{task}"), + }) + } + + pub fn finalize(&mut self, task: &str) -> Effects { + let generation = self.generation(task); + self.ok(EventKind::Finalize { + task: task.into(), + generation, + }) + } + + /// Work done, finalize, then the M1 completion: the task becomes final + /// for its consumers. + pub fn finish(&mut self, task: &str) -> Effects { + self.work_done(task); + self.finalize(task); + let generation = self.generation(task); + let claim = self.mint_completion(task); + self.ok(EventKind::CompletionVerified { + task: task.into(), + generation, + claim, + }) + } +} diff --git a/crates/spark-harness/tests/provisional_guards.rs b/crates/spark-harness/tests/provisional_guards.rs new file mode 100644 index 00000000..4fedba0a --- /dev/null +++ b/crates/spark-harness/tests/provisional_guards.rs @@ -0,0 +1,353 @@ +//! Headstart M2 (#535): one test per guard that a deletion mutation must +//! break, plus bounded duplicate memory and reserved audit ids. + +mod common; + +use common::{enabled, H}; +use serde_json::json; +use spark_harness::completion::CompletionError; +use spark_harness::execution::TaskState; +use spark_harness::readiness::{ + verify_interface, InterfaceSubmission, OperationClass, ReadinessLevel, +}; +use spark_harness::scheduler::{ + Event, EventKind, Outcome, ProvisionalConfig, Revocation, SchedError, RESERVED_ID_PREFIX, +}; + +fn remove_receipt(h: &H, receipt_id: &str) { + std::fs::remove_file( + h.engine + .completion_store + .join("receipts") + .join(format!("{receipt_id}.json")), + ) + .unwrap(); +} + +#[test] +fn heartbeat_after_lease_expiry_is_refused() { + let mut h = H::new(enabled()); + h.register("a", 1, &[]); + h.advance(1_000); + // No Tick has run yet, so a is still Provisional, but its lease is gone. + let r = h.send(EventKind::Heartbeat { + task: "a".into(), + generation: h.generation("a"), + beat: 1, + }); + assert!(matches!(r, Err(SchedError::LeaseExpired(_))), "{r:?}"); + assert_eq!(h.sched.state("a"), Some(TaskState::Provisional)); + let fx = h.ok(EventKind::Tick); + assert_eq!(fx.aborted, vec!["a"]); +} + +#[test] +fn finalize_rechecks_the_whole_ancestor_chain() { + 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.work_done("c"); + h.finish("a"); + h.finish("b"); + assert!(h.sched.may_finalize("c").is_ok()); + // Only the grandparent's completion disappears; b's own proof is fine. + let a = h.sched.task("a").unwrap().completion.clone().unwrap(); + remove_receipt(&h, &a.receipt_id); + assert!(h.sched.may_finalize("b").is_err()); + let r = h.sched.may_finalize("c"); + assert!( + matches!(r, Err(SchedError::Proof { ref task, .. }) if task == "a"), + "{r:?}" + ); + assert!(h + .send(EventKind::Finalize { + task: "c".into(), + generation: h.generation("c") + }) + .is_err()); + assert_eq!(h.sched.state("c"), Some(TaskState::AwaitingFinalProof)); +} + +#[test] +fn proofs_are_accepted_only_for_active_tasks() { + let mut h = H::new(enabled()); + h.register("p", 1, &[]); + h.register("b", 1, &["p"]); + assert_eq!(h.sched.state("b"), Some(TaskState::Blocked)); + // A valid receipt for b exists, but b has not started. + let claim = h.mint_interface("b", 1); + let r = h.send(EventKind::InterfacePublished { + task: "b".into(), + generation: 1, + claim, + }); + assert!(matches!(r, Err(SchedError::WrongState { .. })), "{r:?}"); + assert!(h.sched.task("b").unwrap().interface.is_none()); +} + +#[test] +fn failed_final_upgrade_falls_back_to_the_interface_level() { + let mut h = H::new(enabled()); + h.register("a", 1, &[]); + h.register("b", 1, &["a"]); + h.publish("a", 1); + h.finish("a"); + // b was bound at the interface level; a is final now, so it upgrades. + assert!(h.sched.may_start("b", OperationClass::Commit).is_ok()); + let a = h.sched.task("a").unwrap().completion.clone().unwrap(); + remove_receipt(&h, &a.receipt_id); + // The interface still verifies: reversible work may go on... + let r = h + .sched + .may_start("b", OperationClass::ReadOnlyAnalysis) + .unwrap(); + assert_eq!(r[0].level(), ReadinessLevel::InterfaceVerified); + // ...but nothing irreversible. + assert!(matches!( + h.sched.may_start("b", OperationClass::Commit), + Err(SchedError::NotPermitted { .. }) + )); +} + +#[test] +fn reserved_ids_and_audit_events_cannot_be_delivered() { + let mut h = H::new(enabled()); + h.register("a", 1, &[]); + let r = h.sched.deliver(Event { + id: format!("{RESERVED_ID_PREFIX}audit-3"), + kind: EventKind::Tick, + }); + assert!(matches!(r, Err(SchedError::InvalidEvent(_))), "{r:?}"); + let r = h.send(EventKind::AuditRevoke { + revocations: vec![Revocation { + task: "a".into(), + reason: "forged".into(), + }], + }); + assert!(matches!(r, Err(SchedError::InvalidEvent(_))), "{r:?}"); + assert_eq!(h.sched.state("a"), Some(TaskState::Provisional)); + // A caller id that looks like an old audit id does not block the audit. + let (claim, _) = h.publish("a", 1); + h.sched + .deliver(Event { + id: "audit-4-a".into(), + kind: EventKind::Tick, + }) + .unwrap(); + remove_receipt(&h, &claim.receipt_id); + assert_eq!(h.sched.audit().unwrap(), vec!["a"]); +} + +#[test] +fn duplicate_memory_is_bounded() { + let mut h = H::new(enabled()); + h.register("a", 1, &[]); + let (claim, _) = h.publish("a", 1); + let publish = Event { + id: "pub-a-1".into(), + kind: EventKind::InterfacePublished { + task: "a".into(), + generation: 1, + claim, + }, + }; + // Same claim again under a new id: no change, so it applies cleanly. + assert!(matches!( + h.sched.deliver(publish.clone()), + Ok(Outcome::Applied(_)) + )); + assert_eq!(h.sched.deliver(publish.clone()), Ok(Outcome::Duplicate)); + let bump = Event { + id: "gen-a-2".into(), + kind: EventKind::NewGeneration { + task: "a".into(), + generation: 2, + }, + }; + h.sched.deliver(bump.clone()).unwrap(); + assert_eq!(h.sched.deliver(bump), Ok(Outcome::Duplicate)); + // The generation-1 bucket is gone: the old event is refused as stale, + // and either way it changes nothing. + let before = h.sched.snapshot(); + assert!(matches!( + h.sched.deliver(publish), + Err(SchedError::StaleGeneration { .. }) + )); + assert_eq!(h.sched.snapshot(), before); + // Heartbeats live in a window of `dedup_window` ids, however many come. + let first = Event { + id: "beat-1".into(), + kind: EventKind::Heartbeat { + task: "a".into(), + generation: 2, + beat: 1, + }, + }; + h.sched.deliver(first.clone()).unwrap(); + for beat in 2..=500 { + h.ok(EventKind::Heartbeat { + task: "a".into(), + generation: 2, + beat, + }); + } + let window = enabled().dedup_window; + assert!( + h.sched.remembered_event_ids() <= window + 2, + "{} ids remembered", + h.sched.remembered_event_ids() + ); + // The first beat left the window long ago; redelivered, it is refused + // by its beat number and the lease is not renewed. + let before = h.sched.snapshot(); + let r = h.sched.deliver(first); + assert!(matches!(r, Err(SchedError::StaleHeartbeat { .. })), "{r:?}"); + assert_eq!(h.sched.snapshot(), before); +} + +/// Inspector reproduction: with a tiny window, a Cancel redelivered after +/// the task was retried and the window rolled over must not abort again. +#[test] +fn cancel_redelivered_after_retry_and_window_rollover_is_refused() { + let mut h = H::new(ProvisionalConfig { + dedup_window: 4, + ..enabled() + }); + h.register("a", 1, &[]); + h.register("b", 1, &["a"]); + let cancel = Event { + id: "cancel-a".into(), + kind: EventKind::Cancel { + task: "a".into(), + generation: 1, + }, + }; + let fx = match h.sched.deliver(cancel.clone()) { + Ok(Outcome::Applied(fx)) => fx, + other => panic!("{other:?}"), + }; + assert_eq!(fx.aborted, vec!["a", "b"]); + for t in ["a", "b"] { + h.ok(EventKind::Retry { + task: t.into(), + generation: 1, + }); + } + for _ in 0..6 { + h.ok(EventKind::Tick); + } + assert_eq!(h.sched.state("a"), Some(TaskState::Provisional)); + let before = h.sched.snapshot(); + let r = h.sched.deliver(cancel); + assert!( + matches!(r, Err(SchedError::StaleGeneration { .. })), + "{r:?}" + ); + assert_eq!(h.sched.snapshot(), before); + assert_eq!(h.sched.state("a"), Some(TaskState::Provisional)); + assert_eq!(h.sched.state("b"), Some(TaskState::Blocked)); +} + +/// A late Retry must not undo a later Cancel of the retried generation. +#[test] +fn retry_redelivered_after_a_second_cancel_is_refused() { + let mut h = H::new(enabled()); + h.register("a", 1, &[]); + h.ok(EventKind::Cancel { + task: "a".into(), + generation: 1, + }); + let retry = Event { + id: "retry-a".into(), + kind: EventKind::Retry { + task: "a".into(), + generation: 1, + }, + }; + h.sched.deliver(retry.clone()).unwrap(); + h.ok(EventKind::Cancel { + task: "a".into(), + generation: 2, + }); + assert_eq!(h.sched.state("a"), Some(TaskState::Aborted)); + let r = h.sched.deliver(retry); + assert!( + matches!(r, Err(SchedError::StaleGeneration { .. })), + "{r:?}" + ); + assert_eq!(h.sched.state("a"), Some(TaskState::Aborted)); + assert_eq!(h.generation("a"), 2); +} + +/// Late Revoke and Finalize redeliveries must not act on a newer generation. +#[test] +fn revoke_and_finalize_redelivered_after_rerun_are_refused() { + let mut h = H::new(enabled()); + h.register("a", 1, &[]); + h.register("b", 1, &["a"]); + h.publish("a", 1); + h.finish("a"); + h.work_done("b"); + let finalize = Event { + id: "fin-b".into(), + kind: EventKind::Finalize { + task: "b".into(), + generation: 1, + }, + }; + h.sched.deliver(finalize.clone()).unwrap(); + let revoke = Event { + id: "rv-b".into(), + kind: EventKind::Revoke { + task: "b".into(), + generation: 1, + reason: "operator".into(), + }, + }; + h.sched.deliver(revoke.clone()).unwrap(); + // b re-runs at generation 2 against the final a. + assert_eq!(h.sched.state("b"), Some(TaskState::Provisional)); + let r = h.sched.deliver(revoke); + assert!( + matches!(r, Err(SchedError::StaleGeneration { .. })), + "{r:?}" + ); + assert_eq!(h.sched.state("b"), Some(TaskState::Provisional)); + h.work_done("b"); + let r = h.sched.deliver(finalize); + assert!( + matches!(r, Err(SchedError::StaleGeneration { .. })), + "{r:?}" + ); + assert_eq!(h.sched.state("b"), Some(TaskState::AwaitingFinalProof)); + assert_eq!(h.generation("b"), 2); +} + +#[test] +fn interface_republished_at_a_new_commit_retires_the_old_receipt() { + let mut h = H::new(enabled()); + h.register("a", 1, &[]); + let old = h.mint_interface("a", 1); + // Same generation and interface, new commit: a new receipt replaces it. + let new = h + .engine + .publish_interface(&InterfaceSubmission { + task_id: "a".into(), + generation: 1, + source_commit: "2222222222222222222222222222222222222222".into(), + interface: json!({ "task": "a", "api_version": 1 }), + }) + .unwrap() + .claim(); + assert_eq!(old.digest, new.digest); + assert_ne!(old.receipt_id, new.receipt_id); + let store = &h.engine.completion_store; + assert!(verify_interface(store, "a", 1, &new).is_ok()); + assert!(matches!( + verify_interface(store, "a", 1, &old), + Err(CompletionError::NotCurrentCompletion(_)) + )); +} diff --git a/crates/spark-harness/tests/provisional_journal.rs b/crates/spark-harness/tests/provisional_journal.rs new file mode 100644 index 00000000..cb48a985 --- /dev/null +++ b/crates/spark-harness/tests/provisional_journal.rs @@ -0,0 +1,260 @@ +//! Headstart M2 (#535): the scheduler journal survives restarts, ignores a +//! torn final line, refuses corruption, and replay never creates a +//! committable task without re-verification. + +mod common; + +use common::{enabled, H}; +use spark_harness::execution::TaskState; +use spark_harness::scheduler::{EventKind, ProvisionalConfig, SchedError, Scheduler}; +use std::fs::{self, OpenOptions}; +use std::io::Write; + +fn scenario(h: &mut H) { + h.register("a", 1, &[]); + h.register("b", 1, &["a"]); + h.register("c", 1, &["b"]); + h.publish("a", 1); + h.publish("b", 1); + h.advance(40); + h.work_done("c"); + h.publish("a", 2); // interface change: b and c revoked, re-dispatched + h.publish("b", 1); + h.finish("a"); +} + +#[test] +fn replay_reproduces_state_and_trace_exactly() { + let mut h = H::journaled(enabled()); + scenario(&mut h); + let snap = h.sched.snapshot(); + let trace = h.sched.timing_trace(); + // Move the clock: replay must use journaled times, not the clock. + h.advance(500); + assert_eq!(h.reopen(enabled()).unwrap(), (0, vec![])); + assert_eq!(h.sched.snapshot(), snap); + assert_eq!(h.sched.timing_trace(), trace); + h.sched.check_invariants().unwrap(); + // The replayed scheduler keeps working and keeps journaling. + h.work_done("b"); + h.finalize("b"); + let snap2 = h.sched.snapshot(); + h.reopen(enabled()).unwrap(); + assert_eq!(h.sched.snapshot(), snap2); + assert_eq!(h.sched.state("b"), Some(TaskState::Committable)); +} + +#[test] +fn torn_last_line_is_ignored_and_truncated() { + let mut h = H::journaled(enabled()); + scenario(&mut h); + let snap = h.sched.snapshot(); + let path = h.fx.journal(); + let before = fs::read(&path).unwrap(); + // Simulate a crash mid-append of the next event. + let torn = br#"{"seq":999,"id":"ev-torn","at":1,"kind":{"type":"fin"#; + OpenOptions::new() + .append(true) + .open(&path) + .unwrap() + .write_all(torn) + .unwrap(); + assert_eq!(h.reopen(enabled()).unwrap().0, torn.len()); + assert_eq!(h.sched.snapshot(), snap); + assert_eq!(fs::read(&path).unwrap(), before, "torn tail truncated"); + // Next append starts on a clean line and replays. + h.work_done("b"); + let snap2 = h.sched.snapshot(); + assert_eq!(h.reopen(enabled()).unwrap().0, 0); + assert_eq!(h.sched.snapshot(), snap2); +} + +#[test] +fn version_1_journal_is_refused() { + let mut h = H::journaled(enabled()); + scenario(&mut h); + let path = h.fx.journal(); + let text = fs::read_to_string(&path).unwrap(); + assert!(text.lines().next().unwrap().contains("\"version\":2")); + let old = text.replacen("\"version\":2", "\"version\":1", 1); + fs::write(&path, &old).unwrap(); + let r = h.reopen(enabled()); + assert!( + matches!(r, Err(SchedError::Journal(ref m)) if m.contains("header mismatch")), + "{r:?}" + ); + assert_eq!(fs::read_to_string(&path).unwrap(), old); +} + +#[test] +fn refused_journal_is_not_truncated() { + let mut h = H::journaled(enabled()); + scenario(&mut h); + let path = h.fx.journal(); + OpenOptions::new() + .append(true) + .open(&path) + .unwrap() + .write_all(br#"{"seq":999,"id":"ev-torn""#) + .unwrap(); + let before = fs::read(&path).unwrap(); + let other = ProvisionalConfig { + lease_ttl: 7, + ..enabled() + }; + assert!(matches!(h.reopen(other), Err(SchedError::Journal(_)))); + assert_eq!( + fs::read(&path).unwrap(), + before, + "refused journal untouched" + ); +} + +#[test] +fn restart_rebases_the_clock_so_dead_leases_expire() { + let mut h = H::journaled(enabled()); + h.advance(1_000_000); // the old process ran for a long time + h.register("a", 2, &[]); + assert_eq!(h.sched.state("a"), Some(TaskState::Provisional)); + let lease_ends = h.sched.task("a").unwrap().lease_expires_at.unwrap(); + // The worker dies with the process. The new process's clock starts at 0. + h.restart(enabled()).unwrap(); + assert_eq!(h.sched.permits_in_use().cpu_in_use, 2); + let last = lease_ends - enabled().lease_ttl; + h.advance(enabled().lease_ttl - 11); + let fx = h.ok(EventKind::Tick); // at lease end - 1 + assert!(fx.aborted.is_empty(), "{fx:?}"); + let fx = h.ok(EventKind::Tick); + assert_eq!(fx.aborted, vec!["a"]); + assert_eq!(h.sched.permits_in_use().running, 0); + assert!(h.sched.timing_trace()["as_of"].as_u64().unwrap() > last); +} + +#[test] +fn forged_finalize_in_the_journal_fails_replay() { + let mut h = H::journaled(enabled()); + h.register("a", 1, &[]); + h.register("b", 1, &["a"]); + h.publish("a", 1); + h.work_done("b"); + // a is not final, so no Finalize for b could have been journaled. + let path = h.fx.journal(); + let text = fs::read_to_string(&path).unwrap(); + let last: serde_json::Value = serde_json::from_str(text.lines().last().unwrap()).unwrap(); + let forged = serde_json::json!({ + "seq": last["seq"].as_u64().unwrap() + 1, + "id": "forged", + "at": last["at"], + "kind": { "type": "finalize", "task": "b", "generation": 1 }, + }); + let mut f = OpenOptions::new().append(true).open(&path).unwrap(); + writeln!(f, "{forged}").unwrap(); + drop(f); + let r = h.reopen(enabled()); + assert!(matches!(r, Err(SchedError::Journal(_))), "{r:?}"); +} + +#[test] +fn corrupt_complete_line_fails_closed() { + let mut h = H::journaled(enabled()); + scenario(&mut h); + let path = h.fx.journal(); + let text = fs::read_to_string(&path).unwrap(); + let mut lines: Vec<&str> = text.lines().collect(); + lines[3] = "{\"not\":\"an event\"}"; + fs::write(&path, format!("{}\n", lines.join("\n"))).unwrap(); + let r = h.reopen(enabled()); + assert!(matches!(r, Err(SchedError::Journal(_))), "{r:?}"); +} + +#[test] +fn reordered_or_duplicated_lines_fail_replay() { + let mut h = H::journaled(enabled()); + scenario(&mut h); + let path = h.fx.journal(); + let text = fs::read_to_string(&path).unwrap(); + let mut lines: Vec<&str> = text.lines().collect(); + let dup = lines[2]; + lines.insert(3, dup); + fs::write(&path, format!("{}\n", lines.join("\n"))).unwrap(); + let r = h.reopen(enabled()); + assert!(matches!(r, Err(SchedError::Journal(_))), "{r:?}"); +} + +#[test] +fn config_mismatch_is_refused() { + let mut h = H::journaled(enabled()); + scenario(&mut h); + let other = ProvisionalConfig { + enabled: false, + ..enabled() + }; + let r = h.reopen(other); + assert!(matches!(r, Err(SchedError::Journal(_))), "{r:?}"); +} + +#[test] +fn journal_has_a_single_writer() { + let h = H::journaled(enabled()); + let second = Scheduler::open( + enabled(), + &h.engine.completion_store, + &h.fx.journal(), + common::clock(&h.ticks), + ); + assert!(matches!(second, Err(SchedError::Journal(_)))); +} + +#[test] +fn replay_never_turns_provisional_work_committable() { + let mut h = H::journaled(enabled()); + h.register("a", 1, &[]); + h.register("b", 1, &["a"]); + h.publish("a", 1); + h.work_done("b"); + // Crash before a is final: b replays as AwaitingFinalProof, not more. + h.reopen(enabled()).unwrap(); + assert_eq!(h.sched.state("b"), Some(TaskState::AwaitingFinalProof)); + assert!(h.sched.may_finalize("b").is_err()); + assert!(h + .send(EventKind::Finalize { + task: "b".into(), + generation: h.generation("b") + }) + .is_err()); + assert!(h.sched.audit().unwrap().is_empty()); +} + +#[test] +fn replayed_committable_task_is_reverified_against_the_store() { + let mut h = H::journaled(enabled()); + h.register("a", 1, &[]); + h.register("b", 1, &["a"]); + h.publish("a", 1); + h.work_done("b"); + h.finish("a"); + h.finalize("b"); + assert!(h.sched.may_finalize("b").is_ok()); + let a_completion = h.sched.task("a").unwrap().completion.clone().unwrap(); + // The store loses a's completion receipt while the scheduler is down. + fs::remove_file( + h.engine + .completion_store + .join("receipts") + .join(format!("{}.json", a_completion.receipt_id)), + ) + .unwrap(); + // Replay is pure, so a and b come back Committable; `open` hands out + // only an unaudited handle, and its audit revokes both before any event + // or dispatch can run on them. + let (_, revoked) = h.reopen(enabled()).unwrap(); + assert_eq!(revoked, vec!["a", "b"]); + assert_eq!(h.sched.state("b"), Some(TaskState::Blocked)); + // A consumer registered after the restart is not dispatched on a. + h.register("c", 1, &["a"]); + assert_eq!(h.sched.state("c"), Some(TaskState::Blocked)); + assert!(h.sched.may_finalize("b").is_err()); + // The revocation itself is journaled. + assert_eq!(h.reopen(enabled()).unwrap().1, Vec::::new()); + assert_eq!(h.sched.state("b"), Some(TaskState::Blocked)); +} diff --git a/crates/spark-harness/tests/provisional_scheduler.rs b/crates/spark-harness/tests/provisional_scheduler.rs new file mode 100644 index 00000000..7ab4c86c --- /dev/null +++ b/crates/spark-harness/tests/provisional_scheduler.rs @@ -0,0 +1,685 @@ +//! Headstart M2 (#535): provisional scheduling on verified interfaces, +//! final completion only on verified producer completions. + +mod common; + +use common::{enabled, req, COMMIT, H}; +use serde_json::json; +use spark_harness::completion::CompletionError; +use spark_harness::dependency::GraphError; +use spark_harness::execution::TaskState; +use spark_harness::readiness::{ + verify_interface, InterfaceSubmission, OperationClass, ProofClaim, ReadinessLevel, +}; +use spark_harness::scheduler::{ + BindingLevel, Event, EventKind, Outcome, ProvisionalConfig, ResourceLimits, SchedError, +}; + +const IRREVERSIBLE: [OperationClass; 4] = [ + OperationClass::Commit, + OperationClass::Publish, + OperationClass::PersistentMutation, + OperationClass::ExternalEffect, +]; + +#[test] +fn finalize_rechecks_the_interface_the_consumer_prepared_against() { + let mut h = H::new(enabled()); + two_task(&mut h); + h.publish("a", 1); + h.work_done("b"); + h.finish("a"); + assert!(h.sched.may_finalize("b").is_ok()); + // a's interface changes in the store; the event has not arrived yet. + h.mint_interface("a", 2); + assert!(matches!( + h.sched.may_finalize("b"), + Err(SchedError::Proof { .. }) + )); + assert!(h + .send(EventKind::Finalize { + task: "b".into(), + generation: h.generation("b") + }) + .is_err()); + assert_eq!(state(&h, "b"), TaskState::AwaitingFinalProof); +} + +fn state(h: &H, t: &str) -> TaskState { + h.sched.state(t).unwrap() +} + +fn two_task(h: &mut H) { + h.register("a", 1, &[]); + h.register("b", 1, &["a"]); +} + +fn chain(h: &mut H) { + h.register("a", 1, &[]); + h.register("b", 1, &["a"]); + h.register("c", 1, &["b"]); +} + +#[test] +fn disabled_is_the_default() { + assert!(!ProvisionalConfig::default().enabled); +} + +#[test] +fn two_task_dag_overlaps_preparation_then_finalizes_on_final_proof() { + let mut h = H::new(enabled()); + two_task(&mut h); + assert_eq!(state(&h, "a"), TaskState::Provisional); + assert_eq!(state(&h, "b"), TaskState::Blocked); + assert!(matches!( + h.sched.may_start("b", OperationClass::ReadOnlyAnalysis), + Err(SchedError::WrongState { .. }) + )); + + let (_, fx) = h.publish("a", 1); + assert_eq!(fx.dispatched, vec!["b".to_string()]); + assert_eq!(state(&h, "b"), TaskState::Provisional); + assert_eq!( + h.sched.task("b").unwrap().bindings["a"].level, + BindingLevel::Interface + ); + let grant = h + .sched + .may_start("b", OperationClass::SandboxedCheck) + .unwrap(); + assert_eq!(grant[0].level(), ReadinessLevel::InterfaceVerified); + assert_eq!(grant[0].producer_task(), "a"); + assert_eq!(grant[0].producer_generation(), 1); + + h.advance(100); + h.work_done("b"); + assert_eq!(state(&h, "b"), TaskState::AwaitingFinalProof); + assert!(matches!( + h.sched.may_finalize("b"), + Err(SchedError::ProducerNotFinal { .. }) + )); + assert!(matches!( + h.send(EventKind::Finalize { + task: "b".into(), + generation: h.generation("b") + }), + Err(SchedError::ProducerNotFinal { .. }) + )); + + h.advance(50); + h.finish("a"); + let fin = h.sched.may_finalize("b").unwrap(); + assert_eq!(fin[0].level(), ReadinessLevel::FinalVerified); + h.finalize("b"); + assert_eq!(state(&h, "b"), TaskState::Committable); + + let trace = h.sched.timing_trace(); + println!( + "M2_TIMING_TRACE {}", + serde_json::to_string_pretty(&trace).unwrap() + ); + let b = &trace["tasks"][1]; + assert_eq!(b["task"], "b"); + assert!(b["provisional"].as_u64().unwrap() > 0); + assert!(b["blocked"].as_u64().unwrap() > 0); + // b started while a was still provisional: overlap. + let a_done = h.sched.task("a").unwrap().timing.committable_at.unwrap(); + assert!(h.sched.task("b").unwrap().timing.first_dispatch_at.unwrap() < a_done); +} + +#[test] +fn three_task_chain_prepares_concurrently_and_finalizes_in_order() { + let mut h = H::new(enabled()); + chain(&mut h); + h.publish("a", 1); + h.publish("b", 1); + for t in ["a", "b", "c"] { + assert_eq!(state(&h, t), TaskState::Provisional, "{t}"); + } + assert_eq!(h.sched.permits_in_use().running, 3); + for op in IRREVERSIBLE { + assert!(h.sched.may_start("c", op).is_err()); + } + // b finished and completed but a is not final: b is not final for c. + h.work_done("b"); + assert!(h + .send(EventKind::Finalize { + task: "b".into(), + generation: h.generation("b") + }) + .is_err()); + h.finish("a"); + h.finalize("b"); + h.complete("b"); + // c's interface binding is upgraded to final once both are final. + let grant = h.sched.may_start("c", OperationClass::Publish).unwrap(); + assert_eq!(grant[0].level(), ReadinessLevel::FinalVerified); + h.work_done("c"); + h.finalize("c"); + assert_eq!(state(&h, "c"), TaskState::Committable); +} + +#[test] +fn no_irreversible_op_from_interface_verified_alone() { + let mut h = H::new(enabled()); + two_task(&mut h); + h.publish("a", 1); + for op in IRREVERSIBLE { + match h.sched.may_start("b", op) { + Err(SchedError::NotPermitted { level, .. }) => { + assert_eq!(level, ReadinessLevel::InterfaceVerified) + } + other => panic!("{op:?} must be refused, got {other:?}"), + } + assert!(h.sched.may_start_named("b", op.as_str()).is_err()); + } + // Finalized without an M1 completion is still not final. + h.work_done("a"); + h.finalize("a"); + for op in IRREVERSIBLE { + assert!(h.sched.may_start("b", op).is_err()); + } + // Only the M1 completion makes it final. + h.complete("a"); + for op in IRREVERSIBLE { + assert!(h.sched.may_start("b", op).is_ok()); + } +} + +#[test] +fn unknown_operation_names_fail_closed() { + let mut h = H::new(enabled()); + two_task(&mut h); + h.publish("a", 1); + assert!(h.sched.may_start_named("b", "read_only_analysis").is_ok()); + for bad in [ + "deploy", + "Commit", + "READ_ONLY_ANALYSIS", + "", + "sandboxed-check", + ] { + assert!( + matches!( + h.sched.may_start_named("b", bad), + Err(SchedError::UnknownOperation(_)) + ), + "{bad:?}" + ); + } +} + +#[test] +fn disabled_flag_keeps_consumers_blocked_until_final() { + let mut h = H::new(ProvisionalConfig { + enabled: false, + ..enabled() + }); + two_task(&mut h); + h.publish("a", 1); + let b = h.sched.task("b").unwrap(); + assert_eq!(b.state, TaskState::Blocked); + assert!(!b.queued); + assert_eq!(h.sched.permits_in_use().running, 1); + h.work_done("a"); + h.finalize("a"); + assert_eq!(state(&h, "b"), TaskState::Blocked); + let generation = h.generation("a"); + let claim = h.mint_completion("a"); + let fx = h.ok(EventKind::CompletionVerified { + task: "a".into(), + generation, + claim, + }); + assert_eq!(fx.dispatched, vec!["b".to_string()]); + assert_eq!( + h.sched.task("b").unwrap().bindings["a"].level, + BindingLevel::Final + ); + assert!(h.sched.may_start("b", OperationClass::Commit).is_ok()); +} + +#[test] +fn cycles_and_missing_nodes_are_refused_without_change() { + let mut h = H::new(enabled()); + chain(&mut h); + let before = h.sched.snapshot(); + let r = h.send(EventKind::AddDependency { + producer: "c".into(), + consumer: "a".into(), + }); + assert!( + matches!(&r, Err(SchedError::Graph(GraphError::Cycle(p))) if p.len() == 4), + "{r:?}" + ); + let r = h.send(EventKind::AddDependency { + producer: "zz".into(), + consumer: "b".into(), + }); + assert!( + matches!(r, Err(SchedError::Graph(GraphError::MissingNode(_)))), + "{r:?}" + ); + let r = h.send(EventKind::RegisterTask { + task: "d".into(), + resources: req(1), + producers: vec!["a".into(), "nope".into()], + }); + assert!( + matches!(r, Err(SchedError::Graph(GraphError::MissingNode(_)))), + "{r:?}" + ); + assert_eq!(h.sched.snapshot(), before); + // A running consumer cannot gain a dependency; a blocked one can. + h.register("e", 1, &[]); + assert!(matches!( + h.send(EventKind::AddDependency { + producer: "b".into(), + consumer: "e".into(), + }), + Err(SchedError::WrongState { .. }) + )); + h.edge("e", "c"); + h.publish("a", 1); + h.publish("b", 1); + assert_eq!(state(&h, "c"), TaskState::Blocked, "c still waits for e"); + h.publish("e", 1); + assert_eq!(state(&h, "c"), TaskState::Provisional); +} + +#[test] +fn cancellation_propagates_to_descendants_and_frees_permits() { + let mut h = H::new(enabled()); + chain(&mut h); + h.register("d", 1, &[]); + h.publish("a", 1); + h.publish("b", 1); + let fx = h.ok(EventKind::Cancel { + task: "a".into(), + generation: h.generation("a"), + }); + assert_eq!(fx.aborted, vec!["a", "b", "c"]); + for t in ["a", "b", "c"] { + assert_eq!(state(&h, t), TaskState::Aborted); + } + assert_eq!(state(&h, "d"), TaskState::Provisional); + assert_eq!(h.sched.permits_in_use().running, 1); +} + +#[test] +fn stale_generations_are_rejected_and_cannot_finalize() { + let mut h = H::new(enabled()); + two_task(&mut h); + let (old_claim, _) = h.publish("a", 1); + h.work_done("b"); + let old_completion = h.mint_completion("a"); + let fx = h.ok(EventKind::NewGeneration { + task: "a".into(), + generation: 2, + }); + assert_eq!(fx.revoked, vec!["a", "b"]); + let b = h.sched.task("b").unwrap(); + assert_eq!(b.state, TaskState::Blocked); + assert_eq!(b.generation, 2); + assert!(b.provisional_result.is_none()); + for kind in [ + EventKind::InterfacePublished { + task: "a".into(), + generation: 1, + claim: old_claim.clone(), + }, + EventKind::CompletionVerified { + task: "a".into(), + generation: 1, + claim: old_completion.clone(), + }, + EventKind::NewGeneration { + task: "a".into(), + generation: 2, + }, + ] { + assert!( + matches!(h.send(kind), Err(SchedError::StaleGeneration { .. })), + "stale event accepted" + ); + } + // A generation-1 receipt claimed as generation 2 fails the binding. + let r = h.send(EventKind::InterfacePublished { + task: "a".into(), + generation: 2, + claim: old_claim, + }); + assert!(matches!(r, Err(SchedError::Proof { .. })), "{r:?}"); + let r = h.send(EventKind::WorkDone { + task: "b".into(), + generation: 1, + result_digest: "late".into(), + }); + assert!( + matches!(r, Err(SchedError::StaleGeneration { .. })), + "{r:?}" + ); + // The engine itself refuses a stale interface generation. + let mut stale = InterfaceSubmission { + task_id: "a".into(), + generation: 2, + source_commit: COMMIT.into(), + interface: json!({"v": 2}), + }; + h.engine.publish_interface(&stale).unwrap(); + stale.generation = 1; + assert!(matches!( + h.engine.publish_interface(&stale), + Err(CompletionError::StaleGeneration { .. }) + )); +} + +#[test] +fn producer_failure_revokes_descendants_and_discards_results() { + let mut h = H::new(enabled()); + chain(&mut h); + h.publish("a", 1); + h.publish("b", 1); + h.work_done("b"); + assert!(h.sched.task("b").unwrap().provisional_result.is_some()); + let fx = h.ok(EventKind::ProducerFailed { + task: "a".into(), + generation: 1, + reason: "build broke".into(), + }); + assert_eq!(fx.aborted, vec!["a"]); + assert_eq!(fx.revoked, vec!["b", "c"]); + for t in ["b", "c"] { + let e = h.sched.task(t).unwrap(); + assert_eq!(e.state, TaskState::Blocked); + assert!(e.provisional_result.is_none() && e.bindings.is_empty() && e.interface.is_none()); + assert_eq!(e.generation, 2); + } + assert_eq!(h.sched.permits_in_use().running, 0); +} + +#[test] +fn retry_after_failure_runs_to_committable() { + let mut h = H::new(enabled()); + two_task(&mut h); + h.publish("a", 1); + h.ok(EventKind::ProducerFailed { + task: "a".into(), + generation: 1, + reason: "flaky".into(), + }); + assert!(h + .send(EventKind::Retry { + task: "b".into(), + generation: h.generation("b") + }) + .is_err()); + let fx = h.ok(EventKind::Retry { + task: "a".into(), + generation: h.generation("a"), + }); + assert_eq!(fx.dispatched, vec!["a"]); + assert_eq!(h.generation("a"), 2); + h.publish("a", 1); + assert_eq!(state(&h, "b"), TaskState::Provisional); + assert_eq!(h.sched.task("b").unwrap().bindings["a"].generation, 2); + h.work_done("b"); + h.finish("a"); + h.finalize("b"); + assert_eq!(state(&h, "b"), TaskState::Committable); +} + +#[test] +fn interface_change_at_same_generation_revokes_and_rebinds() { + let mut h = H::new(enabled()); + two_task(&mut h); + let (v1, _) = h.publish("a", 1); + h.work_done("b"); + let (v2, fx) = h.publish("a", 2); + assert_ne!(v1, v2); + assert_eq!(fx.revoked, vec!["b"]); + assert_eq!(fx.dispatched, vec!["b"]); + let b = h.sched.task("b").unwrap(); + assert_eq!(b.bindings["a"].claim, v2); + assert!(b.provisional_result.is_none()); + assert_eq!((b.timing.revocations, b.timing.dispatches), (1, 2)); + let store = &h.engine.completion_store; + assert!(matches!( + verify_interface(store, "a", 1, &v1), + Err(CompletionError::NotCurrentCompletion(_)) + )); + // Republishing the same interface is idempotent: same receipt. + assert_eq!(h.mint_interface("a", 2), v2); +} + +#[test] +fn duplicate_event_delivery_is_idempotent() { + let mut h = H::new(enabled()); + let ev = Event { + id: "reg-a".into(), + kind: EventKind::RegisterTask { + task: "a".into(), + resources: req(1), + producers: vec![], + }, + }; + assert!(matches!( + h.sched.deliver(ev.clone()), + Ok(Outcome::Applied(_)) + )); + let before = h.sched.snapshot(); + assert_eq!(h.sched.deliver(ev), Ok(Outcome::Duplicate)); + assert_eq!(h.sched.snapshot(), before); + let conflict = Event { + id: "reg-a".into(), + kind: EventKind::RegisterTask { + task: "other".into(), + resources: req(1), + producers: vec![], + }, + }; + assert!(matches!( + h.sched.deliver(conflict), + Err(SchedError::EventIdConflict(_)) + )); + assert!(h.sched.task("other").is_none()); +} + +#[test] +fn forged_digest_missing_and_wrong_kind_proofs_are_refused() { + let mut h = H::new(enabled()); + two_task(&mut h); + let good = h.mint_interface("a", 1); + let completion = h.mint_completion("a"); + let forged_digest = ProofClaim { + digest: "0".repeat(64), + ..good.clone() + }; + let missing = ProofClaim { + receipt_id: "a".repeat(64), + ..good.clone() + }; + let wrong_commit = ProofClaim { + commit: "2".repeat(40), + ..good.clone() + }; + let before = h.sched.snapshot(); + for (claim, interface) in [ + (forged_digest, true), + (missing, true), + (wrong_commit, true), + (completion.clone(), true), + (good.clone(), false), + ] { + let kind = if interface { + EventKind::InterfacePublished { + task: "a".into(), + generation: 1, + claim, + } + } else { + EventKind::CompletionVerified { + task: "a".into(), + generation: 1, + claim, + } + }; + let r = h.send(kind); + assert!(matches!(r, Err(SchedError::Proof { .. })), "{r:?}"); + } + assert_eq!(h.sched.snapshot(), before); + assert_eq!(state(&h, "b"), TaskState::Blocked); + + // Receipts cannot be smuggled in through the submission. + let smuggled = json!({ + "task_id": "a", "generation": 1, "source_commit": COMMIT, + "interface": {"x": 1}, "receipt_id": good.receipt_id + }); + assert!(serde_json::from_value::(smuggled).is_err()); + let not_object = InterfaceSubmission { + task_id: "a".into(), + generation: 1, + source_commit: COMMIT.into(), + interface: json!("just a string"), + }; + assert!(matches!( + h.engine.publish_interface(¬_object), + Err(CompletionError::InvalidSubmission(_)) + )); +} + +#[test] +fn tampered_store_fails_gates_and_audit_revokes() { + let mut h = H::new(enabled()); + two_task(&mut h); + let (claim, _) = h.publish("a", 1); + assert!(h + .sched + .may_start("b", OperationClass::ReadOnlyAnalysis) + .is_ok()); + let path = h + .engine + .completion_store + .join("receipts") + .join(format!("{}.json", claim.receipt_id)); + let text = std::fs::read_to_string(&path).unwrap(); + std::fs::write(&path, text.replace("interface:shape", "interface:shapf")).unwrap(); + assert!(matches!( + h.sched.may_start("b", OperationClass::ReadOnlyAnalysis), + Err(SchedError::Proof { .. }) + )); + // The producer whose own claim fails is revoked, which cascades to b; + // a re-runs at a new generation, b waits for a new interface. + let revoked = h.sched.audit().unwrap(); + assert_eq!(revoked, vec!["a", "b"]); + assert_eq!(state(&h, "a"), TaskState::Provisional); + assert_eq!(h.generation("a"), 2); + assert_eq!(state(&h, "b"), TaskState::Blocked); + assert_eq!(h.sched.audit().unwrap(), Vec::::new()); + h.sched.check_invariants().unwrap(); +} + +#[test] +fn resource_budget_bounds_queue_and_permits() { + let mut h = H::new(ProvisionalConfig { + enabled: true, + queue_capacity: 1, + limits: ResourceLimits { + cpu_slots: 3, + memory_bytes: 1 << 30, + max_concurrency: 2, + }, + lease_ttl: 1_000, + dedup_window: 64, + }); + let r = h.send(EventKind::RegisterTask { + task: "huge".into(), + resources: req(4), + producers: vec![], + }); + assert!(matches!(r, Err(SchedError::ExceedsCapacity(_))), "{r:?}"); + for t in ["x", "y", "z"] { + h.register(t, 2, &[]); + } + assert_eq!(state(&h, "x"), TaskState::Provisional); + assert_eq!(h.sched.queue(), vec!["y"]); + let z = h.sched.task("z").unwrap(); + assert_eq!((z.state, z.queued), (TaskState::Blocked, false)); + assert_eq!(h.sched.permits_in_use().cpu_in_use, 2); + let fx = h.work_done("x"); + assert_eq!(fx.dispatched, vec!["y"]); + assert_eq!(h.sched.queue(), vec!["z"]); + h.work_done("y"); + assert_eq!(state(&h, "z"), TaskState::Provisional); + h.register("w", 1, &[]); + assert_eq!(h.sched.permits_in_use().cpu_in_use, 3); + // Concurrency bound: after z finishes, two 1-slot tasks would fit the + // CPU budget next to w, but only max_concurrency = 2 tasks run. + h.work_done("z"); + h.register("u", 1, &[]); + h.register("v", 1, &[]); + let pool = h.sched.permits_in_use(); + assert_eq!((pool.running, pool.cpu_in_use), (2, 2)); + assert_eq!(h.sched.queue(), vec!["v"]); + assert_eq!(state(&h, "v"), TaskState::Blocked); +} + +#[test] +fn blocked_tasks_hold_no_permits() { + let mut h = H::new(enabled()); + h.register("a", 3, &[]); + h.register("b", 3, &["a"]); + h.register("c", 3, &["a"]); + let pool = h.sched.permits_in_use(); + assert_eq!((pool.running, pool.cpu_in_use), (1, 3)); + h.publish("a", 1); + // b fits (6 of 8 slots); c would need 9 and waits in the queue. + assert_eq!(state(&h, "b"), TaskState::Provisional); + let c = h.sched.task("c").unwrap(); + assert_eq!((c.state, c.queued), (TaskState::Blocked, true)); + assert!(c.lease_expires_at.is_none()); + assert_eq!(h.sched.permits_in_use().cpu_in_use, 6); + // Revocation returns b to Blocked and frees its permits; c is then + // blocked too (a has no interface at its new generation). + h.ok(EventKind::NewGeneration { + task: "a".into(), + generation: 2, + }); + for t in ["b", "c"] { + assert_eq!(state(&h, t), TaskState::Blocked); + } + let pool = h.sched.permits_in_use(); + assert_eq!((pool.running, pool.cpu_in_use), (1, 3)); +} + +#[test] +fn leases_expire_into_abort_and_heartbeats_renew() { + let mut h = H::new(enabled()); + two_task(&mut h); + h.publish("a", 1); + h.advance(900); + h.ok(EventKind::Heartbeat { + task: "a".into(), + generation: h.generation("a"), + beat: 1, + }); + h.advance(900); + assert!(h.sched.may_start("a", OperationClass::Commit).is_ok()); + h.advance(200); + assert!(matches!( + h.sched.may_start("a", OperationClass::Commit), + Err(SchedError::LeaseExpired(_)) + )); + assert!(matches!( + h.send(EventKind::WorkDone { + task: "a".into(), + generation: 1, + result_digest: "late".into() + }), + Err(SchedError::LeaseExpired(_)) + )); + let fx = h.ok(EventKind::Tick); + assert_eq!(fx.aborted, vec!["a"]); + assert_eq!(fx.revoked, vec!["b"]); + assert_eq!(h.sched.permits_in_use().running, 0); +} ```