fix: billing on failed responses stream requests anthropic and bedrock - #4842
Conversation
|
Warning Review limit reachedYou’ve reached a temporary PR review limit under our Fair Usage Limits Policy. Next review available in: 39 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews. How do review limits work?CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability. For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window. Please refer docs for additional details. Review details⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (4)
📝 WalkthroughWalkthroughAnthropic and Bedrock Responses streaming handlers now maintain a separate ChangesBilled usage accumulation for Responses streaming
Estimated code review effort: 3 (Moderate) | ~25 minutes Sequence Diagram(s)sequenceDiagram
participant Stream as Responses Stream Handler
participant Accum as Usage Accumulator
participant Ctx as Stream Context
participant Norm as normalizeCachedUsage
Stream->>Ctx: register billedUsage accumulator
loop each streamed event
Stream->>Accum: accumulate usage and billedUsage from event
Accum-->>Stream: updated counters and cache details
end
alt normal completion
Stream->>Norm: normalize billedUsage
else cancellation or timeout
Stream->>Norm: normalize billedUsage (deferred)
end
Norm-->>Ctx: folded cached tokens into prompt/total for billing
Suggested reviewers: 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
Comment |
|
|
This stack of pull requests is managed by Graphite. Learn more about stacking. |
Merge activity
|
The base branch was changed.
64745de to
38db0ce
Compare
* upstream/dev: feat(mcp): add per-MCP-server tool execution timeout (maximhq#4472) fix: billing on failed responses stream requests anthropic and bedrock (maximhq#4842) fix: gemini openai through signature compatibility (maximhq#4810) fix: cancelled state in logs (maximhq#4831) fix: perplexity responses api compatibility (maximhq#4813) docs: clarify two-layer token refresh behavior and disabled-client refresh token expiry (maximhq#4849) fix: skip background token refresh for disabled/unconfigured MCP clients and guarantee non-nil logger in sync workers (maximhq#4848)

Summary
When a streaming Responses API request is cancelled or times out mid-stream, usage tokens reported by intermediate events (e.g.
message_start,message_deltafor Anthropic, or early Bedrock Converse events) were being discarded. This meant callers could not be billed for provider-reported usage that arrived before the stream was interrupted. This PR fixes that by maintaining a mirroredBifrostLLMUsagestruct that is updated in lockstep with the in-flightResponsesResponseUsageand registered on the context so cancellation/timeout paths can retrieve and apply it.Changes
accumulateAnthropicResponsesUsageandaccumulateBedrockResponsesUsagehelper functions that simultaneously update both the streamingResponsesResponseUsageand a parallelBifrostLLMUsage(including all cache token detail fields: read, write, 5m, and 1h TTL buckets).HandleAnthropicResponsesStreamandBedrockProvider.ResponsesStream, abilledUsagepointer is now registered on the context viaBifrostContextKeyStreamAccumulatedUsageat stream start, so any mid-stream interruption can access already-accumulated usage.billedUsage(vianormalizeCachedUsage) when the context is cancelled, ensuring prompt token totals are correct even for partial streams.accumulateAnthropicResponsesUsageandaccumulateBedrockResponsesUsage, verifying that all token fields (including cache read/write details and TTL buckets) are mirrored correctly and that post-normalization totals are accurate.Type of change
Affected areas
How to test
go test ./core/providers/anthropic/... ./core/providers/bedrock/...Specifically, the new test cases
TestAccumulateAnthropicResponsesUsage_MirrorsCacheIntoBilledUsageandTestAccumulateBedrockResponsesUsage_MirrorsCacheIntoBilledUsagevalidate that:BifrostLLMUsage.normalizeCachedUsageis applied, prompt token totals correctly include cached token contributions.To validate the cancellation path end-to-end, initiate a Responses streaming request and cancel the context mid-stream; the usage reported on the context key
BifrostContextKeyStreamAccumulatedUsageshould reflect tokens seen up to the point of cancellation.Screenshots/Recordings
N/A
Breaking changes
Related issues
N/A
Security considerations
No auth, secrets, PII, or sandboxing implications. Usage data is internal billing metadata only.
Checklist
docs/contributing/README.mdand followed the guidelines