Skip to content

The agent that grows with you

fix: encrypted reasoning items are never deleted from retained history

Teknium37d649247441
diff --git a/agent/codex_responses_adapter.py b/agent/codex_responses_adapter.py
index 43f67df3b89..8d6d9bfe8a5 100644
--- a/agent/codex_responses_adapter.py
+++ b/agent/codex_responses_adapter.py
@@ -86,42 +86,28 @@ def _model_can_read_blob(issuer_kind: Optional[str], item_model: Any, current_mo
return family is not None and family == openai_reasoning_family(item_model) and _is_openai_api_issuer(issuer_kind)
-# Responses hosts whose models render replayed reasoning from EARLIER user turns by default: xAI (LIVE: input
-# grows by the turn-1 reasoning-token count; behavioural recall) and Meta ("Both modes preserve chain of thought
-# across turns", dev.meta.ai/docs/protocols/responses). api.openai.com qualifies per model family (all_turns).
-_PRIOR_TURN_REASONING_HOSTS = frozenset({"api.x.ai", "api.meta.ai"})
-
-
-def route_reads_prior_turn_reasoning(route: Any) -> bool:
- """True when earlier-turn ``codex_reasoning_items`` are continuity the model on ``route`` (agent or compressor:
- ``api_mode``/``provider``/``model``/``base_url``) actually reads, so compaction must keep them. The ChatGPT
- Codex backend stays False until its ``reasoning.context`` is probed."""
- from utils import base_url_hostname
-
- if getattr(route, "api_mode", None) != "codex_responses":
- return False
- host = base_url_hostname(str(getattr(route, "base_url", "") or "")).lower()
- if host == "api.openai.com":
- return openai_reasoning_family(_wire_model_identity(getattr(route, "model", None))) is not None
- return host in _PRIOR_TURN_REASONING_HOSTS or getattr(route, "provider", None) in {"xai", "xai-oauth"}
-
-
def strip_unverified_reasoning_items(
messages: Any, *, issuer_kind: Optional[str], issuer_model: Optional[str],
) -> int:
- """First ``invalid_encrypted_content`` rung: drop only reasoning items NOT stamped by exactly this issuer AND
- model (unstamped legacy blobs, sibling-variant blobs) from assistant rows, keeping the session's own
- continuity. Consumes its own precondition (a second call removes nothing), so recovery cannot loop.
+ """First ``invalid_encrypted_content`` rung: drop the items the failing request REPLAYED without an exact
+ issuer+model stamp (unstamped legacy blobs, sibling-variant blobs). Items another issuer or model minted
+ were never sent (``_replay_reasoning_items`` skips them) and stay in history for a switch back.
+ Consumes its own precondition (a second call removes nothing), so recovery cannot loop.
Rebinds the filtered list, never mutates a shared one; returns the number of items removed."""
+ def unverified_but_sent(item: Any) -> bool:
+ if not isinstance(item, dict) or item.get("type") == "compaction":
+ return False
+ kind, model = _canonical_issuer_kind(item.get("_issuer_kind")), item.get("_issuer_model")
+ if kind == issuer_kind and model == issuer_model:
+ return False
+ return (kind is None or kind == issuer_kind) and _model_can_read_blob(issuer_kind, model, issuer_model)
+
removed = 0
for msg in messages if isinstance(messages, list) else []:
items = msg.get("codex_reasoning_items") if isinstance(msg, dict) and msg.get("role") == "assistant" else None
if not isinstance(items, list) or not items:
continue
- kept = [
- i for i in items if isinstance(i, dict)
- and _canonical_issuer_kind(i.get("_issuer_kind")) == issuer_kind and i.get("_issuer_model") == issuer_model
- ]
+ kept = [i for i in items if not unverified_but_sent(i)]
removed += len(items) - len(kept)
if kept:
msg["codex_reasoning_items"] = kept
diff --git a/agent/context_compressor.py b/agent/context_compressor.py
index 8dedb75a888..13b1d4a08b3 100644
--- a/agent/context_compressor.py
+++ b/agent/context_compressor.py
@@ -479,36 +479,20 @@ def drop_shadowed_checkpoints(
return rewritten
-def _prune_stale_reasoning_replay(messages: list[dict[str, Any]], *, keep_prior_turns: bool = False) -> int:
- """Strip stale ``codex_reasoning_items`` from assistant turns older than the active one.
- Boundary is the last USER message (a turn spans several assistant rows): the Responses API replays a
- turn's bridging reasoning items together, so cutting at the last ASSISTANT would strip mid-chain.
- Only the NEWEST ``type: "compaction"`` checkpoint survives (``drop_shadowed_checkpoints``): a shadowed
- one was still copied into the compacted transcript and every child session built from it (#102374).
- ``keep_prior_turns`` (``route_reads_prior_turn_reasoning``) applies only that checkpoint rule.
- Filter items, never pop the key on the carrier. In place; returns pruned message count."""
+def _prune_stale_reasoning_replay(messages: list[dict[str, Any]]) -> int:
+ """Drop shadowed ``type: "compaction"`` checkpoints from assistant turns older than the active one; only the
+ NEWEST survives (``drop_shadowed_checkpoints``): a shadowed one was still copied into the compacted transcript
+ and every child session built from it (#102374). Per-turn ``codex_reasoning_items`` are never pruned: the
+ compacted list becomes canonical history, the wire builder already filters per issuer/model, and a later
+ switch to a route that reads earlier-turn reasoning needs them. In place; returns pruned message count."""
# Active turn = everything after the last real user message; synthetic
# continuation rows and tool results never mark a turn boundary.
last_user_idx = _last_index_with_role(messages, "user")
if last_user_idx < 0:
- # No user boundary: prune nothing (fail open toward correctness).
return 0
-
pruned = set()
for key in _STALE_REPLAY_PRUNE_KEYS:
pruned.update(drop_shadowed_checkpoints(messages, key, before=last_user_idx))
- for i in range(0 if keep_prior_turns else last_user_idx):
- msg = messages[i]
- if not isinstance(msg, dict) or msg.get("role") != "assistant":
- continue
- items = msg.get(key)
- if not isinstance(items, list) or not items:
- continue
- kept = [item for item in items if _is_checkpoint_item(item)]
- if len(kept) == len(items):
- continue # nothing stale in this sidecar
- _set_sidecar(msg, key, kept)
- pruned.add(i)
return len(pruned)
@@ -573,11 +557,9 @@ def _salvage_reduce_todo_snapshot(out: list[dict[str, Any]]) -> None:
def salvage_grown_transcript(
original: list[dict[str, Any]], candidate: list[dict[str, Any]], budget: Optional[int] = None,
- *, route: Any = None,
) -> Optional[list[dict[str, Any]]]:
"""Mechanically shrink a compression candidate (copies, cheapest loss first); ``None`` unless strictly smaller.
- Never strips reasoning text: the result becomes canonical history that replay reads on every retained turn.
- ``codex_reasoning_items`` follow ``compress()``'s rule (``route_reads_prior_turn_reasoning(route)``)."""
+ Never strips reasoning (text or encrypted items): the result becomes canonical history replay reads."""
if not candidate or not original:
return None
if budget is None:
@@ -602,8 +584,7 @@ def salvage_grown_transcript(
and _looks_like_compaction_summary(msg, content)
):
msg["content"] = elide(content, _SALVAGE_SUMMARY_MAX_CHARS) + "\n\n" + _SUMMARY_END_MARKER
- from agent.codex_responses_adapter import route_reads_prior_turn_reasoning
- _prune_stale_reasoning_replay(out, keep_prior_turns=route is not None and route_reads_prior_turn_reasoning(route))
+ _prune_stale_reasoning_replay(out)
if estimate_messages_tokens_rough(out) >= budget:
_salvage_reduce_todo_snapshot(out)
has_user = any(isinstance(message, dict) and message.get("role") == "user" for message in out)
@@ -1291,7 +1272,7 @@ _REPLAY_BUDGET_KEYS = "reasoning", "reasoning_content", "codex_reasoning_items",
_ALWAYS_REPLAYED_BUDGET_KEYS = "codex_reasoning_items", "codex_message_items"
_NEWEST_TURN_ONLY_BUDGET_KEYS = "reasoning", "reasoning_content"
-# Stripped from stale turns only on routes that ignore earlier-turn reasoning; cache prefix already broken.
+# Sidecars whose shadowed compaction checkpoints are dropped from stale turns.
_STALE_REPLAY_PRUNE_KEYS = "codex_reasoning_items",
@@ -5526,9 +5507,7 @@ Write only the summary body. Do not include any preamble or prefix."""
# Invariant (#57491): no compacted message leaves compress() with a persistence marker.
_strip_persistence_markers(compressed)
- # Prior-turn codex_reasoning_items: dead weight on current_turn routes (#71058), continuity elsewhere.
- from agent.codex_responses_adapter import route_reads_prior_turn_reasoning as _reads_prior
- _pruned_replay = _prune_stale_reasoning_replay(compressed, keep_prior_turns=_reads_prior(self))
+ _pruned_replay = _prune_stale_reasoning_replay(compressed)
if _pruned_replay and not self.quiet_mode:
logger.info("Pruned stale replay items from %d assistant message(s) during compaction", _pruned_replay)
self._record_compression_effect(n_messages, compressed, pre_estimate, pruned_count, _pruned_replay)
diff --git a/agent/conversation_compression.py b/agent/conversation_compression.py
index 5fa1b15bafc..3f2ce36b73b 100644
--- a/agent/conversation_compression.py
+++ b/agent/conversation_compression.py
@@ -3211,7 +3211,7 @@ def _salvage_or_refuse_grown_transcript(
# Todo refresh and user-turn anchoring run after the compressor's own size check
# and can tip a break-even candidate; give it one mechanical salvage pass.
from agent.context_compressor import salvage_grown_transcript
- _salvaged = salvage_grown_transcript(original_messages, compressed, budget=_rough_in, route=agent)
+ _salvaged = salvage_grown_transcript(original_messages, compressed, budget=_rough_in)
if _salvaged is not None:
_salv_est = estimate_messages_tokens_rough(_salvaged)
if _salv_est < _rough_in:
diff --git a/tests/agent/test_cross_turn_reasoning_continuity.py b/tests/agent/test_cross_turn_reasoning_continuity.py
index c3f469c5597..7a8295c92fe 100644
--- a/tests/agent/test_cross_turn_reasoning_continuity.py
+++ b/tests/agent/test_cross_turn_reasoning_continuity.py
@@ -62,20 +62,10 @@ def test_sibling_variant_blob_replays_on_openai_only():
assert not any(i.get("type") == "reasoning" for i in cross_family["input"])
-def test_compaction_keeps_prior_turn_reasoning_only_when_the_route_reads_it():
- from types import SimpleNamespace as Route
- from agent.codex_responses_adapter import route_reads_prior_turn_reasoning as reads
-
- def route(provider, model, base_url):
- return Route(api_mode="codex_responses", provider=provider, model=model, base_url=base_url)
- assert reads(route("xai", "grok-4.3", "https://api.x.ai/v1"))
- assert reads(route("openai-api", "gpt-5.5", _OPENAI))
- assert not reads(route("openai-api", "o4-mini", _OPENAI))
- assert not reads(route("openai-codex", "gpt-5.5", "https://chatgpt.com/backend-api/codex"))
- kept, pruned = _history("grok-4.3"), _history("o4-mini")
- assert _prune_stale_reasoning_replay(kept, keep_prior_turns=True) == 0
+def test_compaction_keeps_prior_turn_reasoning_on_every_route():
+ kept = _history("o4-mini")
+ assert _prune_stale_reasoning_replay(kept) == 0
assert kept[1]["codex_reasoning_items"][0]["encrypted_content"] == "BLOB-1"
- assert _prune_stale_reasoning_replay(pruned) == 1 and "codex_reasoning_items" not in pruned[1]
def test_first_invalid_encrypted_rejection_drops_only_unverified_items():
@@ -86,3 +76,20 @@ def test_first_invalid_encrypted_rejection_drops_only_unverified_items():
assert transport.drop_unverified_replay(messages) == 1
assert messages[0]["codex_reasoning_items"] == [own]
assert transport.drop_unverified_replay(messages) == 0 # escalation path takes over next time
+
+
+def test_encrypted_rejection_rung_keeps_items_the_request_never_sent():
+ """The first invalid_encrypted_content rung strips only blobs the failing request replayed without an exact
+ stamp; another issuer's or model family's items were never sent and stay for a switch back."""
+ from agent.codex_responses_adapter import strip_unverified_reasoning_items
+
+ own = f"other:{_OPENAI}"
+ items = [
+ {"type": "reasoning", "encrypted_content": "OWN", "_issuer_kind": own, "_issuer_model": "gpt-5.5"},
+ {"type": "reasoning", "encrypted_content": "LEGACY"},
+ {"type": "reasoning", "encrypted_content": "XAI", "_issuer_kind": "xai:https://api.x.ai/v1", "_issuer_model": "grok-4.3"},
+ {"type": "reasoning", "encrypted_content": "O4", "_issuer_kind": own, "_issuer_model": "o4-mini"},
+ ]
+ history = [{"role": "user", "content": "q"}, {"role": "assistant", "content": "a", "codex_reasoning_items": items}]
+ assert strip_unverified_reasoning_items(history, issuer_kind=own, issuer_model="gpt-5.5") == 1
+ assert [i["encrypted_content"] for i in history[1]["codex_reasoning_items"]] == ["OWN", "XAI", "O4"]
diff --git a/tests/agent/test_stale_replay_prune.py b/tests/agent/test_stale_replay_prune.py
index 500a2ac8be0..f00c12ae675 100644
--- a/tests/agent/test_stale_replay_prune.py
+++ b/tests/agent/test_stale_replay_prune.py
@@ -1,11 +1,8 @@
-"""Tests for stale codex_reasoning_items pruning during compaction (#71058).
-
-Salvaged from PR #71077 (@webtecnica) with two correctness fixes:
-the prune boundary is the last USER message (a Codex turn spans multiple
-assistant messages whose reasoning items must replay together), and the
-newest native compaction checkpoint (type="compaction") is exempt because
-it carries already-pruned history, not per-turn reasoning. Checkpoints a
-newer carrier shadows are pruned: the wire builder discards them anyway
+"""Tests for compaction's codex_reasoning_items handling (#71058, #71077 by @webtecnica).
+
+Per-turn reasoning items are never pruned (they are replay continuity). Only
+checkpoints (type="compaction") that a newer carrier shadows are pruned: the
+wire builder discards them anyway
(#102374; the durable twin lives in tests/hermes_state/test_append_messages_batch.py).
"""
@@ -23,69 +20,20 @@ def _compaction():
return {"type": "compaction", "encrypted_content": "checkpoint-blob"}
-def test_prior_turn_reasoning_items_are_pruned():
+def test_prior_turn_reasoning_items_survive_compaction():
+ """Encrypted reasoning is continuity, not dead weight: the compacted list becomes canonical history and
+ the wire builder filters per issuer/model, so no turn's items are pruned (only shadowed checkpoints)."""
messages = [
{"role": "user", "content": "turn 1"},
- {"role": "assistant", "content": "a1", "codex_reasoning_items": [_reasoning("rs_a")]},
+ {"role": "assistant", "content": "a1", "codex_reasoning_items": [_compaction(), _reasoning("rs_a")]},
{"role": "user", "content": "turn 2"},
{"role": "assistant", "content": "a2", "codex_reasoning_items": [_reasoning("rs_b")]},
]
- pruned = _prune_stale_reasoning_replay(messages)
- assert pruned == 1
- assert "codex_reasoning_items" not in messages[1]
- # Active turn (after last user message) keeps its items.
+ assert _prune_stale_reasoning_replay(messages) == 0
+ assert messages[1]["codex_reasoning_items"] == [_compaction(), _reasoning("rs_a")]
assert messages[3]["codex_reasoning_items"] == [_reasoning("rs_b")]
-def test_multi_message_active_turn_chain_is_never_pruned():
- """A Codex turn spans assistant+tool_calls -> tool -> assistant; ALL of
- the active turn's reasoning items must survive (the #71077 review gap)."""
- messages = [
- {"role": "user", "content": "old turn"},
- {"role": "assistant", "content": "old", "codex_reasoning_items": [_reasoning("rs_old")]},
- {"role": "user", "content": "active turn"},
- {
- "role": "assistant",
- "content": "",
- "tool_calls": [{"id": "c1", "type": "function", "function": {"name": "t", "arguments": "{}"}}],
- "codex_reasoning_items": [_reasoning("rs_chain1")],
- },
- {"role": "tool", "content": "result", "tool_call_id": "c1"},
- {
- "role": "assistant",
- "content": "",
- "tool_calls": [{"id": "c2", "type": "function", "function": {"name": "t", "arguments": "{}"}}],
- "codex_reasoning_items": [_reasoning("rs_chain2")],
- },
- {"role": "tool", "content": "result", "tool_call_id": "c2"},
- {"role": "assistant", "content": "done", "codex_reasoning_items": [_reasoning("rs_final")]},
- ]
- pruned = _prune_stale_reasoning_replay(messages)
- assert pruned == 1 # only the old turn
- assert "codex_reasoning_items" not in messages[1]
- for idx in (3, 5, 7):
- assert messages[idx].get("codex_reasoning_items"), f"active-chain msg {idx} lost its items"
-
-
-def test_native_compaction_checkpoints_survive_pruning():
- """type="compaction" items are cumulative context carriers — they must
- survive on stale messages even when reasoning items are stripped."""
- messages = [
- {"role": "user", "content": "turn 1"},
- {
- "role": "assistant",
- "content": "a1",
- "codex_reasoning_items": [_compaction(), _reasoning("rs_a")],
- },
- {"role": "user", "content": "turn 2"},
- {"role": "assistant", "content": "a2"},
- ]
- pruned = _prune_stale_reasoning_replay(messages)
- assert pruned == 1
- # Reasoning stripped, checkpoint kept.
- assert messages[1]["codex_reasoning_items"] == [_compaction()]
-
-
def test_checkpoint_only_sidecar_untouched_and_uncounted():
messages = [
{"role": "user", "content": "turn 1"},
@@ -213,8 +161,9 @@ class TestShadowedCheckpointsArePruned:
"codex_reasoning_items": [self._checkpoint("live")],
})
_prune_stale_reasoning_replay(messages)
- assert "codex_reasoning_items" not in messages[1]
- assert "codex_reasoning_items" not in messages[3]
+ # Shadowed checkpoints go; each turn's own reasoning stays (continuity, not dead weight).
+ assert messages[1]["codex_reasoning_items"] == [_reasoning("rs_0")]
+ assert messages[3]["codex_reasoning_items"] == [_reasoning("rs_1")]
assert messages[-1]["codex_reasoning_items"] == [self._checkpoint("live")]
def test_compress_retains_exactly_the_checkpoints_the_wire_builder_keeps(self):