Skip to content

perf(dash): cut all-time dashboard endpoint latency 3-25x, same numbers - #445

Merged
amiddavid merged 1 commit into
mainfrom
perf/dashboard-endpoints
Oct 12, 2026
Merged

amiddavid merged 1 commit into
mainfrom
perf/dashboard-endpoints

Conversation

@OsherElhadad

@OsherElhadad OsherElhadad commented Oct 11, 2026 •

Copy link
Copy Markdown
Collaborator

What

Every heavy dashboard endpoint on the all-time window is faster, with the same numbers. Measured on a 3.6 GB snapshot of a production database (187,312 agent requests, 1.76M request_components, 2.3M tool_declarations), one client, fresh process, OS page cache warm, gateway price list loaded.

endpoint (all-time) before, cold after, cold (median of 3) after, repeat (p95, n=12)
/api/stats (Overview) 12.2 s 6.1 s 0.01 s
/api/components 20.1 s 4.7 s 0.01 s
/api/tools 14.4 s 3.6 s 0.01 s
/api/toolfilter 21.4 s 3.7 s 0.01 s
/api/prompt 20.8 s (every call) 2.6 s 0.01 s
/api/kvcache/simulate 52.3 s (every call) 3.2 s 0.01 s
/api/kvcache/suggest 45.6 s (every call) 2.1 s 0.01 s
/api/kvcache/suggest/holdout 46.2 s (every call) 4.0 s 0.01 s
/api/kvcache 4.9 s (every call) 2.0 s 0.01 s
/api/kvcache/rows 4.4 s (every call) 2.1 s 0.01 s
/api/kvcache/pricing 2.9 s 0.35 s 0.01 s
/api/keepalive 4.4 s (every call) 4.0 s 0.01 s
/api/keepalive/behaviour 5.6 s (every call) 4.5 s 0.01 s
/api/keepalive/calc 4.4 s (every call) 3.6 s 0.01 s
/api/keepalive/recommend 4.3 s (every call) 3.5 s 0.01 s
/api/keepalive/sessions 2.8 s 2.6 s 0.01 s
/api/keepalive/live 2.1 s (every call) 0.01 s 0.01 s
/api/sessions?limit=500 2.2 s (every call) 2.1 s 0.01 s
/api/components/compaction-episodes 1.7 s (every call) 1.7 s 0.01 s
/api/series?bucket=3600000 0.8 s 0.9 s 0.01 s

