Skip to content

The agent that grows with you

feat(compression): record every prepared-compaction pass and splice outcome

Teknium4501b3f80b56
diff --git a/agent/conversation_compression_telemetry.py b/agent/conversation_compression_telemetry.py
index 672d516de40..1d977e9da7a 100644
--- a/agent/conversation_compression_telemetry.py
+++ b/agent/conversation_compression_telemetry.py
@@ -146,6 +146,10 @@ def _emit_compression_attempt_telemetry(
finish_compression_attempt(
commit_status, payload.get("failure_class"), getattr(agent.context_compressor, "context_length", None), agent=agent,
)
+ if payload.get("prepared_summary") and commit_status != "committed":
+ from hermes_cli.observability.shared_metrics_prepared_compaction import record_prepared_compaction
+
+ record_prepared_compaction("compaction_failed", failure_class=payload.get("failure_class") or "")
except Exception as exc:
logger.debug("failed to emit compression attempt telemetry: %s", exc, exc_info=True)
diff --git a/agent/prepared_compaction.py b/agent/prepared_compaction.py
index 1fe077ea82f..24e4b93926d 100644
--- a/agent/prepared_compaction.py
+++ b/agent/prepared_compaction.py
@@ -75,6 +75,26 @@ _SUMMARY_CALL_TELEMETRY = (
# Per message: (structure, durable uid or None, text digest).
_Identity = tuple[str, Optional[str], str]
+# Why a compaction stopped waiting on a running pass; the pass then records it as its cancel reason.
+_WAIT_CANCEL_REASONS = frozenset({"wait_timeout", "host_cancelled"})
+
+
+class _Miss(str):
+ """A splice-miss reason: the log text, plus the closed code opt-in shared metrics count."""
+
+ code: str
+
+ def __new__(cls, code: str, text: str) -> _Miss:
+ miss = super().__new__(cls, text)
+ miss.code = code
+ return miss
+
+
+def _record(event: str, **dims: Any) -> None:
+ """Count one event in opt-in shared metrics (a no-op when off; never raises)."""
+ from hermes_cli.observability.shared_metrics_prepared_compaction import record_prepared_compaction
+
+ record_prepared_compaction(event, **dims)
@dataclass(frozen=True)
@@ -102,9 +122,15 @@ class _PendingPass:
self.done = threading.Event()
# Set once nothing can use the pass any more; its summary stream is closed (the aux hard-cancel path).
self.cancelled = threading.Event()
+ self.cancel_reason = "superseded" # set by whoever cancels first; the pass records it
self.on_progress: Optional[Callable[[], None]] = None
self.on_reading: Optional[Callable[[float], None]] = None
+ def cancel(self, reason: str) -> None:
+ if not self.cancelled.is_set():
+ self.cancel_reason = reason
+ self.cancelled.set()
+
def touch(self) -> None:
hook = self.on_progress
if hook is not None:
@@ -150,25 +176,25 @@ def prefix_identities(messages: list[dict[str, Any]], end: int) -> tuple[_Identi
def _mismatch(
window: _Window, messages: list[dict[str, Any]], session_id: str, start: int, end: int,
-) -> Optional[str]:
+) -> Optional[_Miss]:
"""Why *window* cannot splice into the planned window ``[start, end)`` of ``messages``, or None."""
if window.session_id != session_id:
- return "another session"
+ return _Miss("other_session", "another session")
if window.compress_start != start:
- return f"head moved ({window.compress_start} -> {start})"
+ return _Miss("head_moved", f"head moved ({window.compress_start} -> {start})")
if window.compress_end > end:
- return f"prepared boundary {window.compress_end} is inside the protected tail (cut {end})"
+ return _Miss("inside_tail", f"prepared boundary {window.compress_end} is inside the protected tail (cut {end})")
if window.compress_end > len(messages):
- return "transcript shorter than the prepared window"
+ return _Miss("transcript_shorter", "transcript shorter than the prepared window")
for idx, ((structure, uid, digest), msg) in enumerate(zip(window.identities, messages)):
now_structure, now_uid, now_digest = _message_identity(msg)
if now_structure != structure:
- return f"message {idx} changed shape"
+ return _Miss("shape_changed", f"message {idx} changed shape")
if uid and now_uid:
if uid != now_uid:
- return f"message {idx} is a different message (rewound or branched)"
+ return _Miss("rewound", f"message {idx} is a different message (rewound or branched)")
elif digest != now_digest:
- return f"message {idx} changed and has no durable id to vouch for it"
+ return _Miss("text_changed", f"message {idx} changed and has no durable id to vouch for it")
return None
@@ -207,7 +233,9 @@ class PreparedCompaction:
with self._lock:
entry, pending, self._entry, self._pending = self._entry, self._pending, None, None
if pending is not None:
- pending.cancelled.set()
+ pending.cancel("session_boundary")
+ if entry is not None or pending is not None:
+ _record("discarded", reason="session_boundary")
if entry is not None:
logger.info(
"prepared compaction: dropped window=%d-%d reason=%s", entry.compress_start, entry.compress_end, reason,
@@ -218,6 +246,7 @@ class PreparedCompaction:
if not self._needs_provider_context:
self._needs_provider_context = True
logger.info("prepared compaction: off for this agent (memory provider supplies compaction context)")
+ _record("auto_disabled", reason="provider_context")
def take(
self, messages: list[dict[str, Any]], session_id: str, start: int, end: int, *, eligible: bool,
@@ -228,15 +257,22 @@ class PreparedCompaction:
with self._lock:
entry, pending = self._entry, self._pending
self._entry = None
- reason = None if eligible else "fresh summary required"
+ reason = None if eligible else _Miss(
+ "provider_context" if self._needs_provider_context else "fresh_required", "fresh summary required",
+ )
if reason is None and entry is not None:
reason = _mismatch(entry, messages, session_id, start, end)
+ waited = None
try:
if eligible and (entry is None or reason is not None):
if pending is not None and _mismatch(pending.window, messages, session_id, start, end) is None:
+ wait_started = time.monotonic()
entry, reason = self._await(pending)
+ waited = time.monotonic() - wait_started
elif entry is None:
- reason = "running pass does not fit" if pending is not None else "no candidate"
+ reason = _Miss(
+ "running_not_fit", "running pass does not fit",
+ ) if pending is not None else _Miss("none", "no candidate")
finally:
with self._lock:
if self._pending is pending:
@@ -244,17 +280,21 @@ class PreparedCompaction:
# A pass that published after the snapshot above planned on the pre-compaction transcript.
self._entry = None
if pending is not None:
- pending.cancelled.set() # done already, or superseded: stop paying for it
+ # Done already, or superseded: stop paying for it.
+ code = getattr(reason, "code", None)
+ pending.cancel(code if code in _WAIT_CANCEL_REASONS else "superseded")
if reason is not None or entry is None:
if entry is not None or pending is not None:
logger.info("prepared compaction: splice miss reason=%s", reason)
+ _record("discarded", reason=reason.code, wait_seconds=waited)
return None
logger.info(
"prepared compaction: splice hit window=%d-%d (fresh cut %d)", entry.compress_start, entry.compress_end, end,
)
+ _record("used", reason="aux_fallback_main" if entry.telemetry.get("fallback_used") else None, wait_seconds=waited)
return entry
- def _await(self, pending: _PendingPass) -> tuple[Optional[PreparedSummary], Optional[str]]:
+ def _await(self, pending: _PendingPass) -> tuple[Optional[PreparedSummary], Optional[_Miss]]:
"""Wait on the compacting thread for *pending*: what it published, or None and why (the host's
deadline, or the compression aux timeout without one; a host cancel; a discard; a failed pass).
Meanwhile the pass's streamed progress and local prompt reading feed this thread's hooks, so the
@@ -280,19 +320,19 @@ class PreparedCompaction:
max(0.0, min(_WAIT_POLL_SECONDS, (_current_aux_stream_deadline() or fallback) - time.monotonic())),
):
if pending.cancelled.is_set():
- return None, "running pass discarded"
+ return None, _Miss("discarded_while_waiting", "running pass discarded")
if cancel_check is not None and _captured_aux_cancel_requested(cancel_check):
- return None, "host cancelled the wait"
+ return None, _Miss("host_cancelled", "host cancelled the wait")
if time.monotonic() >= (_current_aux_stream_deadline() or fallback):
- return None, "running pass did not finish in time"
+ return None, _Miss("wait_timeout", "running pass did not finish in time")
finally:
pending.on_progress = pending.on_reading = None
if pending.cancelled.is_set():
- return None, "running pass discarded"
+ return None, _Miss("discarded_while_waiting", "running pass discarded")
with self._lock:
entry, self._entry = self._entry, None
if entry is None or entry.identities != pending.window.identities:
- return None, "running pass failed"
+ return None, _Miss("pass_failed_while_waiting", "running pass failed")
return entry, None
def _blocked(self, agent: Any, compressor: Any, origin: str) -> bool:
@@ -342,6 +382,7 @@ class PreparedCompaction:
window = _Window(compressor._session_id, start, end, prefix_identities(working, end))
# Never queue threads that retain transcripts while every slot is busy.
if not _slots.acquire(blocking=False):
+ _record("skipped_busy", origin=origin)
return None
with self._lock:
if self._pending is not None or self._entry is not None:
@@ -355,6 +396,7 @@ class PreparedCompaction:
self._run_pass, name="compaction-prepare", args=(worker, copy.deepcopy(turns), focus, token, origin),
)
thread.start()
+ _record("pass_started", origin=origin)
return thread
except Exception:
if token is not None:
@@ -364,6 +406,7 @@ class PreparedCompaction:
token.done.set()
_slots.release()
logger.debug("prepared compaction: maybe_prepare failed", exc_info=True)
+ _record("internal_error", origin=origin, failure_class="exception")
return None
def _run_pass(
@@ -375,6 +418,7 @@ class PreparedCompaction:
window = token.window
entry: Optional[PreparedSummary] = None
+ event, failure_class = "pass_cancelled", None # a published summary records pass_completed instead
started = time.monotonic()
try:
logger.info(
@@ -401,13 +445,17 @@ class PreparedCompaction:
else:
logger.warning("prepared compaction: pass failed after %.1fs: %s", time.monotonic() - started,
worker._last_summary_error or "summariser returned nothing")
+ event, failure_class = "pass_failed", _pass_failure_class(worker)
except AuxiliaryExplicitCancellation:
# The closed stream raises a BaseException; it must not reach the thread's excepthook (stderr).
logger.info("prepared compaction: pass cancelled after %.1fs (superseded)", time.monotonic() - started)
except Exception:
logger.warning("prepared compaction: pass crashed", exc_info=True)
+ event, failure_class = "internal_error", "exception"
finally:
with self._lock:
+ if entry is not None and self._pending is token:
+ event = "pass_completed"
if self._pending is token:
self._pending = None
if entry is not None:
@@ -418,6 +466,18 @@ class PreparedCompaction:
)
token.done.set()
_slots.release()
+ _record(
+ event, origin=origin, reason=token.cancel_reason if event == "pass_cancelled" else None,
+ failure_class=failure_class,
+ )
+
+
+def _pass_failure_class(worker: Any) -> str:
+ """The class an inline attempt logs for this failed summary call: a terminal failure first."""
+ from agent.context_compressor import _TERMINAL_SUMMARY_FAILURES
+
+ terminal = next((cls for flag, cls, _ in _TERMINAL_SUMMARY_FAILURES if getattr(worker, flag, False)), None)
+ return terminal or (worker._active_compression_telemetry or {}).get("failure_class") or "summary_generation_failed"
def adopt(compressor: Any, prepared: PreparedSummary) -> None:
diff --git a/tests/hermes_cli/test_shared_metrics_prepared_compaction.py b/tests/hermes_cli/test_shared_metrics_prepared_compaction.py
index f6b23809de4..00c30793c4e 100644
--- a/tests/hermes_cli/test_shared_metrics_prepared_compaction.py
+++ b/tests/hermes_cli/test_shared_metrics_prepared_compaction.py
@@ -10,13 +10,17 @@
from __future__ import annotations
import json
+import threading
+import time
from pathlib import Path
import pytest
+from agent import prepared_compaction as pc
from hermes_cli.observability import shared_metrics_contract as contract
from hermes_cli.observability.shared_metrics import SharedMetricsStore
from hermes_cli.observability.shared_metrics_snapshot import collect_install_snapshot
+from tests.agent.test_prepared_compaction import _agent, _compressor, _grow, _messages
SCHEMA_PATH = (
Path(__file__).resolve().parents[2] / "hermes_cli" / "observability" / "schemas"
@@ -45,3 +49,117 @@ def test_snapshot_reports_prepare_ahead_and_older_snapshots_still_package(tmp_pa
jsonschema.Draft202012Validator(json.loads(SCHEMA_PATH.read_text(encoding="utf-8"))).validate(package)
snapshots = [m["dimensions"] for m in package["metrics"] if m["name"] == contract.INSTALL_SNAPSHOT_METRIC]
assert sorted(d.get("compression_prepare_ahead", "absent") for d in snapshots) == ["absent", "on"]
+
+
+def marks(monkeypatch):
+ """Rows as the real producer emits them, with the profile and thread each was recorded under."""
+ from hermes_cli.observability import relay_shared_metrics
+ from hermes_constants import get_hermes_home
+
+ rows = []
+ lock = threading.Lock()
+
+ def record(mark, data):
+ with lock:
+ rows.append((mark, dict(data), str(get_hermes_home()), threading.current_thread().name))
+
+ monkeypatch.setattr(relay_shared_metrics, "enabled", lambda: True)
+ monkeypatch.setattr(relay_shared_metrics, "record_process_mark", record)
+ return rows
+
+
+def _events(rows):
+ for mark, data, _home, _thread in rows:
+ assert mark == contract.PREPARED_COMPACTION_METRIC
+ assert contract.counter_dimensions_are_valid(contract.PREPARED_COMPACTION_METRIC, data), data
+ return sorted(
+ (d["event"], d["origin"], d["reason"], d["failure_class"], d["wait_bucket"]) for _m, d, _h, _t in rows
+ )
+
+
+def _run_pass(cc, msgs, origin):
+ thread = pc.maybe_prepare(_agent(cc), msgs, origin=origin)
+ assert thread is not None
+ thread.join(5.0)
+
+
+def test_pass_and_splice_outcomes_are_counted_in_the_owning_profile(tmp_path, marks):
+ from hermes_constants import reset_hermes_home_override, set_hermes_home_override
+
+ owner = tmp_path / "owner"
+ token = set_hermes_home_override(owner)
+ try:
+ msgs = _messages(30)
+ spliced = _compressor()
+ _run_pass(spliced, msgs, "tool-batch")
+ spliced.compress(_grow(msgs, 4), current_tokens=spliced.threshold_tokens + 1)
+
+ memory = _compressor()
+ _run_pass(memory, msgs, "turn-end")
+ memory.compress(msgs, current_tokens=memory.threshold_tokens + 1, memory_context="provider note")
+
+ moved = _compressor()
+ _run_pass(moved, msgs, "tool-batch")
+ moved._session_id = "S2"
+ moved.compress(msgs, current_tokens=moved.threshold_tokens + 1)
+
+ reset = _compressor()
+ _run_pass(reset, msgs, "tool-batch")
+ reset.on_session_reset()
+ finally:
+ reset_hermes_home_override(token)
+
+ pass_rows = [("pass_completed", "tool_batch", "none", "none", "none"),
+ ("pass_started", "tool_batch", "none", "none", "none")]
+ assert _events(marks) == sorted([
+ *pass_rows, ("used", "none", "none", "none", "none"),
+ ("pass_completed", "turn_end", "none", "none", "none"), ("pass_started", "turn_end", "none", "none", "none"),
+ ("auto_disabled", "none", "provider_context", "none", "none"),
+ ("discarded", "none", "provider_context", "none", "none"),
+ *pass_rows, ("discarded", "none", "other_session", "none", "none"),
+ *pass_rows, ("discarded", "none", "session_boundary", "none", "none"),
+ ])
+ assert {home for _m, _d, home, _t in marks} == {str(owner)}, "every row lands in the owning profile"
+ assert {t for _m, d, _h, t in marks if d["event"] == "pass_completed"} == {"compaction-prepare"}
+
+
+def test_waste_modes_say_why(monkeypatch, marks):
+ from agent.auxiliary_client import aux_stream_deadline
+ from agent.conversation_compression_telemetry import _emit_compression_attempt_telemetry
+ import agent.context_compressor as module
+
+ msgs = _messages(30)
+ # A compaction gives up waiting on a pass that runs past the host's deadline; the pass is told why it stops.
+ slow = _compressor()
+ slow.gate = threading.Event()
+ running = pc.maybe_prepare(_agent(slow), msgs, origin="tool-batch")
+ with aux_stream_deadline(time.monotonic() + 0.2):
+ slow.compress(msgs, current_tokens=slow.threshold_tokens + 1)
+ running.join(5.0)
+
+ # A compaction that spliced the prepared summary and then did not commit.
+ spliced = _compressor()
+ _run_pass(spliced, msgs, "turn-end")
+ spliced.compress(msgs, current_tokens=spliced.threshold_tokens + 1)
+ attempt = spliced._last_compression_telemetry
+ assert attempt["prepared_summary"] is True
+ _emit_compression_attempt_telemetry(
+ type("Agent", (), {"context_compressor": spliced, "session_id": "S1"})(), started_at=time.monotonic(),
+ commit_status="aborted", split_status="aborted", failure_class="session_split_failed",
+ attempt_seed={"attempt_id": attempt["attempt_id"], "session_id": "S1", "trigger_source": "auto"},
+ )
+
+ # A pass whose summary call fails with a terminal access error.
+ failed = _compressor()
+ monkeypatch.setattr(type(failed), "_generate_summary", module.ContextCompressor._generate_summary)
+ denied = RuntimeError("invalid api key")
+ denied.status_code = 401
+ monkeypatch.setattr(module, "call_llm", lambda **_kw: (_ for _ in ()).throw(denied))
+ _run_pass(failed, msgs, "tool-batch")
+
+ rows = _events(marks)
+ assert ("discarded", "none", "wait_timeout", "none", "lt_1s") in rows
+ assert ("pass_cancelled", "tool_batch", "wait_timeout", "none", "none") in rows
+ assert ("compaction_failed", "none", "none", "session_split_failed", "none") in rows
+ assert ("pass_failed", "tool_batch", "none", "summary_auth_failure", "none") in rows