Repository navigation
perf(dash): cut all-time dashboard endpoint latency 3-25x, same numbers - #445
Conversation
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]>
|
Reviewer: approved. CI all pass (build-test 11m41s); go test ./dash ./kvcache green; gofmt and go vet clean. Checked:
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). |
|
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).
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 |
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.3Mtool_declarations), one client, fresh process, OS page cache warm, gateway price list loaded./api/stats(Overview)/api/components/api/tools/api/toolfilter/api/prompt/api/kvcache/simulate/api/kvcache/suggest/api/kvcache/suggest/holdout/api/kvcache/api/kvcache/rows/api/kvcache/pricing/api/keepalive/api/keepalive/behaviour/api/keepalive/calc/api/keepalive/recommend/api/keepalive/sessions/api/keepalive/live/api/sessions?limit=500/api/components/compaction-episodes/api/series?bucket=3600000"Before" is the same binary with the handler time bounds removed (shipped, with the 10 s/45 s bounds,
tools,simulate,suggestandholdoutreturn 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/serieswith nobucketused 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)
requestsfor five breakdowns and four sortedOFFSETreads for two p95s and two medians; the components tab joinedrequest_componentstorequeststhree times. Each is now one read, re-grouped in Go with the same rank rule.json_eachover 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 tojson_each.tool_declarationsonce 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).BudgetPolicy.Windowsrebuilt 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.cachedRoute) with the heavy handler bound./api/promptcaches the unstripped view and applies the per-address content strip to each reader's own copy, so nothing address-dependent is shared (TestPromptPartsAreStrippedForAnUntrustedCallerreads trusted then untrusted inside the TTL).journal_mode(WAL)ran beforebusy_timeout, so a connection opened while the WAL was busy failed immediately withSQLITE_BUSY; the fan-out reads open bursts of connections, sobusy_timeoutis now first.Verification
TestGoldenEndpointscompares 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 withCG_GOLDEN_UPDATE=1on the old code.perf_equivalence_test.gopins 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 vsjson_each, the series bucket cap, and the DSN order.go test ./...,go vet,gofmtclean;go test -raceclean on the tests of every touched area (golden, equivalence, components, tools, prompt, keep-alive, overview, KV).Review notes
/api/stats) is 6.1 s cold. Its remaining cost is about ten independent statements overrequests(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_sizemeasured 20-25% faster but I left it out because of the SIGBUS-on-truncate risk with the incremental-vacuum prune./api/statsand/api/componentsalready were.