The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(compression): describe an aborted attempt from its own seed
mnajafian-nv4280f8b00e6e
diff --git a/agent/conversation_compression.py b/agent/conversation_compression.pyindex bf1e051da88..32bd96da68a 100644--- a/agent/conversation_compression.py+++ b/agent/conversation_compression.py@@ -4030,12 +4030,14 @@ def _begin_compression_attempt(trigger = trigger or ("manual" if force else "auto")with contextlib.suppress(Exception):agent._compression_attempt_id = attempt_id+ # The agent keeps its own copy: a pre-commit restore puts the previous seed back on the compressor.+ agent._compression_attempt_seed = {+ "attempt_id": attempt_id, "session_id": agent.session_id or "", "trigger_source": trigger,+ }from hermes_cli.observability.shared_metrics_events import begin_compression_attemptbegin_compression_attempt(trigger, approx_tokens or getattr(agent.context_compressor, "last_prompt_tokens", None))- agent.context_compressor._compression_telemetry_seed = {- "attempt_id": attempt_id, "session_id": agent.session_id or "", "trigger_source": trigger,- }+ agent.context_compressor._compression_telemetry_seed = dict(agent._compression_attempt_seed)return _Attempt(snapshot, generation, started_at)diff --git a/agent/conversation_compression_telemetry.py b/agent/conversation_compression_telemetry.pyindex 049a0aea9ad..c6c6e20a310 100644--- a/agent/conversation_compression_telemetry.py+++ b/agent/conversation_compression_telemetry.py@@ -26,6 +26,21 @@ logger = logging.getLogger("agent.conversation_compression")_GENERIC_ABORT_VERDICTS = frozenset({"no_progress", "summary_generation_aborted"})+def _attempt_seed(agent: Any, *, attempt_began: bool = True) -> dict[str, Any]:+ """This attempt's id, the session it started in, and its trigger.++ Read from the agent's copy: a pre-commit restore puts the previous attempt's seed back on the compressor.+ An emit with no attempt begun (pool saturation) gets a fresh id and an unknown trigger."""+ attempt_id = getattr(agent, "_compression_attempt_id", None) if attempt_began else None+ seed = getattr(agent, "_compression_attempt_seed", None)+ if attempt_id and isinstance(seed, dict) and seed.get("attempt_id") == attempt_id:+ return dict(seed)+ return {+ "attempt_id": attempt_id or uuid.uuid4().hex, "session_id": getattr(agent, "session_id", "") or "",+ "trigger_source": "unknown",+ }++def _emit_compression_attempt_telemetry(agent: Any, *, started_at: float, commit_status: str, split_status: str, failure_class: str | None = None,commit_started_at: float | None = None, include_last_telemetry: bool = True,@@ -37,8 +52,11 @@ def _emit_compression_attempt_telemetry(try:compressor = agent.context_compressortelemetry = getattr(compressor, "_last_compression_telemetry", None) if include_last_telemetry else None- if not isinstance(telemetry, dict):- telemetry = {}+ own = isinstance(telemetry, dict) and telemetry.get("attempt_id") == getattr(agent, "_compression_attempt_id", None)+ if not own:+ # The attempt-start clear leaves no dict before compress() seeds one, and a pre-commit restore puts+ # the previous attempt's back: describe THIS attempt from its seed, never another's numbers.+ telemetry = {**_attempt_seed(agent, attempt_began=include_last_telemetry), "method": "none"}payload = dict(telemetry)payload.setdefault("event", "compression_attempt")payload.setdefault("route", "hermes")@@ -51,15 +69,17 @@ def _emit_compression_attempt_telemetry(if commit_started_at is not None:telemetry["commit_ms"] = payload["commit_ms"] = max(0, int((time.monotonic() - commit_started_at) * 1000))# Defer only to THIS attempt's class: an abort restore can put the previous attempt's telemetry back.- _own_class = telemetry.get("attempt_id") == getattr(agent, "_compression_attempt_id", None)- if failure_class and not (failure_class in _GENERIC_ABORT_VERDICTS and _own_class and payload.get("failure_class")):+ if failure_class and not (failure_class in _GENERIC_ABORT_VERDICTS and own and payload.get("failure_class")):payload["failure_class"] = failure_classpayload.setdefault("chunking", False)payload.setdefault("chunk_count", 0)+ # The compressor's fallback flags are this attempt's only when its telemetry is.payload["fallback_used"] = bool(payload.get("fallback_used")- or getattr(compressor, "_last_summary_fallback_used", False)- or getattr(compressor, "_last_aux_model_failure_model", None)+ or own and (+ getattr(compressor, "_last_summary_fallback_used", False)+ or getattr(compressor, "_last_aux_model_failure_model", None)+ ))logger.info("context compression attempt telemetry: %s", json.dumps(payload, sort_keys=True, separators=(",", ":"))@@ -89,12 +109,9 @@ def _emit_bypassed_attempt_telemetry(counted these exits and still do not."""try:compressor = getattr(agent, "context_compressor", None)- seed = getattr(compressor, "_compression_telemetry_seed", None)- seed = seed if isinstance(seed, dict) else {}payload = {"event": "compression_attempt", "route": route, "method": method, "failure_class": failure_class,- "attempt_id": getattr(agent, "_compression_attempt_id", "") or seed.get("attempt_id") or uuid.uuid4().hex,- "session_id": getattr(agent, "session_id", "") or "", "trigger_source": seed.get("trigger_source") or "unknown",+ **_attempt_seed(agent),"main_provider": getattr(agent, "provider", "") or "", "main_model": getattr(agent, "model", "") or "",# Private caches only: the public properties can trigger a synchronous context-length probe."main_context_limit": getattr(compressor, "_resolved_context_length", None),diff --git a/tests/agent/test_compression_attempt_effect.py b/tests/agent/test_compression_attempt_effect.pyindex a71f98d84ef..52b1e941bf3 100644--- a/tests/agent/test_compression_attempt_effect.py+++ b/tests/agent/test_compression_attempt_effect.py@@ -219,3 +219,61 @@ def test_blocked_record_never_carries_the_cooldown_seconds(caplog):[record] = _attempt_records(caplog)assert record["failure_class"] == "blocked:structural_backoff"assert "917" not in json.dumps(record)+++def _abort_on_stale_snapshot(agent):+ compress_context(+ agent, _messages(), "system prompt", approx_tokens=80_000, trigger="post_tool",+ snapshot_is_current=lambda: False,+ )+++def _abort_at_the_commit_fence(agent):+ # The fence refuses the commit after the summary ran: the attempt restores the compressor's pre-attempt+ # state, which puts the PREVIOUS attempt's telemetry dict back before the record is written.+ from agent.conversation_compression import CompressionCommitFence++ fence = CompressionCommitFence()+ with patch.object(fence, "begin_commit", return_value=False):+ compress_context(+ agent, _messages(), "system prompt", approx_tokens=80_000, trigger="post_tool", commit_fence=fence,+ )+++def _refuse_on_a_saturated_pool(agent):+ from agent.conversation_compression import run_compress_context_with_progress_timeout++ with patch("agent.conversation_compression._try_admit_compression_job", return_value=False):+ run_compress_context_with_progress_timeout(+ worker=lambda _fence: pytest.fail("a refused job must not run"), messages=_messages(),+ system_prompt_fallback="system prompt", idle_timeout_seconds=5.0, total_ceiling_seconds=5.0,+ telemetry_agent=agent,+ )+++ ("abort", "trigger", "failure_class"),+ [+ (_abort_on_stale_snapshot, "post_tool", "snapshot_stale"),+ (_abort_at_the_commit_fence, "post_tool", "commit_fence_cancelled"),+ # Refused before any attempt begins: a fresh id, and the host does not know the trigger.+ (_refuse_on_a_saturated_pool, "unknown", "pool_saturated"),+ ],+)+def test_aborted_record_after_a_commit_describes_its_own_attempt(caplog, abort, trigger, failure_class):+ agent = _Agent(_compressor())++ with patch.object(agent.context_compressor, "_generate_summary", return_value="SUMMARY"):+ with caplog.at_level(logging.INFO, logger="agent.conversation_compression"):+ compress_context(agent, _messages(), "system prompt", approx_tokens=80_000, trigger="pre_api")+ abort(agent)++ committed, aborted = _attempt_records(caplog)+ assert committed["commit_status"] == "committed" and committed["tokens_reclaimed"] > 0+ assert aborted["attempt_id"] != committed["attempt_id"]+ assert (aborted["commit_status"], aborted["failure_class"]) == ("aborted", failure_class)+ assert (aborted["trigger_source"], aborted["session_id"]) == (trigger, agent.session_id)+ # No rewrite happened in this attempt, so it claims none.+ assert aborted["method"] == "none" and not aborted["fallback_used"]+ assert [aborted.get(key) for key in ("tokens_before", "tokens_after", "tokens_reclaimed")] == [None] * 3+diff --git a/website/docs/developer-guide/context-compression-and-caching.md b/website/docs/developer-guide/context-compression-and-caching.mdindex b224a96c634..de113ba028e 100644--- a/website/docs/developer-guide/context-compression-and-caching.md+++ b/website/docs/developer-guide/context-compression-and-caching.md@@ -235,13 +235,19 @@ text, the focus topic or error messages.- `trigger_source` names why the attempt ran: `manual`, `idle`,`turn_start_threshold`, `engine_preflight`, `pre_api`, `post_tool`,- `gateway_hygiene` or `overflow`.+ `gateway_hygiene` or `overflow`. An automatic caller that passes no label+ reads `auto`; a refusal before any attempt began (pool saturation) reads+ `unknown`.- `route` is `hermes` for the local compressor and `codex_app_server` when theCodex thread owns compaction.- `commit_status` is `committed`, `aborted`, `failed`, `skipped` or `blocked`.A `blocked` attempt was refused by an automatic guard; its `failure_class`names the guard (`blocked:cooldown`, `blocked:structural_backoff`,`blocked:ineffective`).+- `attempt_id` names this attempt and `session_id` the session it started+ in. An attempt that stops before the compressor runs, or rolls its state+ back, logs `method: none` and no token counts, never an earlier attempt's+ numbers.- `method` says how the summary was produced: `llm_summary`,`aux_fallback_main` (the summary model failed and the main model wrote it),`deterministic_fallback` (static anchors summary; `items_dropped` counts the