Keep billed usage when a run stops before a continued response completes
No issue: found while auditing model-reliability accounting.
A continued response is one a provider paused and the agent loop continues: Anthropic pause_turn, OpenAI background mode. Each of its segments is billed, but on a non-streamed request their usage only reached the run's usage when the continuation completed or raised an Exception. So the billed usage was lost when the run stopped earlier:
- Usage limit. The limit check between segments raised before the partial response was handed back to the request handler. Example: the first segment reports 100 input tokens against
input_tokens_limit=5.- Before: the
usage=object passed to the run stayedRunUsage(). - After:
RunUsage(input_tokens=100, output_tokens=1).
- Before: the
- Cancel or timeout during the continuation request. These are
BaseExceptions (CancelledError), which the handler's partial-usage branch didn't catch. Example: the first segment reports 10 input / 2 output tokens, thentimeout=fires orcancel()is called during the next call.- Before:
RunTimedOut.usage == RunUsage(). - After:
RunUsage(input_tokens=10, output_tokens=2).
- Before:
The fix, in _agent_graph.py:
model_request()reports each segment's merged response throughon_progressbefore checking it against the limits, rather than after.- The non-streamed handler records that partial response's usage in a single
except BaseExceptionbranch, through_record_response_usage(..., request_context=req_ctx). It then re-raises anything that isn't anException, and hands the rest to the error hooks as before. - Recording goes through
_billed_by_request, so a run that resumes a suspended response from history still counts only what it billed beyond that response. A test checks this.
Requests that aren't continued don't change: the partial-usage branch only acts on a response on_progress reported, and a request that completes commits its usage once, as before. Streamed continuations already keep this usage.
FallbackModel-rejected responses lose their usage on cancel or timeout too. That is handled separately, with the ModelFallback work in #9348.
Checklist
- No breaking changes in accordance with the version policy.
- Any permitted compatibility impact has a label, warning, migration, release note, and exact API-check waiver.
- PR title is fit for the release changelog.
š¤ Generated with Claude Code