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/approved_replay.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 / approved_replay.rs` 573 lines ยท 21457 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 //! Restart-safe replay protection for approved proposals (sovereign-core #249, part B). 17 //! 18 //! Every approved submission is claimed in the compose home's Cortex journal 19 //! BEFORE anything runs, and its lifecycle is written there as host records of 20 //! kind `effect` with an `approved_submission` field (never a `phase`, so the 21 //! effect ledger of crate::effects ignores them; ComposeNote cannot forge them, 22 //! see effects::check_reserved_note): 23 //! 24 //! accepted the claim: approval key, request id, approval id, trace id, 25 //! the claiming process (pid + start ticks). Durable before return. 26 //! in_flight written immediately before the compose run starts 27 //! committed the run committed exactly the approved proposal (evidence kept) 28 //! failed the run returned and reported that the World did not commit 29 //! not_executed the claim ended before any run started (refusal after the 30 //! claim, or a crash between accepted and in_flight) 31 //! uncertain the run may have changed the World but completion is not 32 //! proven (run error, committed-but-mismatch, crash in flight) 33 //! declared an operator settled an uncertain claim (what the operator saw); 34 //! it changes the reported state only 35 //! 36 //! Invariant: a claim key (approval key, request id, approval id; each on its 37 //! own) is accepted at most once, ever. Every later submission naming any of 38 //! them is refused with the claim's state, whatever that state is: an approval 39 //! is single-use even when its run never started, so no interrupted state is 40 //! ever guessed into a second run. A retry after a lost response gets the 41 //! committed evidence back in the refusal (`AlreadyCommitted`). 42 //! 43 //! Atomicity: the ledger is rebuilt from the journal under the compose-home 44 //! lock and the check and the `accepted` append happen in that one locked step 45 //! (the same pattern as effects::open_intent), so two concurrent submissions 46 //! cannot both be accepted. The journal is opened with CX_OPEN_SYNC: an 47 //! appended record is durable when `note` returns. 48 //! 49 //! The approval identity and its canonical key belong to crate::approved_auth 50 //! (`ApprovalIdentity`, `approval_key`); this module never recomputes them. It 51 //! takes the key and the two ids from the caller ([`ClaimKeys`]). 52 //! 53 //! Limits: the ledger reads at most HOST_RECALL_MAX host records in one recall 54 //! and refuses (fails closed) beyond that; liveness of a claiming process is 55 //! pid + start ticks (effects::executor_alive). 56 use crate::compose::{record_view, ComposeBridge, ComposeHome}; 57 use crate::control::ComposeRecordView; 58 use crate::effects::{executor_alive, self_executor}; 59 use aien_omega_compose::NoteKind; 60 use serde_json::{json, Value}; 61 use std::collections::BTreeMap; 62 use std::fmt; 63 64 /// The JSON field that marks a replay record (reserved against ComposeNote). 65 pub const FIELD: &str = "approved_submission"; 66 const HOST_RECALL_MAX: u32 = 4096; 67 68 /// The keys one submission claims, taken from the authenticated identity. 69 #[derive(Debug, Clone, PartialEq, Eq)] 70 pub struct ClaimKeys { 71 /// `approved_auth::approval_key(&identity)`: sha256 hex of the binding. 72 pub approval_key: String, 73 pub request_id: String, 74 pub approval_id: String, 75 /// Correlation only; not a claim key. 76 pub trace_id: String, 77 } 78 79 impl ClaimKeys { 80 fn keys(&self) -> [String; 3] { 81 [ 82 format!("key:{}", self.approval_key), 83 format!("request:{}", self.request_id), 84 format!("approval:{}", self.approval_id), 85 ] 86 } 87 fn check(&self) -> Result<(), Refusal> { 88 let k = &self.approval_key; 89 if k.len() != 64 90 || !k 91 .bytes() 92 .all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c)) 93 { 94 return Err(Refusal::new( 95 "BadKey", 96 "approval_key is not 64 lowercase hex", 97 )); 98 } 99 if self.request_id.is_empty() || self.approval_id.is_empty() { 100 return Err(Refusal::new("BadKey", "empty request_id or approval_id")); 101 } 102 Ok(()) 103 } 104 } 105 106 /// What a committed run left behind (returned again on a retry). 107 #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] 108 pub struct CommitEvidence { 109 pub compose_proposal_sha256: String, 110 pub cx_promotion: u64, 111 pub cx_evidence: u64, 112 pub task: u64, 113 } 114 115 #[derive(Debug, Clone, Copy, PartialEq, Eq)] 116 pub enum ClaimState { 117 Accepted, 118 InFlight, 119 Committed, 120 Failed, 121 NotExecuted, 122 Uncertain, 123 } 124 125 impl ClaimState { 126 pub fn name(self) -> &'static str { 127 match self { 128 Self::Accepted => "ACCEPTED", 129 Self::InFlight => "IN_FLIGHT", 130 Self::Committed => "COMMITTED", 131 Self::Failed => "FAILED", 132 Self::NotExecuted => "NOT_EXECUTED", 133 Self::Uncertain => "UNCERTAIN", 134 } 135 } 136 pub fn terminal(self) -> bool { 137 !matches!(self, Self::Accepted | Self::InFlight) 138 } 139 } 140 141 /// A named refusal: `REPLAY_REFUSED : ...`. 142 #[derive(Debug, Clone, PartialEq, Eq)] 143 pub struct Refusal { 144 pub name: &'static str, 145 pub detail: String, 146 /// The existing claim the refusal is about, when there is one. 147 pub claim: Option, 148 /// Set for AlreadyCommitted: the original result, for a caller whose 149 /// response was lost. 150 pub evidence: Option, 151 } 152 153 impl Refusal { 154 fn new(name: &'static str, detail: impl Into) -> Self { 155 Self { 156 name, 157 detail: detail.into(), 158 claim: None, 159 evidence: None, 160 } 161 } 162 } 163 164 impl fmt::Display for Refusal { 165 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 166 write!(f, "REPLAY_REFUSED {}: {}", self.name, self.detail) 167 } 168 } 169 170 /// A claim this process holds (the `accepted` record id). 171 #[derive(Debug, Clone, Copy, PartialEq, Eq)] 172 pub struct Claim { 173 pub id: u64, 174 } 175 176 /// One claim as the ledger reads it. 177 #[derive(Debug, Clone, PartialEq, Eq)] 178 pub struct ClaimRow { 179 pub id: u64, 180 pub keys: ClaimKeys, 181 pub executor_pid: u32, 182 pub executor_start: u64, 183 pub state: ClaimState, 184 /// The record that set `state` (the claim itself while ACCEPTED). 185 pub state_record: u64, 186 pub evidence: Option, 187 pub reason: Option, 188 /// Operator declaration on an UNCERTAIN claim: (record, "committed" | "not_committed"). 189 pub declared: Option<(u64, String)>, 190 } 191 192 /// The replay ledger, rebuilt from the journal's host records. 193 #[derive(Debug, Default)] 194 pub struct ReplayLedger { 195 pub claims: BTreeMap, 196 /// claim key -> claim id 197 index: BTreeMap, 198 } 199 200 fn corrupt(id: u64, why: impl Into) -> Refusal { 201 Refusal::new("CorruptLedger", format!("record #{id}: {}", why.into())) 202 } 203 fn s(v: &Value, k: &str, id: u64) -> Result { 204 v.get(k) 205 .and_then(Value::as_str) 206 .map(str::to_string) 207 .ok_or_else(|| corrupt(id, format!("missing {k}"))) 208 } 209 fn u(v: &Value, k: &str, id: u64) -> Result { 210 v.get(k) 211 .and_then(Value::as_u64) 212 .ok_or_else(|| corrupt(id, format!("missing {k}"))) 213 } 214 215 impl ReplayLedger { 216 pub fn from_records(host: &[ComposeRecordView]) -> Result { 217 let mut l = Self::default(); 218 for r in host { 219 if !r.verified { 220 return Err(corrupt(r.id, "digest does not verify")); 221 } 222 if r.note.as_deref() != Some("effect") { 223 continue; 224 } 225 let Some(text) = r.text.as_deref() else { 226 continue; 227 }; 228 let Ok(v) = serde_json::from_str::(text) else { 229 continue; 230 }; 231 let Some(phase) = v.get(FIELD) else { continue }; 232 let phase = phase 233 .as_str() 234 .ok_or_else(|| corrupt(r.id, "phase is not a string"))?; 235 l.read(r.id, phase, &v)?; 236 } 237 Ok(l) 238 } 239 240 fn read(&mut self, id: u64, phase: &str, v: &Value) -> Result<(), Refusal> { 241 if phase == "accepted" { 242 let keys = ClaimKeys { 243 approval_key: s(v, "approval_key", id)?, 244 request_id: s(v, "request_id", id)?, 245 approval_id: s(v, "approval_id", id)?, 246 trace_id: s(v, "trace_id", id)?, 247 }; 248 for k in keys.keys() { 249 if let Some(prev) = self.index.insert(k.clone(), id) { 250 return Err(corrupt(id, format!("{k} already claimed by #{prev}"))); 251 } 252 } 253 let ex = v.get("executor").cloned().unwrap_or(Value::Null); 254 self.claims.insert( 255 id, 256 ClaimRow { 257 id, 258 keys, 259 executor_pid: u(&ex, "pid", id)? as u32, 260 executor_start: u(&ex, "start", id)?, 261 state: ClaimState::Accepted, 262 state_record: id, 263 evidence: None, 264 reason: None, 265 declared: None, 266 }, 267 ); 268 return Ok(()); 269 } 270 let c = u(v, "claim", id)?; 271 let row = self 272 .claims 273 .get_mut(&c) 274 .ok_or_else(|| corrupt(id, format!("names claim #{c}, which is not one")))?; 275 let reason = v.get("reason").and_then(Value::as_str).map(str::to_string); 276 // Allowed transitions; anything else is a corrupt ledger (fail closed). 277 let next = match (phase, row.state) { 278 ("in_flight", ClaimState::Accepted) => ClaimState::InFlight, 279 ("committed", ClaimState::InFlight) => ClaimState::Committed, 280 ("failed", ClaimState::InFlight) => ClaimState::Failed, 281 ("uncertain", ClaimState::InFlight) => ClaimState::Uncertain, 282 ("not_executed", ClaimState::Accepted) => ClaimState::NotExecuted, 283 ("declared", ClaimState::Uncertain) => { 284 if row.declared.is_some() { 285 return Err(corrupt(id, format!("claim #{c} declared twice"))); 286 } 287 let d = s(v, "declared", id)?; 288 if d != "committed" && d != "not_committed" { 289 return Err(corrupt( 290 id, 291 "declared is neither committed nor not_committed", 292 )); 293 } 294 row.declared = Some((id, d)); 295 return Ok(()); 296 } 297 (p, st) => { 298 return Err(corrupt( 299 id, 300 format!("{p} after {} on claim #{c}", st.name()), 301 )); 302 } 303 }; 304 if next == ClaimState::Committed { 305 let e = v.get("evidence").cloned().unwrap_or(Value::Null); 306 row.evidence = 307 Some(serde_json::from_value(e).map_err(|e| corrupt(id, format!("evidence: {e}")))?); 308 } 309 row.state = next; 310 row.state_record = id; 311 row.reason = reason; 312 Ok(()) 313 } 314 315 /// The existing claim on any of these keys, if one exists. 316 pub fn find(&self, keys: &ClaimKeys) -> Option<&ClaimRow> { 317 keys.keys() 318 .iter() 319 .find_map(|k| self.index.get(k)) 320 .and_then(|id| self.claims.get(id)) 321 } 322 323 /// Why a new claim on `keys` is refused (None: it may be claimed). 324 pub fn check(&self, keys: &ClaimKeys) -> Option { 325 let row = self.find(keys)?; 326 let alive = executor_alive(row.executor_pid, row.executor_start); 327 let (name, what): (&'static str, String) = match row.state { 328 ClaimState::Committed => ("AlreadyCommitted", "committed; the original result is attached".into()), 329 ClaimState::Failed => ("AlreadyFailed", "ran and did not commit; a new approval is needed".into()), 330 ClaimState::NotExecuted => ("AlreadyConsumed", "claimed, never ran; a new approval is needed".into()), 331 ClaimState::Uncertain => ("Uncertain", "may have committed; an operator must reconcile it, it is never re-run".into()), 332 ClaimState::Accepted | ClaimState::InFlight if alive => ("InFlight", format!("{} in a running process", row.state.name())), 333 // The claiming process is gone and nothing settled the claim yet: 334 // before in_flight nothing ran; after it, completion is unknown. 335 ClaimState::Accepted => ("AlreadyConsumed", "claimed by a process that is gone, never ran; a new approval is needed".into()), 336 ClaimState::InFlight => ("Uncertain", "in flight in a process that is gone; an operator must reconcile it, it is never re-run".into()), 337 }; 338 let mut r = Refusal::new( 339 name, 340 format!( 341 "claim #{} (request {}, approval {}, key {}) is {}: {what}", 342 row.id, 343 row.keys.request_id, 344 row.keys.approval_id, 345 row.keys.approval_key, 346 row.state.name() 347 ), 348 ); 349 r.claim = Some(row.id); 350 r.evidence = row.evidence.clone(); 351 Some(r) 352 } 353 } 354 355 fn ledger(home: &mut ComposeHome) -> Result { 356 let (recs, total) = home 357 .compose 358 .recall(aien_omega_compose::SUBJECT_HOST, HOST_RECALL_MAX) 359 .map_err(|e| Refusal::new("Journal", format!("host records: {e}")))?; 360 if total > recs.len() as u64 { 361 return Err(Refusal::new( 362 "CorruptLedger", 363 format!("{total} host records exceed the replay ledger's {HOST_RECALL_MAX}"), 364 )); 365 } 366 let views: Vec = recs 367 .iter() 368 .map(|r| record_view(&mut home.compose, r)) 369 .collect(); 370 ReplayLedger::from_records(&views) 371 } 372 373 fn append(home: &mut ComposeHome, link: u64, text: &Value) -> Result { 374 let mut l = [0u64; 4]; 375 l[0] = link; 376 home.compose 377 .note(NoteKind::Effect, l, text.to_string().as_bytes()) 378 .map_err(|e| Refusal::new("Journal", format!("replay record: {e}"))) 379 } 380 381 /// Run `f` under the compose-home lock; a lock/open/mark failure is a refusal. 382 fn locked( 383 b: &ComposeBridge, 384 f: impl FnOnce(&mut ComposeHome) -> Result, 385 ) -> Result { 386 let mut inner: Option = None; 387 let r = b.with_home(|home| { 388 f(home).map_err(|e| { 389 let s = e.to_string(); 390 inner = Some(e); 391 s 392 }) 393 }); 394 match r { 395 Ok(t) => Ok(t), 396 Err(e) => Err(inner.unwrap_or_else(|| Refusal::new("Journal", e))), 397 } 398 } 399 400 /// Claim `keys` for one execution. Durable before it returns. Refused if any 401 /// key was ever claimed, with that claim's state. 402 pub fn claim(b: &ComposeBridge, keys: &ClaimKeys) -> Result { 403 keys.check()?; 404 locked(b, |home| { 405 let l = ledger(home)?; 406 if let Some(r) = l.check(keys) { 407 return Err(r); 408 } 409 let (pid, start) = self_executor(); 410 if start == 0 { 411 return Err(Refusal::new( 412 "Executor", 413 "cannot read this process's start ticks", 414 )); 415 } 416 let text = json!({ 417 FIELD: "accepted", 418 "approval_key": keys.approval_key, "request_id": keys.request_id, 419 "approval_id": keys.approval_id, "trace_id": keys.trace_id, 420 "executor": {"pid": pid, "start": start}, 421 }); 422 Ok(Claim { 423 id: append(home, 0, &text)?, 424 }) 425 }) 426 } 427 428 /// Append one lifecycle record after checking the claim is ours and in `from`. 429 fn step(b: &ComposeBridge, c: &Claim, from: ClaimState, text: Value) -> Result { 430 locked(b, |home| { 431 let l = ledger(home)?; 432 let row = l 433 .claims 434 .get(&c.id) 435 .ok_or_else(|| Refusal::new("NoClaim", format!("#{} is not a claim", c.id)))?; 436 let (pid, start) = self_executor(); 437 if (row.executor_pid, row.executor_start) != (pid, start) { 438 return Err(Refusal::new( 439 "NotOwner", 440 format!("claim #{} belongs to another process", c.id), 441 )); 442 } 443 if row.state != from { 444 return Err(Refusal::new( 445 "WrongState", 446 format!( 447 "claim #{} is {}, expected {}", 448 c.id, 449 row.state.name(), 450 from.name() 451 ), 452 )); 453 } 454 append(home, c.id, &text) 455 }) 456 } 457 458 /// Immediately before the compose run. 459 pub fn mark_in_flight(b: &ComposeBridge, c: &Claim) -> Result<(), Refusal> { 460 step( 461 b, 462 c, 463 ClaimState::Accepted, 464 json!({FIELD: "in_flight", "claim": c.id}), 465 ) 466 .map(|_| ()) 467 } 468 469 /// The run committed exactly the approved proposal. 470 pub fn commit(b: &ComposeBridge, c: &Claim, e: &CommitEvidence) -> Result<(), Refusal> { 471 let text = json!({FIELD: "committed", "claim": c.id, "evidence": e}); 472 step(b, c, ClaimState::InFlight, text).map(|_| ()) 473 } 474 475 /// The run returned and reported that the World did not commit 476 /// (`ComposeTaskReport.committed == false`). 477 pub fn fail(b: &ComposeBridge, c: &Claim, reason: &str) -> Result<(), Refusal> { 478 let text = json!({FIELD: "failed", "claim": c.id, "reason": reason}); 479 step(b, c, ClaimState::InFlight, text).map(|_| ()) 480 } 481 482 /// The claim ends before the run started (any refusal after `claim`). 483 pub fn not_executed(b: &ComposeBridge, c: &Claim, reason: &str) -> Result<(), Refusal> { 484 let text = json!({FIELD: "not_executed", "claim": c.id, "reason": reason}); 485 step(b, c, ClaimState::Accepted, text).map(|_| ()) 486 } 487 488 /// The run may have changed the World and success is not proven: the run 489 /// returned an error, or committed something other than the approved proposal. 490 pub fn uncertain(b: &ComposeBridge, c: &Claim, reason: &str) -> Result<(), Refusal> { 491 let text = json!({FIELD: "uncertain", "claim": c.id, "reason": reason}); 492 step(b, c, ClaimState::InFlight, text).map(|_| ()) 493 } 494 495 /// Operator settles an UNCERTAIN claim after looking at the World. The claim 496 /// stays consumed either way. 497 pub fn declare( 498 b: &ComposeBridge, 499 claim: u64, 500 committed: bool, 501 by: &str, 502 note: &str, 503 ) -> Result { 504 locked(b, |home| { 505 let l = ledger(home)?; 506 let row = l 507 .claims 508 .get(&claim) 509 .ok_or_else(|| Refusal::new("NoClaim", format!("#{claim} is not a claim")))?; 510 if row.state != ClaimState::Uncertain || row.declared.is_some() { 511 return Err(Refusal::new( 512 "WrongState", 513 format!( 514 "claim #{claim} is {} (declared: {})", 515 row.state.name(), 516 row.declared.is_some() 517 ), 518 )); 519 } 520 let d = if committed { 521 "committed" 522 } else { 523 "not_committed" 524 }; 525 append( 526 home, 527 claim, 528 &json!({FIELD: "declared", "claim": claim, "declared": d, "by": by, "note": note}), 529 ) 530 }) 531 } 532 533 /// Daemon start: settle every claim whose process is gone. ACCEPTED (never 534 /// ran) -> not_executed; IN_FLIGHT -> uncertain. Nothing is re-run. 535 pub fn reconcile_at_start(b: &ComposeBridge) -> Result { 536 if !b.dir().join("cortex.cx").exists() { 537 return Ok("Replay reconcile: no compose home yet".into()); 538 } 539 locked(b, |home| { 540 let l = ledger(home)?; 541 let (mut ne, mut un) = (0, 0); 542 for row in l.claims.values() { 543 if row.state.terminal() || executor_alive(row.executor_pid, row.executor_start) { 544 continue; 545 } 546 let (phase, why) = match row.state { 547 ClaimState::Accepted => { 548 ne += 1; 549 ( 550 "not_executed", 551 "claiming process gone before the run started (reconcile@start)", 552 ) 553 } 554 _ => { 555 un += 1; 556 ( 557 "uncertain", 558 "claiming process gone while in flight (reconcile@start)", 559 ) 560 } 561 }; 562 append( 563 home, 564 row.id, 565 &json!({FIELD: phase, "claim": row.id, "reason": why, "by": "reconcile@start"}), 566 )?; 567 } 568 Ok(format!( 569 "Replay reconcile: {} claims, {ne} -> NOT_EXECUTED, {un} -> UNCERTAIN", 570 l.claims.len() 571 )) 572 }) 573 }