Skip to content

fix(host): prevent chat-index and usage SQLite reopen/leak during or after dispose - #2411

Merged
Fei2411 merged 2 commits into
devfrom
fix/sqlite-dispose-race
Nov 27, 2026
Merged

Fei2411 merged 2 commits into
devfrom
fix/sqlite-dispose-race

Conversation

@Fei2411

@Fei2411 Fei2411 commented Nov 27, 2026 •

Copy link
Copy Markdown
Collaborator

Issue

None (fixes deterministic Windows EPERM on rmSync(home) in test/agent-preset.test.js and test/scoped-tools-creation.test.js surfaced by Windows 4-shard CI).

Agent

Agent: Antigravity (Gemini 4 Neon)

What changed / 改了什么

  • ds-bot/src/host/chat-index.js:
    • Added a disposed guard matching coordination.js so openIndex() aborts before mkdir(home) / new DatabaseSync(indexPath) once the plugin is disposing or disposed, and late post-dispose reads (e.g. an in-flight groupSessionFor -> ownChatBrief) never open an unclosed chat-index.sqlite handle.
    • Returned the pending indexOpening settlement from the ctx.effect disposer so await ctx.dispose() waits for any in-flight SQLite open to close before returning.
    • Guarded indexedParts() and recallToolOutput() against touching a closed index.db after catchUp / catchUpToolOutputs yields.
  • ds-bot/src/host/usage.js:
    • Applied the same disposed guard and pending-opening settlement to openLedger(), noteSession(), record(), and the ctx.effect disposer so usage.sqlite cannot be opened or leaked during/after dispose.
  • ds-bot/test/chat-index.test.js & ds-bot/test/usage.test.js:
    • Added regression tests covering in-flight SQLite open racing with dispose() and post-dispose calls verifying neither chat-index.sqlite nor usage.sqlite is created or leaked.

Changelog

none

How I checked it / 怎么验证的

  • node --import ./test/harness-resolve.mjs --test test/chat-index.test.js test/usage.test.js test/agent-preset.test.js test/scoped-tools-creation.test.js (80/80 passed on Mac)
  • npm run lint -- --quiet (0 errors)
  • scripts/scan.mjs (0 must-fix)

Devin Review

@Fei2411 Fei2411 added the agent/antigravity Opened by Antigravity label Nov 27, 2026
devin-ai-integration[bot]

This comment was marked as resolved.

@Fei2411

Fei2411 commented Nov 27, 2026

Copy link
Copy Markdown
Collaborator Author

Review: changes-requested
Reviewer: Antigravity (Gemini 4 Neon) @ a88e9a5

Summary

Core SQLite open/dispose race protection in openIndex(), openLedger(), noteSession(), record(), and the ctx.effect disposers (pending?.then(...)) is sound and prevents SQLite handle leaks during/after dispose. However, three P1 issues remain in mid-flight async reader/scanner paths and test coverage.

Findings

P0

  • None.

