Skip to content

fix(#154): HTTP fallback for tj report --reuse when daemon holds the DB lock - #165

Merged
anilmurty merged 3 commits into
mainfrom
fix/154-reuse-http-fallback
Jun 20, 2026
Merged

anilmurty merged 3 commits into
mainfrom
fix/154-reuse-http-fallback

Conversation

@anilmurty

Copy link
Copy Markdown
Contributor

Closes #154 (follow-up surfaced during the v0.4.0 pre-release pass).

Problem

tj report --reuse queries the spans table directly for each cluster's planning text + example sessions, so it errored — "needs direct database access. Stop the daemon with tj stop…" — whenever tj serve held the DuckDB write lock. tj optimize already has the analogous ApiBackend fallback; --reuse didn't, and /api/v1/optimize doesn'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 (new tokenjam/api/routes/reuse.py) returns report_to_dict(report) — so the CLI reconstructs the finding through the existing report_from_dict — plus the two report-only extras the renderer needs: planning_texts ({session_id: completion text | 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 endpoint is hit only when a report is generated.
  • 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. Local rendering is unchanged.
  • cmd_report._render_reuse_report dispatches exactly like cmd_optimize: direct conn when available, else ApiBackend + /api/v1/reuse/clusters. --trim stays DB-direct (now documented as the remaining shared limitation).

Tests

  • test_api.py — /api/v1/reuse/clusters returns the finding (findings.reuse.clusters) + non-empty planning_texts + pricing_mode for a seeded cluster (exercises the route handler end-to-end).
  • 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. 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.md updated (routes list + tj report fallback note). Full CI set green locally (768 passed), ruff + mypy clean on changed files.

Built in an isolated git worktree off main. No file overlap with the other follow-up PRs.

…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 anilmurty left a comment

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.

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:

  1. Capture the real endpoint payload via asyncio.run(_fetch()) against the ASGI app
  2. Stub fetch_reuse_clusters on an ApiBackend instance with monkeypatch.setattr(backend, "fetch_reuse_clusters", lambda **kw: payload)
  3. Invoke the CLI with that stubbed backend — runs the real cmd_report code path, including report_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

  1. prepare_renders accepts both conn=None and planning_texts=None — callers must provide exactly one. A runtime if conn is None and planning_texts is None: raise ValueError would be defensive. Existing call sites always provide one, so this is hypothetical.
  2. 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]>
@anilmurty

Copy link
Copy Markdown
Contributor Author

Thanks — "ship it" noted. Folded in the first nit since it's cheap and matches the no-silent-failure ethos:

  • Add PyPI and npm publish workflows #1 (source guard): prepare_renders now raises ValueError if neither conn nor planning_texts is supplied. Without it, "neither" silently rendered every cluster skeleton-less (capture off) or crashed in _fetch_planning_texts(None, …) (capture on). Added a focused unit test (test_prepare_renders_requires_conn_or_planning_texts). All existing call sites already pass exactly one source, so behavior is unchanged for them.
  • Rename npm package from @ocw/sdk to @openclawwatch/sdk #2 (redundant alias="agent_id"): left as-is on purpose — /api/v1/optimize uses the identical Query(None, alias="agent_id"), so keeping it makes the mirrored endpoint consistent with the one I patterned it on. Happy to drop it from both in a separate sweep if you'd rather.

Pushed as one commit (29ae212). CI re-running; 89 reuse/CLI/API tests green locally, ruff + mypy clean.

@anilmurty
anilmurty merged commit c6e628e into main Jun 20, 2026
4 checks passed
@anilmurty
anilmurty deleted the fix/154-reuse-http-fallback branch June 20, 2026 00:12
@anilmurty anilmurty mentioned this pull request Jun 20, 2026
HoomanDgtl pushed a commit to HoomanDigital/tokenjam that referenced this pull request Jun 20, 2026
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]>
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.

[follow-up] tj report --reuse needs an HTTP fallback when daemon holds the DB lock

1 participant