Skip to content

perf(ai-vault): reuse and incrementally parse session transcripts across scans (STA-1278) - #7525

Merged
brennanb2025 merged 3 commits into
mainfrom
brennanb2025/1278
Jul 6, 2026
Merged

brennanb2025 merged 3 commits into
mainfrom
brennanb2025/1278

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Jul 6, 2026 •

Copy link
Copy Markdown
Contributor

Problem

STA-1278: customer (M1 Pro) reports loading-screen freezes while Orca pegs ~100% of one core. Video evidence shows the main process at 100.0% while the renderer isn't even in the top-process list.

Root cause — a forced-rescan loop whose per-iteration cost exceeds its interval:

  1. The AI Vault renderer hook (ai-vault-session-refresh.ts) forces a cache-bypassing rescan whenever a new agent provider-session id appears, throttled to one per 5s. A multi-agent workflow (the reporter was running a 22-agent workflow) mints session ids continuously → a forced scan every 5s, indefinitely. Window refocus and panel mounts force scans too.
  2. Each scan (scanAiVaultSessions) re-read and re-JSON.parsed every line of every candidate file — the ~500 newest transcripts plus up to 2000 in-scope ones — with no per-file reuse, all on the main process thread.

Measured on a real corpus (1.3GB Claude + 2.3GB Codex, 1087 sessions): ~8.5s CPU (~10s wall) per scan. That's more than the 5s rescan interval, so the main process re-runs the scan back-to-back forever → one core pegged, IPC starved, UI stuck on loading states. Repeat scans cost exactly the same as the first — zero reuse.

Fix

All at the parseSessionCandidate seam in the scanner (renderer cadence untouched):

  • Per-file session reuse for all agents, keyed on (mtimeMs, sizeBytes) — unchanged files pay only stat cost per scan. Same pattern the claude-usage scanner already uses. LRU-bounded (4096 entries; previews are capped at 220 chars so worst case is ~16MB).
  • Incremental append-parse for Claude transcripts (the dominant, largest, actively-written files): the parser state is now resumable, and a byte-accurate line reader continues from the byte just past the last complete line when a file only grew. Guards: size < resume point (truncation) or a non-\n byte at the resume point (rewrite) ⇒ full re-parse. A trailing unterminated line (mid-write) is included in the visible session but kept out of the resume state, so it's re-read once complete — parity with the old streaming parser, no double-counting.
  • Scope-discovery cwd cache: projectDir → cwd resolution (which reads transcript heads) is stable per directory and now cached.
  • Diagnostics (STA-1278 acceptance criterion): scans are wrapped in an aiVault.scan trace span with candidates / reused / incremental / fullParses / bytesRead attributes, so support can attribute scan CPU from the local trace file during a freeze — the previous investigation found the trace file blind to this subsystem.

Evidence

Benchmark driving scanAiVaultSessions exactly as the renderer's forced 5s rescan does (limit: 500, real scope paths):

Scan Before (user CPU) After (user CPU)
Real corpus (3.6GB, 1087 sessions), cold scan ~6,000ms ~7,600ms (unchanged, expected)
Real corpus, repeat scan ~6,000ms ~210ms (28×)
Synthetic corpus, repeat scan while 12 hot transcripts keep growing ~1,700ms ~20ms (85×)

Steady state drops from >100% of a core to ~4%.

Correctness (differential validation):

  • Real corpus: after populating the cache, a rescan's output was deep-equal to a cold parse for all 1087 sessions (compared per (filePath, mtime)).
  • Unit tests cover: unchanged-file reuse, incremental append ≡ cold parse (titles/tokens/previews/counts), trailing-unterminated-line handling, truncation fallback, grown-rewrite detection via the resume-point newline guard, CRLF transcripts, and non-Claude reuse.

src/main/ai-vault suite: 17 files / 72 tests pass (pre-existing + new). Full pnpm typecheck and oxlint clean.

Trade-offs and accepted risks

