//! Durable session storage: append-only writer, incremental bounded loader, //! and atomic repair publication. use crate::config::Config; use crate::frame::{Frame, HEADER_LEN, write_frame}; use smith::error::{Result, SmithError}; use std::fs::{File, OpenOptions}; use std::io::{BufReader, Read, Seek, SeekFrom, Write}; use std::path::{Path, PathBuf}; /// Append-only session writer with an exclusive file lock. /// /// Opening repairs a torn tail (truncating to the last complete frame /// boundary) before appending, so acknowledged appends are always /// reachable by the loader. The lock serializes concurrent writers. pub struct SessionWriter { file: File, config: Config, path: PathBuf, } impl SessionWriter { /// Open (creating parent directories) and lock the session file. pub fn open>(path: P, config: Config) -> Result { config.validate().map_err(|e| SmithError::Config { field: "store".to_string(), message: e, })?; let path = path.as_ref().to_path_buf(); if let Some(parent) = path.parent() { if !parent.as_os_str().is_empty() { std::fs::create_dir_all(parent).map_err(io_err("STORE_MKDIR"))?; } } let mut file = OpenOptions::new() .read(true) .write(true) .create(true) .truncate(false) .open(&path) .map_err(io_err("STORE_OPEN"))?; use fs2::FileExt; file.lock_exclusive().map_err(io_err("STORE_LOCK"))?; // Repair torn tail before appending so new frames stay reachable. let good_end = scan_and_fix_tail(&mut file, config.max_frame_bytes)?; file.seek(SeekFrom::Start(good_end)) .map_err(io_err("STORE_SEEK"))?; Ok(Self { file, config, path }) } /// Append one frame. The encoded size is checked against the configured /// limit before any bytes are written; a rejected frame leaves the file /// unchanged. pub fn append_frame(&mut self, frame: &Frame) -> Result<()> { let bytes = frame.encode(self.config.max_frame_bytes)?; self.file.write_all(&bytes).map_err(io_err("STORE_WRITE"))?; self.file.flush().map_err(io_err("STORE_WRITE"))?; Ok(()) } /// Path of the underlying session file. pub fn path(&self) -> &Path { &self.path } } impl Drop for SessionWriter { fn drop(&mut self) { // Best-effort unlock; the OS also releases on close. let _ = fs2::FileExt::unlock(&self.file); } } /// Load all frames incrementally with per-frame bounded allocation. /// /// Complete frames are returned in order; a torn tail (partial header or /// payload) is dropped. Corrupt frames with intact declared lengths above /// `max_frame_bytes` are skipped by length when fully present, never scanned. pub fn load_session(path: &Path, max_frame_bytes: usize) -> Result> { let file = File::open(path).map_err(io_err("STORE_OPEN"))?; let mut reader = BufReader::with_capacity(64 * 1024, file); let mut frames = Vec::new(); loop { let mut header = [0u8; HEADER_LEN]; match read_exact_or_eof(&mut reader, &mut header) { Ok(true) => {} // Clean EOF or torn partial header: stop with complete frames. _ => break, } let declared = u32::from_le_bytes(header) as usize; if declared > max_frame_bytes { // Bounded skip by intact length; incomplete means torn tail. let mut remaining = declared as u64; loop { if remaining == 0 { break; } let chunk = remaining.min(64 * 1024) as usize; let mut sink = vec![0u8; chunk]; match reader.read_exact(&mut sink) { Ok(()) => remaining -= chunk as u64, Err(_) => return Ok(frames), // torn: stop before this frame } } continue; } let mut chunk = vec![0u8; declared]; match reader.read_exact(&mut chunk) { Ok(()) => frames.push(Frame::decode_payload(chunk)), Err(_) => return Ok(frames), // torn tail: drop partial frame } } Ok(frames) } /// Repair a session file: recover all complete frames and atomically publish /// a rewritten file containing exactly those frames. Returns the recovered /// frames. The original content stays intact if any step fails before rename. pub fn repair_session(path: &Path, max_frame_bytes: usize) -> Result> { let frames = load_session(path, max_frame_bytes)?; let tmp = path.with_extension("smith-repair.tmp"); { let mut out = File::create(&tmp).map_err(io_err("REPAIR_CREATE"))?; for frame in &frames { write_frame(&mut out, frame, max_frame_bytes)?; } out.sync_all().map_err(io_err("REPAIR_SYNC"))?; } std::fs::rename(&tmp, path).map_err(io_err("REPAIR_PUBLISH"))?; Ok(frames) } /// Scan the file for the last complete frame boundary; truncate a torn tail. /// Returns the byte offset to append at. fn scan_and_fix_tail(file: &File, max_frame_bytes: usize) -> Result { let len = file.metadata().map_err(io_err("STORE_STAT"))?.len(); let mut reader = BufReader::with_capacity(64 * 1024, file.try_clone().map_err(io_err("STORE_OPEN"))?); let mut good_end: u64 = 0; loop { let header_start = reader.stream_position().map_err(io_err("STORE_READ"))?; let mut header = [0u8; HEADER_LEN]; // Clean EOF or torn partial header both end the good region. if !read_exact_or_eof(&mut reader, &mut header).unwrap_or(false) { break; } let declared = u32::from_le_bytes(header) as usize; let total = declared as u64 + HEADER_LEN as u64; let mut remaining = total; let mut complete = true; while remaining > 0 { let chunk = remaining.min(64 * 1024) as usize; let mut sink = vec![0u8; chunk]; match reader.read_exact(&mut sink) { Ok(()) => remaining -= chunk as u64, Err(_) => { complete = false; break; } } } if !complete { // Torn tail: caller truncates to the last good boundary. break; } let _ = max_frame_bytes; // oversized-but-complete frames are skipped, not tail good_end = header_start + total; } if good_end < len { file.set_len(good_end).map_err(io_err("STORE_TRUNCATE"))?; } Ok(good_end) } /// Read exactly `buf.len()` bytes. Returns Ok(false) on immediate EOF, /// Err on partial read (torn). fn read_exact_or_eof(reader: &mut R, buf: &mut [u8]) -> std::io::Result { let mut filled = 0; while filled < buf.len() { match reader.read(&mut buf[filled..]) { Ok(0) => { if filled == 0 { return Ok(false); } return Err(std::io::Error::new( std::io::ErrorKind::UnexpectedEof, "torn header", )); } Ok(n) => filled += n, Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue, Err(e) => return Err(e), } } Ok(true) } fn io_err(code: &'static str) -> impl Fn(std::io::Error) -> SmithError { move |e| SmithError::Session { code: code.to_string(), message: e.to_string(), } } #[cfg(test)] #[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] mod tests { use super::*; use crate::session::{Entry, EntryContent, Session}; use smith::message::{ContentBlock, Message, Role}; fn tmp_path(name: &str) -> PathBuf { let dir = std::env::temp_dir().join(format!("smith_store_tests_{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); dir.join(name) } fn entry(text: &str) -> Entry { Entry::message(Message::with_text(Role::User, text), None) } fn frame(text: &str) -> Frame { Frame::Known { entry: entry(text) } } #[test] fn append_load_round_trip_preserves_entries() { let path = tmp_path("round_trip.smh"); let _ = std::fs::remove_file(&path); let cfg = Config::default_valid(); { let mut w = SessionWriter::open(&path, cfg.clone()).unwrap(); w.append_frame(&frame("one")).unwrap(); w.append_frame(&frame("two")).unwrap(); } let frames = load_session(&path, cfg.max_frame_bytes).unwrap(); assert_eq!(frames.len(), 2); let session = Session::from_frames(&frames); assert_eq!(session.active_branch().entries.len(), 2); assert_eq!( session.active_branch().entries[1].id, session.selected_id().unwrap() ); let _ = std::fs::remove_file(&path); } #[test] fn torn_tail_is_truncated_on_open_and_appends_stay_visible() { let path = tmp_path("torn_tail.smh"); let _ = std::fs::remove_file(&path); let cfg = Config::default_valid(); { let mut w = SessionWriter::open(&path, cfg.clone()).unwrap(); w.append_frame(&frame("kept")).unwrap(); } // Simulate a crash mid-append: partial header + payload bytes. let good = Frame::Known { entry: entry("kept"), } .encode(cfg.max_frame_bytes) .unwrap(); let mut torn = good.clone(); torn.extend_from_slice(&[0x10, 0x00, 0x00, 0x00, 0xAA, 0xBB]); std::fs::write(&path, &torn).unwrap(); { // Open repairs the tail, then a new append must be loadable. let mut w = SessionWriter::open(&path, cfg.clone()).unwrap(); w.append_frame(&frame("after")).unwrap(); } let frames = load_session(&path, cfg.max_frame_bytes).unwrap(); let texts: Vec = frames .iter() .filter_map(|f| match f { Frame::Known { entry } => match &entry.content { EntryContent::Message(m) => match &m.blocks[0] { ContentBlock::Text(t) => Some(t.clone()), _ => None, }, _ => None, }, _ => None, }) .collect(); assert_eq!(texts, vec!["kept".to_string(), "after".to_string()]); let _ = std::fs::remove_file(&path); } #[test] fn loader_stops_at_torn_tail_without_header_fabrication() { let path = tmp_path("loader_torn.smh"); let cfg = Config::default_valid(); let good = frame("a").encode(cfg.max_frame_bytes).unwrap(); let mut bytes = good.clone(); bytes.extend_from_slice(&[0xFF, 0xFF]); // partial header std::fs::write(&path, &bytes).unwrap(); let frames = load_session(&path, cfg.max_frame_bytes).unwrap(); assert_eq!(frames.len(), 1); let _ = std::fs::remove_file(&path); } #[test] fn oversized_complete_frame_is_skipped_and_following_frames_reachable() { let path = tmp_path("oversized_skip.smh"); // declared = 5000 > limit 1024, payload fully present, then a valid frame. let mut bytes = 5000_u32.to_le_bytes().to_vec(); bytes.extend_from_slice(&vec![0xAB_u8; 5000]); bytes.extend_from_slice(&frame("tail").encode(1 << 20).unwrap()); std::fs::write(&path, &bytes).unwrap(); let frames = load_session(&path, 1024).unwrap(); assert_eq!(frames.len(), 1); assert!(matches!(frames[0], Frame::Known { .. })); let _ = std::fs::remove_file(&path); } #[test] fn repair_republishes_file_without_torn_tail() { let path = tmp_path("repair.smh"); let cfg = Config::default_valid(); let good = frame("a").encode(cfg.max_frame_bytes).unwrap(); let mut bytes = good.clone(); bytes.extend_from_slice(&frame("b").encode(cfg.max_frame_bytes).unwrap()[..6]); std::fs::write(&path, &bytes).unwrap(); let before = std::fs::metadata(&path).unwrap().len(); let frames = repair_session(&path, cfg.max_frame_bytes).unwrap(); assert_eq!(frames.len(), 1); let after = std::fs::metadata(&path).unwrap().len(); assert!(after < before); assert_eq!(load_session(&path, cfg.max_frame_bytes).unwrap().len(), 1); let _ = std::fs::remove_file(&path); } #[test] fn writer_rejects_oversized_frame_without_touching_file() { let path = tmp_path("oversize_reject.smh"); let _ = std::fs::remove_file(&path); let mut cfg = Config::default_valid(); cfg.max_frame_bytes = 4096; { let mut w = SessionWriter::open(&path, cfg.clone()).unwrap(); w.append_frame(&frame("small")).unwrap(); let big = Entry::message( { let mut m = Message::with_text(Role::User, "x"); m.add_block(ContentBlock::text("y".repeat(8192))); m }, None, ); let err = w.append_frame(&Frame::Known { entry: big }).unwrap_err(); assert_eq!(err.code(), "FRAME_TOO_LARGE"); } assert_eq!(load_session(&path, cfg.max_frame_bytes).unwrap().len(), 1); let _ = std::fs::remove_file(&path); } #[test] fn lock_serializes_second_writer_handle() { let path = tmp_path("locked.smh"); let _ = std::fs::remove_file(&path); let cfg = Config::default_valid(); let _w1 = SessionWriter::open(&path, cfg.clone()).unwrap(); // While the first writer holds the lock, an independent handle cannot // take it: writers cannot interleave frames. let probe = OpenOptions::new() .read(true) .write(true) .open(&path) .unwrap(); use fs2::FileExt; assert!(probe.try_lock_exclusive().is_err()); drop(_w1); let _ = std::fs::remove_file(&path); } #[test] fn unknown_frames_survive_write_and_load() { let path = tmp_path("unknown_frames.smh"); let _ = std::fs::remove_file(&path); let cfg = Config::default_valid(); let unknown = Frame::Unknown { declared_length: 6, raw_bytes: vec![1, 2, 3, 4, 5, 6], }; { let mut w = SessionWriter::open(&path, cfg.clone()).unwrap(); w.append_frame(&unknown).unwrap(); w.append_frame(&frame("known")).unwrap(); } let frames = load_session(&path, cfg.max_frame_bytes).unwrap(); assert_eq!(frames.len(), 2); match &frames[0] { Frame::Unknown { raw_bytes, declared_length, } => { assert_eq!(raw_bytes, &vec![1, 2, 3, 4, 5, 6]); assert_eq!(*declared_length, 6); } other => panic!("expected unknown frame, got {other:?}"), } match &frames[1] { Frame::Known { entry } => match &entry.content { EntryContent::Message(m) => match &m.blocks[0] { ContentBlock::Text(t) => assert_eq!(t, "known"), other => panic!("unexpected block {other:?}"), }, other => panic!("unexpected content {other:?}"), }, other => panic!("expected known frame, got {other:?}"), } let _ = std::fs::remove_file(&path); } #[test] fn end_to_end_tool_activity_persists_and_reconstructs() { let dir = tmp_path("e2e"); std::fs::create_dir_all(&dir).unwrap(); let workdir = dir.join("work"); std::fs::create_dir_all(&workdir).unwrap(); let session_path = dir.join("e2e.smh"); let _ = std::fs::remove_file(&session_path); let cfg = Config::default_valid(); { let writer = SessionWriter::open(&session_path, cfg.clone()).unwrap(); let mut ts = crate::tools::ToolSession::with_writer(workdir.clone(), writer); ts.invoke( "write", serde_json::json!({"path": "out/hello.txt", "content": "hi"}), ) .unwrap(); ts.invoke("read", serde_json::json!({"path": "out/hello.txt"})) .unwrap(); } let frames = load_session(&session_path, cfg.max_frame_bytes).unwrap(); assert_eq!(frames.len(), 4); // call+result x2 let restored = Session::from_frames(&frames); assert_eq!(restored.active_branch().entries.len(), 4); // Tool call/result pairs stay adjacent and ordered. let kinds: Vec<&str> = restored .active_branch() .entries .iter() .map(|e| match &e.content { EntryContent::ToolCall { .. } => "call", EntryContent::ToolResult { .. } => "result", _ => "other", }) .collect(); assert_eq!(kinds, vec!["call", "result", "call", "result"]); // The file effect actually happened under the invocation workdir. assert_eq!( std::fs::read_to_string(workdir.join("out/hello.txt")).unwrap(), "hi" ); let _ = std::fs::remove_file(&session_path); let _ = std::fs::remove_dir_all(&dir); } #[test] fn header_len_matches_protocol() { assert_eq!(HEADER_LEN, 4); } }