Backtestsopenai-agents-pythonrun-20261024-184640#4690

Issue #4690 Merged fix PR #4698 Run 24 Oct 2026 · run-20261024-184640 openai/openai-agents-python

Resumed terminal tool output cannot recover after a Session append failure

Better

Our patch was judged better than the merged fix.

In this judgment, Patch A = our agent, Patch B = the merged fix.

Both patches stop the retry from re-entering the model, and the independent matrix passes for both, but they implement different contracts from the issue and A matches the issue's ask far more fully. Patch A implements contract 1 (recoverable terminal continuation): once output guardrails accept the resumed NextStepFinalOutput it retains the output, the guardrail results, the tool-use snapshot, and routes the final append through the existing pending-session-write ownership so a fail-before or lost-ack batch is reconciled on resume and the original `receipt-7` is returned with no model, tool, hook, or guardrail repetition. It serializes the step as `next_step_final_output` with an explicit restorability flag, validates that payload on load (schema gate, exact key set, exact-JSON check), and for non-JSON-exact outputs still reconciles the Session and then raises a clear UserError rather than guessing. Its tests cover the full 16-row sync/stream x live/JSON x before/after matrix, the concurrent-writer fail-closed case, structured outputs, and malformed checkpoints. Patch B implements a form of contract 2, but only a boolean `terminal_unrecoverable` marker: it does not preserve the pending batch, the accepted output, or the guardrail results, so in the fail-before rows the Session permanently lacks the tool call/output pair and the caller (who in the sync path never received `receipt-7`) is told only to start a new run. The issue explicitly asked that even the reject option 'preserve an actionable, serializable recovery payload', which B does not do, and B never exercises the changed-history fail-closed path because it rejects before any Session work. B is simpler and lower-risk, and its extra max-turns-handler coverage is careful, but that is adjacent scope rather than the reported terminal-finalization failure. A carries more surface area (new step type, new fields, reconciliation reuse), yet it addresses the root cause described in the issue and is backed by substantive, matrix-shaped regression tests, so it is the better fix.

Four judges ruled on this ticket in parallel, and the verdict comes from counting their votes. Each saw the issue and the two patches, labelled A and B in random order (two of them saw ours as A), with issue links and version numbers removed. Where tests could check the fix, they also saw the results of tests a separate agent wrote for the issue, run on both patches. None was told which patch was ours. The reasoning above is one judge's, shown verbatim.

Solve

27m 59s

Wall-clock time in the container

Full test suite

No new failures

3,059 passed · 1 skipped · 3,060 total

Contamination audit

Clean

No sign the agent saw the real fix

Patch size

504vs 350 merged

Changed lines, ours vs merged

Please read this first

  • I read the Session, RunState, approval, lifecycle, and output-guardrail docs.
  • I searched open and closed issues/PRs for Session append, NextStepFinalOutput, and terminal tool-output persistence. The related work listed under Scope boundaries does not cover this terminal-finalization failure mode.

Describe the bug

After an approval-gated local tool completes, tool_use_behavior="stop_on_first_tool"
can make that tool output the terminal agent output. If the final client-managed
Session.add_items() append then fails, the exception is correctly propagated,
but the resulting RunState cannot recover or explicitly reject that accepted
terminal result.

At the failure boundary:

  • the live runtime step is NextStepFinalOutput;
  • JSON serialization records current_step = null;
  • there is no pending_session_write;
  • the passing output guardrail has already evaluated the original output, but its result is not retained in the failed state.

Retrying the same live or JSON-restored state therefore enters the model again,
runs the output guardrail again, and returns a new final output. The completed
tool effect is not repeated in this reproducer, but terminal output identity,
guardrail evidence, and durable Session history can diverge.

Debug information

  • Agents SDK: latest release v0.22.0, and exact current main@a40ae9803e6b7a79faa246293f56adb100d5868b
  • Exact src tree: 56eeb964e8924a6d0034b3e2289699c719f5450b
  • Python: 3.13.15
  • Operating system: macOS 26.5, arm64
  • Model/provider: deterministic public ScriptedModel; no provider, API key, network request, or timing race
  • Latest release: yes
  • Reproducibility: consistent; focused repro and all 16 frozen matrix rows

The injected exception is:

RuntimeError: injected Session.add_items failure before commit

Repro steps

This focused fail-before-commit case is self-contained and also reproduces
against the installed openai-agents==0.22.0 package:

<details>
<summary>Reproducer</summary>

import asyncio
import copy
import json
from typing import Any

from openai.types.responses import (
    ResponseFunctionToolCall,
    ResponseOutputMessage,
    ResponseOutputText,
)
from agents import (
    Agent,
    GuardrailFunctionOutput,
    RunContextWrapper,
    Runner,
    function_tool,
    output_guardrail,
)
from agents.run import RunConfig
from agents.testing import ScriptedModel


class FailingSession:
    def __init__(self):
        self.session_id = "terminal-write-repro"
        self.items = []
        self.fail_next = False

    async def get_items(self, limit=None):
        items = copy.deepcopy(self.items)
        return items[-limit:] if limit is not None else items

    async def add_items(self, items):
        if self.fail_next:
            self.fail_next = False
            raise RuntimeError("injected Session.add_items failure before commit")
        self.items.extend(copy.deepcopy(items))

    async def pop_item(self):
        return self.items.pop() if self.items else None

    async def clear_session(self):
        self.items.clear()


async def main():
    effects = []
    guardrail_outputs = []

    @function_tool(needs_approval=True)
    async def charge(amount: int) -> str:
        effects.append(amount)
        return f"receipt-{amount}"

    @output_guardrail
    async def record_output(
        context: RunContextWrapper[Any], agent: Agent[Any], output: Any
    ) -> GuardrailFunctionOutput:
        guardrail_outputs.append(str(output))
        return GuardrailFunctionOutput(output_info=output, tripwire_triggered=False)

    model = ScriptedModel(
        steps=[
            [
                ResponseFunctionToolCall(
                    id="fc-1",
                    call_id="charge-1",
                    type="function_call",
                    name="charge",
                    arguments=json.dumps({"amount": 7}),
                )
            ],
            [
                ResponseOutputMessage(
                    id="msg-2",
                    type="message",
                    role="assistant",
                    status="completed",
                    content=[
                        ResponseOutputText(
                            type="output_text",
                            text="retry-final",
                            annotations=[],
                            logprobs=[],
                        )
                    ],
                )
            ],
        ]
    )
    agent = Agent(
        name="terminal-write-repro",
        model=model,
        tools=[charge],
        tool_use_behavior="stop_on_first_tool",
        output_guardrails=[record_output],
    )
    session = FailingSession()
    config = RunConfig(tracing_disabled=True)

    paused = await Runner.run(agent, "charge 7", session=session, run_config=config)
    state = paused.to_state()
    state.approve(paused.interruptions[0])

    session.fail_next = True
    try:
        await Runner.run(agent, state, session=session, run_config=config)
    except RuntimeError as error:
        print(type(error).__name__, str(error))

    serialized = state.to_json()
    print(
        {
            "runtime_step": type(state._current_step).__name__,
            "serialized_step": serialized.get("current_step"),
            "pending_session_write": serialized.get("pending_session_write"),
            "retained_output_guardrails": len(state._output_guardrail_results),
            "model_calls": len(model.calls),
            "effects": effects,
            "guardrail_outputs": guardrail_outputs,
        }
    )

    retried = await Runner.run(agent, state, session=session, run_config=config)
    print(
        {
            "retry_output": retried.final_output,
            "model_calls": len(model.calls),
            "effects": effects,
            "guardrail_outputs": guardrail_outputs,
        }
    )


asyncio.run(main())

</details>

Observed output:

