Skip to content

The agent that grows with you

fix(compression): a demoted tail skill_view result keeps its reload marker

Eva036c31d24c68
diff --git a/agent/context_compressor.py b/agent/context_compressor.py
index e71e62c3265..f8d3cbeae65 100644
--- a/agent/context_compressor.py
+++ b/agent/context_compressor.py
@@ -34,6 +34,7 @@ from agent.context_engine import ContextEngine, sanitize_memory_context
from agent.context_compressor_prellm import PreLlmSkipMixin
from agent.context_compressor_summary import SummaryDispatchMixin
from agent.context_compressor_retry import retryable_user_text
+from agent.context_compressor_tail import demote_stale_tail_tools, is_demoted_stub
from agent.context_compressor_telemetry import CompressionTelemetryMixin
from agent.error_classifier import FailoverReason, classify_api_error
from agent.micro_compaction import MicroCompactionMixin
@@ -831,8 +832,8 @@ _PRUNED_TOOL_PLACEHOLDER = "[Old tool output cleared to save context space]"
def _is_summary_stub(content: str) -> bool:
- """True for a tool result already replaced by a 1-line ``[tool] ... (N chars)`` summary."""
- return content.startswith("[") and " chars)" in content and len(content) < 400
+ """True for a tool result already replaced by a 1-line ``[tool] ... (N chars)`` summary or a lean-tail demotion stub."""
+ return content.startswith("[") and " chars)" in content and len(content) < 400 or is_demoted_stub(content)
# Shared floor; the clarify summary cap must stay strictly BELOW it so a preserved
@@ -926,21 +927,6 @@ _LEAN_USER_MESSAGES_BUDGET_CHARS = 24_000 # ~6K tokens
_LEAN_USER_MESSAGE_MAX_CHARS = 4_000
_LEAN_USER_MESSAGES_HEADING = "## User Messages (verbatim, newest first)"
_LEAN_RECOVERY_HEADING = "## Context Recovery"
-# Demote tool results older than the newest N rounds so the tail budget binds
-# (the tool-group alignment floor otherwise keeps ~32K of tool output alive).
-_LEAN_TAIL_KEEP_TOOL_ROUNDS = 6
-_LEAN_TAIL_DEMOTE_MIN_CHARS = 1_500
-
-
-def _lean_recovery_stub(tool_name: str, content_len: int, session_id: str) -> str:
- """One-line replacement for a demoted tail tool result."""
- hint = f" Recover with session_search(query=..., session_id='{session_id}')" if session_id else ""
- return (
- f"[{tool_name or 'tool'} output demoted at compaction — {content_len:,} "
- f"chars preserved in session history.{hint}]"
- )
-
-
_SYNTHETIC_USER_ROW_PREFIXES = (
"[System:", "[CONTEXT", "[PRIOR CONTEXT", "[IMPORTANT: Background", "[Your active task list",
"[Planning state preserved", "[ASYNC DELEGATION", "[OUT-OF-BAND", "Cronjob Response:",
@@ -3656,29 +3642,8 @@ Summary generation was unavailable, so this is a best-effort deterministic fallb
return self._augment_summary_lean(summary, turns_to_summarize)
def _demote_stale_tail_tools(self, messages: list[dict[str, Any]], tail_start: int) -> list[dict[str, Any]]:
- """Lean mode: demote tail tool results older than the newest ``_LEAN_TAIL_KEEP_TOOL_ROUNDS`` rounds to
- recovery stubs; skill-marker rows untouched. New list (untouched rows shared, demoted copied)."""
- session_id = getattr(self, "_session_id", "") or ""
- rounds_seen = 0
- protected: set[int] = set()
- prev_idx = None
- for i in (i for i in range(len(messages) - 1, tail_start - 1, -1) if messages[i].get("role") == "tool"):
- rounds_seen += prev_idx is None or prev_idx - i > 1
- prev_idx = i
- if rounds_seen > _LEAN_TAIL_KEEP_TOOL_ROUNDS:
- break
- protected.add(i)
- result = list(messages)
- demoted = 0
- for i in range(tail_start, len(messages)):
- msg = messages[i]
- content = msg.get("content")
- if msg.get("role") != "tool" or i in protected or not isinstance(content, str):
- continue
- if len(content) < _LEAN_TAIL_DEMOTE_MIN_CHARS or SKILL_PRUNED_MARKER_PREFIX in content or _is_summary_stub(content):
- continue
- result[i] = _rewritten(msg, _lean_recovery_stub(msg.get("tool_name") or "", len(content), session_id))
- demoted += 1
+ """Lean mode: demote stale tail tool results to recovery stubs (``demote_stale_tail_tools``)."""
+ result, demoted = demote_stale_tail_tools(messages, tail_start, getattr(self, "_session_id", "") or "")
if demoted and not self.quiet_mode:
logger.info("Lean tail: demoted %d stale tool result(s)", demoted)
return result
diff --git a/agent/context_compressor_tail.py b/agent/context_compressor_tail.py
new file mode 100644
index 00000000000..e38ae3bcb11
--- /dev/null
+++ b/agent/context_compressor_tail.py
@@ -0,0 +1,83 @@
+"""Lean-mode stale-tail demotion for ContextCompressor: old tail tool results become one-line recovery stubs."""
+
+from __future__ import annotations
+
+import re
+from typing import Any
+
+# Demote tool results older than the newest N rounds so the tail budget binds
+# (the tool-group alignment floor otherwise keeps ~32K of tool output alive).
+_LEAN_TAIL_KEEP_TOOL_ROUNDS = 6
+_LEAN_TAIL_DEMOTE_MIN_CHARS = 1_500
+
+
+# Matches what ``_lean_recovery_stub`` emits, so later passes treat a demoted row as already summarised: with a session
+# id and a reload marker the stub can pass the Phase-1 prune floor, and re-summarising it would drop both pointers.
+_DEMOTED_STUB_RE = re.compile(r"\[[^\s\]]* output demoted at compaction — [\d,]+ chars preserved in session history\.")
+
+
+def is_demoted_stub(content: str) -> bool:
+ """True for a tail tool result already replaced by ``_lean_recovery_stub`` (plus an optional reload marker)."""
+ return len(content) < 1_000 and _DEMOTED_STUB_RE.match(content) is not None
+
+
+def _lean_recovery_stub(tool_name: str, content_len: int, session_id: str) -> str:
+ """One-line replacement for a demoted tail tool result."""
+ hint = f" Recover with session_search(query=..., session_id='{session_id}')" if session_id else ""
+ return (
+ f"[{tool_name or 'tool'} output demoted at compaction — {content_len:,} "
+ f"chars preserved in session history.{hint}]"
+ )
+
+
+def _skill_view_names_by_call_id(messages: list[dict[str, Any]]) -> dict[str, str]:
+ """Map each ``skill_view`` tool-call id to the skill name it loaded."""
+ from agent.context_compressor import _json_dict, _tc_get
+
+ names: dict[str, str] = {}
+ for msg in messages:
+ if msg.get("role") != "assistant":
+ continue
+ for tc in msg.get("tool_calls") or []:
+ fn = _tc_get(tc, "function", {})
+ skill = _json_dict(_tc_get(fn, "arguments")).get("name") if _tc_get(fn, "name") == "skill_view" else None
+ if isinstance(skill, str) and skill:
+ names[str(_tc_get(tc, "id") or "")] = skill
+ return names
+
+
+def demote_stale_tail_tools(
+ messages: list[dict[str, Any]], tail_start: int, session_id: str,
+) -> tuple[list[dict[str, Any]], int]:
+ """Demote tail tool results older than the newest ``_LEAN_TAIL_KEEP_TOOL_ROUNDS`` rounds to recovery stubs;
+ skill-marker rows untouched. A demoted ``skill_view`` body carries the canonical reload marker, as its
+ Phase-1 stub does, so the model does not act on instructions it no longer has (#32106). Returns a new list
+ (untouched rows shared, demoted copied) and the number of rows demoted."""
+ from agent.context_compressor import SKILL_PRUNED_MARKER_PREFIX, _is_summary_stub, _rewritten, _skill_pruned_marker
+
+ rounds_seen = 0
+ protected: set[int] = set()
+ prev_idx = None
+ for i in (i for i in range(len(messages) - 1, tail_start - 1, -1) if messages[i].get("role") == "tool"):
+ rounds_seen += prev_idx is None or prev_idx - i > 1
+ prev_idx = i
+ if rounds_seen > _LEAN_TAIL_KEEP_TOOL_ROUNDS:
+ break
+ protected.add(i)
+ result = list(messages)
+ demoted = 0
+ skills: dict[str, str] | None = None
+ for i in range(tail_start, len(messages)):
+ msg = messages[i]
+ content = msg.get("content")
+ if msg.get("role") != "tool" or i in protected or not isinstance(content, str):
+ continue
+ if len(content) < _LEAN_TAIL_DEMOTE_MIN_CHARS or SKILL_PRUNED_MARKER_PREFIX in content or _is_summary_stub(content):
+ continue
+ stub = _lean_recovery_stub(msg.get("tool_name") or "", len(content), session_id)
+ skills = _skill_view_names_by_call_id(messages) if skills is None else skills
+ if skill := skills.get(str(msg.get("tool_call_id") or "")):
+ stub += " " + _skill_pruned_marker(skill)
+ result[i] = _rewritten(msg, stub)
+ demoted += 1
+ return result, demoted
diff --git a/tests/agent/test_context_compressor_tail.py b/tests/agent/test_context_compressor_tail.py
new file mode 100644
index 00000000000..8582e13a57e
--- /dev/null
+++ b/tests/agent/test_context_compressor_tail.py
@@ -0,0 +1,134 @@
+"""Lean stale-tail demotion: a demoted ``skill_view`` body keeps its reload marker (#32106)."""
+import json
+
+import pytest
+
+import agent.context_compressor as cc
+from agent.context_compressor_tail import (
+ _LEAN_TAIL_DEMOTE_MIN_CHARS,
+ _LEAN_TAIL_KEEP_TOOL_ROUNDS,
+ _lean_recovery_stub,
+ demote_stale_tail_tools,
+)
+
+SKILL = "synthetic-tail-skill"
+BODY = "Skill instructions " + "s" * 2000
+
+
+def _call(call_id, name, args):
+ return {"id": call_id, "type": "function", "function": {"name": name, "arguments": json.dumps(args)}}
+
+
+def _round(call_id, name, args, content, tool_name=True):
+ tool = {"role": "tool", "tool_call_id": call_id, "content": content}
+ if tool_name:
+ tool["tool_name"] = name
+ return [{"role": "assistant", "tool_calls": [_call(call_id, name, args)]}, tool]
+
+
+def _fresh_rounds(n=_LEAN_TAIL_KEEP_TOOL_ROUNDS):
+ rows = []
+ for i in range(n):
+ rows += _round(f"fresh-{i}", "terminal", {"command": f"echo {i}"}, f"Step {i} done.")
+ return rows
+
+
+def _stub_for(rows, call_id):
+ return next(r["content"] for r in rows if r.get("role") == "tool" and r.get("tool_call_id") == call_id)
+
+
+def test_demoted_skill_view_keeps_reload_marker():
+ rows = _round("skill-1", "skill_view", {"name": SKILL}, BODY) + _fresh_rounds()
+
+ out, demoted = demote_stale_tail_tools(rows, 0, "sess-1")
+
+ stub = _stub_for(out, "skill-1")
+ assert demoted == 1 and stub.startswith(_lean_recovery_stub("skill_view", len(BODY), "sess-1"))
+ assert cc._extract_pruned_skill_names(stub) == [SKILL] # the next compaction lists it under ## Pruned Skills
+
+
+def test_non_skill_stub_unchanged_and_fresh_rounds_kept():
+ output = "Terminal output " + "o" * _LEAN_TAIL_DEMOTE_MIN_CHARS
+ rows = _round("term-1", "terminal", {"command": "make"}, output) + _fresh_rounds()
+
+ out, demoted = demote_stale_tail_tools(rows, 0, "")
+
+ assert demoted == 1 and _stub_for(out, "term-1") == _lean_recovery_stub("terminal", len(output), "")
+ assert all(out[i] is rows[i] for i in range(2, len(rows)))
+
+
+def test_each_skill_row_gets_its_own_name_and_tool_name_is_optional():
+ calls = [_call("a", "skill_view", {"name": "skill-a"}), _call("b", "skill_view", {"name": "skill-b"})]
+ rows = [{"role": "assistant", "tool_calls": calls},
+ {"role": "tool", "tool_call_id": "a", "content": BODY},
+ {"role": "tool", "tool_call_id": "b", "content": BODY}] + _fresh_rounds()
+
+ out, _ = demote_stale_tail_tools(rows, 0, "")
+
+ assert cc._extract_pruned_skill_names(_stub_for(out, "a")) == ["skill-a"]
+ assert cc._extract_pruned_skill_names(_stub_for(out, "b")) == ["skill-b"]
+
+
+def compressor(monkeypatch):
+ monkeypatch.setattr(cc, "get_model_context_length", lambda *a, **k: 100_000)
+ monkeypatch.setattr(cc, "call_llm", lambda **kw: {"choices": [{"message": {
+ "content": "## Goal\nSynthetic work is recorded."}, "finish_reason": "stop"}]})
+ comp = cc.ContextCompressor(model="test/model", config_context_length=100_000, protect_first_n=0,
+ protect_last_n=3, quiet_mode=True, tail_mode="lean")
+ comp.tail_token_budget = 2000
+ return comp
+
+
+def test_compress_demotes_tail_skill_with_reload_marker(compressor):
+ rows = [
+ {"role": "system", "content": "Synthetic test conversation."},
+ {"role": "user", "content": "Summarize the completed earlier work."},
+ {"role": "assistant", "content": "Old notes " + "x" * 40_000},
+ # Phase-1 pressure demotes this older result first, so the skill body reaches tail demotion raw.
+ *_round("older-terminal", "terminal", {"command": "old-job"}, "Earlier output " + "o" * 8000),
+ {"role": "user", "content": "Continue the current work."},
+ *_round("skill-1", "skill_view", {"name": SKILL}, BODY),
+ *_fresh_rounds(),
+ {"role": "assistant", "content": "All rounds completed."},
+ {"role": "user", "content": "Report the current work."},
+ {"role": "assistant", "content": "Current work reported."},
+ ]
+ _, end = compressor._compress_window(rows)
+ assert any(r.get("tool_call_id") == "skill-1" for r in rows[end:]), "skill row must be in the tail"
+
+ out = compressor.compress(rows, force=True)
+
+ assert compressor.compression_count == 1 and not compressor._last_summary_fallback_used
+ stub = _stub_for(out, "skill-1")
+ assert "output demoted at compaction" in stub
+ assert cc._extract_pruned_skill_names(stub) == [SKILL], stub
+
+
+def test_reload_marker_survives_the_next_compaction(compressor):
+ # With a session id the marked stub passes the Phase-1 prune floor (200 chars); it must not be
+ # re-summarised into a plain "[skill_view] ..." line that drops the marker.
+ compressor.bind_session_state(session_id="0123abcd-4567-89ef-0123-456789abcdef")
+ rows = [
+ {"role": "system", "content": "Synthetic test conversation."},
+ {"role": "user", "content": "Summarize the completed earlier work."},
+ {"role": "assistant", "content": "Old notes " + "x" * 40_000},
+ *_round("older-terminal", "terminal", {"command": "old-job"}, "Earlier output " + "o" * 8000),
+ {"role": "user", "content": "Continue the current work."},
+ *_round("skill-1", "skill_view", {"name": SKILL}, BODY),
+ *_fresh_rounds(),
+ {"role": "assistant", "content": "All rounds completed."},
+ ]
+ first = compressor.compress(rows + [{"role": "user", "content": "Report the current work."}], force=True)
+ stub = _stub_for(first, "skill-1")
+ assert len(stub) > cc._PRUNE_MIN_CHARS and cc._extract_pruned_skill_names(stub) == [SKILL]
+
+ later = [{"role": "assistant", "content": "Reported."}, {"role": "user", "content": "Next task."}]
+ for i in range(8):
+ # Enough newer output that the stub falls outside Phase-1 tail protection (tail_token_budget).
+ later += _round(f"later-{i}", "terminal", {"command": f"echo later {i}"}, f"Later step {i} " + "l" * 1400)
+ second = compressor.compress(first + later + [{"role": "assistant", "content": "Done."}], force=True)
+
+ assert compressor.compression_count == 2 and not compressor._last_summary_fallback_used
+ text = "\n".join(str(r.get("content") or "") for r in second)
+ assert SKILL in cc._extract_pruned_skill_names(text), "reload marker lost at the next compaction"