Skip to content

fix(storage): append review state without rewriting history - #1956

Merged
vastsa merged 2 commits into
vastsa:mainfrom
Seraph-x:fix/incremental-tool-review-state
Oct 29, 2026
Merged

vastsa merged 2 commits into
vastsa:mainfrom
Seraph-x:fix/incremental-tool-review-state

Conversation

@Seraph-x

@Seraph-x Seraph-x commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

Rolling back a historical Write/Edit review card loaded the entire session, rewrote its transcript, and rebuilt every message index row just to persist details.review.state. The regression test reproduces that full-rewrite path on the original implementation.

Persist the change as a small append-only tool_review_state record keyed by (messageId, snapshotId). Full, paginated, and nested-tool reads apply the latest state without moving the original message or changing its count or turn ownership. Repeated rollback acknowledgements append nothing.

Layout cache v3 stores message identities and state offsets, so historical-card lookup reads only the selected message after the layout is built. Reuse requires matching file identity and modification/change-time generation; only a Host-owned append from the proven generation advances the cached prefix. Unknown mutations and lagging disk caches are rebuilt.

Review invariants

  1. State survives remaining rewrite paths. truncate_from calls get_session, whose full read reaches read_transcript_window and apply_tool_review_states before the cut. rewrite_transcript_body then uses records_and_texts / ui_to_record and write_transcript_with_compactions to fold the effective state into surviving canonical messages. Discarded messages reach archive_discarded_regenerate_branch and save_message_revision / refresh_message_revision with that state already applied. truncate_from_folds_review_state_into_the_retained_prefix verifies that the state log disappears while the surviving tool record retains rolledBack. The existing tool_review_state_survives_fork_revision_activation_and_deletion covers the archived branch and subsequent lifecycle.
  2. File order is the order of record. State records have no timestamp. RPCs hold the Host state lock, append_line writes and syncs each complete line, and readers apply state in increasing byte-offset order. The last record for a key wins independently of clock precision. The ADR now states this explicitly.
  3. Equal-sized appends remain distinct. equal_length_state_appends_replay_in_file_order_across_cached_reads pads valid JSON whitespace so active and rolledBack records have exactly the same serialized length. It verifies that each append grows the file by that length, adds a distinct state offset, and returns the latest state through warm, cold, and sequential reads. This complements the existing equal-length in-place-edit-then-append invalidation regression.

Validation

  • cargo test -p host-core transcripts::: 84 passed.
  • cargo test -p host-core sessions::: 131 passed.
  • Formatting, diff checks, and node docs/scripts/check-docs.mjs: passed (596 pages).
  • Real release Host E2Es: scripts/e2e-review-state-persistence.mjs --large and scripts/e2e-transcript-cache.mjs cover rollback, original-prefix integrity, restart/retry, paging, legacy cache recovery, navigation, Task rewrites, and invalid UTF-8.
  • macOS arm64 release measurement on this follow-up: a 402,748,604-byte transcript appended only 129 bytes, with unchanged prefix SHA-256; cold layout build 305 ms, subsequent rollback 12 ms. Restart/retry and the existing transcript-cache E2E both passed.
  • The original PR head passed all six GitHub checks, including Windows transcript/cache E2E; the review follow-up adds only tests and documentation, and its checks will run on the updated head.
  • Local Clippy reports three pre-existing warnings: two chunks_exact suggestions in tools/hashline/tag.rs and the transcript's filter(...).next_back() suggestion. Consequently local -D warnings remains failing; no suppression rules were added.

Scope and compatibility

This fixes the review-state full-rewrite trigger in #1836 and its historical-message lookup cost. Deliberate history replacement, cold-start storage-integrity verification, and RPC fairness retain their existing behavior. Windows CI is separate from replaying the reported native WM_NULL/UI timeout, which has not been measured here.

No SQLite or RPC schema change is required. Older apps that ignore the additive state line may display the previous card state; snapshot metadata still prevents repeated destructive rollback. Intentional rewrites fold the effective state into the canonical message payload. The storage spec, ADR, and E2E scenario document these rules.

Refs #1836

Persist review rollback state as a small transcript mutation instead of
materializing and replacing the complete session and message index.

Cache proven message identities with the layout so historical card lookup
reads only its selected record. Invalidate unknown generations, preserve
message positions, and replay state across windows and session mutations.

Refs vastsa#1836
Copilot AI lite review requested due to automatic review settings October 28, 2026 09:42

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Independent Windows validation is still needed for append recovery, change-time generation, restart behavior, file timestamps, and cache invalidation because the supplied large-session evidence is macOS-only.

No open issues 🎉

What changed in this PR

This pull request changes review-state rollback from rewriting the full transcript to appending targeted tool_review_state records, preserving message positions, counts, and turn ownership while reducing large-session I/O.

Changes:

  • Adds append-only review-state persistence keyed by messageId and snapshotId, with replay across full, paginated, and nested-tool reads.
  • Upgrades transcript layout caching to v3 with message identities, state offsets, generation validation, and recovery handling.
  • Adds Rust regression tests, Host E2E coverage, storage specifications, an ADR, and updated test-plan documentation.
