Skip to content

fix(dash,plugin): stop statusline cg! on slow stats, dedupe cache refresh - #403

Merged
amiddavid merged 3 commits into
mainfrom
feat/statusline-stats-timeout
Oct 7, 2026
Merged

amiddavid merged 3 commits into
mainfrom
feat/statusline-stats-timeout

Conversation

@amiddavid

Copy link
Copy Markdown
Collaborator

Summary

The user's live context-guru status line was showing a false "proxy down" (cg!) when the proxy was merely slow. Root-caused and fixed on both sides.

statusline.py: _fetch_stats rendered cg! on ANY URLError/OSError, including a plain TimeoutError. A diagnostic capture against the user's live, healthy v0.4.2 proxy caught ~10 of these in 10 minutes, every one a TimeoutError at exactly the 0.6s client cutoff with the proxy never actually down. It now distinguishes refused/unreachable (still cg!) from timed out: with a recent-enough cached body it renders those numbers immediately with a small stale marker (⏳), and with no cache yet it prints cg: stats loading… instead of claiming the proxy is down.

dash/api.go (the real slowness): jsonCache.serveJSON started a brand-new go a.refreshJSON(...) goroutine — running the full compute — on every single stale-cache read. Under real concurrent traffic (many renders landing while one entry was stale), every one of those duplicate computations contended for the same SQLite connection pool at once. Measured against a read-only copy of the affected deployment's dashboard DB (13 MB → 22 MB after growth, 4.4k requests, 10k tool-declaration rows), a single isolated /api/stats call takes ~0.18s (full) / ~0.08s (lean) — nowhere near the 38-45s the user's live proxy measured under real load, which points squarely at this duplicate-recompute amplification rather than the query itself being slow at this corpus size. jsonCache now gates refreshes with beginRefresh/endRefresh so only the first stale reader for a key starts one, and load() keeps serving that key's (otherwise too-old) body while its refresh is in flight — a reader arriving past dashCacheTTL+dashCacheStale is never forced to block on a brand-new recompute alongside one already running.

