Skip to content

fix(dash): credit the ping saving from the row it rescued, so ping_saved_usd is not always 0 - #677

Merged
amiddavid merged 1 commit into
mainfrom
fix/ping-saved-ledger
Oct 23, 2026
Merged

amiddavid merged 1 commit into
mainfrom
fix/ping-saved-ledger

Conversation

@amiddavid

Copy link
Copy Markdown
Collaborator

Summary

The home screen no longer reports keep-alive pings as a loss when they saved money. ping_saved_usd in /api/spend/explain was 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.
  • The saving is read through 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.
  • No change to cgcost.py. It compares ping_usd with ping_saved_usd, and that comparison is now correct.

Effect on real data (one user, 7 days)

Before After
ping_usd $20.18 $20.18
ping_saved_usd $0.00 $63.55
Home screen item "pings cost more than they saved, $19.40" not shown (net +$43.37)

How it was tested

  • New test TestSpendExplainLedgerCreditsPingSavingFromTheRescuedRow: one ping plus one rescued request ($0.05, counted), and one credit with no ping near it ($0.07, not counted).
  • Mutations, both caught:
    1. Raw keepalive_saved_usd in place of kaSaved: the test gets 0.12 and fails.
    2. Old code (saving added on ping rows): the test gets 0 and fails.
  • go test -race ./dash/...: pass (471 s). gofmt and go vet: clean.

🤖 Generated with Claude Code

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

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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 kaSaved probe reads ping rows with no window filter. With a since filter, 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 from ping_usd (the !counted continue at line 325 runs before the ledger). Effect: ping_saved_usd - ping_usd overstates 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_usd counts manual pings, unlike every other ledger. The line is unchanged by this PR. SavingsTotals and the keep-alive tab select ping cost with autoPing (r.keepalive = 1 AND r.manual_ping = 0, dash/manualping.go:33) so manual pings stay their own category. Here r.keepalive covers both, so a manual ping's cost lands in ping_usd while its rescue, if any, is booked under manual_saved_usd elsewhere. 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.go and dash/spendexplain_test.go. One commit, DCO sign-off present, Assisted-By: attribution per repo convention.
  • The old code at base: PingSavedUSD summed the raw keepalive_saved_usd over keepalive = 1 rows 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 (via kaSaved) and GrossSavedUSD. 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 in savingsArithmetic (dash/savings.go:65).
  • The SELECT switch from r.keepalive_saved_usd to kaSaved("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 > 0 first 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 ping cache_read = 10000 and TokenAccounting: complete, so it is priced and counted in ping_usd. The rescued row at t0+8m is 4 minutes after the ping, inside the 5-minute coverage window, so kaSaved pays 0.05. The stray credit in session u has no ping row at all, so kaSaved refuses 0.07. Both assertions match the code path. seed writes through insertBatch, which does not reprice events, so the hand-set credits survive.
  • Consumers: ping_saved_usd appears only in this route and its test inside the repo; the embedded UI does not read it. The external consumer (cgcost.py per #676) gets a non-zero, reachability-tested figure.
  • Data dependence: no change. The route reads metadata only (costs, timestamps, session ids, token counts).

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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 with KeepAlive set: "a ping never credits itself". The credit is written on the agent row
    the ping rescued. The old code summed r.kaSaved only inside the if r.keepalive branch
    (dash/spendexplain.go:338-340 before this PR). So ping_saved_usd was 0 on every window, exactly
    as issue #676 says.
  • The fix is correct. The sum moved to the else branch (dash/spendexplain.go:340-344). Ping
    rows keep their cost in PingUSD; agent rows now carry the credit. GrossSavedUSD is unchanged
    and does not overlap: it is baseline - cost, the removed-content counterfactual, while
    PingSavedUSD is 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 raw r.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 > 0 guard 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), so kaSaved pays 0.05. The stray row (session "u", credit 0.07) has
    no ping in its session, so the EXISTS fails and kaSaved pays 0. The assertions pin
    ping_usd = 0.002 and ping_saved_usd = 0.05. I traced each value through the seed fixture,
    the store insert (dash/store.go:520 writes KeepAliveSavedUSD) and the kaSaved SQL.
  • No other consumer breaks. ping_saved_usd is 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 sum kaSaved over 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.
    With since set, PingUSD counts only pings inside the window, but
    the kaSaved subquery reads the whole table. A ping at since - 1m that rescues a request at
    since + 1m gives ping_saved_usd > 0 with ping_usd = 0. The keep-alive tab
    (dash/keepalive.go:292, sumBySession) has the same shape, and kaSaved is 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_usd and ping_saved_usd only.
    It does not assert gross_saved_usd stayed 0 (both fixtures set BaselineCostUSD = 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.
    The continue for unpriced rows runs before the ledger, so a rescue on a model the pricer no
    longer knows vanishes from ping_saved_usd. This matches the existing rule for
    GrossSavedUSD on 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_usd in 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).

@amiddavid
amiddavid merged commit 6f5b60e into main Oct 23, 2026
5 checks passed
@github-project-automation github-project-automation Bot moved this from New/ToDo to Done in Rossoctl Issue Prioritization 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
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.

fix(dash): ping_saved_usd is always 0, so the home screen says keep-alive loses money

1 participant