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/patches/ecbd854df4665e82 # 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 ## GitHub aien-dev/aien-sovereign-core-mv#847 (code only) closed derived `ecbd854df4665e82` #847 Imported from GitHub aien-dev/aien-sovereign-core-mv#847 (code only) GitHub's metadata for this pull request is unavailable: its state is DERIVED from the commits (merged: the head is reachable from this project's main; open: GitHub kept a merge ref; else closed). Base `0aaf970e33c0fdbeae7929ffe789f0f81f4451b7` · Head `919d9d4c0b32d348721c81f9f0533762e1fdbfd8` ### Fetch it A git bundle of the pull request's head, 5314 bytes. ``` curl -fsSL https://interplane.io/drakestapleton/aien-sovereign-core-mv/patches/ecbd854df4665e82.bundle -o ecbd854df4665e82.bundle git fetch ecbd854df4665e82.bundle refs/pull/847/head ``` Raw bundle · Diff ### Provenance This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record: ``` github-import 1 aien-dev/aien-sovereign-core-mv 847 919d9d4c0b32d348721c81f9f0533762e1fdbfd8 ``` ``` {"kind":"github-import","owner":"aien-dev","repo":"aien-sovereign-core-mv","number":847,"url":"https://github.com/aien-dev/aien-sovereign-core-mv/pull/847","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:38:07Z","metadata":"unavailable","state_derived":true} ``` ### Changes ``` diff --git a/.crumb b/.crumb index b75d48d2..5af7743d 100644 --- a/.crumb +++ b/.crumb @@ -125,14 +125,14 @@ } ], "children_root": "sha256:9336db0a6669d32e68cee16900dfe9fc9e27304c00dc48daee6578317bf57d2c", - "compiled_at": "2026-10-31T05:14:03Z", + "compiled_at": "2026-10-31T05:29:08Z", "compiler": "crumb-compile/1", - "digest": "sha256:fc5f81f65678705d8ab921d1fdd3633c3d3f94b8d201d9ad21a0c8370d42d179", + "digest": "sha256:568c0cb1be7be888227411530811d7bebf9e62473ad2ffde25b65f7f5c69f006", "evidence_files": 3602, "evidence_root": "sha256:1b8069934a4cc67803874ebd2ad5de32671fae5ccce1a3ea70aeb532fe8ea86b", "files": 8117, - "generated_at_commit": "19bd12c0711e732a6848d212a90ea84b1f2be7e5", - "source_tree": "sha256:1d37bf97fa9c01b4ed970f7057cf5132efafd6f74431a1788dc6217c267817c3" + "generated_at_commit": "9eebe089902cb27c15ca878881bb36756cd45fd2", + "source_tree": "sha256:9d392cd752f0900d75cf181610c112b24183259e26694da3f475797aeccda8b6" } }, "history": [], diff --git a/crates/aien-proof/src/ledger.rs b/crates/aien-proof/src/ledger.rs index 6f74b059..5c087f07 100644 --- a/crates/aien-proof/src/ledger.rs +++ b/crates/aien-proof/src/ledger.rs @@ -86,7 +86,42 @@ fn now() -> u64 { .unwrap_or(0) } +/// Message for a ledger whose last line has no closing newline: an append was +/// cut off (for example by ENOSPC) and the bytes after `intact` are not a +/// sealed event. Callers fail closed on it instead of skipping the torn line. +fn torn_tail(path: &Path, len: u64, intact: u64) -> String { + let newline = match intact { + 0 => "the file has no newline".to_string(), + n => format!("last newline at byte offset {}", n - 1), + }; + format!( + "{}: torn tail: an append was cut off and left {} byte(s) without a closing newline \ + ({newline}); the chain is intact up to byte offset {intact}", + path.display(), + len - intact + ) +} + +/// Length of the prefix of `file` (of length `len`) that ends with a newline, +/// scanning backwards from the end in fixed chunks. 0 when there is none. +fn intact_len(file: &mut File, len: u64) -> io::Result { + let mut buf = vec![0u8; 64 * 1024]; + let mut end = len; + while end > 0 { + let from = end.saturating_sub(buf.len() as u64); + let chunk = &mut buf[..(end - from) as usize]; + file.seek(SeekFrom::Start(from))?; + file.read_exact(chunk)?; + if let Some(p) = chunk.iter().rposition(|&b| b == b'\n') { + return Ok(from + p as u64 + 1); + } + end = from; + } + Ok(0) +} + /// Last event, read from the file tail so appends stay O(1) as the ledger grows. +/// A tail without a closing newline is a cut-off append and fails closed. fn last_event(path: &Path) -> io::Result> { let mut file = match File::open(path) { Ok(f) => f, @@ -94,16 +129,47 @@ fn last_event(path: &Path) -> io::Result> { Err(e) => return Err(e), }; let len = file.metadata()?.len(); + if len == 0 { + return Ok(None); + } let start = len.saturating_sub(64 * 1024); file.seek(SeekFrom::Start(start))?; - let mut tail = String::new(); - file.read_to_string(&mut tail)?; - match tail.lines().rev().find(|l| !l.trim().is_empty()) { - Some(line) => Ok(Some(serde_json::from_str(line)?)), + let mut tail = Vec::new(); + file.read_to_end(&mut tail)?; + if tail.last() != Some(&b'\n') { + let intact = intact_len(&mut file, len)?; + return Err(io::Error::new( + io::ErrorKind::InvalidData, + torn_tail(path, len, intact), + )); + } + match tail + .split(|&b| b == b'\n') + .rev() + .find(|l| !l.trim_ascii().is_empty()) + { + Some(line) => Ok(Some(serde_json::from_slice(line)?)), None => Ok(None), } } +/// Whole ledger text, `None` when the file does not exist. A non-empty ledger +/// that does not end with a newline is a torn tail and is an error. +fn read_ledger(path: &Path) -> Result, String> { + let bytes = match fs::read(path) { + Ok(b) => b, + Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(None), + Err(e) => return Err(e.to_string()), + }; + if !bytes.is_empty() && bytes.last() != Some(&b'\n') { + let intact = bytes.iter().rposition(|&b| b == b'\n').map_or(0, |p| p + 1); + return Err(torn_tail(path, bytes.len() as u64, intact as u64)); + } + String::from_utf8(bytes) + .map(Some) + .map_err(|e| format!("{}: {e}", path.display())) +} + /// Seal and append one test event. `payload` is the run's full output. pub fn append( root: &Path, @@ -123,6 +189,32 @@ pub fn append_action( target: &str, intent: &str, payload: &[u8], +) -> io::Result { + append_with( + root, + action, + agent, + target, + intent, + payload, + |file, line| { + file.write_all(line)?; + file.sync_data() + }, + ) +} + +/// `append_action` with the write-and-sync step passed in, so tests can make it +/// fail part way. On failure the ledger is truncated back to its length before +/// the append, leaving it byte-identical, and the original error is returned. +fn append_with( + root: &Path, + action: &str, + agent: &str, + target: &str, + intent: &str, + payload: &[u8], + write: impl FnOnce(&mut File, &[u8]) -> io::Result<()>, ) -> io::Result { fs::create_dir_all(root)?; let _guard = FileLock::acquire(&root.join("ledger.lock"))?; @@ -157,17 +249,28 @@ pub fn append_action( let mut line = serde_json::to_string(&event)?; line.push('\n'); let mut file = OpenOptions::new().create(true).append(true).open(&path)?; - file.write_all(line.as_bytes())?; - file.sync_data()?; + // Under the ledger lock, so no other writer moves the end while we hold it. + let before = file.metadata()?.len(); + if let Err(err) = write(&mut file, line.as_bytes()) { + return Err(match file.set_len(before).and_then(|()| file.sync_data()) { + Ok(()) => err, + Err(rollback) => io::Error::new( + err.kind(), + format!( + "{}: append of event {index} failed: {err}; rollback to {before} bytes \ + also failed: {rollback}", + path.display() + ), + ), + }); + } Ok(event) } /// Verify the whole chain. Returns the event count and head hash. pub fn verify(path: &Path) -> Result<(u64, [u8; 32]), String> { - let text = match fs::read_to_string(path) { - Ok(t) => t, - Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok((0, [0u8; 32])), - Err(e) => return Err(e.to_string()), + let Some(text) = read_ledger(path)? else { + return Ok((0, [0u8; 32])); }; let (mut expected, mut parent, mut last_ts) = (0u64, [0u8; 32], 0u64); for (n, line) in text.lines().filter(|l| !l.trim().is_empty()).enumerate() { @@ -204,10 +307,8 @@ pub fn hex(bytes: &[u8; 32]) -> String { /// Read the event at `index`, or `Ok(None)` when the ledger is shorter. pub fn read_event(path: &Path, index: u64) -> Result, String> { - let text = match fs::read_to_string(path) { - Ok(t) => t, - Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(None), - Err(e) => return Err(e.to_string()), + let Some(text) = read_ledger(path)? else { + return Ok(None); }; for (n, line) in text.lines().filter(|l| !l.trim().is_empty()).enumerate() { let e: LedgerEvent = @@ -250,4 +351,93 @@ mod tests { assert_eq!(b.parent_hash, a.hash); assert_eq!(b.index, 1); } + + fn enospc() -> io::Error { + io::Error::from_raw_os_error(libc::ENOSPC) + } + + #[test] + fn failed_append_rolls_back_and_next_append_links() { + let root = temp_dir("ledger-rollback"); + let path = root.join(LEDGER_FILE); + // A failed genesis append must leave an empty ledger. + let err = append_with(&root, "test", "t", "g", "pass", b"0", |f, line| { + f.write_all(&line[..line.len() / 2])?; + Err(enospc()) + }) + .unwrap_err(); + assert_eq!(err.raw_os_error(), Some(libc::ENOSPC)); + assert_eq!(fs::read(&path).unwrap(), b""); + + let a = append(&root, "t", "a", "pass", b"1").unwrap(); + let b = append(&root, "t", "b", "pass", b"2").unwrap(); + assert_eq!(a.index, 0); + let before = fs::read(&path).unwrap(); + + // Half the line written then ENOSPC, and the whole line written then a + // failed sync: both must leave the ledger byte-identical. + let half = |f: &mut File, line: &[u8]| { + f.write_all(&line[..line.len() / 2])?; + Err(enospc()) + }; + let synced = |f: &mut File, line: &[u8]| { + f.write_all(line)?; + Err(enospc()) + }; + for step in [ + &half as &dyn Fn(&mut File, &[u8]) -> io::Result<()>, + &synced, + ] { + let err = append_with(&root, "test", "t", "c", "pass", b"3", step).unwrap_err(); + assert_eq!(err.raw_os_error(), Some(libc::ENOSPC)); + assert_eq!(fs::read(&path).unwrap(), before); + assert_eq!(verify(&path).unwrap(), (2, b.hash)); + } + + let c = append(&root, "t", "c", "pass", b"3").unwrap(); + assert_eq!(c.index, 2); + assert_eq!(c.parent_hash, b.hash); + assert_eq!(verify(&path).unwrap(), (3, c.hash)); + } + + #[test] + fn torn_tail_fails_closed_with_clear_error() { + let root = temp_dir("ledger-torn"); + let path = root.join(LEDGER_FILE); + append(&root, "t", "a", "pass", b"1").unwrap(); + append(&root, "t", "b", "pass", b"2").unwrap(); + let intact = fs::metadata(&path).unwrap().len(); + let torn = b"{\"index\":2,\"timestamp\":1,\"agent\":\"t"; + let mut f = OpenOptions::new().append(true).open(&path).unwrap(); + f.write_all(torn).unwrap(); + drop(f); + + let expected = format!( + "torn tail: an append was cut off and left {} byte(s) without a closing newline \ + (last newline at byte offset {}); the chain is intact up to byte offset {intact}", + torn.len(), + intact - 1 + ); + let err = append(&root, "t", "c", "pass", b"3").unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::InvalidData); + assert!(err.to_string().contains(&expected), "{err}"); + let err = verify(&path).unwrap_err(); + assert!(err.contains(&expected), "{err}"); + assert!(!err.contains("EOF"), "{err}"); + let err = read_event(&path, 0).unwrap_err(); + assert!(err.contains(&expected), "{err}"); + // The failed append must not have touched the torn file either. + assert_eq!( + fs::metadata(&path).unwrap().len(), + intact + torn.len() as u64 + ); + + // A ledger that is only a torn line names offset 0. + fs::write(&path, &torn[..10]).unwrap(); + let err = verify(&path).unwrap_err(); + assert!( + err.contains("left 10 byte(s) without a closing newline (the file has no newline); the chain is intact up to byte offset 0"), + "{err}" + ); + } } ```