Repository navigation
fix(dash): rewrite CachesplitHistoricalUSD's correlated subquery as a window function - #127
Merged
Merged
Conversation
… window function split_stable_tokens = 0 AND cache_read > 0 matches 69% of requests, so the NOT EXISTS session-first check ran as a correlated subquery ~79k times instead of once. This is the same anti-pattern CompactionResets already fixed with a window function (see that comment) — ROW_NUMBER over the unfiltered table reproduces the identical "nothing earlier in this session" semantics in one sort. Measured against live production data: identical result set before and after (6,696 rows), 11.33s -> 0.89s. This query runs on every /api/stats call and was blowing Prometheus's /metrics scrape timeout under the same contention, which is what had Grafana reporting the service as down. Signed-off-by: Osher-Elhadad <[email protected]>
OsherElhadad
added a commit
that referenced
this pull request
Aug 30, 2026
… once per tenant (#128) The Prometheus exporter calls CachesplitHistoricalUSD once per tenant to build the per-tenant metric series. Each call's ROW_NUMBER window (the #127 fix) ranks the WHOLE unfiltered requests table to stay correct, so calling it N times re-sorted that same table N times over -- 19 tenants at ~0.8s a sort, every scrape. Adds CachesplitHistoricalUSDByTenant: one query, tenant kept only as an outer grouping key (never part of the session-first ranking, so grouping afterward changes nothing about the answer -- covered by a new test asserting per-tenant equivalence with the existing single-tenant call). tenantMetricsAdapter.TenantMetrics now calls it once instead of looping. Measured against live production data: identical grouped results, ~14.5s (19 sequential sorts) -> ~0.81s (one sort, all tenants). Signed-off-by: Osher-Elhadad <[email protected]> Co-authored-by: Osher-Elhadad <[email protected]>
OsherElhadad
added a commit
that referenced
this pull request
Aug 30, 2026
…lified value view (#131) * fix(dash): bound the SQLite connection pool sql.Open never set SetMaxOpenConns/SetMaxIdleConns, so database/sql's default (unbounded) pool let concurrent dashboard/metrics traffic open one connection per in-flight request. modernc.org/sqlite is pure Go -- unlike a CGO sqlite3 build, connections don't share an mmap'd page cache, so each one carries its own in-heap page cache and VDBE state. Measured on the live deployment: ~600 concurrent connections, cgroup memory climbing 2.15GiB -> 3.86GiB in 15 minutes, three unrecoverable Go runtime OOM crashes today. The two recent query-latency fixes (#127, #128) made /api/stats and /metrics fast enough that more concurrent load now reaches the DB layer, which took this pre-existing unbounded pool from latent to actively crashing the process. Caps at 20 open / 10 idle, with a 5-minute idle timeout so an over-provisioned burst gets reclaimed once traffic quiets. WAL mode already gives every reader a consistent snapshot without needing a dedicated connection to get it quickly, and the writer is a single periodic flush, not one connection per request, so this bounds the real leak without starving real concurrency. Signed-off-by: Osher-Elhadad <[email protected]> * fix(dash): bound the dashboard/metrics HTTP handlers, and attribute keep-alive credit to the strategy that earned it Two independent fixes, both closing gaps the connection-pool bound (previous commit) left open: - /api/stats, /api/facets, and /metrics now run under a 10s http.TimeoutHandler, matching Prometheus's own scrape_timeout. The bounded pool means a burst past it now queues for a connection instead of growing unbounded -- better than the OOM crash it replaces, but a queued request needs a fast, clear timeout rather than hanging the caller indefinitely. Also updates the now-stale comment on kvcache.go's own concurrency semaphore, which cited the pool being unbounded as its rationale. - keeper.arrive (proxy/keepalive.go) had e.appliedStrategy in scope at the exact moment a real request reports what its idle span's pings did, and threw it away. Threading it through (dashcapture.go, then onto the credited row via the existing keepalive_strategy_id column -- already additive, no schema bump) means a credited request now carries the same strategy id its rescuing ping did. dash/keepalivestrategy.go's per-strategy SavedUSD can now filter on it directly instead of reporting a tenant's whole lifetime credit under every strategy that ever touched them. Verified against live production data: 78 credited rows / $129.57 historical, currently zero attributed (expected -- this column is never backfilled, so historical credit stays unattributed and only new credits going forward carry a strategy id). Signed-off-by: Osher-Elhadad <[email protected]> * feat(dash): keep-alive latency diagnostic, batched per-tenant metrics, and a simplified value view Three changes toward one goal: showing the real value of context-guru without ten minutes of reading. - KeepAliveLatencyDiagnostic reuses kvcache.MeasureLatency's exact shape (mean per cohort, N>=20 gate, Known=false rather than a fabricated number) to report how much faster a large-context (100K+ combined tokens) request ran on a cache hit than a cache write. Below that size the comparison runs backwards on this deployment's real traffic (confounded by request kind, not measured mechanism) -- verified live, so it is gated out rather than shown. Surfaced on both the Overview and Keep-alive tabs. Exports kvcache.LatencyMinN (was private) so the two packages can't drift on what "enough samples" means. - Two new per-tenant dollar figures for the Prometheus exporter -- keep-alive net and the declaration filter's saving -- computed as ONE grouped query each (KeepAliveNetUSDByTenant, DeclFilterSavingsByTenant) rather than one query per tenant. The Grafana "Total avoided this month" panel was missing these two of its formula's four terms because promexport emitted neither, for any tenant; its query now matches Overview's own total_saved_usd term for term. - Overview gets one small "Where the value comes from" group (every component that ran, plus keep-alive and the declaration filter -- the two real levers that aren't components) right below the existing headline total, and the token-accounting/amortization/ billed-tier/streaming groups collapse into one Diagnostics <details> -- real and still one click away, just not at the same weight as "is this worth it". Verified against live production data: decl-filter batched query matches its per-tenant equivalent exactly; keep-alive net batched query matches KeepAliveLedger's own net per tenant; the large-context latency population (52,129 hits vs 3,375 writes right now) is well over the sample-size gate. Signed-off-by: Osher-Elhadad <[email protected]> * fix(dash): cover /api/components with the handler timeout; fix an unpriced-display bug in the new value-breakdown tile Two follow-ups from independent review of this branch's prior commit: - /api/components has the same filter-keyed cache and per-row valuation shape as /api/stats and /api/facets (DecomposeComponentSavedUSD, EstimateComponentSavedUSD) but wasn't wrapped in the handler timeout. Now covered by the same dashHandlerTimeout. - The new "Where the value comes from" panel's declaration-filter tile always rendered usd(o.decl_filter_usd), with no fallback for the unpriced case -- unlike the existing Cost group's own decl-filter tile. An unpriced model could have shown "$0.00" for a real, just-unpriced saving. Now falls back to the token count, matching the existing tile. Also documents, on dashHandlerTimeout itself, what the timeout handler actually does and doesn't do: Overview() and Facets() run on plain d.sql.Query (context.Background()), so canceling the request context does not cancel the in-flight query or release its pooled connection early -- a caller gets a fast, honest timeout; a genuinely stuck query's backend pressure is not relieved by this alone. Threading context through those call sites is a larger, separate change, not done here. Signed-off-by: Osher-Elhadad <[email protected]> --------- Signed-off-by: Osher-Elhadad <[email protected]> Co-authored-by: Osher-Elhadad <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What
CachesplitHistoricalUSD(dash/cachehistory.go) used a correlatedNOT EXISTSsubquery to find each session's first request. The outer filter(
split_stable_tokens = 0 AND cache_read > 0) matches 69% of therequeststable, so SQLite ran that subquery ~79k times instead of once. Rewritten as
a window function (
ROW_NUMBER() OVER (PARTITION BY session_id ORDER BY ts, id)), the same fix already applied toCompactionResetsfor the identicalanti-pattern.
Why this matters in production
This query runs on every
/api/statscall. Under load it was taking 11+seconds, which:
/api/statsproxy timeout, showing the dashboard asempty/erroring for real users
/metricsscrape timeout (contending with the same DB),which is why Grafana has been reporting
context-guruas down most ofthe time even though the process itself was up
Verification
TestHistoricalSplitValuationIsReadOnlyAndConservative(existing test,covers the session-first-vs-mid-session distinction this query depends
on) passes unchanged.
make lint && make testclean.read-only: identical result set (6,696 rows, byte-for-byte equal),
11.33s -> 0.89s.
Not in this PR
Root-cause investigation also found unbounded
requests/tool_declarationsgrowth (retention disabled 2026-08-22 to work around an unrelated
tool_declarationsdedup bug) contributing WAL bloat under load. That's aseparate fix, tracked separately — this PR is scoped to the query rewrite.