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/spark-harness/src/journal.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 / spark-harness / src / journal.rs` 175 lines ยท 6943 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 //! Append-only JSON-lines journal (Headstart M2, issue #535). 17 //! 18 //! Why this and not an existing store: the repo's durable stores are the 19 //! aien-proof receipt store (immutable receipts, content addressed) and the 20 //! M1 consumed records (one atomically replaced file per task). Neither fits 21 //! an ordered event history, so the scheduler keeps its own journal. It 22 //! persists only scheduler events; proofs stay in the harness store and are 23 //! re-verified, never copied into the journal as authority. 24 //! 25 //! Format: line 1 is a header (format name, version, scheduler config); every 26 //! further line is one JSON event. Each append is a single `write_all` of 27 //! `json + "\n"` on an `O_APPEND` file followed by `sync_all`. 28 //! 29 //! Crash handling: 30 //! - A final segment with no trailing newline is a torn write. It is ignored 31 //! and truncated away on open (then fsynced), so the next append starts on 32 //! a clean line. Truncation happens only after the header and every 33 //! complete line validated; a refused journal is not modified. 34 //! - A newline-terminated line that does not parse is corruption, not a torn 35 //! write (a torn write is always a prefix of one line), and open fails 36 //! closed. 37 //! - If an append fails, the file is truncated back to its previous length. 38 //! If that also fails the journal refuses every further append. 39 //! - One process at a time: the journal holds an exclusive `flock` on 40 //! `.lock` for its lifetime. 41 42 use aien_proof::lock::FileLock; 43 use serde::de::DeserializeOwned; 44 use serde::Serialize; 45 use serde_json::Value; 46 use std::fs::{self, File, OpenOptions}; 47 use std::io::Write; 48 use std::path::{Path, PathBuf}; 49 50 pub struct Journal { 51 file: File, 52 path: PathBuf, 53 len: u64, 54 poisoned: bool, 55 _lock: FileLock, 56 } 57 58 /// Result of opening a journal. 59 pub struct Opened { 60 pub journal: Journal, 61 pub entries: Vec, 62 /// Bytes of a torn final line that were dropped (0 if none). 63 pub torn_bytes: usize, 64 } 65 66 fn sync_dir(path: &Path) -> std::io::Result<()> { 67 match path.parent() { 68 Some(dir) if !dir.as_os_str().is_empty() => File::open(dir)?.sync_all(), 69 _ => Ok(()), 70 } 71 } 72 73 impl Journal { 74 /// Open `path`, creating it with `header` when missing, and replay its 75 /// entries. An existing journal must carry exactly `header`. 76 pub fn open(path: &Path, header: &Value) -> Result, String> { 77 let lock_path = PathBuf::from(format!("{}.lock", path.display())); 78 if let Some(dir) = path.parent().filter(|d| !d.as_os_str().is_empty()) { 79 fs::create_dir_all(dir).map_err(|e| format!("cannot create {}: {e}", dir.display()))?; 80 } 81 let lock = FileLock::try_acquire(&lock_path) 82 .map_err(|e| format!("cannot lock journal: {e}"))? 83 .ok_or_else(|| format!("journal {} is held by another process", path.display()))?; 84 let bytes = match fs::read(path) { 85 Ok(b) => b, 86 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Vec::new(), 87 Err(e) => return Err(format!("cannot read journal {}: {e}", path.display())), 88 }; 89 let complete = bytes.iter().rposition(|b| *b == b'\n').map_or(0, |i| i + 1); 90 let torn_bytes = bytes.len() - complete; 91 // Validate everything before touching the file: a journal that is 92 // refused (wrong header, corrupt line) is left exactly as found. 93 let text = std::str::from_utf8(&bytes[..complete]) 94 .map_err(|e| format!("journal {} is not UTF-8: {e}", path.display()))?; 95 let mut lines = text.lines(); 96 let fresh = match lines.next() { 97 None => true, 98 Some(first) => { 99 let found: Value = serde_json::from_str(first) 100 .map_err(|e| format!("journal header unreadable: {e}"))?; 101 if &found != header { 102 return Err(format!( 103 "journal header mismatch: journal has {found}, expected {header}" 104 )); 105 } 106 false 107 } 108 }; 109 let mut entries = Vec::new(); 110 for (i, line) in lines.enumerate() { 111 let entry = serde_json::from_str(line) 112 .map_err(|e| format!("journal line {} is corrupt, refusing: {e}", i + 2))?; 113 entries.push(entry); 114 } 115 let file = OpenOptions::new() 116 .create(true) 117 .append(true) 118 .open(path) 119 .map_err(|e| format!("cannot open journal {}: {e}", path.display()))?; 120 if torn_bytes > 0 { 121 file.set_len(complete as u64) 122 .and_then(|_| file.sync_all()) 123 .map_err(|e| format!("cannot truncate torn journal tail: {e}"))?; 124 } 125 let mut journal = Journal { 126 file, 127 path: path.to_path_buf(), 128 len: complete as u64, 129 poisoned: false, 130 _lock: lock, 131 }; 132 if fresh { 133 journal.append(header)?; 134 sync_dir(path).map_err(|e| format!("cannot fsync journal dir: {e}"))?; 135 } 136 Ok(Opened { 137 journal, 138 entries, 139 torn_bytes, 140 }) 141 } 142 143 /// Append one entry as a single line and fsync it. 144 pub fn append(&mut self, entry: &T) -> Result<(), String> { 145 if self.poisoned { 146 return Err("journal is poisoned after a failed rollback".to_string()); 147 } 148 let mut line = serde_json::to_vec(entry).map_err(|e| e.to_string())?; 149 line.push(b'\n'); 150 let written = self 151 .file 152 .write_all(&line) 153 .and_then(|_| self.file.sync_all()); 154 match written { 155 Ok(()) => { 156 self.len += line.len() as u64; 157 Ok(()) 158 } 159 Err(e) => { 160 if self 161 .file 162 .set_len(self.len) 163 .and_then(|_| self.file.sync_all()) 164 .is_err() 165 { 166 self.poisoned = true; 167 } 168 Err(format!( 169 "journal append to {} failed: {e}", 170 self.path.display() 171 )) 172 } 173 } 174 } 175 }