Repository navigation
Keep Agent Session History from freezing the app on huge OpenCode databases - #8924
Conversation
…ode databases (#8864) Opening or refreshing Agent Session History froze the entire app when OpenCode's opencode.db had grown to multiple GB (reporter: 29 GB with 20+ live opencode writers). All OpenCode SQLite reads ran synchronously (node:sqlite DatabaseSync) on the Electron main-process event loop, the discovery query evaluated a COUNT+json_extract subquery for every session before LIMIT, and the preview query JSON-parsed every part blob of each session. Live writers bump session.time_updated continuously, so the mtime parse cache missed every 15s/focus/manual refresh and the multi-tens-of-seconds freeze repeated forever. Fix: - Run OpenCode SQLite discovery and per-session parsing on a persistent worker thread (lazy spawn, unref'd, idle teardown, FIFO dispatch, per-call timeouts, crash-loop cap). Faults surface as per-source scan issues instead of stalls; other providers' results always arrive. - Fall back to the in-process reader when no worker bundle exists, surfacing a degraded-mode scan issue so a persistent fallback cannot silently reintroduce the hang. - Bound the queries: sort+LIMIT sessions before computing message counts, and source previews from the newest 100 messages via the (session_id, time_created, id) index instead of scanning every part. Measured on a 22 GB synthetic DB matching the reporter's shape: main- process IPC RTT during a fully cache-invalidated scan went from a 32.8 s continuous block (UI click timeout) to 1 ms max, with the panel populating normally (previews and message counts intact).
|
Before/after evidence (22 GB synthetic Before (panel Refresh on this branch's base): main process blocked 32,784 ms continuously — 33 consecutive pings queued >1 s, and the Playwright click on the refresh button itself timed out at 30 s. Every 15 s-TTL/focus refresh repeats this while live opencode writers keep invalidating the parse cache → the reported "hangs forever". After (same rig, same forced full re-parse): max ping RTT 1 ms, 0 pings >100 ms; the full scan runs ~10.8 s entirely on the worker; the panel populates with 368–386 OpenCode sessions including previews and message counts; zero scan issues (proves the worker served the scan — a fallback-to-inline regression would surface a degraded-mode issue and pre-fix RTTs). |
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (4)
🚧 Files skipped from review as they are similar to previous changes (2)
📝 WalkthroughWalkthroughOpenCode SQLite discovery and parsing now run through a dedicated worker entrypoint and shared worker client, without synchronous inline SQLite fallback. SQLite listing uses a separate Electron-free module with bounded queries, candidate deduplication, recency ordering, and issue collection. Preview extraction scans only the newest 100 messages while preserving full message counts. Worker lifecycle behavior includes FIFO dispatch, timeouts, crash recovery, idle teardown, and bundled-entry resolution. New tests cover database bounds and worker lifecycle behavior. 🚥 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.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: a9c0b8ba-7ca2-4416-a87a-26182996ad28
📒 Files selected for processing (11)
electron.vite.config.tssrc/main/ai-vault/session-scanner-agent-parser.tssrc/main/ai-vault/session-scanner-opencode-sqlite-bounds.test.tssrc/main/ai-vault/session-scanner-opencode-sqlite-discovery.tssrc/main/ai-vault/session-scanner-opencode-sqlite-list.tssrc/main/ai-vault/session-scanner-opencode-sqlite-worker-client.test.tssrc/main/ai-vault/session-scanner-opencode-sqlite-worker-client.tssrc/main/ai-vault/session-scanner-opencode-sqlite-worker-entry.tssrc/main/ai-vault/session-scanner-opencode-sqlite-worker-protocol.tssrc/main/ai-vault/session-scanner-opencode-sqlite-worker-spawn.tssrc/main/ai-vault/session-scanner-opencode-sqlite.ts
…and document worker-client exports A worker that exits cleanly on its own left this.worker pointing at the dead thread; the next request would post into it and stall to its timeout instead of respawning. Clean idle exits now drop the handle without counting as a death. Also adds JSDoc to the new exported scan-worker surfaces.
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: b7ca08d5-b135-4a93-9523-6efa25c6c4a8
📒 Files selected for processing (6)
src/main/ai-vault/session-scanner-opencode-sqlite-bounds.test.tssrc/main/ai-vault/session-scanner-opencode-sqlite-coexistence.test.tssrc/main/ai-vault/session-scanner-opencode-sqlite-list.tssrc/main/ai-vault/session-scanner-opencode-sqlite-worker-client.test.tssrc/main/ai-vault/session-scanner-opencode-sqlite-worker-client.tssrc/main/ai-vault/session-scanner-opencode-sqlite-worker-spawn.ts
🚧 Files skipped from review as they are similar to previous changes (2)
- src/main/ai-vault/session-scanner-opencode-sqlite-bounds.test.ts
- src/main/ai-vault/session-scanner-opencode-sqlite-worker-spawn.ts
…abases (stablyai#8924) * fix(agent-history): keep the app responsive while scanning huge OpenCode databases (stablyai#8864) Opening or refreshing Agent Session History froze the entire app when OpenCode's opencode.db had grown to multiple GB (reporter: 29 GB with 20+ live opencode writers). All OpenCode SQLite reads ran synchronously (node:sqlite DatabaseSync) on the Electron main-process event loop, the discovery query evaluated a COUNT+json_extract subquery for every session before LIMIT, and the preview query JSON-parsed every part blob of each session. Live writers bump session.time_updated continuously, so the mtime parse cache missed every 15s/focus/manual refresh and the multi-tens-of-seconds freeze repeated forever. Fix: - Run OpenCode SQLite discovery and per-session parsing on a persistent worker thread (lazy spawn, unref'd, idle teardown, FIFO dispatch, per-call timeouts, crash-loop cap). Faults surface as per-source scan issues instead of stalls; other providers' results always arrive. - Fall back to the in-process reader when no worker bundle exists, surfacing a degraded-mode scan issue so a persistent fallback cannot silently reintroduce the hang. - Bound the queries: sort+LIMIT sessions before computing message counts, and source previews from the newest 100 messages via the (session_id, time_created, id) index instead of scanning every part. Measured on a 22 GB synthetic DB matching the reporter's shape: main- process IPC RTT during a fully cache-invalidated scan went from a 32.8 s continuous block (UI click timeout) to 1 ms max, with the panel populating normally (previews and message counts intact). * fix(agent-history): drop the cached worker handle after a clean exit and document worker-client exports A worker that exits cleanly on its own left this.worker pointing at the dead thread; the next request would post into it and stall to its timeout instead of respawning. Clean idle exits now drop the handle without counting as a death. Also adds JSDoc to the new exported scan-worker surfaces. * fix(agent-history): keep OpenCode scans off the main thread * fix(agent-history): align OpenCode recency ordering
Summary
Fixes #8864. Opening or refreshing the Agent Session History panel no longer freezes the whole app when OpenCode's SQLite database is huge (the reporter's
opencode.dbwas 29 GB with 20+ liveopencodeprocesses writing to it; every panel open/refresh wedged the main process for tens of seconds to minutes, repeating on each 15 s/focus refresh — a perceived permanent hang).Root cause (measured on a 22 GB synthetic DB matching the reporter's shape — 7,500 sessions / 100 K messages / 466 K parts / 1.5 M event rows, real OpenCode 1.17.x schema):
node:sqlite) on the Electron main-process event loop.COUNT(*)+json_extractsubquery overmessagefor every session beforeLIMIT(~2.1 s/scan).session.time_updatedcontinuously → the mtime parse cache missed every refresh → the freeze repeated forever. Measured: 32.8 s continuous main-process block per scan (warm cache; the reporter's cold/contended DB multiplies this).Fix:
worker_threadsworker (lazy spawn,unref'd, idle teardown, FIFO dispatch, per-call timeouts of 30 s list / 15 s parse, crash-loop cap). Faults become per-source scan issues instead of stalls; other providers' results always arrive.(session_id, time_created, id)index (~20× read reduction). On an unindexed 500-session / 50,000-message fixture, listing 250 candidates fell from 785 ms to 0.20 ms.What does not change: panel data (titles, previews, message counts, tokens, models, resume/open-log actions), scan cadence, all other providers, mobile (same main-process scan module — it benefits identically). No UI changes, no new settings.
Screenshots
Live A/B on the 22 GB rig (1 Hz renderer→main IPC ping instrumentation), screenshots posted in the PR conversation (hosted internally because this repo is public):
Manual Electron validation
Validated this PR’s Electron build against an isolated, unindexed OpenCode fixture with 400 sessions and 100,000 messages (~22 MB). The panel accepted search input while the real scan was running, then populated all 400 matching sessions with message counts and previews. A forced refresh also completed successfully with zero renderer console errors.
Search remains responsive while the session scan runs
Completed scan renders 400 matching sessions
Testing
pnpm lint(oxlint clean on all changed files)pnpm typecheck(all three tsconfig projects)pnpm test(focused:src/main/ai-vault/— 26 files, 151/151 green; existing OpenCode/scanner test files unmodified)pnpm build(electron-vite dev build emits the new worker entry; dev app exercised live)AI Review Report
Three review rounds with two reviewers per round plus a perf lane; final round clean. Main risks checked: worker protocol races and timer/promise leaks, respawn-cap semantics, structured-clone safety across the worker boundary, SQL correctness against OpenCode's real indexes, cache-poisoning paths, and unapproved scope narrowing. Seven fixes landed from the loop — most notably removing the production inline fallback entirely: worker-start failures now fail closed (the exact hang cannot return), while later scans still re-probe and self-heal. This is falsification-proven by tests. A stale-worker-handle-after-clean-exit finding from automated review was fixed post-open (clean exits now drop the cached handle instead of stalling the next request to timeout).
Cross-platform compatibility was explicitly checked for macOS, Linux, and Windows:
worker_threads+node:sqliteare platform-independent (existing precedent: warp theme parser worker, STT worker), Windows/WSL database paths are passed to the worker exactly as the main thread previously read them (no path-semantics change,path.jointhroughout), no shortcuts/labels/shell behavior touched, and packaged-build path resolution follows the existingapp.isPackagedworker pattern, with a missing bundle failing closed and surfacing a scan issue.Security Audit
PRAGMA query_only = ON(unchanged belt-and-suspenders against mutation).<dbPath>#<sessionId>routing keeps its existingopencode*.dbbasename validation, so renderer-supplied paths cannot be misrouted into the SQLite parser.aiVault:listSessions) is unchanged.Notes
worker.terminate()cannot preempt an in-flight synchronous SQLite read, so a timed-out call may briefly keep reading off-main before the thread dies (bounded,unref'd).