All deliberate. Items 1, 2, and 5 are new with this PR; items 3, 4, and 6 are pre-existing costs this PR shrinks or leaves unchanged. Each lists the concrete bad thing a user could see, then how much it matters:

  1. Stale row on in-place transcript edits (introduced by this PR — the one real new correctness trade-off; previously every scan re-read from disk, so edits always showed within one rescan). Incremental resume assumes transcripts are append-only. Truncation and most rewrites fall back to a full parse (size-shrank guard + the byte before the resume point must be \n), but an in-place rewrite to an equal-or-larger size with a newline landing exactly at the old resume offset would resume from stale state. Documented in code at endsWithNewlineAt.
    What a user would see: one session row in Agent Session History with an outdated or garbled title/message-count/preview. Resume still works (command is id/cwd-based); no data loss, no crash. Self-heals on app restart or the next time the file shrinks.
    How much it matters: low. Requires a hand-edited .jsonl (Claude Code only ever appends, including compaction) and lucky byte alignment — I could not construct a realistic workflow that hits it.
  2. Memory held by the cache (introduced by this PR — scans previously retained nothing between runs). Up to 4096 LRU entries retained in the main process with no TTL (capped previews, titles, scalars, Claude resume state).
    What a user would see: nothing — at most a few extra MB on the Orca main process in Activity Monitor.
    How much it matters: very low — measured, not estimated. Fully populated from the real 3.6GB corpus (1,087 sessions + resume states) the cache retains 4.4MB of heap (theoretical cap ~10–16MB at 4096 entries). Entry size cannot scale with transcript size: every content-derived string is length-capped upstream (titles ≤96 chars, previews ≤220×5); the only uncapped fields are path-scale strings (cwd/branch/model/filePath) that pre-PR already sat in the 15s IPC result cache. GC pressure drops (unchanged files no longer allocate transient parse objects), and the trade buys back ~6s of main-thread CPU per rescan.
  3. Cold scan is unchanged (pre-existing — byte-for-byte the old behavior, now paid once per launch instead of every 5s). First panel open still reads everything (~1.05GB / ~13s wall on the test corpus, async-batched).
    What a user would see: on a very large history, the first "Scanning sessions" after app launch takes ~10s+ and Orca's main process briefly runs hot — exactly like today, but once per launch instead of every 5 seconds.
    How much it matters: moderate as a remaining cost, zero as a regression. Worth a follow-up (persist the cache or scan in a worker thread) only if freeze reports continue after this lands.
  4. Non-Claude hot files still full-re-parse on change (pre-existing and strictly improved — before, ALL files re-parsed every scan; this is the residual not finished, not a new cost). Codex etc. get unchanged-file reuse only.
    What a user would see: with a very large actively running Codex session and the panel open, a little background CPU every rescan (~0.5s per rescan in the worst ~100MB-rollout case). No freeze — it's one file, not the corpus.
    How much it matters: low today. The parseSessionCandidate seam makes extending incremental parsing to Codex a small change if it ever shows in a profile.
  5. Latent invariant for future code (introduced by this PR — fresh objects per scan previously made mutation harmless). Cached sessions are returned by reference across scans; future main-process code mutating a returned session in place would corrupt the cache.
    What a user would see: nothing today. If a future change violated it: subtly wrong session rows (wrong titles/previews) that persist until restart.
    How much it matters: low now, real for maintainers. All current consumers verified read-only; IPC structured-clones before the renderer. Caught by differential-style tests, not the type system.
  6. Residual steady-state cost (pre-existing — discovery statted the same files before; the PR removed the parse cost on top of it). Forced rescans still stat/readdir ~4,000 candidate files every 5s while agents are active.
    What a user would see: ~4% main-process CPU and ~1s of background I/O per rescan while the panel is open during agent activity — imperceptible on an SSD; on a network-mounted ~/.claude, panel refreshes could feel slower.
    How much it matters: very low on typical setups. Only becomes the next bottleneck at ~50k+ transcripts or network filesystems; discovery caching is the obvious next step there.

Explicitly not concerns: mtime-granularity collisions (size is compared too; matches the accepted claude-usage scanner pattern), deleted files (drop out of discovery, never served stale), SSH/remote (separate remote-session-scanner.ts path, unaffected), mobile (aiVault.listSessions contract byte-identical), and concurrent scans (states cloned before mutation — worst case duplicated work, never corruption).

Notes

  • This is the main-process peg under the STA-1278 umbrella. The separate renderer-process peg (WebGL atlas recovery over-firing) is tracked as STA-1365 with its own fix.

STA-1278

Made with Orca 🐋

Tests

Validation run (brennan-test-changes, macOS, real 3.6GB corpus):

  • pnpm typecheck, oxlint (0 errors), git diff --check, 84 focused vitest tests (ai-vault main + ipc + renderer refresh hook) pass; full verify CI green.
  • Two independent Opus 4.8 review-code rounds: round 1 essentially clean (3 low residuals, addressed in af41b17ff), round 2 fully clean.
  • Launched the exact PR worktree in Electron (identity verified: brennanb2025/1278), opened Agent Session History: 500 real sessions render with correct titles/previews/resume actions.
  • New-session detection: created a Claude transcript for demo-project, clicked Refresh Session History → row appears with correct ai-title, preview, and worktree actions.
  • Incremental path live: appended records + revised ai-title to that transcript → refresh → row shows updated title/preview; trace span confirms it resumed (incremental=7, fullParses=1 for the one new file) instead of re-parsing.
  • aiVault.scan spans in main.trace.ndjson: cold scan 12.8s / 731 parses / 1.05GB read; steady-state refresh 0.9s / 728 reused / 20KB read.
  • Perf no-regression: main process peaked at 4.1% CPU during forced rescans (this bug previously pegged ~100% of a core); renderer console 0 errors.
  • Cleanup: synthetic transcript removed, dev instance stopped, worktree clean.
  • SSH/mobile live passes not run — justified out of scope: SSH uses the untouched remote-session-scanner.ts; the aiVault.listSessions RPC contract/shape is unchanged (1087-session deep-equal differential).

