spark-rsi-mv
Native Rust recursive self-improvement engine with paired bootstrap evaluation and cryptographic ledger
Brought by drakestapleton
spark-rsi-mv / src / measure / log.rs
| 1 | //! Append-only JSON lines under `<rsi_root>/measure/`. |
| 2 | //! |
| 3 | //! Writes are synced. Reads are strict: every newline-terminated line must parse as a current |
| 4 | //! schema record. A trailing line with no newline is a torn write that never completed; the |
| 5 | //! reader skips it and the next append drops it before writing. |
| 6 | |
| 7 | use super::{CycleSampleRecord, SCHEMA_VERSION}; |
| 8 | use std::fs::{File, OpenOptions}; |
| 9 | use std::io::{Read, Seek, SeekFrom, Write}; |
| 10 | use std::path::{Path, PathBuf}; |
| 11 | |
| 12 | pub const MEASURE_DIR: &str = "measure"; |
| 13 | pub const COMPLETE_FILE: &str = "stage-samples.jsonl"; |
| 14 | pub const PARTIAL_FILE: &str = "partial-cycles.jsonl"; |
| 15 | |
| 16 | pub struct SampleLog { |
| 17 | dir: PathBuf, |
| 18 | } |
| 19 | |
| 20 | impl SampleLog { |
| 21 | pub fn new(rsi_root: &Path) -> Self { |
| 22 | Self { |
| 23 | dir: rsi_root.join(MEASURE_DIR), |
| 24 | } |
| 25 | } |
| 26 | |
| 27 | pub fn complete_path(&self) -> PathBuf { |
| 28 | self.dir.join(COMPLETE_FILE) |
| 29 | } |
| 30 | |
| 31 | pub fn partial_path(&self) -> PathBuf { |
| 32 | self.dir.join(PARTIAL_FILE) |
| 33 | } |
| 34 | |
| 35 | pub fn append_complete(&self, record: &CycleSampleRecord) -> Result<(), String> { |
| 36 | self.append(&self.complete_path(), record) |
| 37 | } |
| 38 | |
| 39 | pub fn append_partial(&self, record: &CycleSampleRecord) -> Result<(), String> { |
| 40 | self.append(&self.partial_path(), record) |
| 41 | } |
| 42 | |
| 43 | /// Completed cycles in append order. A missing file is an empty log, not an error. |
| 44 | pub fn read_complete(&self) -> Result<Vec<CycleSampleRecord>, String> { |
| 45 | read_records(&self.complete_path()) |
| 46 | } |
| 47 | |
| 48 | pub fn read_partial(&self) -> Result<Vec<CycleSampleRecord>, String> { |
| 49 | read_records(&self.partial_path()) |
| 50 | } |
| 51 | |
| 52 | fn append(&self, path: &Path, record: &CycleSampleRecord) -> Result<(), String> { |
| 53 | if record.schema_version != SCHEMA_VERSION { |
| 54 | return Err(format!( |
| 55 | "refusing to write schema_version {} (current is {SCHEMA_VERSION})", |
| 56 | record.schema_version |
| 57 | )); |
| 58 | } |
| 59 | let mut line = serde_json::to_string(record).map_err(|e| e.to_string())?; |
| 60 | line.push('\n'); |
| 61 | std::fs::create_dir_all(&self.dir).map_err(|e| format!("create {:?}: {e}", self.dir))?; |
| 62 | let mut file = OpenOptions::new() |
| 63 | .read(true) |
| 64 | .append(true) |
| 65 | .create(true) |
| 66 | .open(path) |
| 67 | .map_err(|e| format!("open {path:?}: {e}"))?; |
| 68 | drop_torn_tail(&mut file, path)?; |
| 69 | file.write_all(line.as_bytes()) |
| 70 | .map_err(|e| format!("write {path:?}: {e}"))?; |
| 71 | file.sync_all().map_err(|e| format!("sync {path:?}: {e}"))?; |
| 72 | if let Ok(dir) = File::open(&self.dir) { |
| 73 | let _ = dir.sync_all(); |
| 74 | } |
| 75 | Ok(()) |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | /// Truncates anything after the last newline: a record that never finished writing. |
| 80 | fn drop_torn_tail(file: &mut File, path: &Path) -> Result<(), String> { |
| 81 | let mut bytes = Vec::new(); |
| 82 | file.seek(SeekFrom::Start(0)) |
| 83 | .and_then(|_| file.read_to_end(&mut bytes)) |
| 84 | .map_err(|e| format!("read {path:?}: {e}"))?; |
| 85 | if bytes.is_empty() || bytes.ends_with(b"\n") { |
| 86 | return Ok(()); |
| 87 | } |
| 88 | let keep = bytes.iter().rposition(|b| *b == b'\n').map_or(0, |i| i + 1); |
| 89 | file.set_len(keep as u64) |
| 90 | .map_err(|e| format!("truncate torn tail of {path:?}: {e}")) |
| 91 | } |
| 92 | |
| 93 | fn read_records(path: &Path) -> Result<Vec<CycleSampleRecord>, String> { |
| 94 | let bytes = match std::fs::read(path) { |
| 95 | Ok(b) => b, |
| 96 | Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()), |
| 97 | Err(e) => return Err(format!("read {path:?}: {e}")), |
| 98 | }; |
| 99 | let complete_len = bytes.iter().rposition(|b| *b == b'\n').map_or(0, |i| i + 1); |
| 100 | let text = std::str::from_utf8(&bytes[..complete_len]) |
| 101 | .map_err(|e| format!("{path:?} is not valid UTF-8: {e}"))?; |
| 102 | let mut records = Vec::new(); |
| 103 | for (i, line) in text.lines().enumerate() { |
| 104 | let record: CycleSampleRecord = |
| 105 | serde_json::from_str(line).map_err(|e| format!("{path:?} line {}: {e}", i + 1))?; |
| 106 | if record.schema_version != SCHEMA_VERSION { |
| 107 | return Err(format!( |
| 108 | "{path:?} line {}: unsupported schema_version {}", |
| 109 | i + 1, |
| 110 | record.schema_version |
| 111 | )); |
| 112 | } |
| 113 | records.push(record); |
| 114 | } |
| 115 | Ok(records) |
| 116 | } |