Skip to content

Commit 24171e3

Browse files
committed
feat(state): persist through one checksummed journal (C2)
The shell state is now saved through `journal`: one file, `.vsh_state.journal`, of framed records. Every mutation that must survive a restart is one record, appended and synced, so a crash leaves the state before or after it. The journal is rewritten as a single snapshot record, all-or-nothing, once it outgrows the history. The code mirrors the Agda model (`proofs/agda/JournalModel.agda`); it is not derived from it. What changes for a user: - A saved state that cannot be read stops the shell from starting, and the file is left as it is. Before, the shell started with an empty history, and the next write replaced the file. - Bytes at the end of the journal that are not a complete record (an interrupted write) are set aside in a `.rejected.` file, reported, and removed from the journal. - An old `.vsh_state.json` is converted on first start and kept as `.vsh_state.json.migrated`. - Rollback marks each operation undone as it reverses it, so `undo` no longer tries to reverse it again (`begin t; touch f; rollback; undo` failed on main). It skips operations already undone inside the transaction. It closes the transaction only when every operation has been reversed; if one cannot be, the transaction stays open. - Transaction begin, commit and rollback are journal records, no longer whole-state rewrites. Tests: - `journal_crash_tests` now tolerates no failing class. On real files: 3,070 crash states. On simulated storage that implements the model's file, after every storage call: 3,079 crash images, each required to open, to recover the state before or after the interrupted step, to recover the state after it once the step was acknowledged, and to keep later work. Four deliberate bugs were each caught (no sync, a trim left out of its record, a rollback written as a commit, a torn tail left in place). - Unit tests for an old-format file (a literal fixture), a damaged old-format file, an unknown record, a newer snapshot version, and failed appends, syncs and rewrites. Local results: cargo fmt and clippy clean; cargo test 862 passed, 0 failed; stress suite 11 passed (82 s on ext4, 39 s on tmpfs). The CI stress step now puts its temporary directories on tmpfs, so that it measures the shell and not the runner's disk. Still open on this branch: the journal lives in the session root, so shell commands can delete or alter it and two shells on one root are not kept apart (C3); deleted file contents are still inside history records (C4). Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01J4QvDjNR1ZoYKEPxSKE2nq
1 parent 67d36e7 commit 24171e3

12 files changed

Lines changed: 1005 additions & 519 deletions

‎.github/workflows/compilation_tests.yml‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -86,16 +86,21 @@ jobs:
8686
run: cargo test --verbose
8787

8888
# The ignored stress suite (tests/stress_tests.rs) gates the build. It was
89-
# repaired on 2026-11-17 (see docs/audits/2026-11-16-hypatia-remediation.adoc)
90-
# and runs in 30-50 s locally, so 5 minutes leaves wide margin for a slow
91-
# runner; there is deliberately no continue-on-error (Hypatia RE005).
89+
# repaired on 2026-11-17 (see docs/audits/2026-11-16-hypatia-remediation.adoc);
90+
# there is deliberately no continue-on-error (Hypatia RE005).
91+
# The shell syncs its journal after every operation, so on a real disk
92+
# this suite mostly measures the disk (82 s on ext4 against 39 s on tmpfs
93+
# locally). TMPDIR points at tmpfs so that the step measures the shell,
94+
# and 5 minutes leaves wide margin.
9295
# Linux only: stress_deep_nesting_1000_levels needs 1000 directory levels
9396
# in one absolute path (~2,000 bytes), which fits Linux's PATH_MAX of 4096
9497
# but not macOS's 1024.
9598
- name: Run ignored tests (stress)
9699
if: runner.os == 'Linux'
97100
working-directory: impl/rust-cli
98101
timeout-minutes: 5
102+
env:
103+
TMPDIR: /dev/shm
99104
run: cargo test --test stress_tests -- --ignored --test-threads=1
100105

101106
# ============================================================

‎.gitignore‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -122,8 +122,9 @@ htmlcov/
122122
ai-cli-crash-capture/
123123
.cache/
124124
.vsh_state.json
125+
.vsh_state.json.migrated
125126
.vsh_state.journal
126-
.vsh_state.json.*.tmp
127+
.vsh_state.journal.*
127128

128129
# ============
129130
# Strategic

‎EXPLAINME.adoc‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -127,10 +127,10 @@ reproduce. Absence of a tool is an open obligation, not a passing leg
127127
| About the model only. The crash model (synced bytes survive; the unsynced part survives as a prefix) is an assumption about storage, and reordered or partly written blocks are outside it. No property of the checksum is proved or needed
128128

