interplane.Get Omega
Read in your language

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

branch main Branches Tags History

aien-sovereign-core-mv / crates / spark-harness / src / scheduler / mod.rs

417 lines · 16231 bytes Raw Blame History
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! Provisional dependency scheduler (Headstart M2, issue #535).
17//!
18//! Lets a consumer task start reversible, sandboxed preparation as soon as
19//! its producers publish a harness-verified interface, while final
20//! completion waits for every producer's M1 verified completion. This is an
21//! engineering-workflow scheduler only; it does not touch inference
22//! scheduling, KV/prefill fences, aien-trace or World commit.
23//!
24//! Opt-in: [`ProvisionalConfig::enabled`] defaults to `false`. Disabled means
25//! no early start: a consumer stays `Blocked` until every producer is
26//! final-verified and `Committable`, which is plain sequential behavior. No
27//! existing spark-harness API or MCP tool uses this module.
28//!
29//! Model:
30//! - Tasks and producer -> consumer edges form a cycle-checked DAG
31//! (`dependency.rs`). Task states and the transition table live in
32//! `execution.rs`.
33//! - Everything is an [`Event`] with a caller-chosen id. Redelivering the
34//! same id with the same payload is a no-op ([`Outcome::Duplicate`]); the
35//! same id with a different payload is refused.
36//! - [`Scheduler::deliver`] runs the store checks for the event, applies it
37//! to a copy of the state, journals it, then swaps the copy in. A refused
38//! event changes nothing and is not journaled.
39//! - Producers have monotonic generations. Events for an older generation are
40//! refused as stale. A producer failure, a changed interface or completion
41//! at the same generation, a new generation, a lost lease or a revocation
42//! returns every active descendant to `Blocked` at a new generation and
43//! discards its provisional result.
44//! - A bounded ready queue feeds dispatch. Dispatch takes CPU, memory and
45//! concurrency permits all at once and grants a lease; only `Provisional`
46//! tasks hold permits.
47//!
48//! Persistence choice: an append-only JSON-lines journal (`journal.rs`) of
49//! accepted events, opened with [`Scheduler::open`]. Replay re-applies the
50//! events through the same pure state machine, using the times recorded in
51//! the journal, so it rebuilds the same state (and the same timing trace).
52//! Replay does not re-read the store, so `open` returns an [`Unaudited`]
53//! handle whose only method is `audit`: no event, dispatch or gate query
54//! can run on replayed state until every active task was re-verified
55//! against the store. After that every `may_start` and `may_finalize`
56//! still re-verifies at call time. A task becomes `Committable` only
57//! through a journaled `Finalize` event, which is journaled only after
58//! `may_finalize` passed, so replay cannot turn an unfinished provisional
59//! task into a committable one. The journal is trusted like the store
60//! itself (filesystem ownership); it is not signed.
61//!
62//! Time after a restart: a new process gets a new clock, so `open` rebases
63//! it onto the last journaled time (`now = last_at + clock() - clock_at_open`).
64//! Leases of workers that died with the old process therefore expire at
65//! most `lease_ttl` ticks after the restart. The downtime itself is not
66//! counted.
67//!
68//! Cost per event: `deliver` applies the event to a copy of the state so a
69//! refused event changes nothing. The copy is O(tasks + edges +
70//! `dedup_window`), the same order as the dispatch scan every event already
71//! does; `deliver_cost_is_small_next_to_the_journal_fsync` (ignored test)
72//! measures it. Journal compaction (a snapshot header so replay does not
73//! start from the first event) is a follow-up; until then the journal and
74//! replay time grow with the event count.
75
76pub mod core;
77mod dedup;
78pub mod error;
79mod gates;
80pub mod permits;
81pub mod timing;
82#[cfg(test)]
83mod unit_tests;
84
85pub use self::core::{
86 ApprovalBinding, Binding, BindingLevel, CommitInputs, CommitResult, Effects, Event, EventKind,
87 JournalEntry, Revocation, TaskEntry, MAX_APPROVAL_BINDINGS_PER_TASK, MAX_APPROVAL_KEY_LEN,
88};
89pub use self::error::SchedError;
90pub use self::permits::{PermitPool, ResourceLimits, ResourceRequest};
91
92use self::core::{payload_digest, Core};
93use crate::completion::check_identifier;
94use crate::execution::TaskState;
95use crate::journal::Journal;
96use serde::{Deserialize, Serialize};
97use serde_json::{json, Value};
98use std::path::{Path, PathBuf};
99
100/// Monotonic clock in ticks. Injected so tests are deterministic.
101pub type Clock = Box<dyn Fn() -> u64 + Send + Sync>;
102
103/// Nanoseconds since this clock was created, from `std::time::Instant`.
104/// A new process starts a new base; [`Scheduler::open`] rebases it onto
105/// the last journaled time (see the module docs).
106pub fn monotonic_clock() -> Clock {
107 let start = std::time::Instant::now();
108 Box::new(move || u64::try_from(start.elapsed().as_nanos()).unwrap_or(u64::MAX))
109}
110
111pub const JOURNAL_FORMAT: &str = "spark-harness-provisional-journal";
112/// Version 2: task-directed events carry a generation and heartbeats a
113/// beat number. A version 1 journal
114/// fails the header check on open and is never replayed.
115pub const JOURNAL_VERSION: u64 = 2;
116pub const TRACE_SCHEMA: &str = "spark-harness-provisional-trace";
117/// Event ids starting with this are reserved for events the scheduler
118/// emits itself (the audit). [`Scheduler::deliver`] refuses them.
119pub const RESERVED_ID_PREFIX: &str = "spark-harness:";
120
121#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
122#[serde(deny_unknown_fields)]
123pub struct ProvisionalConfig {
124 /// Allow early start on interface-verified producers. Default `false`.
125 pub enabled: bool,
126 /// Maximum ready-queue length (at least 1).
127 pub queue_capacity: usize,
128 pub limits: ResourceLimits,
129 /// Lease length in clock ticks (at least 1).
130 pub lease_ttl: u64,
131 /// How many generation-free event ids are remembered for duplicate
132 /// detection (at least 1). See `dedup.rs`.
133 pub dedup_window: usize,
134}
135
136impl Default for ProvisionalConfig {
137 fn default() -> Self {
138 ProvisionalConfig {
139 enabled: false,
140 queue_capacity: 64,
141 limits: ResourceLimits::default(),
142 lease_ttl: 300_000_000_000,
143 dedup_window: 4096,
144 }
145 }
146}
147
148impl ProvisionalConfig {
149 fn validate(&self) -> Result<(), SchedError> {
150 if self.queue_capacity == 0
151 || self.lease_ttl == 0
152 || self.limits.max_concurrency == 0
153 || self.dedup_window == 0
154 {
155 return Err(SchedError::InvalidEvent(
156 "config needs queue_capacity, lease_ttl, max_concurrency and dedup_window of at least 1"
157 .to_string(),
158 ));
159 }
160 Ok(())
161 }
162}
163
164#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
165pub enum Outcome {
166 Applied(Effects),
167 /// The event id was already applied with the same payload.
168 Duplicate,
169}
170
171/// What [`Scheduler::open`] found in the journal.
172#[derive(Debug, Clone, Copy, PartialEq, Eq)]
173pub struct ReplayReport {
174 pub entries: usize,
175 pub torn_bytes: usize,
176}
177
178pub struct Scheduler {
179 cfg: ProvisionalConfig,
180 store: PathBuf,
181 clock: Clock,
182 /// `now = clock_base + clock() - clock_origin` (see the module docs).
183 clock_base: u64,
184 clock_origin: u64,
185 core: Core,
186 journal: Option<Journal>,
187}
188
189/// A replayed scheduler that has not been checked against the store yet.
190/// Its only method is [`Unaudited::audit`].
191#[must_use = "a replayed scheduler is usable only after audit()"]
192pub struct Unaudited {
193 sched: Scheduler,
194}
195
196impl Unaudited {
197 /// Mark every replayed `Committing` task `CommitUncertain` (its outcome
198 /// was lost; it is never run again), re-verify every replayed active
199 /// task against the store, revoke the ones that fail, and hand out the
200 /// scheduler.
201 pub fn audit(mut self) -> Result<(Scheduler, Vec<String>), SchedError> {
202 self.sched.settle_interrupted_commits()?;
203 let revoked = self.sched.audit()?;
204 Ok((self.sched, revoked))
205 }
206}
207
208impl Scheduler {
209 /// In-memory scheduler (no journal). `store` is the harness store that
210 /// holds interface and completion receipts (`HarnessEngine::completion_store`).
211 pub fn new(cfg: ProvisionalConfig, store: &Path, clock: Clock) -> Result<Self, SchedError> {
212 cfg.validate()?;
213 Ok(Scheduler {
214 cfg,
215 store: store.to_path_buf(),
216 clock,
217 clock_base: 0,
218 clock_origin: 0,
219 core: Core::default(),
220 journal: None,
221 })
222 }
223
224 /// Journaled scheduler: create `journal` or replay it. The journal's
225 /// header must carry the same config, because dispatch depends on it.
226 /// The replayed state must pass [`Unaudited::audit`] before use.
227 pub fn open(
228 cfg: ProvisionalConfig,
229 store: &Path,
230 journal: &Path,
231 clock: Clock,
232 ) -> Result<(Unaudited, ReplayReport), SchedError> {
233 let mut s = Scheduler::new(cfg, store, clock)?;
234 let header =
235 json!({ "format": JOURNAL_FORMAT, "version": JOURNAL_VERSION, "config": s.cfg });
236 let opened =
237 Journal::open::<JournalEntry>(journal, &header).map_err(SchedError::Journal)?;
238 for entry in &opened.entries {
239 s.core.apply(&s.cfg, entry).map_err(|e| {
240 SchedError::Journal(format!("replay of entry {} failed: {e}", entry.seq))
241 })?;
242 }
243 if !opened.entries.is_empty() {
244 s.clock_base = s.core.last_at;
245 s.clock_origin = (s.clock)();
246 }
247 let report = ReplayReport {
248 entries: opened.entries.len(),
249 torn_bytes: opened.torn_bytes,
250 };
251 s.journal = Some(opened.journal);
252 Ok((Unaudited { sched: s }, report))
253 }
254
255 pub fn config(&self) -> &ProvisionalConfig {
256 &self.cfg
257 }
258
259 fn now(&self) -> u64 {
260 let elapsed = (self.clock)().saturating_sub(self.clock_origin);
261 self.clock_base
262 .saturating_add(elapsed)
263 .max(self.core.last_at)
264 }
265
266 /// Validate, journal and apply one event. See the module docs. Ids with
267 /// [`RESERVED_ID_PREFIX`] and `AuditRevoke` events are refused: only
268 /// the scheduler emits those.
269 pub fn deliver(&mut self, event: Event) -> Result<Outcome, SchedError> {
270 if event.id.starts_with(RESERVED_ID_PREFIX) {
271 return Err(SchedError::InvalidEvent(format!(
272 "event ids starting with '{RESERVED_ID_PREFIX}' are reserved"
273 )));
274 }
275 if matches!(event.kind, EventKind::AuditRevoke { .. }) {
276 return Err(SchedError::InvalidEvent(
277 "audit_revoke is emitted only by audit()".to_string(),
278 ));
279 }
280 self.deliver_unchecked(event)
281 }
282
283 pub(crate) fn deliver_unchecked(&mut self, event: Event) -> Result<Outcome, SchedError> {
284 check_identifier("event id", &event.id)
285 .map_err(|e| SchedError::InvalidEvent(e.to_string()))?;
286 if let Some(prev) = self.core.seen.get(&event.id) {
287 return if *prev == payload_digest(&event.kind) {
288 Ok(Outcome::Duplicate)
289 } else {
290 Err(SchedError::EventIdConflict(event.id))
291 };
292 }
293 self.verify_proofs(&event.kind)?;
294 let entry = JournalEntry {
295 seq: self.core.seq + 1,
296 id: event.id,
297 at: self.now(),
298 kind: event.kind,
299 };
300 let mut next = self.core.clone();
301 let fx = next.apply(&self.cfg, &entry)?;
302 if let Some(j) = self.journal.as_mut() {
303 j.append(&entry).map_err(SchedError::Journal)?;
304 }
305 self.core = next;
306 Ok(Outcome::Applied(fx))
307 }
308
309 pub fn task(&self, id: &str) -> Option<&TaskEntry> {
310 self.core.tasks.get(id)
311 }
312
313 pub fn state(&self, id: &str) -> Option<TaskState> {
314 self.task(id).map(|t| t.state)
315 }
316
317 pub fn generation(&self, id: &str) -> Option<u64> {
318 self.task(id).map(|t| t.generation)
319 }
320
321 /// The fence a bound request key must pass ([`EventKind::BindApproval`]).
322 pub fn approval(&self, key: &str) -> Option<&ApprovalBinding> {
323 self.core.approvals.get(key)
324 }
325
326 /// How many request keys are bound.
327 pub fn approvals_len(&self) -> usize {
328 self.core.approvals.len()
329 }
330
331 pub fn queue(&self) -> Vec<String> {
332 self.core.queue.iter().cloned().collect()
333 }
334
335 pub fn permits_in_use(&self) -> PermitPool {
336 self.core.pool
337 }
338
339 /// How many event ids are remembered for duplicate detection.
340 pub fn remembered_event_ids(&self) -> usize {
341 self.core.seen.len()
342 }
343
344 /// Full scheduler state as JSON, for replay comparisons and debugging.
345 pub fn snapshot(&self) -> Value {
346 serde_json::to_value(&self.core).unwrap_or(Value::Null)
347 }
348
349 /// Structural invariants. Tests call this after every step.
350 pub fn check_invariants(&self) -> Result<(), String> {
351 let mut pool = PermitPool::default();
352 for (id, t) in &self.core.tasks {
353 if t.state.holds_permits() {
354 pool.running += 1;
355 pool.cpu_in_use += t.resources.cpu_slots;
356 pool.memory_in_use += t.resources.memory_bytes;
357 if self.core.graph.producers_of(id).count() != t.bindings.len() {
358 return Err(format!("running task '{id}' lacks a producer binding"));
359 }
360 } else if t.lease_expires_at.is_some() {
361 return Err(format!(
362 "task '{id}' is {} but holds a lease",
363 t.state.as_str()
364 ));
365 }
366 let in_queue = self.core.queue.iter().any(|q| q == id);
367 if t.queued != in_queue || (in_queue && t.state != TaskState::Blocked) {
368 return Err(format!("task '{id}' queue flag disagrees with the queue"));
369 }
370 }
371 if pool != self.core.pool {
372 return Err(format!(
373 "permits in use {:?} differ from running tasks {:?}",
374 self.core.pool, pool
375 ));
376 }
377 if self.core.queue.len() > self.cfg.queue_capacity {
378 return Err("ready queue exceeds its bound".to_string());
379 }
380 Ok(())
381 }
382
383 /// Per-task blocked and provisional time as of the last event, for the
384 /// M6 A/B analysis. Derived only from journaled event times.
385 pub fn timing_trace(&self) -> Value {
386 let now = self.core.last_at;
387 let tasks: Vec<Value> = self
388 .core
389 .tasks
390 .iter()
391 .map(|(id, t)| {
392 let timing = t.timing.as_of(t.state, now);
393 json!({
394 "task": id,
395 "state": t.state.as_str(),
396 "generation": t.generation,
397 "blocked": timing.blocked,
398 "provisional": timing.provisional,
399 "awaiting_final_proof": timing.awaiting_final_proof,
400 "registered_at": timing.registered_at,
401 "first_dispatch_at": timing.first_dispatch_at,
402 "committable_at": timing.committable_at,
403 "dispatches": timing.dispatches,
404 "revocations": timing.revocations,
405 })
406 })
407 .collect();
408 json!({
409 "schema": TRACE_SCHEMA,
410 "version": 1,
411 "enabled": self.cfg.enabled,
412 "clock": "injected monotonic clock ticks",
413 "as_of": now,
414 "tasks": tasks,
415 })
416 }
417}