Skip to content

Commit 2273913

Browse files
committed
fix(state): recover from a torn journal; journal cd's previous_dir
Two findings from the Codex review on #229, both regressions from the journal introduced in 52ed149: - A torn journal line (crash mid-append) ended replay but left the line in place, so operations appended after the restart were skipped by every later reload and could no longer be undone. load() now marks a snapshot as pending when replay stops early, so the next persist writes a full snapshot and truncates the journal. - cd set previous_dir without persisting it; before the journal, the next operation's full rewrite carried it. cd now goes through ShellState::set_previous_dir, which journals a PreviousDir entry, so cd - survives a restart. Two regression tests; the torn-tail one fails without the fix. cargo test 837 passed; stress suite 11 passed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01J4QvDjNR1ZoYKEPxSKE2nq
1 parent 52ed149 commit 2273913

3 files changed

Lines changed: 77 additions & 5 deletions

File tree

‎docs/audits/2026-11-16-hypatia-remediation.adoc‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -112,9 +112,13 @@ Shell bugs fixed (`src/state.rs`, `src/commands.rs`):
112112
keeps the cost amortised O(1). Snapshots are written to a temporary file
113113
and renamed, and record the last journal sequence number they contain, so
114114
a crash cannot tear the snapshot or replay an entry twice. A torn journal
115-
line or a sequence gap ends replay. After the fix, 1,000 touches take
115+
line or a sequence gap ends replay and forces the next save to be a full
116+
snapshot, so operations made after a crash are not stranded behind the
117+
bad line (Codex review on #229). After the fix, 1,000 touches take
116118
0.04 s. Seven new unit tests in `state.rs` cover replay, compaction, trim,
117-
a torn tail, crash-after-rename and transactions.
119+
a torn tail, crash-after-rename and transactions; two more cover
120+
operations after a torn tail and `cd -` surviving a restart (`cd` now
121+
journals `previous_dir`).
118122
* *O(n²) single-step undo.* Each `undo 1` walked past every already-undone
119123
operation to pick its target, then searched for that target again from the
120124
oldest end of the history to mark it. A checked hint for the block of undone operations removes the rescan:
@@ -190,8 +194,6 @@ Still open:
190194
* *macOS.* The suite is not run there: `PATH_MAX` is 1024, so the
191195
1,000-level test cannot pass with absolute paths, and the rest was not
192196
measured on macOS.
193-
* `previous_dir` (set by `cd` without a save) reaches disk at the next
194-
snapshot, not at the next operation as before.
195197
* Neither the journal nor the snapshot is `fsync`ed (the old `fs::write`
196198
was not either), the files keep the default mode, and they still live in
197199
the session root. Route plan items E1d and G2

‎impl/rust-cli/src/executable.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -402,7 +402,7 @@ impl ExecutableCommand for Command {
402402
}
403403

404404
// Store current directory as previous before changing
405-
state.previous_dir = Some(state.root.clone());
405+
state.set_previous_dir(state.root.clone());
406406

407407
// Change the shell's working directory
408408
std::env::set_current_dir(&target)?;

‎impl/rust-cli/src/state.rs‎

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -664,6 +664,21 @@ impl ShellState {
664664
Ok(())
665665
}
666666

667+
/// Set the directory `cd -` returns to, and journal it so it survives a
668+
/// restart without waiting for the next snapshot.
669+
pub fn set_previous_dir(&mut self, dir: PathBuf) {
670+
self.previous_dir = Some(dir);
671+
let persisted =
672+
self.persist_entries(&[JournalEntryRef::PreviousDir(self.previous_dir.clone())]);
673+
if let Err(e) = persisted {
674+
eprintln!(
675+
"{} Failed to save previous directory: {}",
676+
"Warning:".bright_yellow(),
677+
e
678+
);
679+
}
680+
}
681+
667682
/// Drop the active transaction without committing it (after a rollback)
668683
/// and persist that, so a restart does not resurrect it.
669684
pub fn abort_transaction(&mut self) {
@@ -829,23 +844,32 @@ impl ShellState {
829844

830845
if self.journal_file.exists() {
831846
let journal = crate::fs_pure::read_to_string(&self.journal_file)?;
847+
let mut replayed_all = true;
832848
for line in journal.lines() {
833849
// A torn line (crash mid-append) ends the replay, and so does
834850
// a sequence gap: replay keeps the longest consistent prefix.
835851
let Ok(JournalLine { seq, entry }) = serde_json::from_str::<JournalLine>(line)
836852
else {
853+
replayed_all = false;
837854
break;
838855
};
839856
if seq <= self.journal_seq {
840857
continue; // already folded into the snapshot
841858
}
842859
if seq != self.journal_seq + 1 {
860+
replayed_all = false;
843861
break;
844862
}
845863
self.replay(entry);
846864
self.journal_seq = seq;
847865
self.journal_entries += 1;
848866
}
867+
// Entries appended after a torn line or gap would be skipped by
868+
// every later reload. Make the next persist write a full snapshot,
869+
// which also truncates the journal, instead of appending.
870+
if !replayed_all {
871+
self.snapshot_pending = true;
872+
}
849873
}
850874

851875
// The history was replaced wholesale; drop the undone-block hint.
@@ -877,6 +901,9 @@ impl ShellState {
877901
let n = n.min(self.history.len());
878902
self.history.drain(0..n);
879903
}
904+
JournalEntry::PreviousDir(dir) => {
905+
self.previous_dir = dir;
906+
}
880907
}
881908
}
882909

@@ -1209,6 +1236,8 @@ enum JournalEntry {
12091236
Undone { id: Uuid, undone_by: Uuid },
12101237
/// The oldest `n` operations dropped by the history size limit.
12111238
Trim(usize),
1239+
/// The directory `cd -` returns to, as set by `cd`.
1240+
PreviousDir(Option<PathBuf>),
12121241
}
12131242

12141243
/// Borrowing twin of [`JournalEntry`]; serialises to the same shape.
@@ -1217,6 +1246,7 @@ enum JournalEntryRef<'a> {
12171246
Record(&'a Operation),
12181247
Undone { id: Uuid, undone_by: Uuid },
12191248
Trim(usize),
1249+
PreviousDir(Option<PathBuf>),
12201250
}
12211251

12221252
#[derive(Deserialize)]
@@ -1749,6 +1779,46 @@ mod tests {
17491779
assert_eq!(summary(&reloaded), summary(&state));
17501780
}
17511781

1782+
#[test]
1783+
fn test_operations_after_torn_tail_survive_reload() {
1784+
let root = persisted_root();
1785+
let mut state = reopen(&root);
1786+
record(&mut state, "a");
1787+
{
1788+
use std::io::Write;
1789+
let mut journal = fs::OpenOptions::new()
1790+
.append(true)
1791+
.open(&state.journal_file)
1792+
.unwrap();
1793+
journal.write_all(b"{\"seq\":2,\"entry\":{\"Rec").unwrap();
1794+
}
1795+
1796+
// The restarted shell keeps working after the crash...
1797+
let mut restarted = reopen(&root);
1798+
record(&mut restarted, "b");
1799+
record(&mut restarted, "c");
1800+
1801+
// ...and those later operations must not hide behind the torn line.
1802+
let reloaded = reopen(&root);
1803+
assert_eq!(reloaded.history.len(), 3);
1804+
assert_eq!(summary(&reloaded), summary(&restarted));
1805+
}
1806+
1807+
#[test]
1808+
fn test_previous_dir_survives_reload_without_snapshot() {
1809+
let root = persisted_root();
1810+
let mut state = reopen(&root);
1811+
record(&mut state, "a");
1812+
state.set_previous_dir(PathBuf::from("/tmp/elsewhere"));
1813+
assert!(!state.state_file.exists(), "no snapshot should be needed");
1814+
1815+
let reloaded = reopen(&root);
1816+
assert_eq!(
1817+
reloaded.previous_dir.as_deref(),
1818+
Some(Path::new("/tmp/elsewhere"))
1819+
);
1820+
}
1821+
17521822
#[test]
17531823
fn test_snapshot_skips_already_folded_journal_entries() {
17541824
let root = persisted_root();

0 commit comments

Comments
 (0)