Skip to content

Streamed runs swallow consumer cancellation and skip run cleanup while a parallel input guardrail is running #5213

Closed

Description

@hsusul

Please read this first

  • Have you read the docs? Yes, including the streaming cancellation section.
  • Have you searched for related issues? Yes. Streaming is blocking and cannot be cancelled #2222 fixed cancellation while stream_events() waits for the next event; this report covers the remaining waits on the input guardrail task and the run-loop task, which still swallow cancellation.

Describe the bug

Streamed runs mishandle cancellation while a parallel input guardrail is still running. Parallel is the default for input guardrails, and a guardrail that outlasts the model, such as a moderation call, is common.

  1. The consumer's cancellation is swallowed. When the model has finished but the guardrail has not, stream_events() waits for the guardrail after the final event. If the consumer is cancelled or its asyncio.timeout() expires during that wait, the guardrail is cancelled, but stream_events() returns normally. The caller never sees CancelledError/TimeoutError and continues with result.final_output, even though the input guardrail never produced a verdict.
  2. Run cleanup is skipped after result.cancel(). If result.cancel() (or consumer cancellation) happens while the guardrail is running, the run loop's finally awaits the cancelled guardrail task, gets its CancelledError, and aborts the rest of cleanup. The trace plus the task and agent spans are never finished, and computers created by a ComputerProvider for the run are never disposed.

Debug information

  • Agents SDK version: v0.22.3 and main at 08e5c43
  • Python version: 3.12.13 (the regression tests also run on 3.10)
  • Operating system: macOS
  • Model and model provider: none; reproduced with agents.testing.ScriptedModel
  • Does the issue reproduce with the latest Agents SDK release? Yes
  • Does the issue occur consistently or intermittently? Consistently

Repro steps

import asyncio

from agents import (
    Agent,
    GuardrailFunctionOutput,
    Runner,
    add_trace_processor,
    function_tool,
    input_guardrail,
)
from agents.testing import ScriptedModel, assistant_message, function_call
from agents.tracing import TracingProcessor


class OpenTraces(TracingProcessor):
    def __init__(self) -> None:
        self.open: set[str] = set()

    def on_trace_start(self, trace) -> None:
        self.open.add(trace.trace_id)

    def on_trace_end(self, trace) -> None:
        self.open.discard(trace.trace_id)

    def on_span_start(self, span) -> None: ...
    def on_span_end(self, span) -> None: ...
    def shutdown(self) -> None: ...
    def force_flush(self) -> None: ...


traces = OpenTraces()
add_trace_processor(traces)


def make_agent(steps, tools=()):
    # Parallel input guardrails are the default; this one outlasts the model.
    @input_guardrail
    async def slow_guardrail(ctx, agent, input):
        await asyncio.sleep(3600)
        return GuardrailFunctionOutput(output_info=None, tripwire_triggered=False)

    return Agent(
        name="assistant",
        model=ScriptedModel(steps),
        tools=list(tools),
        input_guardrails=[slow_guardrail],
    )


async def timeout_is_swallowed() -> None:
    result = Runner.run_streamed(make_agent([[assistant_message("done")]]), "hi")
    try:
        async with asyncio.timeout(0.5):
            async for _ in result.stream_events():
                pass
        print("1) timeout: stream_events() returned normally, final_output =", repr(result.final_output))
    except TimeoutError:
        print("1) timeout: TimeoutError raised")


async def cancel_skips_cleanup() -> None:
    tool_started = asyncio.Event()

    @function_tool
    async def slow_tool() -> str:
        tool_started.set()
        await asyncio.sleep(3600)
        return ""

    traces.open.clear()
    agent = make_agent([[function_call("slow_tool", {}, call_id="call_1")]], tools=[slow_tool])
    result = Runner.run_streamed(agent, "hi")

    async def consume() -> None:
        async for _ in result.stream_events():
            pass

    consumer = asyncio.create_task(consume())
    await tool_started.wait()
    result.cancel()
    await consumer
    await asyncio.sleep(0.1)
    print("2) result.cancel(): unfinished traces =", len(traces.open))


async def main() -> None:
    await timeout_is_swallowed()
    await cancel_skips_cleanup()


asyncio.run(main())

Output on main:

1) timeout: stream_events() returned normally, final_output = 'done'
2) result.cancel(): unfinished traces = 1

Expected behavior

1) timeout: TimeoutError raised
2) result.cancel(): unfinished traces = 0

Cancelling a stream consumer should propagate to that consumer, and cancelling the run should still finish the trace/spans and dispose per-run computers.

Root cause

Both waits await the shared task directly:

  • RunResultStreaming._await_task_safely() runs await task and suppresses CancelledError. Awaiting a task forwards the waiter's cancellation into the task, so after the consumer is cancelled the task ends cancelled. The CancelledError the consumer then receives looks like the task's own cancellation and is swallowed.
  • input_guardrail_tripwire_triggered_for_stream(), which the run loop's finally calls before disposing computers and finishing spans, runs await task. When the guardrail task was cancelled by cancel(), awaiting it raises CancelledError in the run loop and the remaining cleanup is skipped.

