Repository navigation
fix(dash): credit the ping saving from the row it rescued, so ping_saved_usd is not always 0 - #677
Merged
Merged
Conversation
…ved_usd is not always 0 (#676) The ping's cost is on the ping row. Its saving is on the agent row the ping kept warm. The ledger added keepalive_saved_usd only on ping rows, so ping_saved_usd was always 0. The home screen then reported every ping as a loss ("Keep-alive pings cost more than they saved"). The ledger now adds the saving on agent rows, through kaSaved, like every other keep-alive figure. A credit with no ping that read the cache in the 5 minutes before it does not count. On one real 7-day window: ping cost $20.18, saving was reported as $0, the corrected saving is $63.55 (net +$43.37). Fixes #676 Assisted-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
amiddavid
commented
Oct 23, 2026
amiddavid
left a comment
Collaborator
Author
There was a problem hiding this comment.
| Reviewer | Kind | Started by | Context | Review | Round | Head | Verdict |
|---|---|---|---|---|---|---|---|
| Reviewer 2 (glm, user of @amiddavid) | GLM rits/zai-org/glm-5-3 via Claude Code 2.1.309 | offload-review skill, @amiddavid's session | fresh | 2 of 2 | 1 of 2 | 9a0b2036584a |
approve |
Verdict: approve
Findings
None. The fix is correct and matches issue #676's proposal.
Non-blocking
- dash/spendexplain.go:338-343 — window boundary: a credit can be counted while its ping's cost is not. The
kaSavedprobe reads ping rows with no window filter. With asincefilter, a rescued row just inside the window can be credited by a ping up to one hour before it, while that ping sits in the warm-up region and is skipped fromping_usd(the!countedcontinue at line 325 runs before the ledger). Effect:ping_saved_usd - ping_usdoverstates the net near the window start.SavingsTotals(dash/savings.go:36-48) has the same shape, so this is a shared boundary artifact, not a regression of this PR. Small on real windows (7-day window in #676). - dash/spendexplain.go:338 —
ping_usdcounts manual pings, unlike every other ledger. The line is unchanged by this PR.SavingsTotalsand the keep-alive tab select ping cost withautoPing(r.keepalive = 1 AND r.manual_ping = 0, dash/manualping.go:33) so manual pings stay their own category. Herer.keepalivecovers both, so a manual ping's cost lands inping_usdwhile its rescue, if any, is booked undermanual_saved_usdelsewhere. Same failure class as #676 (cost without saving) but for the manual category only.
What I checked
- The full diff (
git diff 40868e38..HEAD): 2 files,dash/spendexplain.goanddash/spendexplain_test.go. One commit, DCO sign-off present,Assisted-By:attribution per repo convention. - The old code at base:
PingSavedUSDsummed the rawkeepalive_saved_usdoverkeepalive = 1rows only. The write path never credits a ping row (Event.keepaliveSavedUSD, dash/event.go:1027,// a ping never credits itself), so the old sum was always 0. Confirms the bug. - The new accumulation: non-ping rows add both
PingSavedUSD(viakaSaved) andGrossSavedUSD. No double count:baseline_cost_usd = cost + baselineDeltaUSD(dash/event.go:798) prices the pipeline counterfactual only; the keep-alive credit is a separate mechanism, as insavingsArithmetic(dash/savings.go:65). - The SELECT switch from
r.keepalive_saved_usdtokaSaved("r."): the same reachability test every other keep-alive figure reads through (dash/savings.go:38, dash/query.go:196, dash/overview.go:650). The probe is guarded by> 0first and correlates on tenant and session, so it cannot leak across tenants. It also refuses credits with no covering ping, which the new test pins. - The new test line by line:
kaPing(dash/keepalivetab_test.go:47) gives the pingcache_read = 10000andTokenAccounting: complete, so it is priced and counted inping_usd. The rescued row att0+8mis 4 minutes after the ping, inside the 5-minute coverage window, sokaSavedpays 0.05. The stray credit in sessionuhas no ping row at all, sokaSavedrefuses 0.07. Both assertions match the code path.seedwrites throughinsertBatch, which does not reprice events, so the hand-set credits survive. - Consumers:
ping_saved_usdappears only in this route and its test inside the repo; the embedded UI does not read it. The external consumer (cgcost.pyper #676) gets a non-zero, reachability-tested figure. - Data dependence: no change. The route reads metadata only (costs, timestamps, session ids, token counts).
amiddavid
commented
Oct 23, 2026
amiddavid
left a comment
Collaborator
Author
There was a problem hiding this comment.
| Reviewer | Kind | Started by | Context | Review | Round | Head | Verdict |
|---|---|---|---|---|---|---|---|
| Reviewer 1 (glm, user of @amiddavid) | GLM rits/zai-org/glm-5-3 via Claude Code 2.1.309 | offload-review skill, @amiddavid's session | fresh | 1 of 2 | 1 of 2 | 9a0b2036584a |
approve |
Verdict: approve
Findings
None. The change is correct and tested.
What I verified
- The bug was real and structural.
Event.keepaliveSavedUSD(dash/event.go:1027) returns 0 for
any row withKeepAliveset: "a ping never credits itself". The credit is written on the agent row
the ping rescued. The old code summedr.kaSavedonly inside theif r.keepalivebranch
(dash/spendexplain.go:338-340 before this PR). Soping_saved_usdwas 0 on every window, exactly
as issue #676 says. - The fix is correct. The sum moved to the
elsebranch (dash/spendexplain.go:340-344). Ping
rows keep their cost inPingUSD; agent rows now carry the credit.GrossSavedUSDis unchanged
and does not overlap: it isbaseline - cost, the removed-content counterfactual, while
PingSavedUSDis the avoided cache re-creation. The two counterfactuals are disjoint. - The SQL swap is safe. The SELECT now reads
kaSaved("r.")(dash/spendexplain.go:264) instead
of the rawr.keepalive_saved_usd. The alias"r."is passed, so the reachability subquery
resolves outer columns correctly (the empty-alias trap the docstring at dash/keepalive.go:125
warns about). The same expression already runs in dash/query.go:196, dash/savings.go:38 and
dash/overview.go:650, so the SQL shape is proven against this schema. The> 0guard keeps the
EXISTS probe on credited rows only, per dash/keepalive.go:131. Scan column order and count match
the new SELECT list. - The test proves both halves. The rescued row (session "s", credit 0.05) has a ping 4 minutes
before it, inside the 5-minute reachability window (AnthropicDefaultCacheTTL,
apply/cachelifetime.go:21), sokaSavedpays 0.05. The stray row (session "u", credit 0.07) has
no ping in its session, so the EXISTS fails andkaSavedpays 0. The assertions pin
ping_usd = 0.002andping_saved_usd = 0.05. I traced each value through the seed fixture,
the store insert (dash/store.go:520 writesKeepAliveSavedUSD) and the kaSaved SQL. - No other consumer breaks.
ping_saved_usdis produced only by this route. No existing test
pins the old always-0 behaviour. The change makes the ledger consistent with the keep-alive tab
and the savings route, which already sumkaSavedover agent rows. - Data dependence does not change. The route already read ping rows (
WithKeepAlive = true)
and already read only metadata columns. The new subquery reads ping rows'ts,session_id,
keepalive,cache_read,provider,tenant_id— metadata only, no content.
Non-blocking
- dash/spendexplain.go:342 — a rescue at the window edge can credit a saving whose ping cost
sits outside the window. Withsinceset,PingUSDcounts only pings inside the window, but
thekaSavedsubquery reads the whole table. A ping atsince - 1mthat rescues a request at
since + 1mgivesping_saved_usd > 0withping_usd = 0. The keep-alive tab
(dash/keepalive.go:292,sumBySession) has the same shape, andkaSavedis documented as a
ceiling, so this is a known direction rather than a new defect. No change requested. - dash/spendexplain_test.go:210 — the test pins
ping_usdandping_saved_usdonly.
It does not assertgross_saved_usdstayed 0 (both fixtures setBaselineCostUSD = CostUSD),
nor that the stray row contributed nothing anywhere else. Small gap; the two asserted fields are
the ones the fix touched. - dash/spendexplain.go:330-333 — an unpriced or incomplete rescued row drops its credit.
Thecontinuefor unpriced rows runs before the ledger, so a rescue on a model the pricer no
longer knows vanishes fromping_saved_usd. This matches the existing rule for
GrossSavedUSDon the same rows, so it is consistent. Noting it only.
What I checked
- Full diff of PR #677 (one commit, two files, +34/-3).
- The write path for
keepalive_saved_usd: dash/event.go:819, dash/event.go:985-1049. - The reachability expression and its constraints: dash/keepalive.go:79-179.
- The store insert and scan order: dash/store.go:512-538, dash/spendexplain.go:262-295.
- Test helpers the new test relies on:
spendEv,kaPing(dash/keepalivetab_test.go:47),
seed,get,newTestAPI(dash/api_test.go),mkEvent(dash/store_test.go:12). - All consumers of
PingSavedUSD/ping_saved_usdin the repo (only this route). - Other
kaSaved("r.")call sites for SQL-shape and consistency comparison. - docs/data-dependence.md for a needed row change (none: metadata only, no direction change).
This was referenced Oct 23, 2026
amiddavid
added a commit
that referenced
this pull request
Oct 25, 2026
… in (#692) fix(dash): pin the ping saving to the window the ping cost is counted in Two defects in how the ledgers count keep-alive pings, found by the reviewers of #677 (#678): 1. The saving half looked back with no window limit while every cost half is summed inside the filter's window. A ping just before `since` that kept a request just after it warm added to ping_saved_usd while its cost added to nothing, so the net at the window edge read too high. kaSavedSince now floors the credit's ping probe at `since`, and every ledger that pairs the saving with a windowed cost half uses it: the spend ledger, SavingsTotals, Overview and OverviewLean, the keep-alive tab's ledger, session lists and exporter series, the Sessions page, the per-thread session money, and the campaign cells (floored at the campaign's own activated_at, which is what its cost half uses). Since <= 0, no window, is kaSaved unchanged. Sites with no windowed cost half (StrategyLedger, the per-request drill-down) keep kaSaved. 2. The spend ledger's ping_usd counted every keepalive row, so a manual ping's cost landed in the keeper's category while its saving is booked under manual_saved_usd everywhere else. ping_usd now uses the autoPing rule like every other ledger; a manual ping stays out of it. No data-dependence change: both fixes read metadata only. Tests: one per defect per surface — the keep-alive tab's ledger and the exporter series, SavingsTotals, Overview (pinned to agree with SavingsTotals on the same window), and the two spend-ledger cases. Each fails on origin/main. Written by GLM (rits/zai-org/glm-5-3) through Claude Code Assisted-By: GLM Signed-off-by: DAVID AMID <[email protected]> Closes #678
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
The home screen no longer reports keep-alive pings as a loss when they saved money.
ping_saved_usdin/api/spend/explainwas always $0. Fixes #676.Data dependence: no change. The fix reads metadata only (costs, timestamps, session ids, cache-read counts). It works the same at every storage level.
What changed
dash/spendexplain.go: the ledger adds the keep-alive saving on agent rows, where the write path stores it. Before, it added it only on ping rows, which never carry a saving.kaSaved("r."), like every other keep-alive figure. A credit counts only if a ping that read the cache came in the 5 minutes before the request.cgcost.py. It comparesping_usdwithping_saved_usd, and that comparison is now correct.Effect on real data (one user, 7 days)
ping_usdping_saved_usdHow it was tested
TestSpendExplainLedgerCreditsPingSavingFromTheRescuedRow: one ping plus one rescued request ($0.05, counted), and one credit with no ping near it ($0.07, not counted).keepalive_saved_usdin place ofkaSaved: the test gets 0.12 and fails.go test -race ./dash/...: pass (471 s).gofmtandgo vet: clean.🤖 Generated with Claude Code