Skip to content

Native chat: retire superseded saved revisions and reclaim space - #28958

Closed
brennanb2025 wants to merge 32 commits into
mainfrom
brennanb2025/nc-perf-prune
Closed

brennanb2025 wants to merge 32 commits into
mainfrom
brennanb2025/nc-perf-prune

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 3 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​814 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​814
Prod 8 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​833 $\color{#cf222e}{\Huge{\mathbf{−}}}$​26 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​807

ELI5

Long chats save complete copies of messages and tool results as they change. Redundant older copies accumulate on disk. This change removes redundant contents in small background steps and remembers completed cleanup across launches, while keeping the conversation, history and tabs unchanged.

What Changed

Cleanup keeps every saved row number, timestamp and identity, each item’s first and newest copy, and meaningful state changes. It validates each chat through a fixed stopping point before replacing redundant contents. Damaged or unsupported history is skipped independently. Cleanup and streamed text revisions share the host’s existing scoped transaction durability switch; ordinary message saves retain FULL durability, and transaction recovery restores it before reuse.

Only the cleanup position and proven pending work are saved. Per-item comparisons last for the current connection, and ordinary scan steps update only that temporary cache. Cleanup saves its position when it finds work, finishes the selected history, or advances about 4,096 rows. Removed or refused chats are cleared in bounded steps.

After a completed cleanup, a restart scans newly appended rows rather than the old history. Restarting during unfinished cleanup can repeat up to 4,127 rows since the latest surviving cleanup save; this is not a power-loss guarantee. Restart also forgets comparison candidates, so repeated restarts can leave some redundant copies indefinitely. Conversation content stays intact.

Why

The common pattern combines finite background work with an atomic saved position and pending work. In an earlier version of this PR, saving the whole comparison cache on every small scan step caused extra disk writes and pauses, and cleanup restarted from the beginning after each launch. Keeping that cache temporary removes those writes from ordinary steps, while sparse saved progress avoids starting over on every launch. There is no new setting, notice, network message or required client upgrade.

Intended differences from the common pattern: retain saved row envelopes for existing history readers; use file-backed temporary comparisons; keep ordinary message writes fully durable while optional cleanup uses the shared scoped durability switch. A restart forgets the temporary comparison list, so an item still being updated at restart can keep one redundant copy; content is never lost. Individual parsing, saves and filesystem reclamation can still pause the host.

Timing and storage

Brennan accepted the first-cleanup timing trade-off on October 16: on the same staged 246,284-row Windows journal, scan steps measured 3.2 milliseconds at the 99th percentile and 25 milliseconds at the maximum, versus 2.1 and 9.9 milliseconds for an earlier version of this PR that rescanned the whole journal at every launch. First cleanup took about 170 seconds, including the normal 30-second wait, versus 162 seconds. These are one observation on a shared machine, not a worst-case guarantee. No timing tuning followed that decision.

That run kept 98,402 temporary comparison entries using 7,868 logical 4-KiB pages (about 30.7 MiB), plus about 28 KiB for saved progress. The cache setting is not a total memory or disk limit, and temporary allocation can remain until the connection closes. Cleanup reduced the closed main database from 635,092,992 to 634,884,096 bytes in this mostly distinct-item workload. This is not a promise of immediate net savings while the temporary database and write-ahead log are allocated.

Linked Issue

Requested by @BrennanKB5 as part of the native-chat performance investigation.

Visual Proof

Full-window control, final-branch, post-cleanup, post-restart and follow-up screenshots are in the review status comment.

Testing

The accepted pre-integration head preserved transcript, saved row envelopes and row count on the staged journal; all maintenance commits used NORMAL with FULL restored, and all four foreground appends committed FULL. Focused Windows checks passed 96 cases in separate 8-case and 88-case runs. A fresh short Windows restart check on the accepted pre-integration head scanned four appended rows, parsed six rows including two compaction candidates, and retained all 246,288 row envelopes and the same transcript. Because the previous completed disposable database had been removed, this check first reconstructed it once from the staged test journal; that reconstruction observed a 60-millisecond maximum scan step on the shared machine, without further tuning or repetition. The fresh integration review passed the single transaction-switch mechanism and its merge resolutions. On the earlier reviewed head 58fcedd6e2148be44d776028d784c5f27b2686ac, the full PR workflow and its aggregate passed, including all five unit shards, static analysis and typecheck, packages, persistence on all three desktop platforms, changed Electron specs and cross-version checks; Mobile Checks passed too. On M4Air, that earlier head’s hidden Electron QA used the real signed-in Claude with plain Opus / High and the same fixture/prompt as main. The long streamed reply and real Read/Bash tools completed. Normal cleanup kept all 31 target rows while logical payload fell from 95,752 to 30,128 bytes; row identity, transcript, tools and status stayed unchanged. Same-profile restart preserved the exact rendered conversation, tabs and selection with zero maintenance scans or parses. A later prompt appended nine rows and scanned only those nine, preserving the completed prefix. Protected config hashes stayed equal and all owned QA processes exited.

On final head 05463dd354b0c92685f6e42de956f68f2a0c2c09, hidden M4Air Electron QA used real signed-in Claude with plain Opus / High and a fresh throwaway profile. A 1,663-word streamed reply with real Read/Bash tools completed. After the normal quiet delay, cleanup retained all 28 row envelopes while logical payload shrank from 85,122 to 28,023 bytes; the exact rendered text, latest saved contents and tools stayed unchanged. A same-profile restart preserved content, completed status, tabs and selection, with zero maintenance scans, parses or compactions. A read-only table listing confirmed journal_prune_items_v1 is absent. Protected configuration hashes stayed equal and all owned QA processes exited. This is final-head local macOS evidence; the earlier Windows timing decision is unchanged. The full PR workflow and aggregate, Mobile Checks and desktop persistence passed on this exact head. An unchanged Windows hook-stdin test timed out once and passed in 6.2 seconds on one failed-job rerun; no source or timeout was changed.

Review

Prior source reviews checked restart and rollback boundaries, preservation of history, damaged-chat isolation, finite work and fairness, Windows and remote ownership, and compatibility with older readers. Fresh narrow reviews passed the final merge, shared durability switch, timer correction and final removal of the unused saved comparison table. The removal review confirmed healthy progress retention, bounded temporary/work cleanup, retained current refusals and meaningful remaining test coverage. Final-head compiler and all five unit shards passed after restoring the existing global timer runtime.

Agent skill upstream boundary

  • Not applicable; no skill-installer source is copied.

QA limits

The rendered run covers local macOS. Final CI covers the desktop persistence platforms; the large Windows restart experiment used the accepted pre-integration head. A separate folder-workspace smoke was not run, and the setup-only creation path suppressed the configured default tabs on both main and branch, so that tab-launch path was not fully exercised. Existing notification-permission and session-search prompts appeared; their relevant source is unchanged from control, and the direct OS notification result was not captured. Final QA also observed the existing session-search notice, collapsed tool disclosures before normal expansion and the Onboarding checklist sidebar row disappearing after restart, with its cause unproven. Screenshot and DOM samples cannot rule out a one-frame flash.

Checklist

  • Focused on saved chat cleanup and restart progress.
  • Before/after, mechanism and alternatives explained.
  • Real signed-in rendered QA and before/after screenshots attached in the status comment.
  • Correctness, security, performance and compatibility reviewed.
  • Windows, macOS, Linux, SSH ownership and folder workspace impact considered; runtime limits stated above.
  • Full PR workflow and Mobile Checks pass on the final head.

@brennanb2025

brennanb2025 commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor Author

Long chats accumulate complete older copies of messages and tool results as they stream. Those redundant contents waste storage; an earlier version of this PR also reread the entire journal after every launch, repeating completed cleanup.

This PR removes redundant contents in small background steps and keeps completed cleanup progress across restarts. Conversation text, tools, history, saved row positions and tabs stay intact. Streamed writes and optional cleanup reuse one host-owned durability switch and its existing recovery path; ordinary message saves remain FULL.

The review loop and fresh narrow review are complete on 05463dd354b0c92685f6e42de956f68f2a0c2c09. The latest change removes an unused saved comparison table that existed only in unshipped iterations. The fresh review verified healthy chats keep their progress and work, refused or retired chats drain bounded temporary/work rows, current refusals remain saved, and the remaining tests still cover these contracts. Optional test-variable naming cleanup is deferred; no production correction or new test was needed.

The full PR workflow and its PR checks passed aggregate passed on this exact head, including all five unit shards, static analysis/typecheck, packages, WSL, changed Electron specs and cross-version checks. Mobile Checks and desktop persistence passed. The Windows hook-stdin test timed out once in unchanged code, then passed in 6.2 seconds on one failed-job retry; no timeout or source was changed.

On final head 05463dd354b0c92685f6e42de956f68f2a0c2c09, hidden M4Air Electron QA used real signed-in Claude with plain Opus / High and a fresh throwaway profile. A 1,663-word streamed reply with real Read/Bash tools completed. After the normal quiet delay, cleanup retained all 28 row envelopes while logical payload shrank from 85,122 to 28,023 bytes; the exact rendered text, latest saved contents and tools stayed unchanged. A same-profile restart preserved content, completed status, tabs and selection, with zero maintenance scans, parses or compactions. A read-only table listing confirmed journal_prune_items_v1 is absent. Protected configuration hashes stayed equal and all owned QA processes exited. This is final-head local macOS evidence; the earlier Windows timing decision is unchanged.

Brennan accepted the first-cleanup timing trade-off on October 16: on the staged 246,284-row Windows journal, scan steps measured 3.2 milliseconds at the 99th percentile and 25 milliseconds maximum, versus 2.1 and 9.9 milliseconds for the earlier version that rescanned at every launch. No tuning followed. First cleanup took about 170 seconds including the 30-second wait, versus 162 seconds. These are shared-machine samples, not worst-case guarantees. Temporary comparison storage measured about 30.7 MiB, plus about 28 KiB of saved progress; temporary allocation and the write-ahead log can outweigh immediate physical savings. The mostly distinct-item database shrank from 635,092,992 to 634,884,096 bytes after closure.

Intended differences from the common pattern: preserve saved row envelopes for existing readers, keep comparisons in file-backed temporary storage, and retain FULL for ordinary acknowledged writes while streamed revisions and optional cleanup share scoped NORMAL. A restart forgets the temporary comparison list, so an item still being updated at restart can keep one redundant copy; content is never lost. Repeated restarts can leave optional redundant copies indefinitely.

Earlier-head Windows restart evidence is separate: four appended rows scanned, six parses including two compaction candidates, two copies compacted, and all 246,288 saved row envelopes plus transcript preserved. The previous completed disposable database had been removed, so the check first reconstructed it once; that reconstruction observed a 60-millisecond maximum on the shared machine. This is not final-head Windows Electron evidence.

Deferred and unverified: no separate non-git folder smoke, no final-head Windows rendered run and no full default-tab launch coverage (setup-only creation suppressed configured Workspace/Notes tabs on both earlier arms). Final QA also observed the existing session-search notice after restart, collapsed tool disclosures before normal expansion and an absent Onboarding checklist sidebar row whose cause was not established. Earlier QA observed notification-permission and session-search prompts; relevant source matched control, but the direct OS notification result was not captured. Screenshots and DOM samples cannot rule out a one-frame flash. Existing deleted-chat row retention and the previously disclosed post-commit restoration concern remain outside this delta. Corrected earlier harness launch/config attempts and an own-driver overlap were disclosed in the private report. The Windows re-finish preflight could not provide an isolated driver, so it ended before any build or app launch; no credentials were copied and no sign-in was performed.

For Brennan's review:

Final 05463dd: streaming, completed real tools and post-cleanup reply end

11-streaming-response.jpg

13-completed-tools-first.jpg

15-post-cleanup-end.jpg

Final 05463dd same-profile restart: observed search notice, preserved reply end and restored real tools

16-postrestart-initial.jpg

17-postrestart-end.jpg

18-postrestart-expanded-tools-first.jpg

Earlier control-versus-58fcedd evidence remains below, labelled by its actual head:

Main: streaming and completed tools/end

01-control-streaming.png

02-control-completed-tools.png

03-control-completed-end.png

Earlier 58fcedd branch: streaming and completed tools/end, including observed notification notice

04-final-streaming.png

05-final-completed-tools.png

06-final-completed-end-notification.png

Earlier 58fcedd branch after natural cleanup: tools and reply end

07-final-post-cleanup-tools.png

08-final-post-cleanup-end.png

Earlier 58fcedd same-profile restart: preserved tools/end and observed search tip

09-final-post-restart-tools.png

10-final-post-restart-end.png

11-final-restart-search-tip.png

Earlier 58fcedd later real reply after restart

12-final-followup-done.png

Human judgment points:

@brennanb2025
brennanb2025 marked this pull request as ready for review October 16, 2026 01:11
@coderabbitai

coderabbitai Bot commented Oct 16, 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
  • Configuration used: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 6cd036c5-d054-4413-9d22-e6a91334494a
📥 Commits

Reviewing files that changed from the base of the PR and between f35fb59 and 02a3dc1.

📒 Files selected for processing: 3
  • src/main/native-chat/agent-session-journal/journal-prune-pass.ts
  • src/main/native-chat/agent-session-journal/journal-prune-progress.test.ts
  • src/main/native-chat/agent-session-journal/journal-prune-state.ts

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

📝 Walkthrough

The change adds persistent SQLite state and a policy for identifying repeated journal item revisions. Bounded prune passes validate journal rows and compact eligible payloads while preserving row keys and timestamps. Database opening reports whether maintenance is enabled. Host databases connect journal writes and transactions to scheduled pruning and incremental vacuuming.

Priority: ⬇️ Low

Merge Risk: ⚪ Minimal · up to 02a3d

No actionable issue remains identified for this change. Normal validation can precede merge; production-scale cleanup time remains unmeasured.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 18.18% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 22 functions across 11 files. 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.
Title check Passed The title clearly and concisely describes the primary change: retiring superseded native-chat journal revisions and reclaiming storage.
Description check Passed The description is detailed and covers the required explanation, changes, rationale, testing, visual proof, review notes, risks, and checklist. The Linked Issue section identifies the requesting party…
Full details: Description check

Explanation

The description is detailed and covers the required explanation, changes, rationale, testing, visual proof, review notes, risks, and checklist. The Linked Issue section identifies the requesting party but does not provide an actual issue link or Fixes reference.

  • Fix all pre-merge checks with AI
✨ Finishing Touches: 💡 2
📝 Generate docstrings: 💡
  • Commit to this branch
  • Create a new PR
⚔️ Resolve merge conflicts: 💡
  • Resolve merge conflict in branch brennanb2025/nc-perf-prune
  • 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

Comment @coderabbitai help to get the list of available commands.

@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


ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: e195b879-b973-4332-9213-76418a2adc2f
📥 Commits

Reviewing files that changed from the base of the PR and between 2c100ef and a75e118.

📒 Files selected for processing: 10
  • src/main/native-chat/agent-session-journal/journal-database.ts
  • src/main/native-chat/agent-session-journal/journal-host-database.spec.ts
  • src/main/native-chat/agent-session-journal/journal-host-database.ts
  • src/main/native-chat/agent-session-journal/journal-maintenance.ts
  • src/main/native-chat/agent-session-journal/journal-prune-pass.ts
  • src/main/native-chat/agent-session-journal/journal-prune-policy.ts
  • src/main/native-chat/agent-session-journal/journal-prune-progress.test.ts
  • src/main/native-chat/agent-session-journal/journal-prune-state.ts
  • src/main/native-chat/agent-session-journal/journal-pruning.test.ts
  • src/main/native-chat/agent-session-journal/journal-row-writer.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.

@brennanb2025
brennanb2025 marked this pull request as draft October 16, 2026 17:59
Cleanup progress lived in per-connection TEMP tables, so every launch re-read and re-parsed every saved row of every chat. Frontiers, candidates and queued payloads are now saved tables (no user_version bump), owed work is derived from the live epoch's newest row versus the saved frontier, and each slice commits its frontier with its work. A restart reads only rows appended since the last pass.
@brennanb2025
brennanb2025 marked this pull request as ready for review October 16, 2026 20:02

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

Caution

Some comments are outside the diff and can’t be posted inline due to GitHub limitations.

⚠️ Outside diff range comments (1)

🟡 Minor · Treat malformed saved prune state as a per-epoch refusal. · journal-maintenance.ts:101-128

src/main/native-chat/agent-session-journal/journal-maintenance.ts:101-128
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Treat malformed saved prune state as a per-epoch refusal.

For an owed epoch, JournalPrunePass.step() reads the saved progress, and JournalPrunePolicy.observe() reads saved candidates. Both validation failures throw plain Error values. JournalMaintenance.step() catches only JournalPruneRefusal, so the error reaches stop() and closes the shared scheduler. One damaged session can therefore prevent maintenance for healthy sessions until the scheduler is recreated. Throw JournalPruneRefusal for these validation failures so the existing isolation path marks only the damaged epoch as refused.

Suggested fix
-      throw new Error('journal pruning lost its saved frontier')
+      throw new JournalPruneRefusal('journal pruning lost its saved frontier')
...
-      throw new Error('journal pruning lost its saved item frontier')
+      throw new JournalPruneRefusal('journal pruning lost its saved item frontier')

ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 73ca0810-6cdf-4bcc-883b-f2f050df4f76
📥 Commits

Reviewing files that changed from the base of the PR and between a75e118 and 741f25d.

📒 Files selected for processing: 6
  • src/main/native-chat/agent-session-journal/journal-database.ts
  • src/main/native-chat/agent-session-journal/journal-host-database.spec.ts
  • src/main/native-chat/agent-session-journal/journal-maintenance.ts
  • src/main/native-chat/agent-session-journal/journal-prune-pass.ts
  • src/main/native-chat/agent-session-journal/journal-prune-progress.test.ts
  • src/main/native-chat/agent-session-journal/journal-prune-state.ts
💤 Files with no reviewable changes: 1
  • src/main/native-chat/agent-session-journal/journal-host-database.spec.ts

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

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Closing unmerged. The shared text pieces change (#29132) renames the saved-rows table this cleanup reads, so it would stop working, and it would free much less space once that lands: later copies keep the shared text. Measured on a real profile, it saved about 11–20% of disk and about 5 ms per large chat when opening it, with no memory benefit, in exchange for background work on the main process and new saved tables. Saving fewer repeated copies when replies are written (#29132, #28984) replaces it.

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