Skip to content

fix(dash): rewrite CachesplitHistoricalUSD's correlated subquery as a window function - #127

Merged
OsherElhadad merged 1 commit into
mainfrom
fix/cachesplit-historical-window-fn
Aug 30, 2026
Merged

OsherElhadad merged 1 commit into
mainfrom
fix/cachesplit-historical-window-fn

Conversation

@OsherElhadad

Copy link
Copy Markdown
Collaborator

What

CachesplitHistoricalUSD (dash/cachehistory.go) used a correlated NOT EXISTS subquery to find each session's first request. The outer filter
(split_stable_tokens = 0 AND cache_read > 0) matches 69% of the requests
table, 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 to CompactionResets for the identical
anti-pattern.

Why this matters in production

This query runs on every /api/stats call. Under load it was taking 11+
seconds, which:

  • blew nginx's /api/stats proxy timeout, showing the dashboard as
    empty/erroring for real users
  • blew Prometheus's /metrics scrape timeout (contending with the same DB),
    which is why Grafana has been reporting context-guru as down most of
    the 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 test clean.
  • Ran both the old and new SQL directly against the live production DB,
    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_declarations
growth (retention disabled 2026-08-22 to work around an unrelated
tool_declarations dedup bug) contributing WAL bloat under load. That's a
separate fix, tracked separately — this PR is scoped to the query rewrite.

… 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
OsherElhadad merged commit fce1700 into main Aug 30, 2026
4 checks passed
@github-project-automation github-project-automation Bot moved this from New/ToDo to Done in Rossoctl Issue Prioritization Aug 30, 2026
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]>
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