Skip to content

fix(#139): coarsen long cost-chart windows instead of silently emptying (+ Overview parallel fetch) - #163

Merged
anilmurty merged 1 commit into
mainfrom
fix/139-bucket-degradation
Jun 19, 2026
Merged

anilmurty merged 1 commit into
mainfrom
fix/139-bucket-degradation

Conversation

@anilmurty

Copy link
Copy Markdown
Contributor

Closes #139 (follow-up from PR #137 / #133 review). Also bundles the #124 review follow-up (Overview parallel-fetch revert) — same file, same theme.

#139 — graceful bucket coarsening

buildCostSeries guarded pathological grids with if (xs.length > 5000) return null, which renders the empty state with no explanation if a long window (or future finer/hourly bucketing for multi-day ranges) ever crosses 5000 buckets. That's silent truncation.

Fix (option a — graceful degradation): coarsen the bucket up a ladder (hour → day → week) until the grid fits MAX_BUCKETS, computed closed-form (no oversized array is ever built). When coarsening happens, the chart surfaces a note — "Showing <bucket> buckets — this range is too long for <requested>ly detail" — so it's never silent. Genuinely empty windows (no data) still return null → the existing "No spend in this window" state.

Verified in node:

input result
7d, daily no coarsening, 8 points
300d, hourly-requested (>5000 hourly) coarsens to day, 301 points, value preserved
extreme (decades), hourly falls to week, note fires — never empty
no bounds + no rows null (empty state)

#124 follow-up — Overview parallel fetch (per the #161 review)

The #114 serial-fetch workaround is reverted now that the daemon DB layer is concurrency-safe (#124). OverviewView.load fans out via Promise.all. The error handling is deliberately asymmetric and must not be unified (flagged in the #161 review):

  • /cost is load-bearing — no .catch, so its failure rejects the Promise.all and surfaces the error state (the page can't render without spend data).
  • the other five panels each keep a .catch fallback so one failing panel renders empty rather than blanking the whole Overview.

Docs + tests

  • CLAUDE.md: REST API concurrency note and Web UI polling note now describe the parallel fetch + the asymmetric error contract (was: "fetches sequentially").
  • tests/unit/test_lens_ui_regression.py: guards for the coarsening behavior (silent guard gone, ladder + note present) and the parallel/asymmetric fetch pattern (asserts /cost has no .catch while the other five do).

Full CI set green locally (766 passed), UI passes node --check, offline-UI test green.

Built in an isolated git worktree off main.

…ng; parallelize Overview fetch

buildCostSeries guarded pathological grids with `if (xs.length > 5000) return
null`, which renders the empty state with no explanation if a long/finer-bucketed
window ever crosses 5000 buckets. Replace the silent guard with graceful
degradation: coarsen the bucket up a ladder (hour -> day -> week) until the grid
fits, and surface a note ("Showing <bucket> buckets — this range is too long for
<requested>ly detail") so coarsening is never silent. Genuinely empty windows
(no data) still return null -> the existing "No spend" state.

Also bundles the #124 follow-up (same file): the Overview's #114 serial-fetch
workaround is reverted now that the daemon DB layer is concurrency-safe (#124).
OverviewView.load fans out via Promise.all. The error handling is deliberately
ASYMMETRIC and must not be unified:
  - /cost is load-bearing — NO .catch, so its failure rejects the Promise.all
    and surfaces the error state (the page can't render without spend data).
  - the other five panels each keep a .catch fallback so one failing panel
    renders empty rather than blanking the whole Overview.

CLAUDE.md updated (REST API concurrency note + Web UI polling note now describe
parallel fetch + the asymmetric error contract). Static regression guards added
for both the coarsening behavior and the parallel/asymmetric fetch pattern.

Closes #139

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

Both items in one focused PR — exactly the bundling the #161 review asked for. Tight diff, strong tests, accurate doc updates.

#139 — graceful bucket coarsening

Three smart implementation choices:

  1. _BUCKET_LADDER = [hour, day, week] — picks the finest bucket starting from reqBucket whose grid fits MAX_BUCKETS. Genuinely empty windows (!rows.length and no bounds) still return null so the existing "No spend in this window" empty state is preserved — only the silent-on-pathological-range case is fixed. Good preservation of the existing empty-data path.

  2. Closed-form count: (Math.floor(end / s) - Math.floor(start / s)) + 1 — never allocates an oversized array. A naïve for loop would have built a 100K-entry array just to discard it. The closed-form math sidesteps that — important when someone runs a multi-year hourly query.

  3. User-facing note when coarsening fires: "Showing day buckets — this range is too long for hourly detail." The series result stashes requestedBucket so both bucket names are available to the renderer. Honest about what changed; no silent truncation.

#124 follow-up — Overview parallel fetch

The asymmetric error contract from the #161 review is preserved exactly:

const [cost, compare, opt, al, drift, traces] = await Promise.all([
  api('/cost', { since, group_by: 'day' }),                              // ← no .catch, load-bearing
  api('/cost/compare', { since, compare: 'previous' }).catch(() => null),
  api('/optimize', { since, fast: 'true' }).catch(() => null),
  api('/alerts', { since, unread: 'true' }).catch(() => ({ alerts: [] })),
  api('/drift').catch(() => ({ agents: [] })),
  api('/traces', { since, limit: 6 }).catch(() => ({ traces: [] })),
]);

/cost is bare → its failure rejects the Promise.all and surfaces the outer error state. The other five panels each carry their own .catch fallback. The inline comment explicitly documents this is intentional and "must NOT be unified (#124 review)" — exactly the framing the review asked for.

Tests — well-built regression guards

Three new tests, each balancing positive presence and negative absence:

  • test_cost_series_coarsens_not_silently_empty — asserts "xs.length > 5000) return null" is gone, the _BUCKET_LADDER + MAX_BUCKETS constants are present, the user-facing "Showing X buckets" copy is present. The literal-substring assertion on the old guard is robust.
  • test_overview_fetches_in_parallel — old serial-fetch comment is gone, await Promise.all([ is present.
  • test_overview_error_handling_is_asymmetric — asserts /cost has no .catch (positive guard for the asymmetry) and each of the 5 fallback endpoints has its expected .catch(...) clause. Locked in both contracts in one test.

CLAUDE.md updates

Both touched paragraphs accurately reflect the new state with the explicit guidance — "do not collapse conn back to one shared connection object" in the API routes section, "Don't unify them" on the polling section. Future agents reading the file know not to undo either contract.

Tiny non-blocking observation

The ${series.requestedBucket}ly interpolation reads naturally for the current ladder ("hourly", "daily", "weekly"). If anyone ever extends the ladder with a non-clean-suffix name (e.g. "5min" → "5minly"), the copy would need adjustment. Pure forward-looking nit; nothing to do here.

Ship it.

@anilmurty
anilmurty merged commit 435071e into main Jun 19, 2026
4 checks passed
@anilmurty
anilmurty deleted the fix/139-bucket-degradation branch June 19, 2026 23:30
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] buildCostSeries 5000-bucket guard silently empties very long hourly windows

1 participant