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/aienux/blob/main/crates/aienos-kernel/src/continuity.rs # aienux Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately. 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 `aienux / crates / aienos-kernel / src / continuity.rs` 908 lines ยท 31460 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 //! M4 continuity objects over System Store v1 (ADR 0016, Proposed). 17 //! 18 //! AIEN is provisioned once (ADR 0007). Every later start must locate, verify 19 //! and resume the one durable `LogicalAgentId`, or stop. This module holds the 20 //! canonical encodings of the continuity objects and the deterministic boot 21 //! resolution over a mounted [`Store`]. No model, no network, `no_std`. 22 //! 23 //! The encodings carry `format_version = 0` while ADR 0016 is Proposed: they 24 //! are qualification formats on disposable media, not a frozen on-disk format. 25 //! Store v1 object `version` is 1 for all of them (Store v1 rejects 0). 26 27 use alloc::vec::Vec; 28 29 use crate::crypto::sha256::Sha256; 30 use crate::store::checkpoint::CheckpointHook; 31 use crate::store::engine::{MountState, ObjectInput, Store, StoreDevice, StoreError}; 32 use crate::store::v1::ObjectId; 33 34 pub const KIND_AGENT_ROOT: u16 = 16; 35 pub const KIND_MANIFEST: u16 = 17; 36 pub const KIND_AGENT_STATE: u16 = 18; 37 pub const KIND_CORTEX_WAL: u16 = 20; 38 /// Store v1 object version used for every continuity object. 39 pub const STORE_OBJECT_VERSION: u16 = 1; 40 /// Continuity encoding version while ADR 0016 is Proposed. 41 pub const FORMAT_VERSION: u16 = 0; 42 43 pub const MAX_WAL_SEGMENTS: usize = 64; 44 pub const MAX_BRANCHES: usize = 256; 45 pub const MAX_WAL_RECORDS: usize = 64; 46 pub const MAX_STATEMENT_BYTES: usize = 1024; 47 48 const HEADER_BYTES: usize = 16; 49 const MAGIC_ROOT: &[u8; 8] = b"AIENROOT"; 50 const MAGIC_MANIFEST: &[u8; 8] = b"AIENMANI"; 51 const MAGIC_BRANCHES: &[u8; 8] = b"AIENBRAN"; 52 const MAGIC_WAL: &[u8; 8] = b"AIENCWAL"; 53 const ZERO_ID: [u8; 32] = [0; 32]; 54 55 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 56 pub enum ContinuityError { 57 Store(StoreError), 58 /// No agent root and provisioning was not requested: stop, never mint. 59 Unprovisioned, 60 /// More than one agent root: stop. 61 Conflict, 62 /// A root already exists; provisioning refused. 63 AlreadyProvisioned, 64 /// The mount is read-only (`DegradedRecovery`); nothing may be committed. 65 ReadOnly, 66 /// The continuity graph is inconsistent: stop in the Recovery Core. 67 Corrupt(&'static str), 68 /// An update exceeds a format bound. 69 Limit(&'static str), 70 } 71 72 impl From for ContinuityError { 73 fn from(e: StoreError) -> Self { 74 Self::Store(e) 75 } 76 } 77 78 type Result = core::result::Result; 79 80 // --------------------------------------------------------------------------- 81 // Identity derivations (shared with the host `aienos-agent-state` crate) 82 // --------------------------------------------------------------------------- 83 84 /// Root branch id of an agent: SHA-256("AIENOS_ROOT_BRANCH_v1:" || agent). 85 pub fn root_branch_id(agent: &[u8; 32]) -> [u8; 32] { 86 let mut h = Sha256::new(); 87 h.update(b"AIENOS_ROOT_BRANCH_v1:"); 88 h.update(agent); 89 h.finalize() 90 } 91 92 /// Child branch id: SHA-256("AIENOS_CHILD_BRANCH_v1:" || parent || index BE). 93 pub fn child_branch_id(parent: &[u8; 32], index: u64) -> [u8; 32] { 94 let mut h = Sha256::new(); 95 h.update(b"AIENOS_CHILD_BRANCH_v1:"); 96 h.update(parent); 97 h.update(&index.to_be_bytes()); 98 h.finalize() 99 } 100 101 // --------------------------------------------------------------------------- 102 // Canonical byte helpers 103 // --------------------------------------------------------------------------- 104 105 fn header(out: &mut Vec, magic: &[u8; 8], body_len: usize) { 106 out.extend_from_slice(magic); 107 out.extend_from_slice(&FORMAT_VERSION.to_le_bytes()); 108 out.extend_from_slice(&0u16.to_le_bytes()); 109 out.extend_from_slice(&(body_len as u32).to_le_bytes()); 110 } 111 112 /// Strict reader: every read is bounds-checked and the whole input must be 113 /// consumed. 114 struct Reader<'a> { 115 bytes: &'a [u8], 116 at: usize, 117 } 118 119 impl<'a> Reader<'a> { 120 fn open(bytes: &'a [u8], magic: &[u8; 8]) -> Result { 121 let mut r = Self { bytes, at: 0 }; 122 if r.take(8)? != magic { 123 return Err(ContinuityError::Corrupt("bad magic")); 124 } 125 if r.u16()? != FORMAT_VERSION { 126 return Err(ContinuityError::Corrupt( 127 "unsupported continuity format version", 128 )); 129 } 130 if r.u16()? != 0 { 131 return Err(ContinuityError::Corrupt("nonzero header reserved")); 132 } 133 if r.u32()? as usize != bytes.len() - HEADER_BYTES { 134 return Err(ContinuityError::Corrupt("body length mismatch")); 135 } 136 Ok(r) 137 } 138 fn take(&mut self, n: usize) -> Result<&'a [u8]> { 139 let end = self 140 .at 141 .checked_add(n) 142 .filter(|end| *end <= self.bytes.len()) 143 .ok_or(ContinuityError::Corrupt("truncated object"))?; 144 let s = &self.bytes[self.at..end]; 145 self.at = end; 146 Ok(s) 147 } 148 fn id(&mut self) -> Result<[u8; 32]> { 149 let mut out = [0; 32]; 150 out.copy_from_slice(self.take(32)?); 151 Ok(out) 152 } 153 fn u8(&mut self) -> Result { 154 Ok(self.take(1)?[0]) 155 } 156 fn u16(&mut self) -> Result { 157 let b = self.take(2)?; 158 Ok(u16::from_le_bytes([b[0], b[1]])) 159 } 160 fn u32(&mut self) -> Result { 161 let b = self.take(4)?; 162 Ok(u32::from_le_bytes([b[0], b[1], b[2], b[3]])) 163 } 164 fn u64(&mut self) -> Result { 165 let mut a = [0; 8]; 166 a.copy_from_slice(self.take(8)?); 167 Ok(u64::from_le_bytes(a)) 168 } 169 fn zeros(&mut self, n: usize) -> Result<()> { 170 if self.take(n)?.iter().any(|b| *b != 0) { 171 return Err(ContinuityError::Corrupt("nonzero reserved")); 172 } 173 Ok(()) 174 } 175 fn finish(self) -> Result<()> { 176 if self.at != self.bytes.len() { 177 return Err(ContinuityError::Corrupt("trailing bytes")); 178 } 179 Ok(()) 180 } 181 } 182 183 fn object_id(kind: u16, bytes: &[u8]) -> Result { 184 ObjectId::calculate(kind, STORE_OBJECT_VERSION, bytes) 185 .map_err(|e| ContinuityError::Store(StoreError::Format(e))) 186 } 187 188 fn opt_id(id: [u8; 32]) -> Option { 189 (id != ZERO_ID).then_some(ObjectId(id)) 190 } 191 192 fn raw(id: Option) -> [u8; 32] { 193 id.map_or(ZERO_ID, |i| i.0) 194 } 195 196 // --------------------------------------------------------------------------- 197 // AgentRoot (kind 16): written once, at provisioning 198 // --------------------------------------------------------------------------- 199 200 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 201 pub enum ProvisionSource { 202 /// An operator-authorised provisioning action (Recovery Core, ADR 0006). 203 Operator = 1, 204 /// A qualification harness on disposable media. 205 Qualification = 2, 206 } 207 208 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 209 pub struct AgentRoot { 210 pub agent_id: [u8; 32], 211 pub store_uuid: [u8; 16], 212 pub root_branch: [u8; 32], 213 pub provisioned_generation: u64, 214 pub source: ProvisionSource, 215 } 216 217 const ROOT_BODY: usize = 32 + 16 + 32 + 8 + 1 + 7; 218 219 impl AgentRoot { 220 pub fn encode(&self) -> Vec { 221 let mut out = Vec::with_capacity(HEADER_BYTES + ROOT_BODY); 222 header(&mut out, MAGIC_ROOT, ROOT_BODY); 223 out.extend_from_slice(&self.agent_id); 224 out.extend_from_slice(&self.store_uuid); 225 out.extend_from_slice(&self.root_branch); 226 out.extend_from_slice(&self.provisioned_generation.to_le_bytes()); 227 out.push(self.source as u8); 228 out.extend_from_slice(&[0; 7]); 229 out 230 } 231 232 pub fn decode(bytes: &[u8]) -> Result { 233 let mut r = Reader::open(bytes, MAGIC_ROOT)?; 234 let agent_id = r.id()?; 235 let mut store_uuid = [0; 16]; 236 store_uuid.copy_from_slice(r.take(16)?); 237 let root_branch = r.id()?; 238 let provisioned_generation = r.u64()?; 239 let source = match r.u8()? { 240 1 => ProvisionSource::Operator, 241 2 => ProvisionSource::Qualification, 242 _ => return Err(ContinuityError::Corrupt("unknown provisioning source")), 243 }; 244 r.zeros(7)?; 245 r.finish()?; 246 if agent_id == ZERO_ID { 247 return Err(ContinuityError::Corrupt("zero agent id")); 248 } 249 if root_branch != root_branch_id(&agent_id) { 250 return Err(ContinuityError::Corrupt( 251 "root branch does not derive from agent", 252 )); 253 } 254 Ok(Self { 255 agent_id, 256 store_uuid, 257 root_branch, 258 provisioned_generation, 259 source, 260 }) 261 } 262 } 263 264 // --------------------------------------------------------------------------- 265 // ContinuityManifest (kind 17): one per Class A commit 266 // --------------------------------------------------------------------------- 267 268 #[derive(Clone, Debug, Eq, PartialEq)] 269 pub struct Manifest { 270 pub root: ObjectId, 271 pub previous: Option, 272 pub sequence: u64, 273 pub incarnation: u64, 274 pub agent_state: Option, 275 pub cortex_wal: Vec, 276 } 277 278 impl Manifest { 279 pub fn encode(&self) -> Result> { 280 if self.cortex_wal.len() > MAX_WAL_SEGMENTS { 281 return Err(ContinuityError::Limit("too many cortex WAL segments")); 282 } 283 let body = 32 + 32 + 8 + 8 + 32 + 2 + 6 + 32 * self.cortex_wal.len(); 284 let mut out = Vec::with_capacity(HEADER_BYTES + body); 285 header(&mut out, MAGIC_MANIFEST, body); 286 out.extend_from_slice(&self.root.0); 287 out.extend_from_slice(&raw(self.previous)); 288 out.extend_from_slice(&self.sequence.to_le_bytes()); 289 out.extend_from_slice(&self.incarnation.to_le_bytes()); 290 out.extend_from_slice(&raw(self.agent_state)); 291 out.extend_from_slice(&(self.cortex_wal.len() as u16).to_le_bytes()); 292 out.extend_from_slice(&[0; 6]); 293 for id in &self.cortex_wal { 294 out.extend_from_slice(&id.0); 295 } 296 Ok(out) 297 } 298 299 pub fn decode(bytes: &[u8]) -> Result { 300 let mut r = Reader::open(bytes, MAGIC_MANIFEST)?; 301 let root = ObjectId(r.id()?); 302 let previous = opt_id(r.id()?); 303 let sequence = r.u64()?; 304 let incarnation = r.u64()?; 305 let agent_state = opt_id(r.id()?); 306 let wal_count = r.u16()? as usize; 307 r.zeros(6)?; 308 if wal_count > MAX_WAL_SEGMENTS { 309 return Err(ContinuityError::Corrupt("too many cortex WAL segments")); 310 } 311 let mut cortex_wal = Vec::with_capacity(wal_count); 312 for _ in 0..wal_count { 313 cortex_wal.push(ObjectId(r.id()?)); 314 } 315 r.finish()?; 316 if sequence == 0 || (sequence == 1) != previous.is_none() { 317 return Err(ContinuityError::Corrupt( 318 "manifest sequence/previous mismatch", 319 )); 320 } 321 Ok(Self { 322 root, 323 previous, 324 sequence, 325 incarnation, 326 agent_state, 327 cortex_wal, 328 }) 329 } 330 } 331 332 // --------------------------------------------------------------------------- 333 // AgentStateCheckpoint (kind 18): the branch table 334 // --------------------------------------------------------------------------- 335 336 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 337 pub struct Branch { 338 pub id: [u8; 32], 339 /// `None` only for the root branch. 340 pub parent: Option<[u8; 32]>, 341 pub depth: u32, 342 /// Number of children forked from this branch so far. 343 pub forks: u64, 344 } 345 346 #[derive(Clone, Debug, Eq, PartialEq)] 347 pub struct AgentState { 348 pub agent_id: [u8; 32], 349 /// Manifest sequence this checkpoint was written at (keeps ids unique). 350 pub written_at: u64, 351 /// Sorted by branch id. 352 pub branches: Vec, 353 } 354 355 const BRANCH_BYTES: usize = 32 + 32 + 4 + 4 + 8; 356 357 impl AgentState { 358 /// A fresh agent: only the root branch. 359 pub fn genesis(agent_id: [u8; 32], written_at: u64) -> Self { 360 Self { 361 agent_id, 362 written_at, 363 branches: alloc::vec![Branch { 364 id: root_branch_id(&agent_id), 365 parent: None, 366 depth: 0, 367 forks: 0, 368 }], 369 } 370 } 371 372 pub fn branch(&self, id: &[u8; 32]) -> Option<&Branch> { 373 self.branches 374 .binary_search_by(|b| b.id.cmp(id)) 375 .ok() 376 .map(|i| &self.branches[i]) 377 } 378 379 /// Forks a child of `parent` with the next deterministic index. 380 pub fn fork(&mut self, parent: &[u8; 32]) -> Result<[u8; 32]> { 381 if self.branches.len() >= MAX_BRANCHES { 382 return Err(ContinuityError::Limit("too many branches")); 383 } 384 let i = self 385 .branches 386 .binary_search_by(|b| b.id.cmp(parent)) 387 .map_err(|_| ContinuityError::Corrupt("fork parent is absent"))?; 388 let (index, depth) = (self.branches[i].forks, self.branches[i].depth); 389 let child = Branch { 390 id: child_branch_id(parent, index), 391 parent: Some(*parent), 392 depth: depth 393 .checked_add(1) 394 .ok_or(ContinuityError::Limit("branch depth"))?, 395 forks: 0, 396 }; 397 self.branches[i].forks = index + 1; 398 let at = self 399 .branches 400 .binary_search_by(|b| b.id.cmp(&child.id)) 401 .err() 402 .ok_or(ContinuityError::Corrupt("child branch id collision"))?; 403 self.branches.insert(at, child); 404 Ok(child.id) 405 } 406 407 pub fn encode(&self) -> Result> { 408 self.validate()?; 409 let body = 32 + 8 + 4 + 4 + BRANCH_BYTES * self.branches.len(); 410 let mut out = Vec::with_capacity(HEADER_BYTES + body); 411 header(&mut out, MAGIC_BRANCHES, body); 412 out.extend_from_slice(&self.agent_id); 413 out.extend_from_slice(&self.written_at.to_le_bytes()); 414 out.extend_from_slice(&(self.branches.len() as u32).to_le_bytes()); 415 out.extend_from_slice(&[0; 4]); 416 for b in &self.branches { 417 out.extend_from_slice(&b.id); 418 out.extend_from_slice(&b.parent.unwrap_or(ZERO_ID)); 419 out.extend_from_slice(&b.depth.to_le_bytes()); 420 out.extend_from_slice(&[0; 4]); 421 out.extend_from_slice(&b.forks.to_le_bytes()); 422 } 423 Ok(out) 424 } 425 426 pub fn decode(bytes: &[u8]) -> Result { 427 let mut r = Reader::open(bytes, MAGIC_BRANCHES)?; 428 let agent_id = r.id()?; 429 let written_at = r.u64()?; 430 let count = r.u32()? as usize; 431 r.zeros(4)?; 432 if count == 0 || count > MAX_BRANCHES { 433 return Err(ContinuityError::Corrupt("branch count out of range")); 434 } 435 let mut branches = Vec::with_capacity(count); 436 for _ in 0..count { 437 let id = r.id()?; 438 let parent = r.id()?; 439 let depth = r.u32()?; 440 r.zeros(4)?; 441 let forks = r.u64()?; 442 branches.push(Branch { 443 id, 444 parent: (parent != ZERO_ID).then_some(parent), 445 depth, 446 forks, 447 }); 448 } 449 r.finish()?; 450 let state = Self { 451 agent_id, 452 written_at, 453 branches, 454 }; 455 state.validate()?; 456 Ok(state) 457 } 458 459 /// Exactly one root derived from the agent; every child derives from its 460 /// parent with depth + 1; each parent's children are exactly indexes 461 /// `0..forks`; ids strictly sorted. 462 pub fn validate(&self) -> Result<()> { 463 let bad = ContinuityError::Corrupt; 464 if self.branches.is_empty() || self.branches.len() > MAX_BRANCHES { 465 return Err(bad("branch count out of range")); 466 } 467 if self.branches.windows(2).any(|w| w[0].id >= w[1].id) { 468 return Err(bad("branches not strictly sorted")); 469 } 470 let root = root_branch_id(&self.agent_id); 471 let mut roots = 0; 472 let mut children = 0u64; 473 for b in &self.branches { 474 match b.parent { 475 None => { 476 if b.id != root || b.depth != 0 { 477 return Err(bad("unexpected root branch")); 478 } 479 roots += 1; 480 } 481 Some(p) => { 482 let parent = self.branch(&p).ok_or(bad("parent branch is absent"))?; 483 // Scan capped at MAX_BRANCHES, as in the C codec 484 // (cc_state_validate in continuity_codec.c): `forks` is input-controlled, 485 // so an uncapped scan lets a hostile table spin for up to 486 // 2^64 hashes. A table that passes the fork-sum check below 487 // has every forks <= 255, so the cap changes no outcome for 488 // a valid table; an id past the cap is refused here as 489 // Corrupt("branch lineage is inconsistent"), same as C. 490 let lim = parent.forks.min(MAX_BRANCHES as u64); 491 let index_ok = (0..lim).any(|i| child_branch_id(&p, i) == b.id); 492 if !index_ok || Some(b.depth) != parent.depth.checked_add(1) { 493 return Err(bad("branch lineage is inconsistent")); 494 } 495 children += 1; 496 } 497 } 498 } 499 // Checked sum: kernel images build with --release and no profile turns 500 // overflow checks on, so a plain `.sum()` would wrap and accept e.g. 501 // {root forks = 2^64-1, child forks = 2}. An overflowing sum can never 502 // equal `children` (<= 255), so it is refused with the same class and 503 // text as the C codec (cc_state_validate in native/kernel/svc/continuity_codec.c). 504 let forks = self 505 .branches 506 .iter() 507 .try_fold(0u64, |acc, b| acc.checked_add(b.forks)); 508 if roots != 1 || forks != Some(children) { 509 return Err(bad("fork indexes are not contiguous")); 510 } 511 Ok(()) 512 } 513 } 514 515 // --------------------------------------------------------------------------- 516 // CortexWalSegment (kind 20): committed Cortex records 517 // --------------------------------------------------------------------------- 518 519 /// Mirrors `aienos-cortex` `EpistemicStatus` discriminants. 520 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 521 pub enum Epistemic { 522 DirectObservation = 1, 523 VerifiedFact = 2, 524 Inference = 3, 525 Hypothesis = 4, 526 Contradiction = 5, 527 OperatorDecision = 6, 528 } 529 530 impl Epistemic { 531 fn from_u8(v: u8) -> Option { 532 Some(match v { 533 1 => Self::DirectObservation, 534 2 => Self::VerifiedFact, 535 3 => Self::Inference, 536 4 => Self::Hypothesis, 537 5 => Self::Contradiction, 538 6 => Self::OperatorDecision, 539 _ => return None, 540 }) 541 } 542 } 543 544 #[derive(Clone, Debug, Eq, PartialEq)] 545 pub struct CortexRecord { 546 pub status: Epistemic, 547 pub evidence_hash: [u8; 32], 548 pub statement: Vec, 549 } 550 551 #[derive(Clone, Debug, Eq, PartialEq)] 552 pub struct WalSegment { 553 /// Manifest sequence this segment was committed in. 554 pub sequence: u64, 555 pub records: Vec, 556 } 557 558 impl WalSegment { 559 pub fn encode(&self) -> Result> { 560 if self.records.is_empty() || self.records.len() > MAX_WAL_RECORDS { 561 return Err(ContinuityError::Limit("WAL segment record count")); 562 } 563 let mut body = 8 + 4 + 4; 564 for rec in &self.records { 565 if rec.statement.is_empty() || rec.statement.len() > MAX_STATEMENT_BYTES { 566 return Err(ContinuityError::Limit("statement length")); 567 } 568 body += 4 + 32 + rec.statement.len(); 569 } 570 let mut out = Vec::with_capacity(HEADER_BYTES + body); 571 header(&mut out, MAGIC_WAL, body); 572 out.extend_from_slice(&self.sequence.to_le_bytes()); 573 out.extend_from_slice(&(self.records.len() as u32).to_le_bytes()); 574 out.extend_from_slice(&[0; 4]); 575 for rec in &self.records { 576 out.push(rec.status as u8); 577 out.push(0); 578 out.extend_from_slice(&(rec.statement.len() as u16).to_le_bytes()); 579 out.extend_from_slice(&rec.evidence_hash); 580 out.extend_from_slice(&rec.statement); 581 } 582 Ok(out) 583 } 584 585 pub fn decode(bytes: &[u8]) -> Result { 586 let mut r = Reader::open(bytes, MAGIC_WAL)?; 587 let sequence = r.u64()?; 588 let count = r.u32()? as usize; 589 r.zeros(4)?; 590 if count == 0 || count > MAX_WAL_RECORDS { 591 return Err(ContinuityError::Corrupt("WAL segment record count")); 592 } 593 let mut records = Vec::with_capacity(count); 594 for _ in 0..count { 595 let status = Epistemic::from_u8(r.u8()?) 596 .ok_or(ContinuityError::Corrupt("unknown epistemic status"))?; 597 r.zeros(1)?; 598 let len = r.u16()? as usize; 599 if len == 0 || len > MAX_STATEMENT_BYTES { 600 return Err(ContinuityError::Corrupt("statement length")); 601 } 602 let evidence_hash = r.id()?; 603 let statement = r.take(len)?.to_vec(); 604 records.push(CortexRecord { 605 status, 606 evidence_hash, 607 statement, 608 }); 609 } 610 r.finish()?; 611 Ok(Self { sequence, records }) 612 } 613 } 614 615 // --------------------------------------------------------------------------- 616 // Boot resolution 617 // --------------------------------------------------------------------------- 618 619 /// The verified continuity view of one Store generation. 620 #[derive(Clone, Debug, Eq, PartialEq)] 621 pub struct Continuity { 622 pub root_id: ObjectId, 623 pub root: AgentRoot, 624 pub manifest_id: ObjectId, 625 pub manifest: Manifest, 626 pub state: AgentState, 627 /// Every committed Cortex record, in commit order. 628 pub cortex: Vec, 629 } 630 631 /// Class A changes to commit with the next manifest. 632 #[derive(Clone, Debug, Default)] 633 pub struct Update { 634 /// Replace the branch table (e.g. after a fork). 635 pub state: Option, 636 /// Append these Cortex records as one WAL segment. 637 pub cortex: Vec, 638 } 639 640 fn ids_of_kind(store: &Store, kind: u16) -> Vec { 641 store 642 .catalog() 643 .entries 644 .iter() 645 .filter(|e| e.kind == kind) 646 .map(|e| e.object_id) 647 .collect() 648 } 649 650 fn read_kind(store: &mut Store, id: ObjectId, kind: u16) -> Result> { 651 let entry = store 652 .catalog() 653 .entries 654 .iter() 655 .find(|e| e.object_id == id) 656 .copied() 657 .ok_or(ContinuityError::Corrupt("referenced object is absent"))?; 658 if entry.kind != kind || entry.version != STORE_OBJECT_VERSION { 659 return Err(ContinuityError::Corrupt( 660 "referenced object has the wrong kind", 661 )); 662 } 663 Ok(store.read_object(id)?) 664 } 665 666 /// Locates and verifies the continuity view without writing anything. 667 /// Never creates an identity. 668 pub fn resolve(store: &mut Store) -> Result { 669 let roots = ids_of_kind(store, KIND_AGENT_ROOT); 670 let root_id = match roots.as_slice() { 671 // Continuity objects without their root mean the identity was lost, 672 // not that the store was never provisioned: fail toward preservation. 673 [] if [KIND_MANIFEST, KIND_AGENT_STATE, KIND_CORTEX_WAL] 674 .iter() 675 .any(|kind| !ids_of_kind(store, *kind).is_empty()) => 676 { 677 return Err(ContinuityError::Corrupt( 678 "continuity objects without an agent root", 679 )) 680 } 681 [] => return Err(ContinuityError::Unprovisioned), 682 [one] => *one, 683 _ => return Err(ContinuityError::Conflict), 684 }; 685 let root = AgentRoot::decode(&read_kind(store, root_id, KIND_AGENT_ROOT)?)?; 686 687 // Every manifest must belong to one unbroken chain 1..=n for this root. 688 let mut manifests = Vec::new(); 689 for id in ids_of_kind(store, KIND_MANIFEST) { 690 let m = Manifest::decode(&read_kind(store, id, KIND_MANIFEST)?)?; 691 if m.root != root_id { 692 return Err(ContinuityError::Corrupt("manifest names a foreign root")); 693 } 694 manifests.push((id, m)); 695 } 696 if manifests.is_empty() { 697 return Err(ContinuityError::Corrupt("agent root has no manifest")); 698 } 699 manifests.sort_by_key(|(_, m)| m.sequence); 700 for (i, (id, m)) in manifests.iter().enumerate() { 701 if m.sequence != i as u64 + 1 { 702 return Err(ContinuityError::Corrupt("manifest sequence gap or fork")); 703 } 704 let expected_previous = i.checked_sub(1).map(|p| manifests[p].0); 705 if m.previous != expected_previous { 706 return Err(ContinuityError::Corrupt("manifest chain is broken")); 707 } 708 let _ = id; 709 } 710 let (manifest_id, manifest) = manifests.pop().expect("non-empty"); 711 712 let state_id = manifest 713 .agent_state 714 .ok_or(ContinuityError::Corrupt("manifest has no agent state"))?; 715 let state = AgentState::decode(&read_kind(store, state_id, KIND_AGENT_STATE)?)?; 716 if state.agent_id != root.agent_id { 717 return Err(ContinuityError::Corrupt( 718 "agent state belongs to another agent", 719 )); 720 } 721 722 let mut cortex = Vec::new(); 723 let mut last_sequence = 0; 724 for id in &manifest.cortex_wal { 725 let seg = WalSegment::decode(&read_kind(store, *id, KIND_CORTEX_WAL)?)?; 726 if seg.sequence <= last_sequence || seg.sequence > manifest.sequence { 727 return Err(ContinuityError::Corrupt("WAL segments out of order")); 728 } 729 last_sequence = seg.sequence; 730 cortex.extend(seg.records); 731 } 732 733 Ok(Continuity { 734 root_id, 735 root, 736 manifest_id, 737 manifest, 738 state, 739 cortex, 740 }) 741 } 742 743 fn writable(store: &Store) -> Result<()> { 744 if store.mount_state() != MountState::Valid { 745 return Err(ContinuityError::ReadOnly); 746 } 747 Ok(()) 748 } 749 750 /// Creates the one durable identity. Only reachable from an explicit, 751 /// authorised provisioning request; refuses if any root exists. 752 pub fn provision( 753 store: &mut Store, 754 agent_id: [u8; 32], 755 store_uuid: [u8; 16], 756 source: ProvisionSource, 757 ) -> Result { 758 writable(store)?; 759 if !ids_of_kind(store, KIND_AGENT_ROOT).is_empty() { 760 return Err(ContinuityError::AlreadyProvisioned); 761 } 762 if agent_id == ZERO_ID { 763 return Err(ContinuityError::Corrupt("zero agent id")); 764 } 765 let root = AgentRoot { 766 agent_id, 767 store_uuid, 768 root_branch: root_branch_id(&agent_id), 769 provisioned_generation: store.generation() + 1, 770 source, 771 }; 772 let root_bytes = root.encode(); 773 let root_id = object_id(KIND_AGENT_ROOT, &root_bytes)?; 774 let state_bytes = AgentState::genesis(agent_id, 1).encode()?; 775 let state_id = object_id(KIND_AGENT_STATE, &state_bytes)?; 776 let manifest = Manifest { 777 root: root_id, 778 previous: None, 779 sequence: 1, 780 incarnation: 1, 781 agent_state: Some(state_id), 782 cortex_wal: Vec::new(), 783 }; 784 let manifest_bytes = manifest.encode()?; 785 store.transact(&[ 786 ObjectInput { 787 kind: KIND_AGENT_ROOT, 788 version: STORE_OBJECT_VERSION, 789 bytes: &root_bytes, 790 }, 791 ObjectInput { 792 kind: KIND_AGENT_STATE, 793 version: STORE_OBJECT_VERSION, 794 bytes: &state_bytes, 795 }, 796 ObjectInput { 797 kind: KIND_MANIFEST, 798 version: STORE_OBJECT_VERSION, 799 bytes: &manifest_bytes, 800 }, 801 ])?; 802 resolve(store) 803 } 804 805 /// Commits `update` and a new manifest in one Store transaction. With 806 /// `new_incarnation` the incarnation advances (a resume); otherwise it is kept. 807 pub fn commit( 808 store: &mut Store, 809 current: &Continuity, 810 update: Update, 811 new_incarnation: bool, 812 ) -> Result { 813 commit_with_hook(store, current, update, new_incarnation, |_| {}) 814 } 815 816 /// [`commit`] with a Store checkpoint hook (qualification crash campaigns). 817 pub fn commit_with_hook( 818 store: &mut Store, 819 current: &Continuity, 820 update: Update, 821 new_incarnation: bool, 822 hook: H, 823 ) -> Result { 824 writable(store)?; 825 let sequence = current 826 .manifest 827 .sequence 828 .checked_add(1) 829 .ok_or(ContinuityError::Limit("manifest sequence"))?; 830 let mut objects: Vec<(u16, Vec)> = Vec::new(); 831 832 let mut agent_state = current.manifest.agent_state; 833 if let Some(mut state) = update.state { 834 if state.agent_id != current.root.agent_id { 835 return Err(ContinuityError::Corrupt( 836 "agent state belongs to another agent", 837 )); 838 } 839 state.written_at = sequence; 840 let bytes = state.encode()?; 841 agent_state = Some(object_id(KIND_AGENT_STATE, &bytes)?); 842 objects.push((KIND_AGENT_STATE, bytes)); 843 } 844 845 let mut cortex_wal = current.manifest.cortex_wal.clone(); 846 if !update.cortex.is_empty() { 847 if cortex_wal.len() >= MAX_WAL_SEGMENTS { 848 return Err(ContinuityError::Limit("cortex WAL needs compaction")); 849 } 850 let bytes = WalSegment { 851 sequence, 852 records: update.cortex, 853 } 854 .encode()?; 855 cortex_wal.push(object_id(KIND_CORTEX_WAL, &bytes)?); 856 objects.push((KIND_CORTEX_WAL, bytes)); 857 } 858 859 let incarnation = if new_incarnation { 860 current 861 .manifest 862 .incarnation 863 .checked_add(1) 864 .ok_or(ContinuityError::Limit("incarnation"))? 865 } else { 866 current.manifest.incarnation 867 }; 868 let manifest = Manifest { 869 root: current.root_id, 870 previous: Some(current.manifest_id), 871 sequence, 872 incarnation, 873 agent_state, 874 cortex_wal, 875 }; 876 objects.push((KIND_MANIFEST, manifest.encode()?)); 877 878 let inputs: Vec> = objects 879 .iter() 880 .map(|(kind, bytes)| ObjectInput { 881 kind: *kind, 882 version: STORE_OBJECT_VERSION, 883 bytes, 884 }) 885 .collect(); 886 store.transact_with_hook(&inputs, hook)?; 887 resolve(store) 888 } 889 890 /// A normal boot: resolve the existing identity and durably advance the 891 /// incarnation before anything acts on it (commit-before-observation). 892 /// On a read-only mount the verified view is returned without committing. 893 pub fn resume(store: &mut Store) -> Result<(Continuity, bool)> { 894 let current = resolve(store)?; 895 if store.mount_state() != MountState::Valid { 896 return Ok((current, false)); 897 } 898 Ok((commit(store, ¤t, Update::default(), true)?, true)) 899 } 900 901 #[cfg(test)] 902 #[path = "continuity_tests.rs"] 903 mod tests; 904 905 /// D-1/D-2 golden-vector emitter for the C codec (test-only). 906 #[cfg(test)] 907 #[path = "continuity_vectors.rs"] 908 mod continuity_vectors;