Skip to content

Fix: Cap the replay credit in the status line, series and breakdown - #1037

Merged
amiddavid merged 4 commits into
mainfrom
fix/586-capped-readers
Nov 10, 2026
Merged

amiddavid merged 4 commits into
mainfrom
fix/586-capped-readers

Conversation

@boazdavid

Copy link
Copy Markdown
Collaborator

Behavior change (needs a human's yes)

Who it affects: anyone who reads the status line (/stats savings.current and savings.live).

Old: the status line summed the stored credit. It could read far above the dashboard headline.

New: the status line applies the same cap as the headline. For a capped session it now shows the lower number.

How to turn it off: no switch. Use SavingsTotals in place of SavingsTotalsCapped in proxy/savings.go.

Problem

Fixes #586.

#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.

I ran 150 turns of one session through a built origin/main. The transcript passed the compaction ceiling.

Reader Net saved
/api/stats (headline) $0.73
/stats current (status line) $11.60
/api/series $11.60

Changes

  1. SavingsTotalsCapped applies the summarize and replay ledger correction. CapCorrectionUSD adds the two ledgers in one place.
  2. /stats uses it for the current and live scopes.
  3. The all scope stays uncapped and returns cap_not_applied: true. A lifetime read would stream every row through the ledgers on each refresh. dash: #498's tests guard 2 of 4 queries and no numbers; the session query still grows with the square of its size #502 forbids that.
  4. /api/series and /api/breakdown return cap_correction_usd and cap_not_applied beside their rows. The ledgers do not say which bucket a correction belongs to, so I did not spread it over the buckets. Rows plus the correction equal the headline.
  5. The help text of the Prometheus baseline series says they are uncapped.

Result

Same 150-turn session, built from this branch:

Reader Net saved
/api/stats (headline) $0.75
/stats current $0.75
/api/series buckets + cap_correction_usd $0.75
/api/breakdown groups + cap_correction_usd $0.75
/stats all $11.62, cap_not_applied: true

Not done

  • Series, breakdown and metrics are not capped row by row. That needs a per-request correction from both walks.
  • The metrics export stays uncapped. It is labelled.

Tests

  • dash/capreaders_test.go: the capped totals match the headline, the label shows when the cap cannot run, and series and breakdown carry the correction.
  • I regenerated four golden files: series_day, series_hour, breakdown_agent, breakdown_model. Each diff is the two new fields only.
  • go test ./dash ./proxy, go vet and gofmt pass.
  • TestPreflightResolvesToolsOnTheServicePATH in cmd/context-guru-proxy fails. It fails the same way on the base without this change.

Assisted-By: Claude (Anthropic AI) [email protected]

…down (#586)

The headline, /api/components and the episode view cap the summarizer and
offloader replay credit through the ledgers. The status line, /api/series,
/api/breakdown and the metrics export summed the stored credit, so they
could read far above the headline for the same rows.

- SavingsTotalsCapped applies the ledger correction. /stats uses it for the
  current and live scopes. The all scope stays uncapped, because a lifetime
  read would stream every row on each refresh (#502), and says so with
  cap_not_applied.
- /api/series and /api/breakdown return cap_correction_usd and
  cap_not_applied beside their rows. The ledgers do not say which bucket a
  correction belongs to, so it is not spread over them.
- The Prometheus help text of the baseline series says they are uncapped.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>

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

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 1 (glm, user of @boazdavid) GLM rits/zai-org/glm-5-3 via Claude Code 2.1.241 offload-review skill, @boazdavid's session fresh 1 of 2 1 of 2 eb0f89bfc531 blocking

Verdict: blocking

Findings

  1. dash/savings.go:103-116 — CapCorrectionUSD is all-or-nothing, but the headline applies each ledger on its own, so a one-ledger failure makes the readers disagree with the headline

    • What fails: the summarize ledger scan fails and the replay ledger scan succeeds (or the reverse), on a session with real cap credit. The headline then applies the one correction that worked (dash/api.go:1407 and 1413 in the lean path, 1506-1507 in the full path — each Apply* runs when its own ledger succeeded). CapCorrectionUSD returns an error when either ledger fails (dash/savings.go:107-114), so /api/series, /api/breakdown and the /stats current/live scopes report cap_correction_usd: 0, cap_not_applied: true and keep the stored figure. The headline shows the partially corrected figure. The two views show different money for the same rows — exactly the disagreement this PR exists to remove (#586).
    • Proof: lean path, dash/api.go:1404-1416: if l, lerr := db.SummarizeLedgerFor(...); lerr == nil { o.ApplySummarizeLedger(l) } — a summarize failure does not stop o.ApplyReplayLedger(repLedger) at 1413, and ReplayCapNotApplied stays false. dash/savings.go:129-133: SavingsTotalsCapped sets CapNotApplied and drops the whole correction when CapCorrectionUSD errors, which happens if either of the two ledgers errors. The same holds for a.capCorrection (dash/api.go:1561-1572).
    • Fix: in CapCorrectionUSD, apply whichever ledger succeeded and return the sum of the successful ones, mirroring the headline. Only report not-applied when neither ran (no pricer, no windows).
  2. dash/capreaders_test.go:37 — the agreement test compares the combined correction against a replay-only field, and the summarize half of the new arithmetic is never exercised nonzero

    • What fails: capped.CapCorrectionUSD is summarize delta + replay delta (dash/savings.go:115). The test compares it with the headline's replay_cap_correction_usd, which is the replay delta alone (dash/replaycap.go:622-623). The fixture (replayCapAPI, dash/replaycap_test.go:547-582) writes only extract_llm component rows. SummarizerComponents is summarize and cache_aware_summarizer (dash/event.go:976), so the summarize ledger is empty and its delta is 0. The two numbers agree only by fixture luck.
    • Proof: if the summarize half of CapCorrectionUSD had a wrong sign or double count, every assertion in TestSavingsTotalsCappedAgreesWithTheHeadline and TestSeriesAndBreakdownCarryTheCapCorrection (line 92 makes the same replay-only comparison) would still pass. No test in this PR gives SavingsTotalsCapped or CapCorrectionUSD a nonzero summarize correction. That is the new behavior this PR adds, untested.
    • Fix: add a summarize row (a summarize component row on a session that crosses the compaction ceiling) to the fixture, or a second fixture, and assert the combined correction plus the baseline/total agreement there. Compare against the headline totals, not against replay_cap_correction_usd.
  3. proxy/savings.go:97,104 — /stats now runs two full ledger walks on every status-line refresh, with no cache

    • What fails: the status line reads /stats often (the PR's own behavior-change section names it). savingsStats is synchronous and uncached (proxy/proxy.go:3037, the /stats handler has no cache). Each refresh now runs, for the current session and again for every live session: ReplayLedgerFor (streams every row of each session's full history) plus SummarizeLedgerFor, which runs compactEpisodeDataset once per summarizer component — two queries — and materializes every selected row in memory (dash/compactepisode.go:1269-1284, dash/summarizeattr.go:93-110). Before this PR the refresh cost two indexed aggregates. The cost now grows with the session's full history and with the live-session count (up to maxKeepAliveSessions), on every refresh. The PR rejects the same scan for the all scope for this exact reason (#502, quoted in SavingsScope.CapNotApplied's comment); the dashboard's own equivalent read, /api/stats?lean=1, runs the same ledgers but behind a 30 s cache with one refresh in flight (dash/api.go:123, serveJSON).
    • Proof: dash/savings.go:124-139 — SavingsTotalsCapped calls SavingsTotals then CapCorrectionUSD, which calls both SummarizeLedgerFor and ReplayLedgerFor (dash/savings.go:107-113). proxy/savings.go:97 and :104 call it for the live and current scopes inside the /stats handler.
    • Fix: cache the correction — per session, with a short TTL, or recompute only when the session has new rows since the last computation. The dashboard's jsonCache shape is the model.

Non-blocking

  • SavingsTotalsCapped's total_saved_usd still omits DeclFilterSavings and CachesplitHistoricalUSD, which the lean headline adds for a session (dash/overview_lean.go:44-53). So "agrees with the headline" holds for net_saved_usd and baseline_cost_usd, not for total_saved_usd, when those credits are nonzero. Pre-existing for SavingsTotals; the new test's fixture has neither, so its total assertion is also fixture luck. Worth a sentence in the PR.
  • The UI offers "All time" (dash/ui/app.js QUICK_RANGES, [0, 'All time']). With it, /api/series and /api/breakdown run both ledgers over the whole table, which CapCorrectionUSD's own doc warns against (#502). Mitigated: both routes sit behind routeCache (30 s TTL, one refresh in flight, 2-minute detached compute bound). The full /api/stats already does the same scan for a lifetime read, so this is consistent — but the doc and the route disagree.
  • a.capCorrection calls db.CapCorrectionUSD directly and bypasses the a.replayLedger test hook (dash/api.go:595-600). A test cannot inject a replay-ledger failure into series or breakdown. The failure paths of finding 1 are for that reason also hard to test as written.
  • The PR body has no data-dependence statement. The change adds none — it reads the same stored per-request credit the headline cap already reads. Say so in the PR to satisfy the CLAUDE.md rule.

What I checked

  • The full diff of eb0f89bf against base 77a910b0: dash/api.go, dash/savings.go, dash/capreaders_test.go, the four golden files, proxy/promexport.go, proxy/savings.go.
  • The headline's cap application on both paths: the lean branch (dash/api.go:1382-1416) and the full branch (dash/api.go:1423-1520), ApplyReplayLedger (dash/replaycap.go:617-630) and ApplySummarizeLedger (dash/summarizeattr.go:152-162), against SavingsTotalsCapped's arithmetic (dash/savings.go:124-139). The three-field correction (baseline, net, total) matches the headline when both ledgers run.
  • That the two ledgers do not double count: ReplayLedgerFor excludes summarizer components (notSummarizerSQL, dash/replaycap.go:477-484).
  • The fixture replayCapAPI (dash/replaycap_test.go:546-580): components are extract_llm only, so the summarize ledger is empty — the basis of finding 2.
  • The cost claims: ReplayLedgerFor's streaming and memory bound (dash/replaycap.go:486-498), SummarizeLedgerFor's two compactEpisodeDataset runs and full materialization (dash/summarizeattr.go:93-113, dash/compactepisode.go:1251-1286), the /stats handler's lack of a cache (proxy/proxy.go:2842-3037), and the dashboard's jsonCache TTL and single-flight (dash/api.go:108-125, 358-400).
  • Route wiring: series and breakdown are cached routes with the default 10 s handler bound (dash/api.go:824-852, 854-880); cachedRoute runs the handler under a detached read context, so a.db(r) inside capCorrection is safe.
  • The golden-file diffs: each is the two new fields only, with cap_not_applied: true for a test setup with no pricer. Consistent with capCorrection's nil-pricer branch.
  • proxy/promexport.go: help-text changes only, no behavior.
  • The PR body: it names the behavior change, who it affects, the old and new behavior, and how to turn it off, as CLAUDE.md requires.
  • Live tests were not run. Go is not installed on this machine and the review brief forbids builds.

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

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 2 (glm, user of @boazdavid) GLM rits/zai-org/glm-5-3 via Claude Code 2.1.241 offload-review skill, @boazdavid's session fresh 2 of 2 1 of 2 eb0f89bfc531 blocking

Verdict: blocking

Findings

  1. proxy/savings_test.go:128 — the status line's new capping has no test where the cap runs, and the existing agreement test now pins the wrong reference

    • What fails: /stats' Current and Live scopes now return SavingsTotalsCapped (proxy/savings.go:97,104). The only test that covers these scopes, TestStatsSavingsThreeScopesAgreeWithOverview, compares them against plain SavingsTotals (proxy/savings_test.go:128,139). It passes only because the fixture sets Prices: fixedPricer{} but no Options.Windows, so CapCorrectionUSD returns errCapUnavailable and the capped call degenerates to the uncapped figure. No proxy test asserts cap_correction_usd, cap_not_applied, the "all" scope's CapNotApplied = true label, or that Current/Live equal SavingsTotalsCapped when a resolver is present. The PR's headline change (issue #586 names SavingsTotals as a status-line reader) ships untested at the layer it ships in. The dash-level tests (capreaders_test.go) cover only db.SavingsTotalsCapped, not the proxy wiring.
    • Proof: savingsTestHandler (proxy/savings_test.go:55-62) builds Options with Prices and no Windows. SavingsTotalsCapped → CapCorrectionUSD (dash/savings.go:104) returns errCapUnavailable when windows == nil, so lines 144-155 compare uncapped against uncapped. grep SavingsTotalsCapped proxy/*_test.go returns nothing. Production sets Windows (cmd/context-guru-proxy/main.go:717), so the applied path is the one users get.
    • Fix: give the proxy fixture a window resolver (and traffic past the cap, as in dash's replayCapAPI), then assert Current and Live equal db.SavingsTotalsCapped for the same filters and carry cap_correction_usd / cap_not_applied = false; keep a case that asserts All stays labelled cap_not_applied = true with the stored figure.
  2. dash/savings.go:103 — the correction is all-or-nothing, the headline applies each ledger on its own, so a partial failure breaks the agreement this PR exists to guarantee

    • What fails: CapCorrectionUSD returns an error if either ledger fails, so SavingsTotalsCapped and the series/breakdown cap_correction_usd fall back to the stored figure with cap_not_applied = true. The headline does not work that way: /api/stats applies ApplySummarizeLedger and ApplyReplayLedger independently (dash/api.go:1506-1507; lean path 1406-1416) and ReplayCapNotApplied tracks only the replay ledger (dash/api.go:1508). When the summarize ledger fails and the replay ledger succeeds, the headline totals carry the replay delta and are labelled capped, while series/breakdown report correction 0 and the status line reports the stored figure. A client that sums the buckets and adds cap_correction_usd then does not land on the headline — the exact disagreement #586 reports — precisely in the state where one scan timed out, which is when scans do time out.
    • Proof: dash/savings.go:107-114 returns on the first ledger error. dash/api.go:1491-1499 logs a summarize failure and still applies the replay ledger at 1507; ReplayCapNotApplied stays false because repFailed is false. The two readers then disagree by rep.DeltaUSD().
    • Fix: make both sides match. Either fold each ledger's delta in separately (return the per-ledger deltas and a per-ledger "not applied"), or make the headline skip the whole correction when either ledger fails, so one rule governs both.

Non-blocking

  • Proxy /stats cost class changed. savingsStats now runs two row-streaming ledger scans per call (the current session's full history plus every live session's, up to maxKeepAliveSessions), with no cache, while the dash-side equivalent (/api/stats?lean=1) sits behind statsCache. The SavingsStats doc comment still says the query is "cheap enough to run synchronously" (proxy/savings.go:47-48). The scans are session-bounded, which is the cost class the lean path already accepts, and /stats readers look low-frequency (cg.py, monitoring). Consider a short TTL or updating the comment.
  • No consumer in this repo reads the new series/breakdown fields. dash/ui never reads cap_correction_usd or cap_not_applied from /api/series or /api/breakdown, so the dashboard's own charts still sum uncapped buckets and can read above the headline tile until a consumer (UI or the downstream plugin) adds the correction. The API surface alone may be the intent; if the dashboard page was the target, that half is still open.
  • SavingsTotalsCapped's "agrees with the headline" holds for the lean read, not the full one. The full /api/stats also adds CachesplitHistoricalUSD and the decl-filter credit to total_saved_usd (dash/api.go:1518, 1523-1525); SavingsTotals never did. Pre-existing lean/full gap, but the new doc comment (dash/savings.go:118-120) states the agreement without that limit.
  • capreaders_test.go:103 re-checks only /api/series after pricer = nil; the breakdown route's not-applied answer is not re-checked (its cache key was already used earlier in the test).

What I checked

  • The full diff of eb0f89bf against base 77a910b0, and the code around every change: dash/api.go (series, breakdown, stats lean and full, capCorrection, serveJSON/cachedRoute/routeBounds), dash/savings.go, dash/replaycap.go (ReplayLedgerFor, ApplyReplayLedger), dash/summarizeattr.go (SummarizeLedgerFor, ApplySummarizeLedger), proxy/savings.go, proxy/promexport.go.
  • That the new fields' arithmetic matches the headline: CapCorrectionUSD = summarize delta + replay delta; both ApplySummarizeLedger and ApplyReplayLedger add their delta to baseline, net and total, and the two ledgers cover disjoint components (notSummarizerSQL).
  • Route cost and bounding: series and breakdown are cachedRoute-wrapped with dashHeavyTimeout; the ledger scans run under the compute context, so they are bounded. The UI's default range is all-time (state.from = 0), so the default series/breakdown views scan the whole table per cold cache key — the same class the full stats read already accepts, and the handler comment says so.
  • The golden files: key order and values match encoding/json's sorted-map output for the new fields.
  • The new tests in capreaders_test.go: helpers exist (replayCapAPI, nearEq, replayCapHarness.get), the fixture has real capped credit, and the cache-bypass trick (different bucket) is valid because cachedRoute keys on the query string.
  • docs/data-dependence.md: the new reads use only dashboard metadata the headline already reads; no dependence change, so no row update needed.
  • Issue #586: the four readers it names (status line, metrics export, series buckets, per-group totals) are each addressed, by capping or by labelling.
  • I did not run builds or tests (not approved, Go not installed on this machine).

…rrection (#586)

Round 1 review of #1037.

- CapCorrection runs the summarize and replay ledgers on their own, as the
  headline does. A ledger that fails keeps the other's correction and sets
  cap_not_applied, so series, breakdown and the status line land where the
  headline lands. Before, either failure dropped both.
- API.capCorrection goes through the replayLedger test hook, so a replay
  failure reaches series and breakdown the way it reaches the headline.
- /stats reuses the correction of a scope for 15 seconds. The totals under
  it stay live. Before, each refresh streamed the rows of the current
  session and of every live session through two ledgers.
- Tests: the summarize half of the correction, a fixture with both kinds of
  credit for the partial failure, the proxy wiring (capped session scope,
  labelled lifetime scope, no resolver), and the cache.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>
@boazdavid

Copy link
Copy Markdown
Collaborator Author

Round 1 replies. Fixes are in d577af74 and the doc line in the commit after it.

Reviewer 1, finding 1, and Reviewer 2, finding 2 (the correction was all-or-nothing): fixed.

  • CapCorrection now runs the two ledgers on their own. This is how the headline works.
  • If one ledger fails, the other keeps its correction. cap_not_applied is set.
  • API.capCorrection now goes through the replayLedger hook. A test can fail the replay ledger for series and breakdown.
  • Test: TestCapCorrectionKeepsTheLedgerThatRan. The fixture has both kinds of credit, so each failure leaves a part that is not zero.

Reviewer 1, finding 2 (summarize half never tested): fixed.

  • TestSavingsTotalsCappedCountsTheSummarizeLedger uses a summarize session with credit past its span. It compares with the totals that ApplySummarizeLedger and ApplyReplayLedger give the headline. It does not compare with the replay-only field.
  • I removed the summarize delta from the code on purpose. Both tests then failed.

Reviewer 1, finding 3 (two ledger scans on each /stats refresh): fixed.

  • /stats now keeps the correction of each scope for 15 seconds. The totals stay live on each read.
  • One reader at a time runs the scan for a scope. A second reader waits and uses the result.
  • The session ids of the live scope are sorted on a copy. The keeper lists them in map order, so without this the same set would miss the cache.
  • Tests: TestStatsSavingsReusesTheCorrectionButNotTheTotals and TestCapKeyIgnoresTheOrderOfLiveSessions. A cache that never expires, and a cache that never hits, both fail the first one.

Reviewer 2, finding 1 (no proxy test where the cap runs): fixed.

  • New file proxy/savings_cap_test.go. It gives the proxy a window resolver and a session past the cap.
  • It checks that the current scope carries the correction and equals SavingsTotalsCapped.
  • It checks that the all scope is labelled cap_not_applied: true and keeps the stored figure.
  • It checks that a proxy with no resolver labels the current scope.

Non-blocking items

  • total_saved_usd and the full headline: accepted. SavingsTotals never added DeclFilterSavings or CachesplitHistoricalUSD. The doc comment now says the agreement holds for the baseline, net and total of the lean read.
  • All-time range on series and breakdown: accepted. Both routes are cached. The full /api/stats does the same scan for a lifetime read.
  • The dashboard page does not read the new fields: true. This PR changes the API. The page change is a separate task.
  • Breakdown not re-checked after pricer = nil: fixed by the new failure test, which uses another dim so it does not hit the cache.
  • Data dependence: this change reads only the stored per-request credit that the headline cap already reads. It adds no new dependence.

Tests: go test ./dash ./proxy passes, except two timing tests in proxy that failed once in the full parallel run: TestARealRequestsKeepAliveCandidateSurvivesAndAPingDispatchesIt and TestALateFirstByteOnTheRealTransportNeverReachesTheClient. Both pass alone on this branch and on the base, twice each.

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

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 1 (glm, user of @boazdavid) GLM rits/zai-org/glm-5-3 via Claude Code 2.1.241 offload-review skill, @boazdavid's session resumed 1 of 2 2 of 2 b2843a9f9e approve

Verdict: approve

Findings

None. My three round-1 findings are fixed. I verified each fix in the code. Reviewer 2's two findings are fixed too.

Round-1 findings, resolved

  1. All-or-nothing cap correction — fixed (d577af74). DB.capCorrection (dash/savings.go:107-121) now runs each ledger on its own: one that fails leaves the other's delta in CorrectionUSD and sets NotApplied. The numbers now land where the headline lands in every partial-failure case:

    • Summarize fails, replay runs: headline applies the replay delta (dash/api.go:1413, 1507); reader returns the replay delta. Agree.
    • Replay fails, summarize runs: headline applies the summarize delta and sets replay_cap_not_applied (dash/api.go:1415, 1508); reader returns the summarize delta with cap_not_applied. Agree.
    • Neither runs (no pricer or resolver): both sides keep the stored figure and label it. Agree.
    • TestCapCorrectionKeepsTheLedgerThatRan covers all three with a fixture that holds both kinds of credit, so each failure leaves a non-zero part. The author also mutation-tested it (removed the summarize delta; both tests failed).
    • The label semantics differ from the headline's in one case: a summarize-only failure leaves the headline's replay_cap_not_applied false while the reader's cap_not_applied is true. The numbers agree, and CapNotApplied's comment now says "in whole or in part". Accept.
  2. Summarize half untested — fixed (d577af74). TestSavingsTotalsCappedCountsTheSummarizeLedger uses summarizeEvent rows with credit past the span, asserts the summarize delta is negative and the replay delta is zero, and compares SavingsTotalsCapped's baseline, net and total against an Overview that ApplySummarizeLedger and ApplyReplayLedger corrected — the headline's own arithmetic, not the replay-only JSON field. The replay-only comparison in the older test is now explained in the file comment. Helpers exist (dash/summarizeattr_test.go:50-70, handPrice in dash/accounting_test.go:16).

  3. Uncached ledger scans on each /stats refresh — fixed (d577af74). capCorrectionCache (proxy/savings.go:56-100) keeps each scope's correction for 15 s. The base totals stay live on every read (savingsCapped runs SavingsTotals outside the cache). One scan per key at a time — the lock is held across compute on purpose. capKey sorts the live sessions on a copy, so the keeper's map order cannot split the cache. Tests: TestStatsSavingsReusesTheCorrectionButNotTheTotals (totals move, correction cached, recomputed past the TTL) and TestCapKeyIgnoresTheOrderOfLiveSessions (same set, same key, caller's slice untouched). The staleness is disclosed in the code comment and in the author's reply.

Reviewer 2's findings, resolved

  1. No proxy test where the cap runs — fixed. proxy/savings_cap_test.go gives the handler a 1M window resolver and a session past the cap. It asserts the current scope carries the correction and equals SavingsTotalsCapped, the all scope keeps the stored figure with cap_not_applied: true, and a proxy with no resolver labels the session scope. I checked the wiring: Options.Windows flows to h.opts.Windows (proxy/savings.go:99-100), /stats embeds the block under json:"savings" (metrics/metrics.go:1096, proxy/proxy.go:3037), and the helpers used (New, Mux, setLastSession, InsertEvents, fixedPricer) all exist.
  2. All-or-nothing correction — same as my finding 1. Fixed.

Non-blocking

  • DB.capCorrection (dash/savings.go:110-121) swallows both ledger errors with no log line. Round 1 logged "replay cap unavailable" in this path; the headline still logs its failures (dash/api.go:1495, 1694). The reader gets the label, but an operator gets no log to find out why the cap did not run. Add one slog.Warn per failed ledger.
  • capCorrectionCache.get holds one mutex across compute(), so a slow live-scope scan blocks a concurrent read of the current scope's key too. With one status-line reader this is the intended single-flight; a per-key lock would not serialize unrelated scopes. Fine as is.
  • A cached NotApplied result from a transient scan failure holds for the full 15 s. Labelled, so acceptable.

What I checked

  • Last review: round 1, eb0f89b, 2026-11-10T11:43:40Z.
  • New commits read: 2 — d577af74 "fix(dash): Apply each cap ledger on its own, cache the status-line correction (#586)" and b2843a9f "docs(dash): Say where SavingsTotalsCapped and the full headline differ (#586)".
  • Read in full: 2 reviews, 1 comment, 0 inline comments (from .review-in-reviews.txt, .review-in-comments.txt, .review-in-inline.txt).
  • New items since my last review, and what I did about each:
    • Reviewer 2's round-1 review (posted 11:46:12Z, after my 11:43:40Z): read in full. Its finding 2 matches my finding 1; its finding 1 (missing proxy test) I verified as fixed.
    • The author's round-1 reply (11:54:37Z): read in full. Every claim in it checks out against the code, including the mutation test and the sorted-live-sessions rationale.
    • Commit d577af74: read the full diff and the code around each change — dash/api.go (capCorrection through the replayLedger hook), dash/savings.go (CapResult, CapCorrection, ApplyCap, SavingsTotalsCapped), dash/capreaders_test.go (four new tests), proxy/proxy.go (capCache field), proxy/savings.go (cache, savingsCapped, savingsStats), proxy/savings_cap_test.go.
    • Commit b2843a9f: the doc line on SavingsTotalsCapped, which answers my round-1 non-blocking note about the full headline's extra total addends.
  • The partial-failure agreement against both headline paths: lean (dash/api.go:1404-1416) and full (dash/api.go:1506-1508), with ApplySummarizeLedger (dash/summarizeattr.go:152-162) and ApplyReplayLedger (dash/replaycap.go:617-630).
  • No leftovers of the removed API: grep CapCorrectionUSD errCapUnavailable over non-test Go files finds only the struct fields and their setters.
  • The new tests' helpers and wiring: summarizeEvent/testWindows/handPrice in dash, New/Mux/setLastSession/InsertEvents/fixedPricer/metrics.Snapshot.Savings's json:"savings" tag in proxy.
  • Live tests were not run. Go is not installed on this machine and the review brief forbids builds. The author reports go test ./dash ./proxy passes, with two unrelated timing tests flaky in the parallel run and passing alone on both this branch and the base.

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

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 2 (glm, user of @boazdavid) GLM rits/zai-org/glm-5-3 via Claude Code 2.1.241 offload-review skill, @boazdavid's session resumed 2 of 2 2 of 2 b2843a9f9e90 approve

Verdict: approve

Findings

None. Both round-1 findings are fixed and verified. No new defect in the two new commits.

Earlier findings

  • My finding 1 (no proxy test where the cap runs): fixed. proxy/savings_cap_test.go gives the proxy a 1M window resolver and a session past the cap. TestStatsSavingsCapsTheSessionScopeAndLabelsTheLifetimeScope asserts the Current scope equals SavingsTotalsCapped for the same rows, with a negative correction, and that All keeps the stored figure labelled cap_not_applied: true. TestStatsSavingsLabelsTheSessionScopeWithoutAWindowResolver covers the no-resolver labelling. This is the fix I asked for.
  • My finding 2 (all-or-nothing correction vs the per-ledger headline): fixed. CapCorrection (dash/savings.go:116-132) now runs each ledger on its own: a failed ledger keeps the other's delta and sets NotApplied. I traced every state against both headline paths: no pricer or windows (lean dash/api.go:1404, full :1508), both ledgers running, summarize failing while replay runs (full :1491-1507), and replay failing while summarize runs (lean :1412-1416). In every state the reader's buckets plus cap_correction_usd now land on the headline's totals. TestCapCorrectionKeepsTheLedgerThatRan covers the partial failures with a fixture where both halves are non-zero, and TestSeriesAndBreakdownSayWhenTheReplayLedgerFailed reaches series and breakdown through the replayLedger hook.
  • Reviewer 1, finding 1 (same as my finding 2): fixed, verified above on my own reading.
  • Reviewer 1, finding 2 (summarize half never exercised non-zero): fixed. TestSavingsTotalsCappedCountsTheSummarizeLedger uses real summarizeEvent rows with credit past the span and compares SavingsTotalsCapped against an Overview that ApplySummarizeLedger and ApplyReplayLedger corrected — not against the replay-only field. The fixture gate (sl.DeltaUSD() >= 0 → fatal) makes it self-checking.
  • Reviewer 1, finding 3 (two ledger scans per /stats refresh): fixed. The 15-second capCorrectionCache (proxy/savings.go:63-101) reuses each scope's correction, keeps the totals live, holds one scan per key at a time, and sorts the live-session set on a copy so the same set hits the same entry. TestStatsSavingsReusesTheCorrectionButNotTheTotals pins both halves of that contract, and TestCapKeyIgnoresTheOrderOfLiveSessions the key.
  • Non-blocking items: each accepted with a reason that checks out. The lean-vs-full doc sentence is in b2843a9f (dash/savings.go:145-147); the a.capCorrection hook bypass is gone (dash/api.go:1564-1568); the breakdown not-applied answer is now covered through the shared capCorrection path by the new failure test; the data-dependence statement is in the reply and adds no dependence.

Non-blocking

  • The headline's replay_cap_not_applied still tracks only the replay ledger. When the summarize ledger fails, the headline is labelled "capped" while it missed that half. The readers' cap_not_applied is now the honest label. The figures agree in every state, so this is a label gap in the pre-existing headline code, not a defect of this PR.
  • The proxy cache's mutex is global across scopes, so one scope's scan makes a concurrent /stats call for another scope wait, and /stats has no timeout wrapper (only /metrics does, proxy/proxy.go:614). Bounded by one scan; the steady state under the 15-second TTL is cheap. Worth remembering if /stats grows more scopes.
  • The Live scope's capped fields are not asserted directly in the proxy tests (no fixture puts sessions in the keeper's live set). The path is shared with Current through savingsCapped, and capKey's set handling has its own test, so I accept this.

What I checked

  • Last review: round 1, eb0f89b, 2026-11-10T11:46:12Z
  • New commits read: 2 — d577af74 fix(dash): Apply each cap ledger on its own, cache the status-line correction; b2843a9f docs(dash): Say where SavingsTotalsCapped and the full headline differ
  • Read in full: 2 reviews, 1 comment, 0 inline comments (from .review-in-reviews.txt, .review-in-comments.txt, .review-in-inline.txt)
  • New items since my last review: the author's round-1 reply at 2026-11-10T11:54:37Z (each claim checked against the code, as listed under Earlier findings); commits d577af74 and b2843a9f (full diff read, plus the code around each change)
  • The new CapCorrection/capCorrection split, CapResult, ApplyCap and SavingsTotalsCapped: no remaining caller of the removed CapCorrectionUSD method or errCapUnavailable (grepped); the field CapCorrectionUSD keeps its JSON name, so the wire format is unchanged and the golden files need no update (none were made, correctly).
  • That the reader and the headline agree per state, by tracing the lean path (dash/api.go:1396-1418) and the full path (dash/api.go:1477-1508) against capCorrection's four outcomes.
  • The proxy cache: lock discipline (no re-entry, compute does not call back), the nil-map and over-64 reset, the 15-second TTL, the copy-then-sort in capKey, and that a failed scan's partial result is cached but labelled.
  • Compile-level facts for the new tests: summarizeEvent (dash/summarizeattr_test.go:57), InsertEvents (dash/store.go:546), handPrice, testWindows, offload.EventFreshSummary, fixedPricer, oneMillionWindow satisfying modelinfo.Resolver (internal/modelinfo/modelinfo.go:27), and a.replayLedger's hook (dash/api.go:596-601). All exist with matching signatures.
  • The author's test-run claim (go test ./dash ./proxy passing, two flaky timing tests passing alone on base too) is not verifiable here: Go is not installed and live tests are not approved. The new tests' fixtures are self-gating (they fatal when the fixture stops proving the claim), which is the right shape.

Assisted-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: DAVID AMID <[email protected]>
@amiddavid

Copy link
Copy Markdown
Collaborator

Merged origin/main into this branch. New head: 1a6760f3. I merged twice: main moved while I tested, so the first result was dropped.

  • Remerge-diff: 0 lines. No hand edits. No conflicts.
  • Semantic check: only proxy/proxy.go changed on both sides. Every symbol this PR adds has one definition. capCorrection exists on *API and on *DB; the receivers differ, so there is no clash. go vet ./... is clean.
  • Tests (shared box, -race): ./dash/... and ./proxy/... pass on the final merge.
  • Note: under box load 22, ./dash/... needs about 13 minutes. The default 10-minute Go test limit expired once. It passed with -timeout 40m.
  • CI: all jobs pass, CodeQL and DCO included.

@amiddavid
amiddavid merged commit 975d46b into main Nov 10, 2026
7 checks passed
@github-project-automation github-project-automation Bot moved this from New/ToDo to Done in Rossoctl Issue Prioritization Nov 10, 2026
amiddavid added a commit that referenced this pull request Nov 10, 2026
…ur share as an estimate (#988)

On a Claude subscription, the dashboard Overview now shows saved
tokens, not dollars. The total and each card read the accountant's
tier tokens in /api/stats: tokens.saved, tokens.caused and
tokens.by_feature. Tiers show in the order wr, wr1h, rd, in, then
cost. Below the total, a dim line gives the 5-hour limit share as an
estimate (used% x saved_usd / cost_usd, capped at 100 - used%).

Behavior change: users on a Claude subscription who open the
dashboard Overview. Old: every saving shows in dollars. New: every
saving shows in tokens by kind, with a dim estimate of the 5-hour
share below the total, and no dollars. How to turn it off: nothing to
turn off. API-key, Bedrock, Vertex, manager and hosted users see no
change.
Owner's yes, 2026-11-10, in the integrator session: "1021 and 988 in this order are also ready" and "988 is ready".

Data dependence: metadata only (token counts by tier, the auth kind
and the rate-limit numbers). The same at each storage level.
docs/data-dependence.md has the row.

Reviews: 2 offload reviews (GLM), round 5, both approve at 6da7583 (the merge of main that resolved the dash/ui/app.js conflict by hand). After it: one merge of main (#1037, #1021) with no hand resolution (remerge-diff 0). The 6da7583 hand resolution kept both sides of one line in the Tool deferral card: main's "Not counted in Your preset." text, and #988's saving() wrapper.

Signed-off-by: DAVID AMID <[email protected]>
Assisted-By: Claude Opus 5.5 <[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: other views still read the uncapped replay credit (/api/savings, status-line windows, metrics export, series buckets)

2 participants