aien-sovereign-core-mv
AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.
Brought by drakestapleton
aien-sovereign-core-mv / crates / aien-runtime / src / cortex_mark.rs
| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright 2026 Drake Stapleton (AIEN / aien-dev) |
| 3 | // |
| 4 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | // you may not use this file except in compliance with the License. |
| 6 | // You may obtain a copy of the License at |
| 7 | // |
| 8 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | // |
| 10 | // Unless required by applicable law or agreed to in writing, software |
| 11 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | // See the License for the specific language governing permissions and |
| 14 | // limitations under the License. |
| 15 | |
| 16 | //! External Cortex record mark (NEXT-PHASE-2 ACCEPTANCE-v3 section 2.1-2.3). |
| 17 | //! |
| 18 | //! The Cortex journal header carries no record count, and the J-Space anchor |
| 19 | //! moves only at composition commits, so a journal cut exactly at a record |
| 20 | //! boundary that drops only host records opens as if intact (VERDICT-v2 C6c). |
| 21 | //! The mark is kept OUTSIDE the compose dir (`<dir>.cortex-mark`, beside the |
| 22 | //! machine root), written only after an append returned, and checked when the |
| 23 | //! home opens: a journal shorter than its mark is refused, never repaired. |
| 24 | //! |
| 25 | //! Receipt continuity (sovereign-core #408, recovery audit row 8). Each Cortex |
| 26 | //! record digest covers only its own record, so the newest digest alone says |
| 27 | //! nothing about the records before it: one rewritten with a fresh digest |
| 28 | //! (forged, reordered, removed with the count restored, spliced in from |
| 29 | //! another journal) opened as if intact. The version 2 mark also carries the |
| 30 | //! running hash over every record digest #1..#records, `sha256(chain || |
| 31 | //! digest)` from 32 zero bytes (the chain omega's Cortex keeps in memory, |
| 32 | //! `rx_cortex.c` chain_step), recomputed at open: a mismatch is refused |
| 33 | //! (`E_MARK_CHAIN`). |
| 34 | //! |
| 35 | //! Layout v2 (160 bytes, little-endian): `"AIENCXM1"` | u32 version 2 | u32 0 | |
| 36 | //! machine id (32) | u64 seq | u64 records | digest of record #records (32, |
| 37 | //! zeros when records = 0) | chain over records #1..#records (32) | sha256 of |
| 38 | //! the first 128 bytes. Version 1 (128 bytes, no chain, sha256 of the first 96) |
| 39 | //! is still read: its count and digest are checked, and the next mark written |
| 40 | //! is version 2 (reported once; records before that start are taken as read). |
| 41 | //! |
| 42 | //! Limits (declared NOT_PROVED): the sha256 is unkeyed, so rewriting journal |
| 43 | //! and mark together, deleting the mark (adopted and reported), or rolling the |
| 44 | //! compose dir and the mark back together are not detected. Same class: |
| 45 | //! rewriting the mark as version 1 skips the chain check and the next save |
| 46 | //! stamps a fresh version 2 chain; version 1 acceptance must end once the |
| 47 | //! chain is keyed. A version 2 mark with zero records must carry the initial |
| 48 | //! (all-zero) chain, or it is refused as damaged. |
| 49 | use sha2::{Digest, Sha256}; |
| 50 | use std::fmt; |
| 51 | use std::path::{Path, PathBuf}; |
| 52 | |
| 53 | /// Length of a version 2 mark (the one written). |
| 54 | pub const MARK_LEN: usize = 160; |
| 55 | /// Length of a version 1 mark (read only, from installs older than the chain). |
| 56 | pub const MARK_LEN_V1: usize = 128; |
| 57 | const MAGIC: &[u8; 8] = b"AIENCXM1"; |
| 58 | const VERSION: u32 = 2; |
| 59 | |
| 60 | /// One record mark: the journal held `records` records, the newest with |
| 61 | /// `digest`, every digest #1..#records hashing to `chain`, when mark number |
| 62 | /// `seq` was written. `chain` is `None` only for a version 1 mark. |
| 63 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 64 | pub struct Mark { |
| 65 | pub machine_id: [u8; 32], |
| 66 | pub seq: u64, |
| 67 | pub records: u64, |
| 68 | pub digest: [u8; 32], |
| 69 | pub chain: Option<[u8; 32]>, |
| 70 | } |
| 71 | |
| 72 | /// One step of the record chain: `sha256(chain || digest)` (omega |
| 73 | /// `rx_cortex.c` chain_step). |
| 74 | pub fn chain_step(chain: &mut [u8; 32], digest: &[u8; 32]) { |
| 75 | let mut h = Sha256::new(); |
| 76 | h.update(*chain); |
| 77 | h.update(digest); |
| 78 | *chain = h.finalize().into(); |
| 79 | } |
| 80 | |
| 81 | /// The chain over `digests` in journal order, from 32 zero bytes. |
| 82 | pub fn chain_over<'a>(digests: impl IntoIterator<Item = &'a [u8; 32]>) -> [u8; 32] { |
| 83 | let mut c = [0u8; 32]; |
| 84 | for d in digests { |
| 85 | chain_step(&mut c, d); |
| 86 | } |
| 87 | c |
| 88 | } |
| 89 | |
| 90 | impl Mark { |
| 91 | /// Version 2 when the mark has a chain (always, for a mark this code |
| 92 | /// writes); version 1 otherwise. |
| 93 | pub fn encode(&self) -> Vec<u8> { |
| 94 | let (version, body) = match self.chain { |
| 95 | Some(_) => (VERSION, MARK_LEN - 32), |
| 96 | None => (1u32, MARK_LEN_V1 - 32), |
| 97 | }; |
| 98 | let mut b = vec![0u8; body + 32]; |
| 99 | b[..8].copy_from_slice(MAGIC); |
| 100 | b[8..12].copy_from_slice(&version.to_le_bytes()); |
| 101 | b[16..48].copy_from_slice(&self.machine_id); |
| 102 | b[48..56].copy_from_slice(&self.seq.to_le_bytes()); |
| 103 | b[56..64].copy_from_slice(&self.records.to_le_bytes()); |
| 104 | b[64..96].copy_from_slice(&self.digest); |
| 105 | if let Some(c) = &self.chain { |
| 106 | b[96..128].copy_from_slice(c); |
| 107 | } |
| 108 | let h = Sha256::digest(&b[..body]); |
| 109 | b[body..].copy_from_slice(&h); |
| 110 | b |
| 111 | } |
| 112 | |
| 113 | /// The mark in `b`, or why it is damaged. |
| 114 | pub fn decode(b: &[u8]) -> Result<Mark, String> { |
| 115 | if b.len() != MARK_LEN && b.len() != MARK_LEN_V1 { |
| 116 | return Err(format!( |
| 117 | "{} bytes, expected {MARK_LEN} ({MARK_LEN_V1} for version 1)", |
| 118 | b.len() |
| 119 | )); |
| 120 | } |
| 121 | if &b[..8] != MAGIC { |
| 122 | return Err("bad magic".into()); |
| 123 | } |
| 124 | let version = u32::from_le_bytes(b[8..12].try_into().expect("4 bytes")); |
| 125 | let want = if b.len() == MARK_LEN { VERSION } else { 1 }; |
| 126 | if version != want || b[12..16] != [0u8; 4] { |
| 127 | return Err(format!("unknown version {version} in {} bytes", b.len())); |
| 128 | } |
| 129 | let body = b.len() - 32; |
| 130 | if Sha256::digest(&b[..body])[..] != b[body..] { |
| 131 | return Err("checksum does not match".into()); |
| 132 | } |
| 133 | let m = Mark { |
| 134 | machine_id: b[16..48].try_into().expect("32 bytes"), |
| 135 | seq: u64::from_le_bytes(b[48..56].try_into().expect("8 bytes")), |
| 136 | records: u64::from_le_bytes(b[56..64].try_into().expect("8 bytes")), |
| 137 | digest: b[64..96].try_into().expect("32 bytes"), |
| 138 | chain: (version == VERSION).then(|| b[96..128].try_into().expect("32 bytes")), |
| 139 | }; |
| 140 | // No records means the initial chain. Anything else is the mark |
| 141 | // contradicting itself (and would seed the next save's chain), so it |
| 142 | // is refused as a damaged mark, not as changed history. |
| 143 | if m.records == 0 && m.chain.is_some_and(|c| c != [0u8; 32]) { |
| 144 | return Err( |
| 145 | "version 2 mark claims zero records but carries a non-initial chain".into(), |
| 146 | ); |
| 147 | } |
| 148 | Ok(m) |
| 149 | } |
| 150 | } |
| 151 | |
| 152 | /// `<compose dir>.cortex-mark`. |
| 153 | pub fn mark_path(dir: &Path) -> PathBuf { |
| 154 | let mut name = dir.as_os_str().to_owned(); |
| 155 | name.push(".cortex-mark"); |
| 156 | PathBuf::from(name) |
| 157 | } |
| 158 | |
| 159 | /// The mark at `path`: `Ok(None)` when there is none, `Err(why)` when the |
| 160 | /// file exists but is not a valid mark. |
| 161 | pub fn read(path: &Path) -> Result<Option<Mark>, String> { |
| 162 | match std::fs::read(path) { |
| 163 | Ok(b) => Mark::decode(&b) |
| 164 | .map(Some) |
| 165 | .map_err(|why| format!("{}: {why}", path.display())), |
| 166 | Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None), |
| 167 | Err(e) => Err(format!("{}: {e}", path.display())), |
| 168 | } |
| 169 | } |
| 170 | |
| 171 | /// Atomic replace: write `<path>.tmp`, sync it, rename over `path`, sync the |
| 172 | /// parent directory. A failure leaves the previous mark in place. |
| 173 | pub fn write(path: &Path, m: &Mark) -> Result<(), String> { |
| 174 | use std::io::Write; |
| 175 | use std::os::unix::fs::OpenOptionsExt; |
| 176 | let mut tmp = path.as_os_str().to_owned(); |
| 177 | tmp.push(".tmp"); |
| 178 | let tmp = PathBuf::from(tmp); |
| 179 | let res = (|| -> std::io::Result<()> { |
| 180 | let mut f = std::fs::OpenOptions::new() |
| 181 | .write(true) |
| 182 | .create(true) |
| 183 | .truncate(true) |
| 184 | .mode(0o600) |
| 185 | .open(&tmp)?; |
| 186 | f.write_all(&m.encode())?; |
| 187 | f.sync_all()?; |
| 188 | std::fs::rename(&tmp, path)?; |
| 189 | if let Some(p) = path.parent() { |
| 190 | std::fs::File::open(p)?.sync_all()?; |
| 191 | } |
| 192 | Ok(()) |
| 193 | })(); |
| 194 | res.map_err(|e| { |
| 195 | let _ = std::fs::remove_file(&tmp); |
| 196 | format!("write {}: {e}", path.display()) |
| 197 | }) |
| 198 | } |
| 199 | |
| 200 | /// Why a home is refused by its mark. |
| 201 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 202 | pub enum MarkRefusal { |
| 203 | Damaged(String), |
| 204 | Truncated { |
| 205 | file: u64, |
| 206 | mark: u64, |
| 207 | seq: u64, |
| 208 | }, |
| 209 | Digest { |
| 210 | record: u64, |
| 211 | seq: u64, |
| 212 | }, |
| 213 | /// Records #1..#records do not hash to the mark's chain: one before the |
| 214 | /// newest was changed, removed, reordered or spliced in (#408 row 8). |
| 215 | Chain { |
| 216 | records: u64, |
| 217 | seq: u64, |
| 218 | }, |
| 219 | } |
| 220 | |
| 221 | impl fmt::Display for MarkRefusal { |
| 222 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 223 | match self { |
| 224 | MarkRefusal::Damaged(why) => write!( |
| 225 | f, |
| 226 | "record mark damaged (E_MARK): {why}. Run RecoverComposeHome (aien compose recover)" |
| 227 | ), |
| 228 | MarkRefusal::Truncated { file, mark, seq } => write!( |
| 229 | f, |
| 230 | "Cortex journal holds {file} records, its record mark says {mark}: {} record(s) lost at a record boundary (E_MARK_TRUNCATED, mark seq {seq}). Run RecoverComposeHome (aien compose recover)", |
| 231 | mark - file |
| 232 | ), |
| 233 | MarkRefusal::Digest { record, seq } => write!( |
| 234 | f, |
| 235 | "Cortex record #{record} differs from its record mark (E_MARK_DIGEST, mark seq {seq}). Run RecoverComposeHome (aien compose recover)" |
| 236 | ), |
| 237 | MarkRefusal::Chain { records, seq } => write!( |
| 238 | f, |
| 239 | "Cortex records #1..#{records} do not hash to their record mark's chain: a record before the newest was changed, removed, reordered or spliced in (E_MARK_CHAIN, mark seq {seq}). Run RecoverComposeHome (aien compose recover)" |
| 240 | ), |
| 241 | } |
| 242 | } |
| 243 | } |
| 244 | |
| 245 | /// What the open does with the mark, decided before anything is appended. |
| 246 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 247 | pub enum Plan { |
| 248 | /// No mark, no journal: a new home; the mark is created after the open. |
| 249 | New, |
| 250 | /// No mark, a journal exists (an install older than the mark, or a |
| 251 | /// deleted mark): adopted and reported, never refused. |
| 252 | Adopt, |
| 253 | /// A mark exists and the journal is at least as long; its record #N |
| 254 | /// digest and the chain over #1..#N are checked once the home is open. |
| 255 | Verify(Mark), |
| 256 | } |
| 257 | |
| 258 | /// The count check (ACCEPTANCE-v3 2.2), from the probe count `file_records` |
| 259 | /// that `Compose::open` reports before any append. |
| 260 | pub fn plan( |
| 261 | mark: Option<&Mark>, |
| 262 | machine_id: &[u8; 32], |
| 263 | file_records: u64, |
| 264 | journal_present: bool, |
| 265 | ) -> Result<Plan, MarkRefusal> { |
| 266 | let Some(m) = mark else { |
| 267 | return Ok(if journal_present || file_records > 0 { |
| 268 | Plan::Adopt |
| 269 | } else { |
| 270 | Plan::New |
| 271 | }); |
| 272 | }; |
| 273 | if &m.machine_id != machine_id { |
| 274 | return Err(MarkRefusal::Damaged( |
| 275 | "the mark names another machine id".into(), |
| 276 | )); |
| 277 | } |
| 278 | if file_records < m.records { |
| 279 | return Err(MarkRefusal::Truncated { |
| 280 | file: file_records, |
| 281 | mark: m.records, |
| 282 | seq: m.seq, |
| 283 | }); |
| 284 | } |
| 285 | Ok(Plan::Verify(m.clone())) |
| 286 | } |
| 287 | |
| 288 | /// The digest check: record #`m.records` as the open home reads it |
| 289 | /// (`None` when it cannot be read). |
| 290 | pub fn check_digest(m: &Mark, at_mark: Option<[u8; 32]>) -> Result<(), MarkRefusal> { |
| 291 | if m.records == 0 { |
| 292 | return Ok(()); |
| 293 | } |
| 294 | if at_mark == Some(m.digest) { |
| 295 | Ok(()) |
| 296 | } else { |
| 297 | Err(MarkRefusal::Digest { |
| 298 | record: m.records, |
| 299 | seq: m.seq, |
| 300 | }) |
| 301 | } |
| 302 | } |
| 303 | |
| 304 | /// The continuity check (#408 row 8): the chain over records #1..#`m.records` |
| 305 | /// as the open home reads them (`None` when one cannot be read). A version 1 |
| 306 | /// mark has no chain to check. |
| 307 | pub fn check_chain(m: &Mark, at_mark: Option<[u8; 32]>) -> Result<(), MarkRefusal> { |
| 308 | let Some(want) = m.chain else { |
| 309 | return Ok(()); |
| 310 | }; |
| 311 | if m.records == 0 || at_mark == Some(want) { |
| 312 | Ok(()) |
| 313 | } else { |
| 314 | Err(MarkRefusal::Chain { |
| 315 | records: m.records, |
| 316 | seq: m.seq, |
| 317 | }) |
| 318 | } |
| 319 | } |
| 320 | |
| 321 | /// The one line the daemon prints for this open, if any (ACCEPTANCE-v3 2.2). |
| 322 | /// `probe` = records before the open appended anything; `written` = the mark |
| 323 | /// written at the end of the open, if one was. |
| 324 | pub fn open_event(plan: &Plan, probe: u64, written: Option<&Mark>) -> Option<String> { |
| 325 | match (plan, written) { |
| 326 | (Plan::New, Some(w)) => Some(format!( |
| 327 | "Cortex mark: mark created for a new home (seq {}, records {})", |
| 328 | w.seq, w.records |
| 329 | )), |
| 330 | (Plan::Adopt, Some(w)) => Some(format!( |
| 331 | "Cortex mark: mark adopted (seq {}, records {}): this home had no record mark; a loss before this start cannot be ruled out", |
| 332 | w.seq, w.records |
| 333 | )), |
| 334 | (Plan::Verify(m), _) if probe > m.records => Some(format!( |
| 335 | "Cortex mark: record mark advanced {}->{} (records written before an interrupted mark update; not corruption)", |
| 336 | m.records, probe |
| 337 | )), |
| 338 | (Plan::Verify(m), Some(w)) if m.chain.is_none() => Some(format!( |
| 339 | "Cortex mark: version 1 mark (seq {}, records {}) upgraded to version 2 (seq {}, records {}): records before this start were taken as read, without a chain check", |
| 340 | m.seq, m.records, w.seq, w.records |
| 341 | )), |
| 342 | _ => None, |
| 343 | } |
| 344 | } |
| 345 | |
| 346 | /// Where RecoverComposeHome keeps a mark it replaces: `<mark>.lost-<seq>` |
| 347 | /// (`.lost-damaged` when no seq is known), never over an existing file. |
| 348 | pub fn lost_path(mark: &Path, seq: Option<u64>) -> PathBuf { |
| 349 | let tag = seq.map_or_else(|| "damaged".to_string(), |s| s.to_string()); |
| 350 | let mut base = mark.as_os_str().to_owned(); |
| 351 | base.push(format!(".lost-{tag}")); |
| 352 | let base = PathBuf::from(base); |
| 353 | if !base.exists() { |
| 354 | return base; |
| 355 | } |
| 356 | (2u32..) |
| 357 | .map(|i| { |
| 358 | let mut p = base.as_os_str().to_owned(); |
| 359 | p.push(format!("-{i}")); |
| 360 | PathBuf::from(p) |
| 361 | }) |
| 362 | .find(|p| !p.exists()) |
| 363 | .expect("a free name") |
| 364 | } |
| 365 | |
| 366 | #[cfg(test)] |
| 367 | mod tests { |
| 368 | use super::*; |
| 369 | |
| 370 | fn mark(records: u64) -> Mark { |
| 371 | Mark { |
| 372 | machine_id: [7u8; 32], |
| 373 | seq: 4, |
| 374 | records, |
| 375 | digest: [9u8; 32], |
| 376 | chain: Some([3u8; 32]), |
| 377 | } |
| 378 | } |
| 379 | |
| 380 | #[test] |
| 381 | fn round_trip() { |
| 382 | let m = mark(23); |
| 383 | let b = m.encode(); |
| 384 | assert_eq!(b.len(), MARK_LEN); |
| 385 | assert_eq!(&b[..8], b"AIENCXM1"); |
| 386 | assert_eq!(Mark::decode(&b).unwrap(), m); |
| 387 | } |
| 388 | |
| 389 | #[test] |
| 390 | fn zero_records_with_a_chain_is_a_damaged_mark() { |
| 391 | // No records means the initial chain (32 zero bytes); anything else is |
| 392 | // the mark contradicting itself, not lost history. |
| 393 | let m = Mark { |
| 394 | records: 0, |
| 395 | digest: [0u8; 32], |
| 396 | ..mark(0) |
| 397 | }; |
| 398 | let e = Mark::decode(&m.encode()).unwrap_err(); |
| 399 | assert!(e.contains("zero records"), "{e}"); |
| 400 | let ok = Mark { |
| 401 | chain: Some([0u8; 32]), |
| 402 | ..m |
| 403 | }; |
| 404 | assert_eq!(Mark::decode(&ok.encode()).unwrap(), ok); |
| 405 | } |
| 406 | |
| 407 | #[test] |
| 408 | fn version_1_marks_still_read() { |
| 409 | let m = Mark { |
| 410 | chain: None, |
| 411 | ..mark(23) |
| 412 | }; |
| 413 | let b = m.encode(); |
| 414 | assert_eq!(b.len(), MARK_LEN_V1); |
| 415 | assert_eq!(&b[8..12], &1u32.to_le_bytes()); |
| 416 | assert_eq!(Mark::decode(&b).unwrap(), m); |
| 417 | // A version 2 header on 128 bytes (or version 1 on 160) is damage. |
| 418 | let mut x = b.clone(); |
| 419 | x[8] = 2; |
| 420 | assert!(Mark::decode(&x).unwrap_err().contains("version 2")); |
| 421 | let mut y = mark(23).encode(); |
| 422 | y[8] = 1; |
| 423 | assert!(Mark::decode(&y).unwrap_err().contains("version 1")); |
| 424 | } |
| 425 | |
| 426 | #[test] |
| 427 | fn chain_is_omega_running_hash() { |
| 428 | let (d1, d2) = ([1u8; 32], [2u8; 32]); |
| 429 | let mut want = [0u8; 32]; |
| 430 | for d in [d1, d2] { |
| 431 | let mut buf = [0u8; 64]; |
| 432 | buf[..32].copy_from_slice(&want); |
| 433 | buf[32..].copy_from_slice(&d); |
| 434 | want = Sha256::digest(buf).into(); |
| 435 | } |
| 436 | assert_eq!(chain_over([&d1, &d2]), want); |
| 437 | // Order, gaps and repeats all change it. |
| 438 | assert_ne!(chain_over([&d2, &d1]), want); |
| 439 | assert_ne!(chain_over([&d2]), chain_over([&d1, &d2])); |
| 440 | assert_ne!(chain_over([&d1, &d1, &d2]), want); |
| 441 | assert_eq!(chain_over(std::iter::empty::<&[u8; 32]>()), [0u8; 32]); |
| 442 | } |
| 443 | |
| 444 | #[test] |
| 445 | fn chain_check() { |
| 446 | let m = mark(23); |
| 447 | assert_eq!(check_chain(&m, Some([3u8; 32])), Ok(())); |
| 448 | assert_eq!( |
| 449 | check_chain(&m, Some([4u8; 32])), |
| 450 | Err(MarkRefusal::Chain { |
| 451 | records: 23, |
| 452 | seq: 4 |
| 453 | }) |
| 454 | ); |
| 455 | assert!(check_chain(&m, None).is_err()); |
| 456 | let v1 = Mark { |
| 457 | chain: None, |
| 458 | ..mark(23) |
| 459 | }; |
| 460 | assert_eq!(check_chain(&v1, None), Ok(())); |
| 461 | let t = MarkRefusal::Chain { |
| 462 | records: 23, |
| 463 | seq: 4, |
| 464 | } |
| 465 | .to_string(); |
| 466 | assert!( |
| 467 | t.contains("#1..#23") && t.contains("E_MARK_CHAIN, mark seq 4"), |
| 468 | "{t}" |
| 469 | ); |
| 470 | } |
| 471 | |
| 472 | #[test] |
| 473 | fn damaged_marks_are_named() { |
| 474 | let b = mark(23).encode(); |
| 475 | assert!(Mark::decode(&b[..127]).unwrap_err().contains("127 bytes")); |
| 476 | let mut x = b.clone(); |
| 477 | x[0] ^= 1; |
| 478 | assert_eq!(Mark::decode(&x).unwrap_err(), "bad magic"); |
| 479 | let mut x = b.clone(); |
| 480 | x[8] = 3; |
| 481 | assert!(Mark::decode(&x).unwrap_err().contains("version")); |
| 482 | for i in [16usize, 50, 60, 70, 100, 127, 140, 159] { |
| 483 | let mut x = b.clone(); |
| 484 | x[i] ^= 0x40; |
| 485 | assert!(Mark::decode(&x).is_err(), "flip at {i} accepted"); |
| 486 | } |
| 487 | } |
| 488 | |
| 489 | #[test] |
| 490 | fn plan_every_state() { |
| 491 | let id = [7u8; 32]; |
| 492 | assert_eq!(plan(None, &id, 0, false), Ok(Plan::New)); |
| 493 | assert_eq!(plan(None, &id, 0, true), Ok(Plan::Adopt)); |
| 494 | assert_eq!(plan(None, &id, 17, true), Ok(Plan::Adopt)); |
| 495 | let m = mark(23); |
| 496 | assert_eq!( |
| 497 | plan(Some(&m), &id, 22, true), |
| 498 | Err(MarkRefusal::Truncated { |
| 499 | file: 22, |
| 500 | mark: 23, |
| 501 | seq: 4 |
| 502 | }) |
| 503 | ); |
| 504 | assert_eq!(plan(Some(&m), &id, 23, true), Ok(Plan::Verify(m.clone()))); |
| 505 | assert_eq!(plan(Some(&m), &id, 24, true), Ok(Plan::Verify(m.clone()))); |
| 506 | assert!(matches!( |
| 507 | plan(Some(&m), &[1u8; 32], 23, true), |
| 508 | Err(MarkRefusal::Damaged(_)) |
| 509 | )); |
| 510 | } |
| 511 | |
| 512 | #[test] |
| 513 | fn digest_check() { |
| 514 | let m = mark(23); |
| 515 | assert_eq!(check_digest(&m, Some([9u8; 32])), Ok(())); |
| 516 | assert_eq!( |
| 517 | check_digest(&m, Some([8u8; 32])), |
| 518 | Err(MarkRefusal::Digest { record: 23, seq: 4 }) |
| 519 | ); |
| 520 | assert!(check_digest(&m, None).is_err()); |
| 521 | assert_eq!(check_digest(&mark(0), None), Ok(())); |
| 522 | } |
| 523 | |
| 524 | #[test] |
| 525 | fn refusal_text_names_the_code() { |
| 526 | let t = MarkRefusal::Truncated { |
| 527 | file: 22, |
| 528 | mark: 23, |
| 529 | seq: 4, |
| 530 | } |
| 531 | .to_string(); |
| 532 | assert!(t.contains("holds 22 records") && t.contains("says 23")); |
| 533 | assert!(t.contains("1 record(s) lost") && t.contains("E_MARK_TRUNCATED, mark seq 4")); |
| 534 | assert!(MarkRefusal::Digest { record: 5, seq: 1 } |
| 535 | .to_string() |
| 536 | .contains("E_MARK_DIGEST")); |
| 537 | assert!(MarkRefusal::Damaged("x".into()) |
| 538 | .to_string() |
| 539 | .contains("(E_MARK)")); |
| 540 | } |
| 541 | |
| 542 | #[test] |
| 543 | fn events() { |
| 544 | let w = mark(28); |
| 545 | assert!(open_event(&Plan::Adopt, 17, Some(&w)) |
| 546 | .unwrap() |
| 547 | .contains("mark adopted (seq 4, records 28)")); |
| 548 | assert!(open_event(&Plan::New, 0, Some(&w)) |
| 549 | .unwrap() |
| 550 | .contains("mark created for a new home")); |
| 551 | let m = mark(23); |
| 552 | assert!(open_event(&Plan::Verify(m.clone()), 24, Some(&w)) |
| 553 | .unwrap() |
| 554 | .contains("record mark advanced 23->24")); |
| 555 | assert_eq!(open_event(&Plan::Verify(m), 23, Some(&w)), None); |
| 556 | let v1 = Mark { |
| 557 | chain: None, |
| 558 | ..mark(23) |
| 559 | }; |
| 560 | assert!(open_event(&Plan::Verify(v1), 23, Some(&w)) |
| 561 | .unwrap() |
| 562 | .contains("upgraded to version 2")); |
| 563 | } |
| 564 | |
| 565 | #[test] |
| 566 | fn write_is_atomic_and_leaves_no_tmp() { |
| 567 | let d = tempfile::tempdir().unwrap(); |
| 568 | let p = mark_path(&d.path().join("compose")); |
| 569 | assert_eq!(read(&p), Ok(None)); |
| 570 | write(&p, &mark(5)).unwrap(); |
| 571 | assert_eq!(read(&p).unwrap(), Some(mark(5))); |
| 572 | write(&p, &mark(6)).unwrap(); |
| 573 | assert_eq!(read(&p).unwrap().unwrap().records, 6); |
| 574 | let names: Vec<String> = std::fs::read_dir(d.path()) |
| 575 | .unwrap() |
| 576 | .map(|e| e.unwrap().file_name().to_string_lossy().into_owned()) |
| 577 | .collect(); |
| 578 | assert_eq!(names, vec!["compose.cortex-mark".to_string()]); |
| 579 | use std::os::unix::fs::PermissionsExt; |
| 580 | let mode = std::fs::metadata(&p).unwrap().permissions().mode() & 0o777; |
| 581 | assert_eq!(mode, 0o600); |
| 582 | std::fs::write(&p, b"short").unwrap(); |
| 583 | assert!(read(&p).unwrap_err().contains("5 bytes")); |
| 584 | } |
| 585 | |
| 586 | #[test] |
| 587 | fn failed_write_keeps_the_old_mark() { |
| 588 | let d = tempfile::tempdir().unwrap(); |
| 589 | let p = mark_path(&d.path().join("compose")); |
| 590 | write(&p, &mark(5)).unwrap(); |
| 591 | // A directory in place of the tmp file makes the write fail. |
| 592 | let mut tmp = p.as_os_str().to_owned(); |
| 593 | tmp.push(".tmp"); |
| 594 | std::fs::create_dir(PathBuf::from(&tmp)).unwrap(); |
| 595 | assert!(write(&p, &mark(6)).is_err()); |
| 596 | assert_eq!(read(&p).unwrap(), Some(mark(5))); |
| 597 | } |
| 598 | |
| 599 | #[test] |
| 600 | fn lost_path_never_overwrites() { |
| 601 | let d = tempfile::tempdir().unwrap(); |
| 602 | let p = mark_path(&d.path().join("compose")); |
| 603 | let a = lost_path(&p, Some(3)); |
| 604 | assert!(a.to_string_lossy().ends_with("compose.cortex-mark.lost-3")); |
| 605 | std::fs::write(&a, b"x").unwrap(); |
| 606 | let b = lost_path(&p, Some(3)); |
| 607 | assert!(b.to_string_lossy().ends_with(".lost-3-2")); |
| 608 | assert!(lost_path(&p, None) |
| 609 | .to_string_lossy() |
| 610 | .ends_with(".lost-damaged")); |
| 611 | } |
| 612 | } |