[Task] Integrate shared per-attempt LLM usage metering across supported protocols
Background
Parent #7949. This task owns the shared metering integration for LLM usage. A shared per-attempt usage contract is needed for auditing, the existing cost-ledger proposal and subsequent budgets. This issue does not own a second cost ledger.
Existing ownership and reuse
- #7934 owns the usage ledger, versioned prices and currency, effective time, historical estimated costs and export. Reuse its event contract; do not duplicate storage, pricing or export here.
- #7911 / merged PR #7937 delivered the OpenAI Responses output-token repair. Reuse its merged extraction and validate the remaining shared-metering coverage rather than implementing the same bug again.
- #7702 and open PR #7848 own reservation and reconciliation; metering must not introduce another debit or settlement chain.
- Reuse AI Proxy protocol adapters, bounded response observers/parsers and terminal events. The historical
87c22dde7completion-only baseline is superseded by the current-baseline matrix below. Coordinate client-versus-target protocol attribution with #7871; retain applicable Spring AI paths, not a new provider stack.
Implementation scope
- Inventory actual routed provider and protocol combinations first. Define one shared normalized per-upstream-attempt observation, identifying logical request and attempt, trusted identity, actual provider and model where known, protocol, outcome and usage source.
- Cover existing OpenAI Chat and Responses traffic first; verify Anthropic and Gemini only through actually supported routes, adding extraction adapters rather than inventing protocol support. Publish an explicit supported and unsupported coverage matrix.
- Observe before lossy protocol conversion when needed; handle JSON and fragmented SSE, cumulative versus incremental usage, input and output and supported cached-token categories without double counting.
- Keep reported zero, unavailable, estimated and provider-reported values distinct. Aggregate attempts into logical totals without losing retry and fallback costs. Feed the same authoritative measurements to audit, #7934 and budgeting.
Non-goals
Reimplementing #7911, a second ledger or pricing engine, new AI providers or retry/fallback policy, or treating estimates as provider invoices. Cost acceptance remains jointly tracked through #7934.
Acceptance criteria
- [ ] One documented usage contract and collection path is shared by consumers; repeated terminal events cannot double count an attempt.
- [ ] Supported provider and protocol fixtures cover input, output and cache categories and cumulative or incremental semantics; unsupported or missing usage is explicit, never fabricated zero.
- [ ] Native and converted output, streaming and buffered paths preserve response bytes and backpressure with bounded capture.
- [ ] Retry and fallback logical totals reconcile with independent attempt records and #7934 price inputs; no extra budget debit occurs.
- [ ] This capability is complete only when both this metering coverage and #7934 versioned estimated-cost acceptance are satisfied.
Tests
Actual AI Proxy conversion output, including #7937 regressions; chunk and flush-boundary and malformed or oversized stream fixtures; provider-specific JSON and SSE cases; failure, cancel, unknown and zero usage; concurrent tenant isolation and repeated observation; a cross-consumer reconciliation fixture. Reuse the existing parser regression suite.
Dependencies
Completed request/terminal-context and runtime-observability contracts, plus #7950. Coordinate the #7934 schema before implementation; incorporate #7911 and #7937 and account for #7848 integration. No duplicate ownership of those tasks is implied.
Current baseline and remaining delivery (2026-10-30)
Reviewed merged master 8046953ca. The baseline already has AiUsage, AiAttemptEvent, subscription-local attempt/terminal observation and a bounded upstream Chat/Responses usage tap. The earlier 87c22dde7 / completion-only description is historical. These foundations do not complete this issue: the token limiter still has its separate output-token accounting path, and logical terminal usage is the last attempt's snapshot rather than an all-attempt billing total.
Keep #8125 as AI Proxy integration, this issue as cross-protocol/cross-consumer metering, and #7934 as ledger/pricing. Publish a field-and-path matrix of implemented, missing, unsupported and unmerged-dependent behavior before adding another contract.
Remaining acceptance identifies input/output/cache categories, native versus converted protocol attribution, actual attempt identities, duplicate/cumulative-event handling and known-zero versus unknown. Supply one fixture whose independent attempt records reconcile with audit, ledger and budget consumers for primary, retry, fallback and cancellation. Unsupported categories stay explicit; do not derive billed totals from the last successful response.
Metering contributions to the five-layer inventory (2026-10-30)
For #8055, supply one authoritative per-attempt input/output/cache-token observation and its source/certainty, consumed consistently by audit, ledger and budget. Counts and distributions must separate actual attempts from logical requests and distinguish observed zero, unknown, unsupported and no outbound call. Retry/fallback/repair quantities cannot disappear into final-response usage or be counted twice through parent rollups.
Long-context reporting requires a declared threshold/model context capability and valid input-token evidence; absent model limits or usage stay unknown. Character count, payload bytes and SSE chunk count are not exact token counts. Provider cached-token quantities are separate from gateway exact/semantic-cache hits. Token metering itself does not measure tool monetary cost or task quality. Cover these distinctions in the cross-consumer fixture, including cancellation/partial streams and duplicate/cumulative reports.
/assign