File Description
scripts/​e2e-transcript-cache.mjs Updates cache-format assertions for layout cache v3.
scripts/​e2e-review-state-persistence.mjs Adds large-transcript rollback, restart, prefix-integrity, and duplicate-append E2E coverage.
package.json Registers the review-state persistence E2E command.
docs/​spec/​06-delivery/​04-e2e-test-plan.md Documents review-state persistence scenarios and acceptance criteria.
docs/​spec/​03-runtime/​04-data-storage.md Specifies append-only review-state records and layout-cache v3 behavior.
docs/​adr/​README.md Adds the append-only review-state ADR to the index.
docs/​adr/​append-only-review-state.md Records the design decision, cache strategy, compatibility, and consequences.
crates/​host-core/​src/​transcripts/​review_state_tests.rs Tests state replay, cache behavior, torn tails, duplicate IDs, and rewrite handling.
crates/​host-core/​src/​transcripts/​layout.rs Adds layout-cache v3 identities, state offsets, generation validation, and incremental append handling.
crates/​host-core/​src/​transcripts/​binary_integrity.rs Exposes Windows change-time retrieval for generation tracking.
crates/​host-core/​src/​transcripts.rs Implements state-record serialization, append logic, replay, pagination support, and nested-tool integration.
crates/​host-core/​src/​sessions.rs Replaces full review-message rewrites with targeted append operations and adds lifecycle regression tests.

This pull request requires changes.

Review effort: Lite

@muzimu217 muzimu217 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verified the premise on current main: update_tool_review_state (crates/host-core/src/sessions.rs:3054) reads the transcript and calls replace_messages (around :3090), which is the same full-rewrite path regenerate uses. So a single rollback toggle on a large session rewrites the whole body and rebuilds every index — this is the same class of cost as #1836, and removing it is worth doing on its own merits, not only for the toggle.

The append design is the right shape: a (message_id, snapshot_id) keyed record, latest wins on read (apply_tool_review_states), message position/count/turn attribution untouched, and repeated rollback not appending duplicates. Keeping the original row authoritative and layering state on top is what makes the rewrite unnecessary without changing what readers see.

Three things I would want pinned in the description or the tests, because they are where append-only state usually breaks:

  1. What happens to the state records on the rewrite paths that still exist. Regenerate and truncate still call rewrite_transcript; if that path does not carry the appended records forward, a rollback silently reverts after the next regenerate. The test name tool_review_state_survives_fork_revision_activation_and_deletion suggests this is covered — naming the exact function that preserves them would make it reviewable without reading the test.

  2. Ordering under a same-key repeat. latest is built from the file order, so this relies on the append being strictly ordered on disk. If two toggles land within the same timestamp granularity, is the later record still last in the file (not sorted by timestamp)? A line in the ADR saying "file order is the order of record" would settle it.

  3. Cache generation with equal-length appends. The description says an equal-length edit followed by an append forces a rebuild, which is the hard case; a test that appends a record whose serialized length happens to match the previous one, then reads back, would pin it. If that case is already in review_state_tests.rs, ignore this.

The layout cache v3 carrying record offsets rather than re-parsing large messages is the part that makes this a real win rather than a smaller rewrite, and validating file identity plus generation before reusing it is the right guard.

Document the exact read-overlay and serialization path that preserves
review state through transcript rewrites and revision archives.

Cover retained-prefix truncation and equal-sized state appends through
warm, cold, and sequential reads without relying on timestamps.

Refs vastsa#1836
@Seraph-x

Seraph-x commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor Author

@muzimu217 Addressed the three review points in the ADR, PR description, and regression coverage:

  1. Remaining rewrites: truncate_from reads through get_session → read_transcript_window → apply_tool_review_states before cutting. rewrite_transcript_body then calls records_and_texts / ui_to_record and write_transcript_with_compactions, folding the effective state into each surviving canonical tool message. Discarded branches reach archive_discarded_regenerate_branch and save_message_revision / refresh_message_revision with state already applied. Added truncate_from_folds_review_state_into_the_retained_prefix to inspect the rewritten JSONL directly: the mutation log is gone, but the surviving tool still stores rolledBack. The existing fork/revision/delete lifecycle test covers the archived branch and its restoration.
  2. Same-key ordering: the ADR now explicitly says “File order is the order of record.” These records have no timestamp; calling RPCs hold the Host state lock, append writes are synced before returning, and indexed reads order updates by byte offset. Last-write-wins therefore does not depend on clock granularity.
  3. Equal-sized appends: added equal_length_state_appends_replay_in_file_order_across_cached_reads. It uses JSON whitespace to make the valid active and rolledBack lines exactly equal-sized, then checks file growth, distinct state offsets, and latest-state replay through warm, cold, and sequential reads. Equal record length is distinct from unchanged total file size; this also complements the existing in-place equal-length-edit-then-append regression.

The follow-up changes only tests and documentation. Both targeted suites pass: 84 transcript tests and 131 session tests. Formatting, diff checks, and all 596 documentation-page checks pass.

@vastsa vastsa left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed the review-state full-rewrite trigger in #1836 and verified this PR removes that path while preserving message positions, replay, and rewrite folding. On the current main integration tree: 84 transcript tests, 132 session tests, formatting, the 384 MiB Host rollback/restart E2E, and the transcript-cache E2E passed. The large E2E retained the original prefix and appended 129 bytes. Clippy completed with one existing filter(...).next_back() warning. The untested Windows-specific file-generation behavior remains a platform limitation of this local review. Thanks for the careful fix and regression coverage.

@vastsa
vastsa merged commit e425307 into vastsa:main Oct 29, 2026
5 of 6 checks passed
@Seraph-x
Seraph-x deleted the fix/incremental-tool-review-state branch October 29, 2026 02:52
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.

4 participants