Skip to content

fix(native-chat): save each chat change as keyed records and reopen from the newest - #36024

Merged
brennanb2025 merged 108 commits into
mainfrom
brennanb2025/journal-saved-state
Oct 31, 2026
Merged

brennanb2025 merged 108 commits into
mainfrom
brennanb2025/journal-saved-state

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

The problem. Every streamed revision of a native-chat reply or tool call is saved as a full copy, and reopening a chat replays every copy. One user's chat database reached 19.9 GB across 310 chats, and opening a long chat got slower as its history grew. Earlier versions of this PR saved a derived "current state" and planned to convert existing chats to it. Both tied the meaning of saved data to the code that computes it: a later Orca that changed that code, or an earlier Orca reading a later one's data after a downgrade, could misread or quietly drop what was saved, and every release would have needed new upgrade and downgrade handling.

Tracked in #34916.

What changes.

  • From now on, each write saves what it changed as whole, keyed values: each changed message or tool item, each changed piece of chat bookkeeping (sends, receipts, queue cards, Stop facts) and each deletion. Each saved record says which storage format it uses. Decisions such as "this is a duplicate" or "this revision is stale" are made once, when the write happens, and only the result is stored. Opening a chat this build created reads the newest value of each key and never re-runs those decisions.
  • No Orca build rewrites saved data it doesn't fully understand. A build that finds a saved record, field or value it doesn't declare refuses that chat as "saved by a newer Orca" instead of guessing. A field added by a later Orca needs no new format: older builds simply refuse chats that contain it. A compile-time check keeps the storage definitions in step with the code.
  • Existing chats keep their old rows unchanged. The first change this build makes to an existing chat (a send, a Stop, a rewind, or the bookkeeping Orca already does when it opens a chat with queued or interrupted work) appends one marker row, and new records follow it. Opening such a chat reads its old rows the way Orca does today, then the newer records. Old rows are deleted only where Orca already deletes them today (a rewind or a history replacement), and then the kept messages are saved again in the new form.
  • Phones, paired servers and older clients see the same wire messages as before.

Downgrades. A chat this build created or changed carries the marker. The last two Orca releases already refuse such a chat on open with "This chat was saved by a newer Orca. Update Orca to open it." and change nothing on disk; updating again brings it back intact. This is checked against v1.4.244's and v1.4.245's own code in the cross-version tests. An existing chat this build never changed still opens on older builds (checked in QA).

Intended differences from the common pattern.

  • The "newer version" refusal is per chat (a marker row) rather than for the whole database, so chats this build never changed keep opening on older builds.
  • Saved data is checked strictly: a key this build doesn't declare, in a new record, in an old row of an existing chat, or in a legacy queued card, refuses the chat (or leaves that card on disk unshown) rather than being ignored. Rewind and history replacement save the open chat again, so admitting only what the build fully reads keeps them from dropping anything a newer build wrote; it also keeps a two-release downgrade window safe, which the common pattern doesn't support. Audits of every release since native chat shipped, and tests that open, write to and rewind chats written by the last releases, found no existing chat this refuses.
  • A damaged record that a newer record of the same key has replaced is no longer read, so it no longer blocks the chat; Orca today refuses a chat with any unreadable row. Unsupported formats still refuse.
  • Old rows of existing chats get no speed or size benefit; their new writes do.
  • Background cleanup of records left by replaced chat histories starts about a minute after launch instead of storing when it last ran.

Known limits.

  • Storage is not reduced until fix(native-chat): remove superseded chat history rows and return their space #36053 deletes superseded records: each write stores one record per changed key where Orca stores one row today, so this PR alone grows the chat database as Orca does today, until fix(native-chat): remove superseded chat history rows and return their space #36053 lands. Both PRs target the same release.
  • How a changed existing chat's old rows are read is now fixed for good: a later build that needs to read them differently must write a new marker version, which this build and older ones refuse, rather than change what the current marker means.
  • A future change to what a stored field means (not just a new field) is a storage format change: that build adds a new format and reads the old one in memory; older builds refuse chats written in it.
  • If a write fails to save, the send fails as it does today ("Orca couldn't save this to the chat's history.", not sent, with retry).

Validation.

  • CI green on the final head.
  • Real Claude and Codex on Windows, from a current-main build with existing chats: upgrade (existing chats reopen intact and opening writes nothing), first sends (marker appended, old rows byte-identical), restart and resume (both agents remember the conversation), downgrade to main (chats this build changed or created are refused with "This chat was saved by a newer Orca. Update Orca to open it.", an untouched chat still opens and works, and main changes nothing this build wrote), and re-upgrade (every chat intact and takes sends).
  • Reporter-scale benchmark (310 chats, 2.58M rows, 24.5 GB) against main: an untouched existing chat opens at 1.11-1.17x main's time; a 2 MiB streamed revision costs 1.40-1.46x main; a chat this build wrote with 8,000 revisions of a 2 MiB reply opens in 14 ms where main takes 10.5 s; rewind takes 14 ms vs 204 ms; background cleanup reads nothing when there is nothing to clean and stays under 10% of the time after a large rewind; every reopened chat matches its live state, and untouched chats stay byte-identical.
  • Cross-version tests open, write to and rewind chats written by the last releases, and check that those releases refuse this build's chats without changing them.

Publish versioned reducer checkpoints atomically, checkpoint through the chat write queue, and backfill closed chats without retiring journal rows.

Co-Authored-By: Codex <noreply@openai.com>
@brennanb2025
brennanb2025 marked this pull request as ready for review October 29, 2026 17:35
@greptile-apps

greptile-apps Bot commented Oct 29, 2026 •

Copy link
Copy Markdown

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The reviewed changes appear safe to merge.

Summary

The PR saves chat checkpoints and reopens chats from a saved prefix plus newer journal rows.

  • Native chats save their current state alongside the journal.
  • Native chats reopen from a saved state and newer journal rows.
  • A paced background pass builds checkpoints for closed chats.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[Open chat] --> B{Usable saved state?}
  B -->|Yes| C[Read newer journal rows]
  B -->|No| D[Replay retained journal]
  C --> E[Restore chat]
  D --> E
  E --> F[Settled change or close]
  F --> G[Save on chat write queue]
Loading

Reviews (9) · Last reviewed commit: "test: exercise restored consumer backwar..." · Reviewed by Greptile

@coderabbitai

coderabbitai Bot commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review.

Recent review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 4aa39bbd-3421-4a78-990f-c64b62854c9b
Commits

Reviewing files that changed from the base of the PR and between a15c795 and 50278cb.

Files selected for processing: 1
  • src/main/native-chat/agent-session-wire/structured-agent-session-host.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 0 remain after this review.

Walkthrough

The journal now stores versioned reducer-state checkpoints and restores them before replaying later rows. Live journal activity schedules checkpoints, and closing a journal performs a final checkpoint. A scheduled backfill processes eligible closed-session journals. Epoch changes and edits to rows within a saved prefix clear the saved state.

Merge Risk: Minimal · up to 50278

No concrete merge-blocking risk remains in the supplied review scope.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 31.82% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documenta… Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Description check Passed The description is detailed and covers the problem, changes, rationale, linked issue (#34916), known limits, compatibility, testing, performance, and downgrade behavior. It does not include an explici…
Title check Passed The title clearly describes the main changes: saving chat state as keyed records and reopening from the newest saved state.
Full details: Description check

Explanation

The description is detailed and covers the problem, changes, rationale, linked issue (#34916), known limits, compatibility, testing, performance, and downgrade behavior. It does not include an explicit Visual Proof section with N/A, AI Disclosure, or the repository checklist, but these omissions do not prevent the description from being mostly complete.

Full details: Docstring Coverage

Explanation

Docstring coverage is 31.82% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 22 functions across 28 files.

Resolution

Write docstrings for the functions missing them to satisfy the coverage threshold.

Finishing Touches
Generate docstrings
  • Commit to this branch
  • Create a new PR
Fix failing CI checks
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 1

Nitpick comments: 1
src/main/native-chat/agent-session-journal/journal-saved-state.ts: 1

86-99: Trivial · Performance & Scalability · Heavy lift

Each checkpoint rewrites every saved item inside one FULL-synchronous transaction.

saveJournalState deletes all journal_items rows for the session and reinserts every item. It also re-encodes the whole reducer with JSON.stringify first. checkpoint() runs this on the chat's write lane through the synchronous SQLite driver, and every non-streamed commit schedules one. For a long chat, each save costs O(items) in CPU, I/O and fsync. The cost lands on the main process, and queued sends wait behind it. This conflicts with the stated goal that saves do not delay sends.

Consider writing only items whose revision changed since the last save. Alternatively, raise the 1 s debounce for large states. Either option still keeps the "whole checkpoint is atomic" property.


Review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 5efa3a16-a17f-4d52-a362-e7c876de94ba
Commits

Reviewing files that changed from the base of the PR and between d61c8b8 and 4abc374.

Files selected for processing: 20
  • src/main/native-chat/agent-session-journal/journal-database.ts
  • src/main/native-chat/agent-session-journal/journal-derived-turn-scope.ts
  • src/main/native-chat/agent-session-journal/journal-epoch-replacement.ts
  • src/main/native-chat/agent-session-journal/journal-epoch-rollover.ts
  • src/main/native-chat/agent-session-journal/journal-host-database-test-support.ts
  • src/main/native-chat/agent-session-journal/journal-open.ts
  • src/main/native-chat/agent-session-journal/journal-row-table.ts
  • src/main/native-chat/agent-session-journal/journal-row-writer.ts
  • src/main/native-chat/agent-session-journal/journal-saved-state.test.ts
  • src/main/native-chat/agent-session-journal/journal-saved-state.ts
  • src/main/native-chat/agent-session-journal/journal-state-backfill.ts
  • src/main/native-chat/agent-session-journal/journal-state-codec.ts
  • src/main/native-chat/agent-session-journal/journal-store-collaborators.ts
  • src/main/native-chat/agent-session-journal/journal-store-restore.ts
  • src/main/native-chat/agent-session-journal/journal-store.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-host.ts
  • src/main/runtime/structured-agent-runtime-registrations.ts
  • src/main/runtime/structured-agent-session-attachment-wiring.ts
  • src/main/runtime/structured-agent-session-host-assembly.ts
  • src/shared/wsl-move/wsl-move-storage-dispositions.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 7 remain after this review.

@coderabbitai coderabbitai Bot 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.

Nitpick comments: 1
src/main/native-chat/agent-session-journal/journal-saved-state.test.ts: 1

149-155: Trivial · Data Integrity & Integration · Quick win

Exercise both non-default saved-state fields.

The fixture at journal-saved-state.test.ts:149-155 leaves normalizedHandOffs empty and oldestSequence at 1. A codec or restore regression that drops non-empty handoff corrections or fails to restore a non-default replay boundary can therefore pass the round-trip and equivalence tests. Extend this fixture with a rejected in-doubt submission that creates a non-empty normalizedHandOffs and with a non-default oldestSequence. This is a coverage gap, not evidence that the current implementation fails.


Review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 1c898156-69de-4ce8-836c-bc3f7c967b6e
Commits

Reviewing files that changed from the base of the PR and between 5c7df65 and a15c795.

Files selected for processing: 1
  • src/main/native-chat/agent-session-journal/journal-saved-state.test.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 1 remain after this review.

@brennanb2025

brennanb2025 commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor Author

Review status: review loop done on a65467d; CI green; real Claude and Codex QA passed; benchmark under both limits.

The problem. Native chat saves a full copy of every streamed revision of a reply or tool call, and reopening a chat replays every copy. One user's chat database reached 19.9 GB across 310 chats, and long chats got slower to open as they grew. Earlier designs of this PR saved a derived "current state" and converted old chats to it, which tied the meaning of saved data to the code computing it, so any later upgrade or downgrade could misread or drop saved data.

What users get. From this build on, each write saves only what changed, as whole keyed values that no later build rewrites. Opening a chat this build wrote reads each value's newest copy instead of replaying history. A chat this build wrote with 8,000 revisions of a 2 MiB reply opens in 14 ms where main takes 10.5 s. Existing chats keep their old rows untouched; their first change from this build appends a marker, after which the last two releases refuse the chat with "This chat was saved by a newer Orca. Update Orca to open it." and change nothing; updating again brings it back intact. Phones and paired servers see the same wire messages. The database still grows as it does today until #36053 deletes superseded copies; both should ship in the same release.

What review changed (v5: six rounds plus readiness; design settled by panel rulings, the last one unanimous):

  • No conversion of old chats and no rebuildable cache: future writes are immutable, self-describing records, read newest-per-key.
  • A strict storage check: a build refuses a chat holding a saved key it doesn't declare, instead of guessing or dropping it. A compile-time check keeps the storage definitions in step with the code; it caught a real gap (a branded string type) once typecheck ran.
  • Rewind, history replacement and rollover keep main's behavior and delete old data only where main does; background cleanup removes retired records at a 10% duty cycle.
  • After the main merge: open parses each record once, encoding no longer reads through change-tracking proxies, a quadratic record match became linear, and rewind/replacement/rollover have linear-cost contract tests.

Verified.

  • CI green on a65467d (one main merge, 0ef88c1, in d3c7fa6; CI on the merged head checks it, and the readiness reviewers read the PR's diff on merged main).
  • Real Claude and Codex QA on Windows (win-high), main 0ef88c1 → a65467d, all graceful stops: upgrade with existing chats (reopen intact, opening writes nothing), first sends (marker appended, old rows byte-identical), restart and resume (both agents remember the conversation), downgrade to main (changed and new chats refused with the message above; an untouched chat opens and works; main changes nothing this build wrote), re-upgrade (all chats intact and take sends). Not exercised: reopening with a paused queued card, because main has mid-turn queueing switched off and can't create one; tests cover it.
  • Benchmark at reporter scale (310 chats, 2.58M rows, d3c7fa6 vs main): untouched existing chat opens at 1.11-1.17x main (limit ~1.25x); a 2 MiB streamed revision costs 1.40-1.46x (limit ~2x); rewind 14 vs 204 ms; idle cleanup reads nothing; every reopened chat equals its live state. Commits after it change only how new-format records are decoded and encoded (same output, less work) and leave the existing-chat open path unchanged, so these readings carry.
  • Reference comparison: every difference labelled (intended: per-chat downgrade refusal, strict storage check, no cache, no conversion; temporary: superseded records kept until fix(native-chat): remove superseded chat history rows and return their space #36053).

Deferred follow-ups.

  • A phone's history page errors instead of resetting when a superseded record has a damaged key: STA-13100.
  • Retired records after a rewind of a new-format chat wait for the next cleanup pass (up to 6 h) instead of going at once; fix(native-chat): remove superseded chat history rows and return their space #36053's area.
  • Leftover names and dead code from earlier designs of this PR (names like "backfill" and "projection", unused read-failure helpers, one stale comment in journal-store.ts).

Seen on main during QA, not this PR's: the fixture's default tabs (from orca.yaml) never opened, only Setup; Codex replied that its plan tool wasn't available in the chat.

For Brennan's review.
Main before upgrade (Claude, Codex) and the same chats after upgrading:
m-01b-claude-stopped-queued.png u-03-claude-upgraded.png
m-02-codex-plan-tool.png u-04-codex-upgraded.png
Downgraded to main (refusal), then re-upgraded:
d-10-refused-existing.png ru-12-claude-reupgraded.png

Where judgment matters:

@brennanb2025
brennanb2025 marked this pull request as draft October 30, 2026 07:42
…aved-state cache

The cache copied each key's newest record into a second set of tables and needed stamps, a paced
rebuild, a savepoint fallback and a repair runner to stay usable. The records' key index already
answers the same read: an open seeks from one key to the next, taking each key's newest record
(deletions included) and never reading superseded revisions. A mixed chat still folds its frozen
input prefix first. A send now writes only its records, the epoch's coverage and its receipt, so
any failure among them refuses the send as main's row insert does.

The background runner keeps only the paced sweep of retired generations, its one remaining job.
The cache tables are no longer created; they never shipped.
…ecording it

Every write recorded the sequence scalar beside its own records, about half the records on
streamed paths. The epoch's coverage already holds it, so a read supplies it from there and a write
no longer stores it. Records an earlier build stored still decode.
…existing chat at N and 10N

Admission walks each input row it reads once (on top of main's parse), and each outcome record it
reads or writes once: the open of a mixed chat walks exactly its prefix rows and admits one record
per key, a catch-up page walks one row per input row it returns, and a write walks its row's
read-back and admits each record it inserts. Linear in what is read, with a constant of one.
…onger yields that key

A tail record with the prefix ordinal is the key's newest value. If a later
build's reducer reads the old rows differently and no longer produces that
key, the value is appended instead of refusing the whole chat as damaged;
only that key's place can change.
After a page of records the sweep went back to its start position, so every
later page rescanned every live chat's generation numbered below the retired
one. It now resumes at that generation; a contract at N and 10N live chats
pins that only a pass's first page walks them.
… already take

The sweep was wired through an optional parameter, so dropping it at the one
production caller would have left retired records forever with every test
passing. It now runs on the required journal database, and a wiring test
checks that installing starts it and stopping ends it.
…at database wrote are edited, sent to and rewound by this build as the newest release does

Each release writes a Claude and a Codex chat through its own writers. This
build opens it, edits a card the old rows hold (its first write: the marker
and an in-place update), sends, rewinds (every kept message and card saved
again through the strict encoder) and reopens, with every commit restoring
to the live chat. The result equals the newest release's after the same
steps. The oldest release is resolved from tags, as the window is.
…records, and the probe reads each step's result once
…nd on its own result

Comparing the carried chat with the newest release's would fail the required
cross-version check for any legitimate main change to those flows until the
next release ships. The probe still admits every released row, opens the chat
as the release and the newest release do, keeps the release's rows byte for
byte with one marker, and restores to live after every commit; after that it
checks the edited card, the accepted send and the rewind's survivors. The
oldest release with the per-host database is named directly: it never changes.
Six collections folded empty, so a change to how old rows derive their keys
went unnoticed there. Eight rows v1.4.245 wrote through its own journal (an
item with an execution owner, a declared echo, a removed turn, and a queued
card handed over with carried history, then cancelled in doubt) follow the
existing rows unchanged, and the test now requires every collection to be
non-empty.
…er it is frozen

The fold comment claimed an unheld prefix-ordinal value only moves that key;
a prefix read differently can also show a key twice or bring back one the
tail deleted. The marker version now states the rule: a build that reads old
rows into different keys or values keys that reading off a new marker
version, and duplication or resurrection is never intended.
…elds this build adds

The open check compared whole snapshots, so a field main starts setting would
fail the required cross-version job until a release ships it. It now compares
the release's items, sends and cards, in order and by value, allowing added
fields; the byte-identity and restore-equals-live checks are unchanged.
…thout parsing or walking it again or keeping its text
…batch's encode stays linear in its mutations
@brennanb2025 brennanb2025 changed the title fix(native-chat): save each chat's current state and reopen from it fix(native-chat): save each chat change as keyed records and reopen from the newest Oct 31, 2026
@brennanb2025
brennanb2025 merged commit 2cc33b8 into main Oct 31, 2026
64 checks passed
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