Skip to content

Non-streaming runs never attach a generic run error to the agent span #4070

Closed

Description

@hsusul

Please read this first

Affected component

Tracing on the non-streaming run loop — src/agents/run.py (AgentRunner._run_single_turn loop / current_span handling), versus src/agents/run_internal/run_loop.py::start_streaming.

Describe the bug

When a run fails with an exception that is not a ModelBehaviorError or a guardrail tripwire, the streamed path marks the agent span with SpanError(message="Error in agent run", ...), but the non-streamed path leaves the agent span's error as None. The agent span is simply closed in the finally block.

Non-streaming runs do attach Max turns exceeded to the agent span (see the existing snapshot in tests/test_tracing_errors.py::test_max_turns_exceeded), so error attachment on the agent span is expected behavior for that path — generic run errors are the gap.

Debug information

  • Agents SDK version: main @ c3f1781d56e8f1249a01674f18ba1f3e44a16dce (latest release tag v0.19.1)
  • Python version: 3.13.5
  • OS: macOS 15.7.3 (Darwin 24.6.0)
  • No OpenAI API key, no network access, and no paid model call are needed — the repro uses tests/fake_model.py::FakeModel and the in-repo test span processor.

Repro steps

Save as tests/test_repro_agent_span_error.py and run uv run pytest tests/test_repro_agent_span_error.py -q:

from __future__ import annotations

from typing import Any

import pytest

from agents import Agent, Runner

from .fake_model import FakeModel
from .testing_processor import fetch_ordered_spans


def _agent_span_error(spans: list[Any]) -> Any:
    for span in spans:
        if type(span.span_data).__name__ == "AgentSpanData":
            return span.error
    raise AssertionError("no agent span")


@pytest.mark.asyncio
async def test_streamed_marks_agent_span_with_run_error() -> None:
    """Baseline: the streamed path marks the agent span."""
    model = FakeModel(tracing_enabled=True)
    model.set_next_output(RuntimeError("boom"))
    result = Runner.run_streamed(Agent(name="A", model=model), input="hi")
    with pytest.raises(RuntimeError):
        async for _ in result.stream_events():
            pass

    assert _agent_span_error(fetch_ordered_spans()) == {
        "message": "Error in agent run",
        "data": {"error": "boom"},
    }


@pytest.mark.asyncio
async def test_non_streamed_marks_agent_span_with_run_error() -> None:
    model = FakeModel(tracing_enabled=True)
    model.set_next_output(RuntimeError("boom"))
    with pytest.raises(RuntimeError):
        await Runner.run(Agent(name="A", model=model), input="hi")

    assert _agent_span_error(fetch_ordered_spans()) == {
        "message": "Error in agent run",
        "data": {"error": "boom"},
    }

Actual behavior

The streamed test passes; the non-streamed test fails deterministically (reproduced 3/3 runs):

FAILED tests/test_repro_agent_span_error.py::test_non_streamed_marks_agent_span_with_run_error
E       AssertionError: assert None == {'data': {'error': 'boom'}, 'message': 'Error in agent run'}

The existing committed snapshots show the same asymmetry:

  • tests/test_tracing_errors.py::test_single_turn_model_error — agent span has no error key.
  • tests/test_tracing_errors_streamed.py::test_single_turn_model_error — agent span has "error": {"message": "Error in agent run", "data": {"error": "test error"}}.

Expected behavior

Runner.run() and Runner.run_sync() should mark the agent span with the same Error in agent run SpanError the streamed path records, subject to the same _should_attach_generic_agent_error() exclusions (ModelBehaviorError, InputGuardrailTripwireTriggered, OutputGuardrailTripwireTriggered) and the same trace_include_sensitive_data redaction.

.agents/references/runner-lifecycle.md states the general requirement:

Streaming and non-streaming paths must produce equivalent final output, generated items, current agent, usage, guardrail results, session history, and interruption state for the same model behavior.

Root-cause hypothesis (hypothesis, not verified as the maintainers' intent)

start_streaming() in src/agents/run_internal/run_loop.py wraps its turn loop in except Exception as e: handlers that call _error_tracing.attach_error_to_span(current_span, SpanError("Error in agent run", ...)). The equivalent block in src/agents/run.py is except BaseException as exc:, which records run_exception and attaches RunErrorDetails to AgentsExceptions but never touches current_span; the finally block then calls current_span.finish(reset_current=True) with no error recorded.

Proposed focused scope

Attach the same SpanError to the agent span from the non-streaming failure path, reusing _should_attach_generic_agent_error() and _error_tracing.get_trace_error() so the exclusion list and redaction stay identical to the streamed path. This changes two committed inline snapshots in tests/test_tracing_errors.py (the agent span gains an error key); those changes follow directly from the fix. Regression tests would cover Runner.run, Runner.run_sync, the excluded exception types, and trace_include_sensitive_data=False.

User impact

In a non-streaming run, an exported trace shows a failed generation span nested under an agent span reporting no error. Worse, when the exception is raised outside a generation or function span the trace records no error at all. A RunHooks.on_agent_start that raises RuntimeError("hook boom") produces:

# Runner.run(...)                       # Runner.run_streamed(...)
[{"workflow_name": "Agent workflow",    [{"workflow_name": "Agent workflow",
  "children": [                           "children": [
    {"type": "agent",                       {"type": "agent",
     "data": {"name": "A", ...}}             "error": {"message": "Error in agent run",
  ]}]                                                  "data": {"error": "hook boom"}},
                                                "data": {"name": "A", ...}}
                                          ]}]

Dashboards and alerting that key off span errors miss these non-streaming failures entirely while catching the identical streamed ones.

I'd like to work on this and open a PR if that's welcome.

Activity

  1. workeainc commented on Jul 31, 2026

    @workeainc

    I would like to work on this issue. I will add focused regression coverage for Runner.run() and Runner.run_sync() and reuse the streamed path's error-tracing behavior without changing the excluded error cases.

  2. added this to the 0.19.x milestone on Aug 5, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions