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
aien-sovereign-core-mv / crates / spark-harness / src / scheduler / core.rs
| 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 | //! Pure scheduler state and event application. |
| 17 | //! |
| 18 | //! [`Core::apply`] is deterministic: it reads only the current state, the |
| 19 | //! config and the journal entry (including the entry's recorded time). It |
| 20 | //! never touches the harness store or the clock. That is what lets a journal |
| 21 | //! replay rebuild the exact same state. Store checks happen before an event |
| 22 | //! is journaled (`gates.rs`) and again at every `may_start` / `may_finalize`. |
| 23 | |
| 24 | use super::dedup::Seen; |
| 25 | use super::error::SchedError; |
| 26 | use super::permits::{PermitPool, ResourceRequest}; |
| 27 | use super::timing::TaskTiming; |
| 28 | use super::ProvisionalConfig; |
| 29 | use crate::completion::{artifact_digest, check_identifier}; |
| 30 | use crate::dependency::DependencyGraph; |
| 31 | use crate::execution::{check_transition, TaskState}; |
| 32 | use crate::readiness::ProofClaim; |
| 33 | use serde::{Deserialize, Serialize}; |
| 34 | use std::collections::{BTreeMap, VecDeque}; |
| 35 | |
| 36 | /// Everything the scheduler can be told. Producer proof events carry only a |
| 37 | /// [`ProofClaim`] pointer; the receipt itself is re-read from the store. |
| 38 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 39 | #[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)] |
| 40 | pub enum EventKind { |
| 41 | /// Register a task with its producers. A task with no producers is |
| 42 | /// eligible at once, so dependencies are declared here, atomically. |
| 43 | RegisterTask { |
| 44 | task: String, |
| 45 | resources: ResourceRequest, |
| 46 | producers: Vec<String>, |
| 47 | }, |
| 48 | /// Add a producer to a task that is still `Blocked`. |
| 49 | AddDependency { |
| 50 | producer: String, |
| 51 | consumer: String, |
| 52 | }, |
| 53 | InterfacePublished { |
| 54 | task: String, |
| 55 | generation: u64, |
| 56 | claim: ProofClaim, |
| 57 | }, |
| 58 | CompletionVerified { |
| 59 | task: String, |
| 60 | generation: u64, |
| 61 | claim: ProofClaim, |
| 62 | }, |
| 63 | /// The producer's body or interface changed and work restarts at a new, |
| 64 | /// higher generation. |
| 65 | NewGeneration { |
| 66 | task: String, |
| 67 | generation: u64, |
| 68 | }, |
| 69 | ProducerFailed { |
| 70 | task: String, |
| 71 | generation: u64, |
| 72 | reason: String, |
| 73 | }, |
| 74 | /// The task's provisional work finished. `result_digest` names the |
| 75 | /// provisional result, which is discarded on revocation. |
| 76 | WorkDone { |
| 77 | task: String, |
| 78 | generation: u64, |
| 79 | result_digest: String, |
| 80 | }, |
| 81 | // The task-directed events below carry the task's current generation, |
| 82 | // like the proof events above: a redelivery after the task moved on is |
| 83 | // refused as stale, so duplicate detection never depends on a window. |
| 84 | Finalize { |
| 85 | task: String, |
| 86 | generation: u64, |
| 87 | }, |
| 88 | /// `beat` must rise with every heartbeat of one lease (start at 1), so |
| 89 | /// a redelivered heartbeat is refused without remembering its id. |
| 90 | Heartbeat { |
| 91 | task: String, |
| 92 | generation: u64, |
| 93 | beat: u64, |
| 94 | }, |
| 95 | Cancel { |
| 96 | task: String, |
| 97 | generation: u64, |
| 98 | }, |
| 99 | /// `generation` is the aborted generation; the retry runs at the next. |
| 100 | Retry { |
| 101 | task: String, |
| 102 | generation: u64, |
| 103 | }, |
| 104 | Revoke { |
| 105 | task: String, |
| 106 | generation: u64, |
| 107 | reason: String, |
| 108 | }, |
| 109 | /// Emitted only by `Scheduler::audit` (callers cannot deliver it): |
| 110 | /// revoke every listed task that is still active, then dispatch once, |
| 111 | /// so no consumer is dispatched between two audit revocations. |
| 112 | AuditRevoke { |
| 113 | revocations: Vec<Revocation>, |
| 114 | }, |
| 115 | /// Lets time pass: expires leases. |
| 116 | Tick, |
| 117 | /// `Committable -> Committing` (Headstart M3, issue #537). Freezes the |
| 118 | /// task at `generation` with its own accepted completion and every |
| 119 | /// producer's accepted completion, all of which must equal the current |
| 120 | /// state and verify in the store. Refused when another commit is |
| 121 | /// running in the same dependency chain. |
| 122 | BeginCommit { |
| 123 | task: String, |
| 124 | generation: u64, |
| 125 | completion: ProofClaim, |
| 126 | producers: BTreeMap<String, ProofClaim>, |
| 127 | }, |
| 128 | /// Ends a `Committing` task with the wrapped call's outcome. |
| 129 | CommitOutcome { |
| 130 | task: String, |
| 131 | generation: u64, |
| 132 | outcome: CommitResult, |
| 133 | }, |
| 134 | /// Bind an external request `key` (opaque to M2, at most |
| 135 | /// [`MAX_APPROVAL_KEY_LEN`] bytes) to the commit fence of `task` at |
| 136 | /// `generation`. A later bind of the same key replaces it. Refused for |
| 137 | /// a task whose commit ended (`Committed`, `CommitUncertain`). Every |
| 138 | /// binding of a task is dropped when the task reaches one of those |
| 139 | /// states, and only then: an `Aborted` task keeps its bindings, and so |
| 140 | /// does a retried or revoked one (the binding then names a superseded |
| 141 | /// generation), so the request stays fenced until it is bound again. |
| 142 | /// Each task holds at most [`MAX_APPROVAL_BINDINGS_PER_TASK`] keys; a |
| 143 | /// new key beyond that is refused, so one task cannot take another |
| 144 | /// task's slots and the table is bounded by the number of tasks. |
| 145 | BindApproval { |
| 146 | key: String, |
| 147 | task: String, |
| 148 | generation: u64, |
| 149 | }, |
| 150 | } |
| 151 | |
| 152 | /// Most request keys [`EventKind::BindApproval`] holds for one task. |
| 153 | pub const MAX_APPROVAL_BINDINGS_PER_TASK: usize = 64; |
| 154 | /// Longest request key [`EventKind::BindApproval`] accepts, in bytes. |
| 155 | pub const MAX_APPROVAL_KEY_LEN: usize = 512; |
| 156 | |
| 157 | /// One bound request: the task generation whose commit fence it must pass. |
| 158 | #[derive(Debug, Clone, PartialEq, Eq, Serialize)] |
| 159 | pub struct ApprovalBinding { |
| 160 | pub task: String, |
| 161 | pub generation: u64, |
| 162 | } |
| 163 | |
| 164 | /// A task in one of these states has run its commit, for good: it holds no |
| 165 | /// request binding. `Aborted` is not one of them: a cancelled, failed or |
| 166 | /// expired task may be retried, and its bound requests must stay fenced. |
| 167 | fn binding_ended(state: TaskState) -> bool { |
| 168 | matches!(state, TaskState::Committed | TaskState::CommitUncertain) |
| 169 | } |
| 170 | |
| 171 | /// How a commit ended. |
| 172 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 173 | #[serde(tag = "result", rename_all = "snake_case", deny_unknown_fields)] |
| 174 | pub enum CommitResult { |
| 175 | /// The commit succeeded: `Committed`. |
| 176 | Committed { detail: String }, |
| 177 | /// The commit was refused before any durable effect: `Aborted` |
| 178 | /// (retryable at the next generation); consumers are revoked. |
| 179 | Failed { reason: String }, |
| 180 | /// The outcome is unknown: `CommitUncertain`, never run again; |
| 181 | /// consumers are revoked. |
| 182 | Uncertain { reason: String }, |
| 183 | } |
| 184 | |
| 185 | /// What a `BeginCommit` froze. |
| 186 | #[derive(Debug, Clone, PartialEq, Eq, Serialize)] |
| 187 | pub struct CommitInputs { |
| 188 | pub completion: ProofClaim, |
| 189 | pub producers: BTreeMap<String, ProofClaim>, |
| 190 | pub began_at: u64, |
| 191 | } |
| 192 | |
| 193 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 194 | #[serde(deny_unknown_fields)] |
| 195 | pub struct Revocation { |
| 196 | pub task: String, |
| 197 | pub reason: String, |
| 198 | } |
| 199 | |
| 200 | /// One delivered event. Duplicate delivery is detected by `id`. |
| 201 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 202 | #[serde(deny_unknown_fields)] |
| 203 | pub struct Event { |
| 204 | pub id: String, |
| 205 | pub kind: EventKind, |
| 206 | } |
| 207 | |
| 208 | /// One journal line: the accepted event plus its sequence number and the |
| 209 | /// monotonic time it was applied at. |
| 210 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 211 | #[serde(deny_unknown_fields)] |
| 212 | pub struct JournalEntry { |
| 213 | pub seq: u64, |
| 214 | pub id: String, |
| 215 | pub at: u64, |
| 216 | pub kind: EventKind, |
| 217 | } |
| 218 | |
| 219 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] |
| 220 | pub enum BindingLevel { |
| 221 | Interface, |
| 222 | Final, |
| 223 | } |
| 224 | |
| 225 | /// Which producer artifact a consumer was dispatched against. |
| 226 | #[derive(Debug, Clone, PartialEq, Eq, Serialize)] |
| 227 | pub struct Binding { |
| 228 | pub generation: u64, |
| 229 | pub level: BindingLevel, |
| 230 | pub claim: ProofClaim, |
| 231 | } |
| 232 | |
| 233 | /// Scheduler view of one task. Returned by shared reference only. |
| 234 | #[derive(Debug, Clone, PartialEq, Eq, Serialize)] |
| 235 | pub struct TaskEntry { |
| 236 | pub state: TaskState, |
| 237 | /// This task's own producer generation. Starts at 1, only increases. |
| 238 | pub generation: u64, |
| 239 | pub resources: ResourceRequest, |
| 240 | /// Accepted interface claim for the current generation. |
| 241 | pub interface: Option<ProofClaim>, |
| 242 | /// Accepted M1 completion claim for the current generation. |
| 243 | pub completion: Option<ProofClaim>, |
| 244 | pub bindings: BTreeMap<String, Binding>, |
| 245 | pub lease_expires_at: Option<u64>, |
| 246 | /// Highest heartbeat beat accepted for the current lease. |
| 247 | pub last_beat: u64, |
| 248 | pub provisional_result: Option<String>, |
| 249 | pub queued: bool, |
| 250 | pub last_reason: Option<String>, |
| 251 | pub timing: TaskTiming, |
| 252 | /// Set by `BeginCommit`; kept after the outcome as the record of what |
| 253 | /// the commit was checked against. |
| 254 | pub commit: Option<CommitInputs>, |
| 255 | } |
| 256 | |
| 257 | impl TaskEntry { |
| 258 | pub(crate) fn new(resources: ResourceRequest, at: u64) -> Self { |
| 259 | TaskEntry { |
| 260 | state: TaskState::Blocked, |
| 261 | generation: 1, |
| 262 | resources, |
| 263 | interface: None, |
| 264 | completion: None, |
| 265 | bindings: BTreeMap::new(), |
| 266 | lease_expires_at: None, |
| 267 | last_beat: 0, |
| 268 | provisional_result: None, |
| 269 | queued: false, |
| 270 | last_reason: None, |
| 271 | timing: TaskTiming::new(at), |
| 272 | commit: None, |
| 273 | } |
| 274 | } |
| 275 | |
| 276 | /// Final for consumers: `Committable`, `Committing` or `Committed` |
| 277 | /// with an accepted completion. |
| 278 | pub(crate) fn final_ready(&self) -> bool { |
| 279 | self.state.is_final() && self.completion.is_some() |
| 280 | } |
| 281 | |
| 282 | pub(crate) fn interface_ready(&self) -> bool { |
| 283 | self.state.is_active() && self.interface.is_some() |
| 284 | } |
| 285 | |
| 286 | fn lease_valid(&self, at: u64) -> bool { |
| 287 | self.lease_expires_at.is_some_and(|exp| at < exp) |
| 288 | } |
| 289 | } |
| 290 | |
| 291 | /// What applying an event did. |
| 292 | #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)] |
| 293 | pub struct Effects { |
| 294 | pub dispatched: Vec<String>, |
| 295 | pub revoked: Vec<String>, |
| 296 | pub aborted: Vec<String>, |
| 297 | } |
| 298 | |
| 299 | #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)] |
| 300 | pub struct Core { |
| 301 | pub(crate) graph: DependencyGraph, |
| 302 | pub(crate) tasks: BTreeMap<String, TaskEntry>, |
| 303 | pub(crate) queue: VecDeque<String>, |
| 304 | pub(crate) pool: PermitPool, |
| 305 | /// Bounded memory of applied event ids (`dedup.rs`). |
| 306 | pub(crate) seen: Seen, |
| 307 | /// Bound requests by key ([`EventKind::BindApproval`]). |
| 308 | pub(crate) approvals: BTreeMap<String, ApprovalBinding>, |
| 309 | pub(crate) seq: u64, |
| 310 | pub(crate) last_at: u64, |
| 311 | } |
| 312 | |
| 313 | pub(crate) fn payload_digest(kind: &EventKind) -> String { |
| 314 | artifact_digest(&serde_json::to_value(kind).unwrap_or_default()) |
| 315 | } |
| 316 | |
| 317 | fn bad(m: impl Into<String>) -> SchedError { |
| 318 | SchedError::InvalidEvent(m.into()) |
| 319 | } |
| 320 | |
| 321 | impl Core { |
| 322 | pub(crate) fn task(&self, id: &str) -> Result<&TaskEntry, SchedError> { |
| 323 | self.tasks |
| 324 | .get(id) |
| 325 | .ok_or_else(|| SchedError::UnknownTask(id.to_string())) |
| 326 | } |
| 327 | |
| 328 | fn task_mut(&mut self, id: &str) -> Result<&mut TaskEntry, SchedError> { |
| 329 | self.tasks |
| 330 | .get_mut(id) |
| 331 | .ok_or_else(|| SchedError::UnknownTask(id.to_string())) |
| 332 | } |
| 333 | |
| 334 | pub(crate) fn require_generation(&self, id: &str, generation: u64) -> Result<(), SchedError> { |
| 335 | let current = self.task(id)?.generation; |
| 336 | let (task, submitted) = (id.to_string(), generation); |
| 337 | match generation.cmp(¤t) { |
| 338 | std::cmp::Ordering::Less => Err(SchedError::StaleGeneration { |
| 339 | task, |
| 340 | submitted, |
| 341 | current, |
| 342 | }), |
| 343 | std::cmp::Ordering::Greater => Err(SchedError::FutureGeneration { |
| 344 | task, |
| 345 | submitted, |
| 346 | current, |
| 347 | }), |
| 348 | std::cmp::Ordering::Equal => Ok(()), |
| 349 | } |
| 350 | } |
| 351 | |
| 352 | fn require_state( |
| 353 | &self, |
| 354 | id: &str, |
| 355 | ok: impl Fn(TaskState) -> bool, |
| 356 | action: &'static str, |
| 357 | ) -> Result<(), SchedError> { |
| 358 | let state = self.task(id)?.state; |
| 359 | if ok(state) { |
| 360 | Ok(()) |
| 361 | } else { |
| 362 | Err(SchedError::WrongState { |
| 363 | task: id.to_string(), |
| 364 | state, |
| 365 | action, |
| 366 | }) |
| 367 | } |
| 368 | } |
| 369 | |
| 370 | /// The only place a task changes state. Leaving `Provisional` releases |
| 371 | /// the task's permits and lease. |
| 372 | fn set_state(&mut self, id: &str, to: TaskState, at: u64) -> Result<(), SchedError> { |
| 373 | let Core { tasks, pool, .. } = self; |
| 374 | let t = tasks |
| 375 | .get_mut(id) |
| 376 | .ok_or_else(|| SchedError::UnknownTask(id.to_string()))?; |
| 377 | check_transition(t.state, to)?; |
| 378 | t.timing.close(t.state, at); |
| 379 | if t.state.holds_permits() && !to.holds_permits() { |
| 380 | pool.release(t.resources); |
| 381 | t.lease_expires_at = None; |
| 382 | } |
| 383 | t.state = to; |
| 384 | Ok(()) |
| 385 | } |
| 386 | |
| 387 | fn dequeue(&mut self, id: &str) { |
| 388 | if let Some(t) = self.tasks.get_mut(id) { |
| 389 | if t.queued { |
| 390 | t.queued = false; |
| 391 | self.queue.retain(|q| q != id); |
| 392 | } |
| 393 | } |
| 394 | } |
| 395 | |
| 396 | fn clear_work(t: &mut TaskEntry, reason: &str) { |
| 397 | t.interface = None; |
| 398 | t.completion = None; |
| 399 | t.bindings.clear(); |
| 400 | t.provisional_result = None; |
| 401 | t.last_reason = Some(reason.to_string()); |
| 402 | } |
| 403 | |
| 404 | fn reset_to_blocked( |
| 405 | &mut self, |
| 406 | id: &str, |
| 407 | generation: u64, |
| 408 | at: u64, |
| 409 | reason: &str, |
| 410 | fx: &mut Effects, |
| 411 | ) -> Result<(), SchedError> { |
| 412 | if self.task(id)?.state != TaskState::Blocked { |
| 413 | self.set_state(id, TaskState::Blocked, at)?; |
| 414 | } |
| 415 | let t = self.task_mut(id)?; |
| 416 | t.generation = generation; |
| 417 | t.timing.revocations += 1; |
| 418 | Self::clear_work(t, reason); |
| 419 | fx.revoked.push(id.to_string()); |
| 420 | Ok(()) |
| 421 | } |
| 422 | |
| 423 | fn abort( |
| 424 | &mut self, |
| 425 | id: &str, |
| 426 | at: u64, |
| 427 | reason: &str, |
| 428 | fx: &mut Effects, |
| 429 | ) -> Result<(), SchedError> { |
| 430 | self.dequeue(id); |
| 431 | self.set_state(id, TaskState::Aborted, at)?; |
| 432 | Self::clear_work(self.task_mut(id)?, reason); |
| 433 | fx.aborted.push(id.to_string()); |
| 434 | Ok(()) |
| 435 | } |
| 436 | |
| 437 | /// Return every active descendant of `producer` to `Blocked` at a new |
| 438 | /// generation and discard its provisional result. Queued descendants |
| 439 | /// leave the queue and are re-checked by [`Core::pump`]. |
| 440 | fn revoke_descendants( |
| 441 | &mut self, |
| 442 | producer: &str, |
| 443 | at: u64, |
| 444 | reason: &str, |
| 445 | fx: &mut Effects, |
| 446 | ) -> Result<(), SchedError> { |
| 447 | self.guard_descendants(producer)?; |
| 448 | for d in self.affected(producer) { |
| 449 | let t = self.task(&d)?; |
| 450 | if t.state.is_active() { |
| 451 | let next = t.generation + 1; |
| 452 | let why = format!("{reason} (upstream '{producer}')"); |
| 453 | self.reset_to_blocked(&d, next, at, &why, fx)?; |
| 454 | } else { |
| 455 | self.dequeue(&d); |
| 456 | } |
| 457 | } |
| 458 | Ok(()) |
| 459 | } |
| 460 | |
| 461 | /// Descendants of `id` that an upstream change reaches, breadth-first, |
| 462 | /// excluding `id`. A `Committed` or `CommitUncertain` task is done: it |
| 463 | /// is neither returned nor walked through (its consumers are reached |
| 464 | /// only along other paths). |
| 465 | pub(crate) fn affected(&self, id: &str) -> Vec<String> { |
| 466 | let mut seen = std::collections::BTreeSet::new(); |
| 467 | let mut out = Vec::new(); |
| 468 | let mut q: VecDeque<&String> = self.graph.consumers_of(id).collect(); |
| 469 | while let Some(n) = q.pop_front() { |
| 470 | if !seen.insert(n.clone()) { |
| 471 | continue; |
| 472 | } |
| 473 | if self |
| 474 | .tasks |
| 475 | .get(n) |
| 476 | .is_some_and(|t| t.state.is_commit_terminal()) |
| 477 | { |
| 478 | continue; |
| 479 | } |
| 480 | out.push(n.clone()); |
| 481 | q.extend(self.graph.consumers_of(n)); |
| 482 | } |
| 483 | out |
| 484 | } |
| 485 | |
| 486 | /// The `Committing` task an upstream change of `id` would reach. |
| 487 | fn committing_below(&self, id: &str) -> Option<String> { |
| 488 | self.affected(id) |
| 489 | .into_iter() |
| 490 | .find(|d| self.tasks.get(d).map(|t| t.state) == Some(TaskState::Committing)) |
| 491 | } |
| 492 | |
| 493 | fn guard_descendants(&self, id: &str) -> Result<(), SchedError> { |
| 494 | match self.committing_below(id) { |
| 495 | Some(committing) => Err(SchedError::CommitInProgress { |
| 496 | task: id.to_string(), |
| 497 | committing, |
| 498 | }), |
| 499 | None => Ok(()), |
| 500 | } |
| 501 | } |
| 502 | |
| 503 | /// Refuse an event that would change `id` itself while it is |
| 504 | /// `Committing`, or reach a `Committing` task below it. |
| 505 | pub(crate) fn guard_commit(&self, id: &str) -> Result<(), SchedError> { |
| 506 | if self.task(id)?.state == TaskState::Committing { |
| 507 | return Err(SchedError::CommitInProgress { |
| 508 | task: id.to_string(), |
| 509 | committing: id.to_string(), |
| 510 | }); |
| 511 | } |
| 512 | self.guard_descendants(id) |
| 513 | } |
| 514 | |
| 515 | /// A `Committing` task in the same chain as `id` (upstream or |
| 516 | /// downstream along [`Core::affected`] paths), other than `id`. |
| 517 | fn commit_in_chain(&self, id: &str) -> Option<String> { |
| 518 | if let Some(c) = self.committing_below(id) { |
| 519 | return Some(c); |
| 520 | } |
| 521 | self.tasks |
| 522 | .iter() |
| 523 | .filter(|(other, t)| t.state == TaskState::Committing && other.as_str() != id) |
| 524 | .map(|(other, _)| other) |
| 525 | .find(|other| self.affected(other).iter().any(|d| d == id)) |
| 526 | .cloned() |
| 527 | } |
| 528 | |
| 529 | fn eligible(&self, cfg: &ProvisionalConfig, id: &str) -> bool { |
| 530 | let Some(t) = self.tasks.get(id) else { |
| 531 | return false; |
| 532 | }; |
| 533 | t.state == TaskState::Blocked |
| 534 | && self.graph.producers_of(id).all(|p| { |
| 535 | self.tasks |
| 536 | .get(p) |
| 537 | .is_some_and(|pt| pt.final_ready() || (cfg.enabled && pt.interface_ready())) |
| 538 | }) |
| 539 | } |
| 540 | |
| 541 | fn bindings_for(&self, id: &str) -> BTreeMap<String, Binding> { |
| 542 | let mut out = BTreeMap::new(); |
| 543 | for p in self.graph.producers_of(id) { |
| 544 | let Some(pt) = self.tasks.get(p) else { |
| 545 | continue; |
| 546 | }; |
| 547 | let (level, claim) = if pt.final_ready() { |
| 548 | (BindingLevel::Final, pt.completion.clone()) |
| 549 | } else { |
| 550 | (BindingLevel::Interface, pt.interface.clone()) |
| 551 | }; |
| 552 | if let Some(claim) = claim { |
| 553 | out.insert( |
| 554 | p.clone(), |
| 555 | Binding { |
| 556 | generation: pt.generation, |
| 557 | level, |
| 558 | claim, |
| 559 | }, |
| 560 | ); |
| 561 | } |
| 562 | } |
| 563 | out |
| 564 | } |
| 565 | |
| 566 | /// Fill the bounded ready queue in task-id order, then dispatch from its |
| 567 | /// head while permits allow (head-of-line, no reordering). |
| 568 | fn pump( |
| 569 | &mut self, |
| 570 | cfg: &ProvisionalConfig, |
| 571 | at: u64, |
| 572 | fx: &mut Effects, |
| 573 | ) -> Result<(), SchedError> { |
| 574 | loop { |
| 575 | let stale: Vec<String> = self |
| 576 | .queue |
| 577 | .iter() |
| 578 | .filter(|id| !self.eligible(cfg, id)) |
| 579 | .cloned() |
| 580 | .collect(); |
| 581 | for id in stale { |
| 582 | self.dequeue(&id); |
| 583 | } |
| 584 | let ready: Vec<String> = self |
| 585 | .tasks |
| 586 | .iter() |
| 587 | .filter(|(id, t)| !t.queued && self.eligible(cfg, id)) |
| 588 | .map(|(id, _)| id.clone()) |
| 589 | .collect(); |
| 590 | for id in ready { |
| 591 | if self.queue.len() >= cfg.queue_capacity { |
| 592 | break; |
| 593 | } |
| 594 | self.queue.push_back(id.clone()); |
| 595 | self.task_mut(&id)?.queued = true; |
| 596 | } |
| 597 | let mut progressed = false; |
| 598 | while let Some(head) = self.queue.front().cloned() { |
| 599 | let req = self.task(&head)?.resources; |
| 600 | if !self.pool.try_acquire(&cfg.limits, req) { |
| 601 | break; |
| 602 | } |
| 603 | self.queue.pop_front(); |
| 604 | let bindings = self.bindings_for(&head); |
| 605 | self.set_state(&head, TaskState::Provisional, at)?; |
| 606 | let t = self.task_mut(&head)?; |
| 607 | t.queued = false; |
| 608 | t.bindings = bindings; |
| 609 | t.lease_expires_at = Some(at.saturating_add(cfg.lease_ttl)); |
| 610 | // One lease per generation: leaving Provisional always ends |
| 611 | // in a new generation before the next dispatch. |
| 612 | t.last_beat = 0; |
| 613 | t.timing.dispatches += 1; |
| 614 | t.timing.first_dispatch_at.get_or_insert(at); |
| 615 | fx.dispatched.push(head); |
| 616 | progressed = true; |
| 617 | } |
| 618 | if !progressed { |
| 619 | return Ok(()); |
| 620 | } |
| 621 | } |
| 622 | } |
| 623 | |
| 624 | /// Apply one journal entry. On error the caller discards this copy of |
| 625 | /// the state, so a refused event changes nothing. |
| 626 | pub(crate) fn apply( |
| 627 | &mut self, |
| 628 | cfg: &ProvisionalConfig, |
| 629 | e: &JournalEntry, |
| 630 | ) -> Result<Effects, SchedError> { |
| 631 | if e.seq != self.seq + 1 { |
| 632 | return Err(bad(format!( |
| 633 | "sequence {} out of order, expected {}", |
| 634 | e.seq, |
| 635 | self.seq + 1 |
| 636 | ))); |
| 637 | } |
| 638 | if self.seen.contains(&e.id) { |
| 639 | return Err(SchedError::EventIdConflict(e.id.clone())); |
| 640 | } |
| 641 | if e.at < self.last_at { |
| 642 | return Err(bad("event time is earlier than the previous event")); |
| 643 | } |
| 644 | self.last_at = e.at; |
| 645 | let at = e.at; |
| 646 | let mut fx = Effects::default(); |
| 647 | match &e.kind { |
| 648 | EventKind::RegisterTask { |
| 649 | task, |
| 650 | resources, |
| 651 | producers, |
| 652 | } => { |
| 653 | check_identifier("task", task).map_err(|err| bad(err.to_string()))?; |
| 654 | if !cfg.limits.admits(*resources) { |
| 655 | return Err(SchedError::ExceedsCapacity(task.clone())); |
| 656 | } |
| 657 | self.graph.add_node(task)?; |
| 658 | for p in producers { |
| 659 | self.graph.add_edge(p, task)?; |
| 660 | } |
| 661 | self.tasks |
| 662 | .insert(task.clone(), TaskEntry::new(*resources, at)); |
| 663 | } |
| 664 | EventKind::AddDependency { producer, consumer } => { |
| 665 | self.graph.check_edge(producer, consumer)?; |
| 666 | self.require_state(consumer, |s| s == TaskState::Blocked, "gain a dependency")?; |
| 667 | self.graph.add_edge(producer, consumer)?; |
| 668 | self.dequeue(consumer); |
| 669 | } |
| 670 | EventKind::InterfacePublished { |
| 671 | task, |
| 672 | generation, |
| 673 | claim, |
| 674 | } |
| 675 | | EventKind::CompletionVerified { |
| 676 | task, |
| 677 | generation, |
| 678 | claim, |
| 679 | } => { |
| 680 | let is_interface = matches!(e.kind, EventKind::InterfacePublished { .. }); |
| 681 | self.require_generation(task, *generation)?; |
| 682 | self.require_state(task, TaskState::is_active, "publish proof")?; |
| 683 | let t = self.task_mut(task)?; |
| 684 | let slot = if is_interface { |
| 685 | &mut t.interface |
| 686 | } else { |
| 687 | &mut t.completion |
| 688 | }; |
| 689 | let changed = slot.is_some() && slot.as_ref() != Some(claim); |
| 690 | *slot = Some(claim.clone()); |
| 691 | if changed { |
| 692 | self.revoke_descendants(task, at, "producer proof changed", &mut fx)?; |
| 693 | } |
| 694 | } |
| 695 | EventKind::NewGeneration { task, generation } => { |
| 696 | let current = self.task(task)?.generation; |
| 697 | if *generation <= current { |
| 698 | return Err(SchedError::StaleGeneration { |
| 699 | task: task.clone(), |
| 700 | submitted: *generation, |
| 701 | current, |
| 702 | }); |
| 703 | } |
| 704 | self.require_state( |
| 705 | task, |
| 706 | |s| s != TaskState::Aborted, |
| 707 | "start a new generation (use retry)", |
| 708 | )?; |
| 709 | self.guard_commit(task)?; |
| 710 | self.reset_to_blocked(task, *generation, at, "new generation", &mut fx)?; |
| 711 | self.revoke_descendants(task, at, "producer new generation", &mut fx)?; |
| 712 | } |
| 713 | EventKind::ProducerFailed { |
| 714 | task, |
| 715 | generation, |
| 716 | reason, |
| 717 | } => { |
| 718 | self.require_generation(task, *generation)?; |
| 719 | self.require_state(task, |s| s != TaskState::Aborted, "fail")?; |
| 720 | self.guard_commit(task)?; |
| 721 | self.abort(task, at, &format!("failed: {reason}"), &mut fx)?; |
| 722 | self.revoke_descendants(task, at, "producer failed", &mut fx)?; |
| 723 | } |
| 724 | EventKind::WorkDone { |
| 725 | task, |
| 726 | generation, |
| 727 | result_digest, |
| 728 | } => { |
| 729 | self.require_generation(task, *generation)?; |
| 730 | self.require_state(task, |s| s == TaskState::Provisional, "report work done")?; |
| 731 | if !self.task(task)?.lease_valid(at) { |
| 732 | return Err(SchedError::LeaseExpired(task.clone())); |
| 733 | } |
| 734 | if result_digest.is_empty() { |
| 735 | return Err(bad("result_digest is empty")); |
| 736 | } |
| 737 | self.set_state(task, TaskState::AwaitingFinalProof, at)?; |
| 738 | self.task_mut(task)?.provisional_result = Some(result_digest.clone()); |
| 739 | } |
| 740 | EventKind::Finalize { task, generation } => { |
| 741 | self.require_generation(task, *generation)?; |
| 742 | self.require_state(task, |s| s == TaskState::AwaitingFinalProof, "finalize")?; |
| 743 | for p in self.graph.producers_of(task) { |
| 744 | let pt = self.task(p)?; |
| 745 | let bound = self.task(task)?.bindings.get(p).map(|b| b.generation); |
| 746 | if bound != Some(pt.generation) || !pt.final_ready() { |
| 747 | return Err(SchedError::ProducerNotFinal { |
| 748 | producer: p.clone(), |
| 749 | detail: "not committable with a completion at the bound generation" |
| 750 | .to_string(), |
| 751 | }); |
| 752 | } |
| 753 | } |
| 754 | self.set_state(task, TaskState::Committable, at)?; |
| 755 | self.task_mut(task)?.timing.committable_at = Some(at); |
| 756 | } |
| 757 | EventKind::Heartbeat { |
| 758 | task, |
| 759 | generation, |
| 760 | beat, |
| 761 | } => { |
| 762 | self.require_generation(task, *generation)?; |
| 763 | self.require_state(task, |s| s == TaskState::Provisional, "heartbeat")?; |
| 764 | let t = self.task_mut(task)?; |
| 765 | if !t.lease_valid(at) { |
| 766 | return Err(SchedError::LeaseExpired(task.clone())); |
| 767 | } |
| 768 | if *beat <= t.last_beat { |
| 769 | return Err(SchedError::StaleHeartbeat { |
| 770 | task: task.clone(), |
| 771 | beat: *beat, |
| 772 | last: t.last_beat, |
| 773 | }); |
| 774 | } |
| 775 | t.last_beat = *beat; |
| 776 | t.lease_expires_at = Some(at.saturating_add(cfg.lease_ttl)); |
| 777 | } |
| 778 | EventKind::Cancel { task, generation } => { |
| 779 | self.require_generation(task, *generation)?; |
| 780 | self.require_state(task, |s| s != TaskState::Aborted, "cancel")?; |
| 781 | self.guard_commit(task)?; |
| 782 | self.abort(task, at, "cancelled", &mut fx)?; |
| 783 | for d in self.affected(task) { |
| 784 | if self.task(&d)?.state != TaskState::Aborted { |
| 785 | self.abort(&d, at, &format!("ancestor '{task}' cancelled"), &mut fx)?; |
| 786 | } |
| 787 | } |
| 788 | } |
| 789 | EventKind::Retry { task, generation } => { |
| 790 | self.require_generation(task, *generation)?; |
| 791 | self.require_state(task, |s| s == TaskState::Aborted, "retry")?; |
| 792 | self.set_state(task, TaskState::Blocked, at)?; |
| 793 | let t = self.task_mut(task)?; |
| 794 | t.generation += 1; |
| 795 | Self::clear_work(t, "retry"); |
| 796 | } |
| 797 | EventKind::Revoke { |
| 798 | task, |
| 799 | generation, |
| 800 | reason, |
| 801 | } => { |
| 802 | self.require_generation(task, *generation)?; |
| 803 | self.require_state(task, TaskState::is_active, "be revoked")?; |
| 804 | let next = self.task(task)?.generation + 1; |
| 805 | self.reset_to_blocked(task, next, at, reason, &mut fx)?; |
| 806 | self.revoke_descendants(task, at, reason, &mut fx)?; |
| 807 | } |
| 808 | EventKind::AuditRevoke { revocations } => { |
| 809 | let first = revocations |
| 810 | .first() |
| 811 | .ok_or_else(|| bad("empty audit revoke"))?; |
| 812 | self.require_state(&first.task, TaskState::is_active, "be revoked")?; |
| 813 | for r in revocations { |
| 814 | // Earlier entries may already have revoked this one. |
| 815 | let t = self.task(&r.task)?; |
| 816 | if t.state.is_active() { |
| 817 | let next = t.generation + 1; |
| 818 | self.reset_to_blocked(&r.task, next, at, &r.reason, &mut fx)?; |
| 819 | self.revoke_descendants(&r.task, at, &r.reason, &mut fx)?; |
| 820 | } |
| 821 | } |
| 822 | } |
| 823 | EventKind::Tick => { |
| 824 | let expired: Vec<String> = self |
| 825 | .tasks |
| 826 | .iter() |
| 827 | .filter(|(_, t)| t.state == TaskState::Provisional && !t.lease_valid(at)) |
| 828 | .map(|(id, _)| id.clone()) |
| 829 | // An expiry that would reach a running commit waits for |
| 830 | // its outcome (a later Tick expires it). |
| 831 | .filter(|id| self.guard_commit(id).is_ok()) |
| 832 | .collect(); |
| 833 | for id in expired { |
| 834 | if self.task(&id)?.state == TaskState::Provisional { |
| 835 | self.abort(&id, at, "lease expired", &mut fx)?; |
| 836 | self.revoke_descendants(&id, at, "producer lease expired", &mut fx)?; |
| 837 | } |
| 838 | } |
| 839 | } |
| 840 | EventKind::BeginCommit { |
| 841 | task, |
| 842 | generation, |
| 843 | completion, |
| 844 | producers, |
| 845 | } => { |
| 846 | self.require_generation(task, *generation)?; |
| 847 | self.require_state(task, |s| s == TaskState::Committable, "begin a commit")?; |
| 848 | if let Some(committing) = self.commit_in_chain(task) { |
| 849 | return Err(SchedError::CommitInProgress { |
| 850 | task: task.clone(), |
| 851 | committing, |
| 852 | }); |
| 853 | } |
| 854 | if self.task(task)?.completion.as_ref() != Some(completion) { |
| 855 | return Err(bad(format!( |
| 856 | "begin_commit completion for '{task}' is not its accepted completion" |
| 857 | ))); |
| 858 | } |
| 859 | let expected: Vec<&String> = self.graph.producers_of(task).collect(); |
| 860 | if expected.len() != producers.len() |
| 861 | || expected.iter().any(|p| !producers.contains_key(*p)) |
| 862 | { |
| 863 | return Err(bad(format!( |
| 864 | "begin_commit for '{task}' must name exactly its producers" |
| 865 | ))); |
| 866 | } |
| 867 | for (p, claim) in producers { |
| 868 | let pt = self.task(p)?; |
| 869 | // A producer that is itself committing is refused above. |
| 870 | if !matches!(pt.state, TaskState::Committable | TaskState::Committed) |
| 871 | || pt.completion.as_ref() != Some(claim) |
| 872 | { |
| 873 | return Err(SchedError::ProducerNotFinal { |
| 874 | producer: p.clone(), |
| 875 | detail: format!( |
| 876 | "state {}, completion differs from the begin_commit input: {}", |
| 877 | pt.state.as_str(), |
| 878 | pt.completion.as_ref() != Some(claim) |
| 879 | ), |
| 880 | }); |
| 881 | } |
| 882 | } |
| 883 | self.set_state(task, TaskState::Committing, at)?; |
| 884 | self.task_mut(task)?.commit = Some(CommitInputs { |
| 885 | completion: completion.clone(), |
| 886 | producers: producers.clone(), |
| 887 | began_at: at, |
| 888 | }); |
| 889 | } |
| 890 | EventKind::CommitOutcome { |
| 891 | task, |
| 892 | generation, |
| 893 | outcome, |
| 894 | } => { |
| 895 | self.require_generation(task, *generation)?; |
| 896 | self.require_state( |
| 897 | task, |
| 898 | |s| s == TaskState::Committing, |
| 899 | "record a commit outcome", |
| 900 | )?; |
| 901 | // BeginCommit refused any second commit in this chain, so |
| 902 | // no Committing task is reachable from here. |
| 903 | match outcome { |
| 904 | CommitResult::Committed { detail } => { |
| 905 | self.set_state(task, TaskState::Committed, at)?; |
| 906 | self.task_mut(task)?.last_reason = Some(format!("committed: {detail}")); |
| 907 | } |
| 908 | CommitResult::Failed { reason } => { |
| 909 | self.abort(task, at, &format!("commit failed: {reason}"), &mut fx)?; |
| 910 | self.revoke_descendants(task, at, "producer commit failed", &mut fx)?; |
| 911 | } |
| 912 | CommitResult::Uncertain { reason } => { |
| 913 | self.revoke_descendants(task, at, "producer commit uncertain", &mut fx)?; |
| 914 | self.set_state(task, TaskState::CommitUncertain, at)?; |
| 915 | self.task_mut(task)?.last_reason = |
| 916 | Some(format!("commit uncertain: {reason}")); |
| 917 | } |
| 918 | } |
| 919 | } |
| 920 | EventKind::BindApproval { |
| 921 | key, |
| 922 | task, |
| 923 | generation, |
| 924 | } => { |
| 925 | if key.is_empty() || key.len() > MAX_APPROVAL_KEY_LEN { |
| 926 | return Err(bad(format!( |
| 927 | "bind_approval key must be 1 to {MAX_APPROVAL_KEY_LEN} bytes" |
| 928 | ))); |
| 929 | } |
| 930 | self.require_generation(task, *generation)?; |
| 931 | self.require_state( |
| 932 | task, |
| 933 | |s| !binding_ended(s), |
| 934 | "bind a request to a task that already ended", |
| 935 | )?; |
| 936 | let rebind = self.approvals.get(key).is_some_and(|b| b.task == *task); |
| 937 | let held = self.approvals.values().filter(|b| b.task == *task).count(); |
| 938 | if !rebind && held >= MAX_APPROVAL_BINDINGS_PER_TASK { |
| 939 | return Err(SchedError::BindingsFull { |
| 940 | task: task.clone(), |
| 941 | capacity: MAX_APPROVAL_BINDINGS_PER_TASK, |
| 942 | }); |
| 943 | } |
| 944 | self.approvals.insert( |
| 945 | key.clone(), |
| 946 | ApprovalBinding { |
| 947 | task: task.clone(), |
| 948 | generation: *generation, |
| 949 | }, |
| 950 | ); |
| 951 | } |
| 952 | } |
| 953 | self.pump(cfg, at, &mut fx)?; |
| 954 | // Every binding of a task whose commit ended (committed or |
| 955 | // uncertain, by this event or by a cascade from it) is dropped. |
| 956 | // Aborted tasks keep theirs (see `binding_ended`). Deterministic, so |
| 957 | // a replay rebuilds the same table. |
| 958 | let tasks = &self.tasks; |
| 959 | self.approvals |
| 960 | .retain(|_, b| tasks.get(&b.task).is_some_and(|t| !binding_ended(t.state))); |
| 961 | self.seen |
| 962 | .record(&e.id, payload_digest(&e.kind), &e.kind, cfg.dedup_window); |
| 963 | let tasks = &self.tasks; |
| 964 | self.seen.prune(|t| tasks.get(t).map(|x| x.generation)); |
| 965 | self.seq = e.seq; |
| 966 | Ok(fx) |
| 967 | } |
| 968 | } |