Repository navigation
fix(dash): cap extract_llm and offloader replay credit at the counterfactual client compaction (#550) - #573
Conversation
|
Follow-up on review findings, pushed as a second commit:
|
OsherElhadad
left a comment
There was a problem hiding this comment.
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
walkReplayCapcites 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), andtokens_before - tokens_afteralready holds the replayed removals of earlier turns. The close iscf >= ceil*window, and the closing row's own credit counts as past-cap, which is right because that world compacts before sending it. Becausecf >= 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.
fcomes fromtokens.BilledDeltaFactor(model), the measured #240 factor. The ceiling comes fromcompactionpoint.For(model).Frac× the exact window, the same one #546 uses. - Detecting a real compaction. It needs a
tokens_beforedrop 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>failsTestReplayCapEndsAtTheCounterfactualCompaction. Settingf = 1failsTestReplayCapScalesRemovedTokensByTheBilledFactor. - 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/statspath runs it only with a session filter, and the full paths are cached routes. - Checks.
gofmtandgo vetare clean, and the dash Replay/Cap/Golden/Compaction/Episode/Overview/Components tests pass. CI is green, and both commits are signed off.
Non-blocking:
- 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, removingModelfromsameConvpasses every test, so the grouping key isn't pinned. - 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. request_componentshas no unique index (onlyidx_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 existingSUM(saved_usd)aggregates, so they stay consistent, but aMAXper (request, component) would match the dedupe rule used elsewhere in analysis.
OsherElhadad
left a comment
There was a problem hiding this comment.
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 = 3turns. 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 becauser.idis 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_componentsrows collapse to one per (request, component), keeping the largersaved_usd.
- Full read-only snapshot timing: 272,717 rows stream in about 1.8 s (SQLite scans
- (3) /api/components. The ledger runs in a goroutine beside
db.components, and both success paths wait onrepDonebefore reading it. - (4) Unknown or inexact window. These are capped at min(known, 200k), labelled
replay_window_assumedon the row andwindow_assumed_usdon the ledger. With the assumed-window cap removed, TestReplayCapAssumesAWindowWhenNoneIsExact fails. gofmtandgo vetare 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:
- 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".
- Early return leaves work running. When
decomposeFromGroupserrors, the handler returns without waiting onrepDone, so the full-scope scan keeps running after the response. It does not leak, but it is wasted work; wait or cancel there too. - 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_usdlabel keeps it honest, so only the comment should soften. - 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.
98d1b0a to
1b652f7
Compare
OsherElhadad
left a comment
There was a problem hiding this comment.
Re-check: APPROVE at 05bdc43. Notes 1–3 from the c2f5219 review are addressed:
- Larger duplicate kept. TestReplayLedgerKeepsTheLargerOfDuplicateRows uses unequal duplicates, so the rule is now pinned.
- Scan cancelled on error.
ReplayLedgerForCtx:/api/componentscancels the scan and waits for it whendecomposeFromGroupsfails, so nothing runs past the response. TestReplayLedgerStopsWhenItsContextIsCancelled covers it. - Family window floor.
assumedWindowFortakes 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.
05bdc43 to
de92d7a
Compare
OsherElhadad
left a comment
There was a problem hiding this comment.
Re-review: APPROVE at de92d7a (retargeted to main after #546 merged).
- Rebase.
git range-diffagainst 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_summarizerin the summarize ledger, so the replay ledger now excludes every summarizer. The SQL usesNOT INbuilt from the constantSummarizerComponentslist, andapplyReplayLedgerToRowskipsIsSummarizer. No component is credited by both ledgers. TestReplayLedgerLeavesEverySummarizerToItsOwnLedger covers it, and the PR body no longer claimscache_aware_summarizer. - Tests.
gofmtandgo vetare clean,go test -race ./dash -run 'Replay|Summar|Components'passes, and the fullgo test -p 1 ./dashpasses (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.
Review of de92d7aVerdict: 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 merge1. The Overview shows two different numbers in one page load.
2. CI did not run on de92d7a.
Not blocking (file as issues if you agree)
Checked and correct
|
Follow-up to the review of de92d7a: tests, mutations, performanceThe verdict does not change: ready after the lean-window fix and a rebase that starts CI. Tests
Mutations: 25 run, 19 caughtCaught:
Not caught (please add tests):
Equivalent mutation (no action): removing the per-row summarizer check. The SQL already excludes summarizers. PerformanceSynthetic DB: 450k requests, 900k component rows, 3,000 sessions, on the shared box.
|
…factual client compaction (#550) Signed-off-by: Osher-Elhadad <[email protected]>
Signed-off-by: Osher-Elhadad <[email protected]>
Signed-off-by: Osher-Elhadad <[email protected]>
…s, compute it beside /api/components Signed-off-by: Osher-Elhadad <[email protected]>
Signed-off-by: Osher-Elhadad <[email protected]>
…error, family window floor Signed-off-by: Osher-Elhadad <[email protected]>
Signed-off-by: Osher-Elhadad <[email protected]>
…applied, and pin the corrections Signed-off-by: Osher-Elhadad <[email protected]>
de92d7a to
8a9e566
Compare
|
@amiddavid thanks. Everything from your two comments is in Must-fix
Also done
Filed
|
OsherElhadad
left a comment
There was a problem hiding this comment.
Re-review: APPROVE at 8a9e566. (Posted as a comment: GitHub does not let the author account approve.)
- Rebase.
git range-diffagainst 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=1with 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_appliedon both the lean and full paths, and the page says "Cap not applied". With the flag removed, TestHeadlineSaysWhenTheCapWasNotApplied fails. - Totals.
ApplyReplayLedgermoves baseline, net, total-saved and total-reduced by the same delta, and rowNetUSDis pinned. No double subtraction. - Test hook.
replayLedgerFnis an unexported field, nil in production, soReplayLedgerForruns. - UI note. Built with
el(...), no inline style or handler, in plain words. - Checks.
gofmtandgo vetare clean, the fullgo test -p 1 ./dashpasses, nodesavings.test.mjs(3/3) andnavhash.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:
-
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 setreplay_cap_not_appliedhonestly. -
Status line. Its session-scoped lean read already had the cap. The
sparklayout's day-window read runs in the background and covers today only, so render latency is unchanged. -
No price table. Without a pricer or window resolver, the cap is skipped and
replay_cap_not_appliedstays false. Nothing claims "Capped", but nothing says "not applied" either. Consider setting the flag there too.
This approval covers 8a9e566.
Signed-off-by: Osher-Elhadad <[email protected]>
…r window resolver Signed-off-by: Osher-Elhadad <[email protected]>
|
@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
left a comment
There was a problem hiding this comment.
Re-check: APPROVE at 4eff403.
- 2cba23c. On the lean read, the replay scan now starts in a goroutine before
OverviewLeanand 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_appliedis 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. gofmtandgo vetare clean,go test -race ./dash -run 'Replay|Lean|Golden|Headline'passes, CI is green, and both commits are signed off.
This approval covers 4eff403.
…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]>
Closes #550. Builds on #546 (merged).
Problem
extract_llmearned replay credit on every later turn that re-sent its shortened transcript, with no end. #546 cappedsummarizeat 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):
fis the measured tokenizer factor (tokens.BilledDeltaFactor, #240). Whencfreaches 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 intokens_beforeafter 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.ComponentSavedUSDfigure; 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_llmremoves 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, andwindow_assumed_usd/window_unknown_conversationssay 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/componentscomputes 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.gofmt,go vet,go test -race ./dash/... ./proxy/...pass. Goldens: new fields only.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:cat20 log files (about 3.3k tokens each) one at a time, then report. ON =extract_llmalone (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.extract_llmcredit per ON sessionThe 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
saved_usdexisted) is not capped./api/savings, status-line windows, metrics export, series buckets).prefix_changeis 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).Follow-ups filed: #585 (thread-aware detector), #586 (other uncapped views), #587 (
uniqueRateand already-cached content).