Skip to content

fix(dash): cap extract_llm and offloader replay credit at the counterfactual client compaction (#550) - #573

Merged
amiddavid merged 10 commits into
mainfrom
fix/replay-cap-550
Oct 15, 2026
Merged

amiddavid merged 10 commits into
mainfrom
fix/replay-cap-550

Conversation

@OsherElhadad

@OsherElhadad OsherElhadad commented Oct 15, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #550. Builds on #546 (merged).

Problem

extract_llm earned replay credit on every later turn that re-sent its shortened transcript, with no end. #546 capped summarize at its span; an offloader has no trigger fraction, so that span does not apply. The same unbounded credit sat under every replaying component (searchfold, dedup, extract, textclean, cmdfilter, format, toon).

The rule (option 1 of the issue)

End the credit at the counterfactual client compaction, per conversation (tenant, session, model):

cf = billed + f * (tokens_before - tokens_after)      # the transcript of the world without context-guru

f is the measured tokenizer factor (tokens.BilledDeltaFactor, #240). When cf reaches the client's compaction ceiling (compactionpoint.For, the ceiling #546 uses) that world's client compacts and the credit stops. A real client compaction ends it too: a drop in tokens_before after the agent's own compaction request went by, that the transcript does not recover from within a few turns (a subagent or auxiliary turn shares the session and model and interleaves with the main thread, so a bare drop is not evidence).

The cap never reads the real compaction to place the counterfactual one. Removals only make the real transcript smaller, so waiting for the real client to compact would credit exactly the turns the removals pushed past the ceiling. Credit is not reopened by a later epoch (conservative).

  • One ledger, keyed by component (dash/replaycap.go, ReplayLedger). Every component except the summarizers (summarize, cache_aware_summarizer: own span and ledger, fix(dash): cap summarize credit at its span and price the first removal as a read #546) uses the same rule.

  • One pricing path. The ledger counts the stored Event.ComponentSavedUSD figure; it only decides what counts. The headline (replay_cap_correction_usd), /api/components (replay_credit_past_cap_usd, first-removal/replay split) and the episode view (replay_ledger) read it.

  • First removal stays at the write rate for extract_llm. fix(dash): cap summarize credit at its span and price the first removal as a read #546's read-rate rule is for a summary, which removes earlier transcript the previous turn already sent. extract_llm removes the tail output that arrives this turn, which the world without us would have written at the creation rate.

  • A model whose window is not exactly known is capped against a conservative assumed window of 200k (or its known window if smaller). The component row is labelled replay_window_assumed, and window_assumed_usd / window_unknown_conversations say how much and how many.

  • Memory and cost. The scope is streamed session by session; memory is bounded by the largest single session, not the scope. /api/components computes the ledger beside its own read.

  • On the page. The "Your preset" row carries a small note when the cap removed credit, and says "Cap not applied" when the ledger errored or timed out (replay_cap_not_applied), instead of silently showing the uncapped figure.

Tests

  • dash/replaycap_test.go: counterfactual close, real-compaction close, subagent drop is not a compaction, a drop that recovers is not a compaction, compaction request on another model, per-component, first/replay split, unknown window, tokenizer factor, duplicate rows, SQL path, and all three read paths through the HTTP handlers.
  • Mutation checks, each killed by a test, on every clause of the rule and on each read-path wiring.
  • gofmt, go vet, go test -race ./dash/... ./proxy/... pass. Goldens: new fields only.
  • An independent recompute of the rule (sqlite + Python, no repo code) agrees with the Go ledger.

Real end-to-end (my own runs)

Claude Code 2.1.299 through the proxy built from this branch, then LiteLLM, then Azure gpt-5.2 (extractor: gpt-5-mini). Task: cat 20 log files (about 3.3k tokens each) one at a time, then report. ON = extract_llm alone (fire_on: size, economic_gate: false, allow_on_caching_backend: true, so it fires on every large output; the extraction call count was 20 of 20 accepted per session). OFF = proxy with no components. Same task and prompt, ABBA order, ON proxy restarted before each ON session (its cross-session result cache otherwise made later extractions free; the first two ON sessions showed it and are excluded). CLAUDE_CODE_AUTO_COMPACT_WINDOW=48000; Claude Code first tried to compact at about 68.2k billed tokens in every OFF session, so the ledger uses a 68,250-token ceiling (sensitivity below). Billed dollars are from the model shim's usage log, summed at Azure list rates.

pair ON $ (main + extractor) OFF $ measured saving, gross (OFF - ON main) net (OFF - ON total)
1 0.522 (0.422 + 0.100) 0.950 0.528 0.428
2 0.409 (0.309 + 0.100) 0.899 0.590 0.490
3 0.376 (0.286 + 0.091) 0.620 0.335 0.244
4 0.405 (0.317 + 0.088) 0.966 0.649 0.561
mean 0.428 0.859 0.525 (sd 0.14) 0.431 (sd 0.14)
extract_llm credit per ON session before (main / #546) after (this PR)
stored credit, 20 rows $0.229
counted, ceiling 68,250 $0.085 (first removal $0.059, replay $0.026)
counted, ceiling 60,000 / 73,200 $0.063 / $0.097
credit / measured gross saving 0.44 0.16
extractor spend (dashboard) $0.09-0.10 same
net of extractor spend +$0.135 -$0.009

The credit is identical across the four ON sessions (the task is deterministic), 10 of its 20 credited rows fall after the counterfactual close, and no session was closed by a real compaction (ON never reaches the ceiling). Headline "net from compaction" on the lab DB: +0.80 before, -0.01 after (all six ON sessions of the run).

The credit does not exceed the measured saving before or after the cap. It is smaller than the measured saving by design: the measured gap also holds what the cap refuses to claim (the ON sessions never compact, while OFF sessions pay for compaction attempts or carry a 116k-token context to the end), so the two are not meant to match.

Limits

  • Small lab (4 pairs, one task, one model, sd 0.14 on a 0.43 mean saving): it checks the cap's direction and arithmetic, not a savings figure.
  • The ceiling is an assumption about the client, and live Claude Code did not always compact at it (some OFF sessions tried and failed, growing to 116k). A wrong ceiling moves the credit: 0.063 to 0.097 over 60k to 73.2k; "never compacts" equals the stored credit, 0.229.
  • A real compaction is recognised only with the agent's compaction request as evidence; a manual clear is not.
  • The cap sees only the rows a filter selects, so a window that starts mid-session cannot know of an earlier close. The lean and full Overview reads apply it alike (a test pins lean == full for the same window); lifetime reads go to the full handler.
  • Credit valued by the read-time estimate (rows from before saved_usd existed) is not capped.
  • Component credits are summed, not re-derived from request-level baselines (same as fix(dash): cap summarize credit at its span and price the first removal as a read #546).
  • Other readers of the stored credit are unchanged (/api/savings, status-line windows, metrics export, series buckets).
  • A replay that missed with prefix_change is still credited for offloaders (fix(dash): cap summarize credit at its span and price the first removal as a read #546 excludes it for summarize).
  • Not a quality test: the lab's extractor dropped lines the task asked about; that is a separate defect.

Follow-ups filed: #585 (thread-aware detector), #586 (other uncapped views), #587 (uniqueRate and already-cached content).

@OsherElhadad

OsherElhadad commented Oct 15, 2026 •

Copy link
Copy Markdown
Collaborator Author

Follow-up on review findings, pushed as a second commit:

  • Drops are now required to persist: a drop after the agent's compaction request closes the credit only if none of the next three turns brings tokens_before back to its earlier size (an interleaved subagent or auxiliary turn is followed by a main-thread turn as large as before). Test: TestReplayCapRequiresTheDropToPersist, mutation-checked. The ledger keys on (tenant, session, model), not the thread id, because a compaction starts a new thread id and would then be invisible as a drop.
  • The ledger covers every component except summarize, so cache_aware_summarizer rows are included when they carry credit.
  • The ceiling is an assumption about the client, and live Claude Code did not always compact at it. "Never compacts" is the stored credit (no cap); the ceiling sensitivity is in the research notes.

@OsherElhadad OsherElhadad 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.

Review: REQUEST CHANGES at b2202d9, for publication only. The cap itself is correct. (Posted as a comment: GitHub does not let the author account request changes.)

Blocking (publication): this repository is public, and experiment results go in the private research repo, not in PR text or code.

  • The PR body's "Real end-to-end" section has per-pair dollar costs, means and SDs, credit before and after, a ceiling sensitivity range, and the lab DB headline.
  • The comment above walkReplayCap cites a snapshot finding ("On the snapshot three drops in four were that").
  • Replace both with qualitative statements. For example: "a lab A/B run confirmed the cap lowers extract_llm's credit below the measured saving", and "a drop alone is often a subagent turn". Keep the figures in the research repo.

Verified correct:

  • The rule. Per row, cf = billed + f*(tokens_before - tokens_after), and tokens_before - tokens_after already holds the replayed removals of earlier turns. The close is cf >= ceil*window, and the closing row's own credit counts as past-cap, which is right because that world compacts before sending it. Because cf >= real, the counterfactual close can never come after the real one, so credit can't continue past a real compaction. Closes are never reopened.
  • Inputs. f comes from tokens.BilledDeltaFactor(model), the measured #240 factor. The ceiling comes from compactionpoint.For(model).Frac × the exact window, the same one #546 uses.
  • Detecting a real compaction. It needs a tokens_before drop plus a bypassed request in between, from the same session on any model. So a bare subagent drop doesn't count.
  • One ledger feeds all three read paths: the headline (ApplyReplayLedger), /api/components (applyReplayLedgerToRow) and the episode view.
  • Mutations. Changing >= to > fails TestReplayCapEndsAtTheCounterfactualCompaction. Setting f = 1 fails TestReplayCapScalesRemovedTokensByTheBilledFactor.
  • Performance. I timed the ledger's two SQL reads with sqlite3 on a read-only copy of a full dashboard database (about 189K requests, 181K credit rows): about 0.6 s each. In memory that is tens of MB of capRow. The lean /stats path runs it only with a session filter, and the full paths are cached routes.
  • Checks. gofmt and go vet are clean, and the dash Replay/Cap/Golden/Compaction/Episode/Overview/Components tests pass. CI is green, and both commits are signed off.

Non-blocking:

  1. Grouping is (tenant, session, model), not per thread. Subagent rows share the main thread's walk. A close from the main thread also stops the subagents' credit, and a subagent's smaller turn after a main-thread compaction request can be read as a real compaction. Both errors under-credit, so this is conservative. Keying by thread_id (recorded since #426) would be exact. Also, removing Model from sameConv passes every test, so the grouping key isn't pinned.
  2. An unknown window keeps the whole stored, uncapped credit. That is the one path that can over-credit. It is counted in window_unknown_conversations. Surfacing that next to the headline, or capping at a default ceiling, would make it visible.
  3. request_components has no unique index (only idx_rc_request_comp). A duplicated (request, component) row is counted twice in both the stored figure and the ledger. That is the same as the existing SUM(saved_usd) aggregates, so they stay consistent, but a MAX per (request, component) would match the dedupe rule used elsewhere in analysis.

@OsherElhadad OsherElhadad 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.

Re-review: APPROVE at c2f5219. (Posted as a comment: GitHub does not let the author account approve.)

  • Publication. The PR body's figures all come from the agent's own Azure lab runs (ABBA pairs, model shim usage log, Azure list rates), which team-lead's ruling allows. No snapshot- or production-derived numbers remain in the body or in code comments; the "three drops in four" comment is gone.
  • (1) Drop must persist. A drop counts as a client compaction only if the transcript does not come back within recoveryLookahead = 3 turns. With the lookahead set to 0, TestReplayCapRequiresTheDropToPersist fails. If the session ends within 3 turns of the drop, nothing recovers, so the drop counts as a compaction and the credit closes early, which errs toward under-credit.
  • (2) Streaming. One query, ORDER BY tenant_id, session_id, model, ts, id. Sessions are contiguous, and a request's credit rows are contiguous because r.id is last in the key. The walk flushes per session.
    • Full read-only snapshot timing: 272,717 rows stream in about 1.8 s (SQLite scans idx_requests_tenant_session, plus a temp B-tree for the rest of the ORDER BY).
    • The largest session is about 40K rows, so the per-session buffer stays a few MB.
    • Duplicate request_components rows collapse to one per (request, component), keeping the larger saved_usd.
  • (3) /api/components. The ledger runs in a goroutine beside db.components, and both success paths wait on repDone before reading it.
  • (4) Unknown or inexact window. These are capped at min(known, 200k), labelled replay_window_assumed on the row and window_assumed_usd on the ledger. With the assumed-window cap removed, TestReplayCapAssumesAWindowWhenNoneIsExact fails.
  • gofmt and go vet are clean. go test -race ./dash -run 'Replay|Components|Episode' and the full ./dash (68 s) pass. CI is green, and the 3 new commits are signed off.

Non-blocking:

  1. Dedupe rule untested. Keeping the first duplicate instead of the larger one still passes every test, because the duplicate test uses equal rows. A case with unequal duplicates would pin "keep the larger".
  2. Early return leaves work running. When decomposeFromGroups errors, the handler returns without waiting on repDone, so the full-scope scan keeps running after the response. It does not leak, but it is wasted work; wait or cancel there too.
  3. The 200k comment overstates. It says the assumed ceiling is "never later than the real one", but that holds only for the families seen here. An unknown model with a smaller window, such as a 128k OpenAI model whose window modelinfo doesn't know, still over-credits. The window_assumed_usd label keeps it honest, so only the comment should soften.
  4. Grouping unchanged (as before). Conversations are still grouped by (tenant, session, model), not thread, so subagent turns can close the main thread's credit early. That under-credits.

This approval covers c2f5219.

@amiddavid
amiddavid force-pushed the feat/summarize-credit branch from 98d1b0a to 1b652f7 Compare October 15, 2026 14:12

@OsherElhadad OsherElhadad 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.

Re-check: APPROVE at 05bdc43. Notes 1–3 from the c2f5219 review are addressed:

  1. Larger duplicate kept. TestReplayLedgerKeepsTheLargerOfDuplicateRows uses unequal duplicates, so the rule is now pinned.
  2. Scan cancelled on error. ReplayLedgerForCtx: /api/components cancels the scan and waits for it when decomposeFromGroups fails, so nothing runs past the response. TestReplayLedgerStopsWhenItsContextIsCancelled covers it.
  3. Family window floor. assumedWindowFor takes the smallest of the known inexact window, a family floor (gpt-4 and llama 128k, mistral 32k) and 200k. The comment now calls it an assumption, not a bound. A model like gpt-4.1 with a larger real window is capped early, which under-credits and is safe.

Note 4 (thread grouping) stays as documented. gofmt and go vet are clean, go test -race ./dash -run 'Replay|Components' passes, CI is green, and it is signed off. This approval covers 05bdc43.

@OsherElhadad
OsherElhadad changed the base branch from feat/summarize-credit to main October 15, 2026 16:06

@OsherElhadad OsherElhadad 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.

Re-review: APPROVE at de92d7a (retargeted to main after #546 merged).

  • Rebase. git range-diff against the approved series: commits 2–6 are identical. Commit 1 differs only where #546's merged shape is used (applySummarizeLedgerToRow(c, ls[c.Component])).
  • New commit de92d7a. #546 as merged puts cache_aware_summarizer in the summarize ledger, so the replay ledger now excludes every summarizer. The SQL uses NOT IN built from the constant SummarizerComponents list, and applyReplayLedgerToRow skips IsSummarizer. No component is credited by both ledgers. TestReplayLedgerLeavesEverySummarizerToItsOwnLedger covers it, and the PR body no longer claims cache_aware_summarizer.
  • Tests. gofmt and go vet are clean, go test -race ./dash -run 'Replay|Summar|Components' passes, and the full go test -p 1 ./dash passes (80 s).
  • CI. On this head only DCO has run (pass); build-test, purego and trivy have not triggered. Please re-trigger CI before merging.

This approval covers de92d7a.

@OsherElhadad OsherElhadad 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.

CI note: the full CI has now run on de92d7a and is green (build-test, purego, trivy, build, DCO). My approval at de92d7a stands.

@amiddavid

Copy link
Copy Markdown
Collaborator

Review of de92d7a

Verdict: ready after one fix. I found no blocker in the cap rule or the numbers. One fix is needed in the Overview, and CI must run before merge.

What I ran (eval box, foreground, race on)

Fix before merge

1. The Overview shows two different numbers in one page load.

  • dash/ui/app.js:1559 first paints from /api/stats?lean=1 with the date window.
  • dash/api.go:1253 applies the replay cap on the lean path only when a session is set.
  • So the "Your preset" row (dash/ui/savings.js:14, reads net_saved_usd) first shows the uncapped figure. Then the full read replaces it with the capped figure, and the number drops.
  • Example with the lab data in this PR: a window shows +$0.23 for extract_llm, then +$0.085.
  • The comment at dash/ui/app.js:1556 says "No number differs". That is no longer true.
  • The PR body lists "a lean window keeps the stored credit" as a limit. After feat(dash): one redesigned dashboard: Overview rewrite, plain-words tabs, Benchmarks tab removed #564, the user sees it.
  • Fix: apply the cap on lean windows too (fix(dash): cap summarize credit at its span and price the first removal as a read #546 does this for summarize), or leave net_saved_usd out of the lean read. Add a test that the lean and full reads give the same net_saved_usd for the same window.

2. CI did not run on de92d7a.

  • The last CI run was on the earlier head 05bdc43. The pushes at 16:01 and 16:06 UTC made no CI run.
  • The cause is not the workflow triggers. ci.yaml runs on pull_request and ignores only docs paths. Other PRs got CI at the same time. The event was probably dropped.
  • Only DCO is a required check, so GitHub would merge without CI.
  • Fix: push a rebase on main. The new commit starts CI. Merge only when it is green.

Not blocking (file as issues if you agree)

  • The compaction detector is weaker than in fix(dash): cap summarize credit at its span and price the first removal as a read #546.
    • fix(dash): cap summarize credit at its span and price the first removal as a read #546 keys its detector on the thread. This PR keys on (tenant, session, model), and needs a compaction request plus a drop that does not recover within 3 rows.
    • A subagent that runs more than 3 turns on the same model, near a bypass request, can look like a client compaction and end the credit early.
    • This error under-credits, so it is on the safe side.
  • replay_cap_correction_usd has no UI reader. Nothing tells the user that a figure was capped.
  • Uncapped views: /api/savings, status-line windows, metrics export and series buckets still read the uncapped stored credit. The new Overview does not show any of them as a headline, but they can disagree with it.

Checked and correct

@amiddavid

Copy link
Copy Markdown
Collaborator

Follow-up to the review of de92d7a: tests, mutations, performance

The verdict does not change: ready after the lean-window fix and a rebase that starts CI.

Tests

Run PR head Merge with main
go vet ./dash/... ./proxy/... clean clean
go test -race ./dash/... pass, 429 s pass, 417 s
go test -race ./proxy/... pass, 340 s pass, 354 s
node --test dash/*.test.mjs not run 12 of 12 pass

Mutations: 25 run, 19 caught

Caught:

  • The counterfactual close: never closes, ignores removed, or uses >.
  • The persistence check, and recoveryLookahead set to 0.
  • The summarizer exclusion in the SQL, and the model dropped from the key.
  • The duplicate rule, the assumed window, and the factor f.
  • The NetSavedUSD, baseline and row SavedUSD corrections, and the past-cf attribution.
  • The 4 read-path wirings: full stats, lean session, components, and the episode view.

Not caught (please add tests):

  1. The compaction-request evidence. A test passes when the requirement is removed, and when the range is open or has only a lower bound. Add a test with a persistent drop and no compaction request: it must not close the credit.
  2. firstShare. A test passes when it returns 0 or uses only the token path, because the split test feeds FirstUSD directly. Add a test that goes through firstShare.
  3. The TotalSavedUSD and TotalReducedUSD corrections. No test fails when they are removed. The Overview reads total_saved_usd, so this one matters most.
  4. The row NetUSD correction. No test fails when it is removed.

Equivalent mutation (no action): removing the per-row summarizer check. The SQL already excludes summarizers.

Performance

Synthetic DB: 450k requests, 900k component rows, 3,000 sessions, on the shared box.

Scope Time
All rows 7.2 s
A window of about 10% 0.84 s
One session 2.5 ms
  • The query plan scans idx_requests_tenant_session, plus a temp B-tree sort on (model, ts, id).
  • The time grows linearly with the scope.
  • At about 1M requests, the full scope passes the 10 s caller timeout in dash/api.go. On a timeout, the headline silently keeps the uncapped stored credit.
  • Not a blocker today. Please file an issue: on a timeout, say on the page that the cap was not applied.

…applied, and pin the corrections

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

Copy link
Copy Markdown
Collaborator Author

@amiddavid thanks. Everything from your two comments is in 8a9e5664 (rebased on main, CI green: build-test, purego, trivy, build, DCO).

Must-fix

  1. Lean vs full. The lean read now applies the cap for windows too (dash/api.go), and the stale comment at app.js (No number differs) now says what is true. TestLeanStatsMatchFullForTheSameWindow pins net_saved_usd, total_saved_usd, total_reduced_usd and the correction, lean == full, for a window and for a session. The "lean window keeps the stored credit" limit is gone from the PR body.
  2. The four missing tests, each killed by its mutation:
    • persistent drop with no compaction request: TestReplayCapNeedsTheCompactionRequestAsEvidence (also an early and a late request; killed by removing the evidence, a lower-bound-only range, an upper-bound-only range);
    • firstShare: TestFirstShareIsPricedNotCountedInTokens and TestReplayLedgerSplitsFirstRemovalThroughFirstShare (killed by returning 0 and by the token-only path);
    • TotalSavedUSD / TotalReducedUSD / NetSavedUSD: pinned in TestReplayLedgerThroughSQLMovesTheHeadlineAndTheRow (each line removed in turn);
    • row NetUSD / NetUSDWithEstimate: pinned in the same test.
  3. Rebased on main (the push started CI); not merged. Waiting for your re-review.

Also done

  • When the ledger errors or times out, the headline carries replay_cap_not_applied (lean and full), and the page says "Cap not applied" (TestHeadlineSaysWhenTheCapWasNotApplied).
  • The "Your preset" row shows a small "Capped: $X of replay credit ... is not counted" note when replay_cap_correction_usd < 0 (capNote, node test added; 13 of 13 node tests pass).

Filed

go vet, go test -race ./dash/... ./proxy/... and node --test dash/*.test.mjs pass.

@OsherElhadad OsherElhadad 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.

Re-review: APPROVE at 8a9e566. (Posted as a comment: GitHub does not let the author account approve.)

  • Rebase. git range-diff against the approved de92d7a series shows all 7 earlier commits identical. 8a9e566 is the only new commit, and it is signed off.
  • Lean applies the cap. /api/stats?lean=1 with a window now applies the replay cap, so the net and total don't move when the full read lands. With the lean block removed, TestLeanStatsMatchFullForTheSameWindow and TestReplayCapReachesEveryReadPath fail.
  • Honest flag. A ledger error sets replay_cap_not_applied on both the lean and full paths, and the page says "Cap not applied". With the flag removed, TestHeadlineSaysWhenTheCapWasNotApplied fails.
  • Totals. ApplyReplayLedger moves baseline, net, total-saved and total-reduced by the same delta, and row NetUSD is pinned. No double subtraction.
  • Test hook. replayLedgerFn is an unexported field, nil in production, so ReplayLedgerFor runs.
  • UI note. Built with el(...), no inline style or handler, in plain words.
  • Checks. gofmt and go vet are clean, the full go test -p 1 ./dash passes, node savings.test.mjs (3/3) and navhash.test.mjs (10/10) pass, and CI is green. The PR body has no snapshot or production figures.

Non-blocking, worth a decision before release:

  1. Lean latency. The lean window read now scans every request in the window. On a read-only copy of a full dashboard DB:

    scope, window OverviewLean alone replay ledger added
    fleet, 30 days 1.41 s +2.94 s
    top tenant, 30 days — +0.54 s
    fleet or tenant, 24 h — under 10 ms

    So a manager's 30-day Overview first paint goes from about 1.4 s to about 4.4 s, plus the summarize ledger. That is within the 45 s route bound, and the stale-while-revalidate cache hides repeats. It does depart from #502's rule that nothing on the lean path grows with the table, and the code comment saying "a session or a window bounds the scan" overstates a 30-day fleet window. A cheap fix is to run the replay ledger concurrently with OverviewLean (they are independent until the apply), so wall time is the max rather than the sum, or to skip it past N days and set replay_cap_not_applied honestly.

  2. Status line. Its session-scoped lean read already had the cap. The spark layout's day-window read runs in the background and covers today only, so render latency is unchanged.

  3. No price table. Without a pricer or window resolver, the cap is skipped and replay_cap_not_applied stays false. Nothing claims "Capped", but nothing says "not applied" either. Consider setting the flag there too.

This approval covers 8a9e566.

@OsherElhadad

Copy link
Copy Markdown
Collaborator Author

@amiddavid quick re-check at 4eff403 (CI green): (1) the lean read now runs the replay scan beside OverviewLean (2cba23c); (2) when there is no price table or window resolver the cap cannot run, and both reads now set replay_cap_not_applied, so the page says so (TestHeadlineSaysCapNotAppliedWithoutAPriceTable, mutation-checked). Goldens: the new field only.

@OsherElhadad OsherElhadad 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.

Re-check: APPROVE at 4eff403.

  • 2cba23c. On the lean read, the replay scan now starts in a goroutine before OverviewLean and is awaited before any return, including the error path, so nothing outlives the response. On the 30-day fleet window the author measured about 3.1–3.2 s, down from 4.3–5.1 s. It isn't the full max(), because the SQLite driver serialises reads. That still exceeds #502's "lean doesn't grow with the table" aim on long fleet windows, and it is now a documented, bounded trade-off: inside the route limit, and zero cost for 24 h or session scope.
  • 4eff403. replay_cap_not_applied is now also set on both reads when there is no pricer or no window resolver. With that removed, TestHeadlineSaysCapNotAppliedWithoutAPriceTable fails in all three cases, and the goldens carry the field.
  • gofmt and go vet are clean, go test -race ./dash -run 'Replay|Lean|Golden|Headline' passes, CI is green, and both commits are signed off.

This approval covers 4eff403.

@amiddavid
amiddavid merged commit 738eac9 into main Oct 15, 2026
6 checks passed
amiddavid pushed a commit that referenced this pull request Nov 10, 2026
…1037)

#546 and #573 cap the summarizer and offloader replay credit in the
headline, /api/components and the episode view. Other readers still
summed request_components.saved_usd and so disagreed with the
headline. The status line (/stats savings.current and savings.live),
the daily series and the breakdown now apply the same cap
(SavingsTotalsCapped). Fixes #586.

Behavior change: anyone who reads the status line. Old: it summed the
stored credit and could read far above the dashboard headline. New:
it applies the headline's cap; a capped session shows the lower
number. No switch (use SavingsTotals in place of SavingsTotalsCapped
in proxy/savings.go to go back).
Owner's yes, 2026-11-10, in the integrator session: "yes I agree with the claim on 584 and behavior changes".

Data dependence: metadata only. No change.

Reviews: 2 offload reviews (GLM), round 2, both approve at b2843a9.
After it: a merge of main with no hand resolution (remerge-diff 0),
tested on the merged tree (./dash/..., ./proxy/...).

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: DAVID BOAZ <[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.

dash: extract_llm replay credit has no cap

2 participants