Skip to content

fix(dash): pin the ping saving to the window the ping cost is counted in - #692

Merged
amiddavid merged 1 commit into
mainfrom
fix/spend-ledger-pings
Oct 25, 2026
Merged

amiddavid merged 1 commit into
mainfrom
fix/spend-ledger-pings

Conversation

@amiddavid

Copy link
Copy Markdown
Collaborator

Summary

Written by GLM (rits/zai-org/glm-5-3) through Claude Code. Fixes both defects #678 found in how the ledgers count keep-alive pings.

What changed

Item 1 — a ping before the window could add a saving with no cost. Every ledger sums the ping COST inside the filter's window, but the saving's reachability check (kaSaved) looked at pings with no window limit. A ping at since - 1m that kept a request at since + 1m warm added to ping_saved_usd while its cost added to nothing.

  • New helper kaSavedSince(alias, since) in dash/keepalive.go floors the credit's ping probe at since. since <= 0 (no window) is kaSaved unchanged.
  • Applied at every site that pairs the saving with a windowed cost half, so the numbers agree:
    • the spend ledger (dash/spendexplain.go);
    • SavingsTotals (dash/savings.go) and Overview / OverviewLean — SavingsTotals' doc promises the two agree;
    • the keep-alive tab: the ledger, KeepAliveSessions, KeepAliveLive, and KeepAliveNetUSDByTenant (dash/keepalive.go);
    • the Sessions page (dash/query.go), the per-thread session money (dash/cachestate.go), and the campaign cells (dash/campaignsavings.go, floored at the campaign's activated_at, which is what its cost half uses).
  • Sites with no windowed cost half keep kaSaved: StrategyLedger (all-time on both halves) and the per-request drill-down column list.

Item 2 — ping_usd counted manual pings. The spend ledger added every row with r.keepalive = 1. It now uses the autoPing rule (r.keepalive = 1 AND r.manual_ping = 0, dash/manualping.go) like every other ledger. A manual ping's cost stays out of ping_usd; its saving is already booked under manual_saved_usd elsewhere.

No data-dependence change: both fixes use metadata only.

How it was tested

Five new tests, one per defect per surface. Each was run against a clean origin/main copy on the eval box and fails there with the numbers the issue predicts (0.08 vs 0.03; ping_usd 0.052 vs 0.002).

Run Where Result
gofmt -l dash/ fix copy clean
go vet ./dash/ fix copy ok
5 new tests, go test ./dash/ -run … fix copy all PASS
full go test ./dash/ fix copy ok (89.6 s)
5 new tests on clean origin/main + new test files main copy all FAIL as required
full go test -race ./dash/ fix copy ok

Closes #678

🤖 Generated with Claude Code

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]>

@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.310 offload-review skill, @amiddavid's session fresh 1 of 2 1 of 2 940e7c939089 approve

Verdict: approve

Findings

None. I could not prove a defect. Both fixes match what #678 asked for, and the numbers agree across surfaces.

Non-blocking

  • dash/overview_lean.go:112 — the lean path has no window test. leanWindowMainQuery got the same kaSavedSince change, but no new test drives it with a since. The new Overview test (TestOverviewStopsThePingSavingAtTheWindowStart) exercises the full Overview() path only. The lean path serves /api/stats?lean=1, and the status line reads keepalive_net_usd from it. The change is the same one-line pattern, so I do not block on it.
  • dash/spendexplain.go:341-349 — the two halves of the spend ledger still gate on different row predicates. PingUSD counts a ping only when it is counted, complete and priced. The kaSavedSince probe checks neither. So an in-window ping with partial accounting can carry a credit while its cost stays out of ping_usd. This asymmetry predates the PR (kaSaved never checked accounting), and the floor narrows it. Noting it so the next ledger change knows.
  • dash/keepalive.go:188-198 — the probe still admits manual pings as credit carriers. kaSavedGate tests kp.keepalive = 1 AND kp.cache_read > 0 with no manual_ping filter. In the spend ledger a manual ping can now carry a ping_saved_usd credit while its cost is excluded from ping_usd. Every other ledger has the same convention on the saving side, so the PR is consistent with them. Pre-existing; a separate change if you want it.

