Skip to content

feat(metrics): price savings by the whole bill difference at each prompt size - #112

Merged
amiddavid merged 5 commits into
mainfrom
feat/sized-pricer
Nov 25, 2026
Merged

amiddavid merged 5 commits into
mainfrom
feat/sized-pricer

Conversation

@amiddavid

@amiddavid amiddavid commented Nov 25, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #111

Summary

  • The metrics sink now books the whole bill difference when a request crosses a price line.
  • Rule: saving = bill of the request without the operations − bill of the request as sent. Each is priced at its own prompt size.
  • The host opts in. Its pricer adds PriceAt. Pricer does not change.
  • No Result field is added. Observation.Usage already holds the billed size. Observation gets one new optional field, Output.

What changed

  • New interface in metrics/metrics.go:
    type SizedPricer interface {
        PriceAt(model string, at time.Time, tier Tier, promptTokens int64) (usdPerToken float64, estimated bool)
    }
  • Billed size = Usage.Input + CacheRead + CacheWrite.
  • Size without the operations = billed + saved − caused, over the counted (not dry-run) operations.
  • Moved tokens: saved tokens use the size without the operations. Caused tokens use the billed size. Cache effects, the interaction and spend calls follow the same rule.
  • Re-rate of the tokens that stay (owner decision, 2026-11-25). When the two sizes are on different sides of a line, the tokens that stay change rate too. Per tier: stay × (rate at base − rate at billed). stay is the billed tokens of the tier minus the tokens the operations caused.
    • Example, line at 272K, 2x above: a trim takes 290K to 250K. The sink books 40K × 2x for the moved tokens, plus 250K × (2x − 1x) for the tokens that stay. Net: 290K × 2x − 250K × 1x.
  • stay excludes the Caused tokens of every counted (not InBaseline) cache effect. The effect booking already prices their whole tier move. An InBaseline effect stays in stay.
  • The interaction is priced whole at the base size. Interaction and InteractionCaused are both client-side figures. So both sides of the correction use one size.
  • Output tokens are re-rated too. The host gives them in the new field Observation.Output (in the metrics module, so no engine or accountant.go change). All output stays with and without the operations, so its re-rate is output × (rate at base − rate at billed), split like the other tiers. Output never counts toward the prompt size. A host that leaves Output at 0 gets no output re-rate.
  • When the size is unknown (empty Usage, or a size of 0 or less), the sink calls plain Price, and there is no re-rate.
  • Docs: docs/metrics/metrics.md and docs/design.md.
  • Small fix in the same file: price skips 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)

  • The components add up to the request total. Each operation takes a share in proportion to its net saved tokens (saved − caused, only above 0).
  • Why: the operations together cross the line. Net saved tokens is a stable weight and needs no new data.
  • A positive amount books to saved.usd. A negative one books to added.usd. Both use the operation's kind, the tier and the component.
  • A negative amount happens when the sent request is above the line and the base is not. A component's net can then be below 0.
  • If no operation has a net saving above 0, the re-rate books to 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.
  • This is the default design from the owner. I made no change to it.

Decision on estimated: the sink sets no new mark for the derived size. An operation with estimated tokens is already Estimated, so the request is already marked. The estimated that PriceAt returns is used as for Price, also for the re-rate.

How it was tested

macOS, Go 1.27.4. gofmt -l . prints nothing. go vet ./... and go test ./... pass in the root and in metrics/.

New tests (metrics/sized_test.go), line at 272,000, 2x above:

  • 290K → 250K: saved 0.34, added 0.01, net 0.33 = 290K × 2x − 250K × 1x.
  • At the line (272,000): 1x, no re-rate. One token above (272,001): 2x plus the re-rate.
  • Split across two components (a 30K, b 10K): 75% / 25%. The sum equals the bill difference.
  • Negative case (billed 285K, base 250K): re-rate books to added.usd. Component net is below 0. Net equals the bill difference.
  • No saving operation: the re-rate books to interaction.usd, direction added.
  • No line crossed (both below, both above): no re-rate.
  • Dry-run operation does not move the size. Unknown size and non-credible base size use plain Price.
  • Host without PriceAt: same figures as Price.
  • 290K → 250K with 2,000 output tokens at 1.5x vs 1x: output re-rate 0.004, net equals the bill difference. Output 0: no output re-rate. Output does not tip the prompt size over the line.
  • Mixed request: a trim, a rescued span, a break (not InBaseline), an interaction, and a crossed line, with a rate for each tier. The net saving equals the bill difference (0.5895).
  • Empty tier does not mark the request estimated.

