Skip to content

Commit c31638d

Browse files
fix(sessions): arm the max-turns terminal marker only once guardrails pass
finalize_max_turns_handler_output() drives the same save callback from its guardrail-error path, so marking inside that callback closed the state for an output that never passed its guardrails and never reached the caller. A failed append there rejected every later resume, which is worse than the replay the marker exists to prevent: the run had nothing to protect and no way forward. Arm and clear at the success call site instead, which is only reachable once the handler output cleared its guardrails and ran its end hooks. That matches the streamed finalizer, which already wraps only its post-guardrail save, so both runners now arm on the same condition.
1 parent 4847f9d commit c31638d

2 files changed

Lines changed: 51 additions & 10 deletions

File tree

‎src/agents/run.py‎

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1526,15 +1526,8 @@ async def _save_max_turns_handler_output(
15261526
store_setting: bool | None = store_setting,
15271527
generated_items: list[RunItem] = generated_items,
15281528
session_items: list[RunItem] = session_items,
1529-
run_state: RunState[TContext] | None = run_state,
15301529
) -> None:
15311530
nonlocal handler_output_recorded, handler_persisted_item_count
1532-
# The handler output, its guardrails, and its end hooks are complete,
1533-
# so this append carries an accepted result like any other terminal
1534-
# one. run_state stays out of the save itself to keep the resumed
1535-
# turn's persisted count intact.
1536-
if run_state is not None:
1537-
run_state._terminal_unrecoverable = True
15381531
handler_persisted_item_count = (
15391532
await save_final_turn_items_after_guardrails(
15401533
session=session,
@@ -1548,8 +1541,6 @@ async def _save_max_turns_handler_output(
15481541
wrapper=context_wrapper,
15491542
)
15501543
)
1551-
if run_state is not None:
1552-
run_state._terminal_unrecoverable = False
15531544
if not items:
15541545
return
15551546
generated_items.extend(items)
@@ -1570,7 +1561,16 @@ async def _save_max_turns_handler_output(
15701561
include_in_history=include_in_history,
15711562
)
15721563
if include_in_history and not handler_output_recorded:
1564+
# Only reachable once the handler output cleared its guardrails and
1565+
# ran its end hooks, so this append carries an accepted result like
1566+
# any other terminal one. The callback itself stays unmarked because
1567+
# finalize_max_turns_handler_output() also drives it from its
1568+
# guardrail-error path, where no output was ever accepted.
1569+
if run_state is not None:
1570+
run_state._terminal_unrecoverable = True
15731571
await _save_max_turns_handler_output([synthesized_item])
1572+
if run_state is not None:
1573+
run_state._terminal_unrecoverable = False
15741574
current_step = getattr(run_state, "_current_step", None)
15751575
approvals_from_state = approvals_from_step(current_step)
15761576
result = RunResult(

‎tests/test_run_impl_resume_paths.py‎

Lines changed: 42 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
from openai.types.responses import ResponseFunctionToolCall, ResponseOutputMessage
1010

1111
import agents.run as run_module
12-
from agents import Agent, Runner, function_tool, handoff
12+
from agents import Agent, GuardrailFunctionOutput, Runner, function_tool, handoff, output_guardrail
1313
from agents.agent import ToolsToFinalOutputResult
1414
from agents.agent_output import AgentOutputSchema
1515
from agents.decorators import tool, tool_input_guardrail, tool_output_guardrail
@@ -1454,3 +1454,44 @@ def _handler(_data: Any) -> str:
14541454
)
14551455
assert handler_calls == ["handled"]
14561456
assert hooks.ends == ["max-turns-output"]
1457+
1458+
1459+
@pytest.mark.asyncio
1460+
async def test_max_turns_guardrail_failure_leaves_the_state_retryable() -> None:
1461+
"""A handler output that never passed its guardrails must not close the state.
1462+
1463+
`finalize_max_turns_handler_output()` drives the same save callback from its guardrail-error
1464+
path. Marking there would reject every later resume for an output the caller never received,
1465+
which is a worse outcome than the replay the marker exists to prevent.
1466+
"""
1467+
guardrail_calls: list[str] = []
1468+
1469+
@tool(needs_approval=True)
1470+
async def charge(amount: int) -> str:
1471+
return "receipt-7"
1472+
1473+
@output_guardrail
1474+
async def exploding(context: Any, agent: Agent[Any], output: Any) -> GuardrailFunctionOutput:
1475+
guardrail_calls.append(str(output))
1476+
raise RuntimeError("guardrail exploded")
1477+
1478+
model = ScriptedModel([[get_function_tool_call("charge", '{"amount":7}', call_id="charge-1")]])
1479+
agent = Agent(name="payment", model=model, tools=[charge], output_guardrails=[exploding])
1480+
session = _FailingResumeSession()
1481+
config = RunConfig(tracing_disabled=True)
1482+
1483+
paused = await Runner.run(agent, "charge 7", session=session, run_config=config, max_turns=1)
1484+
state = paused.to_state()
1485+
state.approve(state.get_interruptions()[0])
1486+
1487+
handlers: dict[str, Any] = {"max_turns": lambda _data: "max-turns-output"}
1488+
session.fail_on_output = "max-turns-output"
1489+
with pytest.raises(RuntimeError, match="session append failed"):
1490+
await Runner.run(agent, state, session=session, run_config=config, error_handlers=handlers)
1491+
1492+
assert guardrail_calls == ["max-turns-output"]
1493+
assert "terminal_unrecoverable" not in state.to_json()
1494+
1495+
# The retry reports the real guardrail failure rather than a fail-closed rejection.
1496+
with pytest.raises(RuntimeError, match="guardrail exploded"):
1497+
await Runner.run(agent, state, session=session, run_config=config, error_handlers=handlers)

0 commit comments

Comments
 (0)