@@ -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."""
0 commit comments