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-proof / src / ledger.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 | //! The quality ledger: one append-only JSON line per real run, sealed with the |
| 17 | //! Crumb ledger event hash (RFC-0001 section 8.3, `CRUMB_LEDGER_EVENT_V1`), so |
| 18 | //! each line deserializes as a `crumb_spec::ledger::LedgerEvent` and editing any |
| 19 | //! past line breaks every hash after it. |
| 20 | |
| 21 | use crate::lock::FileLock; |
| 22 | use serde::{Deserialize, Serialize}; |
| 23 | use std::fs::{self, File, OpenOptions}; |
| 24 | use std::io::{self, Read, Seek, SeekFrom, Write}; |
| 25 | use std::path::Path; |
| 26 | use std::time::{SystemTime, UNIX_EPOCH}; |
| 27 | |
| 28 | pub const LEDGER_FILE: &str = "ledger.jsonl"; |
| 29 | |
| 30 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 31 | pub struct LedgerEvent { |
| 32 | pub index: u64, |
| 33 | pub timestamp: u64, |
| 34 | pub agent: String, |
| 35 | pub action: String, |
| 36 | pub target: String, |
| 37 | pub intent: String, |
| 38 | pub payload_hash: [u8; 32], |
| 39 | pub parent_hash: [u8; 32], |
| 40 | pub hash: [u8; 32], |
| 41 | } |
| 42 | |
| 43 | #[allow(clippy::too_many_arguments)] |
| 44 | pub fn compute_hash( |
| 45 | index: u64, |
| 46 | timestamp: u64, |
| 47 | agent: &str, |
| 48 | action: &str, |
| 49 | target: &str, |
| 50 | intent: &str, |
| 51 | payload_hash: &[u8; 32], |
| 52 | parent_hash: &[u8; 32], |
| 53 | ) -> [u8; 32] { |
| 54 | let mut h = blake3::Hasher::new(); |
| 55 | h.update(b"CRUMB_LEDGER_EVENT_V1"); |
| 56 | h.update(&index.to_be_bytes()); |
| 57 | h.update(×tamp.to_be_bytes()); |
| 58 | for s in [agent, action, target, intent] { |
| 59 | h.update(&(s.len() as u32).to_be_bytes()); |
| 60 | h.update(s.as_bytes()); |
| 61 | } |
| 62 | h.update(payload_hash); |
| 63 | h.update(parent_hash); |
| 64 | *h.finalize().as_bytes() |
| 65 | } |
| 66 | |
| 67 | impl LedgerEvent { |
| 68 | fn recompute(&self) -> [u8; 32] { |
| 69 | compute_hash( |
| 70 | self.index, |
| 71 | self.timestamp, |
| 72 | &self.agent, |
| 73 | &self.action, |
| 74 | &self.target, |
| 75 | &self.intent, |
| 76 | &self.payload_hash, |
| 77 | &self.parent_hash, |
| 78 | ) |
| 79 | } |
| 80 | } |
| 81 | |
| 82 | fn now() -> u64 { |
| 83 | SystemTime::now() |
| 84 | .duration_since(UNIX_EPOCH) |
| 85 | .map(|d| d.as_secs()) |
| 86 | .unwrap_or(0) |
| 87 | } |
| 88 | |
| 89 | /// Message for a ledger whose last line has no closing newline: an append was |
| 90 | /// cut off (for example by ENOSPC) and the bytes after `intact` are not a |
| 91 | /// sealed event. Callers fail closed on it instead of skipping the torn line. |
| 92 | fn torn_tail(path: &Path, len: u64, intact: u64) -> String { |
| 93 | let newline = match intact { |
| 94 | 0 => "the file has no newline".to_string(), |
| 95 | n => format!("last newline at byte offset {}", n - 1), |
| 96 | }; |
| 97 | format!( |
| 98 | "{}: torn tail: an append was cut off and left {} byte(s) without a closing newline \ |
| 99 | ({newline}); the chain is intact up to byte offset {intact}", |
| 100 | path.display(), |
| 101 | len - intact |
| 102 | ) |
| 103 | } |
| 104 | |
| 105 | /// Length of the prefix of `file` (of length `len`) that ends with a newline, |
| 106 | /// scanning backwards from the end in fixed chunks. 0 when there is none. |
| 107 | fn intact_len(file: &mut File, len: u64) -> io::Result<u64> { |
| 108 | let mut buf = vec![0u8; 64 * 1024]; |
| 109 | let mut end = len; |
| 110 | while end > 0 { |
| 111 | let from = end.saturating_sub(buf.len() as u64); |
| 112 | let chunk = &mut buf[..(end - from) as usize]; |
| 113 | file.seek(SeekFrom::Start(from))?; |
| 114 | file.read_exact(chunk)?; |
| 115 | if let Some(p) = chunk.iter().rposition(|&b| b == b'\n') { |
| 116 | return Ok(from + p as u64 + 1); |
| 117 | } |
| 118 | end = from; |
| 119 | } |
| 120 | Ok(0) |
| 121 | } |
| 122 | |
| 123 | /// Last event, read from the file tail so appends stay O(1) as the ledger grows. |
| 124 | /// A tail without a closing newline is a cut-off append and fails closed. |
| 125 | fn last_event(path: &Path) -> io::Result<Option<LedgerEvent>> { |
| 126 | let mut file = match File::open(path) { |
| 127 | Ok(f) => f, |
| 128 | Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(None), |
| 129 | Err(e) => return Err(e), |
| 130 | }; |
| 131 | let len = file.metadata()?.len(); |
| 132 | if len == 0 { |
| 133 | return Ok(None); |
| 134 | } |
| 135 | let start = len.saturating_sub(64 * 1024); |
| 136 | file.seek(SeekFrom::Start(start))?; |
| 137 | let mut tail = Vec::new(); |
| 138 | file.read_to_end(&mut tail)?; |
| 139 | if tail.last() != Some(&b'\n') { |
| 140 | let intact = intact_len(&mut file, len)?; |
| 141 | return Err(io::Error::new( |
| 142 | io::ErrorKind::InvalidData, |
| 143 | torn_tail(path, len, intact), |
| 144 | )); |
| 145 | } |
| 146 | match tail |
| 147 | .split(|&b| b == b'\n') |
| 148 | .rev() |
| 149 | .find(|l| !l.trim_ascii().is_empty()) |
| 150 | { |
| 151 | Some(line) => Ok(Some(serde_json::from_slice(line)?)), |
| 152 | None => Ok(None), |
| 153 | } |
| 154 | } |
| 155 | |
| 156 | /// Whole ledger text, `None` when the file does not exist. A non-empty ledger |
| 157 | /// that does not end with a newline is a torn tail and is an error. |
| 158 | fn read_ledger(path: &Path) -> Result<Option<String>, String> { |
| 159 | let bytes = match fs::read(path) { |
| 160 | Ok(b) => b, |
| 161 | Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(None), |
| 162 | Err(e) => return Err(e.to_string()), |
| 163 | }; |
| 164 | if !bytes.is_empty() && bytes.last() != Some(&b'\n') { |
| 165 | let intact = bytes.iter().rposition(|&b| b == b'\n').map_or(0, |p| p + 1); |
| 166 | return Err(torn_tail(path, bytes.len() as u64, intact as u64)); |
| 167 | } |
| 168 | String::from_utf8(bytes) |
| 169 | .map(Some) |
| 170 | .map_err(|e| format!("{}: {e}", path.display())) |
| 171 | } |
| 172 | |
| 173 | /// Seal and append one test event. `payload` is the run's full output. |
| 174 | pub fn append( |
| 175 | root: &Path, |
| 176 | agent: &str, |
| 177 | target: &str, |
| 178 | intent: &str, |
| 179 | payload: &[u8], |
| 180 | ) -> io::Result<LedgerEvent> { |
| 181 | append_action(root, "test", agent, target, intent, payload) |
| 182 | } |
| 183 | |
| 184 | /// Seal and append one event with a Crumb action such as `test` or `audit`. |
| 185 | pub fn append_action( |
| 186 | root: &Path, |
| 187 | action: &str, |
| 188 | agent: &str, |
| 189 | target: &str, |
| 190 | intent: &str, |
| 191 | payload: &[u8], |
| 192 | ) -> io::Result<LedgerEvent> { |
| 193 | append_with( |
| 194 | root, |
| 195 | action, |
| 196 | agent, |
| 197 | target, |
| 198 | intent, |
| 199 | payload, |
| 200 | |file, line| { |
| 201 | file.write_all(line)?; |
| 202 | file.sync_data() |
| 203 | }, |
| 204 | ) |
| 205 | } |
| 206 | |
| 207 | /// `append_action` with the write-and-sync step passed in, so tests can make it |
| 208 | /// fail part way. On failure the ledger is truncated back to its length before |
| 209 | /// the append, leaving it byte-identical, and the original error is returned. |
| 210 | fn append_with( |
| 211 | root: &Path, |
| 212 | action: &str, |
| 213 | agent: &str, |
| 214 | target: &str, |
| 215 | intent: &str, |
| 216 | payload: &[u8], |
| 217 | write: impl FnOnce(&mut File, &[u8]) -> io::Result<()>, |
| 218 | ) -> io::Result<LedgerEvent> { |
| 219 | fs::create_dir_all(root)?; |
| 220 | let _guard = FileLock::acquire(&root.join("ledger.lock"))?; |
| 221 | let path = root.join(LEDGER_FILE); |
| 222 | let (index, parent_hash, last_ts) = match last_event(&path)? { |
| 223 | Some(e) => (e.index + 1, e.hash, e.timestamp), |
| 224 | None => (0, [0u8; 32], 0), |
| 225 | }; |
| 226 | let timestamp = now().max(last_ts); |
| 227 | let payload_hash = *blake3::hash(payload).as_bytes(); |
| 228 | let hash = compute_hash( |
| 229 | index, |
| 230 | timestamp, |
| 231 | agent, |
| 232 | action, |
| 233 | target, |
| 234 | intent, |
| 235 | &payload_hash, |
| 236 | &parent_hash, |
| 237 | ); |
| 238 | let event = LedgerEvent { |
| 239 | index, |
| 240 | timestamp, |
| 241 | agent: agent.to_string(), |
| 242 | action: action.to_string(), |
| 243 | target: target.to_string(), |
| 244 | intent: intent.to_string(), |
| 245 | payload_hash, |
| 246 | parent_hash, |
| 247 | hash, |
| 248 | }; |
| 249 | let mut line = serde_json::to_string(&event)?; |
| 250 | line.push('\n'); |
| 251 | let mut file = OpenOptions::new().create(true).append(true).open(&path)?; |
| 252 | // Under the ledger lock, so no other writer moves the end while we hold it. |
| 253 | let before = file.metadata()?.len(); |
| 254 | if let Err(err) = write(&mut file, line.as_bytes()) { |
| 255 | return Err(match file.set_len(before).and_then(|()| file.sync_data()) { |
| 256 | Ok(()) => err, |
| 257 | Err(rollback) => io::Error::new( |
| 258 | err.kind(), |
| 259 | format!( |
| 260 | "{}: append of event {index} failed: {err}; rollback to {before} bytes \ |
| 261 | also failed: {rollback}", |
| 262 | path.display() |
| 263 | ), |
| 264 | ), |
| 265 | }); |
| 266 | } |
| 267 | Ok(event) |
| 268 | } |
| 269 | |
| 270 | /// Verify the whole chain. Returns the event count and head hash. |
| 271 | pub fn verify(path: &Path) -> Result<(u64, [u8; 32]), String> { |
| 272 | let Some(text) = read_ledger(path)? else { |
| 273 | return Ok((0, [0u8; 32])); |
| 274 | }; |
| 275 | let (mut expected, mut parent, mut last_ts) = (0u64, [0u8; 32], 0u64); |
| 276 | for (n, line) in text.lines().filter(|l| !l.trim().is_empty()).enumerate() { |
| 277 | let e: LedgerEvent = |
| 278 | serde_json::from_str(line).map_err(|err| format!("line {}: {err}", n + 1))?; |
| 279 | if e.index != expected { |
| 280 | return Err(format!("event {}: index gap, expected {expected}", e.index)); |
| 281 | } |
| 282 | if e.parent_hash != parent { |
| 283 | return Err(format!( |
| 284 | "event {}: parent hash does not match previous event", |
| 285 | e.index |
| 286 | )); |
| 287 | } |
| 288 | if e.timestamp < last_ts { |
| 289 | return Err(format!("event {}: timestamp goes backwards", e.index)); |
| 290 | } |
| 291 | if e.recompute() != e.hash { |
| 292 | return Err(format!( |
| 293 | "event {}: hash mismatch, event was altered", |
| 294 | e.index |
| 295 | )); |
| 296 | } |
| 297 | expected += 1; |
| 298 | parent = e.hash; |
| 299 | last_ts = e.timestamp; |
| 300 | } |
| 301 | Ok((expected, parent)) |
| 302 | } |
| 303 | |
| 304 | pub fn hex(bytes: &[u8; 32]) -> String { |
| 305 | bytes.iter().map(|b| format!("{b:02x}")).collect() |
| 306 | } |
| 307 | |
| 308 | /// Read the event at `index`, or `Ok(None)` when the ledger is shorter. |
| 309 | pub fn read_event(path: &Path, index: u64) -> Result<Option<LedgerEvent>, String> { |
| 310 | let Some(text) = read_ledger(path)? else { |
| 311 | return Ok(None); |
| 312 | }; |
| 313 | for (n, line) in text.lines().filter(|l| !l.trim().is_empty()).enumerate() { |
| 314 | let e: LedgerEvent = |
| 315 | serde_json::from_str(line).map_err(|err| format!("line {}: {err}", n + 1))?; |
| 316 | if e.index == index { |
| 317 | return Ok(Some(e)); |
| 318 | } |
| 319 | } |
| 320 | Ok(None) |
| 321 | } |
| 322 | |
| 323 | #[cfg(test)] |
| 324 | mod tests { |
| 325 | use super::*; |
| 326 | use crate::testutil::temp_dir; |
| 327 | |
| 328 | #[test] |
| 329 | fn chain_verifies_and_tampering_is_caught() { |
| 330 | let root = temp_dir("ledger"); |
| 331 | for i in 0..3 { |
| 332 | append(&root, "tester", &format!("job-{i}"), "pass exit=0", b"ok").unwrap(); |
| 333 | } |
| 334 | let path = root.join(LEDGER_FILE); |
| 335 | let (count, _) = verify(&path).unwrap(); |
| 336 | assert_eq!(count, 3); |
| 337 | |
| 338 | let tampered = fs::read_to_string(&path) |
| 339 | .unwrap() |
| 340 | .replacen("job-1", "job-X", 1); |
| 341 | fs::write(&path, tampered).unwrap(); |
| 342 | assert!(verify(&path).unwrap_err().contains("event 1")); |
| 343 | } |
| 344 | |
| 345 | #[test] |
| 346 | fn genesis_parent_is_zero_and_events_link() { |
| 347 | let root = temp_dir("ledger-link"); |
| 348 | let a = append(&root, "t", "a", "pass", b"1").unwrap(); |
| 349 | let b = append(&root, "t", "b", "pass", b"2").unwrap(); |
| 350 | assert_eq!(a.parent_hash, [0u8; 32]); |
| 351 | assert_eq!(b.parent_hash, a.hash); |
| 352 | assert_eq!(b.index, 1); |
| 353 | } |
| 354 | |
| 355 | fn enospc() -> io::Error { |
| 356 | io::Error::from_raw_os_error(libc::ENOSPC) |
| 357 | } |
| 358 | |
| 359 | #[test] |
| 360 | fn failed_append_rolls_back_and_next_append_links() { |
| 361 | let root = temp_dir("ledger-rollback"); |
| 362 | let path = root.join(LEDGER_FILE); |
| 363 | // A failed genesis append must leave an empty ledger. |
| 364 | let err = append_with(&root, "test", "t", "g", "pass", b"0", |f, line| { |
| 365 | f.write_all(&line[..line.len() / 2])?; |
| 366 | Err(enospc()) |
| 367 | }) |
| 368 | .unwrap_err(); |
| 369 | assert_eq!(err.raw_os_error(), Some(libc::ENOSPC)); |
| 370 | assert_eq!(fs::read(&path).unwrap(), b""); |
| 371 | |
| 372 | let a = append(&root, "t", "a", "pass", b"1").unwrap(); |
| 373 | let b = append(&root, "t", "b", "pass", b"2").unwrap(); |
| 374 | assert_eq!(a.index, 0); |
| 375 | let before = fs::read(&path).unwrap(); |
| 376 | |
| 377 | // Half the line written then ENOSPC, and the whole line written then a |
| 378 | // failed sync: both must leave the ledger byte-identical. |
| 379 | let half = |f: &mut File, line: &[u8]| { |
| 380 | f.write_all(&line[..line.len() / 2])?; |
| 381 | Err(enospc()) |
| 382 | }; |
| 383 | let synced = |f: &mut File, line: &[u8]| { |
| 384 | f.write_all(line)?; |
| 385 | Err(enospc()) |
| 386 | }; |
| 387 | for step in [ |
| 388 | &half as &dyn Fn(&mut File, &[u8]) -> io::Result<()>, |
| 389 | &synced, |
| 390 | ] { |
| 391 | let err = append_with(&root, "test", "t", "c", "pass", b"3", step).unwrap_err(); |
| 392 | assert_eq!(err.raw_os_error(), Some(libc::ENOSPC)); |
| 393 | assert_eq!(fs::read(&path).unwrap(), before); |
| 394 | assert_eq!(verify(&path).unwrap(), (2, b.hash)); |
| 395 | } |
| 396 | |
| 397 | let c = append(&root, "t", "c", "pass", b"3").unwrap(); |
| 398 | assert_eq!(c.index, 2); |
| 399 | assert_eq!(c.parent_hash, b.hash); |
| 400 | assert_eq!(verify(&path).unwrap(), (3, c.hash)); |
| 401 | } |
| 402 | |
| 403 | #[test] |
| 404 | fn torn_tail_fails_closed_with_clear_error() { |
| 405 | let root = temp_dir("ledger-torn"); |
| 406 | let path = root.join(LEDGER_FILE); |
| 407 | append(&root, "t", "a", "pass", b"1").unwrap(); |
| 408 | append(&root, "t", "b", "pass", b"2").unwrap(); |
| 409 | let intact = fs::metadata(&path).unwrap().len(); |
| 410 | let torn = b"{\"index\":2,\"timestamp\":1,\"agent\":\"t"; |
| 411 | let mut f = OpenOptions::new().append(true).open(&path).unwrap(); |
| 412 | f.write_all(torn).unwrap(); |
| 413 | drop(f); |
| 414 | |
| 415 | let expected = format!( |
| 416 | "torn tail: an append was cut off and left {} byte(s) without a closing newline \ |
| 417 | (last newline at byte offset {}); the chain is intact up to byte offset {intact}", |
| 418 | torn.len(), |
| 419 | intact - 1 |
| 420 | ); |
| 421 | let err = append(&root, "t", "c", "pass", b"3").unwrap_err(); |
| 422 | assert_eq!(err.kind(), io::ErrorKind::InvalidData); |
| 423 | assert!(err.to_string().contains(&expected), "{err}"); |
| 424 | let err = verify(&path).unwrap_err(); |
| 425 | assert!(err.contains(&expected), "{err}"); |
| 426 | assert!(!err.contains("EOF"), "{err}"); |
| 427 | let err = read_event(&path, 0).unwrap_err(); |
| 428 | assert!(err.contains(&expected), "{err}"); |
| 429 | // The failed append must not have touched the torn file either. |
| 430 | assert_eq!( |
| 431 | fs::metadata(&path).unwrap().len(), |
| 432 | intact + torn.len() as u64 |
| 433 | ); |
| 434 | |
| 435 | // A ledger that is only a torn line names offset 0. |
| 436 | fs::write(&path, &torn[..10]).unwrap(); |
| 437 | let err = verify(&path).unwrap_err(); |
| 438 | assert!( |
| 439 | err.contains("left 10 byte(s) without a closing newline (the file has no newline); the chain is intact up to byte offset 0"), |
| 440 | "{err}" |
| 441 | ); |
| 442 | } |
| 443 | } |