Skip to content

fix(dash): scope session-filtered lean queries to the session, not the table - #498

Merged
amiddavid merged 1 commit into
mainfrom
fix/lean-stats-session
Oct 13, 2026
Merged

amiddavid merged 1 commit into
mainfrom
fix/lean-stats-session

Conversation

@amiddavid

Copy link
Copy Markdown
Collaborator

Summary

The status line waits on /api/stats?lean=1&session=<id>. For a busy
session, that call could take minutes, or never finish. This PR fixes it.

Closes #492.

What we found

Three queries inside Overview(), plus one inside
CachesplitHistoricalUSD, used a window function with PARTITION BY session_id. Each one scanned the WHOLE requests table, even when the
caller 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 take
2 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, and
    CompactionResets now scope their inner query to the caller's session
    when 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 the
    same session scoping.
  • dash/overview_session_scope_test.go (new): a correctness test that adds
    hundreds of rows to OTHER sessions and checks the target session's
    numbers do not change, and a regression test that runs EXPLAIN QUERY PLAN against the exact statements Overview() executes, checking none
    of 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):

    Session size (requests) Before After
    132 5.5 s 13-72 ms
    219 5.5 s 13-21 ms
    1,097 32.5 s 34-42 ms
    3,674 45 s timeout (never completed) 123-130 ms
    5,723 2 min 30 s 300-351 ms
  • 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

  • The 262 MB test database was a VACUUM INTO copy of a real deployment's
    dashboard database, never written to, and deleted after testing.
  • "Before" timings for the 3,674- and 5,723-request sessions are not a
    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.
  • The slow correlated-vs-window tradeoff this PR partly reverses was
    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.

…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 amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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/main into a probe test. The fixture had 1,500 rows: 3 tenants that share the same 4 session ids, many ts ties, interleaved sessions, pings, split rows and cache_read = 0 rows. I compared the replay ceiling after the keep-alive correction (ReplayProjectedTokens), CompactionResets and the cachesplit row set. I used 160 filters: session "" plus 4 sessions, x tenant "" / t1 / t2 / TenantAll, x 4 since/until windows, x WithKeepAlive on 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: CompactionResets CTE not scoped fail (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 scoped pass
    M4: CachesplitHistoricalUSD rn CTE not scoped pass
    M5: correlated count ignores pings (AND p.keepalive = 0) pass. My probe fails, so the number does change
    M7: prev CTE 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. With PARTITION 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 only replayCeilingQuery and compactionResetsQuery. The keep-alive correction (dash/overview.go:839-856) and the rn CTE in dash/cachehistory.go:107-117 are 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 before and rn SQL into builders like the other two, and add them to the EXPLAIN map.
  • Planner wording: the patterns at :160 match the current modernc.org/sqlite output (SCAN r USING INDEX …, SCAN s). SQLite older than 3.36 wrote SCAN 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 no SEARCH … 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_id only, and not by tenant_id: dash/overview.go:1133, :850, :1166, and dash/cachehistory.go:112. The outer cond has 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 id s. Tenant A's ReplayProjectedTokens goes 190 → 1140, and CompactionResets goes 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_id to the inner queries would change numbers, and it would also have to change CachesplitHistoricalUSDByTenant (dash/cachehistory.go:200) and the unscoped path. So it should not go into this PR. Proposal: a separate issue, and in it PARTITION BY r.tenant_id, r.session_id and p.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, CachesplitHistoricalUSD and DeclFilterSavings together (dash/api.go:1219-1247). Overview alone takes 300-351 ms for 5,723 requests, by the PR's measurements. The status line has RENDER_BUDGET_SECONDS = 0.36, less RENDER_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 (jsonInflight with context.Background() and dashComputeTimeout, dash/api.go:318-335). So it completes and the result goes into statsCache even 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 no PARTITION BY and 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 of args, which other goroutines in the same errgroup read. It is safe today, because this is the only goroutine that appends to args, and it writes past len(args). -race is clean. But the next goroutine that does the same will race. append(append([]any{}, args...), beforeArgs...) or slices.Concat prevents it.
  • dash/overview.go:1124-1126: the comment says CachesplitHistoricalUSD has "the same shape" as the slow replay ceiling. It does not: it has ROW_NUMBER only, with no COUNT(*) OVER (PARTITION BY …). The comment at :811-814 gives the shape correctly.
  • dash/overview.go:947-955 and the doc comment on compactionResetsQuery (: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 rnCond and prevCond add 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-1134 through cond, :1162; dash/cachehistory.go:109). There is no string interpolation.
  • The branch is behind main. In dash/, main changed only cachestate.go, so I expect no conflict. Not verified on a merge.

@amiddavid
amiddavid merged commit 96ebf41 into main Oct 13, 2026
5 checks passed
@github-project-automation github-project-automation Bot moved this from New/ToDo to Done in Rossoctl Issue Prioritization Oct 13, 2026
amiddavid added a commit that referenced this pull request Oct 13, 2026
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]>
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.

Status line: /api/stats?lean=1&session= never completes for sessions above ~1,000 requests

1 participant