Skip to content

The agent that grows with you

fix(compression): every prepared summary ends counted as used or discarded

Tekniumd773589f7c6e
diff --git a/agent/prepared_compaction.py b/agent/prepared_compaction.py
index 42cfad602f7..a90c47f906b 100644
--- a/agent/prepared_compaction.py
+++ b/agent/prepared_compaction.py
@@ -235,10 +235,20 @@ class PreparedCompaction:
# Set by the first compaction that needed memory-provider context; such compactions summarise fresh.
self._needs_provider_context = False
self._busy_window: Optional[tuple[str, int, int]] = None # last window the slot cap refused (counted once)
+ self._taken: Optional[PreparedSummary] = None # handed to compress(), not yet spliced by adopt()
+
+ def _count_unspliced(self) -> None:
+ """A summary take() handed out that adopt() never spliced (the compaction aborted or no-opped after
+ taking it) is counted once, at the next touch, so every summary ends as used or discarded."""
+ with self._lock:
+ taken, self._taken = self._taken, None
+ if taken is not None:
+ _record("discarded", reason="compaction_aborted", wait_seconds=taken.waited)
def discard(self, reason: str, code: str = "session_boundary") -> None:
"""Drop the candidate and cancel a running pass (it can no longer publish); ``code`` is the closed
reason opt-in shared metrics count."""
+ self._count_unspliced()
with self._lock:
entry, pending, self._entry, self._pending = self._entry, self._pending, None, None
if pending is not None:
@@ -265,6 +275,7 @@ class PreparedCompaction:
"""The completed candidate when it fits ``compress()``'s planned window, else what a running pass
whose window fits publishes while this compaction waits for it, else None. Either way the state is
cleared and a running pass is cancelled: this compaction consumes or supersedes it."""
+ self._count_unspliced()
with self._lock:
entry, pending = self._entry, self._pending
self._entry = None
@@ -304,7 +315,10 @@ class PreparedCompaction:
"prepared compaction: splice hit session=%s window=%d-%d (fresh cut %d)", session_id, entry.compress_start,
entry.compress_end, end,
)
- return replace(entry, waited=waited) # counted as used once adopt() splices it
+ taken = replace(entry, waited=waited) # counted as used once adopt() splices it
+ with self._lock:
+ self._taken = taken
+ return taken
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
@@ -339,10 +353,11 @@ class PreparedCompaction:
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, _Miss("discarded_while_waiting", "running pass discarded")
- with self._lock:
+ with self._lock: # a discard() between the pass publishing and this wake took the entry and cancelled
entry, self._entry = self._entry, None
+ discarded = pending.cancelled.is_set()
+ if discarded:
+ return None, _Miss("discarded_while_waiting", "running pass discarded")
if entry is None or entry.identities != pending.window.identities:
return None, _Miss("pass_failed_while_waiting", "running pass failed")
return entry, None
@@ -374,6 +389,7 @@ class PreparedCompaction:
Never raises."""
token: Optional[_PendingPass] = None
try:
+ self._count_unspliced()
if self._blocked(agent, compressor, origin):
return None
with self._lock:
@@ -508,6 +524,11 @@ def release_for_agent(agent: Any) -> None:
def adopt(compressor: Any, prepared: PreparedSummary) -> None:
"""Leave the live compressor as the inline summary call would have: the summary is the iterative base,
failure state cleared, the pass's main-model fallback (if any) carried over, its call in the telemetry."""
+ state = getattr(compressor, "prepared_compaction", None)
+ if state is not None:
+ with state._lock:
+ if state._taken is prepared:
+ state._taken = None
compressor._record_summary_success(prepared.body)
for name, value in prepared.call_state.items():
setattr(compressor, name, value)
diff --git a/hermes_cli/observability/schemas/hermes.shared_metrics.v4.schema.json b/hermes_cli/observability/schemas/hermes.shared_metrics.v4.schema.json
index 07ab53e67aa..3201f0ffe9d 100644
--- a/hermes_cli/observability/schemas/hermes.shared_metrics.v4.schema.json
+++ b/hermes_cli/observability/schemas/hermes.shared_metrics.v4.schema.json
@@ -5353,6 +5353,7 @@
"enum": [
"agent_released",
"aux_fallback_main",
+ "compaction_aborted",
"fresh_required",
"head_moved",
"host_cancelled",
diff --git a/hermes_cli/observability/shared_metrics_prepared_compaction.py b/hermes_cli/observability/shared_metrics_prepared_compaction.py
index 510d9f53da0..3f7c0611388 100644
--- a/hermes_cli/observability/shared_metrics_prepared_compaction.py
+++ b/hermes_cli/observability/shared_metrics_prepared_compaction.py
@@ -21,7 +21,7 @@ PREPARED_COMPACTION_EVENTS = frozenset({
})
PREPARED_COMPACTION_ORIGINS = frozenset({"none", "tool_batch", "turn_end"})
PREPARED_COMPACTION_REASONS = frozenset({
- "agent_released", "aux_fallback_main", "fresh_required", "head_moved", "host_cancelled",
+ "agent_released", "aux_fallback_main", "compaction_aborted", "fresh_required", "head_moved", "host_cancelled",
"inside_tail", "none", "other_session", "pass_failed_while_waiting", "provider_context", "rewound",
"running_not_fit", "session_boundary", "shape_changed", "superseded", "text_changed",
"transcript_shorter", "wait_timeout",
diff --git a/tests/hermes_cli/test_shared_metrics_prepared_compaction.py b/tests/hermes_cli/test_shared_metrics_prepared_compaction.py
index e48618f3de3..9229b03d0f4 100644
--- a/tests/hermes_cli/test_shared_metrics_prepared_compaction.py
+++ b/tests/hermes_cli/test_shared_metrics_prepared_compaction.py
@@ -164,6 +164,18 @@ def test_waste_modes_say_why(monkeypatch, marks):
("discarded", "none", "session_boundary", "none", "none"),
]
+ # A compaction that took the summary and then aborted before splicing it: counted at the next touch.
+ aborted = _compressor()
+ _run_pass(aborted, msgs, "tool-batch")
+ held = aborted.prepared_compaction._entry
+ taken = aborted.prepared_compaction.take(msgs, held.session_id, held.compress_start, held.compress_end, eligible=True)
+ assert taken is not None
+ before = len(marks)
+ aborted.on_session_end(held.session_id, msgs)
+ assert [row for row in _events(marks[before:]) if row[0] == "discarded"] == [
+ ("discarded", "none", "compaction_aborted", "none", "none"),
+ ]
+
# A pass whose summary call fails with a terminal access error.
failed = _compressor()
monkeypatch.setattr(type(failed), "_generate_summary", module.ContextCompressor._generate_summary)
diff --git a/website/docs/developer-guide/relay-shared-metrics.md b/website/docs/developer-guide/relay-shared-metrics.md
index 41b53a0f216..f24970833a5 100644
--- a/website/docs/developer-guide/relay-shared-metrics.md
+++ b/website/docs/developer-guide/relay-shared-metrics.md
@@ -570,7 +570,7 @@ appears in any dimension: the free-text splice-miss reason is reduced to a close
| Metric | Dimensions | Question it answers |
|---|---|---|
-| `hermes.prepared_compaction.count` | event (`pass_started`, `pass_completed`, `pass_failed`, `pass_cancelled`, `used`, `discarded`, `compaction_failed`, `auto_disabled`, `skipped_busy`, `internal_error`), origin (`tool_batch`, `turn_end`: the hook that started the pass; `none` on compaction-side events), reason (`none`, `fresh_required`, `provider_context`, `other_session`, `head_moved`, `inside_tail`, `transcript_shorter`, `shape_changed`, `rewound`, `text_changed`, `running_not_fit`, `wait_timeout`, `host_cancelled`, `pass_failed_while_waiting`, `superseded`, `session_boundary`, `agent_released`, `aux_fallback_main`), failure class (the `hermes.compression.count` vocabulary; `none` unless the event is a failure), wait bucket (`none`, `lt_1s`, `1s_to_5s`, `5s_to_30s`, `30s_to_120s`, `gte_120s`: how long a compaction waited on a running pass) | Do prepared passes pay off, and if not, why. Pass side (from the background thread): `pass_started`, `pass_completed` (summary published), `pass_failed` (the summariser returned nothing; its class is the one an inline attempt would log, a terminal summary failure first), `pass_cancelled` (the pass saw its cancel event; reason `superseded`, `session_boundary`, `agent_released`, `wait_timeout` or `host_cancelled`, set by whoever cancelled it), `skipped_busy` (the process-wide cap of two concurrent passes refused a pass; counted once per refused window, not per tool batch) and `internal_error` (failure class `exception`). Compaction side: `used` (the summary was spliced into the compacted transcript, counted at the splice itself; reason `aux_fallback_main` when the pass fell back from the summary model to the main model), `discarded` (a completed or running summary the compaction did not use, with the splice-miss code and any wait; a session boundary dropping one reads `session_boundary`, releasing the agent (cache eviction, rewind, close, a one-shot or managed-worker turn ending) reads `agent_released`), `compaction_failed` (a compaction that spliced a prepared summary but did not commit, with its attempt class) and `auto_disabled` (the first compaction needing memory-provider context turned passes off for the agent). One pass can count on both sides, so never add sides together: `discarded` + `pass_cancelled` for a running pass that did not fit or was dropped at a boundary (a boundary that wakes a waiting compaction counts `discarded` once, from the boundary). |
+| `hermes.prepared_compaction.count` | event (`pass_started`, `pass_completed`, `pass_failed`, `pass_cancelled`, `used`, `discarded`, `compaction_failed`, `auto_disabled`, `skipped_busy`, `internal_error`), origin (`tool_batch`, `turn_end`: the hook that started the pass; `none` on compaction-side events), reason (`none`, `fresh_required`, `provider_context`, `other_session`, `head_moved`, `inside_tail`, `transcript_shorter`, `shape_changed`, `rewound`, `text_changed`, `running_not_fit`, `wait_timeout`, `host_cancelled`, `pass_failed_while_waiting`, `superseded`, `session_boundary`, `agent_released`, `compaction_aborted`, `aux_fallback_main`), failure class (the `hermes.compression.count` vocabulary; `none` unless the event is a failure), wait bucket (`none`, `lt_1s`, `1s_to_5s`, `5s_to_30s`, `30s_to_120s`, `gte_120s`: how long a compaction waited on a running pass) | Do prepared passes pay off, and if not, why. Pass side (from the background thread): `pass_started`, `pass_completed` (summary published), `pass_failed` (the summariser returned nothing; its class is the one an inline attempt would log, a terminal summary failure first), `pass_cancelled` (the pass saw its cancel event; reason `superseded`, `session_boundary`, `agent_released`, `wait_timeout` or `host_cancelled`, set by whoever cancelled it), `skipped_busy` (the process-wide cap of two concurrent passes refused a pass; counted once per refused window, not per tool batch) and `internal_error` (failure class `exception`). Compaction side: `used` (the summary was spliced into the compacted transcript, counted at the splice itself; reason `aux_fallback_main` when the pass fell back from the summary model to the main model), `discarded` (a completed or running summary the compaction did not use, with the splice-miss code and any wait; a session boundary dropping one reads `session_boundary`, releasing the agent (cache eviction, rewind, close, a one-shot or managed-worker turn ending) reads `agent_released`, and a summary the compaction took but then aborted or no-opped before splicing reads `compaction_aborted`), `compaction_failed` (a compaction that spliced a prepared summary but did not commit, with its attempt class) and `auto_disabled` (the first compaction needing memory-provider context turned passes off for the agent). One pass can count on both sides, so never add sides together: `discarded` + `pass_cancelled` for a running pass that did not fit or was dropped at a boundary (a boundary that wakes a waiting compaction counts `discarded` once, from the boundary). |
<!-- ---- v5 harness ---- -->
#### Agent-harness accuracy