Skip to content

fix(db): recover off the recorded fatal, and never expose a half-torn-down backend - #702

Merged
anshss merged 1 commit into
mainfrom
fix/db-recovery-race
Aug 6, 2026
Merged

anshss merged 1 commit into
mainfrom
fix/db-recovery-race

Conversation

@anshss

@anshss anshss commented Aug 6, 2026

Copy link
Copy Markdown
Contributor

Follow-up to the DuckDB fatal-recovery work already on main. Two review findings were raised against it and both turned out to be real; the fixes did not make the merge, so both defects are live on main right now.

Finding 1 — a fatal from an analyzer never reached recovery

The scan cycle's in-thread handler (core/optimize/scan_cycle.py, in _job) calls handle_if_fatal, and a fatal raised directly in that frame does recover. But on the real path the exception never gets there.

core/optimize/runner.py isolates each analyzer so one failure cannot lose the others:

except Exception as exc:  # noqa: BLE001 - recorded, not hidden
    log.exception("analyzer %s failed; continuing with the rest", name)
    report.analyzer_errors[name] = f"{type(exc).__name__}: {exc}"

A fatal raised by an analyzer's database write is caught there, filed as that analyzer's failure, and the pass carries on running every remaining analyzer against a database that is already dead. Nothing recovers the connection, and the report ends up with a "did not complete" note per analyzer for a reason that has nothing to do with any of them.

Isolating one analyzer's failure is right. Isolating a fatal is wrong twice over.

Two changes, because patching one handler loses to the next handler someone writes:

  1. The runner re-raises a fatal rather than filing it, and notes on the report that the database became unusable — so nothing reads as "this analyzer found nothing."
  2. Recovery no longer depends on catching the exception at all. note_fatal_db_error records the fatal where it is recognised, before any re-raise, so the process-wide record survives every handler that swallows it. New recover_if_fatal_noted runs from the finally of both background jobs. Exception propagation through several layers of broad except Exception is not a channel worth trusting; the recorded flag is.

Finding 2 — recovery could hand out a closed connection

A genuine race, and the worst one to have shipped in this particular change: the whole point of the original work is "a dead connection must never keep serving traffic", and the recovery path itself served dead connections for a window.

_teardown_connections closes the root connection and bumps the generation counter; _reopen replaces it. In between, another thread calling conn saw the generation mismatch, took the "make a fresh cursor" branch, and called .cursor() on the already-closed root connection — a 500, or a dropped write, caused by the recovery.

The existing test pins that recovery closes cursors belonging to other threads. That is a different property and does not cover this.

Fix: every backend's _conn_lock is held across teardown, reopen and the index repair, via an ExitStack. A thread arriving mid-recovery blocks until the connection is live again instead of being handed something dead. Recovery is sub-second (measured at 1.10s worst case, including a full 14-index rebuild on a 3.9GB database), so blocking is clearly the right trade against serving a closed handle. The repair sits inside the locked region for the same reason: a half-repaired index set is no safer to hand out than a closed connection.

Tests

Both new tests were verified to fail with their fix reverted.

  • test_optimize_runner_does_not_absorb_a_fatal_as_one_analyzer_failing — drives the real build_report with a fatal-raising analyzer; asserts it propagates and that the analyzer queued behind it never runs. With the fix reverted the run logs analyzer fatal-one failed; continuing with the rest, which is the bug stating itself.
  • test_no_thread_gets_a_cursor_from_a_half_torn_down_backend — slows _reopen so the racing thread is guaranteed to arrive inside the window rather than hitting it by luck, then asserts it neither raises nor receives a dead cursor.
  • test_recovery_runs_even_when_every_handler_swallowed_the_fatal — the backstop, with no exception in flight at all.
  • test_backstop_is_a_no_op_when_nothing_was_recorded — the inverse, so an ordinary pass never triggers a teardown.
tests/unit/test_db_fatal_invalidation.py                     42 passed in 2.92s

tests/unit/{agent_config,db_helpers,db_close_backfill,spans_stats_repair,
doctor_spans_indexes,scan_cycle_provenance,serve_transcript_catchup,
mcp_server,deadweight,optimize_analyzers_route}.py          215 passed in 6.12s

tests/integration/{db,api,cli,analyzers_off_the_request_path}.py
                                                            322 passed in 37.95s

ruff check tokenjam/  -> All checks passed
mypy tokenjam/        -> clean apart from one pre-existing core/config.py error
                         this branch does not touch

Full suite not run locally; CI covers it.

Also

CLAUDE.md's rule on this previously said "put the classification at the handler that actually catches" — which is exactly what was done, and it was not enough. It now carries the two lessons this pass cost: don't rely on the exception reaching your handler, and a recovery must not itself hand out dead handles.

…-down backend

Two review findings, both real.

The analyzer path never reached recovery. The scan cycle's in-thread handler
was correct but unreachable: the optimize runner isolates each analyzer with
its own 'failed; continuing with the rest' handler, so a fatal raised by an
analyzer's write was recorded as that analyzer's failure and the pass carried
on running every remaining analyzer against a database that was already dead.
Two changes. The runner now re-raises a fatal instead of filing it as one
analyzer's problem, and notes on the report that the database became unusable
rather than implying the analyzer found nothing. And because patching each
handler loses to the next handler someone writes, recovery no longer depends on
catching the exception at all: note_fatal_db_error records it where it is
RECOGNISED, and recover_if_fatal_noted runs from the finally of both background
jobs, so recovery happens however many layers absorbed it.

