From f0ef86eedd641d07ad235b890c889b60394c7a28 Mon Sep 17 00:00:00 2001 From: LHaghfoss Date: Wed, 25 Nov 2026 23:25:22 +0100 Subject: [PATCH 1/2] refactor(engine): write thread files through one durable atomic writer --- harness/src/run.rs | 1 + rustcode/cli/src/run.rs | 1 + .../core/rustcode-session/src/atomic_file.rs | 199 ++++++++++++++++++ .../src/history_write_tests.rs | 58 +++++ rustcode/core/rustcode-session/src/lib.rs | 82 +++++--- .../core/rustcode-session/src/workspace.rs | 13 +- rustcode/engine/src/acp/mirror.rs | 18 +- rustcode/engine/src/acp/project_relocate.rs | 14 +- rustcode/engine/src/acp/settings.rs | 10 +- rustcode/engine/src/atomic_file.rs | 78 +------ rustcode/engine/src/harness/cache.rs | 2 +- rustcode/engine/src/harness/store.rs | 8 +- rustcode/engine/src/logger.rs | 1 + .../engine/src/orchestration/local_threads.rs | 2 +- .../engine/src/provider_auth/claude_usage.rs | 2 +- rustcode/engine/src/sessions.rs | 19 ++ rustcode/engine/src/sessions/store.rs | 7 +- rustcode/engine/src/text_generation.rs | 5 +- rustcode/engine/src/themes/mod.rs | 2 +- rustcode/engine/src/thread_status.rs | 6 +- rustcode/engine/src/workflow/store.rs | 16 +- rustcode/engine/src/worktrees.rs | 13 +- 22 files changed, 366 insertions(+), 191 deletions(-) create mode 100644 rustcode/core/rustcode-session/src/atomic_file.rs create mode 100644 rustcode/core/rustcode-session/src/history_write_tests.rs diff --git a/harness/src/run.rs b/harness/src/run.rs index afcab515d..3c4d51ab0 100644 --- a/harness/src/run.rs +++ b/harness/src/run.rs @@ -143,6 +143,7 @@ pub async fn run() -> Result<(), Box> { // preserves the message + location in debug.log even when the process // dies without a crash report. rustcode::logger::install_panic_hook(); + rustcode::sessions::report_history_write_failures(); // Provider keys are often exported in `~/.zshrc` (interactive-only) and // invisible to GUI/systemd/IDE launches. Hydrate missing keys from the // login shell once at startup so profiles, MCP servers, and tool shells diff --git a/rustcode/cli/src/run.rs b/rustcode/cli/src/run.rs index 6300db9f1..3a812efa7 100644 --- a/rustcode/cli/src/run.rs +++ b/rustcode/cli/src/run.rs @@ -1128,6 +1128,7 @@ pub async fn run() -> Result<(), Box> { } rustcode::logger::rotate_if_oversized(); rustcode::logger::install_panic_hook(); + rustcode::sessions::report_history_write_failures(); hydrate_shell_provider_keys(); if cli_args.init || matches!(cli_args.command.as_ref(), Some(crate::cli::Commands::Init)) { diff --git a/rustcode/core/rustcode-session/src/atomic_file.rs b/rustcode/core/rustcode-session/src/atomic_file.rs new file mode 100644 index 000000000..1dfed2c6b --- /dev/null +++ b/rustcode/core/rustcode-session/src/atomic_file.rs @@ -0,0 +1,199 @@ +//! Durable whole-file replacement: the one way RustCode writes a file that a +//! crash must never leave empty or half-written. + +use std::fs; +use std::io::{self, Write}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; + +/// Write `bytes` to `path` so a reader sees either the old file or the whole +/// new one, never a truncated mix, even after a crash or power loss: a +/// temporary file beside it that no other writer shares, flushed to disk, +/// renamed over `path`, and on Unix the directory entry flushed too. +pub fn write_atomic(path: &Path, bytes: &[u8]) -> io::Result<()> { + if let Some(parent) = path + .parent() + .filter(|parent| !parent.as_os_str().is_empty()) + { + fs::create_dir_all(parent)?; + } + let temporary = temporary_path(path); + let written = fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(&temporary) + .and_then(|mut file| { + file.write_all(bytes)?; + file.sync_all() + }) + .and_then(|()| replace_file(&temporary, path)); + if let Err(error) = written { + let _ = fs::remove_file(&temporary); + return Err(error); + } + sync_parent(path); + Ok(()) +} + +/// Replace `destination` with `source`, preserving the old destination while +/// the replacement is being installed on platforms that cannot rename over an +/// existing file. +pub fn replace_file(source: &Path, destination: &Path) -> io::Result<()> { + match fs::rename(source, destination) { + Ok(()) => Ok(()), + Err(_error) if cfg!(windows) => { + let backup = backup_path(destination); + let destination_exists = destination.exists(); + if destination_exists { + fs::rename(destination, &backup)?; + } + + match fs::rename(source, destination) { + Ok(()) => { + if destination_exists { + let _ = fs::remove_file(backup); + } + Ok(()) + } + Err(replace_error) => { + if destination_exists { + let _ = fs::rename(&backup, destination); + } + Err(replace_error) + } + } + } + Err(error) => Err(error), + } +} + +/// A temporary name beside `path` that is unique to this process and call, +/// so two writers of the same file never write into each other's temporary. +fn temporary_path(path: &Path) -> PathBuf { + static NEXT: AtomicU64 = AtomicU64::new(0); + let name = path + .file_name() + .and_then(|name| name.to_str()) + .unwrap_or("file"); + let sequence = NEXT.fetch_add(1, Ordering::Relaxed); + path.with_file_name(format!(".{name}.{}.{sequence}.tmp", std::process::id())) +} + +fn backup_path(destination: &Path) -> PathBuf { + let name = destination + .file_name() + .and_then(|name| name.to_str()) + .unwrap_or("file"); + destination.with_file_name(format!(".{name}.rustcode-backup-{}", std::process::id())) +} + +/// Make the rename itself durable. Best effort: the file is already in place. +fn sync_parent(path: &Path) { + if cfg!(unix) + && let Some(parent) = path + .parent() + .filter(|parent| !parent.as_os_str().is_empty()) + { + let _ = fs::File::open(parent).and_then(|directory| directory.sync_all()); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::{Arc, Barrier}; + + #[test] + fn replaces_existing_file() { + let directory = tempfile::TempDir::new().unwrap(); + let source = directory.path().join("source"); + let destination = directory.path().join("destination"); + fs::write(&source, b"new").unwrap(); + fs::write(&destination, b"old").unwrap(); + + replace_file(&source, &destination).unwrap(); + + assert_eq!(fs::read(&destination).unwrap(), b"new"); + assert!(!source.exists()); + } + + #[test] + fn replacement_failure_keeps_existing_file() { + let directory = tempfile::TempDir::new().unwrap(); + let source = directory.path().join("missing-source"); + let destination = directory.path().join("destination"); + fs::write(&destination, b"old").unwrap(); + + assert!(replace_file(&source, &destination).is_err()); + + assert_eq!(fs::read(&destination).unwrap(), b"old"); + } + + #[test] + fn writes_creates_parents_and_leaves_no_temporary() { + let directory = tempfile::TempDir::new().unwrap(); + let path = directory.path().join("a").join("b").join("file.json"); + + write_atomic(&path, b"first").unwrap(); + write_atomic(&path, b"second").unwrap(); + + assert_eq!(fs::read(&path).unwrap(), b"second"); + let names: Vec<_> = fs::read_dir(path.parent().unwrap()) + .unwrap() + .map(|entry| entry.unwrap().file_name()) + .collect(); + assert_eq!(names, ["file.json"]); + } + + #[test] + fn concurrent_writers_never_leave_a_partial_file() { + let directory = tempfile::TempDir::new().unwrap(); + let path = Arc::new(directory.path().join("shared.json")); + let writers = 8; + let barrier = Arc::new(Barrier::new(writers)); + let handles: Vec<_> = (0..writers) + .map(|writer| { + let path = Arc::clone(&path); + let barrier = Arc::clone(&barrier); + std::thread::spawn(move || { + let body = vec![b'a' + writer as u8; 256 * 1024]; + barrier.wait(); + for _ in 0..8 { + write_atomic(&path, &body).unwrap(); + } + }) + }) + .collect(); + for handle in handles { + handle.join().unwrap(); + } + + let written = fs::read(&*path).unwrap(); + assert_eq!(written.len(), 256 * 1024); + assert!(written.iter().all(|byte| *byte == written[0])); + } + + #[test] + fn a_failed_write_keeps_the_old_file_and_no_temporary() { + let directory = tempfile::TempDir::new().unwrap(); + let path = directory.path().join("file.json"); + fs::write(&path, b"old").unwrap(); + let under_a_file = path.join("child.json"); + + assert!(write_atomic(&under_a_file, b"new").is_err()); + + assert_eq!(fs::read(&path).unwrap(), b"old"); + let temporaries = fs::read_dir(directory.path()) + .unwrap() + .filter(|entry| { + entry + .as_ref() + .unwrap() + .file_name() + .to_string_lossy() + .ends_with(".tmp") + }) + .count(); + assert_eq!(temporaries, 0); + } +} diff --git a/rustcode/core/rustcode-session/src/history_write_tests.rs b/rustcode/core/rustcode-session/src/history_write_tests.rs new file mode 100644 index 000000000..0a437e1c8 --- /dev/null +++ b/rustcode/core/rustcode-session/src/history_write_tests.rs @@ -0,0 +1,58 @@ +use super::*; + +fn reported() -> &'static Mutex> { + static REPORTED: OnceLock>> = OnceLock::new(); + REPORTED.get_or_init(Default::default) +} + +fn record_failure(path: &Path, _error: &std::io::Error) { + lock(reported()).push(path.to_path_buf()); +} + +fn reports_of(path: &Path) -> usize { + lock(reported()).iter().filter(|seen| *seen == path).count() +} + +#[test] +fn a_failing_history_write_is_reported_once_until_it_succeeds() { + on_history_write_failure(record_failure); + let root = tempfile::TempDir::new().unwrap(); + let blocker = root.path().join("thread"); + std::fs::write(&blocker, b"a file where the folder should be").unwrap(); + let path = blocker.join(HISTORY_FILE); + let history = vec![ChatMessage::new("user", "hello")]; + + write_history_file_unguarded(&path, &history); + write_history_file_unguarded(&path, &history); + + assert!(history_write_failing(&path)); + assert_eq!(reports_of(&path), 1); + + std::fs::remove_file(&blocker).unwrap(); + write_history_file_unguarded(&path, &history); + + assert!(!history_write_failing(&path)); + assert!(path.is_file()); + + std::fs::remove_dir_all(&blocker).unwrap(); + std::fs::write(&blocker, b"blocked again").unwrap(); + write_history_file_unguarded(&path, &history); + + assert_eq!(reports_of(&path), 2); +} + +#[test] +fn history_writes_leave_no_temporary_beside_the_file() { + let root = tempfile::TempDir::new().unwrap(); + let path = root.path().join(HISTORY_FILE); + let history = vec![ChatMessage::new("user", "hello")]; + + write_history_file_unguarded(&path, &history); + write_history_file_unguarded(&path, &history); + + let names: Vec<_> = std::fs::read_dir(root.path()) + .unwrap() + .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned()) + .collect(); + assert_eq!(names, [HISTORY_FILE]); +} diff --git a/rustcode/core/rustcode-session/src/lib.rs b/rustcode/core/rustcode-session/src/lib.rs index c3d013dd1..e0095e473 100644 --- a/rustcode/core/rustcode-session/src/lib.rs +++ b/rustcode/core/rustcode-session/src/lib.rs @@ -68,8 +68,13 @@ pub fn is_scratch_session_id(session_id: &str) -> bool { }) } +pub mod atomic_file; +#[cfg(test)] +mod history_write_tests; mod search; mod workspace; + +pub use atomic_file::{replace_file, write_atomic}; pub use search::SessionSearchHit; pub use workspace::*; @@ -541,19 +546,50 @@ pub fn write_history_file(path: &Path, history: &[ChatMessage]) { } fn write_history_file_unguarded(path: &Path, history: &[ChatMessage]) { - if let Some(parent) = path.parent() { - let _ = std::fs::create_dir_all(parent); - } - let Ok(json_str) = serde_json::to_string(history) else { - return; - }; - let tmp = path.with_extension(format!("json.tmp{}", std::process::id())); - if std::fs::write(&tmp, json_str).is_err() { - let _ = std::fs::remove_file(&tmp); - return; - } - if std::fs::rename(&tmp, path).is_err() { - let _ = std::fs::remove_file(&tmp); + let written = serde_json::to_vec(history) + .map_err(std::io::Error::other) + .and_then(|json| write_atomic(path, &json)); + report_history_write(path, written); +} + +/// Called once when a history file stops being written, with the path and +/// why, and not again for that path until a write of it succeeds. +pub type HistoryWriteFailureHook = fn(&Path, &std::io::Error); + +static HISTORY_WRITE_FAILURE_HOOK: OnceLock = OnceLock::new(); + +/// Report history files that cannot be written (a full disk, a read-only +/// folder) through `hook` as well as on standard error. The first call wins. +pub fn on_history_write_failure(hook: HistoryWriteFailureHook) { + let _ = HISTORY_WRITE_FAILURE_HOOK.set(hook); +} + +fn failing_histories() -> &'static Mutex> { + static FAILING: OnceLock>> = OnceLock::new(); + FAILING.get_or_init(Default::default) +} + +/// Whether the last write of `path` failed. +pub fn history_write_failing(path: &Path) -> bool { + lock(failing_histories()).contains(path) +} + +fn report_history_write(path: &Path, written: std::io::Result<()>) { + let mut failing = lock(failing_histories()); + match written { + Ok(()) => { + failing.remove(path); + } + Err(error) => { + if !failing.insert(path.to_path_buf()) { + return; + } + drop(failing); + eprintln!("{}: history not saved: {error}", path.display()); + if let Some(hook) = HISTORY_WRITE_FAILURE_HOOK.get() { + hook(path, &error); + } + } } } @@ -1013,7 +1049,7 @@ impl SessionStore { let Ok(json) = serde_json::to_string_pretty(&metadata) else { return; }; - let _ = std::fs::write(path, json); + let _ = write_atomic(&path, json.as_bytes()); } fn history_path_for_id(&self, session_id: &str) -> PathBuf { @@ -1224,7 +1260,7 @@ impl SessionStore { pub fn save_session_title(&self, session_id: &str, title: &str) { let session_dir = self.ensure_session(session_id); - let _ = std::fs::write(session_dir.join("title.txt"), title); + let _ = write_atomic(&session_dir.join("title.txt"), title.as_bytes()); } /// Persist the deterministic title derived from the first user prompt only @@ -1262,7 +1298,7 @@ impl SessionStore { } let session_dir = self.ensure_session(session_id); if let Ok(json) = serde_json::to_string_pretty(cache) { - let _ = std::fs::write(session_dir.join(IMAGE_CACHE_FILE), json); + let _ = write_atomic(&session_dir.join(IMAGE_CACHE_FILE), json.as_bytes()); } } @@ -1276,7 +1312,7 @@ impl SessionStore { pub fn save_segment_checkpoint(&self, session_id: &str, checkpoint: &T) { let session_dir = self.ensure_session(session_id); if let Ok(json) = serde_json::to_string_pretty(checkpoint) { - let _ = std::fs::write(session_dir.join(SEGMENT_CHECKPOINT_FILE), json); + let _ = write_atomic(&session_dir.join(SEGMENT_CHECKPOINT_FILE), json.as_bytes()); } } @@ -1384,7 +1420,7 @@ impl SessionStore { let session_dir = self.ensure_session(&next_session_id()); let path = session_dir.join(HISTORY_FILE); let json = serde_json::to_string_pretty(history).ok()?; - std::fs::write(&path, json).ok()?; + write_atomic(&path, json.as_bytes()).ok()?; Some(path) } @@ -1521,11 +1557,8 @@ impl SessionStore { )); } let directory = self.ensure_session(session_id); - let path = directory.join(SESSION_WORKSPACE_FILE); - let temporary = path.with_extension(format!("json.tmp{}", std::process::id())); let contents = serde_json::to_vec(workspace).map_err(std::io::Error::other)?; - std::fs::write(&temporary, contents)?; - std::fs::rename(temporary, path) + write_atomic(&directory.join(SESSION_WORKSPACE_FILE), &contents) } pub fn load_session_workspace(&self, session_id: &str) -> Option { @@ -1710,11 +1743,8 @@ impl SessionStore { if !update(&mut metadata) { return Ok(()); } - let path = directory.join(SESSION_METADATA_FILE); - let temporary = path.with_extension(format!("json.tmp{}", std::process::id())); let contents = serde_json::to_vec_pretty(&metadata).map_err(std::io::Error::other)?; - std::fs::write(&temporary, contents)?; - std::fs::rename(temporary, path) + write_atomic(&directory.join(SESSION_METADATA_FILE), &contents) } /// The session's recorded YOLO setting, if it was ever set. diff --git a/rustcode/core/rustcode-session/src/workspace.rs b/rustcode/core/rustcode-session/src/workspace.rs index 92f76c8ff..6c347bcfc 100644 --- a/rustcode/core/rustcode-session/src/workspace.rs +++ b/rustcode/core/rustcode-session/src/workspace.rs @@ -1224,19 +1224,10 @@ fn stable_hash(value: &str) -> u64 { } fn write_descriptor(descriptor: &WorkspaceDescriptor) -> Result<(), WorkspaceError> { - if let Some(parent) = descriptor.descriptor_path.parent() { - fs::create_dir_all(parent)?; - } let json = serde_json::to_string_pretty(descriptor) .map_err(|error| WorkspaceError::Json(error.to_string()))?; - let temporary = descriptor - .descriptor_path - .with_extension(format!("json.tmp-{}", std::process::id())); - fs::write(&temporary, json)?; - fs::rename(&temporary, &descriptor.descriptor_path).map_err(|error| { - let _ = fs::remove_file(&temporary); - WorkspaceError::Io(error.to_string()) - }) + crate::write_atomic(&descriptor.descriptor_path, json.as_bytes()) + .map_err(|error| WorkspaceError::Io(error.to_string())) } fn git_error(output: &Output) -> String { diff --git a/rustcode/engine/src/acp/mirror.rs b/rustcode/engine/src/acp/mirror.rs index 39cd17b68..da828765c 100644 --- a/rustcode/engine/src/acp/mirror.rs +++ b/rustcode/engine/src/acp/mirror.rs @@ -167,18 +167,6 @@ fn host_dir(root: &Path, host: &str) -> Result { Ok(root.join(host)) } -fn write_atomic(path: &Path, bytes: &[u8]) -> Result<(), String> { - if let Some(parent) = path.parent() { - std::fs::create_dir_all(parent) - .map_err(|error| format!("could not create {}: {error}", parent.display()))?; - } - let temporary = path.with_extension("tmp"); - std::fs::write(&temporary, bytes) - .map_err(|error| format!("could not write {}: {error}", temporary.display()))?; - crate::atomic_file::replace_file(&temporary, path) - .map_err(|error| format!("could not write {}: {error}", path.display())) -} - fn read_json Deserialize<'de> + Default>(path: &Path) -> T { std::fs::read(path) .ok() @@ -206,7 +194,7 @@ fn read_index_for_write(root: &Path, host: &str) -> Result { fn write_index(root: &Path, host: &str, index: &mut Index) -> Result<(), String> { index.version = 1; let bytes = serde_json::to_vec(index).map_err(|error| error.to_string())?; - write_atomic(&host_dir(root, host)?.join("index.json"), &bytes) + crate::atomic_file::write_described(&host_dir(root, host)?.join("index.json"), &bytes) } // ---------------------------------------------------------------- settings @@ -239,7 +227,7 @@ fn set_settings( settings.excluded_projects = seen; } let bytes = serde_json::to_vec_pretty(&settings).map_err(|error| error.to_string())?; - write_atomic(&root.join("settings.json"), &bytes)?; + crate::atomic_file::write_described(&root.join("settings.json"), &bytes)?; Ok(settings) } @@ -400,7 +388,7 @@ fn put_transcript_in( } let file = json!({ "revision": revision, "cwd": cwd, "transcript": transcript }); let bytes_out = serde_json::to_vec(&file).map_err(|error| error.to_string())?; - write_atomic( + crate::atomic_file::write_described( &host_dir(root, host)? .join("threads") .join(format!("{id}.json")), diff --git a/rustcode/engine/src/acp/project_relocate.rs b/rustcode/engine/src/acp/project_relocate.rs index bad9800d7..9bac37820 100644 --- a/rustcode/engine/src/acp/project_relocate.rs +++ b/rustcode/engine/src/acp/project_relocate.rs @@ -209,7 +209,7 @@ pub(crate) fn relocate( Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} Err(e) => return Err(format!("cannot read settings: {e}")), } - commit_move(&old, &new, &edits, atomic_write)?; + commit_move(&old, &new, &edits, crate::atomic_file::write_atomic)?; Ok(json!({ "path": new, "previous_path": old, "moved": true, "thread_ids": ids })) } @@ -242,16 +242,6 @@ fn commit_move( Ok(()) } -fn atomic_write(path: &Path, bytes: &[u8]) -> std::io::Result<()> { - let temp = path.with_extension("relocate.tmp"); - std::fs::write(&temp, bytes)?; - let result = std::fs::rename(&temp, path); - if result.is_err() { - let _ = std::fs::remove_file(temp); - } - result -} - #[cfg(test)] mod tests { use super::*; @@ -369,7 +359,7 @@ mod tests { if calls == 2 { return Err(std::io::Error::other("disk full")); } - atomic_write(path, bytes) + crate::atomic_file::write_atomic(path, bytes) }) .is_err() ); diff --git a/rustcode/engine/src/acp/settings.rs b/rustcode/engine/src/acp/settings.rs index 636e5dad1..7f73fe2f7 100644 --- a/rustcode/engine/src/acp/settings.rs +++ b/rustcode/engine/src/acp/settings.rs @@ -229,17 +229,9 @@ fn value_matches(kind: SettingType, value: &Value) -> bool { } fn write_file(path: &Path, file: &SettingsFile) -> Result<(), String> { - if let Some(dir) = path.parent() { - std::fs::create_dir_all(dir) - .map_err(|error| format!("could not create {}: {error}", dir.display()))?; - } let text = serde_json::to_string_pretty(file) .map_err(|error| format!("could not serialize settings: {error}"))?; - let temporary = path.with_extension("json.tmp"); - std::fs::write(&temporary, text.as_bytes()) - .map_err(|error| format!("could not write {}: {error}", temporary.display()))?; - crate::atomic_file::replace_file(&temporary, path) - .map_err(|error| format!("could not write {}: {error}", path.display())) + crate::atomic_file::write_described(path, text.as_bytes()) } /// Answer `_rustcode/settings/get`: the requested keys, with each registry diff --git a/rustcode/engine/src/atomic_file.rs b/rustcode/engine/src/atomic_file.rs index 2fd050c16..6f108fe9b 100644 --- a/rustcode/engine/src/atomic_file.rs +++ b/rustcode/engine/src/atomic_file.rs @@ -1,74 +1,10 @@ -use std::fs; -use std::io; -use std::path::{Path, PathBuf}; +use std::path::Path; -/// Replace `destination` with `source`, preserving the old destination while -/// the replacement is being installed on platforms that cannot rename over an -/// existing file. -pub(crate) fn replace_file(source: &Path, destination: &Path) -> io::Result<()> { - match fs::rename(source, destination) { - Ok(()) => Ok(()), - Err(_error) if cfg!(windows) => { - let backup = backup_path(destination); - let destination_exists = destination.exists(); - if destination_exists { - fs::rename(destination, &backup)?; - } +pub(crate) use rustcode_session::atomic_file::{replace_file, write_atomic}; - match fs::rename(source, destination) { - Ok(()) => { - if destination_exists { - let _ = fs::remove_file(backup); - } - Ok(()) - } - Err(replace_error) => { - if destination_exists { - let _ = fs::rename(&backup, destination); - } - Err(replace_error) - } - } - } - Err(error) => Err(error), - } -} - -fn backup_path(destination: &Path) -> PathBuf { - let name = destination - .file_name() - .and_then(|name| name.to_str()) - .unwrap_or("file"); - destination.with_file_name(format!(".{name}.rustcode-backup-{}", std::process::id())) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn replaces_existing_file() { - let directory = tempfile::TempDir::new().unwrap(); - let source = directory.path().join("source"); - let destination = directory.path().join("destination"); - fs::write(&source, b"new").unwrap(); - fs::write(&destination, b"old").unwrap(); - - replace_file(&source, &destination).unwrap(); - - assert_eq!(fs::read(&destination).unwrap(), b"new"); - assert!(!source.exists()); - } - - #[test] - fn replacement_failure_keeps_existing_file() { - let directory = tempfile::TempDir::new().unwrap(); - let source = directory.path().join("missing-source"); - let destination = directory.path().join("destination"); - fs::write(&destination, b"old").unwrap(); - - assert!(replace_file(&source, &destination).is_err()); - - assert_eq!(fs::read(&destination).unwrap(), b"old"); - } +/// [`write_atomic`] with an error that names the file, for callers that +/// report errors as text. +pub(crate) fn write_described(path: &Path, bytes: &[u8]) -> Result<(), String> { + write_atomic(path, bytes) + .map_err(|error| format!("could not write {}: {error}", path.display())) } diff --git a/rustcode/engine/src/harness/cache.rs b/rustcode/engine/src/harness/cache.rs index 6cfc82197..c96461759 100644 --- a/rustcode/engine/src/harness/cache.rs +++ b/rustcode/engine/src/harness/cache.rs @@ -69,7 +69,7 @@ pub(crate) fn save_in(dir: &Path, id: &str, entry: CachedHarness) { file.harnesses.insert(id.to_owned(), entry); if let Ok(text) = serde_json::to_string(&file) { let _ = std::fs::create_dir_all(dir); - let _ = crate::worktrees::write_atomic(&path_in(dir), text.as_bytes()); + let _ = crate::atomic_file::write_atomic(&path_in(dir), text.as_bytes()); } } diff --git a/rustcode/engine/src/harness/store.rs b/rustcode/engine/src/harness/store.rs index e5dd306f2..6cb9f2acb 100644 --- a/rustcode/engine/src/harness/store.rs +++ b/rustcode/engine/src/harness/store.rs @@ -89,16 +89,10 @@ pub(crate) fn save(session_id: &str, record: &HarnessRecord) { let Some(path) = record_path(session_id) else { return; }; - if let Some(parent) = path.parent() { - let _ = std::fs::create_dir_all(parent); - } let Ok(text) = serde_json::to_string_pretty(record) else { return; }; - let temporary = path.with_extension("json.tmp"); - if std::fs::write(&temporary, text).is_ok() && std::fs::rename(&temporary, &path).is_err() { - let _ = std::fs::remove_file(&temporary); - } + let _ = crate::atomic_file::write_atomic(&path, text.as_bytes()); } pub(crate) fn remove(session_id: &str) { diff --git a/rustcode/engine/src/logger.rs b/rustcode/engine/src/logger.rs index 3064d4c52..333f2963b 100644 --- a/rustcode/engine/src/logger.rs +++ b/rustcode/engine/src/logger.rs @@ -1219,6 +1219,7 @@ const ALLOWED_EVENT_FIELDS: &[(&str, &[&str])] = &[ ], ), ("harness.resumed", &["harness", "native_session_id"]), + ("history.write_failed", &["error_kind"]), ("shell_env.probe", &["outcome", "duration_ms", "phase"]), ( "harness.turn_silent", diff --git a/rustcode/engine/src/orchestration/local_threads.rs b/rustcode/engine/src/orchestration/local_threads.rs index 173cfc57d..73f8122bd 100644 --- a/rustcode/engine/src/orchestration/local_threads.rs +++ b/rustcode/engine/src/orchestration/local_threads.rs @@ -1214,7 +1214,7 @@ pub(super) async fn merge_notice(caller: &str, number: u64, result: Value) { let receipt = crate::sessions::get_active_session_dir(caller) .map(|dir| dir.join(format!("merge-{number}.json"))); if let Some(path) = &receipt - && let Err(why) = crate::worktrees::write_atomic(path, result.to_string().as_bytes()) + && let Err(why) = crate::atomic_file::write_atomic(path, result.to_string().as_bytes()) { crate::dbg_log!("merge outcome for {caller} could not be saved: {why}"); } diff --git a/rustcode/engine/src/provider_auth/claude_usage.rs b/rustcode/engine/src/provider_auth/claude_usage.rs index 08797d05b..81719172a 100644 --- a/rustcode/engine/src/provider_auth/claude_usage.rs +++ b/rustcode/engine/src/provider_auth/claude_usage.rs @@ -987,7 +987,7 @@ fn record_in(dir: &Path, config_dir: Option<&Path>, usage: &ClaudeUsage) { history.logins.insert(key, record); if let Ok(text) = serde_json::to_string(&history) { let _ = std::fs::create_dir_all(dir); - let _ = crate::worktrees::write_atomic(&history_path(dir), text.as_bytes()); + let _ = crate::atomic_file::write_atomic(&history_path(dir), text.as_bytes()); } } diff --git a/rustcode/engine/src/sessions.rs b/rustcode/engine/src/sessions.rs index 122cdc2ac..b67341bd3 100644 --- a/rustcode/engine/src/sessions.rs +++ b/rustcode/engine/src/sessions.rs @@ -17,3 +17,22 @@ pub use store::*; #[cfg(test)] pub(crate) use store::{next_session_id_value, queue_history_write, write_history_file}; + +/// Record a thread whose history stops being saved (a full disk, a read-only +/// folder) in its log and as a `history.write_failed` operational event. +pub fn report_history_write_failures() { + rustcode_session::on_history_write_failure(|path, error| { + let thread = path + .parent() + .and_then(std::path::Path::file_name) + .and_then(std::ffi::OsStr::to_str) + .unwrap_or_default(); + crate::logger::operational_event( + "history.write_failed", + serde_json::json!({ + "session_id": thread, + "error_kind": format!("{:?}", error.kind()), + }), + ); + }); +} diff --git a/rustcode/engine/src/sessions/store.rs b/rustcode/engine/src/sessions/store.rs index 693fe96cd..5ef571d1b 100644 --- a/rustcode/engine/src/sessions/store.rs +++ b/rustcode/engine/src/sessions/store.rs @@ -351,12 +351,7 @@ fn record_session_settings_inner( let Ok(json) = serde_json::to_string_pretty(&log) else { return; }; - let temporary = path.with_extension(format!("json.tmp{}", std::process::id())); - if fs::write(&temporary, json).is_ok() { - let _ = fs::rename(&temporary, path); - } else { - let _ = fs::remove_file(temporary); - } + let _ = crate::atomic_file::write_atomic(&path, json.as_bytes()); } #[cfg(test)] diff --git a/rustcode/engine/src/text_generation.rs b/rustcode/engine/src/text_generation.rs index c24246ed3..7878c3dae 100644 --- a/rustcode/engine/src/text_generation.rs +++ b/rustcode/engine/src/text_generation.rs @@ -187,10 +187,7 @@ async fn configure_inner(r: ConfigureRequest) -> Result { _ => bail!("Unknown configuration action"), } let path = file()?; - std::fs::create_dir_all(path.parent().unwrap())?; - let temporary = path.with_extension("tmp"); - std::fs::write(&temporary, serde_json::to_vec_pretty(&config)?)?; - std::fs::rename(temporary, path)?; + crate::atomic_file::write_atomic(&path, &serde_json::to_vec_pretty(&config)?)?; Ok(serde_json::to_value(config)?) } pub(crate) fn bounded(text: &str) -> String { diff --git a/rustcode/engine/src/themes/mod.rs b/rustcode/engine/src/themes/mod.rs index 5e7ed3840..81419135c 100644 --- a/rustcode/engine/src/themes/mod.rs +++ b/rustcode/engine/src/themes/mod.rs @@ -811,7 +811,7 @@ fn sync_builtins(dir: &Path) { let stale = legacy_builtin(content) == Some(existing.as_str()) || previous_builtin(filename, &existing); if stale { - let _ = crate::worktrees::write_atomic(&path, content.as_bytes()); + let _ = crate::atomic_file::write_atomic(&path, content.as_bytes()); } } Err(_) => { diff --git a/rustcode/engine/src/thread_status.rs b/rustcode/engine/src/thread_status.rs index 40a49a644..888916160 100644 --- a/rustcode/engine/src/thread_status.rs +++ b/rustcode/engine/src/thread_status.rs @@ -103,7 +103,7 @@ fn store(session_id: &str, status: Status) -> Result<(), String> { } std::fs::create_dir_all(&dir).map_err(|error| error.to_string())?; let text = json!({ "status": status.as_str(), "at": chrono::Utc::now().to_rfc3339() }); - crate::worktrees::write_atomic(&path, text.to_string().as_bytes()).map_err(|e| e.to_string()) + crate::atomic_file::write_atomic(&path, text.to_string().as_bytes()).map_err(|e| e.to_string()) } fn watched() -> &'static Mutex> { @@ -394,7 +394,7 @@ pub(crate) fn set_snoozed(id: &str, until: Option) -> Result<(), String> { let dir = crate::sessions::get_active_session_dir(id) .filter(|dir| dir.is_dir()) .ok_or_else(|| "thread storage is unavailable".to_owned())?; - crate::worktrees::write_atomic( + crate::atomic_file::write_atomic( &dir.join("snooze.json"), json!(until).to_string().as_bytes(), ) @@ -505,7 +505,7 @@ pub(crate) fn set_pinned(session_id: &str, pinned: bool) -> Result<(), String> { if pinned { std::fs::create_dir_all(&dir).map_err(|error| error.to_string())?; let text = json!({ "pinned": true, "at": chrono::Utc::now().to_rfc3339() }); - crate::worktrees::write_atomic(&path, text.to_string().as_bytes()) + crate::atomic_file::write_atomic(&path, text.to_string().as_bytes()) .map_err(|error| error.to_string())?; } else { let _ = std::fs::remove_file(path); diff --git a/rustcode/engine/src/workflow/store.rs b/rustcode/engine/src/workflow/store.rs index 3a664147d..65bbd7ab9 100644 --- a/rustcode/engine/src/workflow/store.rs +++ b/rustcode/engine/src/workflow/store.rs @@ -11,7 +11,7 @@ use std::collections::HashMap; use std::io::Write; -use std::path::{Path, PathBuf}; +use std::path::PathBuf; use serde::{Deserialize, Serialize}; use serde_json::Value; @@ -187,7 +187,7 @@ impl Store { .ok_or_else(|| "invalid run id".to_owned())?; std::fs::create_dir_all(&dir) .map_err(|error| format!("could not create {}: {error}", dir.display()))?; - write_atomically(&dir.join(SCRIPT_FILE), script.as_bytes())?; + crate::atomic_file::write_described(&dir.join(SCRIPT_FILE), script.as_bytes())?; self.save(record) } @@ -197,7 +197,7 @@ impl Store { .ok_or_else(|| "invalid run id".to_owned())?; let text = serde_json::to_vec_pretty(record) .map_err(|error| format!("could not write the run record: {error}"))?; - write_atomically(&path, &text) + crate::atomic_file::write_described(&path, &text) } /// The final result as a file of its own, for a result too large to answer. @@ -207,7 +207,7 @@ impl Store { .ok_or_else(|| "invalid run id".to_owned())?; let text = serde_json::to_vec_pretty(result) .map_err(|error| format!("could not write the result: {error}"))?; - write_atomically(&path, &text)?; + crate::atomic_file::write_described(&path, &text)?; Ok(path) } @@ -305,14 +305,6 @@ impl Store { } } -fn write_atomically(path: &Path, bytes: &[u8]) -> Result<(), String> { - let temporary = path.with_extension("tmp"); - std::fs::write(&temporary, bytes) - .map_err(|error| format!("could not write {}: {error}", temporary.display()))?; - crate::atomic_file::replace_file(&temporary, path) - .map_err(|error| format!("could not write {}: {error}", path.display())) -} - #[cfg(test)] mod tests { use super::*; diff --git a/rustcode/engine/src/worktrees.rs b/rustcode/engine/src/worktrees.rs index 4dd168e82..a5a91aa19 100644 --- a/rustcode/engine/src/worktrees.rs +++ b/rustcode/engine/src/worktrees.rs @@ -260,19 +260,10 @@ fn save_record(record: &Record) { return; }; if let Ok(text) = serde_json::to_string_pretty(record) { - let _ = write_atomic(&path, text.as_bytes()); + let _ = crate::atomic_file::write_atomic(&path, text.as_bytes()); } } -/// Write `bytes` to `path` through a temporary file beside it. -pub(crate) fn write_atomic(path: &Path, bytes: &[u8]) -> std::io::Result<()> { - let temporary = path.with_extension("tmp"); - std::fs::write(&temporary, bytes)?; - std::fs::rename(&temporary, path).inspect_err(|_| { - let _ = std::fs::remove_file(&temporary); - }) -} - // ------------------------------------------------------------ naming ----- /// Lowercase ASCII words joined by `-`, at most `limit` bytes, cut at a word. @@ -2065,7 +2056,7 @@ pub(crate) fn attach(session_id: &str, worktree: &Worktree) { && let Ok(text) = serde_json::to_string_pretty(worktree) { let _ = std::fs::create_dir_all(&dir); - let _ = write_atomic(&dir.join(THREAD_FILE), text.as_bytes()); + let _ = crate::atomic_file::write_atomic(&dir.join(THREAD_FILE), text.as_bytes()); } // The worktree knows its repository without asking git, so record it on // the thread now: `session/list` reads it later (#3162). From a00128b5a9f43e61f67e8732e8874300ab971ee2 Mon Sep 17 00:00:00 2001 From: LHaghfoss Date: Wed, 25 Nov 2026 23:36:16 +0100 Subject: [PATCH 2/2] fix(engine): keep thread folders from being recreated by atomic writes --- .../core/rustcode-session/src/atomic_file.rs | 23 ++++++++------ rustcode/core/rustcode-session/src/lib.rs | 31 ++++++++++++++----- .../core/rustcode-session/src/workspace.rs | 3 ++ rustcode/engine/src/atomic_file.rs | 8 +++-- rustcode/engine/src/harness/store.rs | 3 ++ rustcode/engine/src/text_generation.rs | 1 + 6 files changed, 51 insertions(+), 18 deletions(-) diff --git a/rustcode/core/rustcode-session/src/atomic_file.rs b/rustcode/core/rustcode-session/src/atomic_file.rs index 1dfed2c6b..2a6ee9ddc 100644 --- a/rustcode/core/rustcode-session/src/atomic_file.rs +++ b/rustcode/core/rustcode-session/src/atomic_file.rs @@ -9,14 +9,9 @@ use std::sync::atomic::{AtomicU64, Ordering}; /// Write `bytes` to `path` so a reader sees either the old file or the whole /// new one, never a truncated mix, even after a crash or power loss: a /// temporary file beside it that no other writer shares, flushed to disk, -/// renamed over `path`, and on Unix the directory entry flushed too. +/// renamed over `path`, and on Unix the directory entry flushed too. The +/// folder must exist: a write never brings back a folder that was removed. pub fn write_atomic(path: &Path, bytes: &[u8]) -> io::Result<()> { - if let Some(parent) = path - .parent() - .filter(|parent| !parent.as_os_str().is_empty()) - { - fs::create_dir_all(parent)?; - } let temporary = temporary_path(path); let written = fs::OpenOptions::new() .write(true) @@ -130,9 +125,9 @@ mod tests { } #[test] - fn writes_creates_parents_and_leaves_no_temporary() { + fn writes_and_leaves_no_temporary() { let directory = tempfile::TempDir::new().unwrap(); - let path = directory.path().join("a").join("b").join("file.json"); + let path = directory.path().join("file.json"); write_atomic(&path, b"first").unwrap(); write_atomic(&path, b"second").unwrap(); @@ -145,6 +140,16 @@ mod tests { assert_eq!(names, ["file.json"]); } + #[test] + fn a_missing_folder_is_not_created() { + let directory = tempfile::TempDir::new().unwrap(); + let folder = directory.path().join("removed"); + + assert!(write_atomic(&folder.join("file.json"), b"x").is_err()); + + assert!(!folder.exists()); + } + #[test] fn concurrent_writers_never_leave_a_partial_file() { let directory = tempfile::TempDir::new().unwrap(); diff --git a/rustcode/core/rustcode-session/src/lib.rs b/rustcode/core/rustcode-session/src/lib.rs index e0095e473..23e138486 100644 --- a/rustcode/core/rustcode-session/src/lib.rs +++ b/rustcode/core/rustcode-session/src/lib.rs @@ -545,10 +545,27 @@ pub fn write_history_file(path: &Path, history: &[ChatMessage]) { } } +/// Write `name` in a thread's folder, which must exist: a scratch request's +/// folder is never created (`is_scratch_session_id`). +fn write_session_file(directory: &Path, name: &str, bytes: &[u8]) -> std::io::Result<()> { + if !directory.is_dir() { + return Err(std::io::Error::new( + std::io::ErrorKind::NotFound, + format!("{} does not exist", directory.display()), + )); + } + write_atomic(&directory.join(name), bytes) +} + fn write_history_file_unguarded(path: &Path, history: &[ChatMessage]) { let written = serde_json::to_vec(history) .map_err(std::io::Error::other) - .and_then(|json| write_atomic(path, &json)); + .and_then(|json| { + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent)?; + } + write_atomic(path, &json) + }); report_history_write(path, written); } @@ -1049,7 +1066,7 @@ impl SessionStore { let Ok(json) = serde_json::to_string_pretty(&metadata) else { return; }; - let _ = write_atomic(&path, json.as_bytes()); + let _ = write_session_file(directory, SESSION_METADATA_FILE, json.as_bytes()); } fn history_path_for_id(&self, session_id: &str) -> PathBuf { @@ -1260,7 +1277,7 @@ impl SessionStore { pub fn save_session_title(&self, session_id: &str, title: &str) { let session_dir = self.ensure_session(session_id); - let _ = write_atomic(&session_dir.join("title.txt"), title.as_bytes()); + let _ = write_session_file(&session_dir, "title.txt", title.as_bytes()); } /// Persist the deterministic title derived from the first user prompt only @@ -1298,7 +1315,7 @@ impl SessionStore { } let session_dir = self.ensure_session(session_id); if let Ok(json) = serde_json::to_string_pretty(cache) { - let _ = write_atomic(&session_dir.join(IMAGE_CACHE_FILE), json.as_bytes()); + let _ = write_session_file(&session_dir, IMAGE_CACHE_FILE, json.as_bytes()); } } @@ -1312,7 +1329,7 @@ impl SessionStore { pub fn save_segment_checkpoint(&self, session_id: &str, checkpoint: &T) { let session_dir = self.ensure_session(session_id); if let Ok(json) = serde_json::to_string_pretty(checkpoint) { - let _ = write_atomic(&session_dir.join(SEGMENT_CHECKPOINT_FILE), json.as_bytes()); + let _ = write_session_file(&session_dir, SEGMENT_CHECKPOINT_FILE, json.as_bytes()); } } @@ -1558,7 +1575,7 @@ impl SessionStore { } let directory = self.ensure_session(session_id); let contents = serde_json::to_vec(workspace).map_err(std::io::Error::other)?; - write_atomic(&directory.join(SESSION_WORKSPACE_FILE), &contents) + write_session_file(&directory, SESSION_WORKSPACE_FILE, &contents) } pub fn load_session_workspace(&self, session_id: &str) -> Option { @@ -1744,7 +1761,7 @@ impl SessionStore { return Ok(()); } let contents = serde_json::to_vec_pretty(&metadata).map_err(std::io::Error::other)?; - write_atomic(&directory.join(SESSION_METADATA_FILE), &contents) + write_session_file(&directory, SESSION_METADATA_FILE, &contents) } /// The session's recorded YOLO setting, if it was ever set. diff --git a/rustcode/core/rustcode-session/src/workspace.rs b/rustcode/core/rustcode-session/src/workspace.rs index 6c347bcfc..9508e87f7 100644 --- a/rustcode/core/rustcode-session/src/workspace.rs +++ b/rustcode/core/rustcode-session/src/workspace.rs @@ -1226,6 +1226,9 @@ fn stable_hash(value: &str) -> u64 { fn write_descriptor(descriptor: &WorkspaceDescriptor) -> Result<(), WorkspaceError> { let json = serde_json::to_string_pretty(descriptor) .map_err(|error| WorkspaceError::Json(error.to_string()))?; + if let Some(parent) = descriptor.descriptor_path.parent() { + fs::create_dir_all(parent)?; + } crate::write_atomic(&descriptor.descriptor_path, json.as_bytes()) .map_err(|error| WorkspaceError::Io(error.to_string())) } diff --git a/rustcode/engine/src/atomic_file.rs b/rustcode/engine/src/atomic_file.rs index 6f108fe9b..924d0f992 100644 --- a/rustcode/engine/src/atomic_file.rs +++ b/rustcode/engine/src/atomic_file.rs @@ -2,9 +2,13 @@ use std::path::Path; pub(crate) use rustcode_session::atomic_file::{replace_file, write_atomic}; -/// [`write_atomic`] with an error that names the file, for callers that -/// report errors as text. +/// [`write_atomic`] into a folder created when missing, with an error that +/// names the file, for callers that report errors as text. pub(crate) fn write_described(path: &Path, bytes: &[u8]) -> Result<(), String> { + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent) + .map_err(|error| format!("could not create {}: {error}", parent.display()))?; + } write_atomic(path, bytes) .map_err(|error| format!("could not write {}: {error}", path.display())) } diff --git a/rustcode/engine/src/harness/store.rs b/rustcode/engine/src/harness/store.rs index 6cb9f2acb..72a870fd4 100644 --- a/rustcode/engine/src/harness/store.rs +++ b/rustcode/engine/src/harness/store.rs @@ -89,6 +89,9 @@ pub(crate) fn save(session_id: &str, record: &HarnessRecord) { let Some(path) = record_path(session_id) else { return; }; + if let Some(parent) = path.parent() { + let _ = std::fs::create_dir_all(parent); + } let Ok(text) = serde_json::to_string_pretty(record) else { return; }; diff --git a/rustcode/engine/src/text_generation.rs b/rustcode/engine/src/text_generation.rs index 7878c3dae..6f13cb780 100644 --- a/rustcode/engine/src/text_generation.rs +++ b/rustcode/engine/src/text_generation.rs @@ -187,6 +187,7 @@ async fn configure_inner(r: ConfigureRequest) -> Result { _ => bail!("Unknown configuration action"), } let path = file()?; + std::fs::create_dir_all(path.parent().unwrap())?; crate::atomic_file::write_atomic(&path, &serde_json::to_vec_pretty(&config)?)?; Ok(serde_json::to_value(config)?) }