"Before" is the same binary with the handler time bounds removed (shipped, with the 10 s/45 s bounds, tools, simulate, suggest and holdout return 503 on this data). "Cold" is the first request after a process start; "repeat" is the response cache. 25 of the 29 endpoint payloads are byte-identical to the pre-change ones on the snapshot; the other four differ only in the last float bit (summation order: components, tools) or in a live field (DB size, server clock). /api/series with no bucket used to be 12.9 MB (78,000 one-minute buckets); it is now widened to a whole multiple that fits 2,000 buckets, which is the one intended difference (default-bucket body: 585 KB, 1,073 buckets of 40 min; the UI's hourly request is unchanged).

Why it was slow (each fixed where it lived)

  • Correlated subqueries. The replay-ceiling count and the ping-inflation sum ran one index walk per saving/ping row (11 s + 4 s inside Overview). Both are window functions now (1.3 s + 1.2 s), over only the sessions that need them. The keep-alive behaviour panel re-ran its LAG CTE once per account to get a median.
  • Repeated passes. Overview made five GROUP BY passes over requests for five breakdowns and four sorted OFFSET reads for two p95s and two medians; the components tab joined request_components to requests three times. Each is now one read, re-grouped in Go with the same rank rule.
  • json_each over 945k gate/event strings (allocation-bound, 7 us a row, only 2.7x on eight cores). Summed in Go when every row is a flat integer object (all the recorder writes); any other shape falls back to json_each.
  • The Inventory probed tool_declarations once per in-scope session (about 1,000 rows each, 11 s) or sorted all 2.3M rows. A broad scope now makes one concurrent pass over the table and reduces it in Go; a narrow scope keeps the probe. No new index (building one takes ~40 s of start-up downtime on this corpus).
  • KV-cache. Every route rebuilt the same window-function dataset (4.5 s): unbounded reads are split in four shards of whole sessions; the count and the median prefix skip the window when nothing narrows on a derived column. BudgetPolicy.Windows rebuilt the reuse model's curve 4n times per decision (25 of the 29 s of a simulate); it builds it once, with a doc comment on why the removed early exit could not change a read. Suggest cells and simulate arms are independent and run side by side.
  • No response cache on the remaining heavy routes, which the UI re-reads on every tab switch. They use the existing stale-while-revalidate singleflight cache (cachedRoute) with the heavy handler bound. /api/prompt caches the unstripped view and applies the per-address content strip to each reader's own copy, so nothing address-dependent is shared (TestPromptPartsAreStrippedForAnUntrustedCaller reads trusted then untrusted inside the TTL).
  • DSN pragma order. journal_mode(WAL) ran before busy_timeout, so a connection opened while the WAL was busy failed immediately with SQLITE_BUSY; the fan-out reads open bursts of connections, so busy_timeout is now first.

Verification

  • TestGoldenEndpoints compares 28 endpoint payloads, number for number (relative 1e-9 on floats), to files recorded from the code before this change on a deterministic fixture (60 sessions, 3 models, pings, TTL expiries, a gate row the fast parser must refuse). Regenerate with CG_GOLDEN_UPDATE=1 on the old code.
  • perf_equivalence_test.go pins each rewritten read to the one it replaced: table pass vs per-session probe (report, windows, prompt), sharded vs single-statement KV dataset (including over the cap), Go counter parser vs json_each, the series bucket cap, and the DSN order.
  • go test ./..., go vet, gofmt clean; go test -race clean on the tests of every touched area (golden, equivalence, components, tools, prompt, keep-alive, overview, KV).

Review notes

  • Not under 5 s: Overview (/api/stats) is 6.1 s cold. Its remaining cost is about ten independent statements over requests (three of them window functions of ~1.3 s each) that do not scale across cores in the pure-Go SQLite driver (allocation-heavy statements contend: ten concurrent ones run ~1.8x slower each than alone); PRAGMA mmap_size measured 20-25% faster but I left it out because of the SIGBUS-on-truncate risk with the incremental-vacuum prune.
  • CPU/memory: cold computations are bursts of up to ~16 concurrent reads (the pool allows 100); they are singleflight-collapsed and cached, and the KV routes keep their two-slot memory gate. The response cache holds up to 256 bodies (largest ~1 MB) before it resets.
  • Staleness: the newly cached routes can be up to dashCacheTTL+stale (60 s) old, same as /api/stats and /api/components already were.
  • Not deployed; no schema or config change.

Measured on a 3.6 GB snapshot of a production database (187k requests,
1.76M request_components, 2.3M tool_declarations), one client, fresh process,
all-time window. Before: Overview 12 s, /api/components 20 s, the Inventory
reads 14-21 s, the KV-cache replays 46-52 s, /api/prompt 21 s, the keep-alive
reads 4-6 s, and /api/series answered its default bucket with 12.9 MB. After,
cold: every endpoint 0.4-4.7 s except Overview at 6.1 s; repeated reads of
any endpoint 10-20 ms. Every number is unchanged (see the tests below).

Root causes, each fixed where it lived:

* Correlated subqueries and per-account re-runs. The replay-ceiling count and
  the ping-inflation sum ran one index walk per saving/ping row (11 s + 4 s);
  both are window functions now, over only the sessions that need them. The
  keep-alive behaviour panel re-ran its LAG CTE once per account for a median;
  it reads every account's gaps once. The keep-alive ledger, calculator and
  recommendation ran 4-6 independent full passes back to back; they run
  together.
* Five passes over requests for five GROUP BYs, and four sorted OFFSET reads for
  two p95s and two medians: one grouped read and one value read each, re-grouped
  and ranked in Go with the same rank rule.
* The components tab joined request_components (1.7M rows) to requests three
  times for the rows and the two read-time valuations, plus json_each over 945k
  gate/event strings (allocation-bound: 7 us a row, 2.7x on eight cores). One
  join at the finest grain feeds the rows and both valuations; the counters are
  summed in Go from the raw JSON when it is a flat integer object (anything else
  falls back to json_each); the join is read in eight id slices side by side.
* The Inventory reads probed tool_declarations once per in-scope session
  (~1,000 rows each, 11 s) or sorted all 2.3M rows. A broad scope now makes one
  concurrent pass over the table and reduces it in Go; a narrow scope keeps the
  probe. The report and the observation windows share the pass.
* Every KV-cache read rebuilt the same window-function dataset (4.5 s). An
  unbounded read is split in four shards of whole sessions (exact: a session
  never straddles two); a time-bounded one stays a single statement (sharding it
  repeats the index lookups per shard and measured slower). The row count and
  the median prefix skip the window when nothing narrows on a derived column.
* BudgetPolicy.Windows asked the reuse model for 4n points and the model rebuilt
  its whole curve for each (25 of the 29 s of an all-history simulate). It
  builds it once per observation and reads it 4n times; the early exit it
  replaces could not change a read (documented at reuseCurve). The policy
  remembers its last answer, which Simulate asks for twice per request. Suggest
  cells and simulate arms are independent replays and run side by side.
* /api/series answered the route's one-minute default bucket over all history
  as 78,000 buckets; it is widened to a whole multiple that fits 2,000 buckets
  (the UI's hourly request is unchanged: 1,305 buckets).
* The remaining heavy GET routes had no response cache and the UI reads them on
  every tab switch. They go through the existing stale-while-revalidate
  singleflight cache (cachedRoute), with the heavy handler bound so the first
  reader after a restart waits for the real work. /api/prompt caches the
  UNSTRIPPED view and applies the per-address content strip to each reader's own
  copy, so nothing that depends on the address is shared.
* The DSN ran journal_mode before busy_timeout, so a connection opened while the
  WAL was busy failed at once with SQLITE_BUSY; the fan-out reads open bursts of
  connections, so busy_timeout now comes first.

No schema change and no new index: the pass over tool_declarations replaces the
index a faster GROUP BY would have needed, and building one costs ~40 s of
start-up downtime on this corpus.

TestGoldenEndpoints pins 28 endpoint payloads, number for number (relative
1e-9 on floats), to files recorded from the code before this change.
perf_equivalence_test.go pins each rewritten read to the one it replaced.

Signed-off-by: Osher-Elhadad <[email protected]>
@OsherElhadad

Copy link
Copy Markdown
Collaborator Author

Reviewer: approved. CI all pass (build-test 11m41s); go test ./dash ./kvcache green; gofmt and go vet clean.

Checked:

  • Golden test is genuinely from the old code: I copied golden_endpoints_test.go and testdata/golden onto a clean origin/main worktree and TestGoldenEndpoints passes there too, so the 28 payloads match pre-change behaviour (not a self-fulfilling recording).
  • Cache tenancy: cachedRoute keys on path + cacheKey(principal, query) = TenantID, Manager flag and the full query (so a manager's ?tenant= is in the key); since/until are bucketed to the 30 s TTL as before. I probed 11 newly cached routes (/api/sessions, series, breakdown, keepalive*, kvcache*, compaction-episodes) with a header-driven principal, a / b / a on the same query: no cross-tenant bodies. None of the cached handlers read the peer address (a.trusted is only used by transcript/request/config/prompt, none cached), so no address-dependent output is shared. /api/prompt caches the unstripped view and strips per reader, as the PR says.
  • TTL vs work: TTL 30 s + stale 30 s against measured cold 0.4-6 s, heavy bound 45 s, detached compute bound 2 min with singleflight. This is the opposite of the 2026-09 outage pattern (the bound is above the work). Residual risk: a slower production box (the PR numbers are warm page cache on a snapshot) could push Overview past 6 s, still well under the bounds.
  • Memory/concurrency: bursts of up to ~16 concurrent reads, cache reset past 256 entries (the existing cheap bound; an authenticated user can churn it with distinct queries, same as before). Acceptable.

Non-blocking: cachedRoute drops handler headers on non-200 answers and the cache is not tenant-bucketed for eviction; fine for now.

Ordering: #443 (UI) and #442 merge cleanly with this branch. #441 CONFLICTS with it in dash/api.go (spendCache field next to the new routeCache/promptCache fields, and the routeBounds map); trivial, but whichever of #441/#445 merges second needs a rebase. Suggest #445 first. Also consider adding /api/spend/explain to the cachedRoutes set after #441 lands (it already has its own spendCache).

@OsherElhadad

Copy link
Copy Markdown
Collaborator Author

Post-merge verification (this merged while I was running it; the result is the same either way).

Same numbers, on real data. I copied a production snapshot database (reflink copy, 187k requests, 1.76M component rows, 2.3M tool declarations), served it through the unchanged HTTP handlers of origin/main and of this branch, and diffed every changed endpoint's JSON (floats to 1e-9 relative): 29 requests covering stats (plain, lean, windowed), series (hour, day), breakdown (model, agent), facets, sessions, components, compaction episodes, all five keep-alive reads, tools (all-time and windowed), toolfilter, prompt and all eight KV-cache reads (rows, sorted rows, simulate, pricing, suggest, holdout, has_next).

  • 28 of 29 bodies are identical.
  • The one difference is the intended one: /api/series with no bucket now returns 1,073 buckets of 40 min instead of 24,849 one-minute buckets. Summed over buckets, requests, every token column, cost, saved and cache counters are equal (cost columns agree to 1e-12). Only the per-bucket averages differ, as they must when buckets are wider.

Latency, same copy, fresh process per endpoint, first request (cold), main vs branch, seconds. The host was heavily loaded (load average 30-130 from other jobs, my runs at nice 10), so absolute values are 2-5x worse than the idle numbers in the PR text; the ratio is what to read. stats 25.8 vs 9.5 (second run, idle-er), stats lean 21.7 vs 9.2, stats windowed 8.4 vs 7.0, breakdown by model 31.7 vs 4.1, components 85 vs 33, compaction episodes 123 vs 9.4, tools 395 vs 125, toolfilter 63 vs 8.2, prompt 46 vs 27, KV-cache 9.3 vs 4.5, rows 7.8 vs 4.0, simulate 13.7 vs 5.9, pricing 4.4 vs 1.4, suggest 13.7 vs 5.0, holdout 46 vs 11.8. Unchanged within noise: series (hour/day), breakdown by agent, facets, sessions, keep-alive reads (1.0-1.4x). A repeated read on the branch is 0-5 ms (response cache); on main it costs the same as the first. Every endpoint answered 200 on both sides, no timeout was needed.

Review notes. I rebased locally onto the then-current main to check the dash/query.go conflict (a new billed column scan against this PR's second return value): resolved by taking main's column and keeping this PR's three-value return; golden payloads needed regenerating for four endpoints that main had changed (two extra breakdown dimensions, the 270 s / K=2 keep-alive default) — main's own regeneration (b8e30ac) covers that, and TestGoldenEndpoints passes on current main. Under heavy host load I saw sporadic SQLITE_BUSY (first request after opening a copy, on main too, and in a full-package run of the dash tests; the failing tests all pass when rerun alone) — worth knowing if the dashboard is ever read while the box is saturated, not a regression of this PR.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ready-to-merge Program PR approved by the reviewer, CI green; needs maintainer approval

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

2 participants