Repository navigation
Description
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.
- 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 itsasyncio.timeout()expires during that wait, the guardrail is cancelled, butstream_events()returns normally. The caller never seesCancelledError/TimeoutErrorand continues withresult.final_output, even though the input guardrail never produced a verdict. - Run cleanup is skipped after
result.cancel(). Ifresult.cancel()(or consumer cancellation) happens while the guardrail is running, the run loop'sfinallyawaits the cancelled guardrail task, gets itsCancelledError, and aborts the rest of cleanup. The trace plus the task and agent spans are never finished, and computers created by aComputerProviderfor the run are never disposed.
Debug information
- Agents SDK version: v0.22.3 and
mainat 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()runsawait taskand suppressesCancelledError. Awaiting a task forwards the waiter's cancellation into the task, so after the consumer is cancelled the task ends cancelled. TheCancelledErrorthe consumer then receives looks like the task's own cancellation and is swallowed.input_guardrail_tripwire_triggered_for_stream(), which the run loop'sfinallycalls before disposing computers and finishing spans, runsawait task. When the guardrail task was cancelled bycancel(), awaiting it raisesCancelledErrorin 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
gomission commentedon Sep 28, 2026
@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 publicComputerProvider.disposecallback is awaiting completion. The consumer has reached the run-loop finalization wait; cancel that consumer.On Python 3.12.11 / macOS, at
08e5c431eb85d243b62d904f21bc57b6db1682a1:CancelledErrorSo 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.connectis blocked.Standalone reproduction (run on main, then with the two-file patch in the issue)
Disclosure: investigating agent recovery behavior for Mission, with Codex assistance. Credit for the original diagnosis and proposed patch is yours.