Skip to content

The agent that grows with you

fix(compaction): invalidate pre-checkpoint usage anchors

simpolism1ae6f650f950
diff --git a/agent/chat_completion_helpers.py b/agent/chat_completion_helpers.py
index 9ff1591cf67..d1b4c6e4e4c 100644
--- a/agent/chat_completion_helpers.py
+++ b/agent/chat_completion_helpers.py
@@ -1681,6 +1681,11 @@ def build_assistant_message(agent, assistant_message, finish_reason: str) -> dic
and has_replayable_native_compaction_checkpoint(agent, [msg])
):
note_checkpoint()
+ # The response priced the pre-checkpoint input, not the next
+ # compacted request. A matching durable prefix is now stale.
+ from agent.usage_anchor import set_usage_anchor
+
+ set_usage_anchor(agent, None)
if assistant_tool_calls:
msg["tool_calls"] = [_assistant_tool_call_dict(agent, tc, i) for i, tc in enumerate(assistant_tool_calls)]
diff --git a/agent/turn_context.py b/agent/turn_context.py
index 3492e7f1865..c655e1d11ca 100644
--- a/agent/turn_context.py
+++ b/agent/turn_context.py
@@ -679,6 +679,11 @@ def _hydrate_from_history(agent: Any, conversation_history: Optional[List[Any]])
agent, conversation_history
):
note_checkpoint()
+ # Restored usage can describe the input that produced this
+ # checkpoint rather than its compacted replay.
+ from agent.usage_anchor import set_usage_anchor
+
+ set_usage_anchor(agent, None)
except Exception:
logger.debug(
"restored native checkpoint hydration skipped", exc_info=True
diff --git a/agent/turn_preflight.py b/agent/turn_preflight.py
index f5215f51bed..3a71db19164 100644
--- a/agent/turn_preflight.py
+++ b/agent/turn_preflight.py
@@ -266,6 +266,10 @@ def compress_after_tool_results(
)
_compressor = agent.context_compressor
+ # A new checkpoint must reach the provider before stale usage can trigger
+ # local compression, overflow warnings, or destructive tool-result pruning.
+ if bool(getattr(_compressor, "awaiting_real_usage_after_compression", False)):
+ return _verdict(False)
# Real usage decides: the anchor is the provider's last prompt count plus a rough delta for
# ONLY the tool results appended since (the raw last_prompt_tokens ignores them). Right after
# a compaction (-1 sentinel) there is no real count yet: never treat the schema-heavy rough
diff --git a/tests/agent/test_413_compression.py b/tests/agent/test_413_compression.py
index 65a9c830673..b29548cb511 100644
--- a/tests/agent/test_413_compression.py
+++ b/tests/agent/test_413_compression.py
@@ -1358,6 +1358,9 @@ class TestPreflightCompression:
agent.context_compressor.threshold_tokens = 130_000
# Exercise the idle pass too: it runs before threshold preflight and must honor
# the same one-response checkpoint latch on a long-idle restored session.
+ from agent.usage_anchor import capture_usage_anchor, set_usage_anchor
+
+ set_usage_anchor(agent, capture_usage_anchor(180_000, 100, history[:1]))
agent.compression_idle_compact_after_seconds = 1
agent._last_activity_ts = 0
response = SimpleNamespace(
diff --git a/tests/agent/test_proactive_prune_loop_wiring.py b/tests/agent/test_proactive_prune_loop_wiring.py
index 25e16768efc..3d7f78a68aa 100644
--- a/tests/agent/test_proactive_prune_loop_wiring.py
+++ b/tests/agent/test_proactive_prune_loop_wiring.py
@@ -137,6 +137,29 @@ def _run_tool_loop(agent, n_tool_iterations: int, task_id=None):
class TestProactivePruneLoopWiring:
+ def test_pending_checkpoint_waits_without_warning_or_pruning(self, agent):
+ from agent.turn_preflight import compress_after_tool_results
+
+ compressor = agent.context_compressor
+ compressor.awaiting_real_usage_after_compression = True
+ compressor.last_prompt_tokens = 255_933
+ compressor.threshold_tokens = 231_200
+ compressor.should_compress.return_value = True
+ compressor.should_compress_info.return_value = (True, None)
+ compressor.prune_tool_results_only.side_effect = lambda messages, **kw: (messages, 0)
+ messages = [{"role": "user", "content": "continue"}]
+ with patch.object(agent, "_warn_context_overflow_blocked") as warn:
+ verdict = compress_after_tool_results(
+ agent, messages=messages, system_message="system", user_message="continue",
+ active_system_prompt="system", conversation_history=[],
+ compression_attempts=0, max_compression_attempts=3,
+ effective_task_id=None, final_response="", turn_exit_reason=None,
+ )
+ assert verdict.messages is messages
+ assert not verdict.end_turn
+ warn.assert_not_called()
+ compressor.prune_tool_results_only.assert_not_called()
+
def test_full_compression_preempts_proactive_prune(self, agent):
agent.context_compressor.should_compress.return_value = True
diff --git a/tests/agent/test_run_agent.py b/tests/agent/test_run_agent.py
index 2451585aa0e..f3ae1534fc3 100644
--- a/tests/agent/test_run_agent.py
+++ b/tests/agent/test_run_agent.py
@@ -1535,10 +1535,16 @@ class TestBuildAssistantMessage:
agent.context_compressor.note_native_compaction_checkpoint = MagicMock()
self._enable_native_compaction(agent)
+ from agent.usage_anchor import capture_usage_anchor, set_usage_anchor
+
+ history = [{"role": "user", "content": "before compaction"}]
+ set_usage_anchor(agent, capture_usage_anchor(255_000, 100, history), turn_base=True)
result = agent._build_assistant_message(msg, "stop")
assert result["codex_reasoning_items"] == [checkpoint]
agent.context_compressor.note_native_compaction_checkpoint.assert_called_once_with()
+ assert agent._usage_anchor is None
+ assert agent._turn_base_usage_anchor is None
def test_native_checkpoint_remains_compatible_with_plugin_context_engine(self, agent):
checkpoint = {