The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(compression): prune native-compaction checkpoints a newer carrier shadows
joaomarcosaddb689a7b2f
diff --git a/agent/context_compressor.py b/agent/context_compressor.pyindex 5519d7d9b2b..acc8281e2b7 100644--- a/agent/context_compressor.py+++ b/agent/context_compressor.py@@ -337,12 +337,33 @@ def stamp_db_persisted_markers(messages: List[Dict[str, Any]]) -> None:msg[_DB_PERSISTED_MARKER] = True+def _newest_checkpoint_carrier(messages: List[Dict[str, Any]], key: str) -> int:+ """Index of the last assistant message carrying a ``type: "compaction"`` item under *key*, or -1.+ Transcript-side mirror of ``native_compaction.prune_pre_checkpoint_items``' newest-run-wins rule:+ the wire builder drops every checkpoint before the last one, so this is the only carrier whose+ checkpoint can still reach a request."""+ for i in range(len(messages) - 1, -1, -1):+ msg = messages[i]+ if not isinstance(msg, dict) or msg.get("role") != "assistant":+ continue+ items = msg.get(key)+ if isinstance(items, list) and any(+ isinstance(item, dict) and item.get("type") == "compaction" for item in items+ ):+ return i+ return -1++def _prune_stale_reasoning_replay(messages: List[Dict[str, Any]]) -> 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 aturn's bridging reasoning items together, so cutting at the last ASSISTANT would strip mid-chain.- ``type: "compaction"`` items are cumulative context carriers that must survive on every retained- message — filter items, never pop the key. In place; returns pruned message count."""+ Only the NEWEST ``type: "compaction"`` checkpoint survives: ``prune_pre_checkpoint_items`` rebuilds+ every request around the last checkpoint run and the replay gate drops checkpoints wholesale once+ native compaction is ineligible, so a checkpoint shadowed by a newer carrier has no reader on any+ wire yet is charged in full by ``_ALWAYS_REPLAYED_BUDGET_KEYS`` (~120 KB ciphertext each), copied+ into child sessions and persisted for the life of the DB (#102374). Filter items, never pop the key+ on the carrier. 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")@@ -350,6 +371,8 @@ def _prune_stale_reasoning_replay(messages: List[Dict[str, Any]]) -> int:# No user boundary: prune nothing (fail open toward correctness).return 0+ newest_carrier = {key: _newest_checkpoint_carrier(messages, key) for key in _STALE_REPLAY_PRUNE_KEYS}+pruned = 0for i in range(last_user_idx):msg = messages[i]@@ -359,7 +382,11 @@ def _prune_stale_reasoning_replay(messages: List[Dict[str, Any]]) -> int:items = msg.get(key)if not isinstance(items, list) or not items:continue- kept = [item for item in items if isinstance(item, dict) and item.get("type") == "compaction"]+ kept = (+ [item for item in items if isinstance(item, dict) and item.get("type") == "compaction"]+ if i == newest_carrier[key]+ else []+ )if len(kept) == len(items):continue # nothing stale in this sidecarif kept:diff --git a/tests/agent/test_stale_replay_prune.py b/tests/agent/test_stale_replay_prune.pyindex 99bcd2a22a2..032e7a17019 100644--- a/tests/agent/test_stale_replay_prune.py+++ b/tests/agent/test_stale_replay_prune.py@@ -2,9 +2,10 @@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 native-compaction checkpoints (type="compaction") are exempt because they carry-already-pruned history, not per-turn reasoning.+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."""from agent.context_compressor import (@@ -164,3 +165,81 @@ class TestInterimMergePreservesCheckpoints:assert merge_interim_reasoning_items(None, None) == []assert merge_interim_reasoning_items(None, [_reasoning("r")]) == [_reasoning("r")]assert merge_interim_reasoning_items([_compaction()], None) == [_compaction()]+++class TestShadowedCheckpointsArePruned:+ """A checkpoint that a newer carrier shadows can never reach a request:+ ``native_compaction.prune_pre_checkpoint_items`` rebuilds every wire+ around the newest checkpoint run and drops each earlier one. Retaining+ the shadowed copies charged them in full against the tail budget and+ persisted ~120 KB of unreachable ciphertext per assistant row.+ """++ @staticmethod+ def _checkpoint(tag):+ return {"type": "compaction", "encrypted_content": f"ckpt-{tag}"}++ def _transcript(self, turns):+ messages = []+ for t in range(turns):+ messages.append({"role": "user", "content": f"u{t}"})+ messages.append({+ "role": "assistant",+ "content": f"a{t}",+ "codex_reasoning_items": [+ _reasoning(f"rs_{t}"),+ self._checkpoint(t),+ ],+ })+ messages.append({"role": "user", "content": "now"})+ return messages++ def test_only_the_newest_carrier_keeps_its_checkpoint(self):+ messages = self._transcript(4)+ _prune_stale_reasoning_replay(messages)+ surviving = [+ (i, item)+ for i, msg in enumerate(messages)+ for item in (msg.get("codex_reasoning_items") or [])+ if item.get("type") == "compaction"+ ]+ assert surviving == [(7, self._checkpoint(3))]++ def test_newest_carrier_inside_the_active_turn_shadows_every_stale_one(self):+ messages = self._transcript(2)+ # Active turn (after the last user message) mints its own checkpoint.+ messages.append({+ "role": "assistant",+ "content": "live",+ "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]+ assert messages[-1]["codex_reasoning_items"] == [self._checkpoint("live")]++ def test_retained_checkpoints_match_what_the_wire_builder_keeps(self):+ """The invariant behind the prune: after it runs, the transcript holds+ exactly the checkpoints ``prune_pre_checkpoint_items`` would have kept."""+ from agent.native_compaction import prune_pre_checkpoint_items++ messages = self._transcript(5)+ _prune_stale_reasoning_replay(messages)++ items = []+ for msg in messages:+ items.extend(dict(i) for i in (msg.get("codex_reasoning_items") or []))+ if msg["role"] == "user":+ items.append({+ "type": "message",+ "role": "user",+ "content": [{"type": "input_text", "text": msg["content"]}],+ })+ wire = [i for i in prune_pre_checkpoint_items(items) if i.get("type") == "compaction"]+ retained = [+ item+ for msg in messages+ for item in (msg.get("codex_reasoning_items") or [])+ if item.get("type") == "compaction"+ ]+ assert retained == wire