Mutations (each fails tests, then restored):

  • Price both sides at the billed size: tests fail.
  • Ignore PriceAt: tests fail.
  • Count dry-run operations in the size: 1 test fails.
  • Drop the re-rate term: 5 tests fail.
  • Split the re-rate equally instead of by net saved tokens: 1 test fails.
  • Remove the zero-tier skip: 1 test fails.
  • Drop the output term: 1 test fails.
  • Do not subtract the effect Caused tokens from stay: 1 test fails.
  • Price the interaction at the billed size: 2 tests fail.

Compatibility

  • Pricer is unchanged.
  • A host without PriceAt gets the same figures as before.
  • A host with PriceAt sees the re-rate in saved.usd / added.usd (or interaction.usd) on a request that crosses a line.

Open questions

  • The size without the operations uses all counted operations together, not one operation alone.

Assisted-By: Claude (Anthropic AI) [email protected]

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 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.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 <= 0 clamp has no test. The clamp sends the saved side back to Price. Every other new path has a test. A one-line test would close the gap.
  • metrics/metrics.go:299 — price still calls the pricer for tiers with zero tokens. The cache-effect loop passes tiers(tt), which always holds all four tiers. book skips n <= 0; price does not. So PriceAt runs for tiers with no tokens, and an estimated return on such a tier marks the request. The same shape existed with Price before 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 splits net into pos and neg, 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.md and docs/metrics/metrics.md in 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. So base = 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) and interaction (:2315-2316) each move the same count between tiers. Excluding them from base is therefore right.
  • Proved spend operations add nothing to base. priced (compute.go:269) and c.price (:2184-2252) leave a spend's Saved and Caused at zero; the call usage is booked apart, at callSize, its own prompt size.
  • Checked Usage.CacheWrite holds the 1h part (internal/engine/types.go:85-92), so billed = Input + CacheRead + CacheWrite is correct and does not double-count.
  • Checked the guards: rate uses PriceAt only when the pricer has it and size > 0; a pricer without PriceAt gets Price on every path. sizes returns zeros for such a host.
  • Checked the interaction split: positive net tiers priced at base, negative at billed, 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 the metrics module (ok).
  • Checked the repo rules: the root module is untouched, so R3 and the accountant.go API rule hold; Compute did not change; the docs were updated in the same PR.

@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.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 sizes does not count it. The engine can refuse to price an operation that still changed the body (media_tokens, unknown_kind). Such an op has zero Saved/Caused, so base misses its tokens and can sit on the wrong side of the threshold. The doc (metrics.md, SizedPricer section) 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 <= 0 fallback has no test. The branch that sends the saved side to Price when the derived size is not credible is documented but untested. TestUnknownSizeUsesPlainPrice covers only the empty-Usage path. A one-line test would close the gap.
  • metrics/metrics.go:327 — base inherits the byte-ratio rounding. Check 6 tolerates about one token per span between the ratio figure and the host's tokens. base carries 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 − Σ caused over counted ops. This is the engine's own conservation identity (check 6, internal/engine/compute.go conservation): client body tokens − billed = Σ(saved − caused), within a one-token-per-span tolerance. So base is 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 zero Saved/Caused (engine price() fills only KindRewrite), so counting them in sizes changes nothing.
  • Cache effects and the interaction net zero tokens. Checked every effect constructor (addBreak, rescue, rescueTail, headTTL, split, premiums, mark payback): Saved and Caused hold the same count n in different tiers. So excluding them from sizes is right, and the two-sided rule (saved side at base, added side at billed) 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 are Result.Interaction (client-side writes) and take base; negative tiers are InteractionCaused (billed reads) and take billed. Consistent, and the USD sign and direction label keep their old meaning.
  • Fallbacks. A pricer without PriceAt gets Price on every path (sizes returns zeros, rate checks size > 0), so its calls and figures are unchanged — TestHostWithoutPriceAtSeesNoChange proves it. A spend call is priced at its own Call.Usage size, independent of the request-level sizes. An empty Usage sends both sides to Price.
  • Docs against code. metrics.md and the design.md paragraph describe the code as written (billed size formula, dry-run skip, the two sides, the spend rule, no new estimated mark). Compute is 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; metrics adds no import. No host names in Go files. The public API of the root package is untouched; SizedPricer is a new export of the metrics module and is documented.
  • Tests. Ran gofmt -l ., go vet ./..., go test ./... in both modules (root and metrics) 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]>
@amiddavid amiddavid changed the title feat(metrics): price savings by the prompt size of each side feat(metrics): price savings by the whole bill difference at each prompt size Nov 25, 2026
@amiddavid

Copy link
Copy Markdown
Collaborator Author

Replies to round 1, and an owner decision

Owner 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 1634fd92 does this:

  • The re-rate: for each tier, the tokens that stay × (the rate at the size without the operations − the rate at the billed size). The tokens that stay are the billed tokens of the tier minus the caused tokens.
  • The split: each operation gets a share in proportion to its net saved tokens, where that number is above 0. So the components add up to the request total.
  • A negative re-rate books to added.usd, because OTel counters reject negative values. With no saving operation, the re-rate books to interaction.usd.
  • A host without PriceAt gets the same figures as before.
  • Example, tested: 290K → 250K on a 272K line at 2x. The net is 290K × 2x − 250K × 1x.

Reviewer 1

  • An unpriced op moves the size: documented. The SizedPricer section now says this, and it no longer says "exact arithmetic".
  • No test for the base <= 0 fallback: fixed: TestBaseSizeNotCredibleFallsBackToPrice. The clamp itself is a redundant guard, because rate() already refuses a size of 0 or less. So no test can catch its removal. We keep it as a guard.
  • The byte-ratio rounding: documented, at about one token per span.

Reviewer 2

  • Only the moved tokens are priced: changed by the owner decision above. The sink now books the full bill difference.
  • No test for the base <= 0 clamp: same as reviewer 1's note.
  • PriceAt runs for tiers with no tokens: fixed. price now skips such a tier. TestEmptyTierDoesNotMarkEstimated covers it.
  • "The same Price calls": fixed. The doc now says "the same figures".

Open questions in the PR body:

  • The output tier is not re-rated, because Observation.Usage has no output tokens.
  • The size without the operations uses all counted operations together.

Tests (macOS, Go 1.27.4): gofmt -l . prints nothing. go vet ./... and go test ./... pass. Dropping the re-rate makes 5 tests fail. An equal split in place of the pro-rata split makes 1 test fail.

@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.332 offload-review skill, @amiddavid's session resumed 1 of 2 2 of 2 1634fd92af1e blocking

Verdict: blocking

Findings

  1. 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. Its Caused side sits in Observation.Usage at the forwarded tier. reRate subtracts only op.Caused when it computes stay, so the effect's tokens stay in stay at 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 (Saved at the client tier and base size, Caused at 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, not InBaseline, 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) sets Saved.CacheRead = n and Caused = write of the same n; rescue (:1698-1699), markPremium/ttlPremium (:1904-1910) and markPayback (: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 the Caused of the counted effects: skip e.InBaseline (the client body would have had that break too, so those tokens really do stay at one tier), then for t, n := range tiers(e.Caused) { billed[t] -= n }. Add a test like TestEffectsAndInteractionFollowTheSides with the effect's write inside Usage.CacheWrite, asserting the net equals the bill difference.

