Skip to content

perf(native-chat): byte-cap the transcript read-cache to bound RSS (GB-scale leak) - #7625

Merged
nwparker merged 1 commit into
mainfrom
nwparker/leak-hunt-big
Jul 7, 2026
Merged

nwparker merged 1 commit into
mainfrom
nwparker/leak-hunt-big

Conversation

@nwparker

@nwparker nwparker commented Jul 7, 2026 •

Copy link
Copy Markdown
Contributor

Description

The process-global native-chat transcript read-cache (src/main/native-chat/transcript-read-cache.ts) was capped only by entry count (MAX_CACHE_ENTRIES = 50) — with no byte cap. Each cached entry is a full, unwindowed transcript parse:

  • readNativeChatTranscript applies no message cap (streams the entire JSONL session file).
  • toolResultOutput returns tool-result strings in full — whole file contents, command output, and diffs, which are the bulk of a real agent transcript.

Heavy Claude/Codex coding sessions are routinely 5–50 MB of JSONL on disk → 10–100 MB parsed in memory. So 50 entries could retain 0.5–several GB in the single process that now serves desktop + every paired web/mobile client. The file's own comment already flagged this:

"Entry-count cap is fine for v1; a byte-aware cap is the follow-up if profiling shows RSS pressure now that one process serves many remote clients."

Reached from both the desktop IPC handler (ipc/native-chat.ts) and the runtime RPC handler that serves every remote client (runtime/rpc/methods/native-chat.ts), and re-cached on every agent write during an active session (file mtime changes). No purge on session/pane/worktree removal — entries persist for the process lifetime, subject only to the 50-entry LRU.

Distinct from #7341, which fixed the cache key (resolved path vs agent:sessionId) — a correctness bug. The entry size dimension was never addressed.

Fix

Reuse the stat() already issued for the mtime check to also read .size (a cheap, monotonic proxy for the parsed footprint), and bound the cache by total cached file bytes (MAX_CACHE_BYTES = 128 MB) in addition to the count cap:

  • Evict oldest until under both caps…
  • …but always keep the most-recent entry (cache.size > 1), so a single active transcript larger than the whole budget is never re-parsed on every read.

Evidence (red → green)

New tests in transcript-read-cache.test.ts (with a test-only budget override so the byte-eviction path is exercised without 100 MB fixtures):

  • WITHOUT the byte condition: "evicts the oldest entry once total cached bytes exceed the budget" fails — the oldest entry stays cached (readSpy 3 ≠ 4). Leak reproduced.
  • WITH the fix: oldest large entries evict, the newest is always kept, and small entries under the default budget never evict (zero-regression for typical use). ✅

Verification:

  • transcript-read-cache.test.ts — 8 tests ✅ (5 original + 3 new)
  • ipc/native-chat.test.ts + runtime/rpc/methods/native-chat.test.ts — 18 total green ✅
  • oxlint clean, tsgo node typecheck clean ✅

ELI5

Orca keeps a shelf of the last 50 chat logs it read so it doesn't re-read them from disk. It counted logs, not their size — but a single AI coding log can be 100 MB. Fifty of those = a few GB just sitting on the shelf. Now it also watches the total size and clears out old big ones (always keeping the one you're currently looking at), so the shelf can't grow past ~128 MB.

Trade-offs / regression risk: near-zero

  • It's a read-through cache: an evicted entry is simply re-read from disk on next access — already the existing cache-miss path. No behavior or output change.
  • The only cost is extra re-parses if a user's simultaneously-hot transcripts exceed 128 MB — exactly the users currently at OOM risk. Typical use (transcripts far under budget) is unaffected, and the newest/active transcript is never evicted, so the common "keep re-reading the session I'm watching" path never re-parses.
  • 128 MB of file bytes ≈ 200–400 MB parsed worst case — a hard bound and ~10–25× lower than the previous several-GB ceiling.

Note

This is one of two massive-scale candidates found this pass. The other — an uncapped unsent PTY backlog (pendingData in main/ipc/pty.ts) — is under separate verification (its fix risks dropping terminal output, so reachability is being confirmed first) and will be a separate PR if it holds up.

Made with Orca 🐋

The process-global transcript read-cache (transcript-read-cache.ts) was
capped only by entry count (MAX_CACHE_ENTRIES = 50). Each entry is a
FULL, unwindowed transcript parse: readNativeChatTranscript applies no
message cap and tool-result strings (whole file contents, command
output, diffs) are kept in full. Heavy Claude/Codex sessions are
5-50 MB of JSONL -> 10-100 MB parsed, so 50 entries could retain
0.5-several GB in the one process that now serves desktop plus every
paired web/mobile client. The file's own comment flagged a byte-aware
cap as the follow-up.

Fix: reuse the stat() already issued for the mtime check to also read
.size (a cheap, monotonic proxy for the parsed footprint) and bound the
cache by total cached file bytes (MAX_CACHE_BYTES = 128 MB) in addition
to the count cap. Evict oldest until under budget, but always keep the
most-recent entry so a single active transcript larger than the whole
budget is never re-parsed on every read.

This is distinct from #7341, which fixed the cache KEY (resolved path
vs agent:sessionId); the entry SIZE dimension was untouched.

Zero behavior change: it's a read-through cache, so an evicted entry is
just re-read from disk on next access (already the cache-miss path). The
only cost is extra re-parses if a user's simultaneously-hot transcripts
exceed 128 MB - exactly the OOM-risk case this bounds; typical use is
unaffected.

Tests (red->green): without the byte condition the eviction test fails
(oldest entry stays cached); with it, oldest large entries evict, the
newest is always kept, and small entries under budget never evict.
@coderabbitai

coderabbitai Bot commented Jul 7, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The transcript cache used by readNativeChatTranscriptCached is extended to enforce a total cached-bytes budget in addition to the existing entry-count limit. CachedTranscript now stores on-disk bytes alongside result and mtimeMs. The file stat helper is updated to return both mtimeMs and bytes, with fallback values on failure. setCached evicts oldest entries until both entry-count and byte-budget constraints are satisfied, while preserving the most recently inserted entry. A new test-only export, setNativeChatTranscriptCacheMaxBytesForTests, allows overriding the byte budget. Corresponding tests validate eviction behavior, retention of oversized single entries, and non-eviction under default budgets.

Changes

Cohort / File(s) Summary
Byte-budget tracking (transcript-read-cache.ts) Adds bytes to cached entries, MAX_CACHE_BYTES/maxCacheBytes, byte-aware eviction in setCached, updated stat helper returning mtimeMs and bytes, and new test-only export setNativeChatTranscriptCacheMaxBytesForTests
Eviction test coverage (transcript-read-cache.test.ts) Adds seedBigFile helper, updates beforeEach to set test byte budget, and adds tests for eviction of oldest entries, retention of oversized single entries, and non-eviction of small entries

Sequence Diagram(s)

sequenceDiagram
  participant Caller
  participant readNativeChatTranscriptCached
  participant statHelper
  participant setCached

  Caller->>readNativeChatTranscriptCached: request transcript
  readNativeChatTranscriptCached->>statHelper: get mtimeMs and bytes
  statHelper-->>readNativeChatTranscriptCached: mtimeMs, bytes
  readNativeChatTranscriptCached->>setCached: store result, mtimeMs, bytes
  setCached->>setCached: evict oldest entries until maxCacheBytes and maxEntries satisfied
  setCached-->>readNativeChatTranscriptCached: cache updated
Loading

Related issues: None linked in the provided context.

Related PRs: None identified in the provided context.

Suggested labels: cache, testing

Suggested reviewers: None specified in the provided context.

Poem
A rabbit counts bytes, hop by hop,
When the cache grows big, old entries drop.
The newest stays snug, safe from the cull,
While big single files stay put, not pulled.
Tests seed and measure, byte by byte —
A tidy cache, evicted just right.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description explains the change well, but it omits required template sections like Summary, Screenshots, Testing, AI Review Report, Security Audit, and Notes. Add the required template headings and fill in Screenshots, Testing, AI Review Report, Security Audit, and Notes, or explicitly mark non-visual behavior as no visual change.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly states the native-chat transcript read-cache byte-cap change and matches the main fix.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch

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.

🧹 Nitpick comments (1)
src/main/native-chat/transcript-read-cache.ts (1)

35-42: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Trim the rationale comment to align with the comment-length guideline.

This 7-line block explains useful context, but as per path instructions, design-rationale comments should stay to "one or two lines, capturing only the non-obvious reason." Consider condensing to the core "why" (count cap alone let unbounded JSONL retain multi-GB memory; byte budget bounds it while keeping the most-recent entry).

As per path instructions for **/*.{ts,tsx,js,jsx}: "Keep comments short — one or two lines, capturing only the non-obvious reason."

Source: Path instructions


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: f29a6e90-1b75-4e49-a586-95b9c70ca2d7

📥 Commits

Reviewing files that changed from the base of the PR and between d84041c and 4646127.

📒 Files selected for processing (2)
  • src/main/native-chat/transcript-read-cache.test.ts
  • src/main/native-chat/transcript-read-cache.ts

@nwparker
nwparker merged commit 86f404e into main Jul 7, 2026
1 of 2 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
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