Skip to content

fix(accounting): price savings across a long-context line by the whole bill difference - #2147

Merged
boazdavid merged 1 commit into
mainfrom
fix/2135-figure-savings
Nov 26, 2026
Merged

boazdavid merged 1 commit into
mainfrom
fix/2135-figure-savings

Conversation

@boazdavid

Copy link
Copy Markdown
Contributor

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

  1. Ledger. Host.Savings priced 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).
  2. Metrics. The issue says the metrics were already right. They were not. accountant/metrics prices each side at its own size only if the host's pricer has PriceAt, and Cortex's boundPricer did not have it. Sink.Observe also did not pass the output tokens, so the sink could not re-rate output.

What changed

  1. Ledger (core/accounting/savings.go): Host.Savings takes its dollars from accountant.Figure.
    • Saved tokens are priced at the prompt size without the ops. Caused tokens are priced at the billed size.
    • The tokens that stay are re-priced when the two sizes are on different sides of a price line. This is the re-rate. The ops that moved the size own it, so an op that pushes a prompt over the line pays the premium (accountant docs: add AuthProxy inbound verification details to manual demo #120).
    • Cortex keeps its own rules for owners, dry runs, spends, subscription units and the estimated flag. A dry run is still priced at the billed size, because Figure does not price dry runs.
    • A re-rate that no op owns goes to Extras.UnattributedBreakUSD. With accountant v0.9.0, this does not happen.
  2. Metrics (core/accounting/metrics.go): boundPricer gets PriceAt, and Sink.Observe passes Output. The ledger and the metrics share one rate function, tierRate (price.go).
  3. Dependency: accountant and accountant/metrics are at v0.9.0 in all 5 workspace modules.
    • v0.9.0 also has accountant docs: Add UI deployment guide for GitHub Issue Agent + AuthBridge demo #118: the metrics sink withholds a request with a fatal check or an unpriced op. It books only that request's spends and counts it in llm.savings.withheld.
    • TestStart_PushesTheSavingsCounters now sends one clean request and one gated request. llm.savings.withheld is an allowed series.
  4. Docs (docs/pricing.md): which prompt size each side uses, with the example from the issue, and the withheld requests.

How it was tested

  • New core/accounting/longcontext_test.go:
    • TestSavings_CrossingTheLongContextLineSavesTheWholeBillDifference runs a real request through Host.Savings with 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.
  • 2 metrics tests changed to the new sizes. TestSink_ConcurrentObservationsKeepTheirOwnEndpoint accepts both sizes of one endpoint. TestSink_SpendCollisionFallsBackToTheRequestBinding now prices a call at its own size, as the ledger does.
  • gofmt is clean. go vet is clean in all 5 modules. go mod tidy -diff is clean in all 5 modules.
  • go test: core/accounting/... passes. cmd/cortex, cmd/cortex-envoy and scripts/readme-demo pass.
  • Failures that also happen on main, so this PR does not cause them:
    • 3 time-zone tests on Havana dates (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

Technical notes

  • savingsBilled is the old SavingsBilled with an optional *figured. SavingsBilled (one prompt size) keeps its signature and behavior.
  • figured groups the USDFigure lines by operator and direction. It skips KindSpend lines, because Extras.Spends prices each call with its own host and currency. It takes the value of each effect from USDFigure.Effects[i], which has the same order as Result.CacheEffects.
  • The metrics pricer sees only a model, so a spend on a model that collides with another binding still falls back to the request's endpoint. It is now priced at the call's own size.

Assisted-By: Claude (Anthropic AI) noreply@anthropic.com

…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>
@boazdavid
boazdavid requested a review from a team as a code owner November 26, 2026 09:46
@coderabbitai

coderabbitai Bot commented Nov 26, 2026

Copy link
Copy Markdown

Warning

Review limit reached

You'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.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

Learn how review limits work.

Review configuration:

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 65489ed6-e649-45d5-a762-25b8a5559a9c
Commits

Reviewing files that changed from the base of the PR and between 4189c7a and 7c9cc62.

Files ignored due to path filters: 5

  • cmd/agentop/go.sum is excluded by !**/*.sum
  • cmd/cortex-envoy/go.sum is excluded by !**/*.sum
  • cmd/cortex/go.sum is excluded by !**/*.sum
  • core/go.sum is excluded by !**/*.sum
  • scripts/readme-demo/go.sum is excluded by !**/*.sum
Files selected for processing: 12

  • cmd/agentop/go.mod
  • cmd/cortex-envoy/go.mod
  • cmd/cortex/go.mod
  • core/accounting/longcontext_test.go
  • core/accounting/metrics.go
  • core/accounting/metrics_test.go
  • core/accounting/price.go
  • core/accounting/push/push_test.go
  • core/accounting/savings.go
  • core/go.mod
  • docs/pricing.md
  • scripts/readme-demo/go.mod
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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.

Share

@github-actions github-actions Bot added the ready-for-ai-review Request automated AI code review from clawgenti label Nov 26, 2026
@boazdavid

Copy link
Copy Markdown
Contributor Author

Test result for cmd/agentop, the last module.

  • All sub-packages pass (apiclient, checklist, cluster, edit, money, servers, toolscan, tui, tui/find, tui/table, updatestatus, internal/testhome).
  • The root package cmd/agentop hangs in the TestDoctor* tests on this machine. It hangs on main (4189c7a4) in the same way, so this PR does not cause it.
    • Both runs used -timeout 240s and skipped TestDoctorNamesTheFixForEachBrokenStep.
    • Branch: it stopped in TestDoctorUpdatesDisabled. main: it stopped in TestDoctorUpdatesNoCheckYet.
  • This PR does not change cmd/agentop code. It changes only go.mod and go.sum there.

@boazdavid

Copy link
Copy Markdown
Contributor Author

CI: Go CI (core peerproc, macOS) was cancelled at its 10-minute limit (timeout-minutes: 10, .github/workflows/ci.yaml:86). No test failed. It was still in Build and test cmd/cortex (local profile).

This is not caused by this PR. The same job was cancelled at 10 minutes on most runs today: main (08:32 UTC) and the PRs for #2134, #2136, #2137, #2138 and #2140. It passed only when it finished in 7 to 8 minutes. I started the job again.

@clawgenti clawgenti left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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) against main. 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) equals fig.DeltaUSD + KeepAlive + Split + TTL to the micro in every case. The dry run is still priced at the billed size, and the spend stays in Extras.Spends.
  • Accountant case corpus through the new path: I played every accountant/test/cases case through Figure + savingsBilled(res, newFigured(fig), ...) with a flat SizedPricer. 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 Figure price at size 0 while promptTotal falls back to TotalTokens. The library marks every op no_usage with 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.

Comment thread docs/pricing.md
- 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.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)".

@boazdavid
boazdavid merged commit 333f52b into main Nov 26, 2026
63 of 65 checks passed
@boazdavid
boazdavid deleted the fix/2135-figure-savings branch November 26, 2026 10:11
@github-project-automation github-project-automation Bot moved this from New/ToDo to Done in Rossoctl Issue Prioritization Nov 26, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ready-for-ai-review Request automated AI code review from clawgenti

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

fix(accounting): price savings across the 200k long-context line by the whole bill difference

2 participants