Repository navigation
fix(#124): make the daemon DB layer safe for concurrent API requests - #161
Conversation
The daemon serves the REST API over a single DuckDB connection. The sync (`def`) read routes (`/optimize`, `/cost/compare`) run in Starlette's threadpool, so two overlapping requests (UI Overview poll + CLI, or two tabs) could touch the same DuckDB connection from different threads. A single DuckDB connection object is NOT safe for concurrent use — overlapping execute/fetch corrupts the shared result set (None rows) and can abort the process. Fix: DuckDBBackend.conn is now a per-thread cursor over one shared database. DuckDB cursors created via connect().cursor() are independent connections that ARE safe to use concurrently from different threads (the DuckDB-recommended multi-threading pattern), while still sharing one database — so a write on one thread is visible to reads on another. Each thread lazily gets and reuses its own cursor via threading.local; single-threaded callers (tests, CLI) always see one cursor, so behavior is unchanged. No call-site changes: every existing `db.conn.execute(...)` is now thread-safe transparently. Verified empirically: a single shared connection hammered from 8+ threads SIGABRTs; per-thread cursors run clean (0 errors) with cross-cursor visibility and concurrent read/write. Test: tests/integration/test_api.py fires the Overview endpoint set concurrently (incl. both sync routes) over several rounds and asserts all 200 — the issue's acceptance criterion. Confirmed it FAILS on the pre-fix single-connection code and passes with the per-thread cursor. Closes #124 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
anilmurty
left a comment
There was a problem hiding this comment.
Review: ✅ Approve
CI green on 3.10/3.11/3.12 + TS. Smaller, cleaner solution than the design comment prescribed. Worth saying so explicitly.
On the architectural deviation from #124's design comment
The design comment specified Option A — threading.Lock() around writes + a read_only_connection() context manager for reads + auditing ~10 route files to switch callers over. This PR uses a different pattern: per-thread DuckDB cursors via threading.local. It's better than what I directed. Reasoning:
-
Transparent to all callers.
db.connbecomes a property that lazily allocates a cursor per thread. Everydb.conn.execute(...)call site keeps working with no edits. Zero route-file diff vs. the ~10-file audit my prescription would have required. -
DuckDB's canonical thread-safety pattern. Cursors from
connection.cursor()are independent connection-like objects over the same database — explicitly documented as the way to do multi-threaded DuckDB. -
Better cross-thread consistency. All cursors see the same database state instantly; the read-only-file-connection approach in my prescription would have had a (small but real) read-after-write lag.
-
InMemoryBackendinherits the fix. Cursors of an in-memory connection share the in-memory database, so cross-thread visibility works for tests too — the agent's comment calls this out and the test confirms it. -
Single-threaded callers behaviorally identical to pre-PR.
getattr(self._local, "cursor", None)returns the same cursor every time when only one thread asks — so tests and the CLI see no change. Important property.
Net diff: +59/−6 across 2 files vs. ~150 LOC across ~12 files for the prescribed approach. Same end-state, much smaller blast radius. Good judgment in evaluating the prescription and choosing the cleaner pattern.
Verification quality
test_overview_endpoint_set_survives_concurrent_requests is well-built — fires 15 endpoints × 5 rounds = 75 concurrent operations through asyncio.gather against the Overview's actual endpoint set, asserts every response is 200. The pre-fix behavior (SIGABRT under 8-thread contention) is empirically confirmed in the PR description.
The test correctly targets the sync (def) read routes (/optimize, /cost/compare) that get scheduled into Starlette's threadpool — those were the actual contention path. Calling out the threadpool mechanics in the docstring is a nice touch for the next reader.
One non-blocking miss — the UI revert
The original design directive's step 4 was "Revert the Overview's sequential-fetch workaround in tokenjam/ui/index.html." The backend is now safe for parallel fetching, but the UI is still serializing — performance left on the table, not a correctness issue. Either:
- Send a one-line follow-up PR removing the workaround, or
- Fold it into your next PR (#139 —
buildCostSeries, which is also inindex.html)
Whichever you prefer. Both work; the second is slightly more economical since you'll already be in that file.
Good to merge.
|
Thanks for the thorough review. On the UI revert (the #114 sequential-fetch workaround): I'll fold it into #139, per your economical option — #139 is already in Concretely, in #139 I'll swap the six sequential |
TokenJam v0.4.1 — concurrency + cycle-aware run-rate + Reuse HTTP fallback + quality follow-ups across the Lens UI. ## What's in 0.4.1 Six issues closed, all branched off main as separate PRs that landed cleanly: | Issue | PR | What | |---|---|---| | Metabuilder-Labs#138 | Metabuilder-Labs#158 | Run-rate honors `[budget.<provider>] cycle_start_day` (per-tier `cycle_bounds` extracted into `core/cycle.py`, shared with `budget_projection`) | | Metabuilder-Labs#124 | Metabuilder-Labs#161 | Daemon DB concurrency: `DuckDBBackend.conn` is now a per-thread DuckDB cursor (`threading.local`) over one shared database. Cursors are independent connections safe for concurrent use, so the Overview fan-out + sync read routes in Starlette's threadpool no longer crash under load. | | Metabuilder-Labs#139 | Metabuilder-Labs#163 | `buildCostSeries` coarsens up an `hour → day → week` ladder instead of silently emptying long windows (closed-form bucket count, never allocates an oversized array). Same PR reverts the Overview's sequential-fetch workaround to `Promise.all` with deliberately-asymmetric error handling (`/cost` no-catch; the other five panels carry per-call fallbacks). | | Metabuilder-Labs#147 | Metabuilder-Labs#164 | `tj status` shows active (compute) time alongside wall-clock elapsed (`session_active_seconds` = Σ span durations). Both CLI and Lens Status tile rendered, plus `--json` carries both fields. `fmtDurLong` reads multi-day spans as `2d 3h` instead of `3087m`. | | Metabuilder-Labs#154 | Metabuilder-Labs#165 | New `GET /api/v1/reuse/clusters` endpoint + `ApiBackend.fetch_reuse_clusters` lets `tj report --reuse` work when the daemon holds the DB lock. Dedicated endpoint (not bolted onto `/optimize`) so per-cluster planning text isn't paid for on every 30s Overview poll. | | Metabuilder-Labs#162 | Metabuilder-Labs#166 | Recoverable Waste tile consistency: title-cased fallback for unknown analyzer names (`reuse` now renders as `Reuse`), em-dash dropped from the not-ready content line, regression guard locks all three states so the bold-title issue can't recur. | ## Pre-release verification Walked the focused 10-step v0.4.1 checklist via a sub-agent (`tests/agent-pre-release-v0.4.1.md`). Result: **10/10 PASS, 0 FAIL, 0 UNCLEAR**. Full log committed at `tests/results/agent-pre-release-v0.4.1-20260620T002546Z.md`. Validated end-to-end against the live daemon: - 90 concurrent reads against the Overview endpoint set: no SIGABRT, no 500s (was the Metabuilder-Labs#124 reproduction) - `tj cost` cache columns show non-zero values with daemon up (was 0 pre-Metabuilder-Labs#153) - `/api/v1/cost` returns a `cycle` block; UI consumes it - `tj status` shows `active 12m 3s · elapsed 2d 3h`; JSON carries both fields - `tj report --reuse` writes HTML + Markdown with the daemon running (was the Metabuilder-Labs#154 error) - Recoverable Waste tile titles render uniformly and "Reuse" is title-cased ## What's in this commit - `pyproject.toml`: `version = "0.4.1"` - `sdk-ts/package.json`: `"version": "0.4.1"` - `tests/agent-pre-release-v0.4.1.md`: the focused 10-step checklist used to validate this release - `tests/results/agent-pre-release-v0.4.1-20260620T002546Z.md`: the agent-run log proving 10/10 PASS Tests: 689 pass locally; mypy + ruff clean. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Closes #124 (follow-up surfaced while building the Lens Overview, #114).
Problem
The daemon serves the REST API over a single DuckDB connection. The sync (
def) read routes —/optimizeand/cost/compare— run in Starlette's threadpool, so two overlapping requests (the Overview's fan-out, a UI poll + CLI, or two browser tabs) could drive the same DuckDB connection from multiple threads. A single DuckDB connection object is not safe for concurrent use: overlapping execute/fetch corrupts the shared result set (a reader getsNonerows) and can abort the process (SIGABRT). #114 worked around it by making the Overview fetch sequentially; this fixes the root cause.Fix
DuckDBBackend.connis now a per-thread cursor over one shared database:connect().cursor()are independent connections that are safe to use concurrently from different threads (the DuckDB-recommended multi-threading pattern), while still sharing one database — so a write on one thread is visible to reads on another.threading.local. Single-threaded callers (tests, the CLI) always see one cursor, so behavior is unchanged.db.conn.execute(...)becomes thread-safe transparently.InMemoryBackendgets the same treatment (in-memory cursors share the same DB, so cross-thread visibility holds for the threadpool-backed integration tests).I verified the underlying behavior empirically before implementing: a single shared connection hammered from 8+ threads SIGABRTs; per-thread cursors run clean (0 errors) with cross-cursor visibility and concurrent read/write.
Test
test_overview_endpoint_set_survives_concurrent_requestsfires the Overview endpoint set (including both sync routes) concurrently over several rounds and asserts every response is 200 — the issue's acceptance criterion. Confirmed it fails on the pre-fix single-connection code (TypeError: 'NoneType' object is not subscriptablefrom a corrupted mid-fetch result) and passes with the per-thread cursor.Full CI set green locally (762 passed), mypy + ruff clean on
db.py.