Skip to content

The agent that grows with you

fix(agent): one rejected reasoning blob no longer ends replay for the session

teknium19c82eab919ab
diff --git a/agent/agent_init.py b/agent/agent_init.py
index 60997e229c1..4a043f66fdf 100644
--- a/agent/agent_init.py
+++ b/agent/agent_init.py
@@ -586,9 +586,11 @@ _TURN_STATE: Dict[str, Any] = {
# Session persistence state.
_SESSION_STATE: Dict[str, Any] = {
"_session_messages": list,
- # Responses encrypted-reasoning replay: routes that 400 with ``invalid_encrypted_content``
- # make the loop disable it for the session (stateless continuity).
+ # Responses encrypted-reasoning replay. The first ``invalid_encrypted_content`` rejection only
+ # strips the stale blobs (a rotated sealing key); a second one means the route cannot round-trip
+ # its own fresh blobs, so replay is disabled for the session (stateless continuity).
"_codex_reasoning_replay_enabled": True,
+ "_codex_reasoning_replay_rejected": False,
"_memory_write_origin": "assistant_tool",
"_memory_write_context": "foreground",
# Cached system prompt (built once, rebuilt on compression) + its cross-session-stable
diff --git a/agent/codex_responses_adapter.py b/agent/codex_responses_adapter.py
index d4a630929d5..94b15a1006f 100644
--- a/agent/codex_responses_adapter.py
+++ b/agent/codex_responses_adapter.py
@@ -558,7 +558,7 @@ def _chat_messages_to_responses_input(
``is_xai_responses``: signature compatibility only (xAI DOES replay encrypted reasoning).
``replay_encrypted_reasoning``: per-session kill switch, threaded False by
- ``AIAgent._disable_codex_reasoning_replay`` after an ``invalid_encrypted_content`` 400.
+ ``AIAgent._disable_codex_reasoning_replay`` after a repeat ``invalid_encrypted_content`` 400.
``is_github_responses``: drops ``id`` from replayed message items (Copilot 401s on stale ids).
``current_issuer_kind`` / ``current_issuer_model``: provenance guard; items stamped by another issuer or
model drop. Legacy items carrying only an endpoint stamp replay on a matching issuer.
diff --git a/agent/turn_recovery.py b/agent/turn_recovery.py
index 994d6607edc..4f5f3a737e6 100644
--- a/agent/turn_recovery.py
+++ b/agent/turn_recovery.py
@@ -452,9 +452,13 @@ def _is_codex_token_expired(agent: Any, api_error: Exception) -> bool:
return isinstance(reason, str) and reason.strip().lower() == "token_expired"
-def _recover_stale_codex_reasoning(agent: Any, _retry: TurnRetryState, messages: List[Dict[str, Any]]) -> bool:
- """Stale ``codex_reasoning_items`` blob rejected by the provider: disable replay for the
- session, strip cached items (mutates persisted ``messages``), retry once."""
+def _recover_stale_codex_reasoning(
+ agent: Any, _retry: TurnRetryState, messages: List[Dict[str, Any]], api_messages: Any,
+) -> bool:
+ """Stale ``codex_reasoning_items`` blob rejected by the provider: strip cached items (mutates
+ persisted ``messages``) and retry once. The first rejection keeps replay on, since blobs the
+ route mints from now on are sealed with its current key; a repeat rejection means the route
+ cannot round-trip its own blobs, so replay is disabled for the session."""
if (
_retry.invalid_encrypted_content_retry_attempted
or agent.api_mode != "codex_responses"
@@ -469,16 +473,22 @@ def _recover_stale_codex_reasoning(agent: Any, _retry: TurnRetryState, messages:
):
return False
_retry.invalid_encrypted_content_retry_attempted = True
- replay_stats = agent._disable_codex_reasoning_replay(messages)
+ keep_replay = not getattr(agent, "_codex_reasoning_replay_rejected", False)
+ agent._codex_reasoning_replay_rejected = True
+ replay_stats = agent._disable_codex_reasoning_replay(messages, keep_replay=keep_replay)
+ # The retry is rebuilt from the request copy; with replay kept on it would resend the stale blob.
+ for _m in api_messages if isinstance(api_messages, list) else []:
+ if isinstance(_m, dict):
+ _m.pop("codex_reasoning_items", None)
+ action = "stripped stale" if keep_replay else "disabled replay for this session and stripped"
_vlines(
agent,
f"⚠️ Encrypted reasoning replay was rejected by the provider — "
- f"disabled replay and stripped {replay_stats['items']} item(s) from "
- f"{replay_stats['messages']} message(s), retrying...",
+ f"{action} {replay_stats['items']} item(s) from {replay_stats['messages']} message(s), retrying...",
)
logger.warning(
- "%sInvalid encrypted reasoning recovery: disabled replay and stripped %d items from %d messages",
- agent.log_prefix, replay_stats["items"], replay_stats["messages"],
+ "%sInvalid encrypted reasoning recovery: %s %d items from %d messages",
+ agent.log_prefix, action, replay_stats["items"], replay_stats["messages"],
)
return True
@@ -519,7 +529,7 @@ def _recover_format_errors(
# 400 ``invalid_encrypted_content`` on a stale ``codex_reasoning_items`` blob (the 401
# ``token_expired`` twin is taken ahead of the credential pool in the caller).
if classified.reason == FailoverReason.invalid_encrypted_content and _recover_stale_codex_reasoning(
- agent, _retry, messages
+ agent, _retry, messages, api_messages
):
return True
@@ -642,7 +652,9 @@ def recover_after_classification(
# stale replayed blob far more often than a dead bearer (#88510): strip BEFORE the pool
# refreshes/benches every healthy entry over a session-state problem. A real expiry pays
# one extra round-trip and then takes the credential path below as before.
- if _is_codex_token_expired(agent, api_error) and _recover_stale_codex_reasoning(agent, _retry, messages):
+ if _is_codex_token_expired(agent, api_error) and _recover_stale_codex_reasoning(
+ agent, _retry, messages, api_messages
+ ):
return True, False
if (
diff --git a/run_agent.py b/run_agent.py
index b3528450531..4f694724e04 100644
--- a/run_agent.py
+++ b/run_agent.py
@@ -496,9 +496,12 @@ class AIAgent(
switch_model = _forward("agent.agent_runtime_helpers", "switch_model")
- def _disable_codex_reasoning_replay(self, messages: Optional[List[Dict[str, Any]]] = None) -> Dict[str, int]:
- """On HTTP 400 ``invalid_encrypted_content``: disable Responses reasoning replay and pop
- ``codex_reasoning_items`` from every assistant message. Returns ``{"messages", "items"}`` counts."""
+ def _disable_codex_reasoning_replay(
+ self, messages: Optional[List[Dict[str, Any]]] = None, *, keep_replay: bool = False,
+ ) -> Dict[str, int]:
+ """On HTTP 400 ``invalid_encrypted_content``: pop ``codex_reasoning_items`` from every assistant
+ message and, unless ``keep_replay``, disable Responses reasoning replay. Returns
+ ``{"messages", "items"}`` counts."""
stripped_messages = stripped_items = 0
for msg in (messages if isinstance(messages, list) else []):
if not isinstance(msg, dict) or msg.get("role") != "assistant":
@@ -507,7 +510,8 @@ class AIAgent(
if isinstance(items, list) and items:
stripped_messages += 1
stripped_items += len(items)
- self._codex_reasoning_replay_enabled = False
+ if not keep_replay:
+ self._codex_reasoning_replay_enabled = False
return {"messages": stripped_messages, "items": stripped_items}
_stream_diag_init = _forward_static("agent.stream_diag", "stream_diag_init")
diff --git a/tests/agent/test_codex_token_expired_replay_recovery.py b/tests/agent/test_codex_token_expired_replay_recovery.py
index 699e7659621..14790345cd3 100644
--- a/tests/agent/test_codex_token_expired_replay_recovery.py
+++ b/tests/agent/test_codex_token_expired_replay_recovery.py
@@ -40,6 +40,7 @@ class _Agent:
model = "gpt-5.3-codex"
api_key = "same-bearer"
_codex_reasoning_replay_enabled = True
+ _codex_reasoning_replay_rejected = False
def __init__(self):
self.refresh_calls = 0
@@ -55,9 +56,9 @@ class _Agent:
from agent.agent_runtime_helpers import extract_api_error_context
return extract_api_error_context(error)
- def _disable_codex_reasoning_replay(self, messages=None):
+ def _disable_codex_reasoning_replay(self, messages=None, **kwargs):
from run_agent import AIAgent
- return AIAgent._disable_codex_reasoning_replay(self, messages)
+ return AIAgent._disable_codex_reasoning_replay(self, messages, **kwargs)
def __getattr__(self, name):
return lambda *args, **kwargs: None
@@ -87,11 +88,15 @@ def test_token_expired_strips_cached_reasoning_once_before_the_credential_path()
assert retried is True
assert agent.refresh_calls == 0 # no refresh token burned on a session-state problem
- assert agent._codex_reasoning_replay_enabled is False
+ # First rejection: only the stale blobs go; blobs minted from now on keep replaying.
+ assert agent._codex_reasoning_replay_enabled is True
assert not any("codex_reasoning_items" in m for m in messages)
# A second identical 401 in the same turn is a real auth failure: refresh once, no second strip.
assert _recover(agent, _Codex401(), retry, messages) == (False, False)
assert agent.refresh_calls == 1
+ # A later turn rejecting its own fresh blobs means the route cannot round-trip them: replay off.
+ assert _recover(agent, _Codex401(), TurnRetryState(), _cached_history()) == (True, False)
+ assert agent._codex_reasoning_replay_enabled is False
@pytest.mark.parametrize("err, history", [
diff --git a/tests/e2e/core/providers/test_openai_responses.py b/tests/e2e/core/providers/test_openai_responses.py
index 04d466a0c8e..270f52360c1 100644
--- a/tests/e2e/core/providers/test_openai_responses.py
+++ b/tests/e2e/core/providers/test_openai_responses.py
@@ -14,8 +14,9 @@ Proven here:
* parallel ``function_call`` items round-trip: every call gets exactly one
``function_call_output`` with its own ``call_id`` and its own result, persisted once;
* a stale encrypted blob rejected with HTTP 400 ``invalid_encrypted_content`` is
- stripped and the SAME primary is retried (no fallback, no give-up) — and the HTTP-200
- soft-failure twin of that rejection must behave the same (#120399);
+ stripped and the SAME primary is retried (no fallback, no give-up), and the blobs the
+ retry mints keep replaying — and the HTTP-200 soft-failure twin of that rejection must
+ behave the same (#120399);
* a stream that dies mid-``function_call`` (arguments half streamed, no terminal event) is
retried without running the half call, and the completed call runs EXACTLY once;
* a 429 carrying ``Retry-After`` is retried after the advertised wait, and answers once.
@@ -146,9 +147,14 @@ def _stale_blob_session(h: Home, srv: FakeResponsesServer, fallback: FakeLLMServ
])
def test_rejected_encrypted_replay_is_stripped_and_primary_retried(tmp_path, rejection) -> None:
h = Home(tmp_path)
- script = [Turn([Reasoning("ENC-STALE"), Message("FIRST")]), rejection, Turn([Message("RECOVERED-ON-PRIMARY")])]
+ script = [
+ Turn([Reasoning("ENC-STALE"), Message("FIRST")]), rejection,
+ Turn([Reasoning("ENC-FRESH"), FunctionCall(READ_TOOL, {"path": "notes.txt"})]),
+ Turn([Message("RECOVERED-ON-PRIMARY")]),
+ ]
with FakeResponsesServer(script) as srv, FakeLLMServer(default_text="FROM-FALLBACK") as fallback:
sid = _stale_blob_session(h, srv, fallback)
+ (h.project / "notes.txt").write_text("CANARY-RESP-2\n", encoding="utf-8")
run = oneshot(h, "second question", resume=sid)
mains = srv.main_requests()
fallback_mains = fallback.main_requests()
@@ -157,8 +163,11 @@ def test_rejected_encrypted_replay_is_stripped_and_primary_retried(tmp_path, rej
scenario = "soft_failure_recovers_on_primary" if isinstance(rejection, SoftFail) else "http_400"
with bug_assertions(KNOWN, scenario):
assert fallback_mains == [], f"fallback engaged instead of replay recovery: {run.describe()}"
- assert len(mains) == 3, [m.get("input") for m in mains]
+ assert len(mains) == 4, [m.get("input") for m in mains]
assert _encs(mains[2]) == [], "the retry must drop the rejected blob"
+ # One stale blob must not end continuity: the retry's fresh blob replays on the next call.
+ assert "reasoning.encrypted_content" in (mains[3].get("include") or []), mains[3]
+ assert _encs(mains[3]) == ["ENC-FRESH"], mains[3]["input"]
assert run.proc.returncode == 0 and _answer(run) == "RECOVERED-ON-PRIMARY", run.describe()
@@ -209,7 +218,7 @@ def test_stream_drop_mid_function_call_runs_the_call_once(tmp_path) -> None:
assert invalid == [], invalid
count = h.project / "count.txt"
assert count.exists(), f"tool never ran: {run.describe()}"
- assert count.read_text(encoding="utf-8").splitlines() == ["ran"], "side effect ran more than once"
+ assert count.read_text(encoding="utf-8-sig").splitlines() == ["ran"], "side effect ran more than once"
# The half call never reaches the wire: the retry resends exactly the first request's input.
assert mains[1]["input"] == mains[0]["input"], (mains[0]["input"], mains[1]["input"])
# The final request replays exactly one call and its one result.
diff --git a/website/docs/developer-guide/provider-runtime.md b/website/docs/developer-guide/provider-runtime.md
index cae44ae79dd..60f1638b1f9 100644
--- a/website/docs/developer-guide/provider-runtime.md
+++ b/website/docs/developer-guide/provider-runtime.md
@@ -159,7 +159,7 @@ Codex uses a separate Responses API path:
- `api_mode = codex_responses`
- dedicated credential resolution and auth store support
-- a resumed session whose lingering Codex reasoning items (`encrypted_content`) are rejected — as a 400 `invalid_encrypted_content` or as a 401 `token_expired` — self-heals by stripping the cached items and replaying once, before any credential refresh or pool rotation
+- a resumed session whose lingering Codex reasoning items (`encrypted_content`) are rejected — as a 400 `invalid_encrypted_content` or as a 401 `token_expired` — self-heals by stripping the cached items and replaying once, before any credential refresh or pool rotation. Reasoning minted after that strip keeps replaying; only a second rejection in the same session turns replay off
## Auxiliary model routing