Skip to content

feat(pricing): price each known request at the tier of its prompt size - #1407

Merged
amiddavid merged 7 commits into
mainfrom
feat/price-tiers-callers
Nov 25, 2026
Merged

amiddavid merged 7 commits into
mainfrom
feat/price-tiers-callers

Conversation

@amiddavid

@amiddavid amiddavid commented Nov 25, 2026 •

Copy link
Copy Markdown
Collaborator

Behavior change (the owner decides before merge)

  • Who it affects: users of OpenAI GPT-5.4 and later with requests over 272K prompt tokens. Users of Claude Haiku 5.5 with prompts over 100K tokens.
  • Old: cost_usd, the savings figures and the keep-alive per-ping dollar guard price every request at the flat base rate.
  • New: they use the tier rate of the request's prompt size. Long requests show 2x cost (OpenAI: 2x input, 2x cache read and write, 1.5x output) or 5x cost (Haiku 5.5). The per-ping guard (MaxUSDPerPing) now refuses some pings in long sessions above the line, which it let through before. Savings now include the tier re-rate: a saving is the bill without context-guru minus the bill as sent, each at its own prompt size, so when a request crosses a line the tokens that stay and all output change rate too. Example: gpt-5.6, a trim takes 290K to 250K, saving = 290K x 2x - 250K x 1x on input, plus the output re-rate. Savings change in both directions, and a component can show a saving below 0. Owner decision: David Amid, 2026-11-25.
  • How to turn it off: flat: true on a price-file entry. There is no global switch. I added none (see Open questions).

Data dependence: metadata only (token counts, model id, price table). No change to docs/data-dependence.md is needed: the Accountant row and the Dashboard database row already say these figures need counts and prices only.

Refs #1343. Local tests: waived (owner rule)

Summary

  • Step 1 (feat(modelinfo): add prompt-size price tiers (no caller yet) #1343) added Price.At and PromptTokens. Nothing called them.
  • This PR makes every caller that prices a KNOWN request use p.At(PromptTokens(fresh, cacheRead, cacheWrite)).
  • A caller with no request size keeps the base price.
  • A lookup error or a zero price behaves as before (fail open).

What changed

Call site Decision
proxy/keepalive.go dispatcher price adapter Tier. Passes promptTokens through: model price, then .At(promptTokens). Fixes projectedPingUSD vs MaxUSDPerPing, the summary, sweep and refresh projections.
keepalive/keeper.go pingCost, substitute.go substitute cost and sweepAnswerUSD Tier, at the size the usage billed (billedPrompt); the planned prefix when usage has no input. A projected ping (projectedPingUSD, summary, sweep) is priced at prefix + DefaultPingInputTokens (pingPrompt), so a prefix of exactly 272,000 prices at the tier.
dash/event.go priceCost (cost_usd, cache-saved, fallback cost; also Event.Price, PriceMode, the reprice pass, the ping row) Tier, at the event's own prompt size.
dash/accountant_price.go AccountantFigure, heldFloorUSD Tier, per side, plus the re-rate. Saved tokens at the size without context-guru (with size + saved - caused of the counted ops). Caused tokens at the size with it. Per tier, the tokens that stay (billed minus caused) re-rate by stay x (rate without - rate billed). All output re-rates by output x (rate without - rate billed). The re-rate is split over the counted components in proportion to each one's net saved tokens (saved - caused, only above 0), so rows add up to the total. With no such component it books to EndedBreakUSD (the ended_change row): it is counted, owned by no component, and keeps the rows equal to DeltaUSD. It is a request-level re-rate, not an ended break, so the row name is approximate: docs/dashboard.md defines ended_change as the break a change left, and in this case the figure is the re-rate (no tokens). No new figure was added. It books in the first-removal column. No tokens move, so no token figure changes. A negative re-rate uses the same split. No line crossed, no tiers or an unknown size: the figures of before. Same rule as accountant#112 (which re-rates input tiers only).
tooldefer ledger (Book, Price) Tier, per side. Gross at the size without the deferral, cost at the size sent. Response gains FreshInput. Unknown size: base.
campaign.Rows, autoPrice, adaptcache Tier. The row's stake is priced at the row's prompt size. A replayed ping is priced at its own size: CachedContext plus kvcache.DefaultPingInputTokens. The price callback gains a promptTokens argument.
dash.NextRequestUSD (cache state, manual ping) Tier, at the prefix + DefaultPingInputTokens.
dash/keepalive.go live view and calculator, proxy/keepalivectl.go Tier, at the prefix + DefaultPingInputTokens.
proxy/inferencemetrics.go miss cost Tier, at the event's prompt size.
Event.PriceCG (compaction calls) Base. It holds the sum of several calls. No size per call.
proxy selfRates / ratesFor (lifecycle/rates.go), proxy/predictive.go, proxy/campaignbuild.go price map, cheapmodel Base. An estimate before a request exists, or a per-model rate card.
dash/readvalue.go (tier cost split, legacy estimators), sweepattr, summarizeattr/replaycap legacy rows, cachehistory, adaptcompaction, adapttools, toolapi, spendexplain, fivehourfit Base. These sum tokens by model in SQL. No per-request size is in the query. Legacy rows predate the accountant, and no tiered model has them.
dash/toolsuggest.go Base. The query has cache_read, cache_write and cache_write_1h per row, but the query does not select fresh_input. Not done here (see Technical notes).
proxy/metricsink.go (accountant metrics module) Base. The module's Pricer has no prompt-size argument. See Open questions.
docs/dashboard.md Replaced "every request is priced at base rates" with the tier rule and the list of base-rate totals. docs/reference already documents flat: true (step 1). No other "flat rate" text found in docs/how-to or docs/reference.

How it was tested

macOS, Go 1.27.4. No whole-package -race run (interim rule).

  • go build ./... and go vet ./...: clean.
  • go test (no race): ./dash, ./proxy, ./proxyapp, ./keepalive, ./tooldefer, ./campaign, ./internal/modelinfo/..., ./dispatch/...: all pass. TestNoHooksKeepsTheBinaryDefaults passed here too.
  • go test -race -run <new tests> on ./keepalive ./tooldefer ./dash ./proxy: pass.
  • New tests, with gpt-5.6 (line 272,000) and Haiku 5.5 (line 100,000): at the line prices at base, one token above prices at the tier. Cases: event cost; dispatcher adapter; per-ping guard (a 270K ping fits a 0.14 limit, a 280K ping does not); ping cost by billed size; saved side above the line while the sent side is below; caused side; both sides on one side; unknown size; tool deferral gross and cost; campaign row price; NextRequestUSD.
  • Round 1 added tests: ping at a prefix of exactly 272,000, replay ping size, heldFloorUSD per-side price, missCostUSD tier, ledger round-up. Each has a mutation that fails it.
  • Savings re-rate tests: 290K to 250K with 2,000 output (gpt-5.6), two-component split adding up, negative re-rate taking a component below 0, no line crossed, no tiers. Mutations: re-rate term dropped, equal split, output term dropped: each fails tests.
  • Mutations (each made a new test fail, then I restored it): adapter .At(promptTokens) to base; event .At removed; accountant with=At(w), without=At(w); accountant At(n), At(n); tool deferral cost .At(0); ping cost by prefix instead of usage; campaign .At(0); NextRequestUSD .At removed.

Open questions

  1. Accountant metrics module. github.com/rossoctl/accountant/metrics prices its savings counters through Price(model, time, tier), with no prompt size. This repo's glue cannot give it one. The cg_* savings counters stay at base rates. To fix it, that module needs a promptTokens argument (or a per-side price function). I did not touch that repo.
  2. Accountant library (v0.7.0). No change was needed. The library returns token counts by tier. All pricing is in dash/accountant_price.go.
  3. Global off switch. None exists. flat: true is per entry. Do you want one? I did not add one.
  4. The size without context-guru is derived: billed size + saved - caused tokens of the counted operations. It is an estimate when the library marks the figure estimated.

Technical notes

  • Why accPrices is in dash: the whole AccountantFigure domain lives there. Moving it out is a wider refactor. Proposed as a follow-up.

  • Re-rate and cache effects. The tokens that stay exclude the Caused tokens of each cache effect that is booked (a break the client body has too, an unowned break and an unknown kind are not booked, so their tokens stay). Without this a booked effect would be re-rated twice. The interaction is not priced in dash (Result.Interaction is ignored on purpose), so the interaction-size bug of accountant#112 does not apply here.

  • The tool deferral size without the deferral is rounded up (math.Ceil), so a fractional billed size cannot fall below a tier line.

  • Cache effects, the mark included, only move tokens between tiers. The marker's own bytes are a rewrite op (apply/ops.go tailOp) that the library prices as Caused, and accPrices subtracts them. The size without is exact for the marker.

  • dash/toolsuggest.go is not done here. The requests table has fresh_input (dash/cachestate.go:422), so adding the column to the query would give the exact size. This is a follow-up.

  • The summary and sweep projections pick the tier at prefix + 1. The real call is larger (instruction or question text), so near a line the guard can project one tier low. The recorded cost uses real usage. This is the same estimate class as summaryOutputBudgetGuess.

  • pingPrompt adds kvcache.DefaultPingInputTokens (1), while predictive pingFresh is 7. One shared constant is a follow-up.

  • Event.accPrices(p) returns the with and without prices. With no billed usage, no tiers or no accountant result, both are p.At(0), the base price, so the old results stay unchanged.

  • modelinfo.Price is passed with its Tiers into PriceMode and AccountantFigure. Callers need no change.

  • keepalive.billedPrompt(u, prefix) prefers the billed usage size and falls back to the planned prefix.

  • The keepalive test fake proxyPricer now applies .At, as the real adapter does.

Step 2 of prompt-size price tiers (refs #1343). Callers that price a
request with a known prompt size now use Price.At(PromptTokens(...)).

- dispatcher price adapter passes promptTokens through (keep-alive
  per-ping guard, summary and sweep projections)
- Event cost_usd, keep-alive ping and substitute cost
- accountant savings: removed tokens at the size without context-guru,
  added tokens at the size with it
- tool deferral ledger, campaign replay, cache state, keep-alive views,
  miss cost metric
- docs/dashboard.md describes the tier rule

Behavior change: long requests of GPT-5.4+ (over 272K) and Haiku 5.5
(over 100K) now show 2x or 5x cost. flat: true turns it off per entry.

Assisted-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: DAVID AMID <[email protected]>
@amiddavid amiddavid added the openai OpenAI / Codex traffic and pricing label Nov 25, 2026

@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 9f5eea7073e8 approve

Verdict: approve

Findings

None. I could not prove a wrong behavior, a data loss, or a broken fail-open path.

Non-blocking

  • Ping projections price the prefix alone, not the prompt the ping sends. A ping carries 1 fresh input token beyond the prefix (kvcache.DefaultPingInputTokens). So a prefix exactly at a tier line (272,000 for GPT-5.4+, 100,000 for Haiku 5.5) bills one tier up, while projectedPingUSD, dash/keepalive.go (live view, calculator) and NextRequestUSD price it at base. The window is one token wide, and recorded costs (billedPrompt, priceCost) use the real usage, so only the guard and the views can under-price at that exact size. Same shape in tooldefer/ledger.go:144: int64(billed(...)) truncates the without-size by a fraction of a token.
  • The cg_* savings counters and PriceCG stay at base rates. The dashboard's savings and the metrics module's counters can now disagree for a tiered model. The PR names both in Open questions 1, so this is tracked, not missed.
  • accPrices's size without context-guru is an estimate (billed size + saved − caused of the counted ops). The PR says so in Open question 4. The estimate only picks a rate tier, so a small size error changes nothing unless it crosses a line.
  • The replay prices a row's pings at the row's own prompt size (campaign/replay.go:188). A replayed ping reads CachedContext, which can sit below the line while the row's prompt sits above. The replay engine is calibrated in its own units, so I rate this an approximation, not a defect.

What I checked

  • The full diff b8f4d92b..HEAD, and the code around every hunk: dash/accountant_price.go, dash/event.go, dash/cachestate.go, dash/keepalive.go, keepalive/keeper.go, keepalive/substitute.go, proxy/keepalive.go, proxy/keepalivectl.go, proxy/campaignauto.go, proxy/adaptcache.go, proxy/inferencemetrics.go, proxy/tooldefer.go, tooldefer/flow.go, tooldefer/ledger.go, campaign/replay.go.
  • The base commit's modelinfo rules this PR builds on: Price.At, PromptTokens, WithTiers, BuiltinTier, tierRate, and the order Resolved before WithTiers at every price source (table.go:345, litellm.go:223). Every Pricer returns resolved, tiered rates, so At always multiplies filled base rates.
  • The per-side pricing in AccountantFigure and heldFloorUSD: Saved tokens at the size without, Caused at the size with; cache effects priced per side instead of on Net() (needed, because the two sides can carry different rates); spend and DryRun ops excluded from both the dollars and the without-size; nil accRes, missing usage and flat prices all fall back to base, exactly as before.
  • That flat-priced models keep their old numbers: At on a price with no tiers returns the same rates; accPrices returns base for both sides when !p.HasTiers(). So the behavior change touches only tiered models, as the PR claims.
  • Every k.price call site in keepalive (projected ping, summary, sweep, refresh, pingCost, substitute, sweepAnswerUSD): each passes either the billed usage size or the planned prefix. Fail-open paths (no model, no rate, zero price) unchanged.
  • The dispatcher adapter contract (dispatch/dispatch.go:90) and the test fake now matching it; no other host in this repo sets dispatch.price.
  • priceCost's local p = p.At(...): the caller's p is untouched, so PriceMode → accOverride → heldFloorUSD still receive the tiered price; CacheReadFallback and Unit survive At.
  • tooldefer.Price: gross at the size without the deferral (prompt + deferred − list, tokenizer factor applied), cost and search at the size sent; unknown size prices both sides at base.
  • The new tests' arithmetic, line by line (272,000 at the line is base, 272,001 is 2x/1.5x; Haiku 100,000/100,001 at 5x; both sides of a saving; unknown size). Test helpers (accNear, testKeeper, setPrices, fixedPrice, pingOutputBudget, SetAccountant) all exist with matching signatures.
  • The PR body: the behavior change is named at the top (who, old, new, how to turn it off), data dependence is stated as metadata only, and every call site I found in the sweep of dash/proxy pricing paths appears in its decision table (including the ones left at base: readvalue, cachehistory, insightsapi/ToolReportFor, metricsink, PriceCG).
  • Commit message: DCO sign-off and Assisted-By present.

@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 9f5eea7073e8 approve

Verdict: approve

Findings

None. I found no wrong behavior, no data loss, no broken fail-open path and no security problem.

Non-blocking

  • keepalive/fake_test.go:158 — stale comment. The proxyPricer comment still says the adapter ignores "the endpoint and the prompt size". The new Price applies the prompt size. Fix the comment to say "the endpoint" only.
  • dash/accountant_price.go:22-24 — the comment overstates one case. It says a cache effect "only moves tokens between tiers, so it does not change the size". A mark effect (markPremium) adds the host's mark tokens to the request sent. Those tokens are in the billed size w but not in the client size n, so n over-counts the client size by the mark's tokens. The effect is a few dozen tokens and the direction is conservative (the client size reads larger, its tier can only rise). No fix needed; say "except the mark" in the comment.
  • dash/toolsuggest.go:230 — decl-filter savings stay at base rates. The query has each row's cache_read, cache_write and cache_write_1h; only fresh_input is missing. The PR body's reason ("no per-request size is in the query") is partly wrong: a partial size is there. On a tiered model this figure under-states by up to 5x. Documented as a base-rate figure in the PR table, so this is a note, not a defect.
  • Two new tiered paths have no test. heldFloorUSD's per-side price (dash/accountant_price.go:522) and missCostUSD's tier (proxy/inferencemetrics.go:262) are new behavior. The PR's own mutation list covers neither. Low risk: both reuse accPrices / At, which are tested.
  • Host-package placement. accPrices is savings math and lives in dash, a host package. CLAUDE.md says cost and savings math is business logic and a PR that adds logic to a host package states why it cannot live in a library package. The PR table does not say. I accept it because the whole AccountantFigure domain already lives there and the function reads Event fields plus accountant.Result; moving it is a wider refactor than this PR.
  • Process, not code. The behavior change is named at the top of the PR and says "the owner decides before merge". Do not merge before the owner's yes on the MaxUSDPerPing refusal above the line.

What I checked

  • Read the full diff (git diff b8f4d92b..HEAD), one commit, and the code around every hunk: dash/accountant_price.go, dash/event.go, dash/cachestate.go, dash/keepalive.go, keepalive/keeper.go, keepalive/substitute.go, tooldefer/flow.go, tooldefer/ledger.go, proxy/keepalive.go, proxy/keepalivectl.go, proxy/campaignauto.go, proxy/adaptcache.go, proxy/inferencemetrics.go, proxy/tooldefer.go, campaign/replay.go.
  • Read the base machinery from #1343: internal/modelinfo/pricetier.go (At, PromptTokens, WithTiers, built-in tiers), modelinfo.go (Resolved, Cost, CacheWrite1h), table.go and litellm.go (both resolve a price before WithTiers, so At sees stated rates).
  • Traced each side of the savings model. accPrices builds the client size as billed size plus Saved minus Caused of the counted ops. Cache effects keep the size (a break, rescue, split or TTL move moves tokens between tiers; only the mark adds size — noted above). Saved prices at the client tier, Caused at the sent tier. This matches the whole-request tier rule the providers state, and BaselineCostUSD = CostUSD + DeltaUSD holds by construction.
  • Checked priceCost: the reassignment p = p.At(...) is local to the function; PriceMode still passes the tiered price to accOverride, which re-derives per side. CacheReadFallback survives At, so FallbackRateCostUSD stays consistent.
  • Checked loop scoping in dash/keepalive.go: both p = p.At(...) sites use a fresh per-row or per-call variable, so no row prices at another row's tier. KeepAliveCalc reassigns after its last use of the base price.
  • Checked the keeper: billedPrompt prefers the billed usage and falls back to the planned prefix. The projected guards (projectedPingUSD, summary, sweep, refresh) use the prefix, which is the ping's prompt size. Projection and actual cost now use the same tier, so the MaxUSDPerPing guard is consistent before and after the ping.
  • Checked the tooldefer ledger: gross at the client size (sent size plus deferred minus list, both scaled by the billed factor), cost at the sent size, unknown size at base. The one production caller (proxy/tooldefer.go:413) passes FreshInput; proxy.Usage has the field.
  • Checked the signature change of the price callback (func(string, int64)): all production callers updated (campaign.Rows, rowsWith, autoRowsFor, adaptReport, tests). The dispatcher adapter in proxy/keepalive.go is the only setter of dispatch.price; no other host implements it.
  • Checked the left-at-base callers the PR names (PriceCG, lifecycle rates, read-time legacy passes, metrics module, toolsuggest): they read base fields of a tiered price, which is the unchanged behavior, and the docs list them.
  • Checked the docs against the code: tier lines (272,000 at 2x/1.5x; 100,000 at 5x), flat: true, the feed winning over built-in tiers, and the base-rate totals list all match pricetier.go, table.go and the call sites.
  • Checked the new tests' arithmetic by hand (at the line is base, one token above is the tier, per-side pricing, unknown size, NextRequestUSD); the expected values match At's strict > comparison. Test helpers (accNear, near, testKeeper, SetAccountant, pingOutputBudget) exist, and no package gets a duplicate helper name.
  • Did not run builds or tests: live tests are not approved for this review.

Review round 1 of #1407.

- price a projected ping and the replay ping at prefix + ping input
- round the tool deferral size without the deferral up
- test heldFloorUSD, missCostUSD and the replay ping
- fix two comments

Assisted-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: DAVID AMID <[email protected]>
@amiddavid

Copy link
Copy Markdown
Collaborator Author

Replies to round 1 (both reviewers)

Both reviewers approved. Commit b13e6832 fixes these notes.

Reviewer 2

  • The ping projection prices the prefix alone. Fixed. A projected ping now prices at the prefix plus kvcache.DefaultPingInputTokens, through the new pingPrompt. The fix covers projectedPingUSD, the summary and sweep projections, the dash/keepalive.go live view and calculator, keepalivectl and NextRequestUSD. A new test checks that a prefix of exactly 272,000 tokens on gpt-5.6 projects at the tier rate.
  • The ledger loses part of a token (tooldefer/ledger.go:144). Fixed. The size without the deferral rounds up (math.Ceil), and a comment says why. A new Haiku test crosses from 99,999 to 100,001 tokens.
  • The replay prices pings at the row's size (campaign/replay.go:188). Fixed. A replayed ping prices at CachedContext plus the ping input. The row's stake still prices at the row's size. The test is in campaign/pricetier_test.go.
  • The cg_* counters and PriceCG stay at base rates, and the size without Context Guru is an estimate. Unchanged. Both are open questions for the owner.

Reviewer 1

  • The proxyPricer comment is stale (keepalive/fake_test.go:158). Fixed. It now says the pricer ignores "the endpoint" only.
  • The accPrices comment (dash/accountant_price.go:22-24). Fixed. It now names the markPremium exception and says the direction is conservative.
  • toolsuggest.go:230 stays at base rates. Kept. I corrected the PR table: the query has no fresh_input, so a partial size cannot pick a tier safely.
  • heldFloorUSD and missCostUSD have no test. Fixed: TestHeldFloorUsesTheSavedSidePrice and TestMissCostUsesTheTierOfThePrompt.
  • The placement in dash has no reason. Fixed. The Technical notes now give the reason and propose a move as a follow-up.

Not changed: the refresh-saving projection still prices the bare prefix. It is the rewrite that a ping saves, and that rewrite has the prefix's size.

Tests (macOS, Go 1.27.4):

  • go build ./... and go vet ./... are clean.
  • Plain go test passes on ./dash ./proxy ./proxyapp ./keepalive ./tooldefer ./campaign.
  • -race with -run on the new and changed tests passes.
  • Each of 5 new mutations made a test fail: base price in heldFloorUSD, no .At in missCostUSD, a bare prefix in projectedPingUSD, CachedContext alone in the replay, and Floor in place of Ceil.

@amiddavid

Copy link
Copy Markdown
Collaborator Author

Owner decisions (David Amid, 2026-11-25)

  • The cg_* savings counters stay at base rates in this PR. The fix goes into the accountant library, as feat(metrics): price savings by the prompt size of each side accountant#111. A later context-guru PR uses it.
  • A global off switch: no. flat: true on a price-file entry stays the only way to turn the tiers off.
  • The estimated size without context-guru: accepted for the savings figures.
  • The behavior change: the owner gives the merge yes at hand-off.

@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 b13e68329213 approve

Verdict: approve

Findings

None. The new commit fixes the round-1 notes correctly, and I found no new wrong behavior.

Round-1 findings: status

Mine (all were non-blocking):

  1. Ping projections priced the prefix alone. Fixed. pingPrompt (keeper.go:2082) adds kvcache.DefaultPingInputTokens; projectedPingUSD, projectedSummaryUSD, projectedSweepBatchesUSD, the dash/keepalive.go live view and calculator, keepalivectl and NextRequestUSD all use it. New boundary tests check a prefix of exactly 272,000 (keepalive, NextRequestUSD).
  2. The ledger truncated the without-size. Fixed. math.Ceil on the net (ledger.go:147); a negative net rounds to 0, still the dearer side. The Haiku test crosses 99,999 → 100,001; BilledDeltaFactor for the haiku family is 1.3686 (billedfactor.go:63), so ceil(1.3686) = 2 holds.
  3. The replay priced pings at the row's size. Fixed. A second lookup at CachedContext + 1 (replay.go:193), after the row filter, with a fallback to the row's rates when the lookup fails. The test's arithmetic matches PingCost = prefix*PRead + 7*PIn + 1*POut (pingFresh = 7, predictive/features.go:24).
  4. cg_* counters, PriceCG, the estimated without-size. Unchanged, kept as the owner's open questions 1 and 4. Accepted.

Reviewer 1's (all were non-blocking; I checked each myself):

  1. Stale proxyPricer comment. Fixed; it now names the endpoint only.
  2. accPrices comment and the mark effect. Fixed as asked: the comment names the markPremium exception. See Non-blocking for the direction claim.
  3. toolsuggest stays at base. Kept, with the PR table corrected. I verified: declFilterSavingsQuery (toolsuggest.go:218) selects cache_read, cache_write, cache_write_1h but no fresh_input. Without fresh input the size is understated, so a tier picked from it could read too cheap. Base is the safe choice. Accept.
  4. No test for heldFloorUSD and missCostUSD. Fixed. TestHeldFloorUsesTheSavedSidePrice: ceiling 50,000 at 10e-6, floor 50,000 at the 2x read rate 1e-6 — matches heldFloorUSD with pb from accPrices. TestMissCostUsesTheTierOfThePrompt: 300,000 above the line at (10e-6 − 1e-6), 272,000 at the line at (5e-6 − 0.5e-6) — matches At's strict >.
  5. accPrices lives in dash. The Technical notes now state the reason (the AccountantFigure domain lives there) and propose a move as a follow-up. Accept, as I did in round 1.
  6. The owner's yes before merge. Still stands. The behavior-change block at the top of the PR is unchanged in substance.

The author's one rejection-with-reason: expectedRefreshSavingUSD still prices the bare prefix (keeper.go:1323). The reason is right: the figure prices the rewrite a ping saves, that rewrite has at least the prefix's size, and the function is a deliberate lower bound (issue #415), so a cheaper tier can only under-state a saving. Accept.

Non-blocking

  • The summary and sweep projections price the tier at prefix + 1, but the real call's prompt is larger. A substitute summary is built from the forwarded body and carries the summarizer's own instruction; a sweep question carries its question text. When prefix + 1 sits below a line and the real prompt crosses it, the guard under-projects by the tier multiple on the read dollars. This is the same estimate class as the 2000-token output guess (summaryOutputBudgetGuess, "unmeasured"), the window is the instruction's size, and the recorded cost uses the real usage. Not a defect; worth a line in the PR's Technical notes if the author wants it exact.
  • The new accPrices comment asserts a direction I could not prove. It says the without-size "errs low" and so is conservative; reviewer 1's round-1 derivation said the opposite (n over-counts by the mark's tokens). From this repo alone I cannot settle which holds — it depends on the accountant library's mark-effect semantics. No code depends on the claim: the size adjustment is the same either way, and the error is a few dozen tokens at a tier line. Suggest the author cites the accountant semantics for the direction, or restores the old "moves tokens between tiers" wording, in a later docs pass.

What I checked

  • Last review: round 1, 9f5eea7, 2026-11-25T14:19:49Z.
  • New commits read: 1 — b13e6832 "fix(pricing): price a ping at its own size, round up, test more sites".
  • Read in full: 2 reviews, 1 issue comment, 0 inline comments (from the three saved files), plus the current PR body (the author edited it; body edits appear in no comment list).
  • New items since my last review, and what I did: reviewer 1's round-1 review (checked each of its six notes against the code myself); the author's reply comment (verified every fixed/kept claim against the diff); the new commit (full diff plus the code around each hunk); the PR body edits (the corrected toolsuggest row and the new Technical notes).
  • The new commit's code: pingPrompt and its three call sites; the +DefaultPingInputTokens tier shift in dash/cachestate.go, both dash/keepalive.go sites and proxy/keepalivectl.go (rate selection only — the dollar formulas still price the prefix and one output token, the pre-PR shape); the replay's second price lookup (placed after the row filter, so dropped rows cost no extra lookup; the pingOK fallback is dead in practice but harmless); math.Ceil on the deferral without-size.
  • The new tests' arithmetic by hand: the replay ping (272,001 above the line, 272,000*2 + 7*2 + 2), the held floor, the miss cost, the Haiku round-up (factor 1.3686, ceil gives 100,001), and the two updated boundary tests (271,999 base, 272,000 tier). Constants verified at their sources: pingFresh = 7, DefaultPingInputTokens = 1, BilledDeltaFactor(haiku) = 1.3686.
  • That nothing else moved: git diff 9f5eea70..HEAD touches only the files listed above; AccountantFigure, accPrices logic, priceCost, the dispatcher adapter and the tooldefer cost side are unchanged from the head I approved in round 1.
  • Commit message: DCO sign-off and Assisted-By present. Tests were not run: live tests are not approved for this review; the author reports them green with five new mutations.

@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 b13e68329213 approve

Verdict: approve

Findings

None. The fixes behave as the reply claims. I verified each one by hand. My round-1 note that started the accPrices comment change was itself wrong; see Non-blocking 1.

Non-blocking

  1. dash/accountant_price.go:23-26 — the new comment states a direction that does not follow, and the PR Technical note repeats it. The comment says the mark effect's tokens are "already in the billed size" and that "not counting them leaves the size without a little low, so the without side is never priced dearer than it should be". Two facts contradict it:
    • markPremium moves the tail content between tiers: our request writes it, the client's request bills it as input. The same content is in both bodies. The size does not change. The round-1 wording ("a cache effect only moves tokens between tiers") was right for the mark too.
    • The marker's own bytes (the only real asymmetry) are counted: apply/ops.go tailOp reports the tail mark as a rewrite of the last message (SizeAfter > SizeBefore), the library prices that growth as the op's Caused, and accPrices subtracts every counted op's Caused from the size without. So the size without is exact for the marker.
      My round-1 note claimed the marker bytes were never subtracted. That was wrong, and the new comment inherits the error with the direction flipped. Fix: drop the exception and restore "a cache effect only moves tokens between tiers, so it does not change the size". Also fix the PR Technical note ("the size without errs low. That is the conservative direction"). Comment only; the code is unchanged and right.
  2. keepalive/keeper.go:2083 — pingPrompt adds 1 token; the measured law is about 7. kvcache.DefaultPingInputTokens is 1, but predictive pingFresh is 7 ("the measured law of a keep-alive's own cost"), and a ping resends the caller's body, so the real fresh input is the last turn's, not 1. The tier picked for a projection can sit one tier low when the true prompt crosses a line. The projections already omit the fresh-input cost altogether (pre-existing), so this is second-order. The new campaign test shows both constants side by side (+1 for the tier, 7 in PingCost). Consider one constant for the ping's own input.
  3. dash/toolsuggest.go — the corrected PR reason overstates. The table now says the query has no fresh_input, so "a partial size cannot pick a tier safely". The requests table has fresh_input (dash/cachestate.go:422 reads it); adding one column to the query would give the exact size. Keeping the figure at base rates is a fair scope decision, but the reason should say "not done here", not "cannot".

What I checked

  • Last review: round 1, 9f5eea7073e8, 2026-11-25T14:23:39Z.
  • New commits read: 1 — b13e6832 "fix(pricing): price a ping at its own size, round up, test more sites".
  • Read in full: 2 reviews, 1 comment, 0 inline comments (the inline file is empty), from the three saved files.
  • New items since my last review: reviewer 2's round-1 review (4 notes, all dispositioned below), the author's reply comment, commit b13e6832 (full diff plus the code around each hunk).

Earlier findings, disposition:

  • Mine 1, stale proxyPricer comment. Fixed: "the endpoint" only.
  • Mine 2, accPrices comment. Rewritten, but the new direction claim is wrong. See Non-blocking 1. My round-1 note was the error's source.
  • Mine 3, toolsuggest at base rates. Rejected with a reason. The reason overstates ("cannot"); the figure's staying at base is acceptable. See Non-blocking 3.
  • Mine 4, no tests for heldFloorUSD and missCostUSD. Fixed. I checked both tests' arithmetic: the floor re-prices 50,000 saved input at the dear tier's read rate (10e-6 → 1e-6); the miss cost prices 300,000 written tokens at the 2x write-read premium and 272,000 at the base premium.
  • Mine 5, placement of accPrices in dash. Addressed: the PR Technical notes now give the reason and propose a move as a follow-up.
  • Mine 6, the owner's yes. Still pending. The PR's behavior-change block still says "the owner decides before merge". Do not merge before it.
  • Reviewer 2, ping projections at the bare prefix. Agree, and fixed: pingPrompt (prefix + ping input) now feeds projectedPingUSD, projectedSummaryUSD, projectedSweepBatchesUSD; NextRequestUSD, the dash live view and calculator, and keepalivectl add the same token. I checked every k.price and p.At call site again; only expectedRefreshSavingUSD keeps the bare prefix, and the author's reason holds (the rewrite it prices has at least the prefix's size; under-stating the saving makes the refresh fire less, the cheap direction).
  • Reviewer 2, ledger truncation. Agree, and fixed: math.Ceil on the deferred-minus-list difference. The new test crosses 99,999 → 100,001 on Haiku with the 1.3686 billed factor; the arithmetic is right.
  • Reviewer 2, replay ping at the row's size. Agree, and fixed: the ping prices at CachedContext + ping input with a fail-open fallback to the row's rates when the lookup fails; the stake keeps the row's rates, a fair proxy.
  • Reviewer 2, cg_* counters and PriceCG at base rates. Agree: tracked as the PR's open questions.

The new commit, checked hunk by hunk:

  • campaign/replay.go: the extra price lookup per row is memoized behind autoPrice; the fallback on !pingOK fails open. The test's numbers check out (row at 271,010 → base; ping at 272,001 → dear; PingCost = 272,000×2 + 7×2 + 2).
  • dash/cachestate.go, dash/keepalive.go, proxy/keepalivectl.go: only the tier lookup adds the ping input; the dollar formulas still multiply the bare prefix, so no figure double-counts the extra token. NextRequestUSD's two callers (manual ping, cachestate) describe a ping-shaped next request, which matches.
  • keepalive/keeper.go: pingPrompt is applied at all three projection sites; pingCost, the substitute and sweepAnswerUSD still price by the billed usage (billedPrompt), which is the measured size.
  • tooldefer/ledger.go: Ceil of the difference, not of each term; a negative difference still rounds toward zero, as before.
  • Test hygiene: imports added (math, kvcache, dash) are used; no duplicate helper names in any package; tokens.BilledDeltaFactor returns 1.3686 for the Haiku family, as the new test assumes.
  • Docs: no doc change was needed for the +1; docs/dashboard.md's rule ("the tier of the request they describe") still matches the code.

Did not run builds or tests: live tests are not approved for this review.

A cache effect, the mark included, only moves tokens between tiers.

Assisted-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: DAVID AMID <[email protected]>
@amiddavid

Copy link
Copy Markdown
Collaborator Author

Round 2 notes

  • Reviewer 1, note 1, the accPrices comment: fixed in d8963449. The comment has the old wording again: the mark moves tokens between tiers. The marker bytes are a rewrite op, and the size subtracts them as Caused. The PR Technical notes say the same now.
  • Reviewer 1, note 3, toolsuggest: the PR body now says "not done here", because fresh_input is in the requests table. That fix is a follow-up.
  • Reviewer 1, note 2, the ping input constant (1 here, 7 in predictive): a follow-up. The Technical notes record it.
  • Reviewer 2, the summary and sweep projections at prefix + 1: recorded in the Technical notes as an estimate. The recorded cost uses the real usage.

The approvals at b13e6832 still count:

approved: b13e68329213 (base b8f4d92b5a89) patch-id 3c81c3ef150d
head:     d8963449b70c (base b8f4d92b5a89) patch-id 59c2cbf7cabd
COMMENTS ONLY: b13e68329213..d8963449b70c changes only comment lines in .go and .sh files. The approval of b13e68329213 still counts. Say so on the PR.

Local tests: waived (owner rule)

…rice line

The saving is the bill without context-guru minus the bill as sent, each
at its own prompt size. The tokens that stay, and all output, change rate
when the two sizes sit on different sides of a line. That re-rate is split
over the components in proportion to their net saved tokens. With no such
component it books to the ended-change figure.

Owner decision, 2026-11-25. Same rule as accountant#112.

Assisted-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: DAVID AMID <[email protected]>
The tokens that stay exclude the Caused tokens of each cache effect that
AccountantFigure books. A break the client body has too is booked nowhere,
so its tokens stay. Found in review of accountant#112.

Assisted-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: DAVID AMID <[email protected]>
@amiddavid

Copy link
Copy Markdown
Collaborator Author

New since round 2: the owner's decision on savings

Owner decision (David Amid, 2026-11-25): the dashboard savings count the full bill difference. The saving is the bill without context-guru minus the bill as sent, each priced at its own prompt size. This matches rossoctl/accountant#112. The owner granted round 3 for this change.

  • c6e96d6b adds the re-rate. For each tier, the tokens that stay × (rate without − rate billed). Output re-rates too.
  • Each counted component gets a share of the re-rate, in proportion to its net saved tokens, so the components add up to DeltaUSD. If no component has a net saving, the re-rate goes to EndedBreakUSD. The PR table names this.
  • c540077e fixes a double count that the accountant#112 reviewers found. The tokens that stay no longer include the Caused tokens of each cache effect that AccountantFigure books. A break that the client body also has (InBaseline), a break without an owner, and an unknown effect kind stay in.
  • The accountant#112 interaction-size fix does not apply here. dash ignores Result.Interaction on purpose.

Tests (macOS, Go 1.27.4):

  • The 290K → 250K example, with 2,000 output tokens.
  • A 3:1 split that adds up.
  • A negative re-rate.
  • No line crossed, and a price with no tiers.
  • A cache effect together with a crossed line: the booked total equals the bill difference.
  • An InBaseline break kept in the re-rate.
  • Mutations that drop the re-rate, use an equal split, drop the output term, or drop the effect subtraction each make a test fail.
  • Plain go test ./dash ./proxy passes. -race -run TestFigure passes.

Local tests: waived (owner rule)

@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 c540077e060e approve

Verdict: approve

Findings

None. The re-rate is a real behavior change with the owner's decision recorded, and I could not break its arithmetic.

Round-2 notes: status

Mine:

  1. Summary and sweep projections price the tier at prefix + 1. Kept as an estimate, now recorded in the PR Technical notes ("the same estimate class as summaryOutputBudgetGuess", follow-up). Accept.
  2. The accPrices comment asserted a direction I could not prove. Fixed in d8963449: the comment says again "a cache effect only moves tokens between tiers". Reviewer 1 supplied the proof I lacked: the marker's own bytes are a rewrite op (apply/ops.go:286 tailOp, SizeAfter > SizeBefore), priced as the op's Caused, which accPrices subtracts. I spot-checked tailOp; the claim holds. Resolved.

Reviewer 1's round-2 notes (checked myself):

  1. accPrices comment direction. Fixed in d8963449, as above.
  2. pingPrompt adds 1, the measured law is 7. Kept as a follow-up, recorded in the Technical notes. Accept: the +1 fixes the tier line for the minimal ping shape; pingFresh = 7 is the measured average inside PingCost; one shared constant is a fair later cleanup.
  3. toolsuggest reason overstated. The PR table now says "Not done here" and the Technical notes name the follow-up (the requests table has fresh_input, dash/cachestate.go:422). Accept.

The new commits

  • d8963449 — comment only, and now correct.
  • c6e96d6b — the re-rate. I verified the model by hand: the booked total (ops + booked effects + re-rate) equals the bill without minus the bill as sent, each at its own prompt size. I recomputed all nine test scenarios independently and each matches, including the two-component 3:1 split, the negative re-rate (mask at −1.15, delta −1.65), the no-line and no-tier cases, and the owner's 290K → 250K example with output (1.68 both ways).
  • c540077e — the double-count fix. bookedCaused mirrors the booking switch in AccountantFigure case by case; I walked every branch (InBaseline break, owned break, ended break with empty ChangeID, unowned break, rescue/split/ttl/mark, unknown kind) and each matches. The identity test's numbers check out by hand: booked 1.004 = bill difference 1.004, with the rescue's 1,000 read and the break's 20,000 write removed from the stay exactly once.

Points I probed and accept:

  • The stay subtraction. Every token of the with-bill is either an op's Caused, a booked effect's Caused, or stay — so no token is priced twice, and the clamp max(stay.X, 0) only guards drift. The unowned break stays in the re-rate by the author's stated choice; I checked when that case can occur with the figure applied (dropped ops and observe mode both gate the figure away, accOverride returns early), and a dry-run change's counterfactual break carries no tokens in the bill, so leaving it in stay is harmless.
  • bookReRate row safety. Shares come only from counted ops, so every share's component already has a ByComponent key — the re-rate cannot create a figure-without-row fallback. The total == 0 path books to EndedBreakUSD, and accOverride adds the ended_change row when it is non-zero, so the rows still sum to DeltaUSD.
  • The gates around the figure. countedSavedTokens uses tokens, not dollars, so the re-rate cannot trip the plausibility bound. The held estimate keeps the re-rate in both its ceiling and its floor, so the floor stays under the ceiling.
  • Process. The re-rate is named in the behavior-change block at the top of the PR with the owner decision (David Amid, 2026-11-25), the owner granted round 3, and docs/dashboard.md states the split rule, the ended_change fallback and the negative case, matching the code.

Non-blocking

  • The re-rate books into ByComponentFirst (the first-removal column). That column's old reading was "the write and input tiers of the saved tokens"; it now also carries rate-change dollars with no tokens behind them. The PR table names the choice and no token figure changes, so I accept it — but a reader of the components table can no longer derive that column from the token columns.
  • A cost-causing component absorbs no share of a negative re-rate (shares need net saved tokens above 0), so a saving component can go below 0, as the test shows. This is the owner's rule and docs/dashboard.md states it. Noted only so the choice is visible in the review trail.

What I checked

  • Last review: round 2, b13e683, 2026-11-25T14:37:59Z.
  • New commits read: 3 — d8963449 "docs(pricing): fix the accPrices comment", c6e96d6b "feat(dash): count the full bill difference when a request crosses a price line", c540077e "fix(dash): do not re-rate the tokens of a booked cache effect twice".
  • Read in full: 4 reviews, 4 comments, 0 inline comments (from the three saved files), plus the current PR body.
  • New items since my last review, and what I did: reviewer 1's round-2 review (its three notes checked against the code and dispositioned above); the owner-decisions comment at 14:36 (counters → accountant#111, no global switch, estimate accepted, merge yes at hand-off); the author's round-2 reply at 14:41 (each claim verified, including the comments-only approval note for b13e6832..d8963449); the round-3 announcement at 15:29 with the owner's savings decision; the three new commits (full diff, plus dash/accountant_price.go in full around the new functions); the updated PR body and docs/dashboard.md.
  • The re-rate arithmetic: recomputed every new and updated test in dash/pricetier_callers_test.go by hand from accPrices, tierUSD, bookedCaused and bookReRate — all nine scenarios match their expected values, and the two identity tests (booked total = bill difference) hold in my independent computation.
  • bookedCaused against the booking switch branch by branch; the stay computation (billed tiers minus ops' Caused minus booked effects' Caused, clamped); the pw == pb early return (Price stays comparable, so == is sound); the output term (OutputTokens × the output-rate difference, output not counted in the prompt size).
  • That nothing else moved: git diff b13e6832..HEAD touches only dash/accountant_price.go, dash/pricetier_callers_test.go and docs/dashboard.md; the keepalive, tooldefer, campaign and proxy sides are unchanged from the head I approved in round 2.
  • Commit messages: DCO sign-off and Assisted-By present on all three. Tests were not run: live tests are not approved; the author reports plain go test ./dash ./proxy and -race -run TestFigure green, with four re-rate mutations each failing a test.

@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 c540077e060e approve

Verdict: approve

Findings

None. The re-rate is a large change to the savings figures, and I could not break it. The decomposition is exact, the double-count fix is right, and the owner's decision is recorded.

Non-blocking

  1. dash/accountant_price.go:273 — the re-rate books into the first-removal column. bookReRate adds its share to ByComponentFirst, including the re-rate of read-tier stay tokens, which the column's own doc calls replay content. The invariant holds (ByComponent minus both columns still equals the costs), and the code comment says the choice. docs/dashboard.md says which row an unowned re-rate books to, but not which column carries it. One line in the docs would close it.
  2. The tool-deferral saving now has two methods. The accountant's deferFig can include a re-rate share (a deferral with net saved tokens owns one), while the lever's own Price in tooldefer/ledger.go prices gross and cost per side with no re-rate. The two figures already differed in scope; the re-rate widens the gap. A note on the lever, or a later alignment, would do.

What I checked

  • Last review: round 2, b13e68329213, 2026-11-25T14:39:38Z.
  • New commits read: 3 — d8963449 "docs(pricing): fix the accPrices comment", c6e96d6b "feat(dash): count the full bill difference when a request crosses a price line", c540077e "fix(dash): do not re-rate the tokens of a booked cache effect twice".
  • Read in full: 4 reviews, 4 comments, 0 inline comments (the inline file is empty), from the three saved files.
  • New items since my last review, and what I did: the author's owner-decisions comment (14:36, posted as my round-2 review landed), the author's round-2 reply (14:41), reviewer 2's round-2 review (14:37, posted after my round-2 fetch; read in full now), the author's round-3 comment (15:29), the three commits, and the PR body edits (behavior-change block, toolsuggest row, Technical notes).

Earlier findings, disposition:

  • Round-2 note 1, the accPrices comment direction. Fixed in d8963449: the old wording is back ("a cache effect only moves tokens between tiers, so it does not change the size"). Verified against the code: the marker bytes leave the size without as the tail-breakpoint op's Caused.
  • Round-2 note 2, the ping input constant (1 vs 7). Kept as a follow-up, recorded in the Technical notes. Accept.
  • Round-2 note 3, toolsuggest "cannot". Fixed: the PR row and Technical notes now say "not done here" and name the follow-up. Accept.
  • My process note, the owner's yes. Resolved: the owner's decisions of 2026-11-25 are on the PR (counters to accountant#111, no global switch, the estimated size accepted, the merge yes at hand-off), and the re-rate itself carries "Owner decision, 2026-11-25" in its commit message and in the PR's behavior-change block.
  • Reviewer 2's round-2 notes (the direction comment, the summary and sweep projection estimate): fixed and recorded the same way. Agree with both dispositions.

The new commits, checked in depth:

  • The decomposition is exact. I proved the identity: the booked total (DeltaUSD + KeepAliveSavedUSD + SplitUSD + TTLUSD) equals the bill without minus the bill as sent, each at its own prompt size. It rests on three facts, each true under the library's semantics: the ops' and the booked effects' Saved/Caused are tier moves of content present in both bodies; the unbooked effects' Caused (an InBaseline break, an unowned break) stays in stay, where it re-rates once, which is right because the client body has those tokens too; and stay is the billed tokens minus what the counted ops and the booked effects caused. BaselineCostUSD = CostUSD + DeltaUSD now equals the client's bill exactly.
  • Every new test's arithmetic, by hand. The owner's example (290K→250K with 2,000 output: 1.68); the 3:1 split that sums to the delta; the negative re-rate (−1.65, the mask share goes below 0); the Haiku opposite sides (0.046); both-above and no-tiers (no re-rate); the mixed cache-effect case (booked 1.004 = bill difference 1.004 — this is the test that pins the c540077e fix); the InBaseline break kept in the re-rate (2.4).
  • bookedCaused mirrors the booking switch case by case. InBaseline, an unowned break and an unknown kind return zero (their tokens stay); the owner case, the ended-change case, rescue, split, both TTL legs and both mark legs return Caused (their value is booked, so their tokens must not re-rate twice). The share list is built after the unpriced-op skip, so a skipped op cannot own a re-rate.
  • Guards and clamps. pw == pb returns 0, so no line crossed, a flat price or an unknown size keeps the old figures (the no-tiers test covers it). Negative stay tiers clamp to 0, so a library over-attribution under-counts the re-rate instead of exploding it. The re-rate adds dollars only; no addTok call, so no token figure changes, as the PR claims.
  • The held path. The re-rate stays whole inside both the ceiling and the floor of a held estimate (the line crossing does not depend on the warm or cold hypothesis), and the estimated branch zeroes the first-removal column with the rest.
  • The agree and shadow tests. priceOfAcc builds prices with no tiers, so the re-rate is zero on every shared accountant case and those comparisons are unaffected.
  • The docs. The docs/dashboard.md example matches the code and the test (290K×2x − 250K×1x on input, plus the output re-rate), and the split rule, the ended_change fallback, the negative re-rate and the no-line case are all stated.
  • d8963449 changes comment lines only; the code is unchanged under it.

Did not run builds or tests: live tests are not approved for this review. The author reports ./dash and ./proxy green and four mutations failing tests.

@amiddavid

Copy link
Copy Markdown
Collaborator Author

Owner decision: merge yes (David Amid, 2026-11-25)

The owner said yes to merging this PR with its behavior change:

  • cost_usd and the savings figures use the tier rate for each request's prompt size. Above the line, OpenAI GPT-5.4+ (272K) shows 2x and Claude Haiku 5.5 (100K) shows 5x.
  • When a request crosses the line, the savings include the rate change of the tokens that stay.
  • The keep-alive per-ping limit (MaxUSDPerPing) stops some pings in long sessions above the line.
  • To turn the tiers off, set flat: true on a price-file entry. The owner decided against a global switch.

The owner also granted round 4. It re-checks the docs and comments delta after c540077e.

@amiddavid

Copy link
Copy Markdown
Collaborator Author

Round 4: re-check the delta after c540077e

Both reviewers approved round 3 at c540077e. The delta after it changes only docs and comments (2 files, +10/−3):

  • 31dbc96d (docs/dashboard.md): when an unowned re-rate goes to ended_change, that row name is approximate.
  • cb595cd2, for the round-3 notes:
    • Reviewer 1, note 1, and reviewer 2, note 1: docs/dashboard.md now says that the re-rate goes to the first-removal column (ByComponentFirst). That column includes the re-rate of cache-read tokens that stay. It can no longer be derived from the token columns.
    • Reviewer 1, note 2: the Price doc comment in tooldefer/ledger.go now says the lever prices gross and cost per side with no re-rate. The accountant figure (deferFig) can include a re-rate share, so the two figures differ in scope.
    • Reviewer 2, note 2: docs/dashboard.md now says that a component with no net saved tokens gets no share of the re-rate.

The .go change touches comment lines only. The owner granted round 4 for this re-check, and the owner's merge yes is recorded above.

@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 4 of 4 cb595cd2b500 approve -->

Verdict: approve

Findings

None. The delta since round 3 changes docs and comments only, and every statement in it matches the code.

Round-3 notes: status

Mine:

  1. The re-rate books into ByComponentFirst, which no longer follows the token columns. Fixed in the docs (cb595cd2): docs/dashboard.md now names the column (saved_first_usd), says it carries the re-rate of staying cache-read tokens too, and says it can no longer be derived from the token columns. I verified the column name against the json tag (dash/event.go:728).
  2. A cost-causing component absorbs no share of a negative re-rate. Now stated in docs/dashboard.md: "a component that only causes cost (no net saved tokens) gets no share". Matches bookReRate's share rule (net saved tokens above 0).

Reviewer 1's round-3 notes (checked myself):

  1. The docs did not say which column carries the re-rate. Fixed, same docs change as my note 1.
  2. The tool-deferral saving has two methods (the lever's Price vs the accountant's deferFig). Fixed in cb595cd2: the Price doc comment in tooldefer/ledger.go now says the lever prices gross and cost per side with no re-rate, and that deferFig can include a re-rate share, so the two differ in scope. I verified both halves against the code: tooldefer.Price has no re-rate term, and a tooldefer op with net saved tokens does receive a share in bookReRate.

The new commits

  • 31dbc96d — one line in docs/dashboard.md: the ended_change row's name is approximate when it holds an unowned re-rate. Matches the total == 0 path in bookReRate and the row accOverride adds.
  • cb595cd2 — the docs naming above, plus the tooldefer ledger comment. The .go change touches comment lines only; Price's body is unchanged from the head I approved in round 3.

No code changed since c540077e, so my round-3 verification of the re-rate arithmetic, the bookedCaused switch, the stay computation and the gates still stands at this head.

Non-blocking

  • Nothing new. The two round-3 notes are now documented, and the owner's merge yes (David Amid, 2026-11-25, 15:58) is on the PR with the behavior change named.

What I checked

  • Last review: round 3, c540077, 2026-11-25T15:34:54Z.
  • New commits read: 2 — 31dbc96d "docs(dashboard): say the ended_change row can hold an unowned re-rate", cb595cd2 "docs(pricing): name the re-rate column and the ledger scope".
  • Read in full: 6 reviews, 6 comments, 0 inline comments (from the three saved files), plus the current PR body.
  • New items since my last review, and what I did: reviewer 1's round-3 review (read in full; its two notes dispositioned above); the owner's merge-yes comment at 15:58 (the behavior change, the per-ping limit and flat: true are all named in it); the author's round-4 announcement at 15:59; the two new commits (full diff, and the changed files around the changes).
  • Every claim in the new docs and comments against the code: the saved_first_usd json tag (dash/event.go:728); the share rule and the ended_change fallback in bookReRate; the absence of a re-rate term in tooldefer.Price; the presence of re-rate shares in deferFig's path.
  • That nothing else moved: git diff c540077e..HEAD touches only docs/dashboard.md (+9/−3) and the comment block above tooldefer.Price (+4/−1); the full diff from base b8f4d92b otherwise matches the heads I approved in rounds 1 to 3.
  • Commit messages: DCO sign-off and Assisted-By present on both. Tests were not run: live tests are not approved; the delta changes no executable line.

@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 4 of 4 cb595cd2b500 approve

Verdict: approve

Findings

None. The delta after c540077e changes documentation and comments only, and every statement in it matches the code.

Non-blocking

None new. Both my round-3 notes are fixed, and I have nothing further to raise.

What I checked

  • Last review: round 3, c540077e060e, 2026-11-25T15:36:44Z.
  • New commits read: 2 — 31dbc96d "docs(dashboard): say the ended_change row can hold an unowned re-rate", cb595cd2 "docs(pricing): name the re-rate column and the ledger scope".
  • Read in full: 6 reviews, 6 comments, 0 inline comments (the inline file is empty), from the three saved files.
  • New items since my last review, and what I did: reviewer 2's round-3 review (15:34, posted just before mine; read in full now — its two notes match mine or the owner's rule, and both are now in the docs); the owner's merge yes (15:58); the author's round-4 announcement (15:59); the two commits; the final docs/dashboard.md text.

Earlier findings, disposition:

  • Round-3 note 1, the docs did not say which column carries the re-rate. Fixed in cb595cd2: the docs now name the first-removal column (saved_first_usd), say it also carries the re-rate of cache-read tokens that stay, and say it can no longer be derived from the token columns. I verified the column name against the code: ByComponentFirst → CompRow.SavedFirstUSD → json saved_first_usd (dash/event.go:728). All three statements match bookReRate.
  • Round-3 note 2, the tool-deferral saving has two methods. Addressed in cb595cd2: the Price doc comment in tooldefer/ledger.go now says the lever prices gross and cost per side with no re-rate, and that the accountant figure (deferFig) can include a re-rate share, so the two differ in scope. I checked the comment's claims against the code: Price has no stay term, and a deferral op with net saved tokens above 0 does become a re-rate share in AccountantFigure. Accurate.
  • Reviewer 2's round-3 notes. Note 1 is my note 1 (fixed the same way). Note 2 (a cost-causing component gets no share of a negative re-rate) is the owner's rule and is now stated in the docs: "A component that only causes cost (no net saved tokens) gets no share." That matches the share rule (tierTotal(Saved) - tierTotal(Caused) > 0), which applies to both signs of the re-rate.

The two commits, checked claim by claim:

  • 31dbc96d + cb595cd2 touch only docs/dashboard.md and the doc comment above tooldefer.Price. No code line changes; the head I approved at round 3 is unchanged under them.
  • Every new docs statement against the code: the share rule (net saved tokens, only above 0); the ended_change fallback with its name approximate and no tokens (bookReRate adds dollars only, no addTok); the column name and its json tag; the negative re-rate taking a net-saving component below 0 (matches TestFigureNegativeReRateCanTakeAComponentBelowZero); no line crossed or no tiers gives the old figures.
  • Commit messages: DCO sign-off and Assisted-By present on both.

Process: the owner's merge yes for the behavior change is on the PR (15:58, David Amid, 2026-11-25), and round 4 was granted for this docs delta. From my side the PR is ready for hand-off.

Did not run builds or tests: live tests are not approved for this review. No code changed since the author's last green run.

amiddavid added a commit that referenced this pull request Nov 25, 2026
…ent test (#1426)

test(proxy): pass the prompt-size price callback in the predictive agent test

#1407 changed campaign.Rows to take a price callback with a prompt size.
#1410 added predictive_agent_test.go with the old callback. Both merged
close together, so main did not compile for the proxy tests.

The test price function now takes (model, promptTokens) and ignores the
size. The rates stay the same. No production code changes.

Refs #1407, #1410

test(proxy): gofmt the price callback, with blank parameter names

lint-build failed with "gofmt needed". gofmt wraps a function literal
that is too long for one line. The callback ignores its parameters,
so it now names them "_", as the other tests do
(campaign/campaign_test.go, proxy/campaignauto_test.go). The line
is shorter, and gofmt keeps it on one line.

Fixes the main build after #1407 and #1410 merged close together. Test only.

Assisted-By: Claude Opus 5.5
Signed-off-by: DAVID AMID <[email protected]>
amiddavid added a commit that referenced this pull request Nov 25, 2026
The flat $0.50 per-ping cap blocked GPT-5.5 pings above about 500K
tokens after #1407. Such a ping saves 9x to 11x its cost.

- Value rule: allow the planned pings of one idle span when they cost
  less than one miss (prefix x (write rate - read rate)), both priced
  at the tier of the prompt size. Live keeper and replay call one
  function, Policy.PingVerdict.
- keepalive_max_usd_per_ping is now an opt-in flat cap on top. The
  loader no longer fills 0.50 and no strategy sets it.
- Summary and sweep calls keep their $0.50 default cap.
- New reason "not worth it". "over budget" now means the operator cap.
- keepalive.PingPrompt replaces the proxy's own prefix + 1 sum.

Fixes #1420

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 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]>
amiddavid added a commit that referenced this pull request Nov 25, 2026
…) (#1428)

feat(keepalive): weigh a ping chain against the miss it protects (#1420)

The flat $0.50 per-ping cap blocked GPT-5.5 pings above about 500K
tokens after #1407. Such a ping saves 9x to 11x its cost.

- Value rule: allow the planned pings of one idle span when they cost
  less than one miss (prefix x (write rate - read rate)), both priced
  at the tier of the prompt size. Live keeper and replay call one
  function, Policy.PingVerdict.
- keepalive_max_usd_per_ping is now an opt-in flat cap on top. The
  loader no longer fills 0.50 and no strategy sets it.
- Summary and sweep calls keep their $0.50 default cap.
- New reason "not worth it". "over budget" now means the operator cap.
- keepalive.PingPrompt replaces the proxy's own prefix + 1 sum.

Fixes #1420

fix(keepalive): round 1 review fixes for the ping value rule (#1420)

- A manager strategy's flat cap of 0 now leaves the account's own cap
  in place. Only a value other than 0 replaces it.
- The strategy form says 0 = no flat cap.
- A miss is priced at the 1-hour write rate when the policy writes at
  1 hour (HeadTTL1h, OneHourAlways) or plans the 1-hour ping.
- Replay weighs the miss at the ping's tier and the live wait-plan
  count (never more than live). The replay-versus-live test now goes
  through a real keeper.
- The arm answer reports the effective cap after the manager strategy.
- Fix stale comments and the OpenAI write-rate sentence.

fix(keepalive): round 2 review fixes for the ping value rule (#1420)

- The arm answer resolves the policy with the provider of the
  session's own last request, so the manager strategy cap is reported
  only where it is enforced (not on an OpenAI session).
- A subagent keeps the 5-minute cache under OneHourAlways, so its
  miss is priced at the 5-minute rate.
- Replace the replay chain test that restated its own definition with
  a pin on the K=8 tool wait and the OpenAI base count.

Behavior change (value rule replaces the flat per-ping cap; flat cap opt-in) approved by the owner in the integrator session, 2026-11-25: "1428 yes". Approvals at 40a3473 carried over (SAME CHANGE: only sign-offs added).

Assisted-By: Claude Opus 5.5
Signed-off-by: DAVID AMID <[email protected]>
amiddavid added a commit that referenced this pull request Nov 25, 2026
)

fix(dash): price the declaration-filter saving at its prompt size

The declaration-filter query did not read fresh_input, so each row
priced at base rates. Read it, size the prompt with
modelinfo.PromptTokens, and price with Price.At, as #1407 does
elsewhere. Both DeclFilterSavings and DeclFilterSavingsByTenant use it.

Fixes #1438

fix(dash): price a filter saving at the size without the filter

Review round 1. A removed declaration prices at the size the request
would have had without the filter: sent plus removed tokens. Apply that
to the declaration-filter saving. Price carriedCost at the request's
prompt size too, so the items and the total on /api/adapt/tools agree.

test(dash): correct the sent size in a tiered-price test comment

mkEvent sets FreshInput to 10, so the one-hour request is 5,010
tokens sent, not 5,000. The 5,050 line holds either way. Only the
comment changes.

style(dash): gofmt the test case struct in toolsuggest_test.go

CI lint-build failed with "gofmt needed". gofmt aligns one struct
field. The change is whitespace only (git diff -w is empty).

Behavior change (declaration-filter saving priced at the size without the filter) approved by the owner in the integrator session: "1442 yes". Approvals at eb64543 carried over: after them only a comment and a gofmt space change in a test.

Assisted-By: Claude Opus 5.5
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

openai OpenAI / Codex traffic and pricing

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

1 participant