Skip to content

fix(db): a fatal DuckDB error must stop the process serving, not be logged per-row - #700

Merged
anshss merged 5 commits into
mainfrom
db-fatal-recovery
Aug 6, 2026
Merged

anshss merged 5 commits into
mainfrom
db-fatal-recovery

Conversation

@anshss

@anshss anshss commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

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:

duckdb.FatalException: FATAL Error: Invalid Input Error:
Failed to delete all rows from index. Only deleted 0 out of 1 rows.

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 FatalException invalidates the whole database instance, not the connection that raised it. Every later query in the process failed with:

FATAL Error: Failed: database has been invalidated because of a previous fatal error.
The database must be restarted prior to being used again.

Result: hundreds of invalidation errors across the alerts, cost, status, budget, relearn, traces, drift and analytics routes; every endpoint 500; an empty dashboard; and /health still 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, sessions and alerts were 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 INDEX as permanently healing the file.

Established by experiment on the affected database:

  • The rows are sound. 104 rows, 104 distinct config_ids, one live row per key.
  • Dropping and re-issuing those indexes makes the tables fully writable again, PRIMARY KEY untouched. That is what identifies which index is at fault.
  • The write half is deterministic — 96 of 103 keys raise it, with the WAL removed, under both DuckDB 1.5.1 and the daemon's actual 1.5.5.
  • It is not our SQL. The same schema and the same INSERT OR REPLACE sequence against a fresh database runs clean through five passes, a CHECKPOINT and 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:

SELECT count(*) FROM agent_config_files WHERE kind = 'instruction'   ->  7
SELECT kind, count(*) FROM agent_config_files GROUP BY 1             -> 94

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_error recognises a FatalException and, 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.connect hands 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_indexes discovers indexes from duckdb_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:

Operation Cost
Full divergence sweep, all 14 indexes 0.33 s
Rebuild all 14 indexes 1.10 s
Slowest single index (idx_spans_start_time, 736k rows) 463 ms drop + 412 ms create
CHECKPOINT on the 3.9GB file 0.06 s

Rows byte-identical before and after. No confirmation prompt needed — --repair is 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 --repair rebuild 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 CAST no-op defect, fixed in both probes. The existing check_spans_index_corruption compared an equality lookup against CAST(col AS VARCHAR) — a no-op on a column already stored as VARCHAR, 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: equality 7, bare-CAST 7, CAST(...) || '' 94.

/health reports 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 reports storage: "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_fatal is 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 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 a Callable[[], None] while the jobs return a Thread and a dict. 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 doctor diagnoses and repairs it. Reports which index disagrees and by how much, plus which it could not prove sound; --repair rebuilds 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:

  • a fatal inside the persistence loop escapes it, and is recorded process-wide;
  • a recoverable write conflict still degrades quietly and keeps the in-memory view — the inverse guard, so widening "fatal" cannot break ordinary degrading;
  • neither the transcript catch-up thread nor the analyzer scan cycle thread swallows a fatal (both verified to fail with the handlers reverted);
  • recovery re-establishes a torn-down backend, preserves the data, and closes cursors belonging to other threads (the multi-threaded case is the whole reason cursors are tracked in a list rather than left in a threading.local);
  • an in-memory backend is never torn down by recovery;
  • /health reports ok only after checking storage, 503 when it cannot recover, unknown when it cannot probe, and recovers an invalidated database in place;
  • the repair rebuilds every index by default, can be scoped, preserves every row, is idempotent, is safe on empty tables, never touches a PRIMARY KEY (asserted by behaviour — the constraint still rejects a duplicate), and leaves an index it cannot recreate alone rather than turning damage into absence;
  • recovery rebuilds every index, not only the flagged ones — the property whose absence left the table still fatal;
  • the sweep covers the whole catalogue, excludes primary keys, reports a multi-column index as not-proven rather than passing, says so when coverage was only a sample, and conversely does report full coverage as proven — otherwise doctor could never give a clean bill of health;
  • the scan form still agrees with a GROUP BY, so the two sides genuinely take different paths rather than both being served by the index under test.
tests/unit/test_db_fatal_invalidation.py tests/unit/test_agent_config.py
tests/unit/test_db_helpers.py tests/unit/test_db_close_backfill.py
tests/unit/test_spans_stats_repair.py tests/unit/test_scan_cycle_provenance.py
tests/unit/test_serve_transcript_catchup.py tests/unit/test_doctor_spans_indexes.py
tests/unit/test_mcp_server.py .................................. 173 passed

tests/integration/test_db.py tests/integration/test_api.py
tests/integration/test_analyzers_off_the_request_path.py .......... 218 passed
tests/unit/test_doctor_paths.py tests/unit/test_doctor_first_signal.py
tests/unit/test_cmd_serve_port_precheck.py tests/unit/test_schema_self_heal.py . 51 passed

tests/integration/test_data_access_parity.py tests/unit/test_deadweight.py
tests/unit/test_mcp_probe.py ................................................. 89 passed

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

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.

…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]>
@anshss
anshss requested a review from anilmurty as a code owner August 6, 2026 09:57
@greptile-apps

greptile-apps Bot commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

The PR adds fatal DuckDB classification, process-wide connection recovery, explicit-index integrity checks and repairs, storage-aware health reporting, and fatal handling inside background worker threads. The recovery path still exposes torn-down backends to concurrent requests before reopening them.

  • Re-raises and records fatal persistence errors instead of degrading per row.
  • Rebuilds explicit indexes and extends tj doctor diagnostics.
  • Makes /health probe and recover storage.
  • Handles fatal errors inside analyzer and transcript worker threads.

Confidence Score: 4/5

The PR is not yet safe to merge because concurrent requests or writes can access a backend after teardown and before recovery reopens it.

Process-wide recovery closes every registered backend in one pass and reopens them only afterward, without preventing concurrent callers from acquiring a cursor from a backend whose root connection is currently closed.

Files Needing Attention: tokenjam/core/db.py

Important Files Changed

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
Loading
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

Comment thread tokenjam/cli/cmd_serve.py Resolved
anshss and others added 4 commits August 6, 2026 15:33
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]>
Comment thread tokenjam/core/db.py
Comment on lines +2491 to +2496
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():

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

@anshss anshss Aug 6, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@anshss
anshss merged commit d5f4074 into main Aug 6, 2026
6 checks passed
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