Verdict: land — no regressions found; remaining risk is limited to the documented append-only rewrite heuristic (stale vault row in a scenario Claude transcripts don't produce).

…oss scans

The AI Vault renderer forces a cache-bypassing rescan every ~5s while new
agent session ids appear (multi-agent workflows mint them continuously), and
every scan re-read and re-JSON.parsed every line of ~500 newest plus up to
2000 in-scope transcripts with no per-file reuse. On a real 1.3GB Claude +
2.3GB Codex corpus each scan cost ~8.5s CPU — more than the 5s rescan
interval — so the main process pegged one core indefinitely and the UI sat
on loading states (STA-1278).

Fix, at the parseSessionCandidate seam:
- (mtime,size)-keyed per-file session reuse for all agents: unchanged files
  now pay only stat cost per scan (same pattern as the claude-usage scanner).
- Incremental append-parse for Claude transcripts: resumable parser state
  plus a byte-accurate line reader continue from the last consumed byte when
  a file only grew, with truncation and rewrite (resume-point newline)
  guards falling back to a full parse. A trailing unterminated line stays
  visible but outside the resume state so it is re-read once complete.
- Cache the scope-discovery projectDir->cwd resolution (stable per dir).
- Wrap scans in an aiVault.scan trace span (candidates/reused/incremental/
  fullParses/bytesRead) so support can attribute scan CPU during freezes.

Real-corpus rescans drop from ~6.0s to ~0.2s user CPU (28x); synthetic
rescans with 12 growing hot transcripts drop from ~1.7s to ~20ms (85x).
Differential validation: cached rescan output deep-equals a cold parse for
all 1087 real sessions on the test machine.

STA-1278

Co-authored-by: Orca <[email protected]>
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Note: the verify failure is not from this diff — main enabled unicorn/prefer-array-find (#7516) which trips on src/shared/linear-inline-media.ts from #7484 (crossed PRs), breaking lint on every PR's merge ref. #7523 fixes it; once that merges I'll push this branch rebased on main to re-run a clean verify. Locally on the rebased merge tree: oxlint clean apart from that one unrelated error, full typecheck clean, all 23 scanner-adjacent test files (188 tests) pass.

@coderabbitai

coderabbitai Bot commented Jul 6, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR adds session parse caching and resumable Claude transcript parsing. FileWithMtime now carries optional sizeBytes, populated during discovery and scope discovery. Claude parsing was refactored into reusable state helpers, enabling incremental resume from cached offsets with byte-accurate JSONL scanning. The scanner now uses cached parsing with shared stats and tracing, while scope discovery caches project cwd lookups. Tests cover reuse, incremental updates, fallback paths, CRLF handling, and non-Claude caching.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description is detailed, but it doesn't follow the required template and omits the AI Review Report and Security Audit sections. Reformat it to the repo template, adding Summary, Screenshots, Testing checklist, AI Review Report with cross-platform checks, Security Audit, and Notes.
✅ Passed checks (4 passed)
Check name Status Explanation
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.
Title check ✅ Passed The title is concise and accurately summarizes the main change: session transcript parsing reuse and incremental parsing.
✨ 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/ai-vault/session-scanner-scope-discovery.ts (1)

20-46: 🚀 Performance & Scalability | 🔵 Trivial

Unresolved cwd lookups aren't cached, so unresolved project dirs get re-read every scan.

cachedProjectDirCwd only stores an entry when readProjectDirCwd returns a truthy cwd (Line 35: if (cwd) { ... }). Project dirs whose transcripts haven't yet reported a cwd (e.g., a brand-new session) will re-run readProjectDirCwd → readFirstCwd (which streams up to REPRESENTATIVE_CWD_LINE_LIMIT lines per file, across REPRESENTATIVE_FILE_LIMIT files) on every 5-second scan until it resolves. Given this PR's goal is eliminating repeated re-reads driving the CPU peg, this negative-case gap could keep some of that cost alive for newly-created sessions.

Consider caching a "pending/unresolved" sentinel with a short TTL or retry-count backoff so repeated failures don't re-trigger full file reads every cycle.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 5f1fe321-78c2-4be0-b6bb-34e80e84e6c0

📥 Commits

Reviewing files that changed from the base of the PR and between 3dd3cc9 and a5789ac.

📒 Files selected for processing (7)
  • src/main/ai-vault/session-scanner-discovery.ts
  • src/main/ai-vault/session-scanner-parse-cache.test.ts
  • src/main/ai-vault/session-scanner-parse-cache.ts
  • src/main/ai-vault/session-scanner-primary-parsers.ts
  • src/main/ai-vault/session-scanner-scope-discovery.ts
  • src/main/ai-vault/session-scanner-types.ts
  • src/main/ai-vault/session-scanner.ts

@AmethystLiang

Copy link
Copy Markdown
Contributor

Good find. we'll roll this out asap

@brennanb2025
brennanb2025 merged commit 34a2549 into main Jul 6, 2026
1 check passed
@brennanb2025
brennanb2025 deleted the brennanb2025/1278 branch July 6, 2026 18:09
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.

2 participants