P1

  1. ds-bot/src/host/chat-index.js — catchUp(), catchUpToolOutputs(), and callers can execute prepared statements on a closed DB after dispose

    • indexedParts() (L409) runs for (const part of parts) await catchUp(index, part, { group }) and only checks if (disposed || index !== chatIndex) after the loop (L410). If dispose() runs after openIndex() settles (microtask gap) or while catchUp awaits eventsBackwards on part 1, the next iteration calls catchUp(index, part2) which synchronously executes index.mark.get(part.sessionId) (L271) on the closed DatabaseSync, throwing database is not open and emitting a spurious rt.warn.
    • The same issue exists in recallToolOutput() (L579–581) + catchUpToolOutputs() (L338 index.toolMark.get(...)).
    • searchOwnChat() (L420), latestOwnChat() (L472), and aroundOwnChat() (L487) also resume across an await indexedParts(...) microtask boundary without re-checking disposed || index !== chatIndex before touching index.db / index.before / index.from / index.between.
    • Fix: Guard if (disposed || index !== chatIndex) return at the entry (and after eventsBackwards) of catchUp() and catchUpToolOutputs(), break early inside the for (const part of ...) loops in indexedParts() and recallToolOutput(), and re-check disposed || index !== chatIndex after await indexedParts(...) in callers.
  2. ds-bot/src/host/usage.js — scan(), scanSession(), and usageView() lack disposed / active-ledger guards

    • scan() (L483) does not short-circuit on disposed, nor does it check disposed || book !== ledger after await openLedger(), await rt.load(), await ctx.sessionController.list(...), or inside scanSession() (L435 mark, L448/L474 commit).
    • If ledger is already open and dispose() closes it while scan() is suspended on rt.load(), list(), projections(), or page(), resuming touches the closed SQLite handle, throwing database is not open, repopulating listed/unreadable after the disposer cleared them, and emitting spurious usage scan failed / usage could not read ... warnings.
    • Calling usageView() after dispose() still triggers a full scan() into a throwaway memoryLedger() that usageView() immediately discards when L580 calls openLedger() for a fresh empty memoryLedger(). Also, if dispose() races across the microtask after await openLedger() at L580, L581/L634/L635 touch a closed DB.
    • Fix: Return early from scan() when disposed; avoid shadowing outer ledger (use book) and abort after each await when disposed || book !== ledger (both in scan() and scanSession(), ideally aborting scan's signal on dispose); in usageView(), skip scan() when disposed and fall back to memoryLedger() if disposed || book !== ledger after await openLedger().
  3. ds-bot/test/usage.test.js (L605–620) — regression test never actually exercises an in-flight openLedger() racing with dispose()

    • meter({ sessionId: 'b2', messages: [] }, ...) calls noteSession('b2'), which suspends at await rt.load() before calling openLedger().
    • call('usage', ...) suspends at await request.json() and await rt.load() in the channel route before calling usageView() / openLedger().
    • Because await stop() runs immediately on the next line, opening is still undefined when dispose() runs, so the in-flight openLedger() + pending?.then(...) settlement path is never exercised.
    • Additionally, calling call('usage', ...) after stop() hits the channel's refresh() path and recreates home (state.json changed while no host held the team), hiding whether usage.js recreated home.
    • Fix: Pre-load state (or test install(rt) directly / trigger recordUsage or usageView directly) so openLedger() is genuinely in flight when dispose() runs; also add tests verifying mid-catchUp / mid-scan dispose causes zero database is not open throws or warnings.

P2

  • None.

P3 (Nits)

  • ds-bot/src/host/usage.js (L354–367): Clear early.length = 0 in the ctx.effect disposer alongside listed, journaled, and unreadable so pre-dispose buffered rows are not retained.
  • ds-bot/test/usage.test.js (L606): Remove duplicate dynamic const { existsSync } = await import('node:fs') (existsSync is already imported on L2).
  • ds-bot/test/chat-index.test.js (L125): Register t.after(() => rmSync(home, { recursive: true, force: true })) so temp directories are cleaned up if an assertion fails.

Checked & Passed

  • openIndex() and openLedger() guard every await gap (import('node:sqlite'), mkdir, unlink) and close any DB opened across the final .then(...) boundary, with ctx.effect disposers returning pending?.then(...).
  • noteSession(), record(), and forgetChatIndexSession() do not reopen or touch SQLite after dispose.
  • Diff is clean, tightly scoped, and has no privacy/path leaks.

@Fei2411 Fei2411 added review/changes-requested Independent review found issues to fix reviewed-by/gemini-4-neon labels Nov 27, 2026
@github-actions github-actions Bot added the reviewed-by/antigravity Reviewed by Antigravity label Nov 27, 2026
@github-actions github-actions Bot added review/re-review New commits pushed after last review — needs re-review and removed review/changes-requested Independent review found issues to fix reviewed-by/antigravity Reviewed by Antigravity labels Nov 27, 2026
@Fei2411

Fei2411 commented Nov 27, 2026

Copy link
Copy Markdown
Collaborator Author

Review: approved
Reviewer: Pi (SWE-2.1 Max) @ 8022cda

Summary

Round 2 convergence review. All three R1 P1 findings, all three R1 P3 nits, and the Devin Review P1 (metered usage lost on unload) are fixed at 8022cdae, with no new regressions found. The dispose paths now close SQLite exactly once, never reopen it, never touch a closed handle, and never warn spuriously; in-flight opens are drained because the disposer returns the pending-open promise and the host lifecycle (cordis _unload → await runDisposable) awaits it before the data directory is removed — which is the actual root fix for the Windows rmSync EPERM race.

R1 findings, verified item by item

P1 #1 — chat-index: fixed.

  • openIndex() now guards disposed at entry and after every await gap (import, mkdir, the fresh-unlink), and the final .then closes any DB opened across a dispose (disposed || indexOpening !== opening). The disposer sets disposed synchronously, drops indexOpening, closes any open DB, and returns pending?.then(...) so a late-opened handle is still closed before unload completes.
  • catchUp() / catchUpToolOutputs() guard at entry, inside the eventsBackwards loop, and again before the transaction. The BEGIN→COMMIT section is synchronous, so once the pre-transaction guard passes no dispose can interleave; a mid-scan dispose now exits silently instead of throwing database is not open into the caller's rt.warn.
  • indexedParts() re-checks inside the per-part loop and after it; searchOwnChat() / latestOwnChat() / aroundOwnChat() re-check disposed || index !== chatIndex after await indexedParts(...) and fall back to log scanning (no DB access); recallToolOutput() guards the outer check, breaks the per-part catchUpToolOutputs loop, and re-guards before preparing statements; forgetChatIndexSession() early-returns when disposed.

P1 #2 — usage: fixed.

  • The local variable shadowing ledger is gone: scan() / scanSession() use book throughout, and every resume point (openLedger, rt.load, list, per-target lane, scanSession projections/page/commit) is guarded by disposed || book !== ledger, so nothing touches a closed handle and listed / unreadable are never repopulated after the disposer clears them.
  • scan() aborts promptly: a per-scan AbortController is wired into AbortSignal.any, aborted by the disposer, and the post-abort catch/list-error paths return without warning; scannedAt is no longer stamped after dispose.
  • usageView() skips scan() when disposed and falls back to memoryLedger() when disposed || opened !== ledger, so post-dispose views are empty but safe and never scan into a throwaway ledger.

P1 #3 — test authenticity: fixed. The new tests genuinely exercise the in-flight races (verified by reading the control flow and running them):

  • chat-index.test.js: openIndex() is in flight when dispose runs (the import cannot settle before the synchronous dispose), the home directory is removed mid-flight, and post-dispose ownChatBrief falls back without recreating home or chat-index.sqlite; the multi-part test blocks part 1 inside sessionController.page() (proved by the pageCalls === 1 assertion), disposes, then releases — asserting zero warnings and that part 2 is never indexed against the closed DB.
  • usage.test.js: recordUsage() starts openLedger() synchronously so opening is genuinely in flight at dispose; post-dispose recordUsage/usageView neither recreate home nor usage.sqlite nor warn. The scan/meter test blocks scanSession inside page() and a metered stream after its usage chunk, disposes, and then verifies directly against reopened usage.sqlite that the active meter's 600/20 tokens were persisted before close — a real end-to-end assertion on the stored bytes, not a mock.
  • Ran locally on Node 24: chat-index.test.js 5/5, usage.test.js 22/22, agent-preset.test.js 7/7 — all pass. CI ubuntu-latest · Node 24 shards (1/3, 2/3, 3/3) and Test result are green at this head.

R1 P3 nits: all fixed — early.length = 0 in the disposer; duplicate existsSync import removed; t.after cleanup registered in both new chat-index tests.

Devin P1 — activeMeters: fixed. Metered streams register an entry in activeMeters at generator start; the disposer synchronously flushes any already-observed usage sample into the still-open ledger before closing it, and the flushed flag makes stream finalization after dispose a no-op, so there is no double-count and no post-close record(). The flush row construction mirrors record() (same key shape, token mapping, kind/session/provider/model), and sqliteLedger.add keeps calls semantics identical.

Residual notes (non-blocking)

  • P3 (accepted trade-off): if dispose lands in the narrow window where opening is still in flight (ledger === undefined at dispose time), in-flight meter usage is dropped together with the early buffer — consistent with pre-existing buffered-row semantics, and Devin's P1 scenario (auxiliary streams mid-unload with the ledger open, the common case) is covered and tested. No handle leak either way.
  • P3: when the scan's list call is aborted by the scan timeout, the "usage could not list the Sessions" line is now suppressed (dispose-abort and timeout share one signal). Informational only; the scan continues.

Not verified here

  • windows-latest · Node 24 CI is skipped at this head by the repo's change-detection gating, so the actual Windows rmSync EPERM end-to-end path did not run in CI. Correctness of the fix does not depend on Windows specifics (handles are guaranteed closed before unload completes on every platform), and the Linux CI plus the local runs above cover the logic.

@Fei2411 Fei2411 added review/approved Independent review passed — ready to merge reviewed-by/swe-2-1-max Reviewed by SWE-2.1 Max (independent read-only review) and removed review/re-review New commits pushed after last review — needs re-review labels Nov 27, 2026
@github-actions github-actions Bot added the reviewed-by/other Reviewed by another AI coding agent label Nov 27, 2026
@Fei2411
Fei2411 merged commit 7b30822 into dev Nov 27, 2026
27 checks passed
@Fei2411
Fei2411 deleted the fix/sqlite-dispose-race branch November 27, 2026 17:56
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agent/antigravity Opened by Antigravity review/approved Independent review passed — ready to merge reviewed-by/gemini-4-neon reviewed-by/other Reviewed by another AI coding agent reviewed-by/swe-2-1-max Reviewed by SWE-2.1 Max (independent read-only review)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant