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/blob/main/crates/aien-runtime/src/provisional.rs # 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 branch `main` Branches Tags History `aien-sovereign-core-mv / crates / aien-runtime / src / provisional.rs` 1345 lines ยท 55405 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 engineering preparation in front of the canonical compose 17 //! path (Headstart M3, issue #537). Compiled only with cargo feature 18 //! `provisional-prep` (default off); the default build has no trace of it and 19 //! the control ABI (`crate::control`) is the same in both builds: no command, 20 //! field or response is added. With the feature, a daemon given an adapter 21 //! (`AienRuntimeServer::with_prep_adapter`) sends a `ComposeApprovedProposal` 22 //! or `ComposeAuthorize` request through the fence only when 23 //! [`PrepAdapter::bind_approval`] bound it to a task generation; every other 24 //! request runs the original call unchanged. A binding is a journaled M2 25 //! `BindApproval` event, so it survives a daemon restart (the replayed 26 //! scheduler still fences the request). M2 drops the bindings of a task only 27 //! when its commit ended (`Committed` or `CommitUncertain`) and refuses a 28 //! binding to such a task; the request is then unbound again, the daemon 29 //! runs it as the original call and the canonical durable guards decide (see 30 //! Duplicates below). An `Aborted` task (cancelled, failed, lease expired, a 31 //! failed commit, or an abort cascaded from an ancestor) keeps its bindings, 32 //! so its bound requests are refused (`NotCommittable`); after a retry they 33 //! name a superseded generation and are refused (`StaleGeneration`) until 34 //! they are bound again. A bound request never falls back to the unfenced 35 //! call while its task may still commit. Each task holds at most 36 //! `MAX_APPROVAL_BINDINGS_PER_TASK` keys; a new key past that is refused. 37 //! 38 //! Two halves: 39 //! 40 //! 1. Early preparation. [`PrepAdapter::prepare`] runs exactly one whitelisted 41 //! operation, [`PrepOperation::ComposePlanPreview`], for a task the M2 42 //! scheduler (`spark_harness::scheduler`) has dispatched as `Provisional`. 43 //! It maps to [`OperationClass::ReadOnlyAnalysis`], so the M2 gate 44 //! `may_start` allows it on an interface-verified producer. The operation 45 //! is `compose::rederive::task_decision`: it reads the workspace to build 46 //! the compose prompt and destination for a goal and never writes 47 //! (bridge.rs `gather_inputs` doc: "Never writes"). No compose home is 48 //! opened, no model runs, no tool is called, nothing goes to the network. 49 //! The only output is an in-memory [`PreparationResult`] bound to each 50 //! producer's source commit, generation, artifact digest and the receipt 51 //! id the store verified. 52 //! 53 //! 2. Final commit fence. [`PrepAdapter::submit_approved`] (World commit 54 //! through `approved::ProposerHook::submit`) and 55 //! [`PrepAdapter::authorize`] (`effects::authorize_with_objective`, the 56 //! `ComposeAuthorize` path) run the existing call only when, for the 57 //! task's current generation: the M2 task is `Committable`, M2 58 //! `may_finalize` passes (every producer final-verified, recursively), and 59 //! the task's own M1 completion receipt verifies (`verify_final`, which is 60 //! M1 `verify_completion`). The fence is a prerequisite only. Desk MAC, 61 //! AEGIS verify, the replay ledger, the effect ledger and the World commit 62 //! stay inside the unchanged calls and still decide. 63 //! 64 //! One task generation has one fenced call. Each bound flow has exactly 65 //! one durable step this daemon takes for it, so that step is the fence: 66 //! - `ComposeApprovedProposal` (`submit_approved`): the proposer hook 67 //! runs the World commit and writes its own grant in the same call 68 //! (approved.rs `submit`, `write_approved_grant`); it writes no 69 //! `compose_commit` record (compose/bridge.rs `run_task_inner` writes 70 //! one only when `approved_text` is None), so no later 71 //! `ComposeAuthorize` can mint against it. 72 //! - `RunComposeTask` then `ComposeAuthorize`: the run is a model call 73 //! this adapter does not fence (see Duplicates); its compose-commit 74 //! record is what `ComposeAuthorize` mints against (effects.rs). The 75 //! grant (`authorize`) is the fenced call, from `Committable`. 76 //! Both start from `Committable` with the same checks. 77 //! 78 //! No check-to-commit window, and no lock held across the call. The fence 79 //! checks run in one critical section that holds (a) the adapter mutex, the 80 //! only way to deliver a scheduler event, and (b) the harness store's 81 //! interface and completion locks (`/interfaces/.lock`, 82 //! `/completions/.lock`, the same aien-proof flock files 83 //! `publish_interface` and `complete_verified_workflow` take). The same 84 //! critical section ends with the journaled M2 `BeginCommit`, which moves 85 //! the task to `Committing` and freezes its generation, 86 //! its own completion claim and every producer's completion claim. That 87 //! event is the decision point. Both locks are then released and the 88 //! existing call runs. While the task is `Committing`, M2 refuses every 89 //! event that would change what was checked (`SchedError::CommitInProgress` 90 //! for a revoke, cancel, failure, proof change or new generation of the 91 //! task or any ancestor; a second commit in the same dependency chain), and 92 //! the M2 audit and lease expiry defer theirs. Store writes after the 93 //! decision cannot change the call: it runs on the proof taken under the 94 //! locks and never re-reads the store. The call's result is journaled as 95 //! `CommitOutcome` (`Committed`, `Failed` which aborts the task, or 96 //! `Uncertain` which is terminal); consumers are revoked on the last two. A 97 //! panic is recorded as `Uncertain`. A replay that finds a `Committing` task 98 //! with no outcome marks it `CommitUncertain` and never runs it again (the 99 //! approved replay ledger's rule for an in-flight claim). Heartbeats, other 100 //! fences and harness writers in every process proceed while a call runs. 101 //! 102 //! Refused events are not lost: an event M2 refuses with `CommitInProgress` 103 //! through [`PrepAdapter::deliver`] is queued ([`Delivered::Deferred`], at 104 //! most [`DEFERRED_CAPACITY`]; a full queue refuses the event with 105 //! [`DeliverError::DeferredFull`] and queues nothing) and delivered again 106 //! right after the commit outcome is recorded, under the same mutex, before 107 //! any other event or fence. What each redelivery did is returned in 108 //! [`Fenced::redelivered`]. Only an event M2 applied (or answered as a 109 //! duplicate) leaves the queue: one still refused by another running commit, 110 //! and one M2 refuses for any other reason (a stale generation, a wrong 111 //! state, a journal write failure), stays queued and journaled, so a revoke 112 //! or cancel is never dropped without a decision. It is delivered again 113 //! after every later outcome and on every open, and it holds a queue slot 114 //! until the caller removes it ([`PrepAdapter::discard_deferred`]); a full 115 //! queue refuses new deferrals (fail closed). With a journaled scheduler 116 //! ([`PrepAdapter::open`]) the queue is journaled in a sidecar next to the M2 117 //! journal ([`deferred_journal_path`]): rewritten atomically (temp file, 118 //! fsync, rename, directory fsync) before `Deferred` is returned and after 119 //! every drain or discard that changed it. A queue that cannot be written 120 //! refuses the event ([`DeliverError::DeferredJournal`]); a failed rewrite 121 //! after a drain is reported ([`Fenced::deferred_error`]) and the next 122 //! rewrite replaces it. On open, after the M2 audit settled every 123 //! interrupted commit, the journaled events are delivered again in order, so 124 //! a revoke or cancel deferred by a commit that never recorded its outcome 125 //! still lands after it ([`PrepAdapter::take_replayed_deferred`] returns 126 //! what each did). An event that was already applied before the crash is a 127 //! duplicate, or a stale generation once its task moved on (spark-harness 128 //! `scheduler/dedup.rs`); the second stays queued until discarded. A sidecar 129 //! that does not parse, holds more than [`DEFERRED_CAPACITY`] events or 130 //! holds a fence-only event fails the open. One adapter owns a journal and 131 //! its sidecar: open resolves the journal path to its canonical form, takes 132 //! the M2 journal lock (`.lock`, held for the adapter's life; a 133 //! second open of the same journal is refused) and only then reads the 134 //! sidecar, whose name extends the journal's full file name, so distinct 135 //! journals never share one. 136 //! 137 //! Duplicates: a second fenced call for the same (task, generation) is 138 //! refused before the existing call runs ([`FenceError::AlreadySubmitted`] 139 //! in this process; M2 also refuses a second `BeginCommit` once the task 140 //! left `Committable`, across restarts too because it is journaled). 141 //! Across restarts the existing durable guards 142 //! decide: the approved replay ledger (`approved_replay::claim`) refuses a 143 //! claimed approval for ever and answers an exact retry with 144 //! `ALREADY_COMMITTED` without a second run; `ComposeAuthorize` refuses a 145 //! used desk nonce and a live or spent grant (effects.rs `AlreadyAuthorized`, 146 //! `AlreadySpent`). A model `RunComposeTask` run has no such durable guard, 147 //! so this adapter does not offer it. 148 //! 149 //! Invalidation: after every delivered event, preparation results whose task 150 //! is no longer active at the generation they were made for are dropped. M2 151 //! returns consumers of a failed, cancelled, restarted or changed producer to 152 //! `Blocked` at a new generation (or `Aborted`), so their results go. A 153 //! result is also refused, not stored, when the task moved while the 154 //! operation ran. Results are never journaled: a restart discards them all. 155 //! 156 //! Resources: preparation runs on the caller's thread without the adapter 157 //! mutex, the compose home lock or the runtime spine lock. Only a 158 //! `Provisional` task with a live lease may prepare, and at most one 159 //! preparation per task is in flight, so concurrent preparations are bounded 160 //! by the M2 permits (`ResourceLimits::max_concurrency`). With 161 //! `ProvisionalConfig::enabled` false (the default) M2 dispatches a consumer 162 //! only after every producer is final, which is the sequential order. 163 //! 164 //! Not in scope: aien-trace is not used (observation is optional); no new 165 //! receipt type; AEGIS, World, KV and inference scheduling are unchanged. 166 //! spark-harness gains only the M2 `Committing` state and the 167 //! `BeginCommit`, `CommitOutcome` and `BindApproval` events. 168 169 use crate::approved::{ApprovedComposeReport, ApprovedProposal, ApprovedRefusal, ProposerHook}; 170 use crate::compose::ComposeBridge; 171 use crate::control::{ControlResponse, DeskProof}; 172 use crate::effects::MintRequest; 173 use aien_proof::lock::FileLock; 174 use parking_lot::Mutex; 175 use serde::Serialize; 176 use sha2::{Digest, Sha256}; 177 use spark_harness::completion::CONSUMED_DIR; 178 use spark_harness::execution::TaskState; 179 use spark_harness::readiness::{ 180 verify_final, ArtifactReadiness, OperationClass, ReadinessLevel, INTERFACE_DIR, 181 }; 182 use spark_harness::scheduler::{ 183 Clock, CommitResult, Event, EventKind, Outcome, PermitPool, ProvisionalConfig, SchedError, 184 Scheduler, 185 }; 186 use std::collections::{BTreeMap, BTreeSet, VecDeque}; 187 use std::fmt; 188 use std::path::{Path, PathBuf}; 189 190 /// The whitelist of early preparation operations. One entry. 191 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] 192 #[serde(rename_all = "snake_case")] 193 pub enum PrepOperation { 194 /// `compose::rederive::task_decision(goal, workspace)`: the compose 195 /// prompt and destination a goal would get. Reads the workspace only. 196 ComposePlanPreview, 197 } 198 199 impl PrepOperation { 200 /// The M2 operation class the scheduler gates this operation as. 201 pub fn class(self) -> OperationClass { 202 match self { 203 PrepOperation::ComposePlanPreview => OperationClass::ReadOnlyAnalysis, 204 } 205 } 206 207 pub fn as_str(self) -> &'static str { 208 match self { 209 PrepOperation::ComposePlanPreview => "compose_plan_preview", 210 } 211 } 212 } 213 214 /// One producer artifact a result or a fence decision rests on, copied from 215 /// a store-verified [`ArtifactReadiness`]. 216 #[derive(Debug, Clone, PartialEq, Eq, Serialize)] 217 pub struct ReadinessBinding { 218 pub producer_task: String, 219 pub source_commit: String, 220 pub producer_generation: u64, 221 pub artifact_digest: String, 222 pub receipt_id: String, 223 pub level: ReadinessLevel, 224 } 225 226 impl From<&ArtifactReadiness> for ReadinessBinding { 227 fn from(r: &ArtifactReadiness) -> Self { 228 ReadinessBinding { 229 producer_task: r.producer_task().to_string(), 230 source_commit: r.source_commit().to_string(), 231 producer_generation: r.producer_generation(), 232 artifact_digest: r.artifact_digest().to_string(), 233 receipt_id: r.receipt_id().to_string(), 234 level: r.level(), 235 } 236 } 237 } 238 239 /// A provisional preparation result. Built only by [`PrepAdapter::prepare`]; 240 /// no public constructor and no `Deserialize`. It authorizes nothing. 241 #[derive(Debug, Clone, PartialEq, Eq, Serialize)] 242 pub struct PreparationResult { 243 task: String, 244 generation: u64, 245 operation: PrepOperation, 246 class: OperationClass, 247 plan_sha256: String, 248 destination: Option, 249 bindings: Vec, 250 } 251 252 impl PreparationResult { 253 pub fn task(&self) -> &str { 254 &self.task 255 } 256 pub fn generation(&self) -> u64 { 257 self.generation 258 } 259 pub fn operation(&self) -> PrepOperation { 260 self.operation 261 } 262 pub fn class(&self) -> OperationClass { 263 self.class 264 } 265 /// sha256 hex of the compose prompt the goal would get. 266 pub fn plan_sha256(&self) -> &str { 267 &self.plan_sha256 268 } 269 pub fn destination(&self) -> Option<&str> { 270 self.destination.as_deref() 271 } 272 pub fn bindings(&self) -> &[ReadinessBinding] { 273 &self.bindings 274 } 275 /// True when at least one producer was only interface-verified. 276 pub fn is_provisional(&self) -> bool { 277 self.bindings 278 .iter() 279 .any(|b| b.level != ReadinessLevel::FinalVerified) 280 } 281 } 282 283 /// What the fence verified, inside the same critical section as the call. 284 #[derive(Debug, Clone, PartialEq, Eq, Serialize)] 285 pub struct FenceProof { 286 pub task: String, 287 pub generation: u64, 288 /// The task's own M1 completion. 289 pub completion: ReadinessBinding, 290 /// Every producer, final-verified (M2 `may_finalize`). 291 pub producers: Vec, 292 } 293 294 /// The existing call's own answer, plus the fence proof it ran under. The 295 /// answer may still be a refusal: the fence does not decide authorization. 296 #[derive(Debug)] 297 pub struct Fenced { 298 pub proof: FenceProof, 299 pub outcome: T, 300 /// How the M2 task ended (`CommitOutcome`), classified from `outcome`. 301 pub result: CommitResult, 302 /// Set when journaling the outcome failed: the task then stays 303 /// `Committing` (never re-run) until a restart marks it 304 /// `CommitUncertain`. 305 pub record_error: Option, 306 /// Deferred events delivered again right after the outcome. 307 pub redelivered: Vec, 308 /// Set when rewriting the deferred sidecar after the drain failed. The 309 /// sidecar then still lists events M2 already applied; replaying them 310 /// on open is a duplicate, or a stale generation that stays queued 311 /// until discarded. The next rewrite replaces it. 312 pub deferred_error: Option, 313 } 314 315 /// Most events [`PrepAdapter::deliver`] holds back while commits run. 316 pub const DEFERRED_CAPACITY: usize = 64; 317 318 /// Largest deferred sidecar [`PrepAdapter::open`] reads, in bytes. 319 pub const DEFERRED_MAX_BYTES: u64 = 4 * 1024 * 1024; 320 321 /// Suffix of the deferred-event sidecar, appended to the journal's full 322 /// file name. A journal whose name ends with it is refused by 323 /// [`PrepAdapter::open`], so no journal is another journal's sidecar. 324 pub const DEFERRED_SUFFIX: &str = ".deferred"; 325 326 /// The deferred-event sidecar of the M2 journal `journal`: 327 /// `.deferred`. Distinct journal paths give distinct sidecars. 328 pub fn deferred_journal_path(journal: &Path) -> PathBuf { 329 let mut name = journal.as_os_str().to_os_string(); 330 name.push(DEFERRED_SUFFIX); 331 PathBuf::from(name) 332 } 333 334 /// What [`PrepAdapter::deliver`] did with an event. 335 #[derive(Debug, Clone, PartialEq, Eq)] 336 pub enum Delivered { 337 /// M2 applied it, or recognised a duplicate. 338 Applied(Outcome), 339 /// M2 refused it because `committing` is committing. It is queued (at 340 /// position `queued`, from 1) and delivered again right after that 341 /// commit's outcome is recorded. 342 Deferred { committing: String, queued: usize }, 343 } 344 345 #[derive(Debug)] 346 pub enum DeliverError { 347 Scheduler(SchedError), 348 /// `BeginCommit`, `CommitOutcome` and `BindApproval` go only through the 349 /// fence and [`PrepAdapter::bind_approval`]. 350 FenceOnly(&'static str), 351 /// The deferred queue is full: the event was not queued and not 352 /// applied; deliver it again later. 353 DeferredFull { 354 committing: String, 355 capacity: usize, 356 }, 357 /// The deferred sidecar could not be written: the event was not queued 358 /// and not applied; deliver it again later. 359 DeferredJournal(String), 360 } 361 362 impl fmt::Display for DeliverError { 363 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 364 match self { 365 DeliverError::Scheduler(e) => write!(f, "DELIVER_REFUSED Scheduler: {e}"), 366 DeliverError::FenceOnly(k) => write!( 367 f, 368 "DELIVER_REFUSED FenceOnly: {k} events are delivered only by the fence" 369 ), 370 DeliverError::DeferredFull { 371 committing, 372 capacity, 373 } => write!( 374 f, 375 "DELIVER_REFUSED DeferredFull: task '{committing}' is committing and {capacity} events already wait; nothing was queued" 376 ), 377 DeliverError::DeferredJournal(e) => write!( 378 f, 379 "DELIVER_REFUSED DeferredJournal: the deferred queue could not be journaled ({e}); nothing was queued" 380 ), 381 } 382 } 383 } 384 385 impl std::error::Error for DeliverError {} 386 387 /// One deferred event delivered again after a commit outcome. 388 #[derive(Debug)] 389 pub struct Redelivered { 390 pub id: String, 391 pub result: Result, 392 } 393 394 #[derive(Debug)] 395 pub enum PrepError { 396 Scheduler(SchedError), 397 /// The caller's generation is not the task's current one. 398 StaleGeneration { 399 task: String, 400 expected: u64, 401 current: Option, 402 }, 403 /// A preparation for this task is already running. 404 Busy(String), 405 /// The task moved (revoked, cancelled, re-dispatched) while the 406 /// operation ran; the result was discarded. 407 Revoked { 408 task: String, 409 detail: String, 410 }, 411 /// The operation itself refused (for example a workspace escape). 412 Operation(String), 413 } 414 415 impl fmt::Display for PrepError { 416 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 417 match self { 418 PrepError::Scheduler(e) => write!(f, "PREP_REFUSED Scheduler: {e}"), 419 PrepError::StaleGeneration { 420 task, 421 expected, 422 current, 423 } => write!( 424 f, 425 "PREP_REFUSED StaleGeneration: task '{task}' asked at generation {expected}, scheduler has {current:?}" 426 ), 427 PrepError::Busy(t) => write!(f, "PREP_REFUSED Busy: task '{t}' is already preparing"), 428 PrepError::Revoked { task, detail } => { 429 write!(f, "PREP_REFUSED Revoked: task '{task}': {detail}; result discarded") 430 } 431 PrepError::Operation(e) => write!(f, "PREP_REFUSED Operation: {e}"), 432 } 433 } 434 } 435 436 impl std::error::Error for PrepError {} 437 438 #[derive(Debug)] 439 pub enum FenceError { 440 /// M2 refused (`may_finalize`, unknown task). 441 Scheduler(SchedError), 442 StaleGeneration { 443 task: String, 444 expected: u64, 445 current: Option, 446 }, 447 NotCommittable { 448 task: String, 449 state: TaskState, 450 }, 451 /// The task has no accepted M1 completion for its current generation. 452 NoCompletion(String), 453 /// The task's own M1 completion receipt no longer verifies. 454 CompletionInvalid { 455 task: String, 456 error: String, 457 }, 458 /// This process already ran the fenced call for this task generation. 459 AlreadySubmitted { 460 task: String, 461 generation: u64, 462 }, 463 StoreLock(String), 464 } 465 466 impl fmt::Display for FenceError { 467 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 468 match self { 469 FenceError::Scheduler(e) => write!(f, "FENCE_REFUSED Scheduler: {e}"), 470 FenceError::StaleGeneration { 471 task, 472 expected, 473 current, 474 } => write!( 475 f, 476 "FENCE_REFUSED StaleGeneration: task '{task}' asked at generation {expected}, scheduler has {current:?}" 477 ), 478 FenceError::NotCommittable { task, state } => write!( 479 f, 480 "FENCE_REFUSED NotCommittable: task '{task}' is {}", 481 state.as_str() 482 ), 483 FenceError::NoCompletion(t) => { 484 write!(f, "FENCE_REFUSED NoCompletion: task '{t}' has no accepted M1 completion") 485 } 486 FenceError::CompletionInvalid { task, error } => { 487 write!(f, "FENCE_REFUSED CompletionInvalid: task '{task}': {error}") 488 } 489 FenceError::AlreadySubmitted { task, generation } => write!( 490 f, 491 "FENCE_REFUSED AlreadySubmitted: task '{task}' generation {generation} already ran its fenced call" 492 ), 493 FenceError::StoreLock(e) => write!(f, "FENCE_REFUSED StoreLock: {e}"), 494 } 495 } 496 } 497 498 impl std::error::Error for FenceError {} 499 500 #[cfg(feature = "test-support")] 501 type PrepHook = std::sync::Arc; 502 503 struct Inner { 504 sched: Scheduler, 505 prepared: BTreeMap, 506 in_flight: BTreeSet, 507 submitted: BTreeSet<(String, u64)>, 508 /// Events M2 refused with `CommitInProgress`, oldest first. 509 deferred: VecDeque, 510 /// Where `deferred` is journaled (journaled schedulers only). 511 deferred_path: Option, 512 /// What replaying the journaled deferred events on open did. 513 replayed: Vec, 514 } 515 516 impl Inner { 517 fn current_generation(&self, task: &str, expected: u64) -> Result<(), Option> { 518 match self.sched.generation(task) { 519 Some(g) if g == expected => Ok(()), 520 other => Err(other), 521 } 522 } 523 524 /// Drop every result whose task is no longer active at its generation. 525 fn prune(&mut self) { 526 let sched = &self.sched; 527 self.prepared.retain(|task, r| { 528 sched 529 .task(task) 530 .is_some_and(|t| t.state.is_active() && t.generation == r.generation) 531 }); 532 } 533 534 /// Deliver every deferred event again, oldest first. Only an event M2 535 /// applied or answered as a duplicate leaves the queue; one still 536 /// refused by a running commit stays queued silently, and one refused 537 /// for any other reason stays queued and is returned with its refusal. 538 /// The sidecar is rewritten when anything left the queue; the error, if 539 /// that failed, is returned too. 540 fn redeliver(&mut self) -> (Vec, Option) { 541 let mut out = Vec::new(); 542 let mut keep = VecDeque::new(); 543 let before = self.deferred.len(); 544 while let Some(ev) = self.deferred.pop_front() { 545 match self.sched.deliver(ev.clone()) { 546 Err(SchedError::CommitInProgress { .. }) => keep.push_back(ev), 547 Ok(o) => out.push(Redelivered { 548 id: ev.id, 549 result: Ok(o), 550 }), 551 Err(e) => { 552 out.push(Redelivered { 553 id: ev.id.clone(), 554 result: Err(e), 555 }); 556 keep.push_back(ev); 557 } 558 } 559 } 560 self.deferred = keep; 561 self.prune(); 562 let error = if self.deferred.len() == before { 563 None 564 } else { 565 self.persist_deferred().err() 566 }; 567 (out, error) 568 } 569 570 /// Rewrite the sidecar from `deferred` (no-op without a journal). 571 fn persist_deferred(&self) -> Result<(), String> { 572 let Some(path) = &self.deferred_path else { 573 return Ok(()); 574 }; 575 let mut buf = String::new(); 576 for ev in &self.deferred { 577 buf.push_str(&serde_json::to_string(ev).map_err(|e| e.to_string())?); 578 buf.push('\n'); 579 } 580 write_atomic(path, buf.as_bytes()).map_err(|e| format!("{}: {e}", path.display())) 581 } 582 } 583 584 /// Temp file in the same directory, fsync, rename over `path`, fsync the 585 /// directory. The temp file is removed on failure. 586 fn write_atomic(path: &Path, bytes: &[u8]) -> std::io::Result<()> { 587 use std::io::Write; 588 let dir = path.parent().ok_or_else(|| { 589 std::io::Error::new( 590 std::io::ErrorKind::InvalidInput, 591 "sidecar has no parent dir", 592 ) 593 })?; 594 let name = path 595 .file_name() 596 .map(|n| n.to_string_lossy().into_owned()) 597 .unwrap_or_default(); 598 let tmp = dir.join(format!(".{name}.tmp-{}", std::process::id())); 599 let result = (|| -> std::io::Result<()> { 600 let mut f = std::fs::File::create(&tmp)?; 601 f.write_all(bytes)?; 602 f.sync_all()?; 603 std::fs::rename(&tmp, path)?; 604 std::fs::File::open(dir)?.sync_all() 605 })(); 606 if result.is_err() { 607 let _ = std::fs::remove_file(&tmp); 608 } 609 result 610 } 611 612 /// Read the deferred sidecar: absent is empty; anything that does not 613 /// parse, is too large, holds too many events or holds a fence-only event 614 /// is an error. 615 fn read_deferred(path: &Path) -> Result, SchedError> { 616 let bad = |what: String| SchedError::Journal(format!("{}: {what}", path.display())); 617 let len = match std::fs::metadata(path) { 618 Ok(m) => m.len(), 619 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(VecDeque::new()), 620 Err(e) => return Err(bad(e.to_string())), 621 }; 622 if len > DEFERRED_MAX_BYTES { 623 return Err(bad(format!( 624 "{len} bytes, more than the {DEFERRED_MAX_BYTES} a deferred queue may hold" 625 ))); 626 } 627 let text = std::fs::read_to_string(path).map_err(|e| bad(e.to_string()))?; 628 let mut out = VecDeque::new(); 629 for (n, line) in text.lines().enumerate() { 630 if out.len() == DEFERRED_CAPACITY { 631 return Err(bad(format!( 632 "more than {DEFERRED_CAPACITY} deferred events" 633 ))); 634 } 635 let ev: Event = 636 serde_json::from_str(line).map_err(|e| bad(format!("line {}: {e}", n + 1)))?; 637 if fence_only(&ev.kind).is_some() { 638 return Err(bad(format!("line {}: a fence-only event", n + 1))); 639 } 640 out.push_back(ev); 641 } 642 Ok(out) 643 } 644 645 /// `journal` with its directory (created if missing) and, when it exists, 646 /// the file itself resolved to canonical form, so every path to one journal 647 /// names the same lock file and sidecar. A name ending with 648 /// [`DEFERRED_SUFFIX`] is refused. 649 fn canonical_journal(journal: &Path) -> Result { 650 let bad = |what: String| SchedError::Journal(format!("{}: {what}", journal.display())); 651 let name = journal 652 .file_name() 653 .ok_or_else(|| bad("a journal path needs a file name".to_string()))?; 654 let dir = journal 655 .parent() 656 .filter(|d| !d.as_os_str().is_empty()) 657 .unwrap_or(Path::new(".")); 658 std::fs::create_dir_all(dir).map_err(|e| bad(e.to_string()))?; 659 let dir = std::fs::canonicalize(dir).map_err(|e| bad(e.to_string()))?; 660 let path = match std::fs::canonicalize(dir.join(name)) { 661 Ok(p) => p, 662 Err(e) if e.kind() == std::io::ErrorKind::NotFound => dir.join(name), 663 Err(e) => return Err(bad(e.to_string())), 664 }; 665 if path 666 .as_os_str() 667 .to_string_lossy() 668 .ends_with(DEFERRED_SUFFIX) 669 { 670 return Err(bad(format!( 671 "a journal name may not end with {DEFERRED_SUFFIX}, the deferred sidecar suffix" 672 ))); 673 } 674 Ok(path) 675 } 676 677 /// The fence's own event kinds, which only the fence delivers. 678 fn fence_only(kind: &EventKind) -> Option<&'static str> { 679 match kind { 680 EventKind::BeginCommit { .. } => Some("begin_commit"), 681 EventKind::CommitOutcome { .. } => Some("commit_outcome"), 682 EventKind::BindApproval { .. } => Some("bind_approval"), 683 _ => None, 684 } 685 } 686 687 /// The adapter: owns the M2 scheduler for engineering tasks and fences the 688 /// existing compose commit calls. Share it behind an `Arc`; every method 689 /// takes `&self`. 690 pub struct PrepAdapter { 691 inner: Mutex, 692 store: PathBuf, 693 #[cfg(feature = "test-support")] 694 prep_hook: Mutex>, 695 #[cfg(feature = "test-support")] 696 begin_hook: Mutex>, 697 } 698 699 impl PrepAdapter { 700 fn with_scheduler(sched: Scheduler, store: &Path, deferred_path: Option) -> Self { 701 PrepAdapter { 702 inner: Mutex::new(Inner { 703 sched, 704 prepared: BTreeMap::new(), 705 in_flight: BTreeSet::new(), 706 submitted: BTreeSet::new(), 707 deferred: VecDeque::new(), 708 deferred_path, 709 replayed: Vec::new(), 710 }), 711 store: store.to_path_buf(), 712 #[cfg(feature = "test-support")] 713 prep_hook: Mutex::new(None), 714 #[cfg(feature = "test-support")] 715 begin_hook: Mutex::new(None), 716 } 717 } 718 719 /// In-memory scheduler over the harness store `store` 720 /// (`HarnessEngine::completion_store`). 721 pub fn new(cfg: ProvisionalConfig, store: &Path, clock: Clock) -> Result { 722 Ok(Self::with_scheduler( 723 Scheduler::new(cfg, store, clock)?, 724 store, 725 None, 726 )) 727 } 728 729 /// Journaled scheduler: create or replay `journal`, then run the M2 730 /// audit before anything can use it (it settles every interrupted 731 /// commit as `CommitUncertain`), then deliver the journaled deferred 732 /// events again ([`PrepAdapter::take_replayed_deferred`]). Returns the 733 /// tasks the audit revoked. No preparation result survives: they are 734 /// never journaled. 735 pub fn open( 736 cfg: ProvisionalConfig, 737 store: &Path, 738 journal: &Path, 739 clock: Clock, 740 ) -> Result<(Self, Vec), SchedError> { 741 let journal = canonical_journal(journal)?; 742 let (unaudited, _report) = Scheduler::open(cfg, store, &journal, clock)?; 743 // The M2 journal lock is held from here on, for the adapter's life: 744 // no other adapter reads or writes this sidecar. 745 let path = deferred_journal_path(&journal); 746 let deferred = read_deferred(&path)?; 747 let (sched, revoked) = unaudited.audit()?; 748 let adapter = Self::with_scheduler(sched, store, Some(path)); 749 { 750 let mut g = adapter.inner.lock(); 751 g.deferred = deferred; 752 // No commit is running after the audit, so every event is 753 // delivered; the refused ones stay queued, and the sidecar is 754 // rewritten if anything left. If that rewrite fails the open 755 // fails: the next open replays the same events. M2 answers the 756 // ones already applied as duplicates, or, once their generation 757 // moved on, refuses them as stale; refused ones stay queued. 758 let (replayed, error) = g.redeliver(); 759 if let Some(e) = error { 760 return Err(SchedError::Journal(e)); 761 } 762 g.replayed = replayed; 763 } 764 Ok((adapter, revoked)) 765 } 766 767 /// What delivering the journaled deferred events on open did, oldest 768 /// first. Taken once; later calls return nothing. 769 pub fn take_replayed_deferred(&self) -> Vec { 770 std::mem::take(&mut self.inner.lock().replayed) 771 } 772 773 /// The runtime enable flag: M2 `ProvisionalConfig::enabled` (default 774 /// false, which is sequential dispatch). 775 pub fn enabled(&self) -> bool { 776 self.inner.lock().sched.config().enabled 777 } 778 779 /// Deliver one M2 event, then drop the preparation results it 780 /// invalidated. An event M2 refuses because a commit is running is 781 /// queued and delivered again after that commit's outcome (see the 782 /// module docs). The fence's own event kinds are refused here. 783 pub fn deliver(&self, event: Event) -> Result { 784 if let Some(kind) = fence_only(&event.kind) { 785 return Err(DeliverError::FenceOnly(kind)); 786 } 787 let mut g = self.inner.lock(); 788 let r = g.sched.deliver(event.clone()); 789 g.prune(); 790 match r { 791 Ok(o) => Ok(Delivered::Applied(o)), 792 Err(SchedError::CommitInProgress { committing, .. }) => { 793 if let Some(i) = g.deferred.iter().position(|e| e.id == event.id) { 794 return if g.deferred[i] == event { 795 Ok(Delivered::Deferred { 796 committing, 797 queued: i + 1, 798 }) 799 } else { 800 Err(DeliverError::Scheduler(SchedError::EventIdConflict( 801 event.id, 802 ))) 803 }; 804 } 805 if g.deferred.len() >= DEFERRED_CAPACITY { 806 return Err(DeliverError::DeferredFull { 807 committing, 808 capacity: DEFERRED_CAPACITY, 809 }); 810 } 811 g.deferred.push_back(event); 812 // Journaled before `Deferred` is returned, so a crash 813 // before the drain still delivers it on the next open. 814 if let Err(e) = g.persist_deferred() { 815 g.deferred.pop_back(); 816 return Err(DeliverError::DeferredJournal(e)); 817 } 818 Ok(Delivered::Deferred { 819 committing, 820 queued: g.deferred.len(), 821 }) 822 } 823 Err(e) => Err(DeliverError::Scheduler(e)), 824 } 825 } 826 827 /// How many deferred events are queued: waiting for a commit outcome, 828 /// or refused on redelivery and kept until discarded. 829 pub fn deferred_len(&self) -> usize { 830 self.inner.lock().deferred.len() 831 } 832 833 /// The queued deferred events, oldest first. 834 pub fn deferred_events(&self) -> Vec { 835 self.inner.lock().deferred.iter().cloned().collect() 836 } 837 838 /// Remove the queued deferred event `id` (the caller's decision about 839 /// an event M2 keeps refusing) and rewrite the sidecar. `Ok(None)` when 840 /// no such event is queued. If the rewrite fails the event stays queued 841 /// and the error is returned. 842 pub fn discard_deferred(&self, id: &str) -> Result, DeliverError> { 843 let mut g = self.inner.lock(); 844 let Some(i) = g.deferred.iter().position(|e| e.id == id) else { 845 return Ok(None); 846 }; 847 let ev = g.deferred.remove(i).expect("position is in range"); 848 if let Err(e) = g.persist_deferred() { 849 g.deferred.insert(i, ev); 850 return Err(DeliverError::DeferredJournal(e)); 851 } 852 Ok(Some(ev)) 853 } 854 855 /// Read-only access to the scheduler (state, generations, invariants, 856 /// timing trace). Holds the adapter mutex while `f` runs. 857 pub fn inspect(&self, f: impl FnOnce(&Scheduler) -> T) -> T { 858 f(&self.inner.lock().sched) 859 } 860 861 pub fn state(&self, task: &str) -> Option { 862 self.inner.lock().sched.state(task) 863 } 864 865 pub fn generation(&self, task: &str) -> Option { 866 self.inner.lock().sched.generation(task) 867 } 868 869 pub fn permits_in_use(&self) -> PermitPool { 870 self.inner.lock().sched.permits_in_use() 871 } 872 873 /// The task's current preparation result, if it is still valid. 874 pub fn prepared(&self, task: &str) -> Option { 875 self.inner.lock().prepared.get(task).cloned() 876 } 877 878 /// Test seam: called between the admission check and the operation, 879 /// outside the adapter mutex. 880 #[cfg(feature = "test-support")] 881 pub fn set_prep_hook(&self, hook: Option) { 882 *self.prep_hook.lock() = hook; 883 } 884 885 /// Run the whitelisted operation for `task` at `generation`. Admission: 886 /// current generation, no preparation in flight for the task, and M2 887 /// `may_start(task, ReadOnlyAnalysis)` (a `Provisional` task with a live 888 /// lease, every producer bound at its current generation and 889 /// store-verified at a level that permits the class). The operation runs 890 /// outside the mutex; the result is stored only if the task is still at 891 /// the same generation and `may_start` passes again, both checked under 892 /// the mutex that stores it. 893 pub fn prepare( 894 &self, 895 task: &str, 896 generation: u64, 897 goal: &str, 898 workspace: &Path, 899 ) -> Result { 900 let op = PrepOperation::ComposePlanPreview; 901 { 902 let mut g = self.inner.lock(); 903 g.current_generation(task, generation).map_err(|current| { 904 PrepError::StaleGeneration { 905 task: task.to_string(), 906 expected: generation, 907 current, 908 } 909 })?; 910 if g.in_flight.contains(task) { 911 return Err(PrepError::Busy(task.to_string())); 912 } 913 g.sched 914 .may_start(task, op.class()) 915 .map_err(PrepError::Scheduler)?; 916 g.in_flight.insert(task.to_string()); 917 } 918 #[cfg(feature = "test-support")] 919 { 920 let hook = self.prep_hook.lock().clone(); 921 if let Some(h) = hook { 922 h(task); 923 } 924 } 925 let out = plan_preview(goal, workspace); 926 let mut g = self.inner.lock(); 927 g.in_flight.remove(task); 928 let (plan_sha256, destination) = out.map_err(PrepError::Operation)?; 929 let revoked = |detail: String| PrepError::Revoked { 930 task: task.to_string(), 931 detail, 932 }; 933 g.current_generation(task, generation).map_err(|current| { 934 revoked(format!( 935 "generation moved from {generation} to {current:?} during preparation" 936 )) 937 })?; 938 // No separate binding comparison: M2 sets a task's bindings only when 939 // it dispatches it, and leaving `Provisional` always moves the task to 940 // a new generation first, so an unchanged generation means unchanged 941 // bindings. The readiness recorded below is the fresh one. 942 let readiness = g 943 .sched 944 .may_start(task, op.class()) 945 .map_err(|e| revoked(e.to_string()))?; 946 let result = PreparationResult { 947 task: task.to_string(), 948 generation, 949 operation: op, 950 class: op.class(), 951 plan_sha256, 952 destination, 953 bindings: readiness.iter().map(ReadinessBinding::from).collect(), 954 }; 955 g.prepared.insert(task.to_string(), result.clone()); 956 Ok(result) 957 } 958 959 /// The harness store locks every interface and completion writer takes. 960 fn store_locks(&self) -> Result<[FileLock; 2], FenceError> { 961 let lock = |dir: &str| { 962 let d = self.store.join(dir); 963 std::fs::create_dir_all(&d) 964 .and_then(|_| FileLock::acquire(&d.join(".lock"))) 965 .map_err(|e| FenceError::StoreLock(format!("{}: {e}", d.display()))) 966 }; 967 Ok([lock(INTERFACE_DIR)?, lock(CONSUMED_DIR)?]) 968 } 969 970 /// The fence (see the module docs). Under the adapter mutex and the store 971 /// locks: every check, then the journaled M2 `BeginCommit`, which moves 972 /// the task to `Committing` and freezes its inputs. Both locks are 973 /// released before `commit` runs. Its result, classified by `classify`, 974 /// is journaled as the M2 `CommitOutcome`, and the deferred events are 975 /// delivered again. A panic in `commit` is recorded as `Uncertain` and 976 /// then resumed. 977 fn fenced( 978 &self, 979 task: &str, 980 generation: u64, 981 commit: impl FnOnce(&FenceProof) -> T, 982 classify: impl FnOnce(&T) -> CommitResult, 983 ) -> Result, FenceError> { 984 let proof = self.begin_commit(task, generation)?; 985 let ran = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| commit(&proof))); 986 let result = match &ran { 987 Ok(v) => classify(v), 988 Err(_) => CommitResult::Uncertain { 989 reason: "the fenced call panicked".to_string(), 990 }, 991 }; 992 let (recorded, redelivered, deferred_error) = 993 self.record_outcome(task, generation, result.clone()); 994 match ran { 995 Ok(outcome) => Ok(Fenced { 996 proof, 997 outcome, 998 result, 999 record_error: recorded.err(), 1000 redelivered, 1001 deferred_error, 1002 }), 1003 Err(panic) => std::panic::resume_unwind(panic), 1004 } 1005 } 1006 1007 /// Check and transition, atomically: the fence checks and the journaled 1008 /// `BeginCommit` under the adapter mutex and both store locks. 1009 fn begin_commit(&self, task: &str, generation: u64) -> Result { 1010 let mut g = self.inner.lock(); 1011 let _store = self.store_locks()?; 1012 let key = (task.to_string(), generation); 1013 let submitted = || FenceError::AlreadySubmitted { 1014 task: task.to_string(), 1015 generation, 1016 }; 1017 if g.submitted.contains(&key) { 1018 return Err(submitted()); 1019 } 1020 g.current_generation(task, generation) 1021 .map_err(|current| FenceError::StaleGeneration { 1022 task: task.to_string(), 1023 expected: generation, 1024 current, 1025 })?; 1026 let entry = g 1027 .sched 1028 .task(task) 1029 .ok_or_else(|| FenceError::Scheduler(SchedError::UnknownTask(task.to_string())))?; 1030 if entry.state != TaskState::Committable { 1031 return Err(FenceError::NotCommittable { 1032 task: task.to_string(), 1033 state: entry.state, 1034 }); 1035 } 1036 let claim = entry 1037 .completion 1038 .clone() 1039 .ok_or_else(|| FenceError::NoCompletion(task.to_string()))?; 1040 let mut inputs = BTreeMap::new(); 1041 for p in entry.bindings.keys() { 1042 let c = g.sched.task(p).and_then(|t| t.completion.clone()); 1043 inputs.insert( 1044 p.clone(), 1045 c.ok_or_else(|| FenceError::NoCompletion(p.clone()))?, 1046 ); 1047 } 1048 let producers = g.sched.may_finalize(task).map_err(FenceError::Scheduler)?; 1049 let own = verify_final(&self.store, task, generation, &claim).map_err(|e| { 1050 FenceError::CompletionInvalid { 1051 task: task.to_string(), 1052 error: e.to_string(), 1053 } 1054 })?; 1055 #[cfg(feature = "test-support")] 1056 if let Some(hook) = self.begin_hook.lock().clone() { 1057 hook(task); 1058 } 1059 let begin = Event { 1060 id: event_id("begin", task, generation), 1061 kind: EventKind::BeginCommit { 1062 task: task.to_string(), 1063 generation, 1064 completion: claim, 1065 producers: inputs, 1066 }, 1067 }; 1068 // M2 re-runs `may_finalize` and `verify_final` here 1069 // (still under both locks), checks the inputs equal its state, 1070 // refuses a second commit in the same chain, and journals the 1071 // transition. 1072 match g.sched.deliver(begin).map_err(FenceError::Scheduler)? { 1073 Outcome::Applied(_) => {} 1074 Outcome::Duplicate => return Err(submitted()), 1075 } 1076 // Spent before the call: a call that fails or panics is not retried 1077 // at this generation (fail closed). 1078 g.submitted.insert(key); 1079 g.prune(); 1080 Ok(FenceProof { 1081 task: task.to_string(), 1082 generation, 1083 completion: ReadinessBinding::from(&own), 1084 producers: producers.iter().map(ReadinessBinding::from).collect(), 1085 }) 1086 } 1087 1088 /// Journal the commit outcome, then deliver the deferred events again, 1089 /// under one lock. If journaling fails the task stays `Committing` 1090 /// (frozen, never re-run) until a restart settles it as 1091 /// `CommitUncertain`, and the deferred events refused by it stay queued 1092 /// (in the sidecar too, so that open delivers them after the settle). 1093 fn record_outcome( 1094 &self, 1095 task: &str, 1096 generation: u64, 1097 outcome: CommitResult, 1098 ) -> (Result<(), SchedError>, Vec, Option) { 1099 let mut g = self.inner.lock(); 1100 let r = g.sched.deliver(Event { 1101 id: event_id("outcome", task, generation), 1102 kind: EventKind::CommitOutcome { 1103 task: task.to_string(), 1104 generation, 1105 outcome, 1106 }, 1107 }); 1108 g.prune(); 1109 let (redelivered, deferred_error) = g.redeliver(); 1110 (r.map(|_| ()), redelivered, deferred_error) 1111 } 1112 1113 /// Fenced `ComposeApprovedProposal`: the existing proposer hook (verify, 1114 /// desk MAC, replay claim, compose run with AEGIS verify and World 1115 /// commit, grant) runs unchanged once the fence passes. 1116 pub fn submit_approved( 1117 &self, 1118 task: &str, 1119 generation: u64, 1120 hook: &ProposerHook, 1121 proposal: &ApprovedProposal, 1122 workspace: &str, 1123 ) -> Result>>, FenceError> { 1124 self.fenced( 1125 task, 1126 generation, 1127 |_| hook.submit(proposal, workspace), 1128 classify_approved, 1129 ) 1130 } 1131 1132 /// Fenced `ComposeAuthorize`, the grant against a compose commit an 1133 /// unfenced `RunComposeTask` recorded: the existing grant minting (desk 1134 /// MAC, compose-commit record match, confinement, nonce and grant 1135 /// replay rules) runs unchanged once the fence passes. 1136 pub fn authorize( 1137 &self, 1138 task: &str, 1139 generation: u64, 1140 bridge: &ComposeBridge, 1141 req: &MintRequest, 1142 desk_proof: Option<&DeskProof>, 1143 objective_id: Option<&str>, 1144 ) -> Result, FenceError> { 1145 self.fenced( 1146 task, 1147 generation, 1148 |_| crate::effects::authorize_with_objective(bridge, req, desk_proof, objective_id), 1149 classify_authorize, 1150 ) 1151 } 1152 1153 /// Bind a control request to the M2 task generation whose fence it must 1154 /// pass, as a journaled M2 `BindApproval`, so the binding survives a 1155 /// restart. Only bound requests are fenced; the daemon runs every other 1156 /// request exactly as before. A later binding for the same key replaces 1157 /// the earlier one. M2 refuses a stale generation, a task whose commit 1158 /// ended and a new key past the task's `MAX_APPROVAL_BINDINGS_PER_TASK`; 1159 /// it drops the binding only when the task's commit ends (an aborted or 1160 /// retried task keeps it, see the module docs). 1161 pub fn bind_approval( 1162 &self, 1163 key: FenceKey, 1164 task: &str, 1165 generation: u64, 1166 ) -> Result { 1167 let encoded = key.encoded(); 1168 // Task ids hold no control characters, so the NUL separator keeps 1169 // (key, task) pairs distinct. 1170 let id = event_id("bind", &format!("{encoded}\0{task}"), generation); 1171 let mut g = self.inner.lock(); 1172 let r = g.sched.deliver(Event { 1173 id, 1174 kind: EventKind::BindApproval { 1175 key: encoded, 1176 task: task.to_string(), 1177 generation, 1178 }, 1179 }); 1180 g.prune(); 1181 r 1182 } 1183 1184 /// The task generation `key` is bound to, if any (M2 state, so it 1185 /// includes bindings replayed from the journal). 1186 pub fn binding(&self, key: &FenceKey) -> Option<(String, u64)> { 1187 let g = self.inner.lock(); 1188 let b = g.sched.approval(&key.encoded())?; 1189 Some((b.task.clone(), b.generation)) 1190 } 1191 1192 /// Daemon entry for `ComposeApprovedProposal`. None when the approval is 1193 /// not bound (the caller runs the original call). A fence refusal is a 1194 /// `FENCE_REFUSED` error and nothing runs. 1195 pub fn route_approved( 1196 &self, 1197 bridge: &std::sync::Arc, 1198 proposal: &ApprovedProposal, 1199 workspace: &str, 1200 ) -> Option { 1201 let (task, generation) = self.binding(&FenceKey::Approval(proposal.approval_id.clone()))?; 1202 let hook = ProposerHook::new(bridge.clone()); 1203 Some( 1204 match self.submit_approved(&task, generation, &hook, proposal, workspace) { 1205 Ok(f) => match f.outcome { 1206 Ok(r) => ControlResponse::ComposeApprovedResult(Box::new(r)), 1207 Err(r) => ControlResponse::ComposeApprovedRefused(r), 1208 }, 1209 Err(e) => ControlResponse::Error(e.to_string()), 1210 }, 1211 ) 1212 } 1213 1214 /// Daemon entry for `ComposeAuthorize`, keyed by the proposal digest. 1215 /// None when it is not bound (the caller runs the original call). 1216 pub fn route_authorize( 1217 &self, 1218 bridge: &ComposeBridge, 1219 req: &MintRequest, 1220 desk_proof: Option<&DeskProof>, 1221 objective_id: Option<&str>, 1222 ) -> Option { 1223 let (task, generation) = self.binding(&FenceKey::Proposal(req.proposal_sha256.clone()))?; 1224 Some( 1225 match self.authorize(&task, generation, bridge, req, desk_proof, objective_id) { 1226 Ok(f) => f.outcome, 1227 Err(e) => ControlResponse::Error(e.to_string()), 1228 }, 1229 ) 1230 } 1231 1232 /// Test seam: the fence around an arbitrary call, so a test can act 1233 /// while the call runs. `classify` maps its result to the outcome M2 1234 /// records. 1235 #[cfg(feature = "test-support")] 1236 pub fn fenced_for_tests( 1237 &self, 1238 task: &str, 1239 generation: u64, 1240 commit: impl FnOnce(&FenceProof) -> T, 1241 classify: impl FnOnce(&T) -> CommitResult, 1242 ) -> Result, FenceError> { 1243 self.fenced(task, generation, commit, classify) 1244 } 1245 1246 /// Test seam: called inside `begin_commit` after every check and before 1247 /// the journaled `BeginCommit`, with the adapter mutex and both store 1248 /// locks held. 1249 #[cfg(feature = "test-support")] 1250 pub fn set_begin_hook(&self, hook: Option) { 1251 *self.begin_hook.lock() = hook; 1252 } 1253 } 1254 1255 /// Which control request a binding fences. 1256 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] 1257 pub enum FenceKey { 1258 /// `ComposeApprovedProposal`, by `ApprovedProposal::approval_id`. 1259 Approval(String), 1260 /// `ComposeAuthorize`, by `MintRequest::proposal_sha256`. 1261 Proposal(String), 1262 } 1263 1264 impl FenceKey { 1265 /// The M2 binding key: the request kind and its id. 1266 pub fn encoded(&self) -> String { 1267 match self { 1268 FenceKey::Approval(id) => format!("approval:{id}"), 1269 FenceKey::Proposal(sha) => format!("proposal:{sha}"), 1270 } 1271 } 1272 } 1273 1274 /// A scheduler event id for this task generation: a fixed prefix and a 1275 /// digest, so any task id fits the M2 identifier limit. 1276 fn event_id(kind: &str, task: &str, generation: u64) -> String { 1277 let mut h = Sha256::new(); 1278 h.update(task.as_bytes()); 1279 h.update([0]); 1280 h.update(generation.to_be_bytes()); 1281 let hex: String = h.finalize().iter().map(|b| format!("{b:02x}")).collect(); 1282 format!("m3-{kind}-{hex}") 1283 } 1284 1285 /// What an approved submission did. Ok: committed (`COMMITTED`, or 1286 /// `ALREADY_COMMITTED` for an exact retry). A refusal without a replay 1287 /// claim came before `approved_replay::claim` (approved.rs `submit`: 1288 /// verify, desk MAC, confinement, bound requirements): nothing durable. 1289 /// `NotCommitted`: the ledger recorded `fail` (the World did not commit). 1290 /// Anything else after a claim may have reached the World: uncertain. 1291 pub fn classify_approved(r: &Result>) -> CommitResult { 1292 match r { 1293 Ok(report) => CommitResult::Committed { 1294 detail: report.state.clone(), 1295 }, 1296 Err(e) if e.replay_claim.is_none() || e.name == "NotCommitted" => CommitResult::Failed { 1297 reason: e.to_string(), 1298 }, 1299 Err(e) => CommitResult::Uncertain { 1300 reason: e.to_string(), 1301 }, 1302 } 1303 } 1304 1305 /// What `ComposeAuthorize` did. `ComposeNoted`: the grant was written. 1306 /// `EFFECT_REFUSED`: refused by name before the only write (effects.rs 1307 /// `authorize_inner`, every refusal precedes its `append`): nothing durable. 1308 /// Any other error (for example a failed `append` or re-read) may have 1309 /// written: uncertain. 1310 pub fn classify_authorize(r: &ControlResponse) -> CommitResult { 1311 match r { 1312 ControlResponse::ComposeNoted(n) => CommitResult::Committed { 1313 detail: format!("grant {}", n.id), 1314 }, 1315 ControlResponse::Error(e) if e.starts_with("EFFECT_REFUSED ") => { 1316 CommitResult::Failed { reason: e.clone() } 1317 } 1318 other => CommitResult::Uncertain { 1319 reason: format!("{other:?}").chars().take(512).collect(), 1320 }, 1321 } 1322 } 1323 1324 /// The whitelisted operation: compose prompt digest and destination. 1325 fn plan_preview(goal: &str, workspace: &Path) -> Result<(String, Option), String> { 1326 let ((prompt, _edit, _kind), destination) = 1327 crate::compose::rederive::task_decision(goal, workspace)?; 1328 let digest = Sha256::digest(prompt.as_bytes()); 1329 let hex: String = digest.iter().map(|b| format!("{b:02x}")).collect(); 1330 Ok((hex, destination)) 1331 } 1332 1333 #[cfg(test)] 1334 mod tests { 1335 use super::*; 1336 1337 #[test] 1338 fn the_whitelist_is_one_reversible_preparation_class() { 1339 let op = PrepOperation::ComposePlanPreview; 1340 assert_eq!(op.class(), OperationClass::ReadOnlyAnalysis); 1341 assert!(op.class().is_reversible_preparation()); 1342 assert!(ReadinessLevel::InterfaceVerified.permits(op.class())); 1343 assert_eq!(op.as_str(), "compose_plan_preview"); 1344 } 1345 }