Repository navigation
fix(#154): HTTP fallback for tj report --reuse when daemon holds the DB lock - #165
Conversation
…s the DB lock
`tj report --reuse` queried the spans table directly for each cluster's planning
text + example sessions, so it errored ("needs direct database access") whenever
`tj serve` held the DuckDB write lock — unlike `tj optimize`, which already has
an ApiBackend fallback.
Implements Option B from the issue (dedicated endpoint, pay-for-what-you-use):
- New GET /api/v1/reuse/clusters returns report_to_dict(report) (so the CLI
reconstructs the finding via the existing report_from_dict) PLUS the
skeleton-rendering extras the renderer needs: planning_texts
({session_id: completion text or null}) and pricing_mode. Dedicated rather
than bolted onto /optimize because per-cluster planner text can be many KB and
the Overview polls /optimize every 30s — this is hit only when a report runs.
- ApiBackend.fetch_reuse_clusters mirrors fetch_optimize_report.
- core/export/reuse_report.py: prepare_renders / write_reuse_report now accept
injected planning_texts (HTTP path) as an alternative to conn (local path);
new gather_planning_texts() batches the per-cluster text fetch server-side.
- cmd_report._render_reuse_report dispatches like cmd_optimize: direct conn when
available, else ApiBackend + /api/v1/reuse/clusters. `--trim` stays DB-direct
(documented).
Tests:
- test_api.py: /api/v1/reuse/clusters returns the finding + planning_texts +
pricing_mode for a seeded cluster.
- test_cli.py: `tj report --reuse` over an ApiBackend (no .conn) writes the HTML
+ Markdown sidecar and never emits the "needs direct database access" error.
CLAUDE.md updated (routes list + tj report fallback note).
Closes #154
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
anilmurty
left a comment
There was a problem hiding this comment.
Review: ✅ Approve
The cleanest of the four v0.4.1 batch PRs. CI green on 3.10/3.11/3.12 + TS. Faithful to the design directive, well-tested, honestly scoped.
Architecture — Option B implemented exactly as directed
Dedicated /api/v1/reuse/clusters endpoint (not bolted onto /optimize) — the route's own docstring defends this: "per-cluster planner text can be many KB, and the Overview polls /optimize every 30s — we don't make every poll pay for report-only data." That's the verbatim economic argument from #154's design comment, internalized in the code.
Payload shape is right. report_to_dict(report) (so the CLI reconstructs via existing report_from_dict) + two report-only extras (planning_texts map + pricing_mode string). One HTTP request gets everything the renderer needs.
cmd_report._render_reuse_report mirrors cmd_optimize's direct-vs-API-shim dispatch. No novel architecture; reused the existing pattern. Exactly per the directive.
gather_planning_texts(conn, finding) is batched across all clusters in one DB query, not a naive per-cluster fetch.
reuse_report.py refactor is graceful
prepare_renders and write_reuse_report now accept either conn (local path) or planning_texts (HTTP path). When planning_texts is supplied, no client-side capture-completions gating — the daemon already applied that filter server-side. When conn is supplied, gating happens locally as before. Clean separation. Existing local callers (tj optimize reuse --export-templates) are unaffected.
The CLI test pattern deserves a callout
test_report_reuse_api_mode_writes_artifacts solves a real testing challenge: runner.invoke() is sync, so it can't await an httpx.AsyncClient against ASGI. The agent worked around it cleverly:
- Capture the real endpoint payload via
asyncio.run(_fetch())against the ASGI app - Stub
fetch_reuse_clusterson anApiBackendinstance withmonkeypatch.setattr(backend, "fetch_reuse_clusters", lambda **kw: payload) - Invoke the CLI with that stubbed backend — runs the real
cmd_reportcode path, includingreport_from_dict, against a real route-handler-produced payload
Route handler is exercised genuinely; the network hop is faked. The asserts then verify the CLI took the HTTP path ("Reuse report written"), the old error is gone ("needs direct database access" not in output), and both HTML + MD files were written.
Honest scoping
tj report --trim stays on the direct-DB path, explicitly documented in the new CLAUDE.md text as "the remaining shared limitation." Could have scope-creeped into fixing both; instead the PR stayed laser-focused on #154's specific symptom and named the equivalent --trim gap as a separate future item. Good restraint — that's the right call.
Tiny non-blocking observations
prepare_rendersaccepts bothconn=Noneandplanning_texts=None— callers must provide exactly one. A runtimeif conn is None and planning_texts is None: raise ValueErrorwould be defensive. Existing call sites always provide one, so this is hypothetical.Query(..., alias="agent_id")on the endpoint — the alias matches the param name, so it's functionally redundant. Harmless.
Neither warrants a follow-up.
With this merged, the v0.4.1 batch core is complete
| Issue | PR | Status |
|---|---|---|
| #138 | #158 | ✅ merged |
| #124 | #161 | ✅ merged |
| #139 | #163 | ✅ merged |
| #154 | #165 | ✅ this PR |
Ship it.
…_texts (#165 review) Non-blocking review nit on #154/#165: prepare_renders accepts either conn (local) or planning_texts (HTTP). Passing neither silently rendered every cluster skeleton-less (capture off) or crashed in _fetch_planning_texts(None,…) (capture on). Raise ValueError instead — matches the project's no-silent-failure ethos. All existing call sites already pass exactly one source. Kept the redundant Query(alias="agent_id") on the endpoint for consistency with the mirrored /api/v1/optimize route (the other review nit). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Thanks — "ship it" noted. Folded in the first nit since it's cheap and matches the no-silent-failure ethos:
Pushed as one commit ( |
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 #154 (follow-up surfaced during the v0.4.0 pre-release pass).
Problem
tj report --reusequeries thespanstable directly for each cluster's planning text + example sessions, so it errored — "needs direct database access. Stop the daemon withtj stop…" — whenevertj serveheld the DuckDB write lock.tj optimizealready has the analogousApiBackendfallback;--reusedidn't, and/api/v1/optimizedoesn't carry the planner text / example details the renderer needs.Fix — Option B (dedicated endpoint, pay-for-what-you-use)
Per the issue's recommendation:
GET /api/v1/reuse/clusters(newtokenjam/api/routes/reuse.py) returnsreport_to_dict(report)— so the CLI reconstructs the finding through the existingreport_from_dict— plus the two report-only extras the renderer needs:planning_texts({session_id: completion text | null}) andpricing_mode. Dedicated rather than bolted onto/optimizebecause per-cluster planner text can be many KB and the Overview polls/optimizeevery 30s; this endpoint is hit only when a report is generated.ApiBackend.fetch_reuse_clustersmirrorsfetch_optimize_report.core/export/reuse_report.py:prepare_renders/write_reuse_reportnow accept injectedplanning_texts(HTTP path) as an alternative toconn(local path); newgather_planning_texts()batches the per-cluster text fetch server-side. Local rendering is unchanged.cmd_report._render_reuse_reportdispatches exactly likecmd_optimize: directconnwhen available, elseApiBackend+/api/v1/reuse/clusters.--trimstays DB-direct (now documented as the remaining shared limitation).Tests
test_api.py—/api/v1/reuse/clustersreturns the finding (findings.reuse.clusters) + non-emptyplanning_texts+pricing_modefor a seeded cluster (exercises the route handler end-to-end).test_cli.py—tj report --reuseover anApiBackend(no.conn) writes the HTML + Markdown sidecar and never emits the "needs direct database access" error. The payload is captured from the real route handler, then the sync network hop is stubbed (sync httpx can't drive ASGI in-process).CLAUDE.mdupdated (routes list +tj reportfallback note). Full CI set green locally (768 passed), ruff + mypy clean on changed files.