Repository navigation
fix(accounting): price savings across a long-context line by the whole bill difference - #2147
Conversation
…e bill difference Cortex priced every saving at the forwarded prompt's rate. A change that took a prompt from above the 200k long-context line to below it booked only the removed tokens at the base rate: 71% too low on a 250k to 150k prune (#2135). - Host.Savings takes its dollars from accountant.Figure: saved tokens at the size without the ops, caused tokens at the billed size, and the re-rate of the tokens that stay. Cortex keeps its own owners, dry runs, spends, units and estimated flags. - The metrics pricer gets PriceAt, so the sink prices the same sizes. Sink.Observe passes the output tokens, so output is re-rated too. Before, the metrics had the same bug. - Bump accountant and accountant/metrics to v0.9.0 in every module. v0.9.0 also withholds the metrics of a request that fails the gates (accountant #118): the push test now sends one clean and one gated request, and llm.savings.withheld is an allowed series. - docs/pricing.md: the prompt sizes, and the withheld requests. Fixes #2135 Assisted-By: Claude (Anthropic AI) <noreply@anthropic.com> Signed-off-by: DAVID BOAZ <DAVIDBO@il.ibm.com>
|
Warning Review limit reachedYou've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository. Next included review available in 27 minutes. View limit details
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. |
|
Test result for
|
|
CI: This is not caused by this PR. The same job was cancelled at 10 minutes on most runs today: |
clawgenti
left a comment
There was a problem hiding this comment.
Summary
The fix works. Host.Savings now takes its op and cache-effect dollars from accountant.Figure, and boundPricer implements PriceAt, so the ledger and the metrics sink price at the same two prompt sizes. I verified the claim directly:
- Base vs head: I ran
TestSavings_CrossingTheLongContextLineSavesTheWholeBillDifference(the part that only uses existing API) againstmain. It fails with ledger = pushed = $0.375109 against the whole-bill-difference $1.320448. On the PR head it passes, and the ledger and the push agree. - Mixed Result probe (a saver, an adder, a dry run, a spend, an owned break and a rescue, at three sizes: crossing, both above, both below): the ledger net (non-projected
USD - PenaltyUSD - UnattributedBreakUSD) equalsfig.DeltaUSD + KeepAlive + Split + TTLto the micro in every case. The dry run is still priced at the billed size, and the spend stays inExtras.Spends. - Accountant case corpus through the new path: I played every
accountant/test/casescase throughFigure+savingsBilled(res, newFigured(fig), ...)with a flatSizedPricer. All cases agree within 1 µ$ (see the inline suggestion). - v0.8.0 → v0.9.0: the library diff is additive (
Figure,Withhold,usd.go,withhold.go). No serialized or JSON shapes change, so there is no decode risk for stored state. - Edge case I ruled out: a usage with every split counter at 0 would make
Figureprice at size 0 whilepromptTotalfalls back toTotalTokens. The library marks every opno_usagewith zero tokens in that case, so no dollars move.
The two inline comments are a doc accuracy fix and a test-coverage suggestion. Neither blocks.
Author: boazdavid (CONTRIBUTOR association, admin permission — maintainer)
Areas reviewed: Go (core/accounting), go.mod/go.sum bumps (5 modules), docs
Agent/IDE config (.claude/.vscode): none
Commits: 1 commit, all signed-off: yes
CI status: passing. The exception is Go CI (core peerproc, macOS), which hit the 10-minute job timeout. That job is cancelled or times out on most recent runs, main included, and this PR does not touch peerproc. go test ./accounting/... passes locally at head.
| - Added tokens are priced at the billed prompt size. | ||
| - If the two sizes are on different sides of a [long-context line](#long-context-tiers), the | ||
| tokens that stay (output included) are re-priced too. That amount is the **re-rate**. Each | ||
| operator with a net saving gets a share of it, in proportion to its net saved tokens. |
There was a problem hiding this comment.
suggestion — This bullet covers only the shrinking case. accountant.Figure gives the re-rate to the net adders when the ops made the prompt larger, and they pay it as a penalty. That is what TestSavings_AnAddThatCrossesTheLinePaysThePremium pins, and what the PR body and the Extras.UnattributedBreakUSD comment say ("an op that pushes a prompt over the line pays the premium"). As written, a reader would conclude that an inject that crosses the line has no re-rate. Suggested wording: "The operators that moved the size own it: when the prompt got smaller, each operator with net saved tokens gets a share in proportion to them; when it got larger, each operator with net added tokens pays a share in proportion to those."
| // savingsBilled is SavingsBilled. With fig nil, every dollar is priced at one prompt size. With | ||
| // fig set, the applied ops and the cache effects take their dollars from fig, and price still | ||
| // gives the estimated flags and the dry runs, which Figure does not price. | ||
| func savingsBilled(res accountant.Result, fig *figured, price func(model, host string, tt accountant.TierTokens) (float64, bool), |
There was a problem hiding this comment.
suggestion — savings_agree_test.go (TestSavingsAgreesWithTheAccountantCases) still plays the accountant case corpus through SavingsBilled, which is now the fig == nil path. Production (Host.Savings) runs savingsBilled(res, newFigured(fig), ...), and no corpus test covers that path. Its stated purpose is to prove the conversion layer on top of the Result, and the conversion layer now includes newFigured's grouping by operator/direction and the fig.effects[i] index alignment.
I ran the corpus through this path locally: a flat SizedPricer built from cases.Rate, then Figure and savingsBilled(res, newFigured(fig), rateOf(rate), spendOf(c), ...), with the same net as playedNet. Every case agrees within 1 µ$. Adding that as a second subtest would keep the guard on the code that actually runs.
| saved, caused map[string]float64 | ||
| // effects is the value of res.CacheEffects[i], SavedUSD - CausedUSD: positive saves. | ||
| effects []float64 | ||
| // unownedReRate is the re-rate no op owns, because no op has a net saving: positive saves. |
There was a problem hiding this comment.
nit — "because no op has a net saving" is narrower than the library's rule. UnownedReRateUSD is set when no op moved the size in the direction it moved, so no net saver when it shrank and no net adder when it grew. Something like "the re-rate no op owns, because no op moved the prompt size (accountant.USDFigure.UnownedReRateUSD; 0 today)".
Summary
Cortex now prices a saving by the whole bill difference. A change that takes a prompt from above the 200k long-context line to below it was booked 71% too low. The ledger and the OTel metrics had this bug, and now both are fixed. They agree to the micro-dollar.
Fixes #2135.
What we found
Host.Savingspriced every token at the forwarded prompt's rate. A prune from 250,091 to 150,062 tokens booked $0.3751. The whole bill difference is $1.3204 (prompt $1.3129, output $0.0075).accountant/metricsprices each side at its own size only if the host's pricer hasPriceAt, and Cortex'sboundPricerdid not have it.Sink.Observealso did not pass the output tokens, so the sink could not re-rate output.What changed
core/accounting/savings.go):Host.Savingstakes its dollars fromaccountant.Figure.estimatedflag. A dry run is still priced at the billed size, becauseFiguredoes not price dry runs.Extras.UnattributedBreakUSD. With accountant v0.9.0, this does not happen.core/accounting/metrics.go):boundPricergetsPriceAt, andSink.ObservepassesOutput. The ledger and the metrics share one rate function,tierRate(price.go).llm.savings.withheld.TestStart_PushesTheSavingsCountersnow sends one clean request and one gated request.llm.savings.withheldis an allowed series.docs/pricing.md): which prompt size each side uses, with the example from the issue, and the withheld requests.How it was tested
core/accounting/longcontext_test.go:TestSavings_CrossingTheLongContextLineSavesTheWholeBillDifferenceruns a real request throughHost.Savingswith a rate table that doubles above 200k. The ledger equals the whole bill difference, output included, and the metrics push equals the ledger. Before this change, it booked $0.3751.TestSavings_AnAddThatCrossesTheLinePaysThePremium: an op that adds 60k tokens and pushes the prompt over the line pays its tokens at the long rate, plus the premium of the tokens that stay.TestSink_ConcurrentObservationsKeepTheirOwnEndpointaccepts both sizes of one endpoint.TestSink_SpendCollisionFallsBackToTheRequestBindingnow prices a call at its own size, as the ledger does.gofmtis clean.go vetis clean in all 5 modules.go mod tidy -diffis clean in all 5 modules.go test:core/accounting/...passes.cmd/cortex,cmd/cortex-envoyandscripts/readme-demopass.main, so this PR does not cause them:core/cost/ledger,core/cost/usage). They probably depend on the local time-zone data.TestDoctorNamesTheFixForEachBrokenStep/PATH_block_removed(cmd/agentop) hangs until the test timeout.Open questions
savings.go,metrics.goanddocs/pricing.md, as this PR does. The PR that merges second must rebase.Technical notes
savingsBilledis the oldSavingsBilledwith an optional*figured.SavingsBilled(one prompt size) keeps its signature and behavior.figuredgroups theUSDFigurelines by operator and direction. It skipsKindSpendlines, becauseExtras.Spendsprices each call with its own host and currency. It takes the value of each effect fromUSDFigure.Effects[i], which has the same order asResult.CacheEffects.Assisted-By: Claude (Anthropic AI) noreply@anthropic.com