Cheap path for the statusline: /api/stats?lean=1 (dash/api.go's statsLean) answers from Overview() alone, skipping the three priced aggregates (CachesplitHistoricalUSD, TierCosts, DeclCreditFor) a full call always runs — none of which the statusline reads, and the heaviest of which (DeclCreditFor → SelfRemovals) does a full scan over tool_declarations regardless of the session filter. statusline.py now always requests it.

Test plan

Run on the eval box (go is not installed locally; see repo CLAUDE.md).

  • go vet ./dash/... — clean
  • go test ./dash/... -race — pass (299s)
  • go test ./dash/... targeted: TestJSONCacheLoadServesPastCapWhileRefreshing, TestServeJSONSingleFlightsStaleRefresh (8 concurrent stale readers of one key → exactly 1 compute, none blocks), TestStatsLeanSkipsThePricedExtras, TestStatsLeanIsACacheKeySeparateFromTheFullHandler — pass
  • go test ./context-guru-plugin/... -run Statusline — pass, including the corrected TestStatuslineReportsLoadingNotDownOnATimeout (previously asserted cg! on an accept-and-stall port; now asserts the loading state, since that shape is indistinguishable from a merely-slow healthy proxy) and the new TestStatuslineServesStaleStatsOnATimeoutRatherThanLoading
  • go test ./... full suite — all green except the two pre-existing eval-box environment failures (TestInstallRefusesAnUnverifiedDownload, TestInstallReportsPATHFromTheSourceFallbackToo), caused by the box's root-owned /usr/local/bin/context-guru-proxy short-circuiting install detection — documented, unrelated to this change
  • gofmt -l on every touched file — clean

Follow-ups

  • SelfRemovals (dash/toolapi.go) scans tool_declarations for the whole tenant regardless of Filter.Session — correct for its own self-removal-detection semantics (it is inherently a cross-session signal), but it means a session-scoped full /api/stats call still pays for a tenant-wide scan. The new lean=1 path avoids this for the statusline; the full dashboard view still pays it, mitigated by the cache fix in this PR. Worth a closer look if a large deployment's full-view /api/stats is still slow after this.

🤖 Generated with Claude Code

…resh

context-guru-plugin/scripts/statusline.py rendered the down indicator (`cg!`)
on ANY URLError/OSError from its /api/stats fetch, including a plain
TimeoutError. A diagnostic capture against a live, healthy v0.4.2 proxy
showed ~10 such timeouts in 10 minutes, every one a TimeoutError at exactly
the client's 0.6s cutoff with the proxy never actually down. _fetch_stats now
reports a distinct STATS_TIMEOUT status: with a recent-enough cached body it
is served immediately with a small stale marker, and with none yet it prints
a friendly "stats loading..." instead of the down indicator.

Root cause of the slowness: dash/api.go's jsonCache.serveJSON started a new
`go a.refreshJSON(...)` goroutine, running the FULL compute, on every single
stale-cache read. Under real concurrent traffic every one of those duplicate
computations contended for the same SQLite connection pool at once, which is
what turned a query that is sub-200ms in isolation (measured on a copy of the
affected deployment's dashboard DB) into the 38-45s the statusline was timing
out against. jsonCache now gates refreshes with beginRefresh/endRefresh so
only the first stale reader for a key starts one, and load() keeps serving
that key's (otherwise too-old) body while its refresh is in flight, so a
reader arriving past dashCacheTTL+dashCacheStale is never forced to block on
a brand-new recompute alongside one already running.

/api/stats also gains a `lean=1` fast path (dash/api.go's statsLean) that
answers from Overview() alone, skipping the three priced aggregates
(CachesplitHistoricalUSD, TierCosts, DeclCreditFor) a full /api/stats call
otherwise always runs — none of which the statusline reads. statusline.py
now always requests it.

Tests: dash/jsoncache_refresh_test.go covers the refresh gate directly and
end-to-end (8 concurrent stale readers collapse onto exactly 1 compute, none
of them blocks) and the lean path's field coverage; context-guru-plugin's
statusline tests gain timeout-vs-down and stale-cache-render coverage and the
existing stalling-port test is corrected to expect the loading state rather
than `cg!`, since an accept-and-never-answer connection is indistinguishable
from a merely-slow healthy proxy at the client. All run on the eval box
(go vet, go test ./dash/... -race, go test ./context-guru-plugin/...).

Assisted-By: Claude Sonnet 5 <[email protected]>
Signed-off-by: DAVID AMID <[email protected]>
@amiddavid

Copy link
Copy Markdown
Collaborator Author

Review: tested live on the eval box. Approve, with two small follow-ups (neither blocking)

Unit tests on the box (Python 3.9, Go 1.26): go vet and gofmt are clean, go test -race ./dash/... passes, and the plugin's Statusline tests pass.

Live load test

I built a test dashboard DB (9,000 requests, 12,000 tool_declarations rows) and ran this branch's proxy and main's side by side. Each got 24 concurrent clients hitting /api/stats across 6 sessions for 70s.

proxy requests p99 max served stale errors
main 29,709 2ms 45.0s 10,523 16 HTTP 500s
PR (full) 32,678 2ms 0.74s 87 0
PR (lean=1) 32,760 2ms 0.15s 181 0

The same queries take 0.04–0.13s when run one at a time. This confirms the diagnosis: on main, every stale read starts its own full recompute, and they pile up. The 45s maximum matches the 38–45s seen in the original report.

Status line against the real proxy

  • Live: shows the figures.
  • Proxy frozen with SIGSTOP, cache 10s old: shows the cached figures with the ⏳ marker, after 684ms.
  • Frozen, no cache: shows cg: stats loading….
  • Nothing listening on the port: shows cg!.
  • Python 3.9: the socket.timeout handling works as intended.

Findings

  1. lean=1 lowers the savings figure on some setups. The lean path leaves two amounts out of total_saved_usd: the historical prefix-cache savings (CachesplitHistorical.USD) and the declaration-filter credit (SetDeclCredit adds FilterUSD). On a deployment that uses either, the status line will show less than it did before and less than the dashboard does. The comment calls this "slightly conservative", but those amounts can be large. Either say so in the PR, or keep the cheap, session-scoped part of the declaration credit in the lean path.
  2. One docstring contradicts the PR's own diagnosis. In statusline.py, the _fetch_stats docstring says the three priced aggregates "measured 38-45s … and were the actual cause". The PR body and the test above both show the duplicate recomputes were the cause, not the queries.
  3. Minor: a hung proxy never shows as down. A deadlocked proxy (the kernel accepts the connection, nothing answers) shows "stats loading…" or stale figures, never cg!. Separately, a timeout during the connection attempt itself (rather than the read) reaches Python as URLError(reason=timeout), so the status line still shows cg!. Checking e.reason for socket.timeout/TimeoutError would close that. This is rare on loopback.

🤖 Generated with Claude Code

Three fixes from the repo owner's live-load-tested review of PR #403:

1. ?lean=1 (dash/api.go's statsLean) used to leave CachesplitHistorical.USD
   and the declaration-filter credit (FilterUSD) out of total_saved_usd, so
   the status line under-reported relative to the dashboard whenever either
   was nonzero. Both are now included. SelfRemovals' full-tenant scan over
   tool_declarations (the one call among /api/stats' four that is
   genuinely expensive at scale) is still skipped, but measurement showed
   that call was never part of total_saved_usd in the first place -
   dash/declcredit.go's SetDeclCredit folds SelfUSD into TotalReducedUSD
   only. So lean's total_saved_usd is now provably exact, not merely
   closer: TestStatsLeanTotalSavedMatchesFullHandler seeds both credits and
   asserts bit-for-bit equality between the lean and full handlers.

2. statusline.py's _fetch_stats docstring claimed the three priced
   aggregates "measured 38-45s ... and were the actual cause" of the
   timeouts. Measured on a copy of the affected deployment's DB, all four
   calls run in well under a second in isolation; the real cause was
   dash/api.go's jsonCache spawning an un-deduplicated refresh goroutine on
   every stale read (fixed in the prior commit). Docstring corrected.

3. _fetch_stats now also catches a CONNECT-phase timeout, which urlopen
   wraps as urllib.error.URLError(reason=socket.timeout(...)) rather than
   raising directly the way a read-phase timeout does - previously that
   shape fell through to the refused/down branch. And once a cached body
   is older than STALE_STATS_MAX_AGE_SECONDS and the proxy keeps timing
   out rather than resolving, the status line now renders a distinct
   "cg? not responding" instead of indefinitely repeating "stats
   loading...", which stopped being an honest description once there was
   a working proxy that had since gone silent for that long.

Tests: dash/jsoncache_refresh_test.go gains
TestStatsLeanTotalSavedMatchesFullHandler. context-guru-plugin/plugin_test.go
gains TestStatuslineTreatsAConnectPhaseTimeoutAsATimeoutNotDown (drives the
real _fetch_stats with a urlopen stub raising the exact URLError shape) and
TestStatuslineReportsNotRespondingOnceAStaleFetchHangsTooLong (real
subprocess run: primes the on-disk cache against a live stub, backdates it
past STALE_STATS_MAX_AGE_SECONDS - read from the script itself via a new
statslineConstInt helper, not retyped - then stalls the same port). All run
on the eval box (go vet, gofmt, go test ./dash/... -race, go test
./context-guru-plugin/... -run Statusline, full go test ./dash/...
./context-guru-plugin/...); the only non-passing tests are the two
pre-existing eval-box-environment failures already documented against this
branch (root-owned /usr/local/bin/context-guru-proxy short-circuiting
install detection) plus one unrelated flake (TestAProjectUninstallNever...,
a shared-box port/pidfile race) that passed cleanly on retry.

Assisted-By: Claude Sonnet 5 <[email protected]>
Signed-off-by: DAVID AMID <[email protected]>
@amiddavid

Copy link
Copy Markdown
Collaborator Author

Thanks for the live-load numbers — pushed fixes for all three.

1. lean=1 under-reporting savings. Fixed by including both amounts rather than documenting their absence: ?lean=1 now also runs CachesplitHistoricalUSD and DeclFilterSavings (the measured half of the declaration credit) and folds their USD into total_saved_usd, exactly like the full handler does. Only SelfRemovals (the self-removal half, needed for TotalReducedUSD, not TotalSavedUSD) is skipped — and measurement showed it was never part of total_saved_usd to begin with (dash/declcredit.go's SetDeclCredit only folds FilterUSD into that field; SelfUSD goes into TotalReducedUSD). So lean's total_saved_usd is now exact, not approximate — TestStatsLeanTotalSavedMatchesFullHandler seeds both credits and asserts the two handlers return the identical number.

2. Docstring contradicting the diagnosis. Fixed. _fetch_stats's docstring now says plainly that the duplicate-recompute bug (jsonCache's un-deduplicated refresh goroutine) was the cause, with the measured sub-second isolated cost of all four aggregate calls, and that lean=1 is a load reduction on top of that fix, not a substitute for it.

3. Connect-phase timeout and the hung-forever case. Both fixed:

  • _fetch_stats now also catches urllib.error.URLError whose .reason is a socket.timeout/TimeoutError — the shape a connect-phase timeout actually takes (wrapped, not raised directly) — and treats it as a timeout rather than falling through to the refused/down branch.
  • Once a cached body is older than STALE_STATS_MAX_AGE_SECONDS and the fetch meant to refresh it keeps timing out, the status line now renders cg? not responding — a new, distinct state — instead of repeating "stats loading…" forever. Still not cg!: this proxy is reachable, unlike a refused one.

New tests: TestStatuslineTreatsAConnectPhaseTimeoutAsATimeoutNotDown drives the real _fetch_stats with a urlopen stub raising the exact wrapped shape; TestStatuslineReportsNotRespondingOnceAStaleFetchHangsTooLong primes the on-disk cache against a live stub, backdates it past the cap (read from the script's own constant, not retyped), then stalls the same port and checks the new rendering end to end.

All run on the eval box: go vet, gofmt, go test ./dash/... -race, go test ./context-guru-plugin/... -run Statusline, and the full go test ./dash/... ./context-guru-plugin/... (clean except the two eval-box-environment failures already on this branch, and one unrelated flake that passed on retry).

@amiddavid

Copy link
Copy Markdown
Collaborator Author

Re-review of 5173d56: one small bug still open, then OK to merge

Summary

  • The new commit fixes all three findings from my first review.
  • The lean path now runs everything that feeds total_saved_usd. It skips only the expensive tenant-wide scan (SelfRemovals).
  • One gap is still open: lean and full still give different totals when one model has no price. The fix is one line.

How it was tested

On the eval box, at 5173d56:

  • go vet is clean.
  • go test -race ./dash/... passes.
  • go test ./context-guru-plugin/... -run Statusline passes.
  • CI is green: build-test, purego, trivy, DCO.

What we found

  1. The full handler adds the declaration-filter dollars (FilterUSD) to total_saved_usd in every case. SetDeclCredit does this.
  2. The lean path adds them only when filterSaving.Priced is true.
  3. Priced goes false if any one request in the scope uses a model with no price.
  4. So one request on an unknown model drops the whole declaration-filter credit from the status line.

I confirmed this on the box with a temporary test (now removed). It was a copy of TestStatsLeanTotalSavedMatchesFullHandler plus one filtered row on some/unmeasured-model:

full lean
total_saved_usd 0.544518 0.539958
decl_filter_usd 0.00456 0

The PR's own parity test does not catch this, because every model in its fixture has a price.

Proposal

  1. In the lean branch of dash/api.go, change if filterSaving != nil && filterSaving.Priced to if filterSaving != nil. This makes lean do the same as SetDeclCredit.
  2. Add an unpriced filtered row to TestStatsLeanTotalSavedMatchesFullHandler, so the test covers this case.

After that, the PR needs only an approving review. There are no conflicts with main.

🤖 Generated with Claude Code

The lean branch of dash/api.go gated the declaration-filter credit on
DeclFilterSaving.Priced before adding it to total_saved_usd. Priced goes
false the moment any ONE request in scope used an unpriced model, but USD
still holds the real dollar figure for the priced subset - SetDeclCredit
(dash/overview.go) adds FilterUSD to TotalSavedUSD unconditionally, so the
lean path disagreed with the full handler whenever an unpriced model
appeared anywhere in scope. Changed to add filterSaving.USD whenever
filterSaving is non-nil, matching SetDeclCredit exactly.

TestStatsLeanTotalSavedMatchesFullHandler now seeds a filtered row on
staticPricer's unpriced sentinel model ("some/unmeasured-model") alongside
the already-priced rows, so the parity assertion actually exercises this
case rather than passing because every model in the fixture had a price.

Found by a re-review of PR #403 (comment 6036833174), which measured the
gap directly: full total_saved_usd 0.544518 vs lean 0.539958 on a fixture
with one unpriced request.

Tests run on the eval box: go vet, gofmt, go test -race ./dash/...,
go test ./context-guru-plugin/... -run Statusline. All clean.

Assisted-By: Claude Sonnet 5 <[email protected]>
Signed-off-by: DAVID AMID <[email protected]>
@amiddavid

Copy link
Copy Markdown
Collaborator Author

We fixed the bug. The lean path and the full handler now agree, even with an unpriced model in scope.

The bug

  • The lean path checked filterSaving.Priced before it added the decl-filter credit.
  • Priced is false when one request in scope has no price.
  • But filterSaving.USD is still correct for the priced requests.
  • The full handler (SetDeclCredit) does not check Priced. It always adds FilterUSD.
  • So one unpriced request anywhere in scope dropped the WHOLE decl-filter credit from the lean path, not just its own share.

The fix

  • dash/api.go: removed the Priced check. The lean path now adds filterSaving.USD whenever filterSaving is not nil. This matches SetDeclCredit.

The test

  • TestStatsLeanTotalSavedMatchesFullHandler now seeds one filtered row on staticPricer's unpriced model (some/unmeasured-model).
  • Before this row, every model in the fixture had a price. The test passed, but it did not test the bug.
  • With this row, the test fails without the fix and passes with it.

Tests run on the eval box

  • go vet: clean.
  • gofmt: clean.
  • go test -race ./dash/...: pass.
  • go test ./context-guru-plugin/... -run Statusline: pass.

CI on this PR (build-test, purego, trivy, DCO): all green.

Commit: 1c0445d.

@amiddavid
amiddavid merged commit 43e61b5 into main Oct 7, 2026
4 checks passed
@amiddavid
amiddavid deleted the feat/statusline-stats-timeout branch October 7, 2026 13:11
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

1 participant