Skip to content

Keep Agent Session History from freezing the app on huge OpenCode databases - #8924

Merged
brennanb2025 merged 4 commits into
mainfrom
brennanb2025/fix-8864-agent-history-hang
Jul 19, 2026
Merged

brennanb2025 merged 4 commits into
mainfrom
brennanb2025/fix-8864-agent-history-hang

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Jul 16, 2026 •

Copy link
Copy Markdown
Contributor

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.db was 29 GB with 20+ live opencode processes 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):

  1. All OpenCode SQLite reads ran synchronously (node:sqlite) on the Electron main-process event loop.
  2. The discovery query evaluated a correlated COUNT(*)+json_extract subquery over message for every session before LIMIT (~2.1 s/scan).
  3. The preview query JSON-parsed every part blob of a session (0.5–1.1 s per heavy session IO-cold, ~250 MB read, up to 1000 sessions/scan).
  4. Live writers bump session.time_updated continuously → 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 thread: OpenCode SQLite discovery + parsing run on a persistent worker_threads worker (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.
  • Fail-closed worker boundary: if the worker bundle is missing or spawn fails, OpenCode history is skipped with a visible scan issue instead of running the pathological synchronous read on the main thread. The next scan retries worker startup, so transient failures self-heal without risking another app freeze.
  • Bounded queries: discovery reads only session identity + recency (no message scan or discarded metadata); previews come from the newest 100 messages per session via OpenCode's (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):

Before After
Max main-process IPC ping RTT during forced scan 32,784 ms (33 pings queued >1 s; a Playwright UI click timed out at 30 s) 1 ms (0 pings >100 ms)
Panel spinner wedged, app frozen 368–386 OpenCode sessions with previews + counts, zero scan issues (worker-served)

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

Agent Session History remains responsive during scan

Completed scan renders 400 matching sessions

Agent Session History populated after scan

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)
  • Added high-quality regression tests: 17 new discriminating tests — worker-client request correlation, dispatch-time-only timeout, crash → single rejection + respawn + queue drain, spawn failure → fail closed + later self-heal, clean-exit and idle-teardown respawn, crash-loop cap, message-free LIMIT-first discovery, and a bounded-preview fixture proven by placing text parts beyond the 100-message window (fails if the bound is widened).

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:sqlite are 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.join throughout), no shortcuts/labels/shell behavior touched, and packaged-build path resolution follows the existing app.isPackaged worker pattern, with a missing bundle failing closed and surfacing a scan issue.

Security Audit

  • The worker executes only the two pre-existing read paths; databases are opened read-only with PRAGMA query_only = ON (unchanged belt-and-suspenders against mutation).
  • No new input surfaces: dbPaths come from the same trusted discovery (XDG data dir / WSL homes / env) as before; sessionIds come from the DB itself. The synthetic <dbPath>#<sessionId> routing keeps its existing opencode*.db basename validation, so renderer-supplied paths cannot be misrouted into the SQLite parser.
  • Worker messages are structured-clone data only (no functions/handles); responses are matched by correlation id against the single active request.
  • No command execution, no auth/secrets, no new dependencies; the one IPC surface (aiVault:listSessions) is unchanged.
  • Follow-up flagged: the OpenCode usage scanner still reads the same DBs synchronously on the main thread (separate surface, out of scope here).

