Skip to content

The agent that grows with you

fix(telemetry): a host-timeout compression cancel counts as failed, not skipped

Teknium561a1e8a670e
diff --git a/agent/conversation_compression.py b/agent/conversation_compression.py
index 61c53cf82ff..a8b6da0a8a8 100644
--- a/agent/conversation_compression.py
+++ b/agent/conversation_compression.py
@@ -30,6 +30,7 @@ from typing import Any, Callable, Dict, List, Literal, Optional, Tuple
from agent.auxiliary_client import AuxiliaryExplicitCancellation
from agent.context_engine import automatic_compaction_status_message, sanitize_memory_context
+from agent.conversation_compression_telemetry import _emit_aborted_attempt_telemetry, _emit_compression_attempt_telemetry
from agent.memory_provider import PRE_COMPRESS_CHECKPOINT_API_VERSION
from agent.model_metadata import estimate_messages_tokens_rough, estimate_request_tokens_rough
from agent.session_activity import ActivityProvenance, normalize_activity_provenance
@@ -1466,66 +1467,11 @@ def _session_was_rotated_by_compression(session_db: Any, session_id: str) -> boo
return bool(session and session.get("ended_at") is not None and session.get("end_reason") == "compression")
-# Caller-side abort verdicts that only restate an outcome the compressor already classified more precisely:
-# ``no_progress`` ("the transcript came back unchanged") covers the structural no-ops
-# (``no_compressible_window``, ``insufficient_messages``, ``empty_post_handoff_window``) and
-# ``summary_generation_aborted`` covers the terminal summary failures (``summary_auth_failure``,
-# ``summary_overload_failure``, ...). The emitter keeps the compressor's class for these so the attempt log
-# says WHY, not just THAT (#131412). Every other caller label names an event the compressor cannot see
-# (fence cancelled, superseded, rollback, pool saturated, ...) and still wins.
-_GENERIC_ABORT_VERDICTS = frozenset({"no_progress", "summary_generation_aborted"})
-
-
-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,
-) -> None:
- """Emit one content-free JSON log line for a compression attempt."""
- with _swallow('failed to emit compression attempt telemetry: %s'):
- compressor = agent.context_compressor
- telemetry = getattr(compressor, "_last_compression_telemetry", None)
- if not isinstance(telemetry, dict):
- telemetry = {}
- payload = dict(telemetry)
- payload.setdefault("event", "compression_attempt")
- payload.setdefault("attempt_id", getattr(agent, "_compression_attempt_id", "") or uuid.uuid4().hex)
- payload.setdefault("session_id", getattr(agent, "session_id", "") or "")
- payload.update(
- total_duration_ms=int((time.monotonic() - started_at) * 1000), commit_status=commit_status,
- split_status=split_status,
- )
- if commit_started_at is not None:
- telemetry["commit_ms"] = payload["commit_ms"] = max(0, int((time.monotonic() - commit_started_at) * 1000))
- if failure_class and not (failure_class in _GENERIC_ABORT_VERDICTS and payload.get("failure_class")):
- payload["failure_class"] = failure_class
- payload.setdefault("chunking", False)
- payload.setdefault("chunk_count", 0)
- 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)
- )
- logger.info(
- "context compression attempt telemetry: %s", json.dumps(payload, sort_keys=True, separators=(",", ":"))
- )
- from hermes_cli.observability.shared_metrics_events import finish_compression_attempt
-
- finish_compression_attempt(
- commit_status, payload.get("failure_class"), getattr(agent.context_compressor, "context_length", None), agent=agent,
- )
-
-
def _existing_system_prompt(agent: Any, system_message: str) -> str:
"""Cached system prompt, or a fresh build when nothing is cached (abort paths)."""
return getattr(agent, "_cached_system_prompt", None) or agent._build_system_prompt(system_message)
-def _emit_aborted_attempt_telemetry(agent: Any, started_at: float, failure_class: str | None) -> None:
- _emit_compression_attempt_telemetry(
- agent, started_at=started_at, commit_status="aborted", split_status="aborted", failure_class=failure_class
- )
-
-
def _restore_messages_snapshot(messages: list, snapshot: Optional[list]) -> None:
"""Put the pre-compression deep snapshot back into the live list if it drifted."""
if snapshot is not None and messages != snapshot:
@@ -3985,8 +3931,15 @@ def _run_summary_phase(
)
_stop_heartbeat("context compression cancelled")
lease.release()
+ # Only the user's stop is ``explicit_interrupt`` (counted skipped); a host timeout cancels the fence
+ # without setting the stop event, and that is a real failure (hygiene 30 s budget, 600 s ceiling).
+ _host_cancel = commit_fence is not None and commit_fence.is_cancelled and not (
+ hard_cancel_event is not None and hard_cancel_event.is_set()
+ )
_emit_aborted_attempt_telemetry(
- agent, attempt.started_at, (STALL_INTERRUPTED_FAILURE_CLASS if _stall_backoff else "explicit_interrupt")
+ agent, attempt.started_at,
+ STALL_INTERRUPTED_FAILURE_CLASS if _stall_backoff
+ else "commit_fence_cancelled" if _host_cancel else "explicit_interrupt",
)
return _SummaryPhase(messages=messages, abort_prompt=_existing_system_prompt(agent, system_message))
except BaseException as _compress_exc:
diff --git a/agent/conversation_compression_telemetry.py b/agent/conversation_compression_telemetry.py
new file mode 100644
index 00000000000..daa0e18a44d
--- /dev/null
+++ b/agent/conversation_compression_telemetry.py
@@ -0,0 +1,75 @@
+"""Content-free per-attempt compression telemetry (attempt log line + shared metric).
+
+Sibling of ``agent/conversation_compression.py`` (the facade), which imports it at module level; this
+module must never import the facade (import cycle). It logs under the facade's logger name so log
+consumers keep one source.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import time
+import uuid
+from typing import Any
+
+logger = logging.getLogger("agent.conversation_compression")
+
+
+# Caller-side abort verdicts that only restate an outcome the compressor already classified more precisely:
+# ``no_progress`` ("the transcript came back unchanged") covers the structural no-ops
+# (``no_compressible_window``, ``insufficient_messages``, ``empty_post_handoff_window``) and
+# ``summary_generation_aborted`` covers the terminal summary failures (``summary_auth_failure``,
+# ``summary_overload_failure``, ...). The emitter keeps the compressor's class for these so the attempt log
+# says WHY, not just THAT (#131412). Every other caller label names an event the compressor cannot see
+# (fence cancelled, superseded, rollback, pool saturated, ...) and still wins.
+_GENERIC_ABORT_VERDICTS = frozenset({"no_progress", "summary_generation_aborted"})
+
+
+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,
+) -> None:
+ """Emit one content-free JSON log line for a compression attempt."""
+ try:
+ compressor = agent.context_compressor
+ telemetry = getattr(compressor, "_last_compression_telemetry", None)
+ if not isinstance(telemetry, dict):
+ telemetry = {}
+ payload = dict(telemetry)
+ payload.setdefault("event", "compression_attempt")
+ payload.setdefault("attempt_id", getattr(agent, "_compression_attempt_id", "") or uuid.uuid4().hex)
+ payload.setdefault("session_id", getattr(agent, "session_id", "") or "")
+ payload.update(
+ total_duration_ms=int((time.monotonic() - started_at) * 1000), commit_status=commit_status,
+ split_status=split_status,
+ )
+ 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")):
+ payload["failure_class"] = failure_class
+ payload.setdefault("chunking", False)
+ payload.setdefault("chunk_count", 0)
+ 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)
+ )
+ logger.info(
+ "context compression attempt telemetry: %s", json.dumps(payload, sort_keys=True, separators=(",", ":"))
+ )
+ from hermes_cli.observability.shared_metrics_events import finish_compression_attempt
+
+ finish_compression_attempt(
+ commit_status, payload.get("failure_class"), getattr(agent.context_compressor, "context_length", None), agent=agent,
+ )
+ except Exception as exc:
+ logger.debug("failed to emit compression attempt telemetry: %s", exc, exc_info=True)
+
+
+def _emit_aborted_attempt_telemetry(agent: Any, started_at: float, failure_class: str | None) -> None:
+ _emit_compression_attempt_telemetry(
+ agent, started_at=started_at, commit_status="aborted", split_status="aborted", failure_class=failure_class
+ )
diff --git a/tests/agent/test_compression_attempt_telemetry.py b/tests/agent/test_compression_attempt_telemetry.py
index 89bc51cdb86..37849ccea5e 100644
--- a/tests/agent/test_compression_attempt_telemetry.py
+++ b/tests/agent/test_compression_attempt_telemetry.py
@@ -261,14 +261,21 @@ def test_structural_no_op_is_counted_skipped_with_the_compressors_class(caplog,
("summary_auth_failure", "summary_generation_aborted", "summary_auth_failure"),
# A caller-side event the compressor cannot see still outranks a recorded class.
("no_compressible_window", "attempt_superseded", "attempt_superseded"),
+ # A snapshot restore put the PREVIOUS attempt's telemetry back: its class is not this attempt's.
+ (("no_compressible_window", "previous-attempt"), "no_progress", "no_progress"),
],
)
def test_generic_caller_verdicts_defer_to_the_recorded_failure_class(caplog, monkeypatch, recorded, caller, expected):
from hermes_cli.observability import shared_metrics_events
+ recorded, attempt_id = recorded if isinstance(recorded, tuple) else (recorded, "this-attempt")
monkeypatch.setattr(shared_metrics_events, "finish_compression_attempt", lambda *_args, **_kwargs: None)
- compressor = SimpleNamespace(_last_compression_telemetry={"failure_class": recorded}, context_length=100_000)
- agent = SimpleNamespace(context_compressor=compressor, session_id="session-telemetry-test")
+ compressor = SimpleNamespace(
+ _last_compression_telemetry={"failure_class": recorded, "attempt_id": attempt_id}, context_length=100_000,
+ )
+ agent = SimpleNamespace(
+ context_compressor=compressor, session_id="session-telemetry-test", _compression_attempt_id="this-attempt",
+ )
with caplog.at_level(logging.INFO, logger="agent.conversation_compression"):
_emit_aborted_attempt_telemetry(agent, time.monotonic(), caller)
diff --git a/tests/agent/test_compression_stall_interrupt.py b/tests/agent/test_compression_stall_interrupt.py
index efbba7d853e..e86235e4fd7 100644
--- a/tests/agent/test_compression_stall_interrupt.py
+++ b/tests/agent/test_compression_stall_interrupt.py
@@ -18,6 +18,8 @@ import time
from pathlib import Path
from unittest.mock import patch
+import pytest
+
from agent.auxiliary_client import AuxiliaryExplicitCancellation
from agent.conversation_compression import (
STALL_INTERRUPTED_FAILURE_CLASS,
@@ -106,9 +108,16 @@ class TestStallClassificationIsFenceIdle:
class TestEarlyStopStaysNeutral:
+ @pytest.mark.parametrize(("user_stop", "outcome"), [(True, "skipped"), (False, "failed")])
def test_explicit_interrupt_before_stall_does_not_arm_cooldown(
- self, tmp_path: Path
+ self, tmp_path: Path, monkeypatch, user_stop, outcome
):
+ """Only the user's stop counts ``skipped``; a host timeout that cancels the fence (gateway hygiene
+ budget, total ceiling) without the stop event is a real failure even before the stall window."""
+ from hermes_cli.observability import shared_metrics_events
+
+ recorded = []
+ monkeypatch.setattr(shared_metrics_events, "record_compression", lambda **kw: recorded.append(kw["outcome"]))
db, agent = _build_agent(tmp_path, "EARLY_STOP_96775")
original = _messages()
live = copy.deepcopy(original)
@@ -116,6 +125,9 @@ class TestEarlyStopStaysNeutral:
def _early_stop(messages, **_kwargs):
messages[0]["content"] = "must be rolled back"
+ if user_stop:
+ agent._hard_interrupt_requested.set()
+ fence.cancel_before_commit()
raise AuxiliaryExplicitCancellation()
agent.context_compressor.compress = _early_stop
@@ -133,6 +145,7 @@ class TestEarlyStopStaysNeutral:
assert db.get_compression_lock_holder("EARLY_STOP_96775") is None
assert db.get_compression_failure_cooldown("EARLY_STOP_96775") is None
assert agent.context_compressor.should_compress(50_000) is True
+ assert recorded == [outcome]
db.append_message("EARLY_STOP_96775", "assistant", "still writable")