Ordering for (1): the model completes, QueueCompleteSentinel is queued, the consumer takes the sentinel and awaits the guardrail task, and the consumer is cancelled. The guardrail is cancelled, the consumer suppresses the resulting CancelledError, and stream_events() ends normally.

Ordering for (2): a tool (or the model) is in flight while the guardrail runs, and result.cancel() cancels the run loop and the guardrail. The run loop enters its finally, awaits the cancelled guardrail task, gets CancelledError, and exits before dispose_resolved_computers(), span.finish(), and trace.finish().

Waiting with asyncio.wait((task,)) avoids both problems: the task's own cancellation is not raised into the waiter, and a CancelledError there always belongs to the waiter. That waiter can then forward its cancellation to the task, as await did, and re-raise it.

Regression test evidence

Two deterministic regression tests through Runner.run_streamed() (event-gated, no sleeps for ordering) fail on main at 08e5c43:

test_cancel_with_pending_parallel_input_guardrail_finishes_run_cleanup
    assert len(disposed) == 1  ->  assert 0 == 1
test_consumer_cancellation_while_awaiting_input_guardrail_propagates
    Failed: DID NOT RAISE <class 'asyncio.exceptions.CancelledError'>

Both pass with the change below. Because CONTRIBUTING.md limits pull requests to collaborators, the fix and tests are offered here for maintainers. They are also available as commit hsusul/openai-agents-python@d1e8466 on branch fix/stream-guardrail-wait-cancellation, based on 08e5c43.

diff --git a/src/agents/result.py b/src/agents/result.py
index 70d48fe3..52276efa 100644
--- a/src/agents/result.py
+++ b/src/agents/result.py
@@ -1166,20 +1166,20 @@ class RunResultStreaming(RunResultBase):
         return pretty_print_run_result_streaming(self)
 
     async def _await_task_safely(self, task: asyncio.Task[Any] | None) -> None:
-        """Await a task if present, ignoring cancellation and storing exceptions elsewhere.
+        """Wait for a task if present, leaving its cancellation and exceptions to _check_errors().
 
