Skip to content

Input guardrail tripwire loses input_guardrail_results in non-streaming runs #4068

Closed

Description

@hsusul

Please read this first

Affected component

AgentRunner.run / Runner.run / Runner.run_sync (non-streaming input-guardrail path) — src/agents/run_internal/guardrails.py::run_input_guardrails and its call sites in src/agents/run.py.

Describe the bug

When an input guardrail tripwire fires, InputGuardrailTripwireTriggered.run_data.input_guardrail_results is empty for Runner.run() / Runner.run_sync(), but correctly contains every completed guardrail result for Runner.run_streamed().

run_input_guardrails() accumulates results in a local list and raises InputGuardrailTripwireTriggered(result) as soon as a tripwire fires, discarding the accumulated list. src/agents/run.py only merges those results into the run-level input_guardrail_results on the success path (input_guardrail_results.extend(sequential_results)), so the RunErrorDetails attached to the exception is built from an empty list.

The streamed path uses run_input_guardrails_with_queue(), which assigns streamed_result.input_guardrail_results before propagating the tripwire, so streamed consumers see all results.

This means a non-streaming caller cannot read the output_info of the guardrails that ran — including the ones that passed — from the raised exception. exc.guardrail_result still exposes the single tripping result, so the loss is specifically the full, documented run-state view.

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 the repository's existing tests/fake_model.py::FakeModel.

Repro steps

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

from __future__ import annotations

import asyncio
from typing import Any

import pytest

from agents import (
    Agent,
    GuardrailFunctionOutput,
    InputGuardrail,
    InputGuardrailTripwireTriggered,
    Runner,
)

from .fake_model import FakeModel
from .test_responses import get_text_message


def _guardrail(name: str, trip: bool, delay: float = 0.0) -> InputGuardrail[Any]:
    async def fn(ctx, agent, inp) -> GuardrailFunctionOutput:
        if delay:
            await asyncio.sleep(delay)
        return GuardrailFunctionOutput(output_info=name, tripwire_triggered=trip)

    return InputGuardrail(guardrail_function=fn, name=name)


def _agent(model: FakeModel) -> Agent[Any]:
    return Agent(
        name="A",
        model=model,
        input_guardrails=[
            _guardrail("passes", trip=False),
            _guardrail("trips", trip=True, delay=0.02),
        ],
    )


@pytest.mark.asyncio
async def test_streamed_exposes_input_guardrail_results() -> None:
    """Baseline: the streamed path already reports every guardrail result."""
    model = FakeModel()
    model.set_next_output([get_text_message("done")])
    result = Runner.run_streamed(_agent(model), input="hi")
    with pytest.raises(InputGuardrailTripwireTriggered) as exc_info:
        async for _ in result.stream_events():
            pass

    run_data = exc_info.value.run_data
    assert run_data is not None
    assert [r.guardrail.get_name() for r in run_data.input_guardrail_results] == ["passes", "trips"]


@pytest.mark.asyncio
async def test_non_streamed_exposes_input_guardrail_results() -> None:
    """Runner.run() must report the same guardrail results as run_streamed()."""
    model = FakeModel()
    model.set_next_output([get_text_message("done")])
    with pytest.raises(InputGuardrailTripwireTriggered) as exc_info:
        await Runner.run(_agent(model), input="hi")

    run_data = exc_info.value.run_data
    assert run_data is not None
    assert [r.guardrail.get_name() for r in run_data.input_guardrail_results] == ["passes", "trips"]

Actual behavior

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

FAILED tests/test_repro_guardrail_results.py::test_non_streamed_exposes_input_guardrail_results
E       AssertionError: assert [] == ['passes', 'trips']
E         Right contains 2 more items, first extra item: 'passes'

Expected behavior

InputGuardrailTripwireTriggered.run_data.input_guardrail_results should list the guardrail results that completed before the run was aborted — including the tripping one — for Runner.run() and Runner.run_sync(), exactly as it already does for Runner.run_streamed().

Two statements in the repository's own maintainer reference (.agents/references/runner-lifecycle.md) describe this expectation:

Guardrail results are observable run state. Preserve them across handoffs, error handlers, streamed completion, and RunState round-trips.

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)

run_input_guardrails() in src/agents/run_internal/guardrails.py builds guardrail_results locally and raises before the caller can observe it. src/agents/run.py assigns the results into the run-level list only after a successful return (line ~1314, input_guardrail_results.extend(sequential_results)), so the except BaseException handler that populates RunErrorDetails sees an empty list.

Proposed focused scope

Let run_input_guardrails() publish results into a caller-owned accumulator (or otherwise surface them on the tripwire path) so src/agents/run.py can attach them to RunErrorDetails before re-raising. No public API additions; InputGuardrailTripwireTriggered.guardrail_result and the exception type are unchanged. Regression tests would cover Runner.run, Runner.run_sync, and Runner.run_streamed for sequential and parallel guardrails.

User impact

Non-streaming callers that inspect err.run_data.input_guardrail_results in an error handler — to log which checks ran, or to read output_info (scores, categories, redaction details) from guardrails that passed — always observe an empty list. Because run_streamed() behaves correctly, the same handler silently changes behavior depending on which Runner entry point is used.

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

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