You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
fix(native-chat): save each chat change as keyed records and reopen from the newest - #36024
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.
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.
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.
[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]
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.
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: 4 · 1
Failed checks: 1 warning
Check name
Status
Explanation
Resolution
Docstring Coverage
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 checks: 4 passed
Check name
Status
Explanation
Linked Issues check
Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check
Check skipped because no linked issues were found for this pull request.
Description check
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
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.
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.
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 7 remain after this review.
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.
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 1 remain after this review.
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.
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:
Downgraded to main (refusal), then re-upgraded:
…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.
…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.
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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.
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.
Known limits.
Validation.