Skip to content

fix(dash): compute CachesplitHistoricalUSD once for every tenant, not once per tenant - #128

Merged
OsherElhadad merged 1 commit into
mainfrom
fix/cachesplit-tenant-batch
Aug 30, 2026
Merged

OsherElhadad merged 1 commit into
mainfrom
fix/cachesplit-tenant-batch

Conversation

@OsherElhadad

Copy link
Copy Markdown
Collaborator

What

Follow-up to #127. That PR fixed CachesplitHistoricalUSD's correlated
subquery for the /api/stats (whole-deployment) case, but the Prometheus
exporter (/metrics) calls it once per tenant in a loop
(cmd/context-guru-proxy/main.go's tenantMetricsAdapter.TenantMetrics).
Each call's ROW_NUMBER() window ranks the whole unfiltered requests
table to stay correct — necessary, not a bug — so calling it 19 times
(one per tenant on this deployment) re-sorted that same table 19 times
over, every single scrape.

Adds CachesplitHistoricalUSDByTenant: one query, tenant_id kept only
as an outer grouping key. It's never part of the session-first ranking
itself, so grouping the qualifying rows by tenant afterward changes
nothing about the answer for any individual tenant — that equivalence is
exactly what the new test asserts (grouped result vs. calling the
existing single-tenant CachesplitHistoricalUSD per tenant).
tenantMetricsAdapter.TenantMetrics now calls it once instead of
looping.

Why this matters in production

After #127 deployed, /metrics was still timing out (confirmed live:
calls ran 90+ seconds with zero bytes returned). Restructuring the
per-tenant loop into one query cuts this specific cost from ~14.5s (19
sequential full-table sorts) to ~0.81s (one sort). This does not by
itself explain the full observed hang — there is a separate, larger,
already-flagged contributor (WAL checkpoint starvation under concurrent
load, from retention having been disabled since 2026-08-22) that this PR
does not address — but it removes a real, measured, redundant cost from
the hot path every 15s scrape pays.

Verification

  • New test TestHistoricalSplitValuationByTenantMatchesPerTenant:
    asserts the grouped call returns, per tenant, exactly what the
    existing single-tenant call would, across two tenants with a
    multi-request session each (the exact case that would break if
    grouping leaked one tenant's rows into another's, or let a
    mid-session row through).
  • go test ./dash/... and go vet ./... clean.
  • Ran the batched query against the live production DB, read-only,
    compared against the old per-tenant-call query for every tenant with
    qualifying rows: identical result sets. Timed: ~14.5s (per-tenant
    loop) -> ~0.81s (batched).

… once per tenant

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]>
@OsherElhadad
OsherElhadad merged commit 098ba36 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
…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