Skip to content

Commit 0d6b741

Browse files
fix: preserve streamed cancellation and pending guardrail cleanup (#5224)
* fix: preserve streamed cancellation and pending guardrail cleanup * fix: preserve terminal cleanup and guardrail cancellation boundaries
1 parent 9c5a5e8 commit 0d6b741

5 files changed

Lines changed: 314 additions & 33 deletions

File tree

‎src/agents/result.py‎

Lines changed: 28 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1045,25 +1045,25 @@ def register_current_consumer() -> None:
10451045
registered_consumer_task.remove_done_callback(consumer_task_done)
10461046
unregister_consumer()
10471047
try:
1048-
if cancelled:
1049-
# Cancellation should return promptly, so avoid waiting on long-running tasks.
1050-
# Tasks have already been cancelled above.
1051-
self._cleanup_tasks()
1052-
else:
1053-
# Ensure main execution completes before cleanup to avoid race conditions
1054-
# with session operations.
1055-
await self._await_task_safely(self.run_loop_task)
1056-
# Re-check for exceptions now that the run loop has fully settled.
1057-
# _await_task_safely swallows exceptions; without this call, a run-loop
1058-
# failure that races past the sentinel (e.g. early sandbox failures) would
1059-
# be silently lost instead of surfaced via _stored_exception.
1060-
self._check_errors()
1061-
# Safely terminate all background tasks after main execution has finished.
1062-
self._cleanup_tasks()
1063-
1064-
if not cancelled:
1065-
await self._await_model_provider_cleanup()
1066-
await self._run_sandbox_cleanup()
1048+
try:
1049+
if cancelled:
1050+
# Queue-wait cancellation should return without awaiting long-running tasks.
1051+
# Tasks have already been cancelled above.
1052+
self._cleanup_tasks()
1053+
else:
1054+
# Ensure main execution completes before cleanup to avoid race conditions
1055+
# with session operations.
1056+
await self._await_task_safely(self.run_loop_task)
1057+
# Re-check for exceptions now that the run loop has fully settled.
1058+
# _await_task_safely leaves errors to _check_errors(); without this call,
1059+
# a run-loop failure racing past the sentinel would be silently lost.
1060+
self._check_errors()
1061+
# Safely terminate background tasks after main execution has finished.
1062+
self._cleanup_tasks()
1063+
finally:
1064+
if not cancelled:
1065+
await self._await_model_provider_cleanup()
1066+
await self._run_sandbox_cleanup()
10671067
finally:
10681068
# Allow any pending callbacks (e.g., cancellation handlers) to enqueue their
10691069
# completion sentinels before we clear the queues for observability.
@@ -1166,20 +1166,20 @@ def __str__(self) -> str:
11661166
return pretty_print_run_result_streaming(self)
11671167

11681168
async def _await_task_safely(self, task: asyncio.Task[Any] | None) -> None:
1169-
"""Await a task if present, ignoring cancellation and storing exceptions elsewhere.
1169+
"""Wait for a task, leaving its cancellation and exceptions to _check_errors().
11701170
1171-
This ensures we do not lose late guardrail exceptions while not surfacing
1172-
CancelledError to callers of stream_events.
1171+
This ensures we do not lose late guardrail exceptions while not surfacing the task's
1172+
CancelledError to callers of stream_events. Consumer cancellation still propagates.
11731173
"""
11741174
if task and not task.done():
11751175
try:
1176-
await task
1176+
# Waiting directly would conflate child cancellation with consumer cancellation.
1177+
await asyncio.wait((task,))
11771178
except asyncio.CancelledError:
1178-
# Task was cancelled (e.g., due to result.cancel()). Nothing to do here.
1179-
pass
1180-
except Exception:
1181-
# The exception will be surfaced via _check_errors() if needed.
1182-
pass
1179+
task.cancel()
1180+
# Preserve direct-await settlement before the consumer releases owned resources.
1181+
await asyncio.wait((task,))
1182+
raise
11831183

11841184
def _drain_event_queue(self) -> None:
11851185
"""Remove any pending items from the event queue and mark them done."""

‎src/agents/run_internal/guardrails.py‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -226,14 +226,23 @@ def record(result: OutputGuardrailResult) -> None:
226226

227227
async def input_guardrail_tripwire_triggered_for_stream(
228228
streamed_result: RunResultStreaming,
229+
*,
230+
ignore_cancelled: bool = False,
229231
) -> bool:
230-
"""Return True if any input guardrail triggered during a streamed run."""
232+
"""Wait for input verdicts, optionally tolerating child cancellation during final cleanup."""
231233
task = streamed_result._input_guardrails_task
232234
if task is None:
233235
return False
234236

235237
if not task.done():
236-
await task
238+
# A cancelled child must not abort the caller's remaining run cleanup.
239+
try:
240+
await asyncio.wait((task,))
241+
except asyncio.CancelledError:
242+
task.cancel()
243+
raise
244+
if not ignore_cancelled or not task.cancelled():
245+
task.result()
237246

238247
return any(
239248
guardrail_result.output.tripwire_triggered

‎src/agents/run_internal/run_loop.py‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2047,7 +2047,9 @@ def _record_max_turns_handler_output(
20472047
_sync_conversation_tracking_from_tracker()
20482048
if streamed_result._input_guardrails_task:
20492049
try:
2050-
triggered = await input_guardrail_tripwire_triggered_for_stream(streamed_result)
2050+
triggered = await input_guardrail_tripwire_triggered_for_stream(
2051+
streamed_result, ignore_cancelled=True
2052+
)
20512053
if triggered:
20522054
first_trigger = next(
20532055
(

‎tests/test_agent_runner_streamed.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1580,7 +1580,7 @@ async def safe_guardrail(
15801580

15811581
error = RuntimeError("SECRET_STREAM_FINALIZER_ERROR")
15821582

1583-
async def fail_finalizer(_result: Any) -> bool:
1583+
async def fail_finalizer(_result: Any, *, ignore_cancelled: bool = False) -> bool:
15841584
raise error
15851585

15861586
monkeypatch.setattr(

0 commit comments

Comments
 (0)