Skip to content

fix: four cost accuracy bugs in export and pricing - #1544

Merged
iamtoruk merged 3 commits into
mainfrom
fix/cost-accuracy
Sep 24, 2026
Merged

iamtoruk merged 3 commits into
mainfrom
fix/cost-accuracy

Conversation

@iamtoruk

Copy link
Copy Markdown
Member

Four money-accuracy bugs found by auditing CodeBurn against AgentMeasure's bug families.

What was wrong

  1. Export daily rows used the turn's day. buildDailyRows skipped turns with no timestamp and bucketed every call on the day its turn started, so export days disagreed with the report (on real data 3 of 7, 11 of 30 and 45 of 118 days; one day showed $852.18 where the report said $798.38).
  2. Invented cache-write premium. calculateCost billed cache-write tokens at 1.25x input for any model without a published write price. That is Anthropic's rule; OpenAI, Gemini and DeepSeek charge no write premium. Only the Codex reader guarded it, so OpenCode and Kilo Code overcharged.
  3. Missing usage read as a measured $0. An OpenCode or Kilo Code message with output but no recorded usage, and a Copilot transcript call with no token count, looked like real free calls.
  4. Export records were rounded to cents one by one, so they did not sum to the summary, and nothing marked a record as estimated or unpriced.

The fix

  • Daily rows bucket each call on call.timestamp || turn.timestamp, the rule the day aggregator uses, and keep turns without a timestamp.
  • New cacheWriteCostPerToken: the published write rate when there is one, 1.25x for Anthropic model ids (Bedrock, Vertex, OpenRouter and gateway spellings included), otherwise the input rate. calculateCost and the audit report use it. Pricing cache schema 3 to 4, daily cache 34 to 35 so settled days re-derive.
  • Those calls are marked costIsEstimated; they are still emitted, so call counts do not change. OpenCode, Kilo Code and Copilot re-parse once.
  • Records keep unrounded cost; CSV prints plain decimals (no float noise, no exponents); estimated and unpriced columns are appended at the end so existing column order is unchanged.

Verification

Real data, fixed range, frozen pricing, fresh cache per run, old vs new:

period before after
7 days $3,914.006640 identical
30 days $12,884.933862 identical
all $21,420.588233 $21,419.409033 (-$1.179200)

The whole delta is OpenCode cache writes on four models, each exactly tokens x 0.25 x input price (gpt-5.3-codex -$0.869339, openai/gpt-5 -$0.155028, gemini-2.5-pro -$0.130353, deepseek-coder-max -$0.024480). Every other provider and model is unchanged in cost and calls; Claude models on every route keep 1.25x. Export daily rows now match the report on every day, and records sum to the summary exactly. About 790 zero-usage OpenCode calls are newly flagged estimated, all $0.

Validated independently before and after rebasing onto the OpenCode 2 fix. tsc clean; full suite green except RootDeepProjectLabels.test.tsx, which fails identically on main in this checkout. New tests fail without the fixes: export reconciliation (daily = records = summary), non-Anthropic cache write at input rate, absent usage flagged estimated, Copilot transcript flagged, CSV decimals.

Not changed: optimize's hardcoded Anthropic multipliers, which only feed Claude-oriented estimates.

iamtoruk and others added 3 commits September 24, 2026 06:32
- export daily rows bucket each call on its own day (same rule as the day
  aggregator) and no longer skip a turn without a timestamp
- cache-write tokens on a non-Anthropic model with no published write rate
  bill at the input rate instead of a fabricated 1.25x (calculateCost and
  audit); daily cache v35 and pricing schema 4 so stored figures re-derive
- OpenCode/Kilo messages with output but no usage, and Copilot transcript
  calls with no token count, are marked estimated
- export records keep unrounded cost and gain estimated/unpriced columns
@iamtoruk
iamtoruk merged commit 6dc81f5 into main Sep 24, 2026
20 checks passed
@iamtoruk
iamtoruk deleted the fix/cost-accuracy branch September 24, 2026 13:55
ozymandiashh added a commit to ozymandiashh/codeburn that referenced this pull request Sep 28, 2026
…ls the implicit cache-write rate

Restore main's two carry-forward tests: with MIN_SUPPORTED_VERSION kept
at 28 (per the review's correction, warm caches re-derive identically
under 41/28, so raising the floor is unnecessary) a v33 file sits in
the adopt-with-repairs window again and main's expectations hold; the
tier's warm-cache coverage stays in daily-cache-version-rederivation.

The tier-omits-slot test bills an implicit cache-write at the input
rate of the costs object in effect (getagentseal#1544), so the tiered expectation
is 1_000 * cacheWriteCostPerToken('gpt-5.5', tieredCosts).

Note on the Codex estimate path: an estimated prompt can cross a
long-context threshold and tier itself; measured corpora hold no
estimated calls that cross.
@ozymandiashh ozymandiashh added bug Something isn't working area: cli The codeburn CLI and its core parsing/reporting engine labels Sep 28, 2026
iamtoruk added a commit that referenced this pull request Sep 28, 2026
… where billing evidence exists (#1478)

* fix(pricing): carry long-context tier rates through bundling and price them where billing evidence exists

LiteLLM publishes *_above_<n>k_tokens rates for 418 models - OpenAI's
gpt-5.4/5.5/5.6 family above 272k, Anthropic above 200k, and 128k/256k/
512k tiers elsewhere - but the bundler flattened every entry to the
fixed five-slot tuple and calculateCost had no threshold dimension, so
a request past its threshold priced at the base rate forever (#1076).

The tuple gains an optional sixth slot {threshold, input, output,
cacheWrite, cacheRead}, the threshold parsed from the key suffix
because LiteLLM ships no numeric field (272k means 272,000; #1075
verified assuming 128k fabricates +64% spend). Old bundles parse
unchanged; CACHE_SCHEMA_VERSION moves to 5 (4 is taken on main by the
implicit cache-write billing) so a stale on-disk live-pricing cache
cannot reintroduce the old behavior; the live-fetch parser picks the
same tier up; service-tier _priority/_flex variants and the 1-hour
cache-write combination are not context thresholds and stay out.

A tier applies when the request's prompt tokens (input + cached input,
the existing grok-4.6 definition) reach the threshold, each published
rate replacing its base and omitted slots keeping the base.
Application is gated on billing evidence via TIERED_PRICING_PROVIDERS:
codex today, where the maintainer's corpus measurement shows the
surcharge passing through; a real Copilot session on gpt-5.6-terra
with ~6M-token prompts billed at the BASE rate, so Copilot keeps base
pricing until such evidence exists - applying it there would fabricate
spend, the exact class #1075 warned about. The audit report recomputes
through the same tier swap so recomputedTotalUSD keeps tracking
attributedCostUSD.

* fix(pricing): read tier rates only from the chosen threshold; e2e codex tier test

Repair pass from review: both tierOf implementations now collect rates
per threshold and read only from the largest one, so a hypothetical
two-tier entry can never mix the smaller tier's rates under the bigger
threshold; the bundler validates tier values exactly like the live
parser (finite, non-negative). A codex end-to-end test drives a real
rollout past gpt-5.5's 272k prompt threshold and asserts the tiered
arithmetic explicitly (a typo'd provider string in codex.ts would
leave the call at base rates and fail it), alongside the no-provider
base-rate control that keeps the real Copilot billing pin intact.
Comment fixes: the priceOverride wording, the grok pin's actual
resolution branch, and the threading note on TIERED_PRICING_PROVIDERS
for whoever adds the next provider.

* fix(pricing): recompute the audit tier per call and re-derive warm daily caches

Both review blockers:

- audit-report no longer feeds a bucket's SUMMED tokens into the
  per-call 272k threshold (a \,979 phantom gap on the reviewer's
  corpus, any tiered codex model clearing the threshold on the sum
  alone). The recompute accumulates per call, through the same tier
  swap calculateCost applies, with each call's own prompt total; a new
  fixture mixes one 300k call with 200 small ones whose sum blows past
  the threshold and pins that only the big call tiers. Web search
  stays on the base rates - it never participates in a tier.
- DAILY_CACHE_VERSION 33 -> 34 with MIN_SUPPORTED_VERSION raised to
  match, the cfdaa68 convention: a 33 file written under tierless
  pricing is below the floor, is not adopted as the finalized base,
  and its days re-derive off the warm session cache (\ of codex
  spend on the reviewer's corpus lives only in the daily cache). The
  migration tests pin the new floor contract: no version-diff repairs
  merge into a below-floor file, and the v30 adoption test tracks
  CURRENT.

Nits from review: the kimi precision tightening is reverted to (8, 5),
and the tieredCostsFor comment is rewrapped.

Measured on this machine's corpus, tier-only (branch vs the refresh
branch, same data): +\.43 lifetime codex - this corpus runs far
more sessions past 272k than the reviewer's 8-of-51,801 (+\.012964);
both numbers are real, the corpora differ.

* fix(pricing): preserve base alias selection when bundling context tiers

* fix(pricing): address the 28 Sep review - floor stays at 28, tier bills the implicit cache-write rate

Restore main's two carry-forward tests: with MIN_SUPPORTED_VERSION kept
at 28 (per the review's correction, warm caches re-derive identically
under 41/28, so raising the floor is unnecessary) a v33 file sits in
the adopt-with-repairs window again and main's expectations hold; the
tier's warm-cache coverage stays in daily-cache-version-rederivation.

The tier-omits-slot test bills an implicit cache-write at the input
rate of the costs object in effect (#1544), so the tiered expectation
is 1_000 * cacheWriteCostPerToken('gpt-5.5', tieredCosts).

Note on the Codex estimate path: an estimated prompt can cross a
long-context threshold and tier itself; measured corpora hold no
estimated calls that cross.

* fix(pricing): pin claude-opus-4 primary and keep carried fallback rows hygienic in the refreshed snapshot

The requested regeneration surfaced two upstream moves beside the tier
work. LiteLLM dropped `claude-opus-4`; a refresh carries dropped ids
into the fallback tier, but the Cursor-style alias `claude-4-opus`
resolves against primary rows, so the bare id fell to the snowflake
gateway row and under-priced by 3x. Pinned at Anthropic's list price
in MANUAL_ENTRIES so it stays primary. LiteLLM also repriced
grok-4.6's base input 2e-6 -> 1.25e-6 (tier rates unchanged); the
below-threshold literal follows. Both changes reproduce identically
with main's unchanged bundler on the same live responses.

Today's drops also exposed a gap in the #1483 carry-forward: primary
files legitimately hold @pin, date-suffixed and free-on-both rows, and
carrying those verbatim imports exactly what
tests/pricing-fallback-data.test.ts keeps out of the fallback file
(main's own next refresh fails those tests today). The carry now skips
@pin/date-suffixed keys (no query can arrive in those forms) and
free-on-both rows (an unpriced model falls to expected-free handling);
vendor-prefixed keys stay carriable since queries match them verbatim.

---------

Co-authored-by: Resham Joshi <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: cli The codeburn CLI and its core parsing/reporting engine bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants