Repository navigation
feat(dash): store the accountant's tier tokens and serve them from /api/stats - #999
Conversation
amiddavid
left a comment
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.321 | offload-review skill, @amiddavid's session | fresh | 2 of 2 | 1 of 2 | a8a4c191bfaf |
approve |
Verdict: approve
Findings
None. I could not prove a defect. Details of the checks are below.
Non-blocking
- dash/query.go:174 and dash/query.go:316 — the per-request read path never serves the new columns.
requestCols/scanRequestand the request_components query do not readtok_*. Soacc_tokensandcomponents[].tokensappear only on the live SSE feed (dash/sse.go marshals the Event), never on/api/requestsor/api/requests/{id}. The field comments say "Stored (requests.tok_*)", which is true, but a reader may expect the fields on a stored row. The PR scope is/api/stats(the commit title says so), so this is a gap to close later, not a defect. - dash/acctokens.go:219 —
by_feature["cachesplit"]merges two dollar figures into one token entry. The entry sums the request-level split effects (tok_split_*) and the cachesplit component's own op tokens, when a priced cachesplit row exists. In dollars these stay apart:cachesplit_saved_usdholds only the effects, the component'ssaved_usdholds its ops. SotokUSD(by_feature["cachesplit"])can exceedCachesplitSavedUSD. The code comment (AccTokenStats.ByFeature) states the merge; docs/dashboard.md says "every dollar saving above has its token form here", which is then not exact for this one entry. The tests do not cover a session where both halves exist. - dash/overview_lean.go:84 — lean now runs 3 bounded aggregates, not 1. The status line is the lean client and reads no
tokensfield, so every tick pays the two extra range scans (the effects aggregate and the components join). The #502 budget was measured for one query (~45 ms on a 20,000-request session; overview_lean.go:102). The queries are indexed and TestOverviewLeanQueriesAreIndexed covers them, and full/lean agreement is a fair reason to share the read. Worth watching the status line's latency on large sessions.
What I checked
- The full diff, every changed line: dash/accountant_price.go, dash/acctokens.go, dash/acctokens_test.go, dash/event.go, dash/keepalivetab_test.go, dash/overview.go, dash/overview_lean.go, dash/overview_lean_test.go, dash/schema.go, dash/store.go, the three golden files, and the three docs pages.
- SQL shape of insertBatch (dash/store.go:580). I counted the columns and the placeholders by script. requests: 95 base columns + 32 token columns = 127, and 95 literal
?+placeholders(32)= 127. request_components: 17 + 8 = 25 on both sides. The Exec argument lists match (95 and 17 base args; the trailing comma accounts for my first miscount). - Column-name agreement.
flowColumns,TokenFlow.args,flowOf, the ddl in dash/schema.go and theadditiveColumnsentries in acctokens.go's init all spell the same names in the same order.requestTokenArgsfollowsrequestTokenEffects(ka, split, ttl, ended). The init appends to a package var initialized before any init runs, and the read-only shim (dash/store.go:346) reads the list at connect time, so file order cannot matter. - Filter semantics.
accTokensRequestQueryuseswithKeepAlive(f).where()and gates every effect sum onr.keepalive = 0; ping tokens useautoPing(keeper pings only, manual pings excluded), the same ruleKeepAlivePingUSDuses.accTokensComponentQueryuses plainf.where(), which excludes pings; ping rows carry no component rows, so nothing is lost. - The kaSaved interaction (dash/keepalive.go:244). The read-time correction trusts
keepalive_saved_usdas stored only foracc_priced = 1rows. Thetok_ka_*columns are nonzero only on those same rows (fallback and legacy rows have zero tokens), so the token figure and the corrected dollar figure describe the same population. A held estimate keeps its rescue tokens, as it keepsKeepAliveSavedUSD. - Attribution invariants in AccountantFigure. Dollars and tokens are added or skipped by the same conditions in every branch: ops (dry run, spend, unpriced-with-no-tokens), breaks (in-baseline, owned, ended, dry-run), rescue, split, TTL, mark effects.
TokByComponentnever holds the TTL or ended-break legs, soby_featurecannot double-count. A headttl operation would put op tokens on the headttl row while the TTL effect legs stay inAccTokens.TTL; the row's dollars hold both, so the sums still match. - Held estimates and repricing.
PriceandPriceModeboth callclearAccTokensfirst.accOverridesets tokens only after every failure return, so a fallback leaves none behind. The held path zeroes component tokens and the TTL/ended legs, and keeps rescue and split, exactly as it does the dollars. The headttl and ended-change rows are added before the duplicate-name checks re-run, so a secondPriceModecannot duplicate rows. - The 5m/1h write split.
event.godefinesCacheWrite1has the part ofCacheWritebilled at 1h, soMAX(cache_write - cache_write_1h, 0)is the 5m part. That decomposition prices to the same number asCostWithCacheWrite1h, so the ping tokens are the token form ofkeepalive_ping_usd. - Migration and old databases. The new columns are in the ddl and in
additiveColumns;addColumnsprobes pragma table_info and is idempotent; the read-only shim adds missing columns as defaults. Tests cover a fresh database, a dropped-column database reopened, and pre-column rows reading 0 and counting as unmeasured. - Lean/full agreement. Both paths call the same
DB.AccTokens(f); TestAccTokens_LeanAgreesWithFull checks a session and a window. The golden files show the sametokensobject in stats.json and stats_lean.json. - Repo rules. Data dependence: docs/data-dependence.md updated with the reason in plain words and "Decided by: David Amid, #998". No proxy or library behavior changes;
/api/statsis append-only and only new fields were added. Tests cover the new behavior (attribution, held, fallback-clears, sums, lean agreement, empty/old rows, schema, migration).
Live tests were not run (not approved; Go is not on this machine). All reasoning above is from reading the code.
amiddavid
left a comment
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.321 | offload-review skill, @amiddavid's session | fresh | 1 of 2 | 1 of 2 | a8a4c191bfaf |
blocking |
Verdict: blocking
Findings
- dash/query.go:314 — the stored per-request tokens are never read back, so the same request shows
acc_tokenslive and loses it on reload- What fails:
PriceModesetsEvent.AccTokensandCompRow.Tokensbefore the event is published, so the SSE feed (/api/events, sse.gowriteEventmarshals the whole Event) serves them. No stored read returns them:requestCols(query.go:180-199) names norequests.tok_*column, andDB.Request's component SELECT (query.go:314-317) names norequest_components.tok_*column. A client that rendersacc_tokensor a component'stokensfrom the feed shows the fields on the live row, then the same request from/api/requests/{id}after a reload omits them (omitzero). Every other stored field onEventandCompRowround-trips; these are the first that do not. - Proof:
dash/event.go:478(AccTokens ... json:"acc_tokens,omitzero", comment "Stored (requests.tok_)"),dash/event.go:671(Tokens ... json:"tokens,omitzero", comment "Stored (request_components.tok_*)"), versusdash/query.go:180-199anddash/query.go:314-328— neither SELECT names a tok column, and no other read path indash/does (checked everyFROM request_componentsand the requests list). - Fix: read the columns back — extend
requestCols/scanRequestwith the 32 request columns and the component SELECT with the 8 component columns — or state in both field comments that per-request tokens are served only by/api/statsand the live feed, never by a stored read, so the flap is a documented contract.
- What fails:
Non-blocking
dash/acctokens.go:219-224—by_feature["cachesplit"]merges two different figures: the request-level split effect and the cachesplit component row's own operations. Their dollars live in two columns (cachesplit_saved_usdand the row'ssaved_usd), so pricing that one entry matches neither dollar column. The merge is documented in the struct comment; a reader comparing tokens to dollars per feature will not reproduce this entry.dash/overview.go:431— the comment "Every dollar saving above has its token form here" overclaims. The decl-filter credit, the cachesplit-historical credit,defer_net_usdand the manual-ping savings have no token form intokens. Say "every accountant-measured saving" as docs/dashboard.md does.- The lean path (
overview_lean.go:84) now runs 2 more queries on everylean=1call, and no current lean client (statusline.py, cg.py) readstokens. The queries are EXPLAIN-tested and bounded, and full/lean agreement is the stated goal; noting the cost only. tokens_unmeasured_requestscounts everyacc_priced = 0agent row, including bypassed and observe-mode rows and rejected requests. "Could not price" is broad but the doc says exactly that.
What I checked
- Read CLAUDE.md, docs/design.md, and the full diff (16 files, +858/-16).
- Traced every token attribution in
AccountantFigureagainst every dollar attribution (ops, breaks, rescue, split, TTL, mark legs, ended-change): eachaddTok/addTierscall sits next to the dollar line it mirrors; headttl and ended_change rows carry dollars only, their tokens stay inAccTokens, so no token is counted twice. The held-estimate path zeroes component, TTL and ended-change tokens and keeps rescue and split, matching the dollars. - Verified
PriceandPriceModeclear the tokens on every path, including fallbacks (clearAccTokensat the start of both,accOverridesets tokens only after all gates pass). - Counted the INSERT columns, placeholders and bound args in
store.goby script: 95 + 32 = 127 columns, 127 placeholders, 127 args forrequests; 17 + 8 = 25 forrequest_components. Aligned. - Checked
flowColumns/args/flowOfordering, the schema DDL names against the generated names, theinit()append toadditiveColumns(package vars initialize beforeinit()), and the additive migration test (DROP COLUMN then reopen). - Checked the two stats queries' column/scan alignment (38 destinations), the agent/ping CASE split against
Filter.where()andautoPing(manual pings excluded from both halves, matchingkeepalive_ping_usd), the 5m-write derivationMAX(cache_write - cache_write_1h, 0)against the schema's tier convention, and the EXPLAIN-index test coverage for both scopes. - Read the new tests line by line and checked their fixtures and expectations against the code paths they name (helpers
figOf,accTestPrice,mkEvent,openTestDBall exist). - Checked the data-dependence row update (tokens are numbers only, metadata level unchanged, "Decided by" added) and the docs (dashboard.md, reference.md anchor, golden files regenerated via CG_GOLDEN_UPDATE).
- Did not run builds or tests (live tests not approved; Go is not on this machine).
|
Round 1 fixes are in commit 573c15a.
Tests: all |
amiddavid
left a comment
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.321 | offload-review skill, @amiddavid's session | resumed | 1 of 2 | 2 of 2 | 573c15a6959d |
approve |
Verdict: approve
Findings
None. My round-1 finding is fixed, and the fix commit introduces no defect I can prove.
Round 1 to round 2
- My finding 1 (dash/query.go:314 — stored tokens never read back): fixed.
requestColsnow appendsrequestTokenSelect(32r.tok_*columns) andscanRequestappendsrequestTokenDest(&e.AccTokens)(32 destinations, same order).DB.Request's component SELECT appends the 8request_components.tok_*columns and scansc.Tokens.dest(). Both users ofrequestCols(db.Requestslist at query.go:270 andDB.Requestat query.go:309) queryFROM requests r, so ther.prefix resolves on both. The single-request read and the list now return what the live SSE row returns. New testTestAccTokens_RoundTripThroughTheStorewrites a priced event and comparesacc_tokensand every component'stokensafter reading back by id and in the list; the fixture's values differ per effect and per tier, so an order mismatch would fail it. - My non-blocking "Overview comment overclaims": fixed. The comment now says "every accountant-measured saving" and names the exceptions (declaration-filter credit, historical split credit,
defer_net_usd, manual pings). - My non-blocking "one cachesplit entry": accepted as kept. The author kept the merge and documented it in docs/dashboard.md: the entry's dollars are
cachesplit_saved_usdplus thecachesplitcomponent'ssaved_usd. The statement is now exact for accountant-priced rows. - My non-blocking lean-queries and unmeasured notes: accepted as kept, with the reasons given (bounded and EXPLAIN-tested; the doc states the population). I have nothing to add against them.
- Reviewer 2's round-1 review (approve, non-blocking only): their three non-blocking items are the same gaps as mine (read-back, cachesplit merge, lean queries). All three are now fixed or documented as above. I checked each myself in round 1; no separate finding to agree with or dispute.
Non-blocking
- docs/dashboard.md, the
cachesplitbullet: "its dollars arecachesplit_saved_usdplus thesaved_usdof thecachesplitcomponent" is exact only for accountant-priced rows. A cachesplit row written before the accountant switch hassaved_usdfrom the legacy rule and no tokens. The same caveat applies to everyby_featureentry, andtokens_unmeasured_requestsmarks those rows. Doc-level only.
What I checked
- Last review: round 1, a8a4c19, 2026-11-09T21:05:03Z.
- New commits read: 1 — 573c15a "fix(dash): read the accountant tokens back from the store" (full diff read: dash/acctokens.go, dash/acctokens_test.go, dash/overview.go, dash/query.go, docs/dashboard.md).
- 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 comment at 2026-11-09T21:30:36Z (fix summary and test results — checked every claim against the diff) and commit 573c15a (reviewed below). Reviewer 2's review at 21:03:47Z predates my last review; read it in full now and covered its items above.
- Verified the read-back alignment:
requestTokenSelectandrequestTokenDestboth followrequestTokenEffects(ka, split, ttl, ended) ×flowColumns(saved in/rd/w5m/w1h, caused in/rd/w5m/w1h); the component SELECT matchesTokenFlow.dest(). Both SELECT and Scan append at the end, so the pre-existing base alignment is untouched. - Checked
stringsis imported in query.go, thatTokenFlow.dest()'s pointer receiver is used on addressable values only, and that no other query selectsrequestColsor scansrequest_componentswith a column list that would now misalign (every otherrequest_componentsquery names its columns and is unchanged). - Checked the golden files need no regeneration: the demo database has no
acc_pricedrows, soacc_tokensstays absent (omitzero) on the golden request reads. - Confirmed no behavior change beyond the new fields: the diff only adds columns to SELECT lists and scan targets.
- Did not run builds or tests (live tests not approved; Go is not on this machine). The author reports
./dash/...passing on the eval box with-race.
amiddavid
left a comment
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.321 | offload-review skill, @amiddavid's session | resumed | 2 of 2 | 2 of 2 | 573c15a6959d |
approve |
Verdict: approve
Findings
None. The round-1 blocking finding is fixed and verified. The new commit adds no defect.
Earlier findings
- Reviewer 1, finding 1 (blocking): the stored tokens were never read back. Fixed in 573c15a, and I verified the fix myself:
requestCols(dash/query.go:199) now appendsrequestTokenSelect(the 32requests.tok_*columns,r.-qualified).scanRequestappendsrequestTokenDest(&e.AccTokens)(32 pointers). I counted by script, treatingkaSaved("r.")as one item: 120 select items and 120 scan targets. The orders match — both followrequestTokenEffects(ka, split, ttl, ended), each inflowColumnsorder (saved in/rd/w5m/w1h, then caused).- The component SELECT in
DB.Request(dash/query.go:316) now reads the 8request_components.tok_*columns; its scan appendsc.Tokens.dest(). 24 columns, 24 targets. - The list path (
/api/requests, dash/query.go:270) uses the samerequestCols, so the list and the single read agree. - New test
TestAccTokens_RoundTripThroughTheStorewrites a priced event and reads it back by id and in the list, comparingacc_tokensand each component'stokens. It covers the fix. - No golden needed a change: no golden file contains
priced_byorsaved_first_usd, so none renders a stored component row.
- My round-1 note 1 and reviewer 1's non-blocking note (same gap): fixed by the same change.
- My note 2 / reviewer 1's note:
by_feature["cachesplit"]merges the split effect and the component's own ops. Kept as one entry; docs/dashboard.md now states the merge and names both dollar columns. The author says the owner has not decided yet. The documentation makes the entry reproducible, so I accept this. - My note 3 / reviewer 1's note: the 2 extra lean queries. Kept. The reason is right: both queries are bounded,
TestOverviewLeanQueriesAreIndexedchecks their plans, and full/lean agreement needs the shared read. I verified the same in round 1. - Reviewer 1's note on the Overview comment ("every dollar saving"). Fixed: the comment now says "every accountant-measured saving" and names what has no token form (the declaration-filter credit, the historical split credit,
defer_net_usd, the manual-ping savings). That matches the code: those figures are read-time credits or their own columns, not stored tokens. - Reviewer 1's note on
tokens_unmeasured_requestsbreadth. Kept, with the doc stating the rule (acc_priced = 0). Accept.
Non-blocking
- dash/query.go:199 — the line ends with an empty raw string (
... + requestTokenSelect + ``, two adjacent backticks). It is valid Go and harmless, but it reads like an editing artifact. A future editor may trip on it. Drop the trailing `+ ``` or keep it deliberate with a word of comment.
What I checked
- Last review: round 1, a8a4c19, 2026-11-09T21:03:47Z.
- New commits read: 1 — 573c15a "fix(dash): read the accountant tokens back from the store".
- 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: reviewer 1's round-1 review (21:05:03Z) — checked each finding against the code; the author's comment (21:30:36Z) — checked each claimed fix; commit 573c15a — reviewed in full below.
- The new commit's diff, line by line: dash/acctokens.go (
TokenFlow.dest,requestTokenSelect,requestTokenDest), dash/acctokens_test.go (the round-trip test), dash/overview.go (the comment), dash/query.go (the three read paths), docs/dashboard.md (the cachesplit entry). - Column/scan alignment after the fix, counted by script with the
kaSavedsplice treated as one item: 88 base + 1 kaSaved + 32 token = 120 select items inrequestCols, 88 + 32 = 120 scan targets inscanRequest; 16 + 8 = 24 on both sides of the component query.requestTokenDestandrequestTokenSelectfollow the same order. - The read paths that consume
requestCols: only the list (query.go:270) and the by-id read (query.go:309), both throughscanRequest. Nothing re-inserts a scanned row, so the read-only shim and the additive columns keep old databases working (round 1 verified the shim covers the new columns). - The new test's fixture and assertions:
db.Request(e.ID, false)anddb.Requests(Filter{TenantAll: true}, 0, 10)both exist with those signatures; the component order comparison by index matches theORDER BY rowidinsert order; the fixture'sPriceModerun populatesAccTokensand every component'sTokens, so the comparison is not vacuous. - The Overview comment and the docs change against the code: the named exclusions (decl-filter credit, cachesplit historical credit,
defer_net_usd, manual pings) are exactly the savings with no stored token figure. - Repo rules: no proxy or library behavior change;
/api/statsstays append-only; the data-dependence row from round 1 is untouched.
Live tests were not run (not approved; Go is not on this machine). The author reports all ./dash/... tests pass on the eval box with -race; I verified the changes by reading the code only.
|
Owner decision (2026-11-10): |
|
The lean read is back inside its budget. Fix: commit Timing.
The fix is 1.22x main, which is inside the 70 ms target. What changed
Tests: all |
amiddavid
left a comment
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.321 | offload-review skill, @amiddavid's session | fresh | 1 of 2 | 3 of 3 | 07aaf5008ba6 |
approve |
Verdict: approve
Findings
None. The new commit introduces no defect I can prove.
Round 2 to round 3
- The lean budget fix (07aaf50) is correct. I checked every part of it; details under "What I checked". The lean totals equal the full totals by construction, and the test holds them together.
- My round-1 finding (stored tokens never read back): still fixed. 07aaf50 does not touch
requestCols,scanRequestor the component SELECT.requestTokenSelectstill reads the 32 effect columns. Thetok_total_*columns need no read-back: they are an aggregate copy, not anEventfield. - My round-2 non-blocking (the cachesplit doc caveat): resolved by decision. The owner decided on 2026-11-10 that
by_feature.cachesplitstays one entry (PR comment, 22:14:00Z). The decision is recorded on the PR. - Reviewer 2's round-2 non-blocking (trailing empty raw string, query.go:199): still there. I checked the line myself. It is valid Go and cosmetic. Agree with reviewer 2, finding 1; nothing to add.
- The flaky
TestRegistrationRateLimitedPerIP: handled outside this PR. Issue #1000 is open for it. This matches the repo rule for a defect in main.
Non-blocking
- dash/acctokens.go:230 — the full read now sums the effect columns without an agent CASE. The result is the same: a ping row stores zeros (
requestStoredTokenArgs), and a row written before this PR has no token columns (DEFAULT 0). A row written by the intermediate commits a8a4c19 or 573c15a with a priced ping would differ, but those commits never shipped. Dev databases of this branch only. No action needed. - The lean response drops
by_featureand the ping tokens that 573c15a served. All three fields are new in this PR, so no released behavior changes. The commit message names the change with numbers, and docs/dashboard.md lists the lean fields. Within the PR's own scope.
What I checked
- Last review: round 2, 573c15a, 2026-11-09T21:33:16Z.
- New commits read: 1 — 07aaf50 "perf(dash): keep the lean stats read in its budget" (full diff read: dash/acctokens.go, dash/acctokens_test.go, dash/overview_lean.go, dash/overview_lean_test.go, dash/schema.go, dash/store.go, 3 golden files, docs/dashboard.md, docs/reference/reference.md).
- Read in full: 4 reviews, 2 comments, 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-2 review (21:34:42Z, approve). Read in full. Its one non-blocking (query.go:199 trailing empty raw string) checked against the code: still present, cosmetic.
- Author comment 22:14:00Z (owner decision: cachesplit stays one entry). Closes my round-2 note. Decision recorded.
- Author comment 22:53:37Z (lean budget fix, timings, flaky test). Every claim checked against the diff; see below. The flaky test has its own issue (#1000, open).
- Commit 07aaf50. Reviewed as a first review; findings above.
- The write path.
requestStoredTokenArgsreturns 32 effect values plus 8 totals. The total is the sum of the event's component figures and its four effects, from the same in-memory fields the writer stores, so the copy cannot drift from what it sums. A ping stores all zeros (&Event{}path terminates: KeepAlive is false there). INSERT alignment counted: 95 base columns + 40 token columns = 135; 95 literal?+placeholders(40)= 135; 95 base args + 40 token args = 135. - The lean scan.
leanWindowMainQueryappendsaccTokenLeanTerms(8tok_total_*sums + the unmeasured count);tok.dest()scans 8 totals then unmeasured, in the same order.flowColumnsorder (saved in/rd/w5m/w1h, caused in/rd/w5m/w1h) matchesflowOf's reading andTokenFlow.args(). The append nesting puts the 9 targets after manual, DeferNetUSD — the same position as the terms in the SELECT. - The scopes. The lean main query and the full effects half both use
withKeepAlive(f).where(). The components half usesf.where()(agent rows only). Ping rows store zero totals and carry no component rows, so the plain SUM (no agent CASE) equals the old CASE sum. Pre-PR rows read 0 on both sides. - Full/lean agreement. Per row,
tok_total= components + effects by construction; held estimates zero their component and TTL/ended figures in memory before the write, so the copy sums the same zeros.TestAccTokens_LeanAgreesWithFullcovers a session and a window; the fixture has an auto ping, a fallback row and a legacy row, so the zero-ping and unmeasured paths are exercised. - Migration and old databases. The 8 new columns are in the DDL and in
additiveColumns; the read-only shim iterates that list generically.TestAccTokenColumnsAreAddedToAnOldDatabasedrops all 40 and reopens; the fresh-database test holds the DDL names against the generated ones (40 columns, 40 args). - The removed EXPLAIN cases. They covered the two queries lean no longer runs. The new terms ride
leanWindowMainQuery, whichTestOverviewLeanQueriesAreIndexedstill EXPLAIN-tests as the exact executed statement. - The goldens and docs.
by_featureisomitemptynow; the goldens lose only"by_feature": {}(the demo database has no priced rows). The docs section moved; the#savings-in-tokensanchor is intact and reference.md links to it. The lean field list matches the code (totals and unmeasured only). - Repo rules. Data dependence: row #998 already covers the token figures as numbers only; the totals are a sum of those numbers, so the level is unchanged. No proxy or library behavior changes. The budget test's 10s backstop is untouched; the 70ms figure is the author's own measurement, named in the commit message.
- Did not run builds or tests (live tests not approved; Go is not on this machine). The author reports all
./dash/...tests pass on the eval box with-race.
amiddavid
left a comment
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.321 | offload-review skill, @amiddavid's session | fresh | 2 of 2 | 3 of 3 | 07aaf5008ba6 |
approve |
Verdict: approve
Findings
None. The new commit adds no defect I can prove. The lean totals equal the full totals by construction, and I traced every path that could break it.
Earlier findings
- Reviewer 1's round-1 blocking finding (stored tokens never read back): fixed in 573c15a, still intact.
requestTokenSelectandrequestTokenDeststill userequestTokenColumns()(32 columns), so the read-back is untouched by this commit. The newtok_total_*columns are rightly not inrequestCols: noEventfield holds them, and they are a derived copy. by_feature["cachesplit"]as one entry: decided. The owner's comment (2026-11-09T22:14:00Z) keeps it one entry. The docs state the merge and both dollar columns. Closed.- My round-1 note 3 (the 2 extra lean queries): fixed by this commit, better than asked. Lean now runs no extra token query at all. The 9 terms ride the one existing scan.
- My round-2 non-blocking note (the empty raw string at the end of
requestCols, dash/query.go:199): still present. Cosmetic; the author kept it. I do not raise it again as a finding.
Non-blocking
- dash/overview.go:446 — a lean call still emits
keepalive_ping_tokensandkeepalive_ping_output_tokens, as zeros. The fields have noomitempty, and a struct cannot use it. The lean path never computes them, soapplywrites zero values. docs/dashboard.md says the lean read "has no ping tokens" and "Full read only" for these fields, but the JSON carries the keys with 0. A client cannot tell "0" from "not measured here" — the same ambiguityacc_pricedexists to avoid. No lean client reads these fields today (statusline.py, cg.py), so this is a doc and contract point only.omitzeroon both fields would make the doc exact. - docs/dashboard.md — "The lean read ... has
tokens.saved,tokens.causedandtokens_unmeasured_requestsonly" is exact for thetokensobject, but see the note above for the two ping fields beside it. One sentence naming them as always-zero on lean would close it.
What I checked
- Last review: round 2, 573c15a, 2026-11-09T21:34:42Z.
- New commits read: 1 — 07aaf50 "perf(dash): keep the lean stats read in its budget".
- Read in full: 4 reviews, 2 comments, 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 comment at 22:14:00Z (owner decision on cachesplit — matches the kept design and the docs), the author's comment at 22:53:37Z (the lean budget fix — every claim checked against the code, below), and commit 07aaf50 (reviewed in full).
- The lean/full equality, the commit's core claim. Lean sums
tok_total_*overwithKeepAlive(f)scope with no agent CASE. Full sums the 32 effect columns over the same scope (plain SUM, no CASE either now) plusrequest_components.tok_*overf.where()scope.tok_totalis written at insert time as the sum of the same in-memoryc.Tokensand effect figures that the two reads sum, from the same event in the same transaction (dash/store.go:682 and the compStmt loop). So the two totals are equal by construction. I checked each way they could diverge:- Ping rows.
requestStoredTokenArgs(dash/acctokens.go:144) returns zeros for everye.KeepAliverow, effects and totals both. Thekeepalivecolumn isboolInt(e.KeepAlive)(dash/store.go:665), so everykeepalive = 1row — auto ping or manual ping — stores no token figure. That is what makes the no-CASE plain SUM safe in both reads. - Held estimates. The held path zeroes component
Tokensand the TTL/ended legs in memory before the insert (dash/accountant_price.go:425-432), sotok_totaland both reads keep only rescue and split, together. - Other writers.
insertBatchis the only INSERT intorequests; the two UPDATEs (setBypassTokens, the project and strategy backfills) touch notok_column. Nothing re-prices a stored row. - Old databases. The 8 new columns are in the DDL and in
additiveColumns(init appendsrequestStoredTokenColumns, 40 entries), soaddColumnsmigrates and the read-only shim adds each missing column as its default 0. - The test.
TestAccTokens_LeanAgreesWithFullcovers a session and a window, with a ping row inside the session's scope, a fallback row and a legacy row.
- Ping rows.
- Scan/term alignment. Full read: 32 sums + 6 tail terms = 38, and
accTokensAgg.dest(32)returns 38 targets in the same order (sums, then ping in/rd/w5m/w1h, output, unmeasured). Lean:accTokenLeanTermsis 8 totals + unmeasured = 9, appended to the query afterdefer_net_usdand scanned bytok.dest()after&o.DeferNetUSD— same position.leanAgg.total[8]andflowOfboth followflowColumnsorder (saved in/rd/w5m/w1h, caused in/rd/w5m/w1h). - Insert alignment. 95 base columns + 40 token columns = 145 named columns; 95 literal
?+placeholders(40); base args +requestStoredTokenArgs(e)(40 values). The base list is unchanged from round 2's verified count. - The full read's scope change. The effect sums lost their
keepalive = 0CASE. I checked every row class the CASE used to exclude: ping rows store zeros (above), and no other writer setstok_*on akeepalive = 1row. The unmeasured count keeps its CASE (unmeasuredTerm), identical in both reads. ByFeatureomitempty. The full read allocates the map;addFeatureadds only non-zero figures, so an empty period omits the key. The three golden files drop"by_feature": {}and change nothing else. The lean golden (/api/stats?lean=1with no session and no window) goes through the full handler's lifetime fallback (dash/api.go:1357), so it is produced by the full path — its ping tokens and the by_feature omission are both the full read's, consistent.- The EXPLAIN test change. The 4 removed cases covered
accTokensRequestQuery/accTokensComponentQueryon the lean path; lean no longer runs them. The lean main query, which now carries the 9 terms, is still covered by the "main aggregate" cases. - Docs. The moved "Savings in tokens" section states the lean/full split and the field list; reference.md's anchor
#savings-in-tokensmatches the new##heading. The data-dependence row (#998, "Decided by: David Amid") already covers token counts by tier;tok_total_*is a derived copy of those numbers, metadata, no level change. - The flaky
TestRegistrationRateLimitedPerIP. The author's analysis (fixed window starting on each whole minute,proxy/limits.go) is plausible and the test is untouched by this PR. It needs its own issue and PR, as the author says. - Repo rules: no proxy or library behavior change;
/api/statsstays append-only against main (main has notokensobject at all); the lean budget test is a pre-existing loose backstop, unchanged.
Live tests were not run (not approved; Go is not on this machine). The author reports all ./dash/... tests pass on the eval box with -race; I verified the changes by reading the code only.
…pi/stats Part 1 of #998. The accountant library measures every saving in tokens by tier; the dashboard stored only the dollars. It now stores the tokens beside them and /api/stats (full and lean) returns a `tokens` object and `tokens_unmeasured_requests`. No existing figure changes. - request_components: 8 token columns (saved and caused, by tier), with the same attribution AccountantFigure uses for the dollars. - requests: 32 token columns for the keep-alive rescue, the split, the head-TTL legs and the ended-change break. - Both additive (default 0); acc_priced tells "not measured" from 0. Assisted-By: Claude Opus 5.5 <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
A stored request now reads back acc_tokens and each component's tokens, in
the single-request read and in the list. Before, /api/requests/{id} after a
reload omitted fields the live row showed. Also narrows the Overview comment
to accountant-measured savings and documents the one cachesplit entry.
Assisted-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: DAVID AMID <[email protected]>
The two token queries made the lean /api/stats read about 4x slower (214 ms against 53 ms on the 20,000-request budget test). The lean read now takes the token totals from its one existing scan: a per-request copy of the request's whole token figure (8 additive tok_total_* columns) and the unmeasured count, 9 terms. It runs no join and no new query: 64.6 ms against main's 53 ms. Lean has no by_feature and no ping tokens; the full read has them. Its totals and unmeasured count equal the full read's (tested). A keep-alive ping stores no token figure, so the sums need no agent CASE. Assisted-By: Claude Opus 5.5 <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
07aaf50 to
3ae7056
Compare
amiddavid
left a comment
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.322 | offload-review skill, @amiddavid's session | resumed | 1 of 2 | 4 of 4 | 3ae7056b1e53 |
approve |
Verdict: approve
Findings
None. The rebase introduces no defect I can prove.
Round 3 to round 4
- The only push is a rebase onto main
8cbb700. The three PR commits were rewritten (new shas591509a6,70ec2b5a,3ae7056b); their messages are unchanged. I diffed the old PR patch (base10329879, head07aaf500) against the new one (base8cbb700, head3ae7056b) hunk by hunk. The PR's core files are byte-identical:dash/accountant_price.go,dash/acctokens.go,dash/acctokens_test.go,dash/keepalivetab_test.go, the goldens. The differences are the rebase's adaptations to main's new code, and I verified each:dash/query.go—requestTokenSelectandrequestTokenDestnow sit after main #991's 7 limit items andauth_subscription, at the end of both the SELECT and the scan. Same order on both sides: 7 + 1 + 32.dash/store.go— the token columns followlimitColsandauth_subscriptionin the INSERT. Counted by script: 95 base + 7limitCols+ 1auth_subscription+ 40 token = 143 named columns, 143 placeholders (103 literal + 40 generated), 143 Exec args (95 base + 7limitArgs+ 1 + 40). Aligned.dash/overview_lean.go— the PR's hunk is unchanged. Main #992'sSavedGross/ReplayTokensblock (new base code) sits beforetok.read().apply(o)and adds no scan terms; it computes from fields already scanned.dash/schema.go,dash/event.go,docs/reference/reference.md— line shifts only; thetok_total_*DDL is intact.docs/dashboard.md— the "Savings in tokens" section moved after main's new hosted-mode content. The#savings-in-tokensanchor is intact and reference.md links to it.
- Main's new lean client is not affected. #981's subscription band (
statusline.py_saved_tokens) readssaved_uniqueandreplay_tokensfrom the lean read, not thetokensobject. Both fields are still served (replay_tokensby #992's block, kept by the rebase). The lean field reduction (noby_feature, no ping tokens) breaks nothing that ships. - My round-1 finding and all earlier notes: unchanged in status. Fixed in round 2, kept intact through the rebase. The owner decision on
by_feature.cachesplitstands. - Reviewer 2's round-3 non-blocking (lean emits zero
keepalive_ping_tokens): still open. I verified it myself:dash/overview.go:446-447has noomitzeroon either field, andleanAgg.read()leavesPingzero, so a lean response carries the two keys with zeros while docs/dashboard.md says lean has no ping tokens. Agree with reviewer 2, non-blocking. New detail: Go 1.24+ supportsomitzeroon structs, and this PR already uses it (acc_tokens,omitzero), so a one-word change would make the doc exact — if the author wants it. - Reviewer 2's round-2 cosmetic (trailing empty raw string in
requestCols): still there, now atdash/query.go:201. Cosmetic.
Non-blocking
- The lean
keepalive_ping_tokens/keepalive_ping_output_tokenszeros, above. The fields are new in this PR and no lean client reads them, so the 0-versus-absent ambiguity harms nothing today. One word (omitzero) or one doc sentence closes it. context-guru-plugin/scripts/statusline.py:1494(main's file, not this PR's) still says cachesplit, keep-alive and declaration-filter savings are "dollar figures with no token count". This PR gives them token counts. The sentence describes only what_saved_tokensshows, so it stays true there, but a reader may take it as a statement about the product. A one-line follow-up on main would keep it exact.
What I checked
- Last review: round 3, 07aaf50, 2026-11-10T07:02:04Z.
- New commits read: the branch was rebased; 3 rewritten commits —
591509a6"feat(dash): store the accountant's tier tokens and serve them from /api/stats",70ec2b5a"fix(dash): read the accountant tokens back from the store",3ae7056b"perf(dash): keep the lean stats read in its budget". Messages unchanged; content compared hunk by hunk against what I reviewed in round 3 (method: diff of the two full PR patches,10329879..07aaf500against8cbb700..3ae7056b; the diff output was fully consumed — the head and tail reads overlapped). - Read in full: 5 reviews, 2 comments, 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 it:
- Reviewer 2's round-3 review (2026-11-10T07:02:35Z, approve). Read in full. Both non-blocking notes checked against the code myself (see above).
- The rebase onto
8cbb700(new base brings #991 limit headers, #992 lean replay tokens, #981 subscription band, #971/#977/#982 installers and Pi/Bob work). Verified the PR's adaptations to #991 and #992, and that #981's client reads none of the reduced lean fields.
- The INSERT alignment after the rebase, counted by script: 143 columns, 143 placeholders, 143 args (95 + 7 + 1 + 40 on every side).
limitArgsalways returns 7 values, matchinglimitCols. requestCols/scanRequestafter the rebase: the PR's 32 token items follow main's 7 limit items andauth_subscriptionon both sides, in the same order.limit_seenis not read (main's choice, unchanged).- The lean read: query and scan identical to round 3's verified shape;
accTokenLeanTerms(9 terms) still scanned bytok.dest()(9 targets) at the same trailing position; #992's arithmetic adds no terms. - The full read, write path, scopes, ping-zero rule, migration and shim: unchanged bytes from round 3, where I verified each (round-3 review, "What I checked"). The rebase touches none of
dash/acctokens.go,dash/accountant_price.goor the tests. - The goldens: byte-identical to round 3 (
by_feature: {}removed, nothing else). - Repo rules: no proxy or library behavior change; the data-dependence row (#998) is unchanged and still covers the token figures as numbers only.
- Did not run builds or tests (live tests not approved; Go is not on this machine). The author's last report (round 3) covers the pre-rebase code; the rebase adaptations are the only new code, and I verified them by reading.
amiddavid
left a comment
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.322 | offload-review skill, @amiddavid's session | resumed | 2 of 2 | 4 of 4 | 3ae7056b1e53 |
approve |
Verdict: approve
Findings
None. The change since round 3 is a rebase onto the new main (8cbb7005), not new feature work. I checked every point where the rebase merged this PR's columns with main's new code. All alignments hold.
What changed since round 3
The PR's three commits were rebased onto the new main and got new SHAs (591509a6, 70ec2b5a, 3ae7056b). Main gained #971, #977, #982, #992, #981 and #991; #991 and #992 touch the same files as this PR. A git range-diff of the old range against the new one shows the whole change: the PR's patches are otherwise byte-identical (dash/acctokens.go, dash/acctokens_test.go, dash/accountant_price.go, dash/overview.go, dash/keepalivetab_test.go and the goldens did not change at all). The rebase adapted four merge points:
insertBatch(dash/store.go): the token columns now follow main #991'slimitCols, auth_subscription.requestCols/scanRequest(dash/query.go):requestTokenSelectandrequestTokenDestnow follow the 6 limit columns andauth_subscription.overviewLeanWindow(dash/overview_lean.go): the tokens read sits beside main #992'sSavedGross/ReplayTokensarithmetic.docs/dashboard.md: the "Savings in tokens" section moved to follow main #991's limits section; the#savings-in-tokensanchor still matches, and reference.md still links to it.
Earlier findings
- All findings from rounds 1 to 3: fixed or decided, unchanged by the rebase. The read-back fix, the lean budget fix and the cachesplit owner decision are all in the byte-identical parts of the patches.
- My round-3 non-blocking notes: not addressed. The author pushed no fix for them and replied to nothing. Both stay non-blocking; see below.
- Reviewer 1's round-3 non-blocking notes: agree with both, checked myself. The no-CASE effect sum is safe because ping rows store zeros and the intermediate commits never shipped. The lean field drop is within this PR's own scope. Nothing to add.
Non-blocking
- dash/overview.go:446 — a lean call still emits
keepalive_ping_tokensandkeepalive_ping_output_tokensas zeros (round 3, unchanged). The fields have noomitzero, and the lean path never computes them. docs/dashboard.md says "Full read only" for these fields, but the JSON carries the keys with 0. No lean client reads them today.omitzeroon both fields would make the doc exact. - dash/query.go:201 —
requestColsstill ends with an empty raw string (+ requestTokenSelect + ```, round 2, unchanged). Valid Go, reads like an editing artifact.
What I checked
- Last review: round 3, 07aaf50, 2026-11-10T07:02:35Z.
- New commits read: the three rebased commits — 591509a "store the accountant's tier tokens", 70ec2b5 "read the accountant tokens back", 3ae7056 "keep the lean stats read in its budget" — plus the new main commits they now sit on, read where they touch this PR's files (8cbb700 #991 limits, dbca625 #992 lean replay tokens; the others touch no file this PR changes).
- Read in full: 6 reviews, 3 comments, 0 inline comments (from .review-in-reviews.txt, .review-in-comments.txt, .review-in-inline.txt).
- New items since my last review: reviewer 1's round-3 review (07:02:04Z — read in full, both non-blocking notes checked and agreed); the rebase itself (no author comment covers it — the last comment, 22:53:37Z on Nov 9, predates it). No test-run report exists for the rebased head. I could not run tests (not approved), so I verified the rebase's merge points by counting instead:
insertBatch, requests: 95 base columns + 7limitCols+ 1auth_subscription+ 40 token columns = 143 named columns. Placeholders: 103 literal?+placeholders(40)= 143. Args: 95 base +limitArgs(7) +boolInt(e.AuthSubscription)(1) +requestStoredTokenArgs(40) = 143. The order matches on all three sides (limit columns, then auth, then tokens). The base list is byte-identical to the round-3-verified one; only the limit/auth splice was added.requestCols/scanRequest: 95 select items before the token select (94 named +kaSaved("r.")as one expression) +requestTokenSelect(32) = 127 columns; 95 base scan targets +requestTokenDest(32) = 127 targets. The token dests still scan last, after&authSub, the same position as the select.- The component SELECT in
DB.Request: untouched by main; still 17 + 8 = 25 columns and targets, as verified in round 2. leanWindowMainQuery: main #992 added no SQL terms —SavedGrossandReplayTokensare Go arithmetic on values the scan already reads (overview_lean.go:86-89). The 9 token terms are still last in the SELECT andtok.dest()still last in the Scan, as verified in round 3.- The schema: main #991's limit columns (DDL and
additiveColumns) and this PR's 40 token columns coexist; both are additive, the fresh-database test checks all 40 token names against the DDL, and the drop-column test re-adds them. - The lean/full equality:
dash/acctokens.gois byte-identical to round 3's approved state, and the write path it depends on (requestStoredTokenArgs, the held-estimate zeroing,insertBatch's token args) is unchanged apart from the limit splice, which sits before the token args and cannot affect them. - The goldens: the PR diff against the new base adds only the
tokensobjects (same numbers as round 3: ping cache_read 720540, 591 unmeasured, output 750). Main's limit fields were already in the base goldens and are kept. - Main's new tests: #992's lean replay-tokens test reads fields this PR does not touch; #991's limits tests read columns the PR does not touch.
Live tests were not run (not approved; Go is not on this machine). The author's last test report (all ./dash/... passing, -race) covers 07aaf500, not the rebased head; the rebase changes only the four merge points counted above.
Rebase after #991The branch is rebased onto main (8cbb700). New head: The same 3 commits are kept. The rebase had hand-merged conflicts in 4 files. Both sides were kept each time.
Tests
Approval checkThe patch changed. A new review round must review the merge hunks above.
|
…tats On a Claude subscription, /context-guru:status and /context-guru:insights savings now show everything in tokens, with no dollars (#998 part 2). - The totals come from tokens.saved and tokens.caused (#999), not from saved_unique and replay_tokens. They cover every feature, not only compaction. - The tiers show apart, in the order wr, wr1h, rd, in. A tier that a change paid shows after "cost". - status: this session, the 5-hour window with the estimate, then today, yesterday and the period. The estimates show without dollars. - insights savings: the totals, then one line per feature from tokens.by_feature. The keep-alive pings show apart, outside the total. - A note counts the requests with no token figure. - The 5-hour estimate is unchanged. Assisted-By: Claude Opus 5.5 Signed-off-by: DAVID AMID <[email protected]>
The Overview on a Claude subscription now reads the accountant's tier tokens from /api/stats (#999), not saved_unique and replay_tokens. - The total: tokens.saved, and tokens.caused plus the keep-alive ping tokens as cost. One display rule: tiers that are not 0, in the order wr, wr1h, rd, in; the cost after. Tiers are never added. - Each card shows tokens from tokens.by_feature: Cache (keepalive, cachesplit, ttl; the pings as keep-alive cost), Preset (every other component and ended_change), Tools and skills filter (toolfilter), Tool deferral (tooldefer). - The subscription view starts on the auth kind (subscription: true), not only on an open 5-hour window. The estimate still needs one. - A note under the total counts requests not measured in tokens. - No dollars on a subscription: the replay-cap and estimated-request notes leave them out. Assisted-By: Claude Opus 5.5 <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
…cription (#989) On a Claude subscription, /context-guru:status and /context-guru:insights savings (and the Savings part of /context-guru:insights) now show everything in tokens, by tier, with no dollars. The source is tokens.saved and tokens.caused in /api/stats (#999), which cover every feature: compaction, cache split, keep-alive and the 1-hour cache. One estimate line shows the 5-hour share. The Codex copy of cg.py is the same. Behavior change: Claude subscription users of those screens. Old: the screens show dollars. New: tokens by tier, and one 5-hour-share estimate line. API-key, Bedrock and Vertex users see no change. Owner's yes, 2026-11-10, in the integrator session: "989 is also ready for merge" (the owner asked for this on 2026-11-09 and chose the token form for #998). Data dependence: metadata only (token counts by tier, dollar totals the dashboard already keeps, and the 5-hour share from the limit headers, #984). The same at each storage level. Reviews: 2 offload reviews (GLM), round 3, both approve at 639b73d. Assisted-By: Claude Opus 5.5 <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
…lds (#1018) On a Claude subscription, the band now shows the session's saving from the tokens fields of /api/stats (#999): one figure per tier, for every feature, saved and cost, never added into one number. Tiers show in the order wr, wr1h, rd, in; a tier at 0 is left out. A proxy before #999 (no tokens) keeps the old figure. The Codex copy of cg.py is the same. Part 2 of #998, for the band. Behavior change: Claude Code users on a subscription, in the band's second row. Old: compaction's rd / wr estimate (this session saved 1.2M rd / 85.0k wr). New: the accountant's tokens for every feature by tier (this session saved 85.0k wr · cost 40.0k rd). No switch; revert this PR. Owner's yes, 2026-11-10, in the integrator session: "pls merge #1018". Data dependence: metadata only (token counts by tier). The same at each storage level. No change to docs/data-dependence.md. Reviews: 2 offload reviews (GLM), round 2, both approve at 85ea890. CI green (build-test passed on a rerun of the new flake #1028). Assisted-By: Claude Opus 5.5 Signed-off-by: DAVID AMID <[email protected]>
Merges #988 at 407534d, which adds tokenFigure: one rule for zero against "not measured" on every screen. Conflict resolution and the follow-up change: - kaTokenLines takes the rescue text and its `measured` flag from tokenFigure. The three sentences still branch on the flag. - A ledger with no `tokens` (a server from before #999) now reads "not measured", as tokenFigure says. - The "Cache rewrites avoided" fact reads "up to 85.0k wr · cost 40.0k rd", without a second "saved". - savings.test.mjs keeps both sides' new tests. Assisted-By: Claude Opus 5.5 Signed-off-by: DAVID AMID <[email protected]>
…1022) (#1042) On a Claude subscription, the dashboard Cache strategy tab shows the measured rescue and the ping cost in tokens, by tier, not dollars. The source is the accountant's tier tokens stored by #999. The forecast, "Ahead"/"Behind", the winner/loser split and the "costs more than it saves" banner keep the same dollar rule, and say they are at API-price weights. A ledger with no token rows shows "saved 0 tokens" and the "not measured" note. Fixes #1022. Behavior change: members and local proxies on a Claude subscription (/api/me/limits says subscription: true, or a 5-hour window is open). Old: every measured figure in dollars. New: tokens by tier, as above. Managers, API-key, Bedrock and Vertex users and hosted mode keep dollars. No switch; it follows the subscription signal, as #988 does. Owner's yes, 2026-11-11, in the integrator session: "1042 has my approval". Data dependence: metadata only (token counts by tier, already stored by #999). No change at any storage level. Reviews: 2 offload reviews (GLM), round 5 (owner granted it), both approve at f893c22; round 5 confirmed the PR's own change is byte-identical to the round-4 approval at 6b586a6. After it: a merge of main with no hand resolution (remerge-diff 0), tested on the merged tree. Assisted-By: Claude Opus 5.5 <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
…1041) On a Claude subscription, the Sessions tab shows tokens, not dollars, in its three dollar columns: Cost becomes Tokens used, Net saved becomes Tokens saved (a dagger marks a session with unmeasured requests), and Keep-alive net becomes Keep-alive, with the pings on a line of their own, never added into a total. /api/sessions adds five fields to each row for every caller: tokens, keepalive_tokens, keepalive_ping_tokens, used_tokens and tokens_unmeasured_requests. One formatter, sessionTokenCells in savings.js, reuses #988's helpers. Closes #1023. Behavior change: only the one #1023 asks for: on a subscription the Sessions tab shows tokens. Managers, API-key users and hosted mode (#997) keep dollars. Owner's yes, 2026-11-11, in the integrator session: "#1041 (Sessions tab): approved, but merge it after #1042". Data dependence: metadata only (token counts by tier, already stored by #999). No change at any storage level. Reviews: 2 offload reviews (GLM), round 4 (pre-approved by the owner), both approve at 7e454bc. Round 4 reviewed the merge of main after #1042, which kept both sides by hand in dash/ui/savings.js, dash/savings.test.mjs, dash/savingsparts_test.go and docs/dashboard.md. Assisted-By: Claude Opus 5.5 <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
Part 1 of #998.
This PR changes no existing figure. Every dollar figure, every existing field and every existing column keeps its value. It only adds token columns and new fields in
/api/stats.PRs #988 (dashboard) and #989 (status and insights) wait for this PR. They switch their token source to the new fields.
Data dependence: metadata only. The new columns are token counts. They are the same at each storage level (off: no dashboard, nothing stored; metadata only and everything: stored).
docs/data-dependence.mdrow "Accountant savings" is updated.Summary
The accountant library measures every saving in tokens by tier. The dashboard stored only the dollars, so the tokens were lost after the write. This PR stores the tokens beside the dollars and returns them from
/api/stats, full and lean.What changed
request_components: 8 columnstok_{saved,caused}_{in,rd,w5m,w1h}. A row gets the tokens whose dollars it gets: the same attribution asAccountantFigure(owner by ChangeID; dry runs, spend ops and unpriced ops with no tokens skipped; breaks and mark legs to their owner).requests: 32 columns for the 4 request-level effects: keep-alive rescue (tok_ka_*), split (tok_split_*), head-TTL legs (tok_ttl_*) and the ended-change break (tok_ended_*).headttlandended_changerows keep their dollars; their effect tokens are on the request.acc_priced(already stored) tells "not measured" from a measured 0./api/stats(full andlean=1) returnstokens,tokens_unmeasured_requests,keepalive_ping_tokensandkeepalive_ping_output_tokens. Both paths call one function,DB.AccTokens, so they agree.requests, one join torequest_componentsdriven by the requests index. Both are inTestOverviewLeanQueriesAreIndexed.docs/dashboard.md(new section "Savings in tokens"),docs/reference/reference.md,docs/data-dependence.md.The
tokensobjectby_feature: one entry per component (mask,extract,tailbreakpoint,toolfilter,tooldefer, ...), pluskeepalive,cachesplit,ttl,ended_change. A feature with no tokens has no entry.keepalive_ping_tokens/keepalive_ping_output_tokens(top level, besidekeepalive_ping_usd): what the cache strategy's pings paid, from the ping rows' billed usage. A ping is not agent traffic, so it is not intokens. The keep-alive's net istokens.by_feature.keepaliveless this.How it was tested
On the eval box,
go test -race -count=1 ./dash/...in two halves. Results: all pass.^Test[A-H]: 542 passed, 0 failed, 5 skipped.^Test[^A-H]: 840 passed, 0 failed, 9 skipped (counts include subtests)../proxy/...is not touched and was not run.New tests (
dash/acctokens_test.go):SavedUSD == tierUSD(saved) - tierUSD(caused)of its tokens; forheadttlandended_change, with the request's effect tokens added.TestPingRowsStayOutOfAgentAggregatesnow allows the two ping token fields to move with the pings, as it allowskeepalive_ping_usd.Golden files
stats.json,stats_lean.json,stats_windowed.jsonare updated on purpose: they only add the 4 new fields. The golden fixture has no accountant-priced rows, soby_featureis empty there and every request is unmeasured.Open questions
estimated_saved_usd), so a screen can show them as an estimate? Today they are held out, the same as the dollars.cachesplitadds acachesplitcomponent row's own tokens (if the library ever gives it any) to the split effect. Is one entry right, or should they be two?🤖 Generated with Claude Code