Repository navigation
fix(db): a fatal DuckDB error must stop the process serving, not be logged per-row - #700
Conversation
…ogged per-row A corrupt PRIMARY KEY index on the agent-config table made one background upsert raise duckdb.FatalException. That exception invalidates the whole database instance -- every connection in the process, including ones opened afterwards -- but the per-record handler caught it, logged a soft "this record could not be persisted" warning, and carried on. Every API route then returned 500, the dashboard rendered empty, and /health went on reporting "ok" because it never touched the database. Root cause: the ART behind agent_config_files.config_id had diverged from the table's rows. Reads agree with the table, so the existing count-based index probe cannot see it; only a statement that REMOVES an index entry (DELETE, and the delete half of INSERT OR REPLACE) exposes it, as "Failed to delete all rows from index. Only deleted 0 out of 1 rows". Reproduced deterministically on an affected database for 96 of 103 keys under DuckDB 1.5.1 and 1.5.5, with the WAL removed; the same schema and the same upsert sequence on a fresh database runs clean through five passes, a CHECKPOINT and a reopen, so this is engine-level index divergence rather than bad SQL. - is_fatal_db_error classifies a fatal, and the agent-config store re-raises instead of degrading: after a fatal there are no more rows to skip. - recover_invalidated_database closes EVERY connection in the process before reopening. Verified against the engine: while any handle survives, duckdb.connect returns the same invalidated instance from its per-path cache, so reconnecting without closing recovers nothing. Closing them all makes in-process recovery work with no restart. - repair_agent_config_index rebuilds the table from the canonical DDL so the PRIMARY KEY index is rebuilt from live rows. A PK index cannot be dropped the way repair_spans_indexes drops secondary ones. - /health probes storage, recovers in place, and returns 503 when it cannot. - The serve background jobs treat a fatal as fatal instead of letting it die unheard on a scheduler thread. - tj doctor exposes the rebuild unconditionally, and says why it cannot probe. End-to-end on the affected database: the fatal escapes the handler, the request-path connection is confirmed dead, recovery restores it with all 736,746 spans and 7,131 sessions intact, and re-running the pass that killed it now succeeds. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
| Filename | Overview |
|---|---|
| tokenjam/core/db.py | Adds index probing, repair, fatal tracking, and process-wide recovery, but recovery leaves each torn-down backend reachable before the reopen phase. |
| tokenjam/core/optimize/scan_cycle.py | Moves fatal handling into the analyzer worker exception handler, resolving the previously reported swallowed-fatal path. |
| tokenjam/core/transcript_sync.py | Classifies and recovers fatal database errors within the transcript catch-up worker. |
| tokenjam/api/routes/version.py | Changes /health into a storage readiness probe and recovery trigger. |
| tokenjam/cli/cmd_doctor.py | Adds explicit-index divergence diagnostics and repair dispatch. |
| tokenjam/core/agent_config.py | Records and re-raises fatal database errors while preserving ordinary degraded-write behavior. |
Sequence Diagram
sequenceDiagram
participant A as Analyzer worker
participant R as Recovery
participant B as Request backend
participant Q as Concurrent request
A->>R: handle_if_fatal()
R->>B: teardown connections
Q->>B: acquire cursor
B-->>Q: closed-connection error
R->>B: reopen connection
Prompt To Fix All With AI
### Issue 1
tokenjam/core/db.py:2491-2496
**Recovery exposes closed backends**
If a request or ingest operation overlaps process-wide recovery, the first loop tears down its backend before the second loop reopens it, while `conn` remains accessible. The concurrent operation can therefore acquire a cursor from a closed root connection, causing another 500 response or dropping the write during recovery.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.Reviews (5): Last reviewed commit: "fix(db): sweep and repair every explicit..." | Re-trigger Greptile
The first pass guarded the background jobs at their DISPATCH, which never sees the exception: both `start_catch_up` and `trigger_scan_cycle` are fire-and-forget, starting a daemon thread and returning, and each thread already catches everything -- one with `except Exception: pass`, the other logging a warning. That is correct for a job that failed and catastrophic for a fatal, which invalidates the whole database instance rather than that thread's connection. The type checker surfaced it: the guard was annotated as wrapping a `Callable[[], None]` while both jobs return a Thread and a dict. `handle_if_fatal` is now the single hook for a broad `except Exception` that means to log and carry on -- it classifies, records, recovers, and reports whether it handled the error, so ordinary failures still take their existing path untouched. Wired into both thread handlers; the dispatch guard stays for a failure on the dispatch path itself and says what it does and does not cover. Both new tests were verified to fail with the handlers reverted. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…arrying on Appended as Critical Rule 45 (never renumbered, appended at the end). The non-guessable parts are what earn the space: the invalidation is per-database rather than per-connection, a reconnect while any handle survives returns the same dead instance, and a fire-and-forget job swallows its own exception on the thread it spawns so a guard around the dispatch sees nothing. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…mary key Correcting the diagnosis in the previous commit. Dropping ONLY idx_agent_config_kind and idx_agent_config_last_seen makes the affected database fully writable again with the PRIMARY KEY untouched, which identifies which index is actually at fault. This matches the open upstream report, duckdb/duckdb#23645, where the same error is reproduced against explicit non-unique ART indexes and DROP INDEX + CREATE INDEX is described as permanently healing the file. Two consequences. The repair is now a drop and re-issue of those two indexes rather than a full table rebuild -- the same shape as repair_spans_indexes, cheaper, and it leaves the rows, the schema and the PRIMARY KEY alone. Verified on the affected database: every previously-fatal upsert then succeeds, the heal survives a CHECKPOINT and reopen, and the PRIMARY KEY still rejects a duplicate. The fault IS detectable non-destructively, so the check is a real diagnosis instead of an unconditional offer. Getting there exposed a defect in the existing spans probe, fixed here too: it compares an equality lookup against CAST(col AS VARCHAR), and that cast is a no-op on a column already stored as VARCHAR -- so for four of the five spans columns the index served BOTH sides and the probe compared a damaged index against itself. CAST(col AS VARCHAR) || '' is a real expression for every type. Measured on the affected index: the equality form answered 7 where the table held 94, the bare-CAST form also answered 7, the concatenated form answered 94. That 7-of-94 is the wider finding. This corruption does not only make writes fatal; it makes ordinary reads silently under-report, so analyzers reading the table were understating the config surface with no error anywhere. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…erclaiming Generalises the repair from one hardcoded table to the whole catalogue, after the same corruption turned up on sessions and alerts as well as agent_config_files. Indexes are now discovered from duckdb_indexes() and re-issued from their own catalogue DDL, so the repair covers indexes this module has never heard of. That catalogue does not list a PRIMARY KEY's ART, so a repair driven by it structurally cannot drop a primary key -- the property that makes the sweep safe to run unattended. No rows are read, written or moved. Two corrections to the previous commit, both found by running against the affected database rather than by review. The probe was sampling three values per index and reporting the rest sound. It found three of the damaged indexes, missed a fourth, and a repair driven by that verdict left the table STILL raising the fatal on the next write. The probe now compares every distinct value where the table is small enough to enumerate, falls back to sampling above that, and reports anything it could not prove in an explicit not-proven category instead of counting it as passing. On the affected database it now finds five damaged indexes across three tables. Consequently, repair no longer trusts the probe. Recovery and doctor both rebuild EVERY explicit index, because a verdict that cannot prove soundness must not decide what gets repaired -- and recovering into the same fatal is the one outcome that path cannot have. Measured: 1.10s to rebuild all fourteen indexes of a 3.9GB, 736k-row database, rows byte-identical, re-probe clean, and DELETE then works on all three affected tables. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
| backends = [b for b in _LIVE_BACKENDS if b.recoverable] | ||
| for backend in backends: | ||
| backend._teardown_connections() | ||
| ok = True | ||
| for backend in backends: | ||
| if not backend._reopen(): |
There was a problem hiding this comment.
Recovery exposes closed backends
If a request or ingest operation overlaps process-wide recovery, the first loop tears down its backend before the second loop reopens it, while conn remains accessible. The concurrent operation can therefore acquire a cursor from a closed root connection, causing another 500 response or dropping the write during recovery.
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: 2491-2496
Comment:
**Recovery exposes closed backends**
If a request or ingest operation overlaps process-wide recovery, the first loop tears down its backend before the second loop reopens it, while `conn` remains accessible. The concurrent operation can therefore acquire a cursor from a closed root connection, causing another 500 response or dropping the write during recovery.
**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.There was a problem hiding this comment.
Verdict: valid. Recording the resolution here since this PR merged before the fix landed — the race is live on main, and the fix is in #702.
The window is exactly as described. _teardown_connections closes the root connection and bumps the generation counter; _reopen replaces it. In between, another thread calling conn sees the generation mismatch, takes the "make a fresh cursor" branch, and calls .cursor() on the already-closed root connection — a 500 or a dropped write caused by the recovery. For a change whose entire purpose is "a dead connection must never keep serving traffic", that is the worst possible defect to ship.
The observation about the existing coverage is also correct: test_recovery_closes_cursors_belonging_to_other_threads pins a different property and does not cover this.
Fixed by holding every backend's _conn_lock across teardown, reopen and the index repair via an ExitStack, so a thread arriving mid-recovery blocks until the connection is live rather than being handed something dead. Recovery is sub-second (measured 1.10s worst case including a full 14-index rebuild on a 3.9GB database), so blocking is clearly the right trade. The repair is inside the locked region for the same reason — a half-repaired index set is no safer to hand out than a closed connection.
Pinned by test_no_thread_gets_a_cursor_from_a_half_torn_down_backend, which slows _reopen so the racing thread is guaranteed to arrive inside the window rather than hitting it by luck. Verified to fail with the lock acquisition removed.
The failure
One failed background write took the entire web UI down, and nothing said so.
Roughly a dozen log lines after
Application startup complete, a background pass persisting one agent-config record raised:The persistence loop caught it and logged a soft per-record warning — "this record could not be persisted, carrying on with the in-memory view" — which is the correct response to a write-write conflict and completely wrong here. A DuckDB
FatalExceptioninvalidates the whole database instance, not the connection that raised it. Every later query in the process failed with:Result: hundreds of invalidation errors across the alerts, cost, status, budget, relearn, traces, drift and analytics routes; every endpoint 500; an empty dashboard; and
/healthstill returning{"status": "ok"}throughout, because it only ever proved the process was alive. A restart recovered it until the same record was written again.The database file was never damaged — opening it read-only showed every table intact.
Root cause
Explicit non-unique ART indexes had reached a persisted state where they no longer agree with their tables' rows. The PRIMARY KEY is not affected. The damage is not confined to one table — on the affected database, five indexes across
agent_config_files,sessionsandalertswere diverged.This is a known, still-open upstream bug: duckdb/duckdb#23645 reproduces the identical error against explicit non-unique indexes and reports
DROP INDEX+CREATE INDEXas permanently healing the file.Established by experiment on the affected database:
config_ids, one live row per key.INSERT OR REPLACEsequence against a fresh database runs clean through five passes, aCHECKPOINTand a reopen.The half that is worse than the crash
The fatal is loud. The same damage also makes ordinary reads silently wrong, with no error at all:
Every analyzer reading this table was understating the user's config surface by 87 rows and reporting nothing.
What changed
Both halves, because the class of bug is "a fatal treated as recoverable" and the next fatal would do this again regardless of the index.
A fatal is classified and re-raised, never degraded.
is_fatal_db_errorrecognises aFatalExceptionand, as a backstop, the invalidation message. The agent-config store re-raises it instead of logging a per-record warning: after a fatal there are no more rows to skip, only queries that will all fail. Ordinary write-write conflicts still degrade quietly — that path is what the store exists for, and a test pins that it still works.Recovery closes every connection before reopening. Verified against the engine, and the reason the naive fix does not work: while any handle to the path survives,
duckdb.connecthands back the same invalidated instance from DuckDB's per-path cache. Close them all and the instance is evicted, so the next connect opens a healthy database — in the same process, with no restart. That is also why a background job's "own" connection is not isolation: it is the same instance the request path is using, which is exactly how a scan's failure reached the web server. Recovery is therefore process-wide, over a registry of live backends, and hands each thread a fresh cursor. In-memory backends are excluded — their database is their connection.The repair sweeps the whole catalogue.
repair_explicit_indexesdiscovers indexes fromduckdb_indexes()and re-issues each from its own catalogue DDL, so it repairs indexes this module has never heard of. That catalogue does not list a PRIMARY KEY's ART, so a repair driven by it structurally cannot drop a primary key — which is what makes it safe to run unattended. No rows are read, written or moved.Measured cost, since "is this safe on a multi-GB database" needs a number. On the affected 3.9GB / 736,746-row database:
idx_spans_start_time, 736k rows)CHECKPOINTon the 3.9GB fileRows byte-identical before and after. No confirmation prompt needed —
--repairis already an explicit opt-in flag, and a one-second index rebuild that cannot touch a primary key or move a row does not warrant a second gate.The probe reports what it proved, and nothing more. It compares counts for particular values, so it can only find damage in what it looked at. It now compares every distinct value where the table is small enough to enumerate, samples above that, and puts anything it could not prove in an explicit not proven category rather than counting it as passing.
Repair therefore does not trust the probe. Recovery and
--repairrebuild every index. This is the correction that matters most, and I only found it by running against the real database: the earlier three-value sample found three damaged indexes, missed a fourth, and a repair scoped to that verdict left the table still raising the fatal on the next write. A verdict that cannot prove soundness must not decide what gets repaired — especially on the recovery path, where recovering into the same fatal is the one outcome that cannot be allowed.The
CASTno-op defect, fixed in both probes. The existingcheck_spans_index_corruptioncompared an equality lookup againstCAST(col AS VARCHAR)— a no-op on a column already stored asVARCHAR, so for four of its five columns the index served both sides and it compared a damaged index against itself. Measured on a damaged index: equality7, bare-CAST7,CAST(...) || ''94./healthreports readiness, not liveness. It now asks the database, attempts an in-place recovery when it finds an invalidated one, and returns 503 with the reason when it cannot. A backend that cannot be probed reportsstorage: "unknown"rather than"ok". A green tick that cannot distinguish "serving" from "up but unable to read anything" is worse than no status at all.The background jobs treat a fatal as fatal, at the handler that actually swallows it.
handle_if_fatalis the single hook for a broadexcept Exceptionthat means to log and carry on: it classifies, records, recovers, and reports whether it handled the error, so ordinary failures keep their existing path untouched.Placing it took a correction worth spelling out. The first attempt guarded the two jobs at their dispatch, which never sees the exception — both are fire-and-forget, starting a daemon thread and returning, and each thread already catches everything (one with
except Exception: pass, the other logging a warning). The type checker surfaced it: the guard was annotated as wrapping aCallable[[], None]while the jobs return aThreadand adict. The hook now sits in both thread handlers, where the outage's exception actually died; the dispatch guard remains for a failure on the dispatch path itself and documents what it does and does not cover.tj doctordiagnoses and repairs it. Reports which index disagrees and by how much, plus which it could not prove sound;--repairrebuilds every index and re-probes to confirm.Tests
tests/unit/test_db_fatal_invalidation.py, 38 tests. The fatal itself is simulated, since the root-cause index state is a persistent property of one database file. They pin:threading.local);/healthreportsokonly after checking storage,503when it cannot recover,unknownwhen it cannot probe, and recovers an invalidated database in place;GROUP BY, so the two sides genuinely take different paths rather than both being served by the index under test.Also exercised end-to-end against a copy of the affected database: the fatal escapes the handler, the request-path connection is confirmed dead, recovery restores it with all 736,746 spans and 7,131 sessions intact, and re-running the exact pass that killed the daemon then succeeds without degrading.