From c24e4b569650e23d6a9c1fe9e24ceb7647a39c1c Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sun, 20 Sep 2026 20:58:58 +0200 Subject: [PATCH] fix: make snapshot writes atomic and reject unsupported stats --- AGENTS-TASKS.md | 2 +- docs/repository.md | 7 +- lib_efo/Cargo.toml | 2 +- lib_efo/src/epoch/epoch_traits.rs | 72 +++++++++++++++++-- lib_efo/src/error.rs | 8 +++ .../src/stats/implementations/from_impl.rs | 10 +++ lib_efo/src/stats/implementations/test.rs | 8 +++ 7 files changed, 97 insertions(+), 12 deletions(-) diff --git a/AGENTS-TASKS.md b/AGENTS-TASKS.md index db78d42..879b3d0 100644 --- a/AGENTS-TASKS.md +++ b/AGENTS-TASKS.md @@ -43,7 +43,7 @@ work belongs here before implementation. diff, and delete by name and stable identifier. - [ ] Test epoch workflows: next, log, switch, diff, tag, summary, and reset. - [ ] Test malformed/corrupt configuration and snapshot files without panics. -- [ ] Test interrupted/failed writes where feasible and implement atomic file +- [x] Test interrupted/failed writes where feasible and implement atomic file replacement for repository metadata and epoch snapshots. - [x] Remove currently reported unused dependencies and the demo `show` path. - [x] Make format, tests, strict Clippy, and release build pass. diff --git a/docs/repository.md b/docs/repository.md index 86e21c4..baabd90 100644 --- a/docs/repository.md +++ b/docs/repository.md @@ -17,9 +17,10 @@ and blockers. The full world is duplicated per epoch. Entity commands edit the current snapshot directly. `epoch next` creates a new snapshot; `epoch switch` only changes the current pointer. `epoch reset` deletes -later directories. This is not yet Git-equivalent: there is no working -tree/index separation, reflog, locking, atomic multi-file transaction, or -built-in undelete. +later directories. Individual JSON files are written through same-directory +temporary files and atomically replaced. This is not yet Git-equivalent: there +is no working tree/index separation, reflog, repository locking, atomic +transaction spanning multiple files, or built-in undelete. ## Safety and recovery diff --git a/lib_efo/Cargo.toml b/lib_efo/Cargo.toml index a1f2350..aab9476 100644 --- a/lib_efo/Cargo.toml +++ b/lib_efo/Cargo.toml @@ -16,7 +16,7 @@ colored = {workspace = true} uuid = {workspace = true} rand = "0.9.2" once_cell = "1.21.3" +tempfile = "3.23.0" [dev-dependencies] insta = {workspace = true} -tempfile = "3.23.0" diff --git a/lib_efo/src/epoch/epoch_traits.rs b/lib_efo/src/epoch/epoch_traits.rs index 4e6384d..55ae43d 100644 --- a/lib_efo/src/epoch/epoch_traits.rs +++ b/lib_efo/src/epoch/epoch_traits.rs @@ -7,7 +7,7 @@ use cli_table::{Style, Table, WithTitle}; use serde::Serialize; -use std::{fmt::Display, fs::File, io::Write}; +use std::{fmt::Display, io::Write, path::Path}; use uuid::Uuid; use crate::{epoch::SaveMode, error::EpochError, items_table}; @@ -95,13 +95,22 @@ pub trait ConfigWritable: Serialize { do_not_erase: &SaveMode, // advice: Option, ) -> Result<(), EpochError> { - let mut f = match *do_not_erase { - SaveMode::Erase => File::create(self.save_path()), - SaveMode::DoNotErase => File::create_new(self.save_path()), - } - .map_err(|e| EpochError::ConfigCreation(self.save_path(), e))?; - write!(f, "{}", self.as_json(action_description.to_owned())?) + let save_path = self.save_path(); + let destination = Path::new(&save_path); + let parent = destination.parent().unwrap_or_else(|| Path::new(".")); + let json = self.as_json(action_description.to_owned())?; + let mut temporary = tempfile::NamedTempFile::new_in(parent) + .map_err(|error| EpochError::ConfigCreation(save_path.clone(), error))?; + temporary + .write_all(json.as_bytes()) + .and_then(|_| temporary.as_file().sync_all()) .map_err(EpochError::ConfigWrite)?; + + let persisted = match *do_not_erase { + SaveMode::Erase => temporary.persist(destination), + SaveMode::DoNotErase => temporary.persist_noclobber(destination), + }; + persisted.map_err(|error| EpochError::ConfigCreation(save_path, error.error))?; Ok(()) } } @@ -184,6 +193,55 @@ mod tests { assert_snapshot!(json); } + #[test] + fn save_with_context_atomically_replaces_existing_content() { + let directory = tempdir().expect("temporary directory"); + let path = directory.path().join("dummy.json"); + std::fs::write(&path, "old content").expect("seed destination"); + let item = DummyItem { + id: Uuid::nil(), + value: 42, + save: path.to_string_lossy().into_owned(), + }; + + item.save_with_context("replace test", &SaveMode::Erase) + .expect("replace destination"); + + let saved: serde_json::Value = serde_json::from_str( + &std::fs::read_to_string(&path).expect("read replaced destination"), + ) + .expect("valid JSON"); + assert_eq!(saved["value"], 42); + assert_eq!( + std::fs::read_dir(directory.path()) + .expect("list temporary directory") + .count(), + 1, + "the temporary file must be removed after persistence" + ); + } + + #[test] + fn save_with_context_does_not_clobber_when_forbidden() { + let directory = tempdir().expect("temporary directory"); + let path = directory.path().join("dummy.json"); + std::fs::write(&path, "keep this").expect("seed destination"); + let item = DummyItem { + id: Uuid::nil(), + value: 42, + save: path.to_string_lossy().into_owned(), + }; + + assert!( + item.save_with_context("no-clobber test", &SaveMode::DoNotErase) + .is_err() + ); + assert_eq!( + std::fs::read_to_string(path).expect("read preserved destination"), + "keep this" + ); + } + // fn dummy_with_tempfile(value: i32) -> (DummyItem, std::path::PathBuf) { // let dummy = DummyItem::new(value); // (dummy.clone(), dummy.save.clone().into()) diff --git a/lib_efo/src/error.rs b/lib_efo/src/error.rs index ecb5e0d..686c51e 100644 --- a/lib_efo/src/error.rs +++ b/lib_efo/src/error.rs @@ -226,6 +226,14 @@ pub enum EpochError { #[diagnostic(code(EpochError::IllFormedStatQualifier))] IllFormedStatQualifier(String), + /// The statistic name is recognised but is not stored by this release. + #[error("Statistic `{0}` is not implemented in this release")] + #[diagnostic(code(EpochError::UnsupportedStat))] + #[diagnostic(help( + "Use `efo add --help` and choose a currently supported statistic." + ))] + UnsupportedStat(String), + /// User error, meant to be very explicit over what happened and what to do. #[error("An user facing error")] #[diagnostic(code(EpochError::UserError))] diff --git a/lib_efo/src/stats/implementations/from_impl.rs b/lib_efo/src/stats/implementations/from_impl.rs index ccff46a..0a6c5c0 100644 --- a/lib_efo/src/stats/implementations/from_impl.rs +++ b/lib_efo/src/stats/implementations/from_impl.rs @@ -27,6 +27,16 @@ impl FromStr for StatPair { }; let stat: ListStats = stat_str.parse()?; + if matches!( + stat, + ListStats::Social + | ListStats::Culture + | ListStats::Education + | ListStats::Tourism + | ListStats::Influence + ) { + return Err(EpochError::UnsupportedStat(stat_str.to_owned())); + } let value: isize = val_str .parse() .map_err(|_| EpochError::IllFormedStatQualifier(val_str.to_owned()))?; diff --git a/lib_efo/src/stats/implementations/test.rs b/lib_efo/src/stats/implementations/test.rs index 087c44b..e6c0aa1 100644 --- a/lib_efo/src/stats/implementations/test.rs +++ b/lib_efo/src/stats/implementations/test.rs @@ -90,6 +90,14 @@ fn stat_pair_ill_formed_errors_are_detected() { let err = stats::StatPair::from_str("unknown:5").unwrap_err(); assert!(matches!(err, EpochError::UnknownStatAcronim(_))); } + +#[test] +fn stat_pair_rejects_recognised_but_unimplemented_stats() { + for name in ["social", "culture", "education", "tourism", "influence"] { + let err = stats::StatPair::from_str(&format!("{name}:10")).unwrap_err(); + assert!(matches!(err, EpochError::UnsupportedStat(_))); + } +} #[test] fn position_invalid_format_errors_are_detected() { // 1️⃣ No comma