RuntimeError injected Session.add_items failure before commit
{'runtime_step': 'NextStepFinalOutput', 'serialized_step': None,
 'pending_session_write': None, 'retained_output_guardrails': 0,
 'model_calls': 1, 'effects': [7], 'guardrail_outputs': ['receipt-7']}
{'retry_output': 'retry-final', 'model_calls': 2, 'effects': [7],
 'guardrail_outputs': ['receipt-7', 'retry-final']}

Frozen behavior matrix

I also froze a 16-row Cartesian product before inspecting results:

DimensionValues
failing resume runnersync, stream
retry runnersync, stream
retry statesame live object, JSON round trip
append failurefail before commit, commit then raise (lost acknowledgement)

The tool is charge(amount=7), its exact output is receipt-7, and a second
scripted response retry-final exists only to expose a new model call.

ObservationRows
injected append failure propagated16 / 16
retry completed16 / 16
tool effect and tool start/end hooks remained exactly once16 / 16
first output guardrail evaluated receipt-7 before failure16 / 16
pending terminal Session checkpoint retained after failure0 / 16
first passing output-guardrail result retained after failure0 / 16
original receipt-7 recovered without another model call0 / 16
retry made a second model call and returned retry-final16 / 16
durable Session contained one exact call/output pair after retry8 / 16
public replay and retry model input contained one exact pair16 / 16

The eight durable-Session successes are only the append-then-raise rows: the
pair had already committed before the simulated lost acknowledgement. Those
rows still make a second model call because no terminal checkpoint recognizes
the committed batch as the already accepted result. In all eight
fail-before-commit rows, the Session lacks the tool call/output even after
retry, while replay/model input contain the pair and the Session contains the
later assistant message.

Relevant control flow

At the pinned commit:

  • the resumed state is updated, but the pre-guardrail save is skipped for NextStepFinalOutput in 1;
  • output guardrails run before the final append and result construction in 0;
  • resumed pending-write ownership is limited to NextStepRunAgain and NextStepInterruption in 2;
  • RunState declares only those two resumable steps and serializes a terminal runtime step as null in 2 and 3;
  • the streamed terminal path has the same guardrail-then-save boundary in 0.

Expected behavior / design question

I do not want to force terminal finalization into NextStepRunAgain: the
matrix shows that doing so re-enters the model and changes an already accepted
terminal result.

Would maintainers prefer one of these contracts?

  1. Recoverable terminal continuation. Persist enough state to own the pending terminal batch, accepted final output, and completed guardrail results; reconcile the same Session before any model call. An unchanged fail-before tail can append and finalize, and a provable lost acknowledgement can finalize without repeating model/tool/hooks/guardrails.
  2. Explicitly non-resumable terminal failure. Preserve an actionable, serializable recovery payload, but reject subsequent Runner.run*() calls before model execution instead of silently treating the state as run-again.

For either choice, changed, partial, or concurrently modified Session history
should fail closed rather than guess. Sync/stream and live/JSON recovery should
have the same contract.

I can prepare the focused implementation and regression matrix after the
contract is selected.

Scope boundaries

  • This is narrower than distributed exactly-once execution. It does not cover process death before state capture, independent concurrent state copies, non-atomic partial appends, or external tools without idempotency.
  • #4630 covers NextStepRunAgain; #4650 covers renewed interruption; #4685 covers handoff. This issue is only terminal NextStepFinalOutput.
  • #2695 covers approval argument overrides, not terminal Session ownership.
  • #4125 and its fixes cover output-guardrail tripwire history, not recovery after a successful guardrail followed by append failure.
  • The broader closed #4621 was superseded by the narrower maintainer change in #4630; this report does not reuse that implementation.

Evidence integrity

The full provider-neutral harness was run twice with byte-identical JSON and
JSONL results. Its standard-library verifier reconstructs the pinned Git tree,
checks all 315 source files and every trace/state/Session/model cross-field
relationship, and rejects re-sealed source/trace/state/package-boundary
mutations in negative tests.

  • source snapshot SHA-256: 5779a3d6d2e2e94b078d85785b0886d470636cd7513b4946d35c46340f448417
  • baseline JSON SHA-256: 5f4102aef87b7875f61562ac6f649437fc711edfb29f92ae5815e1665ff757ae
  • baseline JSONL SHA-256: 49e7bca13ca4d1fd155ab34b3ca38a8734f9c0ba5d06ffd06e11100ae20d27c1
  • external manifest root SHA-256: f53612af88d0180b55bfb58ea5fe12cf8db251b583c9050e8b655010d28aad46

The two patches

