Repository navigation
fix(dash): scope session-filtered lean queries to the session, not the table - #498
Conversation
…e table Overview()'s per-session aggregates — the replay ceiling, its keep-alive inflation correction, and CompactionResets — ran their window-function CTEs over every session's rows, not just the one the caller asked about, because PARTITION BY session_id was wrongly assumed to need the whole table. CachesplitHistoricalUSD's ROW_NUMBER ranking had the same shape. A session's window values never depend on another session's rows, so each query is scoped to the caller's own session when one is given. The replay ceiling also moves back to a correlated subquery when scoped: measured against a real 262 MB / 12.4k-request deployment, the window form stayed slow (3.6-4.8s) even once narrowed to one session's rows, where the correlated form over the session index took 165ms for an identical result. Verified byte-identical results against the unscoped form on five real sessions (132-5,723 requests), and added a regression test that runs EXPLAIN QUERY PLAN against the exact statements Overview() executes, so a future change that reintroduces an unscoped scan fails the test rather than only showing up at scale. Fixes the issue in #492: a single busy session made /api/stats?lean=1&session=<id> — the call the status line waits on — run for minutes instead of milliseconds, sometimes never completing within the server's 45s ceiling. Closes #492 Assisted-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
amiddavid
left a comment
There was a problem hiding this comment.
Verdict
Approve. The session-scoped numbers are identical to main, the no-filter path is unchanged, and the session id is always a bound parameter. The tests have gaps (finding 1). I suggest a small follow-up commit for them, but they do not block the release. One defect is in main already and this PR does not change it (finding 2). It needs its own issue.
What I ran
All runs were on the eval box, on the PR head da84035. I made no live test.
-
go test -race -count=1 ./dash/...: pass (293 s). -
go test -race -count=1 ./proxy/...: pass (403 s). -
Old SQL against new SQL (box only, not committed). I copied the pre-PR queries from
origin/maininto a probe test. The fixture had 1,500 rows: 3 tenants that share the same 4 session ids, manytsties, interleaved sessions, pings, split rows andcache_read = 0rows. I compared the replay ceiling after the keep-alive correction (ReplayProjectedTokens),CompactionResetsand the cachesplit row set. I used 160 filters: session "" plus 4 sessions, x tenant "" / t1 / t2 / TenantAll, x 4 since/until windows, xWithKeepAliveon and off. All 160 are identical. In 32 of them, all four values are non-zero. -
I reverted parts of the fix on the box copy and ran the 3 new tests each time:
Change on the box New tests M1: CompactionResetsCTE not scopedfail (EXPLAIN test, SCAN r USING INDEX idx_requests_session)M2: replay ceiling back to the window form fail (EXPLAIN test, SCAN s)M3: keep-alive correction ( before) CTE not scopedpass M4: CachesplitHistoricalUSDrnCTE not scopedpass M5: correlated count ignores pings ( AND p.keepalive = 0)pass. My probe fails, so the number does change M7: prevCTE also drops pings (AND r.keepalive = 0)pass. My probe fails -
Not verified: a mutation that removes the
(p.ts = r.ts AND p.id > r.id)tie-break. My script did not apply it. The probe has many ties and shows that the shipped form matches the window form. -
Not verified: any timing. I did not use the user's database.
Findings, most severe first
1. The tests protect the speed of 2 of the 4 queries, and none of the numbers (medium, confirmed by the reverts above)
dash/overview_session_scope_test.go:39: the "matches table-wide" test compares the new code with itself, before and after it adds rows to other sessions. WithPARTITION BY session_id, other sessions can never change the result, before the PR or after it. So the test cannot fail when the scoping changes a number. M5 and M7 change real numbers, and the test passes. Also, every other-session row is later in time than the target's rows, and all rows have one tenant. So the test never puts other sessions' rows between the target's rows, and never puts two tenants on one session id.dash/overview_session_scope_test.go:127: the EXPLAIN test checks onlyreplayCeilingQueryandcompactionResetsQuery. The keep-alive correction (dash/overview.go:839-856) and thernCTE indash/cachehistory.go:107-117are still inline SQL. If someone reverts their scoping, no test fails (M3, M4).- Suggestion: put the expected values in the fixture as constants (replay ceiling, inflation, resets, split rows). Put other sessions' rows between the target's rows and include a second tenant on the same session id. Move the
beforeandrnSQL into builders like the other two, and add them to the EXPLAIN map. - Planner wording: the patterns at
:160match the currentmodernc.org/sqliteoutput (SCAN r USING INDEX …,SCAN s). SQLite older than 3.36 wroteSCAN TABLE requests AS r. That form contains none of the patterns, so the test would pass without a check. The driver version is pinned, so the risk is low. A check that fails when noSEARCH … session_id=?line is present would be more robust.
2. Tenant B's rows change tenant A's session numbers. This is in main too, and the PR keeps it (medium, privacy; confirmed by a box-only test)
- The window CTEs and the new correlated count partition by
session_idonly, and not bytenant_id:dash/overview.go:1133,:850,:1166, anddash/cachehistory.go:112. The outercondhas the tenant filter, but the inner queries do not. - Scenario: tenant A has 3 rows in session
s. Tenant B then writes 10 rows under the same session ids. Tenant A'sReplayProjectedTokensgoes 190 → 1140, andCompactionResetsgoes 1 → 0. If A knows or guesses B's session id, A learns how much traffic B sends, and A's own numbers are wrong. - The PR does not make this worse. My probe shows old = new on fixtures where tenants share session ids. To add
tenant_idto the inner queries would change numbers, and it would also have to changeCachesplitHistoricalUSDByTenant(dash/cachehistory.go:200) and the unscoped path. So it should not go into this PR. Proposal: a separate issue, and in itPARTITION BY r.tenant_id, r.session_idandp.tenant_id = r.tenant_id.
3. The status line budget for the largest session (low, from reading the code; timing not verified)
- The lean path runs
Overview,CachesplitHistoricalUSDandDeclFilterSavingstogether (dash/api.go:1219-1247).Overviewalone takes 300-351 ms for 5,723 requests, by the PR's measurements. The status line hasRENDER_BUDGET_SECONDS = 0.36, lessRENDER_SAFETY_SECONDS = 0.03, from Python import. So the first uncached render for a session of this size will usually miss the budget. - It recovers. The compute is detached from the caller (
jsonInflightwithcontext.Background()anddashComputeTimeout,dash/api.go:318-335). So it completes and the result goes intostatsCacheeven after the status line closes its socket. Later renders get a fresh hit for 30 s (dashCacheTTL). For 30 s more they get a stale body at once, and one refresh starts in the background (dashCacheStale). Both cost about 1 ms. After more than 60 s with no reader, the next render is cold again. On a miss, the status line shows its last numbers from its disk cache with a stale mark, or "stats loading…" if it has none. - The cost grows with the square of the session size. The correlated count does one index range walk per saving row, over all later rows (plan:
SEARCH p USING COVERING INDEX idx_requests_session_tb (session_id=? AND ts>?)). A session 2x larger costs about 4x as much in this query. A session of 15-20k requests can take seconds again. Not verified. A follow-up could use one window with noPARTITION BYand the session's row count as a scalar subquery:(SELECT COUNT(*) FROM requests WHERE session_id = ?) - ROW_NUMBER() OVER (ORDER BY ts, id). That costs O(n log n). Not measured. CachesplitSizeSpread()(dash/cachehistory.go:269) still reads the whole table on every cold lean call. It is a deployment-wide fact, so this is correct, but its cost grows with the table and not with the session. Not measured.
Minor
dash/overview.go:856:append(args, beforeArgs...)can write into the backing array ofargs, which other goroutines in the sameerrgroupread. It is safe today, because this is the only goroutine that appends toargs, and it writes pastlen(args).-raceis clean. But the next goroutine that does the same will race.append(append([]any{}, args...), beforeArgs...)orslices.Concatprevents it.dash/overview.go:1124-1126: the comment saysCachesplitHistoricalUSDhas "the same shape" as the slow replay ceiling. It does not: it hasROW_NUMBERonly, with noCOUNT(*) OVER (PARTITION BY …). The comment at:811-814gives the shape correctly.dash/overview.go:947-955and the doc comment oncompactionResetsQuery(:1146-1159) say the same thing twice. One copy is sufficient.- The no-filter SQL is the same as before, except for whitespace: the empty
rnCondandprevCondadd a blank line, and the indentation changed. The args are the same. My probe confirms identical results for session "". - The session id is always a bound
?(dash/overview.go:845,:1131-1134throughcond,:1162;dash/cachehistory.go:109). There is no string interpolation. - The branch is behind
main. Indash/,mainchanged onlycachestate.go, so I expect no conflict. Not verified on a merge.
User decision on this PR's review: remove the daily_rollup design entirely for this release. Ship only the bounded session and day scopes; lifetime (since=0) goes back to answering exactly like the full handler, no rollup, no backfill, no watermark. A bounded lifetime is its own project, tracked as #510 rather than shipped half-verified here. - Removed: the daily_rollup table and index (schema.go), its backfill (dailyrollupbackfill.go, deleted), its write-time accumulation and watermark (store.go), and its wiring into backgroundMigrations (capture.go). - OverviewLean: session and day-window scope still run the single bounded aggregate from the previous commit. True lifetime (session=="" && since==0 && until==0) now calls Overview() plus both read-time-priced credits unconditionally — byte-identical to main's own lean handler, confirmed via the regenerated stats_lean golden file (the only remaining differences are fields lean never computed even before #498: self_removed_*, tier_costs, total_reduced_usd). - Review M3: CachesplitSizeSpread (dash/cachehistory.go) ran a deployment-wide, unindexed scan on every session-scoped lean call. Added a TTL cache (5 minutes) behind a *DB-held pointer, so DB.WithContext's shallow copy stays lock-free and every handle shares one cache. TestCachesplitSizeSpreadQueryItselfIsAWholeTableScan documents why the cache exists; TestCachesplitSizeSpreadIsCached proves it intercepts repeat calls (verified it fails with the cache disabled, passes with it restored). - Review M4: cg_latency_ms_avg stays in the lean SELECT — the released v0.4.2 status line (before #478) reads it and renders "proxy: 0ms" if it is ever absent. - DeclFilterSavings now included for day-window scope too, not just session (TestOverviewLeanDeclFilterSavingsIncludedForDayScope). - The EXPLAIN-plan test now rejects "SCAN ... USING INDEX", not just a bare table scan — an index-assisted scan still visits every matching row, unbounded by session or time. Lifetime is deliberately excluded from it, with a comment pointing at the follow-up issue. - Kept: the #501 tenant-scoping fix in cachesplitHistoricalQuery. go test -race -count=1 on ./dash/... and ./proxy/... both pass. Assisted-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
Summary
The status line waits on
/api/stats?lean=1&session=<id>. For a busysession, that call could take minutes, or never finish. This PR fixes it.
Closes #492.
What we found
Three queries inside
Overview(), plus one insideCachesplitHistoricalUSD, used a window function withPARTITION BY session_id. Each one scanned the WHOLErequeststable, even when thecaller asked for one session. A session's window values never depend on
another session's rows, so this was always wasted work. It just did not
show up until a real deployment had enough data: on a 262 MB database with
one session of 5,723 requests, this made
Overview()for that session take2 minutes 30 seconds, measured in isolation, with no other load.
One of the four, the "replay ceiling" query, stayed slow even after we
scoped it to the one session: 3.6-4.8 seconds. The window function itself
is slow through this driver (
modernc.org/sqlite) for that specific shape,regardless of how little data it reads. The fix for that one query goes
back to a correlated subquery, which took 165 ms for the same, verified
result.
What changed
dash/overview.go: the replay ceiling, its keep-alive correction, andCompactionResetsnow scope their inner query to the caller's sessionwhen one is given. The replay ceiling also switches to a correlated
subquery in that case (see above). The whole-deployment view (no session
filter) is unchanged.
dash/cachehistory.go:CachesplitHistoricalUSD's ranking query gets thesame session scoping.
dash/overview_session_scope_test.go(new): a correctness test that addshundreds of rows to OTHER sessions and checks the target session's
numbers do not change, and a regression test that runs
EXPLAIN QUERY PLANagainst the exact statementsOverview()executes, checking noneof them scan the whole table once a session filter is set.
Not in this PR: the status line's own fail-open behavior if a session's
stats are still slow (issue #492's proposal, item 4). That is a separate,
later change.
How it was tested
Verified byte-identical results between the old and new queries on five
real sessions (132 to 5,723 requests), copied from a live deployment's
dashboard database.
Timed
Overview()for each of those five sessions, before and after,in isolation (no HTTP, no other load):
Added the two new tests above; confirmed the regression test fails when
the session scoping is reverted, and passes with it restored.
go test -race -count=1 ./dash/...and./proxy/...: both pass.Technical notes
VACUUM INTOcopy of a real deployment'sdashboard database, never written to, and deleted after testing.
fresh cold start: the server's own query cache was never able to hold a
successful result for them, so every call paid the full cost.
originally chosen based on a different, larger corpus (189k rows,
sessions of ~1,000 turns) and a different query shape (an outer filter
that excluded ~91.5% of rows). Neither held here: at the scale and shape
in Status line: /api/stats?lean=1&session= never completes for sessions above ~1,000 requests #492, the window form was the slower one once scoped.