129129
| The Rust journal follows the journal model
130-
| open
131-
| `impl/rust-cli/tests/journal_crash_tests.rs` (crash-point harness)
132-
| `impl/rust-cli/src/state.rs`
133-
| The code predates the model. Its two-file journal (a snapshot and an append log) fails two crash classes, which the harness pins in `KNOWN_OPEN`. Until the code is rebuilt on the model's storage interface this row stays `open`; after that it can be at most `tested-only`
130+
| tested-only
131+
| `cargo test --test journal_crash_tests`: 3,079 crash images on simulated storage that implements the model's file, and 3,070 crash states on real files, none failing (2026-11-17, local); four deliberate bugs were each caught
132+
| `impl/rust-cli/src/journal.rs`, `impl/rust-cli/src/state.rs`, `impl/rust-cli/tests/journal_crash_tests.rs`
133+
| Written to mirror the model, not derived from it or proved against it. One scripted session, not all sessions. The journal file still lives in the session root, so the shell's own commands can delete or alter it; the model does not cover that
134134

135135
| Same theorems restated in Z3 (Isabelle and Mizar archived 2026-11-09)
136136
| argued (the ledger word for PROOF-POLICY §5 `ASSUMED`: a direct SMT run with no proof certificate)

‎docs/ARCHITECTURE_DIAGRAMS.adoc‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -103,7 +103,7 @@ System Documentation
103103
│ │ │ │ │ │ │
104104
│ │ ┌──────▼──────────────────▼──────────────────▼───────┐ │ │
105105
│ │ │ State Persistence (JSON) │ │ │
106-
│ │ │ ~/.vsh_state.json │ │ │
106+
│ │ │ <root>/.vsh_state.journal │ │ │
107107
│ │ └────────────────────────────────────────────────────┘ │ │
108108
│ └─────────────────────────────────────────────────────────────┘ │
109109
│ │
@@ -214,7 +214,7 @@ USER INPUT: echo "Hello $USER" > output.txt
214214
┌─────────────────┐
215215
│ 7. UPDATE │ Update shell state
216216
│ STATE │ last_exit_code = 0
217-
│ (state.rs) │ Persist to ~/.vsh_state.json
217+
│ (state.rs) │ Persist to <root>/.vsh_state.journal
218218
└────────┬────────┘
219219
│
220220
▼
@@ -391,7 +391,7 @@ USER: undo
391391
392392
┌────────────┐
393393
│ START │ Initialize shell
394-
│ (clean) │ Load ~/.vsh_state.json (if exists)
394+
│ (clean) │ Load <root>/.vsh_state.journal (if exists)
395395
└──────┬─────┘
396396
│
397397
▼

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

Lines changed: 29 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,19 @@ Shell bugs fixed (`src/state.rs`, `src/commands.rs`):
119119
a torn tail, crash-after-rename and transactions; two more cover
120120
operations after a torn tail and `cd -` surviving a restart (`cd` now
121121
journals `previous_dir`).
122+
+
123+
*Superseded later on 2026-11-17.* Review kept finding crash-consistency
124+
defects in that two-file design (a snapshot beside a journal), and a
125+
crash-point harness confirmed two failing classes. It was replaced by one
126+
file of length-prefixed, checksummed records, each appended and synced,
127+
following an Agda model (`proofs/agda/JournalModel.agda`). The journal is
128+
rewritten as a single snapshot record, all-or-nothing, at the same threshold.
129+
A failed load is now an error instead of an empty history, and an old
130+
`.vsh_state.json` is converted on first start and kept as
131+
`.vsh_state.json.migrated`. The crash harness
132+
(`impl/rust-cli/tests/journal_crash_tests.rs`) finds no failing class on the
133+
new format. The amortised cost is unchanged; each operation now also pays
134+
one sync.
122135
* *O(n²) single-step undo.* Each `undo 1` walked past every already-undone
123136
operation to pick its target, then searched for that target again from the
124137
oldest end of the history to mark it. A checked hint for the block of undone operations removes the rescan:
@@ -129,6 +142,12 @@ Shell bugs fixed (`src/state.rs`, `src/commands.rs`):
129142
without saving. That had been masked by the next operation's full rewrite,
130143
and the journal would have exposed it. It now goes through
131144
`ShellState::abort_transaction`, which saves.
145+
* *Rollback left reversed operations live* (found in review, also on
146+
`main`): `begin t; touch f; rollback; undo` failed with "No such file or
147+
directory". Rollback now marks each operation undone as it reverses it,
148+
skips operations already undone inside the transaction, and closes the
149+
transaction only when every operation has been reversed. If one cannot
150+
be, the transaction stays open so the rollback can be run again.
132151

133152
Test expectations corrected (`tests/stress_tests.rs`):
134153

@@ -158,7 +177,11 @@ Test expectations corrected (`tests/stress_tests.rs`):
158177
(measured: 2.3 MB).
159178

