Repository navigation
fix(dash,plugin): stop statusline cg! on slow stats, dedupe cache refresh - #403
Conversation
…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]>
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): Live load testI built a test dashboard DB (9,000 requests, 12,000
The same queries take 0.04–0.13s when run one at a time. This confirms the diagnosis: on Status line against the real proxy
Findings
🤖 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]>
|
Thanks for the live-load numbers — pushed fixes for all three. 1. 2. Docstring contradicting the diagnosis. Fixed. 3. Connect-phase timeout and the hung-forever case. Both fixed:
New tests: All run on the eval box: |
Re-review of
|
| 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
- In the lean branch of
dash/api.go, changeif filterSaving != nil && filterSaving.Pricedtoif filterSaving != nil. This makes lean do the same asSetDeclCredit. - 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]>
|
We fixed the bug. The lean path and the full handler now agree, even with an unpriced model in scope. The bug
The fix
The test
Tests run on the eval box
CI on this PR (build-test, purego, trivy, DCO): all green. Commit: |
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_statsrenderedcg!on ANYURLError/OSError, including a plainTimeoutError. A diagnostic capture against the user's live, healthy v0.4.2 proxy caught ~10 of these in 10 minutes, every one aTimeoutErrorat exactly the 0.6s client cutoff with the proxy never actually down. It now distinguishes refused/unreachable (stillcg!) 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 printscg: stats loading…instead of claiming the proxy is down.dash/api.go (the real slowness):
jsonCache.serveJSONstarted a brand-newgo 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/statscall 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.jsonCachenow gates refreshes withbeginRefresh/endRefreshso only the first stale reader for a key starts one, andload()keeps serving that key's (otherwise too-old) body while its refresh is in flight — a reader arriving pastdashCacheTTL+dashCacheStaleis 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'sstatsLean) answers fromOverview()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 overtool_declarationsregardless of the session filter.statusline.pynow always requests it.Test plan
Run on the eval box (
gois not installed locally; see repo CLAUDE.md).go vet ./dash/...— cleango 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— passgo test ./context-guru-plugin/... -run Statusline— pass, including the correctedTestStatuslineReportsLoadingNotDownOnATimeout(previously assertedcg!on an accept-and-stall port; now asserts the loading state, since that shape is indistinguishable from a merely-slow healthy proxy) and the newTestStatuslineServesStaleStatsOnATimeoutRatherThanLoadinggo 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-proxyshort-circuiting install detection — documented, unrelated to this changegofmt -lon every touched file — cleanFollow-ups
SelfRemovals(dash/toolapi.go) scanstool_declarationsfor the whole tenant regardless ofFilter.Session— correct for its own self-removal-detection semantics (it is inherently a cross-session signal), but it means a session-scoped full/api/statscall still pays for a tenant-wide scan. The newlean=1path 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/statsis still slow after this.🤖 Generated with Claude Code