Repository navigation
fix(db): recover off the recorded fatal, and never expose a half-torn-down backend - #702
Conversation
…-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]>
|
| 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
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
| 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) |
There was a problem hiding this 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
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.
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 onmainright 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) callshandle_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.pyisolates each analyzer so one failure cannot lose the others: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:
note_fatal_db_errorrecords the fatal where it is recognised, before any re-raise, so the process-wide record survives every handler that swallows it. Newrecover_if_fatal_notedruns from thefinallyof both background jobs. Exception propagation through several layers of broadexcept Exceptionis 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_connectionscloses the root connection and bumps the generation counter;_reopenreplaces it. In between, another thread callingconnsaw 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_lockis held across teardown, reopen and the index repair, via anExitStack. 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 realbuild_reportwith a fatal-raising analyzer; asserts it propagates and that the analyzer queued behind it never runs. With the fix reverted the run logsanalyzer 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_reopenso 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.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.