What I checked

  • Read CLAUDE.md, docs/design.md, the full diff, and the code around every hunk.
  • Every kaSaved caller in the package, converted or not:
    • Converted and consistent (windowed cost half, floored saving half): KeepAliveLedger (all three saving queries and the per-session sumBySession), KeepAliveNetUSDByTenant, KeepAliveSessions, KeepAliveLive, SavingsTotals, Overview (main query plus its own cost query at overview.go:1030), leanWindowMainQuery, SessionsOrdered (cost half via pingsBySession on withKeepAlive(f)), cacheThreadsQuery (ping and manual cost summed under the same windowed cond), CampaignRealSavings (cost half gated ts >= since, floor at the same since).
    • Left unconverted, correctly: StrategyLedger (both halves are all-time), requestCols in query.go (per-row detail, no paired cost aggregate).
  • Filter.where() semantics: Since renders as r.ts >= ? on the same filter object each pair of queries shares, so the floor constant equals the cost half's window start in every converted site. Until needs no floor: kp.ts <= r.ts and the outer r.ts < until bound it already.
  • SQL correctness of the splice: pingFloor lands inside the EXISTS on kp, after kp.ts <= r.ts, as a literal from strconv.FormatInt — no injection, no bind-order change (important for CampaignRealSavings, whose comment warns about SELECT-before-WHERE binding; the floor adds no placeholder).
  • The spend-explain rework by hand: the SELECT column order (r.keepalive, r.manual_ping, r.token_accounting) matches the Scan order; insertBatch writes manual_ping; kaSavedSince floors at f.Since, not the warm-up warm.Since, which is right because PingUSD accumulates only for rows with counted true.
  • The five new tests, traced by hand (I could not run them; live tests are not approved): fixture gaps sit inside the 5-minute default TTL (mkEvent sets provider anthropic, no cache_ttl), so the early ping is reachable without the floor and the floor is the only thing that zeroes it. The asserted numbers (0.03, 0.003, 0.027, 0.002) follow from the fixtures. The PR body reports each test fails on clean origin/main with the issue's predicted numbers.
  • Existing tests that set Since (keepalivetab, savings, overview_lean, kvcacheholdout, replay-clipping): none of them pairs a pre-window ping with a post-window credit, so the floor does not change what they assert. /stats calls SavingsTotals with Since: 0, where kaSavedSince is kaSaved unchanged — the append-only /stats contract keeps both its field names and its values.
  • The window-edge trade-off: a ping paid in one window whose credit lands in the next is now counted in neither window's net, only in the unbounded view. Each window's net can no longer overstate. That is the direction #678 proposed, and under-claiming is the safe direction everywhere else in this repo too.
  • Data dependence: no change; both fixes read metadata columns only. The PR states this.

@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.310 offload-review skill, @amiddavid's session fresh 2 of 2 1 of 2 940e7c939089 approve

Verdict: approve

Findings

None. The change is correct at every call site I traced.

Non-blocking

  • dash/keepalive.go:193 — the credit's ping probe still accepts a manual ping. The probe reads kp.keepalive = 1 AND kp.cache_read > 0. A manual ping has keepalive = 1 too (dash/manualping.go says so). Every cost half now uses autoPing, which excludes manual pings. So a manual ping that is the only reachable refresh can carry a credit into SavedUSD/PingSavedUSD while its cost sits in the manual category. The case is narrow: the write path never credits through a manual ping (PingNow leaves e.pings and e.refreshed alone, keepalive/manual.go), and a manual ping needs a live, un-stopped entry. The probe line is unchanged by this PR, and the PR aligns SpendExplain with the rule every other ledger already uses. Fix later with kp.manual_ping = 0 inside kaSavedGate, plus a test.
  • Missing tests at some converted call sites. The floor is tested for KeepAliveLedger, KeepAliveNetUSDByTenant, SavingsTotals, Overview, and SpendExplainFor (window and manual ping). It is not tested for overviewLeanWindow, CampaignRealSavings, SessionsOrdered, ThreadsFor's money, KeepAliveSessions, and KeepAliveLive. All six apply the same helper in the same shape, so I rate this below the finding bar. CampaignRealSavings is the most distinct query (its own arg order), so a regression there would be silent.
  • dash/spendexplain.go:171 — the PingSavedUSD doc is loose. It says "the pings inside the window kept warm". The probe also accepts manual pings, per the first note. Wording only.

