Skip to content

The agent that grows with you

fix(compression): pin the shadowed-checkpoint prune through compress(); drop the tail-budget claim

teknium1e1f46b851839
diff --git a/agent/context_compressor.py b/agent/context_compressor.py
index acc8281e2b7..ac6de4de4de 100644
--- a/agent/context_compressor.py
+++ b/agent/context_compressor.py
@@ -337,6 +337,10 @@ def stamp_db_persisted_markers(messages: List[Dict[str, Any]]) -> None:
msg[_DB_PERSISTED_MARKER] = True
+def _is_checkpoint_item(item: Any) -> bool:
+ return isinstance(item, dict) and item.get("type") == "compaction"
+
+
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:
@@ -347,23 +351,49 @@ def _newest_checkpoint_carrier(messages: List[Dict[str, Any]], key: str) -> int:
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
- ):
+ if isinstance(items, list) and any(_is_checkpoint_item(item) for item in items):
return i
return -1
+def _set_sidecar(msg: Dict[str, Any], key: str, kept: List[Any]) -> None:
+ """Filter items, never leave an empty sidecar behind."""
+ if kept:
+ msg[key] = kept
+ else:
+ msg.pop(key, None)
+
+
+def drop_shadowed_checkpoints(
+ messages: List[Dict[str, Any]], key: str = "codex_reasoning_items", *, before: Optional[int] = None,
+) -> List[int]:
+ """Drop ``type: "compaction"`` items from every assistant row older than the newest carrier (rows at
+ index >= *before* are left alone). A checkpoint a newer carrier shadows has no reader on any wire:
+ ``prune_pre_checkpoint_items`` rebuilds each request around the newest checkpoint run and the replay
+ gate drops checkpoints wholesale once native compaction is ineligible. Non-checkpoint items stay.
+ In place; returns the indices rewritten."""
+ newest = _newest_checkpoint_carrier(messages, key)
+ stop = newest if before is None else min(newest, before)
+ rewritten: List[int] = []
+ for i in range(max(stop, 0)):
+ 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 any(_is_checkpoint_item(item) for item in items):
+ continue
+ _set_sidecar(msg, key, [item for item in items if not _is_checkpoint_item(item)])
+ rewritten.append(i)
+ return rewritten
+
+
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 a
turn's bridging reasoning items together, so cutting at the last ASSISTANT would strip mid-chain.
- 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."""
+ 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).
+ 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")
@@ -371,30 +401,22 @@ 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 = 0
- for i in range(last_user_idx):
- msg = messages[i]
- if not isinstance(msg, dict) or msg.get("role") != "assistant":
- continue
- for key in _STALE_REPLAY_PRUNE_KEYS:
+ pruned = set()
+ for key in _STALE_REPLAY_PRUNE_KEYS:
+ pruned.update(drop_shadowed_checkpoints(messages, key, before=last_user_idx))
+ for i in range(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 isinstance(item, dict) and item.get("type") == "compaction"]
- if i == newest_carrier[key]
- else []
- )
+ kept = [item for item in items if _is_checkpoint_item(item)]
if len(kept) == len(items):
continue # nothing stale in this sidecar
- if kept:
- msg[key] = kept
- else:
- msg.pop(key, None)
- pruned += 1
- return pruned
+ _set_sidecar(msg, key, kept)
+ pruned.add(i)
+ return len(pruned)
# Explicit end boundary: weak models otherwise read quoted headers as fresh
diff --git a/tests/agent/test_stale_replay_prune.py b/tests/agent/test_stale_replay_prune.py
index 032e7a17019..500a2ac8be0 100644
--- a/tests/agent/test_stale_replay_prune.py
+++ b/tests/agent/test_stale_replay_prune.py
@@ -5,7 +5,8 @@ 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.
+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).
"""
from agent.context_compressor import (
@@ -171,21 +172,21 @@ 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.
+ the shadowed copies carried ~120 KB of unreachable ciphertext per
+ assistant row into the compacted transcript and every child session.
"""
@staticmethod
def _checkpoint(tag):
return {"type": "compaction", "encrypted_content": f"ckpt-{tag}"}
- def _transcript(self, turns):
+ def _transcript(self, turns, size=1):
messages = []
for t in range(turns):
- messages.append({"role": "user", "content": f"u{t}"})
+ messages.append({"role": "user", "content": f"u{t} " + "z" * size})
messages.append({
"role": "assistant",
- "content": f"a{t}",
+ "content": f"a{t} " + "z" * size,
"codex_reasoning_items": [
_reasoning(f"rs_{t}"),
self._checkpoint(t),
@@ -194,16 +195,14 @@ class TestShadowedCheckpointsArePruned:
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)
+ @staticmethod
+ def _retained_checkpoints(messages):
+ return [
+ item
+ for msg in 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)
@@ -218,16 +217,26 @@ class TestShadowedCheckpointsArePruned:
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."""
+ def test_compress_retains_exactly_the_checkpoints_the_wire_builder_keeps(self):
+ """Through the production entry point: ``ContextCompressor.compress()`` hands back a
+ transcript whose checkpoints are exactly those ``prune_pre_checkpoint_items`` would keep."""
+ from agent.context_compressor import ContextCompressor
from agent.native_compaction import prune_pre_checkpoint_items
- messages = self._transcript(5)
- _prune_stale_reasoning_replay(messages)
+ cc = ContextCompressor(
+ model="test-model", threshold_percent=0.75, protect_first_n=1, protect_last_n=12,
+ quiet_mode=True, config_context_length=40960, provider="test",
+ )
+ cc._generate_summary = lambda *a, **k: "Summary of earlier turns."
+ messages = self._transcript(12, size=1500)
+ before = self._retained_checkpoints(messages)
+
+ compressed = cc.compress(messages, current_tokens=100_000, force=True)
+ retained = self._retained_checkpoints(compressed)
+ assert len(before) > len(retained) >= 1, "the protected tail must carry several shadowed checkpoints"
items = []
- for msg in messages:
+ for msg in compressed:
items.extend(dict(i) for i in (msg.get("codex_reasoning_items") or []))
if msg["role"] == "user":
items.append({
@@ -236,10 +245,4 @@ class TestShadowedCheckpointsArePruned:
"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
+ assert retained == wire == [self._checkpoint(11)]