Skip to content

feat(dash): store the accountant's tier tokens and serve them from /api/stats - #999

Merged
amiddavid merged 3 commits into
mainfrom
feat/acc-tokens
Nov 10, 2026
Merged

amiddavid merged 3 commits into
mainfrom
feat/acc-tokens

Conversation

@amiddavid

Copy link
Copy Markdown
Collaborator

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.md row "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

  1. Storage (additive columns, default 0).
    • request_components: 8 columns tok_{saved,caused}_{in,rd,w5m,w1h}. A row gets the tokens whose dollars it gets: the same attribution as AccountantFigure (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_*).
    • The component tokens and the effect tokens never overlap. The headttl and ended_change rows keep their dollars; their effect tokens are on the request.
    • acc_priced (already stored) tells "not measured" from a measured 0.
    • A held estimate (Accountant integration (#893 Major 5): the first request on an unseen warm cache books a baseline about 2x too high #915) holds its tokens out as it holds its dollars. The rescue and the split stay, as their dollars do.
  2. /api/stats (full and lean=1) returns tokens, tokens_unmeasured_requests, keepalive_ping_tokens and keepalive_ping_output_tokens. Both paths call one function, DB.AccTokens, so they agree.
  3. Lean read. 2 more bounded reads: one aggregate over requests, one join to request_components driven by the requests index. Both are in TestOverviewLeanQueriesAreIndexed.
  4. Docs. docs/dashboard.md (new section "Savings in tokens"), docs/reference/reference.md, docs/data-dependence.md.

The tokens object

"tokens": {
  "saved":  {"input": 0, "cache_read": 600,  "cache_write_5m": 6000, "cache_write_1h": 0},
  "caused": {"input": 0, "cache_read": 4000, "cache_write_5m": 600,  "cache_write_1h": 0},
  "by_feature": {
    "mask":      {"saved": {"input": 0, "cache_read": 600, "cache_write_5m": 2000, "cache_write_1h": 0},
                  "caused": {"input": 0, "cache_read": 0, "cache_write_5m": 600, "cache_write_1h": 0}},
    "keepalive": {"saved": {"input": 0, "cache_read": 0, "cache_write_5m": 4000, "cache_write_1h": 0},
                  "caused": {"input": 0, "cache_read": 4000, "cache_write_5m": 0, "cache_write_1h": 0}}
  }
},
"tokens_unmeasured_requests": 2,
"keepalive_ping_tokens": {"input": 3, "cache_read": 9000, "cache_write_5m": 20, "cache_write_1h": 10},
"keepalive_ping_output_tokens": 1
  • by_feature: one entry per component (mask, extract, tailbreakpoint, toolfilter, tooldefer, ...), plus keepalive, cachesplit, ttl, ended_change. A feature with no tokens has no entry.
  • keepalive_ping_tokens / keepalive_ping_output_tokens (top level, beside keepalive_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 in tokens. The keep-alive's net is tokens.by_feature.keepalive less this.
  • The tiers are never added into one number.

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):

  • Attribution matches the dollars: for every row, SavedUSD == tierUSD(saved) - tierUSD(caused) of its tokens; for headttl and ended_change, with the request's effect tokens added.
  • Dry run, spend op, in-baseline break and an unowned break's ChangeID get no tokens; an unpriced op with no tokens adds no entry.
  • A held estimate and a fallback have no component tokens.
  • Stats: each effect lands in its feature; a fallback request and a legacy row count as unmeasured; the ping row is not an agent request.
  • Lean and full agree, for a session and for a time window.
  • The columns exist on a fresh database and are added to an old one.

TestPingRowsStayOutOfAgentAggregates now allows the two ping token fields to move with the pings, as it allows keepalive_ping_usd.

Golden files stats.json, stats_lean.json, stats_windowed.json are updated on purpose: they only add the 4 new fields. The golden fixture has no accountant-priced rows, so by_feature is empty there and every request is unmeasured.

Open questions

  • Should a held estimate's tokens be served apart (like estimated_saved_usd), so a screen can show them as an estimate? Today they are held out, the same as the dollars.
  • cachesplit adds a cachesplit component row's own tokens (if the library ever gives it any) to the split effect. Is one entry right, or should they be two?
  • The golden fixture has no accountant-priced rows. Add some in a later PR?

🤖 Generated with Claude Code

@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.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/scanRequest and the request_components query do not read tok_*. So acc_tokens and components[].tokens appear only on the live SSE feed (dash/sse.go marshals the Event), never on /api/requests or /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_usd holds only the effects, the component's saved_usd holds its ops. So tokUSD(by_feature["cachesplit"]) can exceed CachesplitSavedUSD. 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 tokens field, 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 the additiveColumns entries in acctokens.go's init all spell the same names in the same order. requestTokenArgs follows requestTokenEffects (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. accTokensRequestQuery uses withKeepAlive(f).where() and gates every effect sum on r.keepalive = 0; ping tokens use autoPing (keeper pings only, manual pings excluded), the same rule KeepAlivePingUSD uses. accTokensComponentQuery uses plain f.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_usd as stored only for acc_priced = 1 rows. The tok_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 keeps KeepAliveSavedUSD.
  • 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. TokByComponent never holds the TTL or ended-break legs, so by_feature cannot double-count. A headttl operation would put op tokens on the headttl row while the TTL effect legs stay in AccTokens.TTL; the row's dollars hold both, so the sums still match.
  • Held estimates and repricing. Price and PriceMode both call clearAccTokens first. accOverride sets 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 second PriceMode cannot duplicate rows.
  • The 5m/1h write split. event.go defines CacheWrite1h as the part of CacheWrite billed at 1h, so MAX(cache_write - cache_write_1h, 0) is the 5m part. That decomposition prices to the same number as CostWithCacheWrite1h, so the ping tokens are the token form of keepalive_ping_usd.
  • Migration and old databases. The new columns are in the ddl and in additiveColumns; addColumns probes 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 same tokens object 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/stats is 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 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.321 offload-review skill, @amiddavid's session fresh 1 of 2 1 of 2 a8a4c191bfaf blocking

Verdict: blocking

Findings

  1. dash/query.go:314 — the stored per-request tokens are never read back, so the same request shows acc_tokens live and loses it on reload
    • What fails: PriceMode sets Event.AccTokens and CompRow.Tokens before the event is published, so the SSE feed (/api/events, sse.go writeEvent marshals the whole Event) serves them. No stored read returns them: requestCols (query.go:180-199) names no requests.tok_* column, and DB.Request's component SELECT (query.go:314-317) names no request_components.tok_* column. A client that renders acc_tokens or a component's tokens from 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 on Event and CompRow round-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_*)"), versus dash/query.go:180-199 and dash/query.go:314-328 — neither SELECT names a tok column, and no other read path in dash/ does (checked every FROM request_components and the requests list).
    • Fix: read the columns back — extend requestCols/scanRequest with 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/stats and the live feed, never by a stored read, so the flap is a documented contract.

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_usd and the row's saved_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_usd and the manual-ping savings have no token form in tokens. Say "every accountant-measured saving" as docs/dashboard.md does.
  • The lean path (overview_lean.go:84) now runs 2 more queries on every lean=1 call, and no current lean client (statusline.py, cg.py) reads tokens. The queries are EXPLAIN-tested and bounded, and full/lean agreement is the stated goal; noting the cost only.
  • tokens_unmeasured_requests counts every acc_priced = 0 agent 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 AccountantFigure against every dollar attribution (ops, breaks, rescue, split, TTL, mark legs, ended-change): each addTok/addTiers call sits next to the dollar line it mirrors; headttl and ended_change rows carry dollars only, their tokens stay in AccTokens, 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 Price and PriceMode clear the tokens on every path, including fallbacks (clearAccTokens at the start of both, accOverride sets tokens only after all gates pass).
  • Counted the INSERT columns, placeholders and bound args in store.go by script: 95 + 32 = 127 columns, 127 placeholders, 127 args for requests; 17 + 8 = 25 for request_components. Aligned.
  • Checked flowColumns/args/flowOf ordering, the schema DDL names against the generated names, the init() append to additiveColumns (package vars initialize before init()), 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() and autoPing (manual pings excluded from both halves, matching keepalive_ping_usd), the 5m-write derivation MAX(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, openTestDB all 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).

@amiddavid

Copy link
Copy Markdown
Collaborator Author

Round 1 fixes are in commit 573c15a.

  1. Blocking: the stored tokens were never read back. Fixed.
    • requestCols and scanRequest now read the 32 requests.tok_* columns.
    • The component SELECT in DB.Request now reads the 8 request_components.tok_* columns.
    • The list read (/api/requests) uses requestCols too, so it also reads them. The list is paged. The extra cost is 32 integer columns for each row on a page, and that cost is very small. The single-request read and the list now show the same fields.
    • New test TestAccTokens_RoundTripThroughTheStore: it writes an accountant-priced event and reads it back by id and in the list. It then compares acc_tokens and the tokens of each component with what it wrote.
  2. The Overview comment said too much. Fixed. It now says "every accountant-measured saving". It names what has no token form: the declaration-filter credit, the historical split credit, defer_net_usd and the manual-ping savings.
  3. One cachesplit entry. Kept as one entry. This is the main session's proposal; the owner has not decided yet. docs/dashboard.md now says that its dollars are cachesplit_saved_usd plus the saved_usd of the cachesplit component.
  4. The 2 extra lean queries. Kept. Both are bounded, and TestOverviewLeanQueriesAreIndexed checks their plans. Full and lean use the same function, so they agree.
  5. tokens_unmeasured_requests. Kept. It counts every agent row with acc_priced = 0: rows from before the accountant and rows it could not price. docs/dashboard.md says so.

Tests: all ./dash/... tests pass on the eval box (-race -count=1, two halves). ^Test[A-H]: 543 passed, 0 failed, 5 skipped. ^Test[^A-H]: 840 passed, 0 failed, 9 skipped. The counts include subtests.

@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.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. requestCols now appends requestTokenSelect (32 r.tok_* columns) and scanRequest appends requestTokenDest(&e.AccTokens) (32 destinations, same order). DB.Request's component SELECT appends the 8 request_components.tok_* columns and scans c.Tokens.dest(). Both users of requestCols (db.Requests list at query.go:270 and DB.Request at query.go:309) query FROM requests r, so the r. prefix resolves on both. The single-request read and the list now return what the live SSE row returns. New test TestAccTokens_RoundTripThroughTheStore writes a priced event and compares acc_tokens and every component's tokens after 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_usd plus the cachesplit component's saved_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 cachesplit bullet: "its dollars are cachesplit_saved_usd plus the saved_usd of the cachesplit component" is exact only for accountant-priced rows. A cachesplit row written before the accountant switch has saved_usd from the legacy rule and no tokens. The same caveat applies to every by_feature entry, and tokens_unmeasured_requests marks 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: requestTokenSelect and requestTokenDest both follow requestTokenEffects (ka, split, ttl, ended) × flowColumns (saved in/rd/w5m/w1h, caused in/rd/w5m/w1h); the component SELECT matches TokenFlow.dest(). Both SELECT and Scan append at the end, so the pre-existing base alignment is untouched.
  • Checked strings is imported in query.go, that TokenFlow.dest()'s pointer receiver is used on addressable values only, and that no other query selects requestCols or scans request_components with a column list that would now misalign (every other request_components query names its columns and is unchanged).
  • Checked the golden files need no regeneration: the demo database has no acc_priced rows, so acc_tokens stays 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 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.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 appends requestTokenSelect (the 32 requests.tok_* columns, r.-qualified). scanRequest appends requestTokenDest(&e.AccTokens) (32 pointers). I counted by script, treating kaSaved("r.") as one item: 120 select items and 120 scan targets. The orders match — both follow requestTokenEffects (ka, split, ttl, ended), each in flowColumns order (saved in/rd/w5m/w1h, then caused).
    • The component SELECT in DB.Request (dash/query.go:316) now reads the 8 request_components.tok_* columns; its scan appends c.Tokens.dest(). 24 columns, 24 targets.
    • The list path (/api/requests, dash/query.go:270) uses the same requestCols, so the list and the single read agree.
    • New test TestAccTokens_RoundTripThroughTheStore writes a priced event and reads it back by id and in the list, comparing acc_tokens and each component's tokens. It covers the fix.
    • No golden needed a change: no golden file contains priced_by or saved_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, TestOverviewLeanQueriesAreIndexed checks 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_requests breadth. 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 kaSaved splice treated as one item: 88 base + 1 kaSaved + 32 token = 120 select items in requestCols, 88 + 32 = 120 scan targets in scanRequest; 16 + 8 = 24 on both sides of the component query. requestTokenDest and requestTokenSelect follow the same order.
  • The read paths that consume requestCols: only the list (query.go:270) and the by-id read (query.go:309), both through scanRequest. 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) and db.Requests(Filter{TenantAll: true}, 0, 10) both exist with those signatures; the component order comparison by index matches the ORDER BY rowid insert order; the fixture's PriceMode run populates AccTokens and every component's Tokens, 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/stats stays 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.

@amiddavid

Copy link
Copy Markdown
Collaborator Author

Owner decision (2026-11-10): by_feature.cachesplit stays one entry. It joins the cache split component's own operations and the split cache effect.

@amiddavid

Copy link
Copy Markdown
Collaborator Author

The lean read is back inside its budget. Fix: commit 07aaf500.

Timing. TestOverviewLeanSessionStaysUnderBudgetAt20000Requests, the timed second OverviewLean call, eval box, 5 runs each:

Code Plain With -race
origin/main 52.7-55.0 ms 2.16 s
573c15a (before) 214 ms (coordinator's figure) 8.7 s
All 40 token sums in the main scan, no join 89 ms not measured
This fix 64.5-69.3 ms (64.6 ms median) 2.58 s

The fix is 1.22x main, which is inside the 70 ms target.

What changed

  1. No new query on the lean path. The lean read takes its token terms from the existing single scan (leanWindowMainQuery). It runs no join to request_components.
  2. 8 new additive columns requests.tok_total_*. Each holds the request's whole token figure, by tier: its component rows plus its four effects. The write path fills them at write time. The lean read sums only these 8 columns and the unmeasured count: 9 terms. Each term costs about 1 ms on this test.
  3. Lean has fewer fields than full. Lean has tokens.saved, tokens.caused and tokens_unmeasured_requests. It has no tokens.by_feature and no keepalive_ping_tokens. The ping tokens are only useful next to the keep-alive's own entry, and lean does not have that entry. docs/dashboard.md lists the lean fields.
  4. by_feature is now left out when empty (omitempty). So lean has no by_feature key. The golden files lose "by_feature": {}; no other figure changes.
  5. A keep-alive ping stores no token figure. The library never prices a ping, so this drops nothing. Because of it, the sums need no agent CASE. With that CASE, the 40-term version took 105 ms.
  6. Lean and full still agree. TestAccTokens_LeanAgreesWithFull checks the totals and the unmeasured count, for a session and for a time window. Lean takes its totals from tok_total_*. Full takes them from the component rows and the effect columns. So the test also checks that the per-request copy equals the figures it sums.

TestRegistrationRateLimitedPerIP is flaky on main. This PR does not touch it.

  • On the box, at origin/main: 20 of 20 runs passed with -race.
  • Cause: the limiter uses a fixed window that starts on each whole minute (proxy/limits.go, time.Now().Truncate(time.Minute)). The test makes 6 registrations in about 1.5 s under -race. If those cross a minute boundary, the count starts again at 0 and the limit never trips. The chance is about 2.5% for each run.
  • It needs its own issue and PR.

Tests: all ./dash/... tests pass on the eval box (-race -count=1 -timeout 30m, two halves). ^Test[A-H]: 543 passed, 0 failed, 5 skipped. ^Test[^A-H]: 836 passed, 0 failed, 9 skipped. The counts include subtests. The second half has 4 fewer subtests than before: the 4 EXPLAIN cases for the lean token queries are gone, because lean no longer runs those queries.

@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.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, scanRequest or the component SELECT. requestTokenSelect still reads the 32 effect columns. The tok_total_* columns need no read-back: they are an aggregate copy, not an Event field.
  • My round-2 non-blocking (the cachesplit doc caveat): resolved by decision. The owner decided on 2026-11-10 that by_feature.cachesplit stays 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_feature and 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:
    1. 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.
    2. Author comment 22:14:00Z (owner decision: cachesplit stays one entry). Closes my round-2 note. Decision recorded.
    3. 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).
    4. Commit 07aaf50. Reviewed as a first review; findings above.
  • The write path. requestStoredTokenArgs returns 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. leanWindowMainQuery appends accTokenLeanTerms (8 tok_total_* sums + the unmeasured count); tok.dest() scans 8 totals then unmeasured, in the same order. flowColumns order (saved in/rd/w5m/w1h, caused in/rd/w5m/w1h) matches flowOf's reading and TokenFlow.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 uses f.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_LeanAgreesWithFull covers 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. TestAccTokenColumnsAreAddedToAnOldDatabase drops 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, which TestOverviewLeanQueriesAreIndexed still EXPLAIN-tests as the exact executed statement.
  • The goldens and docs. by_feature is omitempty now; the goldens lose only "by_feature": {} (the demo database has no priced rows). The docs section moved; the #savings-in-tokens anchor 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 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.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. requestTokenSelect and requestTokenDest still use requestTokenColumns() (32 columns), so the read-back is untouched by this commit. The new tok_total_* columns are rightly not in requestCols: no Event field 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_tokens and keepalive_ping_output_tokens, as zeros. The fields have no omitempty, and a struct cannot use it. The lean path never computes them, so apply writes 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 ambiguity acc_priced exists to avoid. No lean client reads these fields today (statusline.py, cg.py), so this is a doc and contract point only. omitzero on both fields would make the doc exact.
  • docs/dashboard.md — "The lean read ... has tokens.saved, tokens.caused and tokens_unmeasured_requests only" is exact for the tokens object, 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_* over withKeepAlive(f) scope with no agent CASE. Full sums the 32 effect columns over the same scope (plain SUM, no CASE either now) plus request_components.tok_* over f.where() scope. tok_total is written at insert time as the sum of the same in-memory c.Tokens and 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 every e.KeepAlive row, effects and totals both. The keepalive column is boolInt(e.KeepAlive) (dash/store.go:665), so every keepalive = 1 row — 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 Tokens and the TTL/ended legs in memory before the insert (dash/accountant_price.go:425-432), so tok_total and both reads keep only rescue and split, together.
    • Other writers. insertBatch is the only INSERT into requests; the two UPDATEs (setBypassTokens, the project and strategy backfills) touch no tok_ column. Nothing re-prices a stored row.
    • Old databases. The 8 new columns are in the DDL and in additiveColumns (init appends requestStoredTokenColumns, 40 entries), so addColumns migrates and the read-only shim adds each missing column as its default 0.
    • The test. TestAccTokens_LeanAgreesWithFull covers a session and a window, with a ping row inside the session's scope, a fallback row and a legacy row.
  • 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: accTokenLeanTerms is 8 totals + unmeasured = 9, appended to the query after defer_net_usd and scanned by tok.dest() after &o.DeferNetUSD — same position. leanAgg.total[8] and flowOf both follow flowColumns order (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 = 0 CASE. I checked every row class the CASE used to exclude: ping rows store zeros (above), and no other writer sets tok_* on a keepalive = 1 row. The unmeasured count keeps its CASE (unmeasuredTerm), identical in both reads.
  • ByFeature omitempty. The full read allocates the map; addFeature adds 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=1 with 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/accTokensComponentQuery on 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-tokens matches 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/stats stays append-only against main (main has no tokens object 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]>

@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.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 shas 591509a6, 70ec2b5a, 3ae7056b); their messages are unchanged. I diffed the old PR patch (base 10329879, head 07aaf500) against the new one (base 8cbb700, head 3ae7056b) 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 — requestTokenSelect and requestTokenDest now sit after main #991's 7 limit items and auth_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 follow limitCols and auth_subscription in the INSERT. Counted by script: 95 base + 7 limitCols + 1 auth_subscription + 40 token = 143 named columns, 143 placeholders (103 literal + 40 generated), 143 Exec args (95 base + 7 limitArgs + 1 + 40). Aligned.
    • dash/overview_lean.go — the PR's hunk is unchanged. Main #992's SavedGross/ReplayTokens block (new base code) sits before tok.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; the tok_total_* DDL is intact.
    • docs/dashboard.md — the "Savings in tokens" section moved after main's new hosted-mode content. The #savings-in-tokens anchor is intact and reference.md links to it.
  • Main's new lean client is not affected. #981's subscription band (statusline.py _saved_tokens) reads saved_unique and replay_tokens from the lean read, not the tokens object. Both fields are still served (replay_tokens by #992's block, kept by the rebase). The lean field reduction (no by_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.cachesplit stands.
  • Reviewer 2's round-3 non-blocking (lean emits zero keepalive_ping_tokens): still open. I verified it myself: dash/overview.go:446-447 has no omitzero on either field, and leanAgg.read() leaves Ping zero, 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+ supports omitzero on 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 at dash/query.go:201. Cosmetic.

Non-blocking

  • The lean keepalive_ping_tokens / keepalive_ping_output_tokens zeros, 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_tokens shows, 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..07aaf500 against 8cbb700..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:
    1. 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).
    2. 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). limitArgs always returns 7 values, matching limitCols.
  • requestCols/scanRequest after the rebase: the PR's 32 token items follow main's 7 limit items and auth_subscription on both sides, in the same order. limit_seen is not read (main's choice, unchanged).
  • The lean read: query and scan identical to round 3's verified shape; accTokenLeanTerms (9 terms) still scanned by tok.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.go or 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 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.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:

  1. insertBatch (dash/store.go): the token columns now follow main #991's limitCols, auth_subscription.
  2. requestCols/scanRequest (dash/query.go): requestTokenSelect and requestTokenDest now follow the 6 limit columns and auth_subscription.
  3. overviewLeanWindow (dash/overview_lean.go): the tokens read sits beside main #992's SavedGross/ReplayTokens arithmetic.
  4. docs/dashboard.md: the "Savings in tokens" section moved to follow main #991's limits section; the #savings-in-tokens anchor 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_tokens and keepalive_ping_output_tokens as zeros (round 3, unchanged). The fields have no omitzero, 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. omitzero on both fields would make the doc exact.
  • dash/query.go:201 — requestCols still 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 + 7 limitCols + 1 auth_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 — SavedGross and ReplayTokens are Go arithmetic on values the scan already reads (overview_lean.go:86-89). The 9 token terms are still last in the SELECT and tok.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.go is 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 tokens objects (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.

@amiddavid

Copy link
Copy Markdown
Collaborator Author

Rebase after #991

The branch is rebased onto main (8cbb700). New head: 3ae7056b. Old head: 07aaf500.

The same 3 commits are kept. The rebase had hand-merged conflicts in 4 files. Both sides were kept each time.

Tests

  • go vet ./dash/... and gofmt -l dash: clean.
  • go test -race ./dash/...: the one full run hit the 10-minute timeout under box load (stuck in migrate). Three split runs all passed.

Approval check

The patch changed. A new review round must review the merge hunks above.

@amiddavid
amiddavid merged commit 7fd26dc into main Nov 10, 2026
9 checks passed
@github-project-automation github-project-automation Bot moved this from New/ToDo to Done in Rossoctl Issue Prioritization Nov 10, 2026
amiddavid added a commit that referenced this pull request Nov 10, 2026
…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]>
amiddavid added a commit that referenced this pull request Nov 10, 2026
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]>
amiddavid added a commit that referenced this pull request Nov 10, 2026
…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]>
amiddavid added a commit that referenced this pull request Nov 10, 2026
…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]>
amiddavid added a commit that referenced this pull request Nov 10, 2026
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]>
amiddavid added a commit that referenced this pull request Nov 11, 2026
…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]>
amiddavid added a commit that referenced this pull request Nov 11, 2026
…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]>
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.

1 participant