[Feature][AI] Add a usage ledger with versioned pricing and cost attribution
Goal
Allow operators to explain AI usage and estimated cost by tenant/application, provider and actual model, then reconcile those records with provider reports.
Existing capabilities and boundary
#7702 and PR #7848 own token-budget reservations and settlement. #7911 addresses missing Responses-protocol usage accounting. Reuse normalized usage and settlement observations; do not implement a second admission counter or present reserved estimates as actual billed usage.
MVP
- Define a versioned usage event: namespace/authorized tenant/application, provider, requested/resolved model where known, operation/attempt identity, timestamps, protocol, final outcome and available token categories.
- Distinguish provider-reported usage, estimated usage, reported zero and unavailable usage. Record attempted upstream work separately from the final logical request so retries/fallback costs are attributable without double counting.
- Attach a versioned operator-supplied price schedule with effective dates, currency and supported categories (for example input, output and cached tokens). Preserve the price version and raw normalized quantities needed to recompute an estimate.
- Add bounded asynchronous delivery to a pluggable ledger sink and basic aggregation/export. Define delivery guarantees, idempotency keys, retention and failure visibility; do not block gateway traffic on a remote billing database.
- Begin with one documented provider/protocol and fixed token pricing. Reconciliation against provider exports can be a follow-up; negotiated discounts, taxes and unsupported pricing must remain explicit unknowns.
Acceptance criteria
- [ ] Buffered and streaming success, failure, cancellation, missing usage, retry and fallback cases create correctly scoped records with no false exact cost.
- [ ] Duplicate delivery is idempotent within a documented retention window; queue overflow/crash loss is observable and the delivery guarantee is stated honestly.
- [ ] Historical estimates retain their original price version; revaluation produces a separate auditable result rather than silently rewriting history.
- [ ] Tenant authorization applies to queries/exports. Prompts, responses and credentials are excluded by default; event volume, cardinality and retention are bounded.
- [ ] Usage extraction is shared with existing accounting and tested across supported formats, including #7911's protocol distinction.
- [ ] A small fixture reconciles ledger totals, attempts and price calculations against known inputs; unavailable pricing is never displayed as zero cost.
Related: #7702, PR #7848 and #7911. Cost values are estimates unless a provider reconciliation establishes otherwise.
Executable MVP and event mapping (2026-10-30)
Map AiAttemptEvent / AiTerminalEvent and #7955 quantities from master 8046953ca into the existing versioned ledger design. Terminal usage is the last attempt, not all billable work. Assigned HTTP status, delivery, unknown usage and reserved estimates are not invoices.
Start with one documented protocol and operator-supplied fixed token prices/effective dates. Check in network-independent input events and expected rows/totals for primary success, failed-primary-plus-retry, fallback, duplicate delivery, known zero, missing usage and cancellation. An opt-in repair generation (#8257) is additional attributable work, not a free retry.
Specify the join/idempotency key, authoritative quantities and price revision per row. Revaluation is separate from historical estimates. Verify tenant-authorized export and bounded observable delivery through #7950 instead of adding another logging transport. Advanced pricing categories remain explicitly unsupported until measured and priced.
Cost metric populations and supported pricing (2026-10-30)
Implement the cost layer of #8055 through this ledger and #7955 quantities: input/output tokens, cost per request and authorized tenant/app/feature, fallback cost, declared long-context cohorts and applicable cache categories. Requested dimensions require trustworthy mapping/provenance; missing app/feature/model information stays unknown. Prefer ledger queries/exports over unbounded tenant/app/feature metric labels.
Record all actual primary/retry/fallback/repair work once; do not sum both parent rollups and their constituent attempts. Define fallback cost as the declared fallback attempt subset while total request cost still includes failed primaries/retries. Unknown/estimated quantities or unavailable prices are not zero billed cost. Preserve price/currency/effective-time provenance and separate provider reconciliation from an estimate.
Gateway exact-cache hits, semantic-cache hits and provider cached-token prices have different denominators and quality implications (#8049/#8050). Serving a cache hit must not replay the cached answer's original usage as new provider billing; it does not prove total request/tool/retrieval cost is zero. Long-context ratios require declared model/context or explicit token thresholds and valid measurements; byte/character length is not an exact token count.
tool_call_cost needs separately declared measured units and an approved price category; no implicit conversion from LLM tokens or invocation counts. Keep it unsupported/unknown in the initial one-protocol fixed-token MVP until its measurement/pricing contract is accepted, rather than silently expanding this task into another MCP billing system. Add deterministic expected-total fixtures for attribution gaps, cache-served requests, fallback, duplicate events and absent prices.
/assign