160179
Measured (debug build, 4 cores, each test run alone with the CI flags):
161-
whole suite 29-51 s across three runs.
180+
whole suite 29-51 s across three runs. These are the timings of the two-file
181+
design. With the single-file journal and a sync per record, the whole suite
182+
takes 82 s on this machine's ext4 disk and 39 s on tmpfs (one run each). The
183+
CI step therefore puts its temporary directories on tmpfs, so that it
184+
measures the shell's own cost and not the runner's disk.
162185

163186
[cols="3,1",options="header"]
164187
|===
@@ -194,9 +217,8 @@ Still open:
194217
* *macOS.* The suite is not run there: `PATH_MAX` is 1024, so the
195218
1,000-level test cannot pass with absolute paths, and the rest was not
196219
measured on macOS.
197-
* Neither the journal nor the snapshot is `fsync`ed (the old `fs::write`
198-
was not either), and they still live in the session root. Both are now
199-
created with mode 0600 on Unix, since history can hold deleted file
200-
contents (Codex review on #229). Route plan items E1d and G2
201-
(`docs/plans/VSH-ROUTE-PLAN-2026-11-04.adoc`) still cover fsync and moving
202-
state out of the root; the journal is a new file they must include.
220+
* The journal still lives in the session root, so shell commands can delete
221+
or edit it, and two shells on one root are not kept apart. It is created
222+
with mode 0600, never opened through a symlink, and synced on every
223+
record. Moving it to an owner-only directory under an exclusive lock is
224+
the next step (route plan section 14.3, C3).

‎docs/plans/VSH-ROUTE-PLAN-2026-11-04.adoc‎

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -967,7 +967,7 @@ and ends at a machine-checked gate.
967967
|Step |What |Gate |Status
968968

969969
|C1 |Journal model in Agda (OD-30): record framing, event replay, a file and crash model |Checks under the estate invocation, in `All.agda` |Done (section 14.4)
970-
|C2 |One file of length-prefixed, checksummed records behind a small storage interface (append, sync, atomic replace, read), with a real implementation and a simulated one that loses exactly what the model's crash may lose. Compaction writes one snapshot record to a new file, syncs it, renames it over the old one and syncs the directory. A failed load is an error that stops the shell from writing; the files are kept. Rollback writes a record that marks each reversed operation undone. Old `.vsh_state.json` files still load (fixture test) |`KNOWN_OPEN` is empty; the harness also runs against the simulated storage |Next
970+
|C2 |One file of length-prefixed, checksummed records behind a small storage interface (append, sync, atomic replace, read), with a real implementation and a simulated one that loses exactly what the model's crash may lose. Compaction writes one snapshot record to a new file, syncs it, renames it over the old one and syncs the directory. A failed load is an error that stops the shell from writing; the files are kept. Rollback writes a record that marks each reversed operation undone. Old `.vsh_state.json` files still load (fixture test) |No failing crash class; the harness also runs against the simulated storage |Done (section 14.4a)
971971
|C3 |State moves out of the command root to an owner-only directory keyed by session root (OD-12a), opened with `O_NOFOLLOW`, checked through the descriptor, and held under an exclusive lock for the life of the shell |Shell commands cannot delete or edit state; a second shell on the same root is refused; a two-instance test passes |Open
972972
|C4 |Deleted-file contents go to a content-addressed blob store, not into the history |Removing 100 MB no longer writes about 300 MB of JSON |Open
973973
|===
@@ -1035,6 +1035,34 @@ Limits:
10351035
* A checksum cannot rule out bytes that were never written as a record but
10361036
happen to match.
10371037

1038+
[[c2-result]]
1039+
*14.4a C2 result (Measured 2026-11-17, local).* The shell state now persists
1040+
through `impl/rust-cli/src/journal.rs`: one file, `.vsh_state.journal`, of
1041+
records framed as a 4-byte length, the payload and its SHA-256. Each mutation
1042+
is one record, appended and synced. The crash harness finds no failing class:
1043+
3,079 crash images on the simulated storage (the model's file: synced bytes,
1044+
and every prefix of the unsynced ones, after every storage call) and 3,070
1045+
crash states on real files. Four deliberate bugs (no sync, a trim left out of
1046+
the record, a rollback written as a commit, a torn tail left in place) were
1047+
each caught. `cargo test`: 862 passed, 0 failed. An old `.vsh_state.json` is
1048+
converted on first start and kept under a new name. A sync costs about 0.15 ms
1049+
here (p95 0.43 ms), under the 2 ms threshold for syncing every record; the
1050+
stress suite takes 82 s on disk and 39 s on tmpfs, so its CI step uses tmpfs.
1051+
1052+
Three behaviours changed with it, each following the model. They are the
1053+
owner's to confirm:
1054+
1055+
* A saved state that cannot be read stops the shell from starting, with the
1056+
file left as it is. Before, the shell started with an empty history.
1057+
* Rollback marks the operations it reverses as undone, so `redo` can bring
1058+
them back one at a time.
1059+
* If rollback cannot reverse an operation, the transaction stays open, to be
1060+
rolled back again or committed. Before, it was closed with the operation
1061+
still in place.
1062+
1063+
Still open in Phase C: the journal lives in the session root (C3), and deleted
1064+
file contents are still inside the history records (C4).
1065+
10381066
Design choices the model fixes for C2:
10391067

10401068
* The history is append-only. Undo and rollback mark entries; redo records a new

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

Lines changed: 36 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1313,18 +1313,24 @@ pub fn commit_transaction(state: &mut ShellState) -> Result<()> {
13131313
Ok(())
13141314
}
13151315

1316-
/// Rollback the current transaction, reversing all operations atomically.
1316+
/// Rollback the current transaction, reversing its operations.
13171317
///
1318-
/// Undoes all operations in the active transaction started with [`begin_transaction`].
1319-
/// Operations are reversed in LIFO order. Reports partial failures if any rollback fails.
1318+
/// Undoes the operations of the active transaction started with
1319+
/// [`begin_transaction`], newest first. Each operation is marked undone as
1320+
/// soon as it has been reversed, so a later `undo` does not try to reverse
1321+
/// it again and an interrupted rollback can be resumed. Operations already
1322+
/// undone inside the transaction are left alone.
1323+
///
1324+
/// The transaction is closed only when every operation has been reversed.
1325+
/// If one cannot be (the reversal fails, or the operation has no inverse),
1326+
/// the transaction stays open: run `rollback` again once the cause is
1327+
/// fixed, or `commit` to keep what remains.
13201328
///
13211329
/// # Arguments
13221330
/// * `state` - Mutable shell state for transaction management
13231331
///
13241332
/// # Errors
1325-
/// Returns error if:
1326-
/// - No active transaction
1327-
/// - Rollback operations fail (reports which operations failed)
1333+
/// Returns error if an operation could not be reversed (reports which).
13281334
///
13291335
/// # Examples
13301336
/// ```no_run
@@ -1338,13 +1344,21 @@ pub fn commit_transaction(state: &mut ShellState) -> Result<()> {
13381344
/// # Ok::<(), anyhow::Error>(())
13391345
/// ```
13401346
pub fn rollback_transaction(state: &mut ShellState) -> Result<()> {
1347+
let Some(txn_id) = state.active_transaction.as_ref().map(|txn| txn.id) else {
1348+
println!("{}", "Nothing to rollback".bright_yellow());
1349+
return Ok(());
1350+
};
1351+
13411352
let ops: Vec<_> = state
13421353
.current_transaction_ops()
13431354
.iter()
1355+
.filter(|o| !o.undone)
13441356
.map(|o| (*o).clone())
13451357
.collect();
13461358

13471359
if ops.is_empty() {
1360+
// Nothing to reverse, but the transaction must not stay open.
1361+
state.abort_transaction();
13481362
println!("{}", "Nothing to rollback".bright_yellow());
13491363
return Ok(());
13501364
}
@@ -1514,18 +1528,24 @@ pub fn rollback_transaction(state: &mut ShellState) -> Result<()> {
15141528
}
15151529
};
15161530

1517-
// Collect failures
1518-
if let Err(e) = result {
1519-
failed_rollbacks.push((op.path.clone(), e.to_string()));
1531+
// Record each reversal as it happens, so the history never
1532+
// shows a reversed operation as live.
1533+
match result {
1534+
Ok(()) => state.mark_undone(op.id, txn_id),
1535+
Err(e) => failed_rollbacks.push((op.path.clone(), e.to_string())),
15201536
}
1537+
} else {
1538+
failed_rollbacks.push((
1539+
op.path.clone(),
1540+
format!("{} cannot be reversed", op.op_type),
1541+
));
15211542
}
15221543
}
15231544

1524-
// Clear the transaction (and persist that it is gone)
1525-
state.abort_transaction();
1526-
15271545
// Report results
15281546
if failed_rollbacks.is_empty() {
1547+
// Everything is reversed: close the transaction as rolled back.
1548+
state.abort_transaction();
15291549
println!(
15301550
"{} {} operations",
15311551
"Transaction rolled back:".bright_green(),
@@ -1544,6 +1564,10 @@ pub fn rollback_transaction(state: &mut ShellState) -> Result<()> {
15441564
for (path, err) in &failed_rollbacks {
15451565
eprintln!(" {} {}: {}", "Failed:".bright_red(), path, err);
15461566
}
1567+
eprintln!(
1568+
"The transaction is still open. Run rollback again once the cause is fixed, \
1569+
or commit to keep the remaining operations."
1570+
);
15471571

15481572
anyhow::bail!(
15491573
"Transaction rollback incomplete: {}/{} operations failed",

0 commit comments

Comments
 (0)