Recovery could hand out a dead cursor. Between closing the connections and
reopening them, another thread calling conn saw the bumped generation and took
a cursor from the already-closed root connection - a 500 or a dropped write
caused BY the recovery, which would have this change doing the exact thing it
exists to prevent. Every backend's connection lock is now held across teardown,
reopen and repair, so a racing thread blocks for the sub-second recovery
instead of being served something dead.

Both tests were verified to fail with their fix reverted; the runner one drives
the real build_report and asserts the analyzer queued behind the fatal never
runs.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@anshss
anshss requested a review from anilmurty as a code owner August 6, 2026 13:20
@greptile-apps

greptile-apps Bot commented Aug 6, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR records fatal DuckDB failures independently of exception propagation, stops analyzer execution after a fatal, and serializes backend teardown, reopen, and index repair. It also adds background-job recovery backstops and focused regression tests, but the cursor fast path still leaves a teardown race.

  • Adds process-wide fatal-record recovery from analyzer and transcript-job finally blocks.
  • Re-raises analyzer fatals instead of treating them as isolated analyzer failures.
  • Holds backend connection locks across recovery and index repair.
  • Adds tests for swallowed fatal recovery, analyzer termination, and concurrent cursor acquisition.

Confidence Score: 4/5

This PR should not merge until cursor retrieval is synchronized with teardown, because recovery can still close a cursor after another thread has selected it for use.

The recovery lock protects stale-cursor creation but not the valid cached-cursor fast path, leaving a reachable check-then-close race that can still fail requests or writes during recovery.

Files Needing Attention: tokenjam/core/db.py and tests/unit/test_db_fatal_invalidation.py

Important Files Changed

Filename Overview
tokenjam/core/db.py Adds fatal-record backstop and lock-scoped recovery, but the lock does not cover the valid cached-cursor fast path.
tokenjam/core/optimize/runner.py Correctly stops analyzer execution and re-raises when an analyzer encounters a database fatal.
tokenjam/core/optimize/scan_cycle.py Adds a finally-based recovery backstop while preserving scan-cycle state cleanup.
tokenjam/core/transcript_sync.py Adds the same recorded-fatal recovery backstop before closing the catch-up backend.
tests/unit/test_db_fatal_invalidation.py Adds useful fatal-recovery tests, but the concurrency test begins after generation invalidation and misses the remaining fast-path race.
CLAUDE.md Documents the fatal-record and recovery-locking lessons introduced by this change.

Sequence Diagram

sequenceDiagram
    participant T as Request/ingest thread
    participant B as DuckDBBackend.conn
    participant R as Recovery thread
    participant C as Cached cursor
    T->>B: Read cached cursor and generation
    B-->>T: Return cursor without _conn_lock
    R->>R: Acquire _conn_lock
    R->>C: Close cached cursor
    R->>R: Increment generation and reopen
    T->>C: Execute query
    C-->>T: Closed-cursor failure
Loading
Prompt To Fix All With AI
### Issue 1
tokenjam/core/db.py:2538-2540
**Fast-path cursor escapes recovery lock**

If a request or ingest thread passes the cached-cursor generation check immediately before teardown, `conn` returns that cursor without acquiring `_conn_lock`; recovery then closes it before the caller executes its query, causing a failed request or dropped write despite the new recovery locking.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Reviews (1): Last reviewed commit: "fix(db): recover off the recorded fatal,..." | Re-trigger Greptile

Comment thread tokenjam/core/db.py
Comment on lines +2538 to +2540
with ExitStack() as locks:
for backend in backends:
try:
faults, _unproven = check_index_divergence(backend.conn)
if faults:
logger.error(
"index damage found while recovering: %s",
"; ".join(f"{n} on {t} {r}" for n, t, r in faults),
)
rebuilt = repair_explicit_indexes(backend.conn)
except duckdb.Error as exc:
logger.error("index repair failed after recovery: %s", exc)
locks.enter_context(backend._conn_lock)

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.

P1 Fast-path cursor escapes recovery lock

If a request or ingest thread passes the cached-cursor generation check immediately before teardown, conn returns that cursor without acquiring _conn_lock; recovery then closes it before the caller executes its query, causing a failed request or dropped write despite the new recovery locking.

Knowledge Base Used: Core Data Model

Prompt To Fix With AI
This is a comment left during a code review.
Path: tokenjam/core/db.py
Line: 2538-2540

Comment:
**Fast-path cursor escapes recovery lock**

If a request or ingest thread passes the cached-cursor generation check immediately before teardown, `conn` returns that cursor without acquiring `_conn_lock`; recovery then closes it before the caller executes its query, causing a failed request or dropped write despite the new recovery locking.

**Knowledge Base Used:** [Core Data Model](https://app.greptile.com/metabldr/-/custom-context/knowledge-base/metabuilder-labs/tokenjam/-/docs/core-data-model.md)

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

@anshss
anshss merged commit 5ef1268 into main Aug 6, 2026
7 checks passed
@anilmurty
anilmurty deleted the fix/db-recovery-race branch September 18, 2026 21:03
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.

1 participant