What I checked

  • The full diff, and the code around each hunk, in all 11 files.
  • Window consistency, both halves of every net. Each converted site sums its ping COST inside Filter.where()'s window (r.ts >= since), and now floors the credit's probe at the same since with the same >= boundary. Traced at: KeepAliveLedger (saving query, cost query, both sumBySession halves), KeepAliveNetUSDByTenant (credit and cost passes), KeepAliveSessions, KeepAliveLive, SavingsTotals, Overview, leanWindowMainQuery, SessionsOrdered + pingsBySession, cacheThreadsQuery, CampaignRealSavings, SpendExplainFor.
  • The two kaSaved callers left unfloored are correct. requestCols (dash/query.go:196) is a per-row display read with no window beside it. StrategyLedger (dash/keepalivestrategy.go:68) has no time bound on either half, so both span the strategy's full history.
  • SpendExplainFor's warm-up span. The WHERE uses warm.Since = f.Since - ttl1h, but the floor and the counted check both use f.Since. Warm-up rows are scanned for thread state only and skipped before any ledger accumulation. Consistent.
  • SQL construction. kaSavedSince embeds since through strconv.FormatInt, not a placeholder. So the bind-arg order in CampaignRealSavings — where the CASE sits in the SELECT and the comment calls the order load-bearing — is unchanged. since <= 0 degrades to kaSaved, which matches Filter.where()'s Since > 0 gate and counted's f.Since == 0 case.
  • spendRow scan order. The SELECT adds r.manual_ping after r.keepalive; the Scan adds &mp after &ka. They match. manual_ping is INTEGER NOT NULL DEFAULT 0 (dash/schema.go:189), so the scan into an int cannot fail on NULL.
  • The new tests' arithmetic. Recomputed each expected value (0.03 saved, 0.003 ping, 0.027 net, MissesAvoided 1, the grouped per-tenant net) against the probe's TTL rules. The "late" control row confirms the floor does not eat an in-window credit. Existing window tests (TestCampaignRealSavingsRespectsTheSinceBound, the replay-ceiling clip test) do not assert the old unfloored values, so nothing existing contradicts the new behavior.
  • Remaining readers of keepalive_saved_usd. Grepped the package. No aggregate reader bypasses kaSaved/kaSavedSince except the two noted above and the backfill, which only writes keepalive_strategy_id.

@amiddavid
amiddavid merged commit caac0b8 into main Oct 25, 2026
5 checks passed
@github-project-automation github-project-automation Bot moved this from New/ToDo to Done in Rossoctl Issue Prioritization Oct 25, 2026
amiddavid added a commit that referenced this pull request Oct 25, 2026
Main added #691 and #692. The only conflict was docs/data-dependence.md:
#691 added three sentences to the end of the "Keep-alive pings" row, and
this branch edits the "Body stash" row next to it. Main's keep-alive row
is kept as it is, and so is this branch's Body stash row.

Also, in the same commit, two small round-2 fixes:
- Delete spendHeld, which has no caller since the claim replaced it.
- Say that sweep_not_registered is counted at the request, not at a ping.

Assisted-By: Claude Opus 5.5
Signed-off-by: DAVID AMID <[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.

fix(dash): spend ledger counts manual pings in ping_usd, and can credit a ping saving at the window edge with no cost

1 participant