Non-blocking

  • docs/metrics/metrics.md:101 — the counter table row for interaction.usd is now incomplete. The row says the counter holds Result.Interaction minus InteractionCaused. Since 1634fd9 it can also hold an unattributed re-rate. The SizedPricer section 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". Read git diff ce8ed43..HEAD in full and the code around each change (metrics/metrics.go reRate, price, the Observe call 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, commit 1634fd9. 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 the base <= 0 fallback — fixed, TestBaseSizeNotCredibleFallsBackToPrice; the author's note that the clamp is a redundant guard is right (rate already 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 <= 0 clamp test — fixed. PriceAt on empty tiers — fixed, price skips n == 0, TestEmptyTierDoesNotMarkEstimated covers 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: InBaseline effects must stay in stay (the client body would have had that break too, so the tier does not change between the requests); the interaction tokens never enter Usage (the op removed the content), so they cannot pollute stay; op Caused and effect Caused are disjoint (the premiums identity, §4.4); the pro-rata split sums exactly to the re-rate; a negative part goes to added.usd because OTel counters reject negatives; a host without PriceAt never reaches reRate (sz.base stays 0).
  • The empty-tier skip (a64c04d): price now skips n == 0, keeps pricing n < 0 (the interaction's negative tiers need it). Figures unchanged for every host; only the estimated mark 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 the metrics module (ok).
  • Rules: the root module is untouched (R3, accountant.go API); Compute did not change; docs/design.md and docs/metrics/metrics.md were 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 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.332 offload-review skill, @amiddavid's session resumed 2 of 2 2 of 2 1634fd92af1e blocking

Verdict: blocking

Findings

  1. 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-caused per tier. The effect's caused tokens are billed tokens, so they land in stay. 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 form booked − 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).
  2. 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. InteractionCaused is "the same tokens at the read tier, as the operation books them" (design.md §6.2) — the operation books them as Saved, so the sink prices them at base. The interaction then subtracts them at billed. The two sides of the correction must use the same size, or the op-plus-interaction total is wrong by C × (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.

Non-blocking

  • metrics/metrics.go:341 — the re-rate fallback books one interaction.usd point 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 PriceAt varies 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:

  1. Moved tokens only, no re-rate of the tokens that stay — the owner chose to book the full difference, and commit 1634fd92 does it. The idea is right; the implementation is finding 1.
  2. No test for the base <= 0 clamp — fixed (TestBaseSizeNotCredibleFallsBackToPrice). The reply says the clamp is redundant because rate refuses a size of 0. Correct: rate checks size > 0, so no test can catch the clamp's removal. Accepted.
  3. PriceAt on zero-token tiers — fixed (price skips n == 0, TestEmptyTierDoesNotMarkEstimated covers it).
  4. "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.txt in 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: addBreak moves read→write, interaction writes 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 Caused keeps InBaseline breaks in stay, which is right (the client body would have had that break too). Pricing the interaction's negative tiers at base changes 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 to interaction.usd; the re-rate runs only for a host with PriceAt (sz.base > 0 needs sizes, which needs a sized pricer); spend calls stay out of stay (their usage is in Call.Usage, not Observation.Usage).
  • Ran, in this worktree: gofmt -l . (nothing), go vet ./... (clean), go test ./... (ok) for the root module and the metrics module. 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; Compute did 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]>
@amiddavid

Copy link
Copy Markdown
Collaborator Author

Replies to round 2 (both reviewers blocked)

The owner also decided that output tokens are re-rated. Commit 95a8a5b1 adds the optional Observation.Output. Output never counts toward the prompt size. A host that leaves it at 0 gets no output re-rate.

Finding 1, both reviewers: the re-rate counts cache-effect tokens twice. Fixed in 2b395309.

  • reRate now subtracts the Caused tokens of each cache effect that is not InBaseline from stay, per tier.
  • An InBaseline effect stays in stay, because the client body has it too.
  • New test: TestEffectAndInteractionAddUpToTheBillDifference, built from reviewer 2's case. It uses its own stated per-tier rates (input 3e-6, read 3e-7, write5m 3.75e-6, 2x above 272K). The booked total equals the client bill minus the sent bill (0.5895). The test computes that figure from the rates; it does not hard-code it.
  • A mutation that drops the subtraction makes it fail.

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". TestEffectsAndInteractionFollowTheSides expects 600 × 2e-6. A mutation that prices at the billed size makes both tests fail.

Reviewer 2's non-blocking notes: all fixed.

  • The no-saving-op fallback books one interaction.usd point, with the sign of the total.
  • The re-rate-is-0 sentence now applies to a threshold pricer only.
  • The examples say that they assume no cache effect.

Tests (macOS, Go 1.27.4): gofmt -l . prints nothing. go vet ./... and go test ./... pass.

The owner granted round 3.

@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.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. callTiers prices a call's output at the call's prompt size, and the re-rate covers only the request's own Observation.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". Read git diff 1634fd9..2b39530 in full and the changed files around each change (reRate, the interaction block in Observe, 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, commit 2b39530.
  • My round-2 finding 1 (effect Caused double-counted in stay): fixed. reRate now subtracts the Caused of every non-InBaseline effect, per tier, which is the fix I proposed. InBaseline effects stay in stay — 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: Interaction is the client body's cold write, InteractionCaused is the read the op books as Saved at the base size. The whole net now prices at sz.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.usd point 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.usd counter-table row now names the unowned re-rate — fixed. The missing effect-plus-line test — added (TestEffectAndInteractionAddUpToTheBillDifference).
  • The output re-rate (95a8a5b). Observation.Output is a new optional field; 0 means the host gives nothing and nothing changes. I checked: tiers() has no output key, so op and effect Caused can never touch the output stay; sizes and callSize use input, cache read and cache write only, so output never moves the prompt size (TestOutputDoesNotCountTowardPromptSize proves it at the line); the re-rate gate (money && sz.base > 0) still keeps a host without PriceAt and an empty Usage out. Hand-checked TestOutputIsReRated: 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.md and design.md describe the code as written: the stay formula with the effect subtraction, the interaction at one size, the one-point fallback, the output rules. The counter table matches. Compute is unchanged, so no spec change is due. The root module is untouched (R3, accountant.go API); metrics adds 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 the metrics module (ok). All 9 re-rate and output tests pass, read against 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 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

  1. The re-rate counted cache-effect tokens twice (mine and reviewer 1's, same finding). Fixed. reRate now subtracts the Caused of every non-InBaseline effect from stay, per tier (metrics/metrics.go:336-342). InBaseline effects stay in stay, which is right: the client body would have had that break too. The new test TestEffectAndInteractionAddUpToTheBillDifference is my round-2 case with per-tier rates; I recomputed its figures by hand (booked 0.5895 = client bill − sent bill) and they hold.
  2. 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". Read git diff 1634fd9..HEAD in full, and metrics/metrics.go, metrics/observer.go, metrics/sized_test.go and 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.txt in 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, commit 2b395309, 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-caused and 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, so Observation.Output re-rates alone and closes its own term.
  • The output re-rate (95a8a5b1). Output never enters sizes(), so it never moves the prompt size (TestOutputDoesNotCountTowardPromptSize covers the boundary). A host without PriceAt never reaches reRate; a host that leaves Output at 0 gets no output term. A negative Output gives stay <= 0 and 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.md and metrics.md now describe stay with the effect subtraction, the interaction at one size, the output tier, the one-point fallback, and the threshold-pricer caveat. The counter table row for interaction.usd names 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 the metrics module.
  • Repo rules: the root module is untouched (R3, accountant.go API); Compute did not change; Observation.Output is a new field of the metrics module only, with a doc comment; the docs were updated in the same commits.

@amiddavid
amiddavid merged commit 05cd0f8 into main Nov 25, 2026
3 checks passed
amiddavid added a commit to rossoctl/context-guru that referenced this pull request Nov 25, 2026
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]>
boazdavid added a commit to rossoctl/cortex that referenced this pull request Nov 26, 2026
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(metrics): price savings by the prompt size of each side

1 participant