Repository navigation
perf(ai-vault): reuse and incrementally parse session transcripts across scans (STA-1278) - #7525
Conversation
…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]>
|
Note: the |
📝 WalkthroughWalkthroughThis PR adds session parse caching and resumable Claude transcript parsing. 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches📝 Generate docstrings
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. Comment |
There was a problem hiding this comment.
🧹 Nitpick comments (1)
src/main/ai-vault/session-scanner-scope-discovery.ts (1)
20-46: 🚀 Performance & Scalability | 🔵 TrivialUnresolved cwd lookups aren't cached, so unresolved project dirs get re-read every scan.
cachedProjectDirCwdonly stores an entry whenreadProjectDirCwdreturns a truthycwd(Line 35:if (cwd) { ... }). Project dirs whose transcripts haven't yet reported acwd(e.g., a brand-new session) will re-runreadProjectDirCwd→readFirstCwd(which streams up toREPRESENTATIVE_CWD_LINE_LIMITlines per file, acrossREPRESENTATIVE_FILE_LIMITfiles) 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
📒 Files selected for processing (7)
src/main/ai-vault/session-scanner-discovery.tssrc/main/ai-vault/session-scanner-parse-cache.test.tssrc/main/ai-vault/session-scanner-parse-cache.tssrc/main/ai-vault/session-scanner-primary-parsers.tssrc/main/ai-vault/session-scanner-scope-discovery.tssrc/main/ai-vault/session-scanner-types.tssrc/main/ai-vault/session-scanner.ts
|
Good find. we'll roll this out asap |
…oss scans (STA-1278) (stablyai#7525) Co-authored-by: Orca <[email protected]>
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:
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.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
parseSessionCandidateseam in the scanner (renderer cadence untouched):(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).\nbyte 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.projectDir → cwdresolution (which reads transcript heads) is stable per directory and now cached.aiVault.scantrace span withcandidates/reused/incremental/fullParses/bytesReadattributes, 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
scanAiVaultSessionsexactly as the renderer's forced 5s rescan does (limit: 500, real scope paths):Steady state drops from >100% of a core to ~4%.
Correctness (differential validation):
(filePath, mtime)).src/main/ai-vaultsuite: 17 files / 72 tests pass (pre-existing + new). Fullpnpm typecheckandoxlintclean.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:
\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 atendsWithNewlineAt.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.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.
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.
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
parseSessionCandidateseam makes extending incremental parsing to Codex a small change if it ever shows in a profile.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.
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.tspath, unaffected), mobile (aiVault.listSessionscontract byte-identical), and concurrent scans (states cloned before mutation — worst case duplicated work, never corruption).Notes
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; fullverifyCI green.review-coderounds: round 1 essentially clean (3 low residuals, addressed inaf41b17ff), round 2 fully clean.brennanb2025/1278), opened Agent Session History: 500 real sessions render with correct titles/previews/resume actions.demo-project, clicked Refresh Session History → row appears with correct ai-title, preview, and worktree actions.incremental=7, fullParses=1for the one new file) instead of re-parsing.aiVault.scanspans inmain.trace.ndjson: cold scan 12.8s / 731 parses / 1.05GB read; steady-state refresh 0.9s / 728 reused / 20KB read.remote-session-scanner.ts; theaiVault.listSessionsRPC 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).