Repository navigation
fix(dash): pin the ping saving to the window the ping cost is counted in - #692
Merged
Merged
Conversation
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
commented
Oct 25, 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.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.
leanWindowMainQuerygot the samekaSavedSincechange, but no new test drives it with asince. The new Overview test (TestOverviewStopsThePingSavingAtTheWindowStart) exercises the fullOverview()path only. The lean path serves/api/stats?lean=1, and the status line readskeepalive_net_usdfrom 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.
PingUSDcounts a ping only when it is counted,completeand priced. ThekaSavedSinceprobe checks neither. So an in-window ping with partial accounting can carry a credit while its cost stays out ofping_usd. This asymmetry predates the PR (kaSavednever 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.
kaSavedGatetestskp.keepalive = 1 AND kp.cache_read > 0with nomanual_pingfilter. In the spend ledger a manual ping can now carry aping_saved_usdcredit while its cost is excluded fromping_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
kaSavedcaller in the package, converted or not:- Converted and consistent (windowed cost half, floored saving half):
KeepAliveLedger(all three saving queries and the per-sessionsumBySession),KeepAliveNetUSDByTenant,KeepAliveSessions,KeepAliveLive,SavingsTotals,Overview(main query plus its own cost query at overview.go:1030),leanWindowMainQuery,SessionsOrdered(cost half viapingsBySessiononwithKeepAlive(f)),cacheThreadsQuery(ping and manual cost summed under the same windowedcond),CampaignRealSavings(cost half gatedts >= since, floor at the samesince). - Left unconverted, correctly:
StrategyLedger(both halves are all-time),requestColsin query.go (per-row detail, no paired cost aggregate).
- Converted and consistent (windowed cost half, floored saving half):
Filter.where()semantics:Sincerenders asr.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.Untilneeds no floor:kp.ts <= r.tsand the outerr.ts < untilbound it already.- SQL correctness of the splice:
pingFloorlands inside theEXISTSonkp, afterkp.ts <= r.ts, as a literal fromstrconv.FormatInt— no injection, no bind-order change (important forCampaignRealSavings, 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 theScanorder;insertBatchwritesmanual_ping;kaSavedSincefloors atf.Since, not the warm-upwarm.Since, which is right becausePingUSDaccumulates only for rows withcountedtrue. - 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 (
mkEventsets provideranthropic, nocache_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 cleanorigin/mainwith 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./statscallsSavingsTotalswithSince: 0, wherekaSavedSinceiskaSavedunchanged — the append-only/statscontract 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
commented
Oct 25, 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.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 haskeepalive = 1too (dash/manualping.go says so). Every cost half now usesautoPing, which excludes manual pings. So a manual ping that is the only reachable refresh can carry a credit intoSavedUSD/PingSavedUSDwhile its cost sits in the manual category. The case is narrow: the write path never credits through a manual ping (PingNowleavese.pingsande.refreshedalone, 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 withkp.manual_ping = 0insidekaSavedGate, plus a test. - Missing tests at some converted call sites. The floor is tested for
KeepAliveLedger,KeepAliveNetUSDByTenant,SavingsTotals,Overview, andSpendExplainFor(window and manual ping). It is not tested foroverviewLeanWindow,CampaignRealSavings,SessionsOrdered,ThreadsFor's money,KeepAliveSessions, andKeepAliveLive. All six apply the same helper in the same shape, so I rate this below the finding bar.CampaignRealSavingsis the most distinct query (its own arg order), so a regression there would be silent. - dash/spendexplain.go:171 — the
PingSavedUSDdoc 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 samesincewith the same>=boundary. Traced at:KeepAliveLedger(saving query, cost query, bothsumBySessionhalves),KeepAliveNetUSDByTenant(credit and cost passes),KeepAliveSessions,KeepAliveLive,SavingsTotals,Overview,leanWindowMainQuery,SessionsOrdered+pingsBySession,cacheThreadsQuery,CampaignRealSavings,SpendExplainFor. - The two
kaSavedcallers 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 useswarm.Since = f.Since - ttl1h, but the floor and thecountedcheck both usef.Since. Warm-up rows are scanned for thread state only and skipped before any ledger accumulation. Consistent.- SQL construction.
kaSavedSinceembedssincethroughstrconv.FormatInt, not a placeholder. So the bind-arg order inCampaignRealSavings— where the CASE sits in the SELECT and the comment calls the order load-bearing — is unchanged.since <= 0degrades tokaSaved, which matchesFilter.where()'sSince > 0gate andcounted'sf.Since == 0case. spendRowscan order. The SELECT addsr.manual_pingafterr.keepalive; the Scan adds&mpafter&ka. They match.manual_pingisINTEGER NOT NULL DEFAULT 0(dash/schema.go:189), so the scan into anintcannot 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 bypasseskaSaved/kaSavedSinceexcept the two noted above and the backfill, which only writeskeepalive_strategy_id.
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]>
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
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 atsince - 1mthat kept a request atsince + 1mwarm added toping_saved_usdwhile its cost added to nothing.kaSavedSince(alias, since)indash/keepalive.gofloors the credit's ping probe atsince.since <= 0(no window) iskaSavedunchanged.dash/spendexplain.go);SavingsTotals(dash/savings.go) andOverview/OverviewLean— SavingsTotals' doc promises the two agree;KeepAliveSessions,KeepAliveLive, andKeepAliveNetUSDByTenant(dash/keepalive.go);dash/query.go), the per-thread session money (dash/cachestate.go), and the campaign cells (dash/campaignsavings.go, floored at the campaign'sactivated_at, which is what its cost half uses).kaSaved:StrategyLedger(all-time on both halves) and the per-request drill-down column list.Item 2 —
ping_usdcounted manual pings. The spend ledger added every row withr.keepalive = 1. It now uses theautoPingrule (r.keepalive = 1 AND r.manual_ping = 0,dash/manualping.go) like every other ledger. A manual ping's cost stays out ofping_usd; its saving is already booked undermanual_saved_usdelsewhere.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/maincopy on the eval box and fails there with the numbers the issue predicts (0.08 vs 0.03;ping_usd0.052 vs 0.002).gofmt -l dash/go vet ./dash/go test ./dash/ -run …go test ./dash/origin/main+ new test filesgo test -race ./dash/Closes #678
🤖 Generated with Claude Code