fix(agent): preserve model response in history when ModelRetry crosses usage limits

CH
21d ago
+91-2

Description

PR #11413 introduced the invariant to preserve model responses in history when crossing UsageLimits:

"Token and cost limits are only known once the response has been billed, so commit it to history first: a run a limit stops keeps it in its messages, and resuming from them doesn't request it again."

While _finish_handling() was updated to append before checking usage limits, the two except exceptions.ModelRetry as e: handlers in _agent_graph.py (streaming at line 1830 and non-streaming at line 1974) still checked _enforce_usage_limits() before appending _handler_response.

This caused UsageLimitExceeded to bypass _append_response(), dropping the response from message_history / capture_run_messages() even though the request had already been recorded in ctx.state.usage, leading to data loss and double-billing if resumed.

This PR:

  1. Aligns both except exceptions.ModelRetry: handlers with _finish_handling(): appends _handler_response first, and if UsageLimitExceeded is raised, marks state='interrupted'.
  2. Adds a regression test test_response_over_limit_with_model_retry_is_kept_in_captured_messages in tests/test_usage_limits.py.

Checklist

  • No breaking changes in accordance with the version policy.
  • Any permitted compatibility impact has a label, warning, migration and release note, and an exact API-check waiver if the gate reports it.
  • PR title is fit for the release changelog.