Our patch+495 −9
src/agents/result.pyindex 0ceb0d71..4c491a42 100644@@ -150,6 +150,8 @@ def _populate_state_from_result(         state._pending_input = copy.deepcopy(source_state._pending_input)         state._pending_session_write = copy.deepcopy(source_state._pending_session_write)         state._current_step = source_state._current_step+        state._final_output_accepted = source_state._final_output_accepted+        state._final_output_restorable = source_state._final_output_restorable     else:         state._generated_prompt_cache_key = getattr(result, "_generated_prompt_cache_key", None)         state._pending_input = copy.deepcopy(getattr(result, "_pending_input_for_state", []))src/agents/run.pyindex 37dd6658..6a5ad674 100644@@ -134,6 +134,8 @@ from .run_internal.run_steps import ( ) from .run_internal.session_persistence import (     _session_get_items,+    accept_resumed_final_output,+    accepted_final_output_to_return,     admit_pending_input,     commit_server_pending_input,     persist_session_items_for_guardrail_trip,@@ -1062,6 +1064,35 @@ class AgentRunner:                             wrapper=context_wrapper,                         )                         session_input_items_for_persistence = []+                    accepted_final_output = accepted_final_output_to_return(run_state)+                    if accepted_final_output is not None and run_state is not None:+                        # The pending terminal batch was reconciled before this loop. Return the+                        # output that guardrails already accepted instead of calling the model.+                        result = RunResult(+                            input=copy_input_items(original_input),+                            new_items=session_items,+                            raw_responses=model_responses,+                            final_output=accepted_final_output.output,+                            _last_agent=current_agent,+                            input_guardrail_results=input_guardrail_results,+                            output_guardrail_results=output_guardrail_results,+                            tool_input_guardrail_results=tool_input_guardrail_results,+                            tool_output_guardrail_results=tool_output_guardrail_results,+                            context_wrapper=context_wrapper,+                            interruptions=[],+                            _tool_use_tracker_snapshot=_tool_use_tracker_snapshot(),+                            max_turns=max_turns,+                        )+                        result._current_turn = current_turn+                        result._model_input_items = list(generated_items)+                        result._replay_from_model_input_items = list(generated_items) != list(+                            session_items+                        )+                        result._trace_state = run_state._trace_state+                        result._original_input = copy_input_items(original_input)+                        run_state._current_step = None+                        run_state._final_output_accepted = False+                        return _finalize_result(result)                     if run_state is not None and run_state._current_step is not None:                         if isinstance(run_state._current_step, NextStepInterruption):                             logger.debug("Continuing from interruption")@@ -1367,6 +1398,15 @@ class AgentRunner:                                     current_agent,                                     run_config,                                 )+                                run_state._model_responses = list(model_responses)+                                accept_resumed_final_output(+                                    run_state,+                                    final_output=turn_result.next_step,+                                    output_guardrail_results=output_guardrail_results,+                                    tool_input_guardrail_results=tool_input_guardrail_results,+                                    tool_output_guardrail_results=tool_output_guardrail_results,+                                    tool_use_tracker_snapshot=_tool_use_tracker_snapshot(),+                                )                                 await save_final_turn_items_after_guardrails(                                     session=session,                                     run_state=run_state,@@ -1405,6 +1445,7 @@ class AgentRunner:                                     result._trace_state = run_state._trace_state                                 result._original_input = copy_input_items(original_input)                                 run_state._current_step = None+                                run_state._final_output_accepted = False                                 return _finalize_result(result)                             elif isinstance(turn_result.next_step, NextStepHandoff):                                 current_agent = cast(src/agents/run_internal/agent_runner_helpers.pyindex be1d9767..3e0a747e 100644@@ -571,6 +571,12 @@ async def save_final_turn_items_after_guardrails(         return 0     if input_guardrails_triggered(input_guardrail_results):         return 0+    # An accepted resumed terminal output owns its batch so a failed append stays recoverable.+    terminal_write_state = (+        run_state+        if run_state is not None and run_state._accepted_final_output() is not None+        else None+    )     if run_state is not None and run_state._current_turn_persisted_item_count > 0:         run_state._current_turn_persisted_item_count = await save_resumed_turn_items(             session=session,@@ -580,6 +586,7 @@ async def save_final_turn_items_after_guardrails(             reasoning_item_id_policy=run_state._reasoning_item_id_policy,             store=store,             wrapper=wrapper,+            run_state=terminal_write_state,         )         return run_state._current_turn_persisted_item_count     return await save_result_to_session(@@ -591,6 +598,7 @@ async def save_final_turn_items_after_guardrails(         reasoning_item_id_policy=reasoning_item_id_policy,         store=store,         wrapper=wrapper,+        resumed_write_state=terminal_write_state,     )  src/agents/run_internal/run_loop.pyindex 3c7d9ee5..1b80b257 100644@@ -172,6 +172,8 @@ from .run_steps import ( ) from .session_persistence import (     _session_get_items,+    accept_resumed_final_output,+    accepted_final_output_to_return,     admit_pending_input,     commit_server_pending_input,     persist_session_items_for_guardrail_trip,@@ -477,6 +479,26 @@ async def _run_output_guardrails_for_stream(         raise  +def _resumed_final_output_acceptor(+    run_state: RunState[Any],+    final_output: NextStepFinalOutput,+    streamed_result: RunResultStreaming,+) -> Callable[[], None]:+    """Retain a resumed terminal output with the stream's results once guardrails accept it."""++    def accept() -> None:+        accept_resumed_final_output(+            run_state,+            final_output=final_output,+            output_guardrail_results=streamed_result.output_guardrail_results,+            tool_input_guardrail_results=streamed_result.tool_input_guardrail_results,+            tool_output_guardrail_results=streamed_result.tool_output_guardrail_results,+            tool_use_tracker_snapshot=streamed_result._tool_use_tracker_snapshot,+        )++    return accept++ def _retained_items_for_blocked_output(     items: list[RunItem],     model_response: ModelResponse | None = None,@@ -503,6 +525,7 @@ async def _finalize_streamed_final_output(     response_id: str | None,     store_setting: bool | None,     on_persisted_after_guardrails: Callable[[bool], None] | None = None,+    on_output_accepted: Callable[[], None] | None = None, ) -> None:     output_guardrail_result_start = len(streamed_result.output_guardrail_results)     redacted_persistence_error: BaseException | None = None@@ -624,6 +647,8 @@ async def _finalize_streamed_final_output(         agent,         run_config,     )+    if on_output_accepted is not None:+        on_output_accepted()      # Saved as one ordered batch so the session mirrors the model response. Doing it in two     # halves would both reorder the turn and, because the first save advances the turn's@@ -1265,6 +1290,19 @@ async def start_streaming(                     run_state._nested_history_owned_session_item_refs = list(retained_owned_refs)                 sandbox_runtime.apply_result_metadata(streamed_result) +            accepted_final_output = (+                accepted_final_output_to_return(run_state) if is_resumed_state else None+            )+            if accepted_final_output is not None and run_state is not None:+                # The pending terminal batch was reconciled before this loop. Return the output+                # that guardrails already accepted instead of calling the model.+                streamed_result.final_output = accepted_final_output.output+                run_state._current_step = None+                run_state._final_output_accepted = False+                streamed_result.is_complete = True+                streamed_result._event_queue.put_nowait(QueueCompleteSentinel())+                break+             if is_resumed_state and run_state is not None and run_state._current_step is not None:                 if isinstance(run_state._current_step, NextStepInterruption):                     if not run_state._model_responses:@@ -1454,10 +1492,16 @@ async def start_streaming(                             owner_starts=blocked_output_owner_starts,                             response_id=turn_result.model_response.response_id,                             store_setting=store_setting,+                            on_output_accepted=_resumed_final_output_acceptor(+                                run_state,+                                turn_result.next_step,+                                streamed_result,+                            ),                         )                         if streamed_result._stored_exception is not None:                             break                         run_state._current_step = None+                        run_state._final_output_accepted = False                         break                      if isinstance(turn_result.next_step, NextStepRunAgain):src/agents/run_internal/session_persistence.pyindex de5d3e6b..357b77b9 100644@@ -11,8 +11,8 @@ import hashlib import inspect import json from collections import deque-from collections.abc import Sequence-from typing import Any, cast+from collections.abc import Mapping, Sequence+from typing import TYPE_CHECKING, Any, cast  from .. import _debug from ..exceptions import UserError@@ -62,6 +62,7 @@ from .items import ( ) from .oai_conversation import OpenAIServerConversationTracker from .run_steps import (+    NextStepFinalOutput,     NextStepHandoff,     NextStepInterruption,     NextStepRunAgain,@@ -69,7 +70,13 @@ from .run_steps import (     SingleStepResult, ) +if TYPE_CHECKING:+    from ..guardrail import OutputGuardrailResult+    from ..tool_guardrails import ToolInputGuardrailResult, ToolOutputGuardrailResult+ __all__ = [+    "accept_resumed_final_output",+    "accepted_final_output_to_return",     "admit_pending_input",     "commit_server_pending_input",     "prepare_input_with_session",@@ -577,7 +584,53 @@ def update_run_state_after_resume(         # "run again". Normalizing here, before the fallible Session append, lets the existing         # pending-write checkpoint carry the handoff batch without a new persisted step type.         next_step = NextStepRunAgain()-    run_state._current_step = next_step  # type: ignore[assignment]+    run_state._current_step = next_step+    # Output guardrails have not judged this step yet.+    run_state._final_output_accepted = False+    run_state._final_output_restorable = True+++def accept_resumed_final_output(+    run_state: RunState,+    *,+    final_output: NextStepFinalOutput,+    output_guardrail_results: Sequence[OutputGuardrailResult],+    tool_input_guardrail_results: Sequence[ToolInputGuardrailResult],+    tool_output_guardrail_results: Sequence[ToolOutputGuardrailResult],+    tool_use_tracker_snapshot: Mapping[str, Sequence[str]],+) -> None:+    """Retain a resumed terminal output once output guardrails accepted it.++    Called before the fallible final Session append, so a failed append leaves a state that+    reconciles the pending batch and returns this output instead of calling the model again.+    """+    run_state._current_step = final_output+    run_state._output_guardrail_results = list(output_guardrail_results)+    run_state._tool_input_guardrail_results = list(tool_input_guardrail_results)+    run_state._tool_output_guardrail_results = list(tool_output_guardrail_results)+    run_state.set_tool_use_tracker_snapshot(tool_use_tracker_snapshot)+    run_state._final_output_accepted = True+    run_state._final_output_restorable = True+++def accepted_final_output_to_return(run_state: RunState | None) -> NextStepFinalOutput | None:+    """Return an accepted terminal output to finalize without another model call.++    Call only after ``resume_pending_session_write`` settled the terminal batch. Raises when a+    restored snapshot could not carry the original output, rather than producing a new one.+    """+    if run_state is None:+        return None+    final_output = run_state._accepted_final_output()+    if final_output is None:+        return None+    if not run_state._final_output_restorable:+        raise UserError(+            "This RunState already accepted a final output that could not be serialized, so the "+            "restored snapshot cannot return it. Its Session write is reconciled; finish from the "+            "original live RunState or start a new run instead of calling the model again."+        )+    return final_output   async def save_result_to_session(@@ -780,7 +833,10 @@ async def save_resumed_turn_items(         resumed_write_state=(             run_state             if run_state is not None-            and isinstance(run_state._current_step, NextStepRunAgain | NextStepInterruption)+            and (+                isinstance(run_state._current_step, NextStepRunAgain | NextStepInterruption)+                or run_state._accepted_final_output() is not None+            )             else None         ),     )src/agents/run_state.pyindex 732e768d..d84cdbff 100644@@ -148,6 +148,7 @@ if TYPE_CHECKING:     from .guardrail import InputGuardrailResult, OutputGuardrailResult     from .items import ModelResponse, RunItem     from .run_internal.run_steps import (+        NextStepFinalOutput,         NextStepInterruption,         NextStepRunAgain,         ProcessedResponse,@@ -227,7 +228,8 @@ SCHEMA_VERSION_SUMMARIES: dict[str, str] = {     ),     "1.17": (         "Persists Docker container labels and current-response generated-item ownership across "-        "resume flows, including pending resumed Session writes."+        "resume flows, including pending resumed Session writes and accepted terminal outputs "+        "awaiting their final Session write."     ), } SUPPORTED_SCHEMA_VERSIONS = frozenset(SCHEMA_VERSION_SUMMARIES)@@ -775,6 +777,12 @@ class RunState(Generic[TContext, TAgent]):     Changed or ambiguous history requires application repair. Independently restored snapshots must     not be resumed concurrently against the same Session. +    The same applies when resumed tool work produces the terminal output: once output guardrails+    accept it, a failed final Session append keeps that output, its guardrail results, and the+    pending batch. Resuming reconciles the batch and returns the accepted output without another+    model call. A serialized snapshot can only restore an output that round-trips through JSON+    unchanged; otherwise resuming it reconciles the Session and then raises ``UserError``.+     Context serialization is intentionally conservative:      - Mapping contexts round-trip directly.@@ -845,8 +853,11 @@ class RunState(Generic[TContext, TAgent]):     _tool_output_guardrail_results: list[ToolOutputGuardrailResult] = field(default_factory=list)     """Results from tool output guardrails applied during the run.""" -    _current_step: NextStepInterruption | NextStepRunAgain | None = None-    """Current resumable step, or ``None`` when the state is terminal."""+    _current_step: NextStepInterruption | NextStepRunAgain | NextStepFinalOutput | None = None+    """Current resumable step, or ``None`` when the state is terminal.++    ``NextStepFinalOutput`` is only resumable once ``_final_output_accepted`` is set.+    """      _last_processed_response: ProcessedResponse | None = None     """The last processed model response. This is needed for resuming from interruptions."""@@ -878,6 +889,12 @@ class RunState(Generic[TContext, TAgent]):     _session_write_in_progress: bool = field(default=False, repr=False)     """Live ownership guard; independent serialized copies require caller serialization.""" +    _final_output_accepted: bool = field(default=False, repr=False)+    """Whether output guardrails accepted the current ``NextStepFinalOutput``."""++    _final_output_restorable: bool = field(default=True, repr=False)+    """Whether the accepted final output is the original value rather than a lost one."""+     def __init__(         self,         context: RunContextWrapper[TContext],@@ -920,10 +937,20 @@ class RunState(Generic[TContext, TAgent]):         self._schema_version = CURRENT_SCHEMA_VERSION         self._pending_session_write = None         self._session_write_in_progress = False+        self._final_output_accepted = False+        self._final_output_restorable = True         from .agent_tool_state import get_agent_tool_state_scope          self._agent_tool_state_scope_id = get_agent_tool_state_scope(context) +    def _accepted_final_output(self) -> NextStepFinalOutput | None:+        """Return the guardrail-accepted terminal step that still awaits finalization."""+        from .run_internal.run_steps import NextStepFinalOutput++        if self._final_output_accepted and isinstance(self._current_step, NextStepFinalOutput):+            return self._current_step+        return None+     def _copy_for_result_checkpoint(self) -> RunState[TContext, TAgent]:         """Copy SDK-owned decision state when nesting this checkpoint in a result snapshot."""         copied = copy.copy(self)@@ -1990,6 +2017,19 @@ class RunState(Generic[TContext, TAgent]):         if isinstance(self._current_step, NextStepRunAgain):             return {"type": "next_step_run_again"} +        accepted_final_output = self._accepted_final_output()+        if accepted_final_output is not None:+            restorable = self._final_output_restorable and _is_exact_json_value(+                accepted_final_output.output+            )+            return {+                "type": "next_step_final_output",+                "data": {+                    "output": copy.deepcopy(accepted_final_output.output) if restorable else None,+                    "output_restorable": restorable,+                },+            }+         if self._current_step is None or not isinstance(self._current_step, NextStepInterruption):             return None @@ -2841,6 +2881,19 @@ class _DeserializedFunctionAction:     nested_agent_run_state_data: Mapping[str, Any] | None  +def _is_exact_json_value(value: Any) -> bool:+    """Return whether a JSON round trip reproduces ``value`` with the same types."""+    if value is None or type(value) in (str, bool, int):+        return True+    if type(value) is float:+        return math.isfinite(value)+    if type(value) is list:+        return all(_is_exact_json_value(item) for item in value)+    if type(value) is dict:+        return all(type(key) is str and _is_exact_json_value(item) for key, item in value.items())+    return False++ def _serialize_guardrail_results(     results: Sequence[InputGuardrailResult | OutputGuardrailResult],     *,@@ -4354,6 +4407,28 @@ async def _build_run_state_from_json(             state._clear_generated_items_last_processed_marker()         for approval_item in state._current_step.interruptions:             context._mark_restored_unbound_pending_approval(approval_item)+    elif current_step_data and current_step_data.get("type") == "next_step_final_output":+        final_output_data = current_step_data.get("data")+        if (+            (schema_major, schema_minor) < (1, 17)+            or not isinstance(final_output_data, Mapping)+            or set(final_output_data) != {"output", "output_restorable"}+            or type(final_output_data["output_restorable"]) is not bool+            or not _is_exact_json_value(final_output_data["output"])+            or (+                not final_output_data["output_restorable"]+                and final_output_data["output"] is not None+            )+        ):+            raise validation_error_factory(+                "Run state accepted final output is invalid",+                UserError,+            )+        from .run_internal.run_steps import NextStepFinalOutput++        state._current_step = NextStepFinalOutput(output=copy.deepcopy(final_output_data["output"]))+        state._final_output_accepted = True+        state._final_output_restorable = final_output_data["output_restorable"]      state._current_turn_persisted_item_count = state_json.get(         "current_turn_persisted_item_count", 0@@ -4364,7 +4439,10 @@ async def _build_run_state_from_json(          if (             (schema_major, schema_minor) < (1, 17)-            or not isinstance(state._current_step, NextStepRunAgain | NextStepInterruption)+            or not (+                isinstance(state._current_step, NextStepRunAgain | NextStepInterruption)+                or state._accepted_final_output() is not None+            )             or not isinstance(pending_write, dict)             or set(pending_write) != {"session_id", "items", "before", "persisted_count"}             or not isinstance(pending_write.get("session_id"), str)@@ -5172,6 +5250,7 @@ _TRUSTED_RUN_STATE_ERROR_MESSAGES = frozenset(         "Run state agent not found in agent map",         "Run state pending_input must be a list",         "Run state pending Session write is invalid",+        "Run state accepted final output is invalid",         "Run state references an agent identity that is not present in the restored graph",         (             "RunState context was serialized from a custom type; provide context_deserializer "tests/test_run_impl_resume_paths.pyindex 8e6211ce..2fb6e9e2 100644@@ -1,5 +1,6 @@ import asyncio import copy+import dataclasses import json from pathlib import Path from types import SimpleNamespace@@ -9,7 +10,14 @@ import pytest from openai.types.responses import ResponseFunctionToolCall, ResponseOutputMessage  import agents.run as run_module-from agents import Agent, Runner, function_tool, handoff+from agents import (+    Agent,+    GuardrailFunctionOutput,+    Runner,+    function_tool,+    handoff,+    output_guardrail,+) from agents.agent import ToolsToFinalOutputResult from agents.agent_output import AgentOutputSchema from agents.decorators import tool, tool_input_guardrail, tool_output_guardrail@@ -1221,3 +1229,251 @@ async def test_resumed_handoff_session_append_is_recovered_before_next_model(     assert _call_pair(result.to_input_list(), "charge-1") == expected_pair     assert _call_pair(result.to_input_list(), "handoff-1") == expected_pair     assert "pending_session_write" not in result.to_state().to_json()+++@dataclasses.dataclass+class _Receipt:+    amount: int+++async def _approved_terminal_session_state(streamed: bool, *, structured_output: bool = False):+    """Pause on an approval-gated tool whose output becomes the terminal agent output."""+    effects: list[int] = []+    guardrail_outputs: list[Any] = []+    hook_calls: list[str] = []++    class CountingHooks(RunHooks[Any]):+        async def on_tool_start(+            self,+            context: RunContextWrapper[Any],+            agent: Agent[Any],+            tool: Tool,+        ) -> None:+            hook_calls.append("tool-start")++        async def on_tool_end(+            self,+            context: RunContextWrapper[Any],+            agent: Agent[Any],+            tool: Tool,+            result: object,+        ) -> None:+            hook_calls.append("tool-end")++        async def on_agent_end(+            self,+            context: RunContextWrapper[Any],+            agent: Agent[Any],+            output: Any,+        ) -> None:+            hook_calls.append("agent-end")++    @output_guardrail+    async def record_output(+        context: RunContextWrapper[Any], agent: Agent[Any], output: Any+    ) -> GuardrailFunctionOutput:+        guardrail_outputs.append(output)+        return GuardrailFunctionOutput(output_info=str(output), tripwire_triggered=False)++    @tool(needs_approval=True)+    async def charge(amount: int) -> str:+        effects.append(amount)+        return f"receipt-{amount}"++    def structured_receipt(+        context: RunContextWrapper[Any], results: list[Any]+    ) -> ToolsToFinalOutputResult:+        # A custom behavior can make a value without an exact JSON form the terminal output.+        return ToolsToFinalOutputResult(is_final_output=True, final_output=_Receipt(7))++    model = ScriptedModel(+        [+            [get_function_tool_call("charge", '{"amount":7}', call_id="charge-1")],+            [get_text_message("retry-final")],+            [get_text_message("follow-up")],+        ]+    )+    agent = Agent(+        name="terminal",+        model=model,+        tools=[charge],+        tool_use_behavior=structured_receipt if structured_output else "stop_on_first_tool",+        output_type=_Receipt if structured_output else None,+        output_guardrails=[record_output],+    )+    hooks = CountingHooks()+    session = _FailingResumeSession()+    paused = await _run_session_resume(agent, "charge 7", session, streamed, hooks)+    state = paused.to_state()+    state.approve(state.get_interruptions()[0])+    return agent, model, session, state, effects, guardrail_outputs, hook_calls, hooks+++async def _fail_terminal_append(+    agent: Agent[Any],+    state: RunState[Any],+    session: _FailingResumeSession,+    streamed: bool,+    hooks: RunHooks[Any],+    failure: str,+) -> RunState[Any]:+    session.failure = failure+    if not streamed:+        with pytest.raises(RuntimeError) as error:+            await _run_session_resume(agent, state, session, False, hooks)+        assert error.value is session.error+        return state+    failed_result = Runner.run_streamed(+        agent,+        state,+        session=session,+        run_config=RunConfig(tracing_disabled=True),+        hooks=hooks,+    )+    with pytest.raises(RuntimeError) as error:+        async for _ in failed_result.stream_events():+            pass+    assert error.value is session.error+    return failed_result.to_state()+++@pytest.mark.asyncio+@pytest.mark.parametrize(+    "failing_streamed,retry_streamed", [(False, False), (False, True), (True, False), (True, True)]+)+@pytest.mark.parametrize("round_trip", [False, True], ids=["live", "json"])+@pytest.mark.parametrize("failure", ["before", "after"], ids=["atomic-failure", "lost-ack"])+async def test_resumed_terminal_output_session_append_is_recovered_without_model_call(+    failing_streamed: bool, retry_streamed: bool, round_trip: bool, failure: str+) -> None:+    (+        agent,+        model,+        session,+        state,+        effects,+        guardrail_outputs,+        hook_calls,+        hooks,+    ) = await _approved_terminal_session_state(failing_streamed)+    state = await _fail_terminal_append(agent, state, session, failing_streamed, hooks, failure)+    assert effects == [7]+    assert guardrail_outputs == ["receipt-7"]+    assert hook_calls == ["tool-start", "tool-end", "agent-end"]+    assert len(model.calls) == 1++    failed_payload = state.to_json()+    assert failed_payload["current_step"] == {+        "type": "next_step_final_output",+        "data": {"output": "receipt-7", "output_restorable": True},+    }+    pending_items = cast(list[TResponseInputItem], failed_payload["pending_session_write"]["items"])+    assert _charge_pair(pending_items) == ["function_call", "function_call_output"]+    assert [+        entry["output"]["outputInfo"] for entry in failed_payload["output_guardrail_results"]+    ] == ["receipt-7"]+    if round_trip:+        state = await RunState.from_json(agent, failed_payload)++    result = await _run_session_resume(agent, state, session, retry_streamed, hooks)+    assert result.final_output == "receipt-7"+    assert [item.output.output_info for item in result.output_guardrail_results] == ["receipt-7"]+    assert len(model.calls) == 1+    assert effects == [7]+    assert guardrail_outputs == ["receipt-7"]+    assert hook_calls == ["tool-start", "tool-end", "agent-end"]+    expected_pair = ["function_call", "function_call_output"]+    assert _charge_pair(await session.get_items()) == expected_pair+    assert _charge_pair(result.to_input_list()) == expected_pair+    completed_payload = result.to_state().to_json()+    assert "pending_session_write" not in completed_payload+    assert completed_payload["current_step"] is None++    follow_up = await _run_session_resume(agent, "What was the receipt?", session, retry_streamed)+    assert follow_up.final_output == "retry-final"+    assert _charge_pair(model.calls[-1].input) == expected_pair+++@pytest.mark.asyncio+@pytest.mark.parametrize("retry_streamed", [False, True])+async def test_resumed_terminal_output_rejects_changed_session_history(+    retry_streamed: bool,+) -> None:+    (+        agent,+        model,+        session,+        state,+        effects,+        guardrail_outputs,+        _,+        hooks,+    ) = await _approved_terminal_session_state(False)+    await _fail_terminal_append(agent, state, session, False, hooks, "before")+    state = await RunState.from_json(agent, state.to_json())+    await session.add_items([{"role": "user", "content": "another writer"}])+    before = await session.get_items()+    with pytest.raises(UserError, match="history changed or is ambiguous"):+        await _run_session_resume(agent, state, session, retry_streamed, hooks)+    assert len(model.calls) == 1+    assert effects == [7]+    assert guardrail_outputs == ["receipt-7"]+    assert await session.get_items() == before+++@pytest.mark.asyncio+@pytest.mark.parametrize("retry_streamed", [False, True])+@pytest.mark.parametrize("round_trip", [False, True], ids=["live", "json"])+async def test_resumed_terminal_structured_output_recovery_never_reruns_model(+    retry_streamed: bool, round_trip: bool+) -> None:+    (+        agent,+        model,+        session,+        state,+        effects,+        guardrail_outputs,+        _,+        hooks,+    ) = await _approved_terminal_session_state(False, structured_output=True)+    await _fail_terminal_append(agent, state, session, False, hooks, "before")+    payload = state.to_json()+    assert payload["current_step"] == {+        "type": "next_step_final_output",+        "data": {"output": None, "output_restorable": False},+    }+    expected_pair = ["function_call", "function_call_output"]+    if not round_trip:+        result = await _run_session_resume(agent, state, session, retry_streamed, hooks)+        assert result.final_output == _Receipt(7)+        assert len(model.calls) == 1+        assert _charge_pair(await session.get_items()) == expected_pair+        return++    state = await RunState.from_json(agent, payload)+    for _ in range(2):+        with pytest.raises(UserError, match="could not be serialized"):+            await _run_session_resume(agent, state, session, retry_streamed, hooks)+        assert len(model.calls) == 1+        assert effects == [7]+        assert guardrail_outputs == [_Receipt(7)]+        # The pending batch is still reconciled before the run is rejected.+        assert _charge_pair(await session.get_items()) == expected_pair+        assert "pending_session_write" not in state.to_json()+++@pytest.mark.asyncio+@pytest.mark.parametrize("invalid", ["old-schema", "unknown-field", "lost-output"])+async def test_accepted_final_output_rejects_invalid_serialized_checkpoint(invalid: str) -> None:+    agent, _, session, state, _, _, _, hooks = await _approved_terminal_session_state(False)+    await _fail_terminal_append(agent, state, session, False, hooks, "before")+    payload = state.to_json()+    if invalid == "old-schema":+        payload["$schemaVersion"] = "1.16"+    elif invalid == "unknown-field":+        payload["current_step"]["data"]["extra"] = True+    else:+        payload["current_step"]["data"]["output_restorable"] = False+    with pytest.raises(UserError, match="accepted final output is invalid"):+        await RunState.from_json(agent, payload) 
Merged fix · PR #4698+348 −2
src/agents/result.pyindex 0ceb0d718..a5340edb3 100644@@ -150,6 +150,9 @@ def _populate_state_from_result(         state._pending_input = copy.deepcopy(source_state._pending_input)         state._pending_session_write = copy.deepcopy(source_state._pending_session_write)         state._current_step = source_state._current_step+        # A streamed result exists before its terminal append does, so a checkpoint taken from a+        # failed stream has to keep the fail-closed marker or it would look resumable.+        state._terminal_unrecoverable = source_state._terminal_unrecoverable     else:         state._generated_prompt_cache_key = getattr(result, "_generated_prompt_cache_key", None)         state._pending_input = copy.deepcopy(getattr(result, "_pending_input_for_state", []))src/agents/run.pyindex 37dd66582..abb72a161 100644@@ -70,6 +70,7 @@ from .run_internal.agent_runner_helpers import (     finalize_conversation_tracking,     get_unsent_tool_call_ids_for_interrupted_state,     input_guardrails_triggered,+    reject_unrecoverable_terminal_state,     resolve_processed_response,     resolve_resumed_context,     resolve_trace_settings,@@ -635,6 +636,7 @@ class AgentRunner:             )             context = context_wrapper.context +            reject_unrecoverable_terminal_state(run_state)             await resume_pending_session_write(run_state, session, wrapper=context_wrapper)             max_turns = run_state._max_turns         else:@@ -1367,6 +1369,11 @@ class AgentRunner:                                     current_agent,                                     run_config,                                 )+                                # The output, its guardrails, and its terminal hooks are all+                                # complete, so from here until the turn is persisted this run owns+                                # a result no resume can reproduce.+                                if run_state is not None:+                                    run_state._terminal_unrecoverable = True                                 await save_final_turn_items_after_guardrails(                                     session=session,                                     run_state=run_state,@@ -1377,6 +1384,10 @@ class AgentRunner:                                     store=store_setting,                                     wrapper=context_wrapper,                                 )+                                # The append and any post-append maintenance both succeeded,+                                # so the turn is durable and the state is open again.+                                if run_state is not None:+                                    run_state._terminal_unrecoverable = False                                 current_step = getattr(run_state, "_current_step", None)                                 approvals_from_state = approvals_from_step(current_step)                                 result = RunResult(@@ -1550,7 +1561,16 @@ class AgentRunner:                             include_in_history=include_in_history,                         )                         if include_in_history and not handler_output_recorded:+                            # Only reachable once the handler output cleared its guardrails and+                            # ran its end hooks, so this append carries an accepted result like+                            # any other terminal one. The callback itself stays unmarked because+                            # finalize_max_turns_handler_output() also drives it from its+                            # guardrail-error path, where no output was ever accepted.+                            if run_state is not None:+                                run_state._terminal_unrecoverable = True                             await _save_max_turns_handler_output([synthesized_item])+                            if run_state is not None:+                                run_state._terminal_unrecoverable = False                         current_step = getattr(run_state, "_current_step", None)                         approvals_from_state = approvals_from_step(current_step)                         result = RunResult(@@ -1994,6 +2014,8 @@ class AgentRunner:                                 current_agent,                                 run_config,                             )+                            if run_state is not None:+                                run_state._terminal_unrecoverable = True                             await save_final_turn_items_after_guardrails(                                 session=session,                                 run_state=run_state,@@ -2004,6 +2026,8 @@ class AgentRunner:                                 store=store_setting,                                 wrapper=context_wrapper,                             )+                            if run_state is not None:+                                run_state._terminal_unrecoverable = False                              # Ensure starting_input is not None and not RunState                             final_output_result_input: str | list[TResponseInputItem] = (src/agents/run_internal/agent_runner_helpers.pyindex be1d97672..6662f71e2 100644@@ -53,6 +53,7 @@ __all__ = [     "build_interruption_result",     "build_resumed_stream_debug_extra",     "describe_run_state_step",+    "reject_unrecoverable_terminal_state",     "ensure_context_wrapper",     "finalize_conversation_tracking",     "get_unsent_tool_call_ids_for_interrupted_state",@@ -491,6 +492,22 @@ def build_interruption_result(     return result  +def reject_unrecoverable_terminal_state(run_state: RunState | None) -> None:+    """Fail closed when a previous run already produced a final output that cannot be reproduced.++    The marker is set once that output, its guardrails, and its terminal hooks have completed,+    and is cleared only once the turn is fully persisted. In between, the run owns a result no+    resume can settle, so resuming would repeat the model call and the lifecycle hooks for an+    output the caller already received. Raised before any Session, sandbox, model, tool,+    guardrail, or hook work so the rejection has no side effects of its own.+    """+    if run_state is not None and run_state._terminal_unrecoverable:+        raise UserError(+            "This RunState already produced a final output whose Session write did not "+            "complete, so it cannot be resumed. Start a new run instead."+        )++ def append_model_response_if_new(     model_responses: list[ModelResponse],     response: ModelResponse,src/agents/run_internal/run_loop.pyindex 3c7d9ee58..9871a5404 100644@@ -102,6 +102,7 @@ from .agent_runner_helpers import (     apply_resumed_conversation_settings,     attach_usage_to_span,     get_unsent_tool_call_ids_for_interrupted_state,+    reject_unrecoverable_terminal_state,     snapshot_usage,     usage_delta,     validate_output_guardrails_with_server_managed_conversation,@@ -628,6 +629,10 @@ async def _finalize_streamed_final_output(     # Saved as one ordered batch so the session mirrors the model response. Doing it in two     # halves would both reorder the turn and, because the first save advances the turn's     # persisted-item count, make the second one a no-op.+    # The output, its guardrails, and its terminal hooks are all complete, so from here until+    # the turn is persisted this run owns a result no resume can reproduce.+    if streamed_result._state is not None:+        streamed_result._state._terminal_unrecoverable = True     if on_persisted_after_guardrails is None:         await save_items(final_turn_items, response_id, store_setting)     else:@@ -640,6 +645,10 @@ async def _finalize_streamed_final_output(             streamed_result.is_complete = True             streamed_result._event_queue.put_nowait(QueueCompleteSentinel())             return+    # The append and any post-append maintenance both succeeded, so the turn is durable and the+    # state is open again.+    if streamed_result._state is not None:+        streamed_result._state._terminal_unrecoverable = False      streamed_result.final_output = output     if on_persisted_after_guardrails is not None:@@ -923,6 +932,7 @@ async def start_streaming(         streamed_result._reasoning_item_id_policy = resolved_reasoning_item_id_policy          if is_resumed_state and run_state is not None:+            reject_unrecoverable_terminal_state(run_state)             await resume_pending_session_write(run_state, session, wrapper=context_wrapper)             streamed_result._current_turn_persisted_item_count = (                 run_state._current_turn_persisted_item_countsrc/agents/run_state.pyindex 732e768d3..d79e0781a 100644@@ -227,7 +227,7 @@ SCHEMA_VERSION_SUMMARIES: dict[str, str] = {     ),     "1.17": (         "Persists Docker container labels and current-response generated-item ownership across "-        "resume flows, including pending resumed Session writes."+        "resume flows, including pending resumed Session writes and terminal-unrecoverable runs."     ), } SUPPORTED_SCHEMA_VERSIONS = frozenset(SCHEMA_VERSION_SUMMARIES)@@ -878,6 +878,13 @@ class RunState(Generic[TContext, TAgent]):     _session_write_in_progress: bool = field(default=False, repr=False)     """Live ownership guard; independent serialized copies require caller serialization.""" +    _terminal_unrecoverable: bool = field(default=False, repr=False)+    """Set once a final output, its guardrails, and its terminal hooks have all completed.++    It closes the state for the window where the run owns an accepted result that no resume can+    reproduce, and it is cleared only once that turn is fully persisted.+    """+     def __init__(         self,         context: RunContextWrapper[TContext],@@ -920,6 +927,7 @@ class RunState(Generic[TContext, TAgent]):         self._schema_version = CURRENT_SCHEMA_VERSION         self._pending_session_write = None         self._session_write_in_progress = False+        self._terminal_unrecoverable = False         from .agent_tool_state import get_agent_tool_state_scope          self._agent_tool_state_scope_id = get_agent_tool_state_scope(context)@@ -1909,6 +1917,8 @@ class RunState(Generic[TContext, TAgent]):         result["current_turn_persisted_item_count"] = self._current_turn_persisted_item_count         if self._pending_session_write is not None:             result["pending_session_write"] = copy.deepcopy(self._pending_session_write)+        if self._terminal_unrecoverable:+            result["terminal_unrecoverable"] = True         result["trace"] = self._serialize_trace_data(             include_tracing_api_key=include_tracing_api_key         )@@ -4383,6 +4393,13 @@ async def _build_run_state_from_json(         ):             raise validation_error_factory("Run state pending Session write is invalid", UserError)         state._pending_session_write = copy.deepcopy(cast(_PendingSessionWrite, pending_write))+    terminal_unrecoverable = state_json.get("terminal_unrecoverable")+    if terminal_unrecoverable is not None:+        # An older label never wrote this marker, so honoring one would let a snapshot claim a+        # resume boundary the schema it declares does not have.+        if (schema_major, schema_minor) < (1, 17) or terminal_unrecoverable is not True:+            raise validation_error_factory("Run state terminal marker is invalid", UserError)+        state._terminal_unrecoverable = True     serialized_policy = state_json.get("reasoning_item_id_policy")     if serialized_policy in {"preserve", "omit"}:         state._reasoning_item_id_policy = cast(Literal["preserve", "omit"], serialized_policy)@@ -5172,6 +5189,7 @@ _TRUSTED_RUN_STATE_ERROR_MESSAGES = frozenset(         "Run state agent not found in agent map",         "Run state pending_input must be a list",         "Run state pending Session write is invalid",+        "Run state terminal marker is invalid",         "Run state references an agent identity that is not present in the restored graph",         (             "RunState context was serialized from a custom type; provide context_deserializer "tests/test_run_impl_resume_paths.pyindex 8e6211cea..482a13edd 100644@@ -9,7 +9,7 @@ import pytest from openai.types.responses import ResponseFunctionToolCall, ResponseOutputMessage  import agents.run as run_module-from agents import Agent, Runner, function_tool, handoff+from agents import Agent, GuardrailFunctionOutput, Runner, function_tool, handoff, output_guardrail from agents.agent import ToolsToFinalOutputResult from agents.agent_output import AgentOutputSchema from agents.decorators import tool, tool_input_guardrail, tool_output_guardrail@@ -37,6 +37,7 @@ from agents.run_internal.run_loop import (     SingleStepResult, ) from agents.run_state import RunState+from agents.sandbox.runtime import SandboxRuntime from agents.testing import ScriptedModel from agents.tool import Tool from agents.tool_guardrails import (@@ -65,8 +66,14 @@ class _FailingResumeSession(SimpleListSession):         self.block_next_add = False         self.add_started = asyncio.Event()         self.release_add = asyncio.Event()+        self.fail_on_output: str | None = None      async def add_items(self, items: list[TResponseInputItem]) -> None:+        if self.fail_on_output is not None and any(+            self.fail_on_output in json.dumps(item, default=str) for item in items+        ):+            self.fail_on_output = None+            raise self.error         failure, self.failure = self.failure, None         if failure == "before":             raise self.error@@ -1221,3 +1228,270 @@ async def test_resumed_handoff_session_append_is_recovered_before_next_model(     assert _call_pair(result.to_input_list(), "charge-1") == expected_pair     assert _call_pair(result.to_input_list(), "handoff-1") == expected_pair     assert "pending_session_write" not in result.to_state().to_json()+++class _TerminalLifecycleHooks(RunHooks[Any]):+    """Count the agent lifecycle hooks an application can attach its own effects to."""++    def __init__(self) -> None:+        self.starts = 0+        self.ends: list[str] = []++    async def on_agent_start(self, context: Any, agent: Agent[Any]) -> None:+        self.starts += 1++    async def on_agent_end(self, context: Any, agent: Agent[Any], output: Any) -> None:+        self.ends.append(str(output))+++async def _terminal_output_session_state(+    streamed: bool,+    session: Session | None = None,+    hooks: RunHooks[Any] | None = None,+):+    """Pause on an approval whose tool output becomes the terminal agent output."""+    effects: list[int] = []++    @tool(needs_approval=True)+    async def charge(amount: int) -> str:+        effects.append(amount)+        return "receipt-7"++    model = ScriptedModel(+        [+            [get_function_tool_call("charge", '{"amount":7}', call_id="charge-1")],+            [get_text_message("retry-final")],+        ]+    )+    agent = Agent(+        name="payment",+        model=model,+        tools=[charge],+        tool_use_behavior="stop_on_first_tool",+    )+    session = session if session is not None else _FailingResumeSession()+    paused = await _run_session_resume(agent, "charge 7", session, streamed, hooks=hooks)+    state = paused.to_state()+    state.approve(state.get_interruptions()[0])+    return agent, model, session, state, effects+++@pytest.mark.asyncio+@pytest.mark.parametrize(+    "failing_streamed,retry_streamed", [(False, False), (False, True), (True, False), (True, True)]+)+@pytest.mark.parametrize("round_trip", [False, True], ids=["live", "json"])+@pytest.mark.parametrize("failure", ["before", "after"], ids=["atomic-failure", "lost-ack"])+async def test_terminal_session_append_failure_rejects_every_later_resume(+    failing_streamed: bool, retry_streamed: bool, round_trip: bool, failure: str+) -> None:+    """An accepted terminal output whose append failed is not resumable, and never replayed."""+    hooks = _TerminalLifecycleHooks()+    agent, model, session, state, effects = await _terminal_output_session_state(+        failing_streamed, hooks=hooks+    )+    session.failure = failure+    with pytest.raises(RuntimeError) as error:+        await _run_session_resume(agent, state, session, failing_streamed, hooks=hooks)+    assert error.value is session.error++    # The output, its guardrails, and its terminal hooks all completed exactly once.+    assert effects == [7]+    assert len(model.calls) == 1+    assert hooks.ends == ["receipt-7"]+    starts_after_failure = hooks.starts+    assert state.to_json()["terminal_unrecoverable"] is True++    if round_trip:+        state = await RunState.from_json(agent, state.to_json())++    # Every later resume fails closed, including a second one.+    for _ in range(2):+        with pytest.raises(UserError, match="cannot be resumed"):+            await _run_session_resume(agent, state, session, retry_streamed, hooks=hooks)+        assert len(model.calls) == 1+        assert effects == [7]+        assert hooks.starts == starts_after_failure+        assert hooks.ends == ["receipt-7"]+++@pytest.mark.asyncio+@pytest.mark.parametrize("streamed", [False, True])+async def test_unrecoverable_terminal_state_rejects_before_any_resumed_work(+    streamed: bool, monkeypatch: pytest.MonkeyPatch+) -> None:+    """The rejection precedes Session reconciliation and sandbox preparation."""+    agent, model, session, state, effects = await _terminal_output_session_state(streamed)+    session.failure = "before"+    with pytest.raises(RuntimeError, match="session append failed"):+        await _run_session_resume(agent, state, session, streamed)++    async def _fail_get_items(*args: Any, **kwargs: Any) -> list[TResponseInputItem]:+        raise AssertionError("Session reconciliation must not run for a rejected terminal state")++    async def _fail_prepare_agent(*args: Any, **kwargs: Any):+        raise AssertionError("sandbox preparation must not run for a rejected terminal state")++    monkeypatch.setattr(type(session), "get_items", _fail_get_items)+    monkeypatch.setattr(SandboxRuntime, "prepare_agent", _fail_prepare_agent)++    restored = await RunState.from_json(agent, state.to_json())+    with pytest.raises(UserError, match="cannot be resumed"):+        await _run_session_resume(agent, restored, session, not streamed)+    assert len(model.calls) == 1+    assert effects == [7]+++@pytest.mark.asyncio+@pytest.mark.parametrize("streamed", [False, True])+async def test_terminal_marker_is_cleared_once_the_turn_is_persisted(streamed: bool) -> None:+    """A terminal turn that persists cleanly leaves a normal, unmarked result."""+    agent, model, session, state, effects = await _terminal_output_session_state(streamed)+    result = await _run_session_resume(agent, state, session, streamed)++    assert result.final_output == "receipt-7"+    assert effects == [7]+    assert "terminal_unrecoverable" not in result.to_state().to_json()+    assert _charge_pair(await session.get_items()) == ["function_call", "function_call_output"]+++@pytest.mark.asyncio+async def test_terminal_marker_rejects_an_older_schema_label() -> None:+    """The marker is only honored on the schema boundary that introduced it."""+    agent, _, session, state, _ = await _terminal_output_session_state(False)+    session.failure = "before"+    with pytest.raises(RuntimeError, match="session append failed"):+        await _run_session_resume(agent, state, session, False)++    payload = state.to_json()+    payload["$schemaVersion"] = "1.16"+    with pytest.raises(UserError, match="terminal marker is invalid"):+        await RunState.from_json(agent, payload)+++@pytest.mark.asyncio+async def test_failed_stream_result_checkpoint_keeps_the_terminal_marker() -> None:+    """A checkpoint taken from a failed streamed run stays closed to resumes.++    A streamed result exists before its terminal append does, so `to_state()` is reachable on the+    failed attempt. If that snapshot dropped the marker it would look like an ordinary resumable+    state and bypass the rejection entirely.+    """+    agent, model, session, state, effects = await _terminal_output_session_state(True)+    session.failure = "before"+    streamed = Runner.run_streamed(+        agent, state, session=session, run_config=RunConfig(tracing_disabled=True)+    )+    with pytest.raises(RuntimeError, match="session append failed"):+        async for _ in streamed.stream_events():+            pass++    checkpoint = streamed.to_state()+    assert checkpoint.to_json()["terminal_unrecoverable"] is True++    restored = await RunState.from_json(agent, checkpoint.to_json())+    for candidate in (checkpoint, restored):+        with pytest.raises(UserError, match="cannot be resumed"):+            await _run_session_resume(agent, candidate, session, False)+    assert len(model.calls) == 1+    assert effects == [7]+++@pytest.mark.asyncio+async def test_max_turns_handler_output_is_marked_before_it_is_persisted() -> None:+    """The max-turns fallback is a final output too, so its failed append closes the state."""+    handler_calls: list[str] = []+    hooks = _TerminalLifecycleHooks()++    @tool(needs_approval=True)+    async def charge(amount: int) -> str:+        return "receipt-7"++    model = ScriptedModel(+        [+            [get_function_tool_call("charge", '{"amount":7}', call_id="charge-1")],+            [get_text_message("unused")],+        ]+    )+    agent = Agent(name="payment", model=model, tools=[charge])+    session = _FailingResumeSession()+    config = RunConfig(tracing_disabled=True)++    paused = await Runner.run(+        agent, "charge 7", session=session, run_config=config, max_turns=1, hooks=hooks+    )+    state = paused.to_state()+    state.approve(state.get_interruptions()[0])++    def _handler(_data: Any) -> str:+        handler_calls.append("handled")+        return "max-turns-output"++    session.fail_on_output = "max-turns-output"+    with pytest.raises(RuntimeError, match="session append failed"):+        await Runner.run(+            agent,+            state,+            session=session,+            run_config=config,+            hooks=hooks,+            error_handlers={"max_turns": _handler},+        )++    # The handler and its end hook each ran exactly once before the append failed.+    assert handler_calls == ["handled"]+    assert hooks.ends == ["max-turns-output"]+    assert state.to_json()["terminal_unrecoverable"] is True++    with pytest.raises(UserError, match="cannot be resumed"):+        await Runner.run(+            agent,+            state,+            session=session,+            run_config=config,+            hooks=hooks,+            error_handlers={"max_turns": _handler},+        )+    assert handler_calls == ["handled"]+    assert hooks.ends == ["max-turns-output"]+++@pytest.mark.asyncio+async def test_max_turns_guardrail_failure_leaves_the_state_retryable() -> None:+    """A handler output that never passed its guardrails must not close the state.++    `finalize_max_turns_handler_output()` drives the same save callback from its guardrail-error+    path. Marking there would reject every later resume for an output the caller never received,+    which is a worse outcome than the replay the marker exists to prevent.+    """+    guardrail_calls: list[str] = []++    @tool(needs_approval=True)+    async def charge(amount: int) -> str:+        return "receipt-7"++    @output_guardrail+    async def exploding(context: Any, agent: Agent[Any], output: Any) -> GuardrailFunctionOutput:+        guardrail_calls.append(str(output))+        raise RuntimeError("guardrail exploded")++    model = ScriptedModel([[get_function_tool_call("charge", '{"amount":7}', call_id="charge-1")]])+    agent = Agent(name="payment", model=model, tools=[charge], output_guardrails=[exploding])+    session = _FailingResumeSession()+    config = RunConfig(tracing_disabled=True)++    paused = await Runner.run(agent, "charge 7", session=session, run_config=config, max_turns=1)+    state = paused.to_state()+    state.approve(state.get_interruptions()[0])++    handlers: dict[str, Any] = {"max_turns": lambda _data: "max-turns-output"}+    session.fail_on_output = "max-turns-output"+    with pytest.raises(RuntimeError, match="session append failed"):+        await Runner.run(agent, state, session=session, run_config=config, error_handlers=handlers)++    assert guardrail_calls == ["max-turns-output"]+    assert "terminal_unrecoverable" not in state.to_json()++    # The retry reports the real guardrail failure rather than a fail-closed rejection.+    with pytest.raises(RuntimeError, match="guardrail exploded"):+        await Runner.run(agent, state, session=session, run_config=config, error_handlers=handlers)