Repository navigation
feat(metrics): price savings by the whole bill difference at each prompt size - #112
Conversation
Add the optional SizedPricer interface. If the host's pricer has PriceAt, the sink prices saved tokens at the prompt size without the operations and caused tokens at the billed size. A pricer without PriceAt sees no change. Fixes #111 Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
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.332 | offload-review skill, @amiddavid's session | fresh | 2 of 2 | 1 of 2 | ce8ed435de95 |
approve |
Verdict: approve
Findings
None. The code matches the docs, and the arithmetic rests on an identity the engine already checks.
Non-blocking
- metrics/metrics.go:299 — the model prices moved tokens only, not the re-rate of unchanged tokens. When an operation moves a request across a pricing line, the tokens that stay also change rate. The sink books only
saved × rate(base) − caused × rate(billed). Example: billed 250,000 below the line, base 290,000 above it, saved 40,000. The sink books 40,000 × 2x. The bill difference is 290,000 × 2x − 250,000 × 1x, which is larger. The convention is documented and conservative (it understates a saving). A host that reads the USD as a bill difference should know this. No change asked. - metrics/metrics.go:334 — the
base <= 0clamp has no test. The clamp sends the saved side back toPrice. Every other new path has a test. A one-line test would close the gap. - metrics/metrics.go:299 —
pricestill calls the pricer for tiers with zero tokens. The cache-effect loop passestiers(tt), which always holds all four tiers.bookskipsn <= 0;pricedoes not. SoPriceAtruns for tiers with no tokens, and anestimatedreturn on such a tier marks the request. The same shape existed withPricebefore this PR, so it is not a regression. - docs/metrics/metrics.md:66 — "the same Price calls" is not literal. For a host without
PriceAt, the figures are the same. The interaction path now splitsnetintoposandneg, so the exact call sequence can differ (it drops zero-token tiers). The figures are identical; only the sentence is loose.
What I checked
- Read
CLAUDE.md,docs/spec.md,docs/design.mdanddocs/metrics/metrics.mdin full for the rules that apply. - Read the full diff (
ac23a62..HEAD, 4 files) and the code around each change:metrics/metrics.go,metrics/observer.go,metrics/sized_test.go,metrics/metrics_test.go. - Proved the base-size arithmetic against the engine. Check 6 (
conservation,internal/engine/compute.go:2323) states the identity: client body tokens minus billed tokens equalΣ(Saved − Caused)over the content operations. Sobase = billed + Σ(Saved − Caused)is the size of the request without the operations, which is what the docs promise. - Proved the "effects and interaction net zero tokens" claim.
addBreak(compute.go:1659-1665),rescue(:1698-1699),split(:1781-1782),ttlRescue(:1751),markPremium(:1904-1905),ttlPremium(:1910) andinteraction(:2315-2316) each move the same count between tiers. Excluding them frombaseis therefore right. - Proved spend operations add nothing to
base.priced(compute.go:269) andc.price(:2184-2252) leave a spend'sSavedandCausedat zero; the call usage is booked apart, atcallSize, its own prompt size. - Checked
Usage.CacheWriteholds the 1h part (internal/engine/types.go:85-92), sobilled = Input + CacheRead + CacheWriteis correct and does not double-count. - Checked the guards:
rateusesPriceAtonly when the pricer has it andsize > 0; a pricer withoutPriceAtgetsPriceon every path.sizesreturns zeros for such a host. - Checked the interaction split: positive net tiers priced at
base, negative atbilled, signs preserved, direction booked from the signed total. Matches the docs. - Ran, in this worktree:
gofmt -l .(nothing),go vet ./...(clean),go test ./...(ok) for the root module, and the same three for themetricsmodule (ok). - Checked the repo rules: the root module is untouched, so R3 and the
accountant.goAPI rule hold;Computedid not change; the docs were updated in the same PR.
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.332 | offload-review skill, @amiddavid's session | fresh | 1 of 2 | 1 of 2 | ce8ed435de95 |
approve |
Verdict: approve
Findings
None.
Non-blocking
- metrics/metrics.go:328 — an unpriced operation moves the base size, but
sizesdoes not count it. The engine can refuse to price an operation that still changed the body (media_tokens,unknown_kind). Such an op has zeroSaved/Caused, sobasemisses its tokens and can sit on the wrong side of the threshold. The doc (metrics.md,SizedPricersection) says the size is "exact arithmetic", which is stronger than this case. Mostly the safe direction (an under-counted base understates a saving, R45). Suggest one doc line, not a code change. - metrics/metrics.go:334 — the
base <= 0fallback has no test. The branch that sends the saved side toPricewhen the derived size is not credible is documented but untested.TestUnknownSizeUsesPlainPricecovers only the empty-Usagepath. A one-line test would close the gap. - metrics/metrics.go:327 —
baseinherits the byte-ratio rounding. Check 6 tolerates about one token per span between the ratio figure and the host's tokens.basecarries the same slack, so a request within a few tokens of a threshold can price on either side. Inherent in the engine's figures; no change asked.
What I checked
- Read the full diff (
ac23a62..ce8ed43):metrics/metrics.go,metrics/sized_test.go,docs/metrics/metrics.md,docs/design.md, and the code around each change. - The base-size formula.
base = billed + Σ saved − Σ causedover counted ops. This is the engine's own conservation identity (check 6,internal/engine/compute.goconservation): client body tokens − billed = Σ(saved − caused), within a one-token-per-span tolerance. Sobaseis the size of the client request, which design §6.2 "The long-context tier" names as the side for saved tokens. Verified that spend and setting ops carry zeroSaved/Caused(engineprice()fills onlyKindRewrite), so counting them insizeschanges nothing. - Cache effects and the interaction net zero tokens. Checked every effect constructor (
addBreak,rescue,rescueTail,headTTL,split,premiums, mark payback):SavedandCausedhold the same count n in different tiers. So excluding them fromsizesis right, and the two-sided rule (saved side atbase, added side atbilled) matches the bill-difference identity: every counterfactual token belongs to the client request, every billed token to the forwarded one. - The interaction split by tier sign (
Observe, pos/neg maps): positive tiers areResult.Interaction(client-side writes) and takebase; negative tiers areInteractionCaused(billed reads) and takebilled. Consistent, and the USD sign anddirectionlabel keep their old meaning. - Fallbacks. A pricer without
PriceAtgetsPriceon every path (sizesreturns zeros,ratecheckssize > 0), so its calls and figures are unchanged —TestHostWithoutPriceAtSeesNoChangeproves it. A spend call is priced at its ownCall.Usagesize, independent of the request-level sizes. An emptyUsagesends both sides toPrice. - Docs against code.
metrics.mdand thedesign.mdparagraph describe the code as written (billed size formula, dry-run skip, the two sides, the spend rule, no newestimatedmark).Computeis unchanged, so no spec change is due. The doc's provider examples check out: Haiku 5.5 bills beyond 100K prompt tokens at a higher rate, and the 272,000 figure matches the GPT long-context tier. - Rules. The root module still imports only the standard library;
metricsadds no import. No host names in Go files. The public API of the root package is untouched;SizedPriceris a new export of themetricsmodule and is documented. - Tests. Ran
gofmt -l .,go vet ./...,go test ./...in both modules (root andmetrics) in this worktree: all clean, all 7 new tests pass. Read each new test and its expectations against the code.
- Do not price a tier with 0 tokens, so an estimated return on an empty tier no longer marks the request. - Test the fallback to Price when the derived size is not above 0. - Docs: unpriced operations, byte rounding, and softer wording. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
When the sent request and the request without the operations fall on different sides of a price line, the tokens that stay change rate too. Book stay x (rate at base - rate at billed) per tier, so the saving is the whole bill difference. Split it across the operations by net saved tokens. With no saving operation, book it to interaction.usd. Only a host with PriceAt gets it. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
Replies to round 1, and an owner decisionOwner decision (David Amid, 2026-11-25): count the full bill difference. A request can cross a price line. Then the tokens that stay also change rate, and the saving includes that change. Commit
Reviewer 1
Reviewer 2
Open questions in the PR body:
Tests (macOS, Go 1.27.4): |
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.332 | offload-review skill, @amiddavid's session | resumed | 1 of 2 | 2 of 2 | 1634fd92af1e |
blocking |
Verdict: blocking
Findings
- metrics/metrics.go:331-339 — the re-rate counts cache-effect tokens as staying, so the request total over-states the bill difference
- What fails: a counted (not
InBaseline) cache effect moves tokens between tiers. ItsCausedside sits inObservation.Usageat the forwarded tier.reRatesubtracts onlyop.Causedwhen it computesstay, so the effect's tokens stay instayat their forwarded tier. But those tokens are not staying tokens: the request without the operations bills them at another tier (a break: read; a rescue: write). The effect already prices their whole difference (Savedat the client tier and base size,Causedat the forwarded tier and billed size). The re-rate prices them a second time, at the forwarded tier on both sides. When the two sizes straddle a price line, the net saving exceeds the bill difference byΣ effectCaused_t × (rate at base − rate at billed). This breaks the property the commit exists for: "the saving is the whole bill difference". - Proof: take the test pricer (
tiered{}, line at 272,000, 2x above, all tiers). Usage ={Input: 249_000, CacheWrite: 1_000}(billed 250,000, below the line). One rewrite op,Saved{Input: 50_000}→ base 300,000 (above the line). One break effect, notInBaseline,Saved{CacheRead: 1_000},Caused{CacheWrite5m: 1_000}. The sink books: op saved 50,000×2e-6 = 0.1; effect saved 1,000×2e-6 = 0.002; effect added 1,000×1e-6 = 0.001; re-rate stay: Input 249,000 and Write5m 1,000 → (249,000+1,000)×(2e-6−1e-6) = 0.25. Net = (0.1+0.25) + 0.002 − 0.001 = 0.351. The bill difference is 300,000×2e-6 − 250,000×1e-6 = 0.35. The over-statement is 0.001 = the break's 1,000 tokens priced again at the write tier. The engine side confirms the tier move:addBreak(internal/engine/compute.go:1659-1665) setsSaved.CacheRead = nandCaused= write of the samen;rescue(:1698-1699),markPremium/ttlPremium(:1904-1910) andmarkPayback(:2001) all do the same. Design §4.4 defines an effect as "a change in how the provider bills content that is already there" — the content is in both requests, only the tier moves. - Fix: in
reRate, also subtract theCausedof the counted effects: skipe.InBaseline(the client body would have had that break too, so those tokens really do stay at one tier), thenfor t, n := range tiers(e.Caused) { billed[t] -= n }. Add a test likeTestEffectsAndInteractionFollowTheSideswith the effect's write insideUsage.CacheWrite, asserting the net equals the bill difference.
- What fails: a counted (not
Non-blocking
- docs/metrics/metrics.md:101 — the counter table row for
interaction.usdis now incomplete. The row says the counter holdsResult.InteractionminusInteractionCaused. Since1634fd9it can also hold an unattributed re-rate. TheSizedPricersection says so; the table row does not. One sentence fixes it. - metrics/sized_test.go — no test combines the re-rate with a counted effect. Every re-rate test has effects absent or outside
Usage. That is why Finding 1 passed the suite. The fix's test closes this.
What I checked
- Last review: round 1,
ce8ed435de95a3ca777b4ed83eac94852748cf31, 2026-11-25T14:47:57Z. - New commits read: 2 —
a64c04d"fix(metrics): skip empty tiers and cover the unknown base size",1634fd9"feat(metrics): book the re-rate of the tokens that stay". Readgit diff ce8ed43..HEADin full and the code around each change (metrics/metrics.goreRate,price, theObservecall site, all new tests, both doc files). - 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 15:11 (replies to round 1 and the owner decision), commit
a64c04d, commit1634fd9. Also read reviewer 2's round-1 review (posted 13 s before mine) as round 2 requires. - My round-1 notes: unpriced ops and the "exact arithmetic" wording — fixed in
metrics.md(documented, wording softened). No test for thebase <= 0fallback — fixed,TestBaseSizeNotCredibleFallsBackToPrice; the author's note that the clamp is a redundant guard is right (ratealready refuses a size of 0). Byte-ratio rounding — documented. - Reviewer 2's round-1 notes: moved tokens only — superseded by the owner decision, now implemented (with Finding 1).
base <= 0clamp test — fixed.PriceAton empty tiers — fixed,priceskipsn == 0,TestEmptyTierDoesNotMarkEstimatedcovers it. "The same Price calls" — fixed, the doc now says "the same figures". - The re-rate arithmetic. Re-derived the bill-difference identity: forwarded bill per tier = stay + opCaused + counted-effect Caused; client bill per tier = stay + opSaved + counted-effect Saved + interaction. Without effects the code is exact — I checked every re-rate test's numbers by hand (
TestSavedPricedWithoutTheOperationCausedAtBilled,TestTheLineIsExclusive,TestReRateSplitsByNetSavedTokens,TestNegativeReRate,TestReRateWithNoSavingOpIsUnattributed,TestNoLineNoReRate): each net equals the bill difference. With counted effects it is not — Finding 1. Also checked:InBaselineeffects must stay instay(the client body would have had that break too, so the tier does not change between the requests); the interaction tokens never enterUsage(the op removed the content), so they cannot pollutestay; opCausedand effectCausedare disjoint (the premiums identity, §4.4); the pro-rata split sums exactly to the re-rate; a negative part goes toadded.usdbecause OTel counters reject negatives; a host withoutPriceAtnever reachesreRate(sz.basestays 0). - The empty-tier skip (
a64c04d):pricenow skipsn == 0, keeps pricingn < 0(the interaction's negative tiers need it). Figures unchanged for every host; only theestimatedmark from empty tiers goes. Documented. - Ran, in this worktree at
1634fd9:gofmt -l .(nothing),go vet ./...(clean),go test ./...(ok) for the root module, and the same three for themetricsmodule (ok). - Rules: the root module is untouched (R3,
accountant.goAPI);Computedid not change;docs/design.mdanddocs/metrics/metrics.mdwere updated in the same commits.
Above the line a provider can bill output at a higher rate (GPT: 1.5x). Add Observation.Output. The output is the same with and without the operations, so all of it stays: book output x (rate at base - rate at billed), split like the other tiers. Output never counts toward the prompt size. A host with Output 0 sees no change. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
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.332 | offload-review skill, @amiddavid's session | resumed | 2 of 2 | 2 of 2 | 1634fd92af1e |
blocking |
Verdict: blocking
Findings
-
metrics/metrics.go:336 — the re-rate counts the tokens a cache effect caused, so it books a saving that never existed.
- What fails: a request with a cache effect (a break, a rescue, a split, a premium, a payback) that crosses a price line. The re-rate computes
stay = billed − op-causedper tier. The effect's caused tokens are billed tokens, so they land instay. But the request without the operations does not hold them in that tier (its copy sits in the effect's saved tier, priced by the effect booking). The re-rate prices them a second time. The docs promise "the saving is then the whole bill difference" (design.md, metrics.md). It is not. - Proof: an engine-realistic request that satisfies the conservation identity (design §6.3). Billed 270,000 (input 100,000, read 150,000, write5m 20,000). A trim saves 50,000 input; a rescued span saves 1,000 read; one non-InBaseline break (saved read 20,000, caused write5m 20,000); interaction write 1,000 / read 1,000. Client body 321,000, above a 272,000 line (2x); billed below (1x). True bill difference 0.1650 USD. The sink's own formulas book 0.2251 USD — 37 percent too much. The excess is exactly the break's 20,000 write5m tokens in
stay: 20,000 × (6e-6 − 3e-6) = 0.06. I checked the arithmetic three ways: by hand, by the closed formbooked − true = Σ (rb−rs) × (effect Caused)per tier, and by a numeric simulation of the coded formulas. - Fix: subtract the caused tokens of every non-InBaseline cache effect from
stay, per tier. An InBaseline break's tokens do stay in both bodies, so keep those. With this fix, and finding 2's fix, the booked total equals the bill difference exactly (0.1650 in the example above).
- What fails: a request with a cache effect (a break, a rescue, a split, a premium, a payback) that crosses a price line. The re-rate computes
-
metrics/metrics.go:194 — the interaction's negative tier is priced at the billed size, but it is a client-side figure.
- What fails: a rescued request that crosses a price line.
InteractionCausedis "the same tokens at the read tier, as the operation books them" (design.md §6.2) — the operation books them asSaved, so the sink prices them atbase. The interaction then subtracts them atbilled. The two sides of the correction must use the same size, or the op-plus-interaction total is wrong byC × (rate at base − rate at billed)on the read tier. The tokens were removed from the sent body, so the provider billed nothing for them; nothing about them lives at the billed size. - Proof: same request as finding 1. The interaction books −1,000 × 1e-7 (billed size, 1x). It should book −1,000 × 2e-7 (base size, 2x), the exact opposite of the op's own booking of the same 1,000 tokens. Error 0.0001, confirmed by the same simulation. This is round-1 code, and both round-1 reviews missed it; I raise it now because the new "whole bill difference" claim depends on it, and this round is the last.
- Fix: price the negative net tiers of the interaction at
sz.base. The docs ("a negative one is added") must change with it.
- What fails: a rescued request that crosses a price line.
Non-blocking
- metrics/metrics.go:341 — the re-rate fallback books one
interaction.usdpoint per tier. The interaction booking above it books one point for the whole net, with the sign of the total. When no operation has a net saving and several tiers re-rate in opposite directions, the two paths shape the counter differently. The request total is still right. - metrics/metrics.go:343 — the docs say "a request that crosses no line has a re-rate of 0". True only for a threshold pricer. A host whose
PriceAtvaries with size gets a nonzero re-rate on every request. The formula stays right for such a host; only the sentence is too narrow. - docs/metrics/metrics.md — the example figures in "The re-rate" hold only with no cache effect on the request. Once finding 1 is fixed, add one test that mixes an effect with a crossed line. All six new tests keep effects and line-crossing apart, which is why the double-count passed.
Earlier findings, and the replies
My round-1 notes:
- Moved tokens only, no re-rate of the tokens that stay — the owner chose to book the full difference, and commit
1634fd92does it. The idea is right; the implementation is finding 1. - No test for the
base <= 0clamp — fixed (TestBaseSizeNotCredibleFallsBackToPrice). The reply says the clamp is redundant becauseraterefuses a size of 0. Correct:ratecheckssize > 0, so no test can catch the clamp's removal. Accepted. PriceAton zero-token tiers — fixed (priceskipsn == 0,TestEmptyTierDoesNotMarkEstimatedcovers it).- "The same Price calls" wording — fixed (the doc now says "the same figures").
Reviewer 1's round-1 notes: the unpriced-operation caveat and the byte-rounding caveat are now doc lines, and "exact arithmetic" is softened — fixed. The base <= 0 test — fixed, same test as mine.
What I checked
- Last review: round 1,
ce8ed435de95a3ca777b4ed83eac94852748cf31, 2026-11-25T14:47:44Z. - New commits read: 2 —
a64c04d"fix(metrics): skip empty tiers and cover the unknown base size",1634fd92"feat(metrics): book the re-rate of the tokens that stay". - Read in full: 2 reviews, 1 comment, 0 inline comments (from
.review-in-reviews.txt,.review-in-comments.txt,.review-in-inline.txtin my folder). - New items since my last review: reviewer 1's round-1 review (checked its three notes against the fixes), the author's reply comment (checked every claim in it, including the redundant-clamp argument), and the two commits above (full diff read, plus the changed files around each change).
- The re-rate claim. Built the request-total identity from design §6.3: client body per tier = billed + ops(saved−caused) + effects(saved−caused) + (Interaction − InteractionCaused). Verified each part against the engine:
addBreakmoves read→write,interactionwrites the cold side and names the read side "as the operation books them" (compute.go:2315-2316). Then computed the sink's bookings from the coded formulas and compared with the true difference. Result: the two findings above, each with its exact error term, and the proof that both fixes together close the gap to 0. - The two fixes' side effects. Subtracting only non-InBaseline effect
Causedkeeps InBaseline breaks instay, which is right (the client body would have had that break too). Pricing the interaction's negative tiers atbasechanges nothing for a request that crosses no line. - The rest of the new code: the split by net saved tokens sums to the whole amount; a negative part books to
added.usd(OTel counters take no negative); the no-saving-op fallback books tointeraction.usd; the re-rate runs only for a host withPriceAt(sz.base > 0needssizes, which needs a sized pricer); spend calls stay out ofstay(their usage is inCall.Usage, notObservation.Usage). - Ran, in this worktree:
gofmt -l .(nothing),go vet ./...(clean),go test ./...(ok) for the root module and themetricsmodule. All 6 new tests pass; the double-count is invisible to them because each keeps effects and a crossed line apart. - Repo rules: the root module is untouched;
Computedid not change; the docs were updated in the same commits.
- The re-rate left the Caused tokens of counted cache effects in the tokens that stay. The effect booking already prices them. Subtract them per tier. InBaseline effects stay. - Price the interaction whole at the size without the operations. Both of its sides are client-side figures. - Book an unowned re-rate as one interaction point with the sign of the total. - Test a mixed request: the net saving equals the bill difference. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
Replies to round 2 (both reviewers blocked)The owner also decided that output tokens are re-rated. Commit Finding 1, both reviewers: the re-rate counts cache-effect tokens twice. Fixed in
Finding 2, reviewer 2: the interaction was priced at the billed size. Fixed. The interaction's net now prices at the size without the operations, so both sides of the correction use one size. The docs no longer say "a negative one is added". Reviewer 2's non-blocking notes: all fixed.
Tests (macOS, Go 1.27.4): The owner granted round 3. |
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.332 | offload-review skill, @amiddavid's session | resumed | 1 of 2 | 3 of 3 | 2b3953090178 |
approve |
Verdict: approve
Findings
None.
Non-blocking
- metrics/observer.go:12 — the output re-rate rests on the assumption that the output count is the same with and without the operations. The counterfactual request would produce a different output; the sink cannot know it, so it holds the count fixed. The doc says so, and no other convention is workable. No change asked; noted so the assumption is on the record.
- metrics/metrics.go — a spend call's output tokens get no re-rate.
callTiersprices a call's output at the call's prompt size, and the re-rate covers only the request's ownObservation.Output. The doc does not promise a call output re-rate, so this is a scope note, not a defect.
What I checked
- Last review: round 2,
1634fd92af1e2a4e6faab187bd8a492612a804e4, 2026-11-25T15:17:48Z. - New commits read: 2 —
95a8a5b"feat(metrics): re-rate the output tokens too",2b39530"fix(metrics): do not double-count cache effects in the re-rate". Readgit diff 1634fd9..2b39530in full and the changed files around each change (reRate, the interaction block inObserve,Observation, all new and changed tests, both doc files). - 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: reviewer 2's round-2 review (15:23, two findings — checked both against the fixes), the author's reply comment (15:27 — checked every claim), commit
95a8a5b, commit2b39530. - My round-2 finding 1 (effect Caused double-counted in
stay): fixed.reRatenow subtracts theCausedof every non-InBaselineeffect, per tier, which is the fix I proposed.InBaselineeffects stay instay— right, the client body would have had that break too. I verified the new mixed test by hand: billed 270,000 (input 100,000, read 150,000, write5m 20,000), op saved 50,000 input and 1,000 read, break saved 20,000 read / caused 20,000 write5m, interaction 1,000 write against 1,000 read, base 321,000. The sink books op 0.3006, effect −0.063, interaction 0.0069, re-rate 0.345 (stay: input 100,000, read 150,000, write5m 0). Total 0.5895 = client bill 1.0095 − sent bill 0.42. The identity closes exactly, with each tier at its own rate. - Reviewer 2's round-2 finding 2 (interaction's negative tiers at the billed size): fixed, and the fix is right. Both sides of the interaction are client-side figures:
Interactionis the client body's cold write,InteractionCausedis the read the op books asSavedat the base size. The whole net now prices atsz.base, so the op's read booking and the interaction's read subtraction cancel at the same rate. I checked the changed test's figure (600 × 2e-6) and the mixed test above, where the pair cancels exactly. - Reviewer 2's round-2 non-blocking notes: the unowned re-rate now books one
interaction.usdpoint with the sign of the total — fixed, and the code books nothing when the tiers cancel to 0. The "crosses no line" sentence now names a threshold pricer — fixed. The re-rate example says it assumes no cache effect — fixed. - My round-2 non-blocking notes: the
interaction.usdcounter-table row now names the unowned re-rate — fixed. The missing effect-plus-line test — added (TestEffectAndInteractionAddUpToTheBillDifference). - The output re-rate (
95a8a5b).Observation.Outputis a new optional field; 0 means the host gives nothing and nothing changes. I checked:tiers()has no output key, so op and effectCausedcan never touch the output stay;sizesandcallSizeuse input, cache read and cache write only, so output never moves the prompt size (TestOutputDoesNotCountTowardPromptSizeproves it at the line); the re-rate gate (money && sz.base > 0) still keeps a host withoutPriceAtand an emptyUsageout. Hand-checkedTestOutputIsReRated: net 0.334 = (290,000×2e-6 + 2,000×6e-6) − (250,000×1e-6 + 2,000×4e-6) ✓. The doc's GPT output figure (1.5x above the line) matches the provider's documented long-context multiplier. - Docs against code.
metrics.mdanddesign.mddescribe the code as written: thestayformula with the effect subtraction, the interaction at one size, the one-point fallback, the output rules. The counter table matches.Computeis unchanged, so no spec change is due. The root module is untouched (R3,accountant.goAPI);metricsadds no import. - Ran, in this worktree at
2b39530:gofmt -l .(nothing),go vet ./...(clean),go test ./...(ok) for the root module, and the same three for themetricsmodule (ok). All 9 re-rate and output tests pass, read against the code.
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.332 | offload-review skill, @amiddavid's session | resumed | 2 of 2 | 3 of 3 | 2b3953090178 |
approve |
Verdict: approve
Findings
None. Both round-2 findings are fixed, and the fixes are exact.
Round-2 findings, and the fixes
- The re-rate counted cache-effect tokens twice (mine and reviewer 1's, same finding). Fixed.
reRatenow subtracts theCausedof every non-InBaseline effect fromstay, per tier (metrics/metrics.go:336-342).InBaselineeffects stay instay, which is right: the client body would have had that break too. The new testTestEffectAndInteractionAddUpToTheBillDifferenceis my round-2 case with per-tier rates; I recomputed its figures by hand (booked 0.5895 = client bill − sent bill) and they hold. - The interaction's negative tier was priced at the billed size (mine). Fixed. The whole net now prices at the size without the operations (
metrics/metrics.go:233-236), so both sides of the correction use one size. The docs dropped "a negative one is added" and state the reason.
My round-2 non-blocking notes: all fixed. The unowned re-rate books one interaction.usd point with the sign of the total (metrics/metrics.go:370-383); the re-rate-is-0 sentence now names a threshold pricer; the doc example says it assumes no cache effect. Reviewer 1's round-2 notes are fixed too: the interaction.usd table row now names the unowned re-rate, and the mixed test exists.
What I checked
- Last review: round 2,
1634fd92af1e2a4e6faab187bd8a492612a804e4, 2026-11-25T15:23:38Z. - New commits read: 2 —
95a8a5b1"feat(metrics): re-rate the output tokens too",2b395309"fix(metrics): do not double-count cache effects in the re-rate". Readgit diff 1634fd9..HEADin full, andmetrics/metrics.go,metrics/observer.go,metrics/sized_test.goand both doc files around every change. - Read in full: 4 reviews, 2 comments, 0 inline comments (from
.review-in-reviews.txt,.review-in-comments.txt,.review-in-inline.txtin my folder). - New items since my last review: reviewer 1's round-2 review (its finding is my finding 1; its proof I checked and agree with), commit
95a8a5b1, commit2b395309, and the author's reply at 15:27:35Z (every claim in it checked against the code). - The identity, end to end. I re-ran my round-2 request (billed 270,000 below the line, client 321,000 above it; a trim, a rescued span, a non-InBaseline break, an interaction) through the final coded formulas, now with 2,000 output tokens added. True bill difference 0.619500 USD; booked 0.619500 USD; gap 0. The closed form also collapses: with
stay = billed − op-caused − effect-causedand the interaction whole at base, the booked total equalsΣ client×rate(base) − billed×rate(billed)per tier, term for term. The output term extends the identity exactly: no op, effect or interaction books output, soObservation.Outputre-rates alone and closes its own term. - The output re-rate (
95a8a5b1).Outputnever enterssizes(), so it never moves the prompt size (TestOutputDoesNotCountTowardPromptSizecovers the boundary). A host withoutPriceAtnever reachesreRate; a host that leavesOutputat 0 gets no output term. A negativeOutputgivesstay <= 0and is skipped. The assumption that the output is the same without the operations is stated in the docs; under it the arithmetic is exact. - The docs against the code.
design.mdandmetrics.mdnow describestaywith the effect subtraction, the interaction at one size, the output tier, the one-point fallback, and the threshold-pricer caveat. The counter table row forinteraction.usdnames the unowned re-rate. I found no sentence that disagrees with the code. - Ran, in this worktree at
2b395309:gofmt -l .(nothing),go vet ./...(clean),go test ./...(ok) for the root module, and the same three for themetricsmodule. - Repo rules: the root module is untouched (R3,
accountant.goAPI);Computedid not change;Observation.Outputis a new field of the metrics module only, with a doc comment; the docs were updated in the same commits.
feat(metrics): price the cg_* savings counters by prompt size Bump rossoctl/accountant to 05cd0f84 (#112). The host pricer now has PriceAt, which reads the rate of the tier for the prompt size, with the same rule as the dashboard (modelinfo.Price.At). The host also fills Observation.Output, so the sink re-rates the output tokens. The counters now book the full bill difference at each prompt size. They did book base rates. Set flat: true on a price-file entry to turn the tiers off. Refs #1407, rossoctl/accountant#112. docs(metrics): name the llm_savings counters, fix 3 comments build(deps): pin accountant and accountant/metrics to v0.8.0 No pseudo-version is left in go.mod. v0.8.0 is 05cd0f84 plus #113 (an in-place change ends when a later change deletes its item). Behavior change (sized llm_savings counters; accountant #113 in v0.8.0) approved by the owner in the integrator session, 2026-11-25: "1424 yes". Both accountant modules pinned to the v0.8.0 tags. Assisted-By: Claude Opus 5.5 Signed-off-by: DAVID AMID <[email protected]>
v0.8.0 adds two engine fixes over v0.6.0: - A cache rewrite is charged to the new change at the first difference (rossoctl/accountant#110). - An in-place change on a whole item ends when a later change rewrites that same client item to 0 bytes (rossoctl/accountant#113, fixes rossoctl/accountant#108). Found reviewing #2057: with tool-prune, turn 1 remove:[NotebookEdit] moves the cache mark onto the survivor, and turn 2 remove:[Bash,NotebookEdit] deletes that survivor, so the stale in-place rewrite failed the sum and conservation checks on every later turn. The nested metrics module is now tagged at this commit, so metrics moves from a pseudo-version to v0.8.0 (rossoctl/accountant#112, SizedPricer): it prices savings by the whole bill difference at each prompt size. The new interface is additive, so cortex builds unchanged. Add a toolprune regression test for the #108 shape (fails on v0.6.0, passes on v0.8.0). Widen the savings-agreement thread-total tolerance to absorb the per-step micro-dollar rounding the new v0.8.0 case exposes. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
Fixes #111
Summary
metricssink now books the whole bill difference when a request crosses a price line.PriceAt.Pricerdoes not change.Resultfield is added.Observation.Usagealready holds the billed size.Observationgets one new optional field,Output.What changed
metrics/metrics.go:Usage.Input + CacheRead + CacheWrite.spendcalls follow the same rule.stay × (rate at base − rate at billed).stayis the billed tokens of the tier minus the tokens the operations caused.stayexcludes theCausedtokens of every counted (notInBaseline) cache effect. The effect booking already prices their whole tier move. AnInBaselineeffect stays instay.InteractionandInteractionCausedare both client-side figures. So both sides of the correction use one size.Observation.Output(in themetricsmodule, so no engine oraccountant.gochange). All output stays with and without the operations, so its re-rate isoutput × (rate at base − rate at billed), split like the other tiers. Output never counts toward the prompt size. A host that leavesOutputat 0 gets no output re-rate.Usage, or a size of 0 or less), the sink calls plainPrice, and there is no re-rate.docs/metrics/metrics.mdanddocs/design.md.priceskips a tier with 0 tokens, so an estimated return on an empty tier does not mark the request.How the re-rate splits (design choice)
saved.usd. A negative one books toadded.usd. Both use the operation'skind, the tier and thecomponent.interaction.usd(the existing series for tokens no operation owns), as one point with the sign of the total. The request total still holds it.Decision on
estimated: the sink sets no new mark for the derived size. An operation with estimated tokens is alreadyEstimated, so the request is already marked. TheestimatedthatPriceAtreturns is used as forPrice, also for the re-rate.How it was tested
macOS, Go 1.27.4.
gofmt -l .prints nothing.go vet ./...andgo test ./...pass in the root and inmetrics/.New tests (
metrics/sized_test.go), line at 272,000, 2x above:added.usd. Component net is below 0. Net equals the bill difference.interaction.usd, directionadded.Price.PriceAt: same figures asPrice.InBaseline), an interaction, and a crossed line, with a rate for each tier. The net saving equals the bill difference (0.5895).Mutations (each fails tests, then restored):
PriceAt: tests fail.Causedtokens fromstay: 1 test fails.Compatibility
Priceris unchanged.PriceAtgets the same figures as before.PriceAtsees the re-rate insaved.usd/added.usd(orinteraction.usd) on a request that crosses a line.Open questions
Assisted-By: Claude (Anthropic AI) [email protected]