Repository navigation
feat(billing): cached prompt pricing - #883
Conversation
Prompt tokens a provider serves from its prefix cache now settle at a
cache_read_price (OpenRouter pricing.input_cache_read) instead of the
input price, on the same validated cached_tokens count the consumer sees
in usage.prompt_tokens_details. The OpenRouter feed advertised
input_cache_read "0" while settlement billed cached tokens at the full
input rate; both now read the same payments.Rates, so a service-account
debit equals the feed's per-token math.
- payments: Rates{Input, Output, CacheRead} + Usage{Prompt, Cached,
Completion}; Rates.Cost / CostWithMinimum replace the CalculateCost*
family. Unset cache_read_price derives DefaultCacheReadDiscountPercent
(50%) off the input price via RatesFor.
- store: model_prices.cache_read_price (nullable), ModelPrice.CacheReadPrice
*int64, struct-based Set/GetModelPrice; usage.cached_tokens column and a
single RecordUsage(UsageRecord) replacing the five positional wrappers.
- api: settlement uses billableUsage + RatesFor; reservation unchanged
(worst case, no hit); PUT /v1/admin/pricing, PUT /v1/pricing and model
registration accept cache_read_price in [0, input_price]; GET /v1/pricing
publishes the effective rate; usage history carries cached_tokens;
billing.cached_prompt_tokens metric.
- tests: payments cost matrix incl. clamping; memory+postgres price and
usage round trips plus the legacy-table migration; settlement, feed
parity, handler validation and usage-history coverage.
Co-authored-by: Gajesh Naik <Gajesh2007@users.noreply.github.com>
Console: PriceEntry/UsageEntry carry cache_read_price and cached_tokens; the model catalog parses the rate (only when it is a valid discount off the input rate) and shows it in the row details; billing history marks cached tokens; API console examples reflect the new fields. Admin: models table gains a "Cached in $/1M" column reading model_prices.cache_read_price, deriving the coordinator's default when the row sets none (lib/pricing mirrors payments.DefaultCacheReadPrice). Co-authored-by: Gajesh Naik <Gajesh2007@users.noreply.github.com>
…workflow Rewrite invariant 5 (cached tokens bill at the cache-read rate and the bill matches the advertised price), document cache_read_price on every price writer, GET /v1/pricing and usage history, and update the stale CalculateCost*/RecordUsageFullWithPublicModel references. The register-model workflow takes an optional cache_read_price input. Co-authored-by: Gajesh Naik <Gajesh2007@users.noreply.github.com>
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
… review fixes - payments: termCost/saturatingAdd make Rates.Cost total over untrusted provider counts — a wrapped negative cost was refundable to a service consumer; absurd counts now saturate and meet the 2x reservation clamp. Rates.CacheReadDiscount for the revenue effect of a hit; tests for the 64-bit boundaries, negative rates and per-term flooring direction. - api: billing.cache_read_discount_micro_usd replaces the pre-gate token counter (already covered by cache_model_cached_tokens), emitted only for finalized non-free settlements; typed responses (types.ModelPriceQuote, PricingResponse, PriceUpdateResponse, registerModelResponse) replace the map splicing; billableUsage moves next to validCacheUsage. - store: RecordUsage logs a failed insert instead of discarding it; legacy usage-table migration test for cached_tokens; stale comment. - admin-ui: read cache_read_price through to_jsonb so /models survives a replica the coordinator has not migrated yet; import pricing helpers directly. - register-model workflow: bind the trimmed input once; document that an empty value clears a previously set rate. Rollback build script takes an optional cache_read_price. Stale docs (model-registry-format, model-migration, prefix-cache design status, admin-ui component). Co-authored-by: Gajesh Naik <Gajesh2007@users.noreply.github.com>
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: bcf075742a
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
Resolve conflicts with 70 master commits and port master's newer billing code to the Rates / ModelPrice / UsageRecord API this branch introduces. Conflicts: - payments: keep Rates/Usage (CalculateCost* family stays removed); take master's removal of the Payout alias. - store: single RecordUsage(UsageRecord) replaces master's surviving wrappers; RecordPayment/UsageRecordsSince/TelemetryEventRecord stay removed as on master; cached_tokens added to master's new postgres_usage_read.go; migrate-never-deletes test ported. - provider.go: price lookup keeps master's PromotionFreeTokens gate; usage recording moved into completionAccounting on master. - billing.md: master's fee wording plus the cache-read invariant. Port of master code written against the removed API: - completionAccounting records cached_tokens via store.RecordUsage (0 for a model-token promotion, which bills cached tokens at input). - priceModelTokens / modelTokenQuote / settleModelTokenPromotion take payments.Rates; RatesFor(_, false) equals the old default fallback. Review follow-ups (Codex threads on bcf0757): - DefaultCacheReadPrice no longer wraps for input > MaxInt64/50. - billing.cache_read_discount_micro_usd uses the settle function (payments.CacheReadDiscount), so the per-request minimum, uncollected charges and promotions report no discount. - /v1/completions and /v1/messages non-stream usage report cached tokens (prompt_tokens_details.cached_tokens; cache_read_input_tokens). - Console catalog resolves alias prices from embedded /v1/models pricing. - Design record body reverted (frozen); storage.md and api-contracts.md document the new columns and fields; OpenRouter legacy-format note.
…computed price The discount metric now requires totalCost == the computed settle price, so an overage clamp or a failed overage charge (capped at a bound the cold price hits too) no longer reports a discount. Tests: the metric under the minimum, at the clamp and at the computed price; a model-token promotion with a cache hit bills cached prompt tokens at the input rate and records cached_tokens=0. Both tests fail without the corresponding fix.
# Conflicts: # CHANGELOG.md # docs/reference/api-contracts.md
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: dc2ba0e641
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
# Conflicts: # CHANGELOG.md # docs/reference/api-contracts.md
… cached usage - usage.cached_tokens and model_prices.cache_read_price are added by plain ALTER TABLE ... ADD COLUMN IF NOT EXISTS instead of DO blocks that swallow every error, so a lock timeout or missing privilege aborts startup rather than booting with every price lookup missing (default rates) and every usage insert failing. Test holds a conflicting lock under a short lock_timeout; it fails with the old wrapped statements. - Streamed /v1/completions carries completionsUsage on its final chunk and streamed /v1/messages carries messagesUsage on message_delta, so a streamed caller can reconcile a cache-read discount too.
jonathan308
left a comment
There was a problem hiding this comment.
Approved — reviewed the money math, validation, migration, and provider-feed parity closely.
Billing math is the risk surface and it holds. Rates.Cost splits the prompt into uncached (×Input) and cached (×CacheRead) plus completion (×Output), each term floored, with CachedTokens clamped to [0, PromptTokens] and negative counts/rates billing as 0. Every product saturates via bits.Mul64/Div64 instead of wrapping — closing the pre-existing path where a wrapped negative cost was refundable to a service consumer. DefaultCacheReadPrice splits around /100 so a max-int64 input can't overflow into a negative rate. CacheReadDiscount reuses the same settlement function so a request at the per-request minimum correctly reports no discount.
Can't be exploited upward. cache_read_price ≤ input_price is enforced at every writer (admin, provider-custom, register) and rejected rather than clamped; a cache hit can only lower a bill. Trust boundary unchanged — cached_tokens is provider-reported like prompt/completion, and a provider reporting a fake hit only reduces its own payout.
Migration fails closed. usage.cached_tokens and model_prices.cache_read_price use plain ALTER … ADD COLUMN IF NOT EXISTS (not the exception-swallowing DO blocks), so a lock timeout or privilege failure aborts startup rather than silently billing at defaults / dropping usage rows — with a test asserting it.
Feed == settlement for the service channel: TestServiceSettlementMatchesOpenRouterFeedCachePricing asserts the debit equals the advertised per-token math, and input_cache_read moves from the hardcoded "0" to the real rate. Legacy flat-format usage of the documented key is correct; v2 migration is properly scoped as separate.
CI green on head 3da224b (Coordinator, Provider, E2E Integration, Prompt Sidecar, Release Integrity all pass), MERGEABLE. Two notes I'm flagging as release-ops, not blockers: the boot ALTER takes ACCESS EXCLUSIVE on usage — check pg_stat_activity before restart as the PR says; and the every-row-half-price-on-deploy effect on provider payouts is intentional and operator-tunable. Nice catch that the old billing invariant 5 was factually wrong ("cached tokens free").
Summary
Prompt tokens a provider serves from its prefix cache (the existing memory/SSD prefix cache, reported in the terminal
usage.cached_tokensand surfaced to consumers asprompt_tokens_details.cached_tokens) now bill at a per-modelcache_read_priceinstead of the input price. The same rate is advertised to OpenRouter aspricing.input_cache_readin the provider feed — previously the feed declared"0"while settlement billed cached tokens at the full input rate, so a service-account debit disagreed with what OpenRouter computes from the usage and the feed. Rows without an explicit rate derive half the input price (DefaultCacheReadDiscountPercent = 50). Caching is provider-initiated, so per OpenRouter's guidance ("omit SKUs you don't bill") noinput_cache_writeSKU is declared.Behavior
flowchart LR subgraph Before A1["inference_complete<br/>prompt=10k, cached=8k, completion=500"] --> B1["validCacheUsage<br/>feeds routing.cache_* metrics only"] B1 --> C1["calculateCost(prompt, completion)<br/>cached tokens billed at the full input price"] C1 --> D1["debit consumer, pay provider"] D1 --> E1["usage row and /v1/completions, /v1/messages usage<br/>no cached count"] F1["GET /v1/models/openrouter"] --> G1["pricing.input_cache_read = '0'<br/>feed ≠ settlement"] end subgraph After A2["inference_complete<br/>prompt=10k, cached=8k, completion=500"] --> B2["validCacheUsage<br/>malformed report → cached = 0"] B2 --> C2["Rates.Cost<br/>(prompt − cached) × input<br/>+ cached × cache_read<br/>+ completion × output"] B2 --> M2["model-token grant request<br/>priceModelTokens: every prompt token at input<br/>(unchanged, records cached = 0)"] C2 --> D2["debit consumer, pay provider<br/>refund the discount vs. the reservation"] D2 --> E2["usage row, GET /v1/payments/usage,<br/>/v1/completions and /v1/messages usage<br/>(non-stream and stream) carry cached tokens"] F2["GET /v1/models/openrouter"] --> G2["pricing.input_cache_read = cache-read rate<br/>feed == settlement"] H2["PUT /v1/admin/pricing, PUT /v1/pricing,<br/>POST /v1/admin/models/register"] --> I2["optional cache_read_price<br/>0 ≤ value ≤ input_price"] J2["coordinator boot"] --> K2["ADD COLUMN cached_tokens, cache_read_price<br/>failure aborts startup"] endCode
flowchart LR subgraph Before S1["store.GetModelPrice<br/>→ (in, out, ok)"] --> P1["payments.CalculateCostWithOverrides*<br/>(model, prompt, completion, in, out, hasCustom)"] P1 --> H1["handleCompleteAt: totalCost"] S1 --> T1["settleModelTokenPromotion / priceModelTokens<br/>(model, …, in, out, custom)"] S1 --> O1["buildModelPricing(in, out)<br/>input_cache_read hardcoded '0'"] H1 --> U1["completionAccounting →<br/>RecordUsageFullWithPublicModel (10 positional args)"] Y1["migrate: DO block, EXCEPTION WHEN others<br/>(pattern for added columns)"] end subgraph After W2["modelPriceInput.validate<br/>(api/model_pricing.go)"] --> S2["store.GetModelPrice<br/>→ (ModelPrice with CacheReadPrice *int64, ok)"] S2 --> R2["payments.RatesFor<br/>→ Rates{Input, Output, CacheRead}"] R2 --> P2["Rates.Cost / CostWithMinimum<br/>(Usage{Prompt, Cached, Completion})<br/>saturating arithmetic"] P2 --> H2["handleCompleteAt<br/>billableUsage(msg.Usage) → totalCost"] H2 --> U2["completionAccounting →<br/>store.RecordUsage(UsageRecord{…, CachedTokens})"] H2 --> X2["payments.CacheReadDiscount(settle, usage)<br/>billing.cache_read_discount_micro_usd"] R2 --> T2["settleModelTokenPromotion / priceModelTokens(Rates)<br/>same math as before"] R2 --> O2["buildModelPricing(Rates)<br/>input_cache_read = FormatPerTokenUSD(CacheRead)"] R2 --> Q2["modelPriceQuote → types.ModelPriceQuote<br/>GET /v1/pricing, PUT responses, register response"] R2 --> V2["reservationCost<br/>no cache hit assumed"] B2["validCacheUsage / clearCacheUsage<br/>(msg.Usage)"] --> P2 B2 --> G2["completionsUsage / messagesUsage<br/>non-stream responses and stream terminal events"] Y2["migrate: plain ALTER TABLE … ADD COLUMN IF NOT EXISTS<br/>for cached_tokens, cache_read_price"] endWhat changed
coordinator/payments/pricing.go):Rates{Input, Output, CacheRead},Usage{PromptTokens, CachedTokens, CompletionTokens},RatesFor,DefaultRates,DefaultCacheReadPrice,Rates.Cost(no floor, ≥1 µUSD for nonzero usage) /Rates.CostWithMinimum,CacheReadDiscount(settle, usage).DefaultCacheReadPriceis computed without 64-bit overflow. Replaces theCalculateCost*family.CachedTokensis clamped to[0, PromptTokens]; negative counts/rates bill as 0; every product saturates viabits.Mul64/Div64instead of wrapping (a wrapped negative cost was refundable to a service consumer — pre-existing incalculateCost, closed here).model_prices.cache_read_price BIGINT NULL(ALTER … IF NOT EXISTS on boot; NULL = unset → derived),ModelPrice.CacheReadPrice *int64,SetModelPrice(ModelPrice)/GetModelPrice → (ModelPrice, bool);usage.cached_tokens INTEGER NOT NULL DEFAULT 0; the five positionalRecordUsage*wrappers collapse intoRecordUsage(UsageRecord), which now logs a failed insert instead of discarding it. Postgres price cache stores the full row (deep-copied).handleCompleteAtuses the validatedcached_tokens(clearCacheUsagealready zeroes malformed reports before billing). Reservation is unchanged — worst case assumes no hit, settlement refunds the discount.PUT /v1/admin/pricing,PUT /v1/pricing,POST /v1/admin/models/registersharemodelPriceInput(cache_read_priceoptional,0 ≤ v ≤ input_price; above input is rejected, not clamped; omitted = unset, which also clears a previously set rate). Typed responses:types.PricingResponse/PriceUpdateResponse/ModelPriceQuote,registerModelResponse.GET /v1/payments/usageentries carrycached_tokens. New count metricbilling.cache_read_discount_micro_usd{model}(µUSD the settled bill was below the cold price, through the same settle function so the per-request minimum is honoured), emitted only when a cache hit settled at its computed price (not free, not zeroed, not capped by the overage clamp, not a model-token promotion)./v1/completionsreportsusage.prompt_tokens_details.cached_tokens(streams: on the final chunk);/v1/messagesreportscache_read_input_tokensand excludes those tokens frominput_tokens(Anthropic semantics; streams: onmessage_delta).PriceEntry.cache_read_price,UsageEntry.cached_tokens; catalog carries the rate (only when it's a valid discount) and shows "Cached input / 1M" in row details; a public alias (listed under its alias id while/v1/pricingis keyed by the build) resolves input/output/cached rates from its embedded/v1/modelspricing (catalogPrice); billing history marks cached tokens; API console examples updated.lib/pricing.tsmirrors the coordinator default.cache_read_priceis read viato_jsonb(mp) ->> 'cache_read_price'so/modelskeeps working against a replica the coordinator has not migrated yet (verified against both schemas on a real Postgres).reference/pricing-model.md,architecture/billing.md(invariant 5 rewritten — it previously claimed cached tokens were "free"; they were billed at the full input price),consumer/billing.md,consumer/models.md,reference/model-registry-format.md,reference/api-contracts.md(new fields on the pricing, usage, registration, completions and messages contracts),architecture/storage.md(new columns),operations/model-migration.md, admin-ui component doc, stale symbol references; every changed page restamped. The frozen prefix-cache design record is left unchanged.register-model.ymlandscripts/preposition-rollback-build.shtake an optionalcache_read_price.Merge with master (2026-09-28)
Master moved 72 commits after this branch was cut (merged through #1206). Conflicts were resolved in favour of this branch's
Rates/ModelPrice/UsageRecordAPI, keeping every master behaviour:(in, out, custom)API.priceModelTokens,modelTokenQuote,settleModelTokenPromotionand the promotion top-ups now takepayments.Rates;RatesFor(_, false)is the old 50 000 / 200 000 fallback, so promotion pricing is numerically unchanged. Promotion settlements get no cache-read discount (which prompt tokens a grant covers, and at what rate the sponsor values them, is an open product question) and recordcached_tokens = 0. Service consumers never enter that path, so the OpenRouter parity is unaffected.completionAccounting(refactor(coordinator): share routing, trust, accounting and request operations #909) now owns usage recording; it writesstore.RecordUsage(UsageRecord{…, CachedTokens}). Master'spr.PromotionFreeTokens == 0gate on provider custom pricing is kept.RecordPayment,UsageRecordsSince,TelemetryEventRecord, thePayoutalias and the wallet-price cleanup; they stay removed, andcached_tokensis added to master's newpostgres_usage_read.go.OpenRouter docs check
pricing.{prompt, completion, image, request, input_cache_read}, USD per token as strings), which OpenRouter says "remains supported for existing integrations" (legacy format).input_cache_readis a documented per-token key there; the schema has no cache-write key.cached_promptSKU withimplicit: true. The code comment now says this correctly. Migrating to v2 is a separate change.usage.prompt_tokens_details.cached_tokens(Chat Completions) /usage.input_tokens_details.cached_tokens(Responses) (prompt caching). This is the count we bill on.TestServiceSettlementMatchesOpenRouterFeedCachePricingasserts(prompt−cached)×prompt + cached×input_cache_read + completion×completion; confirm against the first OpenRouter invoice after deploy.Test plan
DATABASE_URL=… go test ./coordinator/...against a throwaway local PostgreSQL 16 — 25 packages pass; the only failure iscoordinator/datadogTestHistogramOrGaugeUsesConfiguredTransport, which fails identically onmasterin this environment (UDP transport, package untouched).TestModelPriceCacheReadRoundTrip(unset/explicit/0/clear, no pointer aliasing),TestPostgresModelPriceCacheTracksCacheRead,TestPostgresModelPricesMigrationAddsCacheReadColumnandTestPostgresUsageMigrationAddsCachedTokensColumn(legacy table → migrate → readable),TestUsageRecordCachedTokens.CacheReadDiscount, service-cost parity with the advertised per-token strings.coordinator/api/cache_pricing_test.go): settlement with explicit / derived / zero cache-read rate, provider-custom rate, malformed cache report billed at full input price, service-account debit equals the feed'sprompt/input_cache_read/completionper-token math,PUT /v1/admin/pricingvalidation matrix throughhttptest.NewServer(srv.Handler()),GET /v1/pricingshape,PUT /v1/pricing,GET /v1/payments/usage(in-memory and persisted paths).go test -raceon payments, store and the new api billing tests;gofmt -lclean;go vet ./coordinator/...clean.POST /v1/admin/models/register(manifest + file HEADs verified againstmodels.darkbloom.ai), one withcache_read_price: 8400and one without →GET /v1/pricingshows8400and the derived21000;GET /v1/models/openrouteradvertisesinput_cache_read0.0000000084/0.000000021;cache_read_price > input_price→ 400.cd console-ui && npx eslint src/ && npx vitest run && npm run build— clean.cd admin-ui && npx eslint src/ && npx vitest run && npx tsc --noEmit— clean.go build ./... && go vet ./...clean;go test ./...(memory store) all packages pass;DATABASE_URL=<throwaway PG16> go test ./store/... ./payments/...pass, includingTestModelPriceCacheReadRoundTrip,TestPostgresModelPriceCacheTracksCacheRead, both migration tests,TestUsageRecordCachedTokens,TestPostgresMigrateNeverDeletesModelPrices;go test -raceon payments and the billing/promotion/usage api tests; newTestDefaultCacheReadPriceNeverWraps, minimum-awareTestCacheReadDiscount,TestGenericEndpointResponsesReportCachedTokens,TestCacheReadDiscountMetricCountsOnlySettledDiscounts,TestModelTokenPromotionBillsCachedPromptAtInputRate,TestGenericEndpointStreamsReportCachedTokensandTestPostgresBillingColumnMigrationFailureAbortsStartup(each fails with its fix reverted); consoleeslint(0 errors) +vitest(798 pass, incl. aliascatalogPrice) +next build; admineslint+vitest+tsc;make docs-check(316 files OK).Components touched
Protocol / interface changes
HTTP only; no WebSocket protocol change (the provider already reports
cached_tokens). Additive fields onGET /v1/pricing,GET /v1/payments/usage, the pricing writers and the model feed. Schema: two nullable/defaulted columns added idempotently on boot; rollback-safe (an older coordinator ignores both). The*_usdstrings ofPUT /v1/admin/pricing/PUT /v1/pricingdrop the trailing " per 1M tokens" to matchGET /v1/pricing(nothing in the repo parsed them).Notes for reviewers
cache_read_priceis set, and the feed'sinput_cache_readmoves from"0"to that rate. Provider payouts on cache hits drop accordingly. Rollback is a redeploy. The 50% default is deliberately conservative (OpenAI's standard prompt-caching discount; the market is trending to ~0.1×); operators tune per model viaPUT /v1/admin/pricing.cached_tokensis provider-reported likeprompt_tokens/completion_tokens. A provider can only lower its own payout by reporting a hit; a cache hit can never raise a bill (clamped,cache_read_price ≤ input_priceenforced at every writer, saturating arithmetic).cache_read_priceon a writer resets the row to derived. This is the safe direction: "keep the old explicit value" could leavecache_read > inputafter an input-price change. Documented on the workflow input and inmodel-registry-format.md.cache_read_priceinGET /v1/pricing.ALTER TABLE usage ADD COLUMN IF NOT EXISTS(metadata-only with a constant default, but it takes anACCESS EXCLUSIVElock onusagelike the existingkey_id/public_modelALTERs). Checkpg_stat_activityfor long-running reads onusagebefore the restart, or the ALTER queues behind them and blocks the boot.401 API key is invalidfrom the Anthropic API. It fails the same way on every PR since at least 2026-09-13, so it is a repo-wide secret problem, not a finding here.usage.cached_tokensandmodel_prices.cache_read_priceare added by plainALTER TABLE … ADD COLUMN IF NOT EXISTS, not the exception-swallowingDOblocks used by older columns. If either cannot be added (a lock timeout, a missing privilege), the coordinator refuses to start rather than billing at the default rates and dropping usage rows (TestPostgresBillingColumnMigrationFailureAbortsStartup)./v1/modelsand the OpenRouter feed price a public alias from its primary build, while settlement prices the build that served the request (pre-existing). Feed == debit therefore holds for an alias only when the builds behind it share their price rows;preposition-rollback-build.shnow copiescache_read_pricefor that reason. Documented in billing invariant 5.8305ac7aa.DeleteModelPricedoes not invalidate the Postgres 30 s price cache (pre-existing), so a deleted provider custom price can linger for up to 30 s.Need help on this PR? Tag
@codesmith-botwith what you need. Autofix is disabled.