Notes

  • Preview window semantics: previews now come from a session's newest 100 messages; a session whose newest 100 messages contain no text parts shows fewer/no preview lines (previously older text could be found). Judged acceptable for a history-list preview.
  • Timeouts replace "wait forever": a DB pathological enough to exceed 30 s (list) / 15 s (parse) degrades to a visible scan issue for that source — a deliberate behavior change.
  • Cold-scan populate latency: on a pathological cold DB the panel may take tens of seconds to populate (serialized worker parses) — the app stays fully responsive throughout; not a regression (the pre-fix path was also serial, but blocking).
  • 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).
  • Not exercised live: Windows/WSL (path semantics unchanged), packaged app packaging, SSH (remote scanning never touches this code). The emitted production worker bundle was built and launched directly in a smoke test; missing bundles fail closed.
  • Process note (updated): all dedicated verification passes completed. Completeness verification: COMPLETE-WITH-NOTES, zero blockers (recursively traced the worker entry's 81-file import graph as electron-free; confirmed routing completeness, structured-clone safety, and why existing suites stay green). Perf audit: PASS — no code findings; DB handles/caches are not held between worker calls, all timers/queues settle on every fault path, spawn is lazy, and the 30 s idle teardown already exceeds the 15 s scan TTL so refreshes reuse the warm worker; the idle-teardown→respawn and clean-exit→respawn branches now have deterministic lifecycle tests. Independent merge-confidence pass: LAND — a separate agent re-drove the real Refresh button on the 22 GB rig and measured max 1 ms IPC RTT over a 44.5 s cache-invalidated scan window, zero scan issues (worker-served), all 40 heavy sessions rendering with previews.

…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).
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Before/after evidence (22 GB synthetic opencode.db matching the reporter's 29 GB shape; 1 Hz renderer→main IPC ping instrumentation; screenshots hosted internally because this repo is public — org members: before: app frozen mid-scan · after: panel populated · after: OpenCode sessions with previews).

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

@coderabbitai

coderabbitai Bot commented Jul 16, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: d9774414-ef8d-4395-ba34-6ffe7e1fc875

📥 Commits

Reviewing files that changed from the base of the PR and between 18e965d and 4f7c68c.

📒 Files selected for processing (4)
  • src/main/ai-vault/session-scanner-opencode-sqlite-bounds.test.ts
  • src/main/ai-vault/session-scanner-opencode-sqlite-list.ts
  • src/main/ai-vault/session-scanner-opencode-sqlite-worker-client.ts
  • src/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-client.ts

📝 Walkthrough

Walkthrough

OpenCode 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)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly captures the primary change: preventing Agent Session History freezes on large OpenCode databases.
Description check ✅ Passed The description includes all required sections and covers summary, screenshots, testing, AI review, security, notes, plus cross-platform verification.
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.

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: a9c0b8ba-7ca2-4416-a87a-26182996ad28

📥 Commits

Reviewing files that changed from the base of the PR and between 84ca07d and 54ad17f.

📒 Files selected for processing (11)
  • electron.vite.config.ts
  • src/main/ai-vault/session-scanner-agent-parser.ts
  • src/main/ai-vault/session-scanner-opencode-sqlite-bounds.test.ts
  • src/main/ai-vault/session-scanner-opencode-sqlite-discovery.ts
  • src/main/ai-vault/session-scanner-opencode-sqlite-list.ts
  • src/main/ai-vault/session-scanner-opencode-sqlite-worker-client.test.ts
  • src/main/ai-vault/session-scanner-opencode-sqlite-worker-client.ts
  • src/main/ai-vault/session-scanner-opencode-sqlite-worker-entry.ts
  • src/main/ai-vault/session-scanner-opencode-sqlite-worker-protocol.ts
  • src/main/ai-vault/session-scanner-opencode-sqlite-worker-spawn.ts
  • src/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.
@AmethystLiang AmethystLiang self-assigned this Jul 18, 2026
@AmethystLiang
AmethystLiang self-requested a review July 18, 2026 16:47

@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: Pro

Run ID: b7ca08d5-b135-4a93-9523-6efa25c6c4a8

📥 Commits

Reviewing files that changed from the base of the PR and between 29180f4 and 18e965d.

📒 Files selected for processing (6)
  • src/main/ai-vault/session-scanner-opencode-sqlite-bounds.test.ts
  • src/main/ai-vault/session-scanner-opencode-sqlite-coexistence.test.ts
  • src/main/ai-vault/session-scanner-opencode-sqlite-list.ts
  • src/main/ai-vault/session-scanner-opencode-sqlite-worker-client.test.ts
  • src/main/ai-vault/session-scanner-opencode-sqlite-worker-client.ts
  • src/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

@brennanb2025
brennanb2025 merged commit ca4003a into main Jul 19, 2026
8 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…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
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.

[Bug] Agent history lookup hang forever

2 participants