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 / gates.rs

372 lines · 14613 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//! Store-backed gates: `may_start`, `may_finalize`, event proof checks and
17//! the post-replay audit.
18//!
19//! Every gate re-reads receipts from the harness store and compares them
20//! with the producers' current generations at call time. Scheduler state
21//! (which records what was accepted earlier) only says which receipt to
22//! re-check; it is never the authority on its own.
23
24use super::core::{Binding, BindingLevel, CommitResult, EventKind, Revocation, TaskEntry};
25use super::error::SchedError;
26use super::{Event, Outcome, Scheduler, RESERVED_ID_PREFIX};
27use crate::completion::CompletionError;
28use crate::execution::TaskState;
29use crate::readiness::{verify_final, verify_interface, ArtifactReadiness, OperationClass};
30
31fn proof(task: &str) -> impl Fn(CompletionError) -> SchedError + '_ {
32 move |error| SchedError::Proof {
33 task: task.to_string(),
34 error,
35 }
36}
37
38impl Scheduler {
39 /// Checks that need the store, run before an event is journaled.
40 pub(crate) fn verify_proofs(&self, kind: &EventKind) -> Result<(), SchedError> {
41 match kind {
42 EventKind::InterfacePublished {
43 task,
44 generation,
45 claim,
46 } => {
47 self.core.require_generation(task, *generation)?;
48 verify_interface(&self.store, task, *generation, claim).map_err(proof(task))?;
49 }
50 EventKind::CompletionVerified {
51 task,
52 generation,
53 claim,
54 } => {
55 self.core.require_generation(task, *generation)?;
56 verify_final(&self.store, task, *generation, claim).map_err(proof(task))?;
57 }
58 EventKind::Finalize { task, generation } => {
59 self.core.require_generation(task, *generation)?;
60 self.may_finalize(task)?;
61 }
62 EventKind::BeginCommit {
63 task,
64 generation,
65 completion,
66 ..
67 } => {
68 // Every producer re-verified (recursively), then the task's
69 // own completion; `apply` checks the claims equal the state.
70 self.core.require_generation(task, *generation)?;
71 self.may_finalize(task)?;
72 verify_final(&self.store, task, *generation, completion).map_err(proof(task))?;
73 }
74 _ => {}
75 }
76 Ok(())
77 }
78
79 /// May `task` run `op` right now? Requires a `Provisional` task with a
80 /// live lease, a binding to every producer at the producer's current
81 /// generation, and a store-verified readiness for each producer whose
82 /// level permits `op`. Irreversible classes therefore need every
83 /// producer final-verified. A grant only says the dependencies allow
84 /// the operation; authorization and World commit stay with AEGIS and
85 /// aien-runtime.
86 pub fn may_start(
87 &self,
88 task: &str,
89 op: OperationClass,
90 ) -> Result<Vec<ArtifactReadiness>, SchedError> {
91 let t = self.core.task(task)?;
92 if t.state != TaskState::Provisional {
93 return Err(SchedError::WrongState {
94 task: task.to_string(),
95 state: t.state,
96 action: "start an operation",
97 });
98 }
99 let now = self.now();
100 if !t.lease_expires_at.is_some_and(|exp| now < exp) {
101 return Err(SchedError::LeaseExpired(task.to_string()));
102 }
103 let mut out = Vec::new();
104 for p in self.core.graph.producers_of(task) {
105 let r = self.bound_readiness(task, t, p)?;
106 if !r.permits(op) {
107 return Err(SchedError::NotPermitted {
108 task: task.to_string(),
109 op,
110 producer: p.clone(),
111 level: r.level(),
112 });
113 }
114 out.push(r);
115 }
116 Ok(out)
117 }
118
119 /// [`Scheduler::may_start`] for an operation name from outside (MCP,
120 /// config, CLI). Any name that is not an [`OperationClass`] is refused.
121 pub fn may_start_named(
122 &self,
123 task: &str,
124 op: &str,
125 ) -> Result<Vec<ArtifactReadiness>, SchedError> {
126 let op = OperationClass::parse(op).map_err(SchedError::UnknownOperation)?;
127 self.may_start(task, op)
128 }
129
130 /// May `task` become (or stay) `Committable`? Requires the task to be
131 /// `AwaitingFinalProof` or `Committable`, every binding at the producer's
132 /// current generation, an interface binding whose receipt still verifies
133 /// (no interface change), and every producer final-verified: M1
134 /// completion verifies for its current generation, the producer is
135 /// `Committable`, and the same check passes for its own producers.
136 pub fn may_finalize(&self, task: &str) -> Result<Vec<ArtifactReadiness>, SchedError> {
137 self.finalize_check(task, 0)
138 }
139
140 fn finalize_check(
141 &self,
142 task: &str,
143 depth: usize,
144 ) -> Result<Vec<ArtifactReadiness>, SchedError> {
145 if depth > self.core.tasks.len() {
146 return Err(SchedError::InvalidEvent(
147 "dependency recursion deeper than the task count".to_string(),
148 ));
149 }
150 let t = self.core.task(task)?;
151 // A producer (depth > 0) may also be frozen in `Committing`.
152 if !matches!(
153 t.state,
154 TaskState::AwaitingFinalProof | TaskState::Committable
155 ) && !(depth > 0 && t.state == TaskState::Committing)
156 {
157 return Err(SchedError::WrongState {
158 task: task.to_string(),
159 state: t.state,
160 action: "finalize",
161 });
162 }
163 let mut out = Vec::new();
164 for p in self.core.graph.producers_of(task) {
165 let b = self.binding(task, t, p)?;
166 if b.level == BindingLevel::Interface {
167 verify_interface(&self.store, p, b.generation, &b.claim).map_err(proof(p))?;
168 }
169 out.push(self.producer_final(p, depth + 1)?);
170 }
171 Ok(out)
172 }
173
174 fn producer_final(&self, p: &str, depth: usize) -> Result<ArtifactReadiness, SchedError> {
175 let pt = self.core.task(p)?;
176 let claim = match (&pt.completion, pt.final_ready()) {
177 (Some(c), true) => c,
178 _ => {
179 return Err(SchedError::ProducerNotFinal {
180 producer: p.to_string(),
181 detail: format!(
182 "state {}, completion accepted: {}",
183 pt.state.as_str(),
184 pt.completion.is_some()
185 ),
186 })
187 }
188 };
189 let r = verify_final(&self.store, p, pt.generation, claim).map_err(proof(p))?;
190 // A committed producer is done: its own completion is the proof,
191 // and its upstream may have moved on since (see `Core::affected`).
192 if pt.state != TaskState::Committed {
193 self.finalize_check(p, depth)?;
194 }
195 Ok(r)
196 }
197
198 fn binding<'a>(
199 &self,
200 task: &str,
201 t: &'a TaskEntry,
202 p: &str,
203 ) -> Result<&'a Binding, SchedError> {
204 let stale = |detail: String| SchedError::StaleBinding {
205 task: task.to_string(),
206 producer: p.to_string(),
207 detail,
208 };
209 let current = self.core.task(p)?.generation;
210 let b = t
211 .bindings
212 .get(p)
213 .ok_or_else(|| stale("no binding".to_string()))?;
214 if b.generation != current {
215 return Err(stale(format!(
216 "bound to generation {}, producer is at {current}",
217 b.generation
218 )));
219 }
220 Ok(b)
221 }
222
223 /// Re-verified readiness of producer `p` as `task` is bound to it. An
224 /// interface binding is upgraded to final when the producer is final and
225 /// that proof verifies; if the upgrade fails the interface level (the
226 /// more restrictive one) is returned.
227 fn bound_readiness(
228 &self,
229 task: &str,
230 t: &TaskEntry,
231 p: &str,
232 ) -> Result<ArtifactReadiness, SchedError> {
233 let b = self.binding(task, t, p)?;
234 match b.level {
235 BindingLevel::Interface => {
236 let r =
237 verify_interface(&self.store, p, b.generation, &b.claim).map_err(proof(p))?;
238 if self.core.task(p)?.final_ready() {
239 if let Ok(f) = self.producer_final(p, 1) {
240 return Ok(f);
241 }
242 }
243 Ok(r)
244 }
245 BindingLevel::Final => self.producer_final(p, 1),
246 }
247 }
248
249 /// Active tasks whose own accepted interface or completion claim no
250 /// longer verifies.
251 fn own_claim_failures(&self) -> Vec<Revocation> {
252 let mut out = Vec::new();
253 for (id, t) in self.core.tasks.iter().filter(|(_, t)| t.state.is_active()) {
254 let g = t.generation;
255 let i = t
256 .interface
257 .as_ref()
258 .map(|c| verify_interface(&self.store, id, g, c));
259 let f = t
260 .completion
261 .as_ref()
262 .map(|c| verify_final(&self.store, id, g, c));
263 if let Some(e) = [i, f].into_iter().flatten().find_map(Result::err) {
264 out.push(revocation(id, proof(id)(e)));
265 }
266 }
267 out
268 }
269
270 /// Active tasks whose bindings or finalize check no longer verify.
271 fn binding_failures(&self) -> Vec<Revocation> {
272 let mut out = Vec::new();
273 for (id, t) in &self.core.tasks {
274 let check = match t.state {
275 TaskState::Provisional | TaskState::AwaitingFinalProof => self
276 .core
277 .graph
278 .producers_of(id)
279 .try_for_each(|p| self.bound_readiness(id, t, p).map(|_| ())),
280 TaskState::Committable => self.may_finalize(id).map(|_| ()),
281 // Frozen or done: not re-checked (see `audit`).
282 TaskState::Blocked
283 | TaskState::Aborted
284 | TaskState::Committing
285 | TaskState::Committed
286 | TaskState::CommitUncertain => Ok(()),
287 };
288 if let Err(e) = check {
289 out.push(revocation(id, e));
290 }
291 }
292 out
293 }
294
295 /// Re-verify every active task against the store and revoke the ones
296 /// that no longer verify. Run whenever the store may have changed; a
297 /// replayed journal must pass through it (see [`super::Unaudited`]).
298 /// Returns the revoked tasks.
299 ///
300 /// Each round is one journaled `AuditRevoke`: first every task whose own
301 /// claim fails (which cascades to its consumers), and only when there
302 /// are none, every task whose bindings fail. One batch dispatches once,
303 /// after all of its revocations, so no consumer is dispatched against a
304 /// claim the same round is about to revoke. Each round revokes at least
305 /// one active task; the round count is capped as a backstop.
306 ///
307 /// A revocation that would reach a `Committing` task is deferred (left
308 /// out of the batch): the commit was checked against the store when it
309 /// began, and a later audit catches the change once the outcome is in.
310 pub fn audit(&mut self) -> Result<Vec<String>, SchedError> {
311 let mut revoked = Vec::new();
312 let ready = |s: &Self, mut b: Vec<Revocation>| {
313 b.retain(|r| s.core.guard_commit(&r.task).is_ok());
314 b
315 };
316 for _ in 0..=2 * self.core.tasks.len() {
317 let mut batch = ready(self, self.own_claim_failures());
318 if batch.is_empty() {
319 batch = ready(self, self.binding_failures());
320 }
321 if batch.is_empty() {
322 return Ok(revoked);
323 }
324 let event = Event {
325 id: format!("{RESERVED_ID_PREFIX}audit-{}", self.core.seq + 1),
326 kind: EventKind::AuditRevoke { revocations: batch },
327 };
328 if let Outcome::Applied(fx) = self.deliver_unchecked(event)? {
329 revoked.extend(fx.revoked);
330 }
331 }
332 Err(SchedError::InvalidEvent(
333 "audit did not converge; refusing to continue".to_string(),
334 ))
335 }
336
337 /// After a replay: every task still `Committing` lost its outcome with
338 /// the old process. Its commit may or may not have reached the World, so
339 /// it becomes `CommitUncertain` through a journaled `CommitOutcome` and
340 /// is never run again (as `approved_replay` treats an in-flight claim).
341 /// Returns those tasks.
342 pub(crate) fn settle_interrupted_commits(&mut self) -> Result<Vec<String>, SchedError> {
343 let open: Vec<(String, u64)> = self
344 .core
345 .tasks
346 .iter()
347 .filter(|(_, t)| t.state == TaskState::Committing)
348 .map(|(id, t)| (id.clone(), t.generation))
349 .collect();
350 for (task, generation) in &open {
351 let event = Event {
352 id: format!("{RESERVED_ID_PREFIX}commit-uncertain-{}", self.core.seq + 1),
353 kind: EventKind::CommitOutcome {
354 task: task.clone(),
355 generation: *generation,
356 outcome: CommitResult::Uncertain {
357 reason: "restarted while committing; no outcome was recorded".to_string(),
358 },
359 },
360 };
361 self.deliver_unchecked(event)?;
362 }
363 Ok(open.into_iter().map(|(t, _)| t).collect())
364 }
365}
366
367fn revocation(task: &str, e: SchedError) -> Revocation {
368 Revocation {
369 task: task.to_string(),
370 reason: format!("audit: {e}"),
371 }
372}