-        This ensures we do not lose late guardrail exceptions while not surfacing
-        CancelledError to callers of stream_events.
+        This ensures we do not lose late guardrail exceptions while not surfacing the task's
+        CancelledError to callers of stream_events. Cancellation of the consumer still propagates.
         """
         if task and not task.done():
+            # Do not await the task directly: its cancellation (e.g., due to result.cancel())
+            # would be indistinguishable from cancellation of this consumer.
             try:
-                await task
+                await asyncio.wait((task,))
             except asyncio.CancelledError:
-                # Task was cancelled (e.g., due to result.cancel()). Nothing to do here.
-                pass
-            except Exception:
-                # The exception will be surfaced via _check_errors() if needed.
-                pass
+                # This consumer was cancelled. Forward it to the task, as awaiting it would.
+                task.cancel()
+                raise
 
     def _drain_event_queue(self) -> None:
         """Remove any pending items from the event queue and mark them done."""
diff --git a/src/agents/run_internal/guardrails.py b/src/agents/run_internal/guardrails.py
index dc09f0cd..199b935c 100644
--- a/src/agents/run_internal/guardrails.py
+++ b/src/agents/run_internal/guardrails.py
@@ -233,7 +233,16 @@ async def input_guardrail_tripwire_triggered_for_stream(
         return False
 
     if not task.done():
-        await task
+        # Do not await the task directly: its cancellation (e.g., due to result.cancel()) would be
+        # indistinguishable from cancellation of this caller and abort the caller's cleanup.
+        try:
+            await asyncio.wait((task,))
+        except asyncio.CancelledError:
+            # This caller was cancelled. Forward it to the task, as awaiting it would.
+            task.cancel()
+            raise
+        if not task.cancelled():
+            task.result()
 
     return any(
         guardrail_result.output.tripwire_triggered

Activity

  1. gomission commented on Sep 28, 2026

    @gomission

    @hsusul, I checked the run-loop wait separately from the input-guardrail wait. Your proposed patch restores consumer cancellation in this case too.

    Additional checkpoint: no input guardrails, model has produced done, and the public ComputerProvider.dispose callback is awaiting completion. The consumer has reached the run-loop finalization wait; cancel that consumer.

    On Python 3.12.11 / macOS, at 08e5c431eb85d243b62d904f21bc57b6db1682a1:

    Case Consumer outcome Dispose callback Unfinished traces / spans
    Normal exhaustion, main or your patch Returns normally Completes 0 / 0
    Cancel during disposal, main Returns normally Cancelled 1 / 2
    Cancel during disposal, your patch CancelledError Cancelled 1 / 2

    So there are two distinct observations here: your wait change fixes cancellation propagation at this boundary; it does not make already-running async disposal cancellation-safe. This cleanup behavior is present on main as well; it is not introduced by your patch. It is a separate window after terminal output and may warrant separate cleanup coverage/scope. I measured callback interruption and missing trace-end callbacks, not a leak of real provider resources. I have not attempted a broader fix.

    The reproduction uses Runner.run_streamed, ScriptedModel, an inert local computer and an in-memory trace processor. Event gates establish ordering; a wrapper only observes entry to _await_task_safely(run_loop_task) and delegates its behavior unchanged. No provider calls or real device actions; socket.socket.connect is blocked.

    Standalone reproduction (run on main, then with the two-file patch in the issue)
    """Local public-Runner reproduction for #5213's run-loop wait boundary.
    
    No model/provider network calls. The private wait wrapper only observes which
    task the public stream consumer is awaiting; it delegates behavior unchanged.
    """
    
    import asyncio
    import json
    import socket
    from unittest.mock import patch
    
    from agents import Agent, ComputerProvider, ComputerTool, Runner, set_trace_processors
    from agents.computer import Computer
    from agents.result import RunResultStreaming
    from agents.testing import ScriptedModel, assistant_message
    from agents.tracing import TracingProcessor
    
    
    class LocalComputer(Computer):
        def screenshot(self): return "unused"
        def click(self, x, y, button): pass
        def double_click(self, x, y): pass
        def scroll(self, x, y, scroll_x, scroll_y): pass
        def type(self, text): pass
        def wait(self): pass
        def move(self, x, y): pass
        def keypress(self, keys): pass
        def drag(self, path): pass
    
    
    class LocalTraces(TracingProcessor):
        def __init__(self):
            self.open_traces = set()
            self.open_spans = set()
        def on_trace_start(self, trace): self.open_traces.add(trace.trace_id)
        def on_trace_end(self, trace): self.open_traces.discard(trace.trace_id)
        def on_span_start(self, span): self.open_spans.add(span.span_id)
        def on_span_end(self, span): self.open_spans.discard(span.span_id)
        def shutdown(self): pass
        def force_flush(self): pass
    
    
    async def run_case(cancel_consumer):
        disposal_started = asyncio.Event()
        release_disposal = asyncio.Event()
        disposal_exited = asyncio.Event()
        consumer_awaits_run = asyncio.Event()
        events = []
        traces = LocalTraces()
        set_trace_processors([traces])
    
        async def create(**kwargs):
            events.append("created")
            return LocalComputer()
    
        async def dispose(**kwargs):
            events.append("dispose_started")
            disposal_started.set()
            try:
                await release_disposal.wait()
                events.append("dispose_completed")
            except asyncio.CancelledError:
                events.append("dispose_cancelled")
                raise
            finally:
                disposal_exited.set()
    
        agent = Agent(
            name="local-disposal-check",
            model=ScriptedModel([[assistant_message("done")]]),
            tools=[ComputerTool(computer=ComputerProvider(create=create, dispose=dispose))],
        )
        result = Runner.run_streamed(agent, "synthetic input")
        original_wait = RunResultStreaming._await_task_safely
    
        async def observe_wait(self, task):
            if self is result and task is result.run_loop_task:
                consumer_awaits_run.set()
            return await original_wait(self, task)
    
        async def consume():
            async for _ in result.stream_events():
                pass
            events.append("consumer_returned_normally")
    
        with patch.object(RunResultStreaming, "_await_task_safely", observe_wait):
            consumer = asyncio.create_task(consume())
            try:
                await asyncio.wait_for(disposal_started.wait(), 5)
                await asyncio.wait_for(consumer_awaits_run.wait(), 5)
                assert result.final_output == "done"
                assert not consumer.done()
                if cancel_consumer:
                    consumer.cancel()
                else:
                    release_disposal.set()
                try:
                    await asyncio.wait_for(consumer, 5)
                    outcome = "returned_normally"
                except asyncio.CancelledError:
                    outcome = "CancelledError"
                await asyncio.wait_for(disposal_exited.wait(), 5)
                await asyncio.gather(result.run_loop_task, return_exceptions=True)
                return {
                    "case": "cancel_during_disposal" if cancel_consumer else "normal_disposal",
                    "consumer_outcome": outcome,
                    "final_output": result.final_output,
                    "events": events,
                    "open_traces": len(traces.open_traces),
                    "open_spans": len(traces.open_spans),
                }
            finally:
                release_disposal.set()
                for task in (consumer, result.run_loop_task):
                    if task and not task.done():
                        task.cancel()
                await asyncio.gather(consumer, result.run_loop_task, return_exceptions=True)
    
    
    async def main():
        rows = [await run_case(False), await run_case(True)]
        control = rows[0]
        assert control["consumer_outcome"] == "returned_normally"
        assert control["open_traces"] == control["open_spans"] == 0
        assert "dispose_completed" in control["events"]
        print(json.dumps(rows, indent=2))
    
    
    if __name__ == "__main__":
        with patch.object(socket.socket, "connect", side_effect=AssertionError("network disabled")):
            asyncio.run(main())

    Disclosure: investigating agent recovery behavior for Mission, with Codex assistance. Credit for the original diagnosis and proposed patch is yours.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions