Skip to content

impl(067): spend journal identity: journal_id and created_at_ms in new headers (increment 1a, journal half) - #551

Merged
bartekus merged 2 commits into
mainfrom
impl/067-inc1a-journal
Nov 8, 2026
Merged

bartekus merged 2 commits into
mainfrom
impl/067-inc1a-journal

Conversation

@bartekus

@bartekus bartekus commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Spec 067 increment 1a, journal half (split out of #550, whose AI review timed out on size; #550 keeps the run binding and is rebased onto this once it merges).

crates/rustev-live/src/journal.rs (3.4.5):

  • Header gains optional journal_id and created_at_ms (schema name unchanged; deny_unknown_fields kept, so an earlier release refuses a new journal rather than misreading it). Header::new computes journal_id = tagged_digest("rustev.spend-journal-id/1", canonical_bytes({created_at_ms, run_id})) from the injected clock and the creating run's id. Header::parse accepts a header with both or neither member, a well-formed id, and the current or superseded testing cap (A-75).
  • JournalIdentity { id, created_at_ms, created: this_run | earlier | legacy }; a legacy header is never stamped (no time invented).
  • JournalOpening::prepare(path, kind, clock, run_id, require_existing) reads the header without creating anything (refuses a missing file with JournalError::Missing when asked), exposes header_digest(), superseded_header_digest() and identity(); open() takes the lock and refuses with JournalError::Changed if the header bytes changed since prepare. An empty file left by an interrupted creation gets an identity on open.
  • The A-75 migration replaces only the cap token (with_cap, a bounded byte scanner over the validated header line with a typed fallback), so identity and layout survive; the checkpoint digest is over the actual header bytes.
  • SpendJournal::open keeps its signature and creates under run id standalone; open_for_run names the run; identity() and header_digest() accessors.

The run binding (RunOptions journal path/switch/clock, checkpoint bound to the actual header, journal report member, CLI --require-existing-journal and new_journal) is in #550. This half changes no run, checkpoint or CLI behavior: checkpoints still bind the fixed testing header digest until #550.

Spec: 067 3.4.5. The implementation record paragraph is held for the increment 4 closure pull request (no spec or derived edit here, so 067 code pull requests stop colliding in the queue).

Spec-Drift-Waiver: spec 067 (approved, A-86) already extends crates/rustev-live/ for 3.4.5; under the 0.6.0 orchestrator rule of 2026-11-07 22:05, 067 implementation record paragraphs land together in the increment 4 closure pull request, because parallel record edits collided on .statecraft/derived and ejected each other from the merge queue. Covered by the owner's 0.6.0 preapproval of 2026-11-07.

Re-blessed conformance files

Rebased over #557 (live conformance cases), whose journals carry the old header. Re-blessed with the suite's own mechanism (RUSTEV_BLESS=1 cargo test -p rustev-conformance --test live, then --test manifest), never by hand: in each tools/rustev-conformance/expected/live/*/journal.jsonl and in fixtures/live/journal-cap.jsonl only the header line changes (gains journal_id and created_at_ms); the cases/live/*.json and cases/manifest.json changes are only the matching sha256 pins. No other golden moves. 14 files, 21 lines each way.

Tests

crates/rustev-live/tests/journal.rs: ids for (1, "23.x"), (12, "3.x"), (1, "3.x") distinct and equal to an independently computed tagged_digest over the canonical record; reopen reports earlier with unchanged bytes; superseded-cap migration keeps identity and returns the original bytes; a hand-written legacy header (whitespace, reordered members) is legacy, unstamped and its digest is over its actual bytes; an empty file gets an identity on open. The crash suite's release clock now counts the journal creation read (crates/rustev-live/crash/tests/crash.rs). The with_cap code was exercised by #550's full runs (cargo test -p rustev-live, -p rustev-cli, crash crate, -p rustev-jev, -p rustev-bedrock, clippy, fmt, all passing); after the rebase: cargo test -p rustev-conformance --locked (full), cargo test -p rustev-live -p rustev-live-crash --locked (full), make gate.

@github-actions

github-actions Bot commented Nov 7, 2026

Copy link
Copy Markdown

AI review (no-findings)

Reviewing the diff across the three changed files.

crates/rustev-live/src/journal.rs

Header::parse correctly enforces that journal_id and created_at_ms are both present or both absent, and validates the journal_id as a parseable ContentDigest. The JournalOpening::prepare / open_prepared split is a sound TOCTOU mitigation: read_header is called again after the lock file is created, and any difference returns JournalError::Changed before the journal file is touched. create_new(created) where created = opening.original.is_none() correctly handles the three cases (new file, empty file from interrupted write, existing file).

with_cap is a carefully narrowed byte scanner. The depth counter is updated only for bytes outside string literals, the escape-advance in the inner loop handles \" and \\, and the continue correctly prevents i += 1 from firing after the string arm. The depth == 1 guard confines the match to the top-level object. The at(n) sentinel (defaulting to b'}', which is neither : nor a digit) is safe for the end-of-buffer case. The fallback serde_json::from_slice … header.bytes() for escaped key spellings is documented in the comment and tested. The header_digest stored in Inner is computed from opening.current_header_bytes() before the migration write, but current_header_bytes() already returns the post-migration bytes (with_cap(original, new_cap)), so the digest matches the file after migration.

The relaxation of migrate from kind == BudgetKind::Testing && found == superseded to found.cap != kind.cap() is semantically equivalent: Header::parse already rejects any cap mismatch that isn't the superseded testing cap, so the only case where found.cap != kind.cap() can be true after a successful parse is that one case.

crates/rustev-live/tests/journal.rs

The legacy_bytes_open_continue_and_match_new_writes change from whole-file equality to tail equality (after the first newline) is correct: a legacy header upgraded by migration will now include journal_id and created_at_ms, so only the spend-entry section needs to match. The testing_header_digest_matches_the_written_header_including_newline change from the static testing_header_digest() to j.header_digest() is correct for the same reason. The new tests cover distinct IDs, reopen, migration, legacy, and interrupted-creation cases adequately.

specs/067-node-live-repeat-runs/spec.md

The implementation record (paragraph added under "Implementation record") accurately describes the code change. The spec status/implementation fields are not visible in the diff context, but the record addition does not claim ratification.

No concrete defects found.

{"head": "998ee470552a39bc18cf698e43b02c6e06c0faf5", "verdict": "no-findings", "findings": []}

Subject: 3a3c9bb...998ee47, diff digest 4b4b6195ec445b74f43f0b9f688ee2704a00e49128763ec877072f02843a5a7b, 1 call(s). An AI comment is not an approval.

@github-actions

github-actions Bot commented Nov 7, 2026

Copy link
Copy Markdown

AI review (no-findings)

Reviewing the diff across the four changed files: journal.rs (main feature), crash/tests/crash.rs (test adjustment), tests/journal.rs (test updates), and specs/067-node-live-repeat-runs/spec.md (implementation record).

crates/rustev-live/src/journal.rs

  • Header::new and Header::parse are symmetric: new sets both journal_id and created_at_ms together; parse enforces is_some() == is_some() for the pair. The invariant is maintained.
  • JournalOpening::prepare reads the header before the lock; open_prepared re-reads it after acquiring the lock and returns JournalError::Changed on any difference. This is a correct two-phase TOCTOU guard.
  • create_new(created) where created = opening.original.is_none(): for existing files (false), opens without O_CREAT; for new files (true), uses exclusive creation. Lock is held before the TOCTOU check and before the open, so no other SpendJournal instance can interfere.
  • with_cap: the scanner skips string contents (including escaped quotes and backslashes) before comparing against br#""cap""# at depth 1. The fallback for escaped key spellings via typed deserialization is correct and tested. The function is only called with previously validated header bytes, making the trailing expect a reasonable assertion rather than a reachable panic.
  • The migrate condition refactoring from kind == BudgetKind::Testing && found == superseded to found.cap != kind.cap() is correct: Header::parse already rejects any cap mismatch that isn't the testing-superseded exception, so found.cap != kind.cap() is only true for that exact case.
  • identity() logic: journal_id.is_none() → Legacy; journal_id.is_some() and original is None or empty → ThisRun; otherwise Earlier. Consistent with the documented contract.

crates/rustev-live/crash/tests/crash.rs

  • Counter initialised to usize::from(journal_exists_and_nonempty) and trigger changed from == 6 to == 7: prepare calls clock.now_ms() once (for Header::new) only when no existing non-empty journal is present. Starting the counter at 1 when a journal already exists correctly offsets for the skipped creation call, keeping the trigger at the same relative operation. Correct.

crates/rustev-live/tests/journal.rs

  • legacy_bytes_open_continue_and_match_new_writes now compares only post-header content against migrated(). The header is omitted from the assertion because it now contains journal_id and created_at_ms. The header identity is covered by creation_identity_uses_canonical_record_and_survives_reopen_and_migration and legacy_header_is_never_stamped_and_actual_bytes_are_bound. Acceptable relaxation.
  • testing_header_digest_matches_the_written_header_including_newline switched from the static SpendJournal::testing_header_digest() to j.header_digest(). Correct: the actual written header now includes identity fields, so only j.header_digest() matches.
  • creation_identity_uses_canonical_record_and_survives_reopen_and_migration uses {"run_id": run, "created_at_ms": time} (fields in opposite order from production code {"created_at_ms": ..., "run_id": ...}). Both produce the same digest only if canonical_bytes sorts keys lexicographically. c < r, so both orderings canonicalise to created_at_ms first. Correct assuming canonical serialisation sorts keys (which "canonical" implies and which the test suite would catch if wrong).

specs/067-node-live-repeat-runs/spec.md

  • Adds an implementation record for increment 1a. No lifecycle-value changes visible in the diff.

No concrete defects found.

{"head": "219cd181060cb333b0cbdcce9966ca44e20daf3f", "verdict": "no-findings", "findings": []}

Subject: 3a3c9bb...219cd18, diff digest 9e12752a7de1f0e9c5ed976b18c0f2f683911364ae85e855f4d31f62bea0ede1, 1 call(s). An AI comment is not an approval.

@bartekus
bartekus added this pull request to the merge queue Nov 7, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to a conflict with the base branch Nov 7, 2026
@bartekus
bartekus force-pushed the impl/067-inc1a-journal branch from 219cd18 to 8ac52cc Compare November 7, 2026 21:45
@github-actions

github-actions Bot commented Nov 7, 2026

Copy link
Copy Markdown

AI review (no-findings)

Reviewing the four changed files against each other and the governance context.

crates/rustev-live/src/journal.rs

Header::new — the canonical identity record uses serde_json::json! with key order {"created_at_ms": ..., "run_id": ...}. The test supplies them in the opposite order. If canonical_bytes sorts keys alphabetically this is fine (c < r), and the test proves it passes, so no defect.

with_cap — custom byte scanner that patches only the cap token. depth starts at 0; b'}' | b']' => depth -= 1 can go negative for malformed input, but the function is documented and called only with bytes that already passed Header::parse, so no reachable panic. The inner escape-advance (i += 1 after b'\\' without re-checking bounds) is bounded by (i + 1).min(bytes.len()) after the loop; no out-of-bounds access. The scanner correctly skips string contents (via continue) so string values containing {"cap":…} text cannot masquerade as a key. The double application with_cap(with_cap(x, a), b) used by superseded_header_digest is idempotent as long as the numeric token is found, which the existing tests exercise. No defect found.

open_prepared — the new ordering (acquire lock → re-read header → compare with opening.original → open file) is correct. Changing .create(true) to .create_new(created) without .create(true) for the existing-file case is an improvement: a rogue deletion now surfaces as an Io error rather than silently recreating an empty journal. JournalError::Changed is correctly returned when read_header(&path)? != opening.original, bounded by the writer lock. No defect found.

Header::parse — validates that journal_id and created_at_ms are either both present or both absent, and that if present the journal_id is a valid ContentDigest. Correct.

JournalOpening::identity — the three cases (journal_id.is_none() → Legacy; original.is_none_or(is_empty) → ThisRun; otherwise Earlier) are consistent with how prepare branches on original. Verified by the new tests.

crates/rustev-live/crash/tests/crash.rs

The ReleaseClock counter starts at usize::from(journal_exists_and_nonempty): 1 for resume (skipping the Header::new → clock.now_ms() call that is absent when the header is parsed from an existing file), 0 for fresh creation. The threshold changes from == 6 to == 7 to account for the new now_ms() call in Header::new during creation. Manual trace confirms: for creation the 8th call (case-reservation #3) still triggers; for resume the same relative call triggers. No defect.

crates/rustev-live/tests/journal.rs

legacy_bytes_open_continue_and_match_new_writes correctly narrows the assertion to everything after the first newline, because the migrated header now carries journal_id / created_at_ms while the golden migrated() string was written without them. The spend records below the header are still byte-compared. No defect.

testing_header_digest_matches_the_written_header_including_newline switched from SpendJournal::testing_header_digest() (legacy, no journal_id) to j.header_digest() (actual written bytes). The unchanged superseded_testing_header_digest_matches_the_legacy_header test still uses SpendJournal::testing_header_digest(), which is correct for its purpose (legacy headers with no journal_id). No defect.

specs/067-node-live-repeat-runs/spec.md

The implementation record is added within an existing spec. The diff touches only the ## Implementation record section, not lifecycle frontmatter. No ratification claim is made and no ownership change is introduced.

No concrete defect found across all changed paths.

{"head": "8ac52ccbc9283b139d46bb2d26046dcf93fc9d1b", "verdict": "no-findings", "findings": []}

Subject: ce699ae...8ac52cc, diff digest 640257730860164c731f90bbfc4dc370dc862ece93b20af915f9fb16d7a1785f, 1 call(s). An AI comment is not an approval.

@bartekus
bartekus added this pull request to the merge queue Nov 7, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to a conflict with the base branch Nov 7, 2026
@bartekus
bartekus force-pushed the impl/067-inc1a-journal branch from 8ac52cc to 47ffe56 Compare November 7, 2026 22:05
@github-actions

github-actions Bot commented Nov 7, 2026

Copy link
Copy Markdown

AI review (no-findings)

Review

crates/rustev-live/src/journal.rs

with_cap fast-path correctness. I traced all call sites: current_header_bytes() only reaches the with_cap(bytes, …) arm when self.original is a Some(bytes) that passed Header::parse (which asserts the bytes end with \n and serde-parsed cleanly), and superseded_header_digest() calls it on the same chain. The fallback serde_json::from_slice(bytes).expect("validated header") is therefore always called on bytes that serde can parse, so the panic branch is dead for production inputs.

Value-string false-positive for "cap". A string value "cap" at depth 1 is followed by , or }, never :. The function checks at(next) == b':' before treating a string as a key, so string values whose content equals cap are silently skipped. ✓

create_new(created) semantics. When created = false (file already exists and was confirmed by read_header under the lock-file), OpenOptions has neither .create(true) nor .create_new(true) set, which is correct: the file must already exist and will be opened without creation. ✓

migrate condition broadening. The new condition found.cap != kind.cap() appears broader than the previous kind == BudgetKind::Testing && found == superseded, but Header::parse itself returns Mismatch for any cap mismatch that isn't the superseded-Testing case, so the two conditions are equivalent in the reachable state space. ✓

Race between prepare and open_prepared. The read_header(&path)? != opening.original check under the lock correctly catches all file-state changes (creation, deletion, modification) between the two phases. ✓

crates/rustev-live/crash/tests/crash.rs

Counter initialization. usize::from(bool) yields 0 or 1. fetch_add returns the value before the increment, so starting at 1 means the 7th actual now_ms() call returns 7 and triggers the advance, correctly accounting for the skipped creation read on existing journals. ✓

crates/rustev-live/tests/journal.rs

testing_header_digest_matches_the_written_header_including_newline. Changed from SpendJournal::testing_header_digest() (a fixed no-identity digest) to j.header_digest() compared against tagged_digest(JOURNAL_SCHEMA, all_bytes). For a fresh fixture journal the file contains only the header line, so header_digest() (computed from header bytes only) equals the whole-file digest. ✓

legacy_bytes_open_continue_and_match_new_writes weakening. The assertion now compares only the body (post-first-line), not the full file, because the migrated header now carries identity fields. The header behavior is covered by legacy_header_is_never_stamped_and_actual_bytes_are_bound and creation_identity_uses_canonical_record_and_survives_reopen_and_migration, so the weakening is adequately compensated. ✓

specs/067-node-live-repeat-runs/spec.md

Additive implementation-record entry in a draft spec. No normative lifecycle or authority change. ✓


No concrete defects found.

{"head": "47ffe5605320f497e7179131f6067f13203bcfe2", "verdict": "no-findings", "findings": []}

Subject: e8f6653...47ffe56, diff digest 54baf9bec70e5e756a33238a0d60d3edee555a4808fe9b8b3c254ff3c4795227, 1 call(s). An AI comment is not an approval.

@bartekus
bartekus added this pull request to the merge queue Nov 7, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Nov 7, 2026
@bartekus
bartekus added this pull request to the merge queue Nov 7, 2026
@bartekus
bartekus removed this pull request from the merge queue due to a manual request Nov 7, 2026
@bartekus
bartekus force-pushed the impl/067-inc1a-journal branch from 47ffe56 to c2f6d47 Compare November 7, 2026 23:17
@github-actions

github-actions Bot commented Nov 7, 2026

Copy link
Copy Markdown

AI review (findings)

Review

crates/rustev-live/src/journal.rs

Lock file not cleaned up on JournalError::Changed

In open_prepared, the lock file at lp is created via create_new(true) and the PID is synced to it before the new TOCTOU check:

let _ = writeln!(lf, "{}", std::process::id());
let _ = lf.sync_all();

if read_header(&path)? != opening.original {
    return Err(JournalError::Changed);   // ← early return here
}

The Lock RAII guard (which removes the lock file on drop) is not initialized until the end of open_prepared when Inner is constructed. The diff context between lf.sync_all() and the Changed check shows no let lock = Lock { ... } line, confirming the guard is created later. Any early return before that point — including JournalError::Changed — leaves <journal>.lock on disk permanently, blocking all subsequent callers with JournalError::Locked until the file is manually deleted.

The pre-existing Mismatch and Corrupt returns shared this pattern, but those represent programmer-error or corruption scenarios unlikely to occur in production. Changed is specifically designed to fire under concurrent access, making the leak far more likely to happen in practice.

The fix would be to either initialize the Lock guard immediately after the sync (before any fallible operations) or drop lf and explicitly delete lp on the Changed path.


Other observations (no findings)

  • with_cap scanner: string-skipping is correct; depth tracking is sound; the at(n) sentinel b'}' correctly terminates digit/whitespace loops at EOF; the escaped-key fallback is exercised by the new unit test.
  • read_header / Changed double-check: the TOCTOU pattern is correct — header is read pre-lock, then re-confirmed post-lock before any writes.
  • Header::parse validation: the three-way guard (!ends_with('\n'), is_some() != is_some(), digest parse) is sound.
  • identity() / JournalCreated logic: None → Legacy, None-or-empty original + Some id → ThisRun, non-empty original + Some id → Earlier is internally consistent and matches the tests.
  • journal_id computation: the canonical_bytes path normalises key order, so the production computation (created_at_ms first) and test assertion (run_id first) produce the same digest.
  • crash.rs adjustment: starting calls at 1 when a non-empty journal exists correctly accounts for the creation clock.now_ms() call that is skipped on existing journals; the threshold == 7 is consistent.
{"head": "c2f6d4793449d30490546b6ee14198bf475d679a", "verdict": "findings", "findings": [{"path": "crates/rustev-live/src/journal.rs", "line": 649, "severity": "medium", "category": "correctness", "summary": "open_prepared creates the lock file via create_new and syncs it before the new JournalError::Changed early return, but the Lock RAII guard that removes the file is not initialized until Inner is constructed at the end of the function; returning Changed before that point leaves the lock file on disk permanently, blocking all future opens of that journal."}]}

Subject: 35ab7e5...c2f6d47, diff digest dd1444772a96a1d57d62b75f7ac1e4112b43f6c93de45ce8522071b0db9628ea, 1 call(s). An AI comment is not an approval.

@bartekus
bartekus temporarily deployed to statecraft-review-exception November 7, 2026 23:24 — with GitHub Actions Inactive
@bartekus

bartekus commented Nov 7, 2026

Copy link
Copy Markdown
Contributor Author

Review note: false positive. In open_prepared the RAII guard is bound immediately after the lock file is created (let lock = Lock(lp);, before the pid write and before the read_header(&path)? != opening.original check), so the early return Err(JournalError::Changed) (and the ? on read_header) drop lock and remove <journal>.lock. Inner only takes ownership of the same guard at the end. The pre-existing early returns after that line (header mismatch, corrupt lines) rely on the same guard. Covered by journal_changed_between_prepare_and_open_is_refused in #550 and by the CLI test replaced_journal_is_refused_on_resume_without_modifying_evidence, which asserts no journal.jsonl.lock remains.

@bartekus
bartekus added this pull request to the merge queue Nov 7, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Nov 8, 2026
@bartekus
bartekus force-pushed the impl/067-inc1a-journal branch from c2f6d47 to 745dcc4 Compare November 8, 2026 00:23
@github-actions

github-actions Bot commented Nov 8, 2026

Copy link
Copy Markdown

AI review (no-findings)

Reviewing the diff carefully for bugs, security issues, and correctness problems.

with_cap byte scanner – The depth-tracking correctly ignores {/[/}/] inside strings because the '"' branch uses continue to skip the outer i += 1. The check depth == 1 is applied after string scanning with the depth that was in effect before the string. For \uXXXX sequences, the scanner only skips one byte (u), leaving the four hex digits to be processed as ordinary characters; this means the key won't match "cap" literally, which is intentional — the comment and tests document that escaped key spellings fall back to serde_json. The fallback expect() is reachable only on validated bytes, which all callers enforce.

TOCTOU mitigation – open_prepared acquires the lock, then re-reads the header with read_header(&path)? != opening.original, returning JournalError::Changed if anything differs. The subsequent create_new(created) open adds a further guard for the new-file path. This is correct.

Migration path – Header::parse already restricts the cap-mismatch case to BudgetKind::Testing with the superseded cap, so let migrate = found.cap != kind.cap() is effectively Testing-only. The rewrite uses opening.current_header_bytes() = with_cap(original, kind.cap()), which preserves the original field order and the identity fields.

Identity computation – Header::new builds the journal_id from canonical bytes of {"created_at_ms": ..., "run_id": ...}. Since canonical_bytes sorts keys, the insertion order in the source JSON (different between Header::new and the test fixture) doesn't affect the result.

prepare clock call for new journals – JournalOpening::prepare calls clock.now_ms() exactly once (inside Header::new) for a new or empty journal, and not at all for an existing journal. The crash-test counter adjustment (usize::from(file_exists_and_nonempty)) correctly compensates for this asymmetry, so the trigger at counter == 7 hits the same relative call in both cases.

header_digest consistency – For a new journal, inner.header_digest = digest(header.bytes()) = digest(serde_json + \n). The file is written by append with the same bytes. The test testing_header_digest_matches_the_written_header_including_newline (updated to use j.header_digest()) verifies this directly.

Conformance fixtures – The input fixture journal-cap.jsonl and all expected journal.jsonl files carry the same journal_id/created_at_ms, consistent with a fixed clock and the "standalone" run-id used by SpendJournal::open.

No concrete defect found that the supplied evidence supports.

{"head": "745dcc4acfa520543fb6a2fc751d0da130d1dbf0", "verdict": "no-findings", "findings": []}

Subject: 811643f...745dcc4, diff digest b13238a4ee6df0b80373ab3736e954bffc95049ce71c822b1db44e59fdbeecc6, 1 call(s). An AI comment is not an approval.

@bartekus
bartekus added this pull request to the merge queue Nov 8, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Nov 8, 2026
@bartekus
bartekus added this pull request to the merge queue Nov 8, 2026
Merged via the queue into main with commit c575145 Nov 8, 2026
26 checks passed
@bartekus
bartekus deleted the impl/067-inc1a-journal branch November 8, 2026 01:43
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant