Skip to content

feat(billing): cached prompt pricing - #883

Merged
Gajesh2007 merged 12 commits into
masterfrom
cursor/cached-input-pricing-3446
Sep 28, 2026
Merged

Gajesh2007 merged 12 commits into
masterfrom
cursor/cached-input-pricing-3446

Conversation

@Gajesh2007

@Gajesh2007 Gajesh2007 commented Sep 10, 2026 •

Copy link
Copy Markdown
Member

Summary

Prompt tokens a provider serves from its prefix cache (the existing memory/SSD prefix cache, reported in the terminal usage.cached_tokens and surfaced to consumers as prompt_tokens_details.cached_tokens) now bill at a per-model cache_read_price instead of the input price. The same rate is advertised to OpenRouter as pricing.input_cache_read in 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") no input_cache_write SKU 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"]
  end
Loading

Code

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"]
  end
Loading

What changed

  • payments (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). DefaultCacheReadPrice is computed without 64-bit overflow. Replaces the CalculateCost* family. CachedTokens is clamped to [0, PromptTokens]; negative counts/rates bill as 0; every product saturates via bits.Mul64/Div64 instead of wrapping (a wrapped negative cost was refundable to a service consumer — pre-existing in calculateCost, closed here).
  • store: 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 positional RecordUsage* wrappers collapse into RecordUsage(UsageRecord), which now logs a failed insert instead of discarding it. Postgres price cache stores the full row (deep-copied).
  • api: settlement in handleCompleteAt uses the validated cached_tokens (clearCacheUsage already 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/register share modelPriceInput (cache_read_price optional, 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/usage entries carry cached_tokens. New count metric billing.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/completions reports usage.prompt_tokens_details.cached_tokens (streams: on the final chunk); /v1/messages reports cache_read_input_tokens and excludes those tokens from input_tokens (Anthropic semantics; streams: on message_delta).
  • console-ui: 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/pricing is keyed by the build) resolves input/output/cached rates from its embedded /v1/models pricing (catalogPrice); billing history marks cached tokens; API console examples updated.
  • admin-ui: models table "Cached in $/1M" column (explicit or "(derived)"); lib/pricing.ts mirrors the coordinator default. cache_read_price is read via to_jsonb(mp) ->> 'cache_read_price' so /models keeps working against a replica the coordinator has not migrated yet (verified against both schemas on a real Postgres).
  • docs/ops: 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.yml and scripts/preposition-rollback-build.sh take an optional cache_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 / UsageRecord API, keeping every master behaviour:

  • Model-token promotions (Add claimable model token grants and Bonsai SLA #1130) were written against the removed (in, out, custom) API. priceModelTokens, modelTokenQuote, settleModelTokenPromotion and the promotion top-ups now take payments.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 record cached_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 writes store.RecordUsage(UsageRecord{…, CachedTokens}). Master's pr.PromotionFreeTokens == 0 gate on provider custom pricing is kept.
  • chore: remove pre-0.9.5 compat code, dead tests and Python/Rust/Solana-era leftovers #1208 removed RecordPayment, UsageRecordsSince, TelemetryEventRecord, the Payout alias and the wallet-price cleanup; they stay removed, and cached_tokens is added to master's new postgres_usage_read.go.

OpenRouter docs check

  • Our feed uses OpenRouter's legacy flat provider format (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_read is a documented per-token key there; the schema has no cache-write key.
  • The "do not zero-stuff / omit SKUs you don't bill" guidance quoted earlier comes from the current v2 format (provider integration), where pricing is a per-modality array and provider-initiated caching is a cached_prompt SKU with implicit: true. The code comment now says this correctly. Migrating to v2 is a separate change.
  • OpenRouter documents cache reads to consumers as usage.prompt_tokens_details.cached_tokens (Chat Completions) / usage.input_tokens_details.cached_tokens (Responses) (prompt caching). This is the count we bill on.
  • Not verifiable from public docs: OpenRouter's internal formula for pricing a legacy provider's cached tokens. TestServiceSettlementMatchesOpenRouterFeedCachePricing asserts (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 is coordinator/datadog TestHistogramOrGaugeUsesConfiguredTransport, which fails identically on master in this environment (UDP transport, package untouched).
  • New store tests (memory + postgres): TestModelPriceCacheReadRoundTrip (unset/explicit/0/clear, no pointer aliasing), TestPostgresModelPriceCacheTracksCacheRead, TestPostgresModelPricesMigrationAddsCacheReadColumn and TestPostgresUsageMigrationAddsCachedTokensColumn (legacy table → migrate → readable), TestUsageRecordCachedTokens.
  • New payments tests: cost matrix with cached tokens, clamping, saturation at the 64-bit boundaries (2^63/2^80/2^83/2^100 products, negative rates), per-term flooring direction (≤ 3 µUSD under the exact math), CacheReadDiscount, service-cost parity with the advertised per-token strings.
  • New api tests (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's prompt/input_cache_read/completion per-token math, PUT /v1/admin/pricing validation matrix through httptest.NewServer(srv.Handler()), GET /v1/pricing shape, PUT /v1/pricing, GET /v1/payments/usage (in-memory and persisted paths).
  • go test -race on payments, store and the new api billing tests; gofmt -l clean; go vet ./coordinator/... clean.
  • Live run: coordinator built from this branch (memory store), two real catalog models registered through POST /v1/admin/models/register (manifest + file HEADs verified against models.darkbloom.ai), one with cache_read_price: 8400 and one without → GET /v1/pricing shows 8400 and the derived 21000; GET /v1/models/openrouter advertises input_cache_read 0.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.
  • Two independent review passes (correctness/money math; edge cases/UI/docs) — findings fixed in the last commit.
  • After the master merge: go build ./... && go vet ./... clean; go test ./... (memory store) all packages pass; DATABASE_URL=<throwaway PG16> go test ./store/... ./payments/... pass, including TestModelPriceCacheReadRoundTrip, TestPostgresModelPriceCacheTracksCacheRead, both migration tests, TestUsageRecordCachedTokens, TestPostgresMigrateNeverDeletesModelPrices; go test -race on payments and the billing/promotion/usage api tests; new TestDefaultCacheReadPriceNeverWraps, minimum-aware TestCacheReadDiscount, TestGenericEndpointResponsesReportCachedTokens, TestCacheReadDiscountMetricCountsOnlySettledDiscounts, TestModelTokenPromotionBillsCachedPromptAtInputRate, TestGenericEndpointStreamsReportCachedTokens and TestPostgresBillingColumnMigrationFailureAbortsStartup (each fails with its fix reverted); console eslint (0 errors) + vitest (798 pass, incl. alias catalogPrice) + next build; admin eslint + vitest + tsc; make docs-check (316 files OK).

Components touched

  • coordinator (Go)
  • provider (Rust, legacy)
  • provider-swift (Swift CLI)
  • console-ui (Next.js)
  • enclave (Swift)
  • infra / CI / release
  • docs

Protocol / interface changes

  • No protocol/interface changes
  • Yes — described above and matching side updated

HTTP only; no WebSocket protocol change (the provider already reports cached_tokens). Additive fields on GET /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 *_usd strings of PUT /v1/admin/pricing / PUT /v1/pricing drop the trailing " per 1M tokens" to match GET /v1/pricing (nothing in the repo parsed them).

Notes for reviewers

  • Rollout effect: on deploy every existing price row — platform and provider custom — starts billing cache hits at half its own input price until an explicit cache_read_price is set, and the feed's input_cache_read moves 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 via PUT /v1/admin/pricing.
  • Trust boundary is unchanged: cached_tokens is provider-reported like prompt_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_price enforced at every writer, saturating arithmetic).
  • Omitting cache_read_price on a writer resets the row to derived. This is the safe direction: "keep the old explicit value" could leave cache_read > input after an input-price change. Documented on the workflow input and in model-registry-format.md.
  • Deploy order: coordinator before admin-ui is no longer required (schema-tolerant read), but the coordinator migration must have run before any consumer relies on cache_read_price in GET /v1/pricing.
  • Deploy: the boot migration adds one more ALTER TABLE usage ADD COLUMN IF NOT EXISTS (metadata-only with a constant default, but it takes an ACCESS EXCLUSIVE lock on usage like the existing key_id/public_model ALTERs). Check pg_stat_activity for long-running reads on usage before the restart, or the ALTER queues behind them and blocks the boot.
  • Threat Model Review fails with 401 API key is invalid from 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.
  • Startup fails closed on the billing columns: usage.cached_tokens and model_prices.cache_read_price are added by plain ALTER TABLE … ADD COLUMN IF NOT EXISTS, not the exception-swallowing DO blocks 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).
  • Alias parity: /v1/models and 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.sh now copies cache_read_price for that reason. Documented in billing invariant 5.
  • An independent post-merge review (merge fidelity, money math, store, usage objects) passed; its test-gap and metric-overstatement findings are fixed in 8305ac7aa.
  • Not changed, worth a follow-up: DeleteModelPrice does not invalidate the Postgres 30 s price cache (pre-existing), so a deleted provider custom price can linger for up to 30 s.
Open in Web Open in Cursor 

View with [code]smith Autofix with [code]smith
Need help on this PR? Tag @codesmith-bot with what you need. Autofix is disabled.

cursoragent and others added 3 commits September 10, 2026 02:42
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>
@vercel

vercel Bot commented Sep 10, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
d-inference Ready Ready Preview Sep 28, 2026 7:16am UTC
d-inference-console-ui-dev Ready Ready Preview Sep 28, 2026 7:16am UTC
d-inference-landing Ready Ready Preview Sep 28, 2026 7:16am UTC
eigen-homepages-darkbloom Ready Ready Preview Sep 28, 2026 7:16am UTC

Request Review

… 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>
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 10, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-28T07:19:58.133004Z 3da224b New commits
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Comment thread coordinator/payments/pricing.go Resolved
Comment thread docs/architecture/billing.md Resolved
Comment thread coordinator/store/postgres.go Resolved
Comment thread coordinator/api/types/types.go Resolved
Comment thread coordinator/api/provider.go Resolved
Comment thread coordinator/api/provider.go Resolved
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

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Comment thread coordinator/store/postgres.go Resolved
# 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.
@Gajesh2007 Gajesh2007 changed the title feat(billing): cached prompt pricing — per-model cache_read_price, advertised as OpenRouter input_cache_read feat(billing): cached prompt pricing Sep 28, 2026

@jonathan308 jonathan308 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.

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

@Gajesh2007
Gajesh2007 merged commit 4d67936 into master Sep 28, 2026
34 of 35 checks passed
@Gajesh2007
Gajesh2007 deleted the cursor/cached-input-pricing-3446 branch September 28, 2026 19:31

This branch was successfully deployed

4 active deployments
Preview – d-inference-console-ui-dev — 3da224b8 Deployed Sep 28, 2026 by vercel[bot]
Preview – d-inference — 3da224b8 Deployed Sep 28, 2026 by vercel[bot]
Preview – eigen-homepages-darkbloom — 3da224b8 Deployed Sep 28, 2026 by vercel[bot]
Preview – d-inference-landing — 3da224b8 Deployed Sep 28, 2026 by vercel[bot]
benchmarks — 3da224b8 Deployed Sep 28, 2026 by Gajesh2007 via E2E Benchmarks #1718
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants