The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(compression): a publish-then-discard race and a cancelled splice are counted right
Teknium7f64198bc16a
diff --git a/agent/conversation_compression_telemetry.py b/agent/conversation_compression_telemetry.pyindex 1d977e9da7a..c6908973570 100644--- a/agent/conversation_compression_telemetry.py+++ b/agent/conversation_compression_telemetry.py@@ -146,7 +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":+ state = getattr(compressor, "prepared_compaction", None)+ spliced = payload.get("prepared_summary") or (+ state is not None and state.spliced_attempt_id is not None and state.spliced_attempt_id == seed["attempt_id"])+ if spliced and commit_status != "committed":from hermes_cli.observability.shared_metrics_prepared_compaction import record_prepared_compactionrecord_prepared_compaction("compaction_failed", failure_class=payload.get("failure_class") or "")diff --git a/agent/prepared_compaction.py b/agent/prepared_compaction.pyindex a90c47f906b..2645e397637 100644--- a/agent/prepared_compaction.py+++ b/agent/prepared_compaction.py@@ -236,6 +236,11 @@ class PreparedCompaction:self._needs_provider_context = Falseself._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()+ # The attempt that spliced the last summary. Lives here, not on the compressor, because a pre-commit+ # cancel restores the compressor's attempt telemetry (and its prepared_summary flag) before the+ # attempt record is emitted.+ self.spliced_attempt_id: Optional[str] = None+ self._boundaries = 0 # discard() calls that dropped something; a wait that spans one was discardeddef _count_unspliced(self) -> None:"""A summary take() handed out that adopt() never spliced (the compaction aborted or no-opped after@@ -253,6 +258,8 @@ class PreparedCompaction:entry, pending, self._entry, self._pending = self._entry, self._pending, None, Noneif pending is not None:pending.cancel(code) # under the lock: the pass reads its cancel reason after it+ if entry is not None or pending is not None:+ self._boundaries += 1if entry is not None or pending is not None:_record("discarded", reason=code)dropped = entry or (pending.window if pending is not None else None)@@ -279,6 +286,7 @@ class PreparedCompaction:with self._lock:entry, pending = self._entry, self._pendingself._entry = None+ boundaries = self._boundariesreason = None if eligible else _Miss("provider_context" if self._needs_provider_context else "fresh_required", "fresh summary required",)@@ -291,6 +299,10 @@ class PreparedCompaction:wait_started = time.monotonic()entry, reason = self._await(pending)waited = time.monotonic() - wait_started+ if entry is None and self._boundaries != boundaries:+ # The pass published, then a boundary dropped it before this wait read it: a discard,+ # already counted by the boundary, not a failed pass.+ reason = _Miss("discarded_while_waiting", "running pass discarded")elif entry is None:reason = _Miss("running_not_fit", "running pass does not fit",@@ -525,14 +537,15 @@ 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)+ telemetry = getattr(compressor, "_active_compression_telemetry", None)if state is not None:with state._lock:if state._taken is prepared:state._taken = None+ state.spliced_attempt_id = telemetry.get("attempt_id") if isinstance(telemetry, dict) else Nonecompressor._record_summary_success(prepared.body)for name, value in prepared.call_state.items():setattr(compressor, name, value)- telemetry = getattr(compressor, "_active_compression_telemetry", None)if isinstance(telemetry, dict):telemetry.update({key: value for key, value in prepared.telemetry.items() if value is not None})telemetry["prepared_summary"] = Truediff --git a/tests/agent/test_prepared_compaction.py b/tests/agent/test_prepared_compaction.pyindex 074fce17740..e071b98c716 100644--- a/tests/agent/test_prepared_compaction.py+++ b/tests/agent/test_prepared_compaction.py@@ -429,13 +429,16 @@ def test_prompt_reading_in_the_pass_extends_the_deadline_the_wait_honours():from agent.local_prompt_progress import prompt_reading_hookcc = _compressor()- deadline = [time.monotonic() + 1.0]- initial = deadline[0]+ initial = []# The pass finishes only after the deadline the wait started with has passed.- cc.read_seconds, cc.after_read = 5.0, lambda: wait_until(lambda: time.monotonic() > initial + 0.3)+ cc.read_seconds = 5.0+ cc.after_read = lambda: wait_until(lambda: initial and time.monotonic() > initial[0] + 0.3, timeout=10)msgs = _messages(30)running = pc.maybe_prepare(_agent(cc), msgs, origin="test")assert running is not None+ # The deadline starts once the pass is running, with room for a busy runner to reach the wait.+ deadline = [time.monotonic() + 2.0]+ initial.append(deadline[0])with aux_stream_deadline(lambda: deadline[0]), prompt_reading_hook(lambda s: deadline.__setitem__(0, deadline[0] + s)):compressed = cc.compress(msgs, current_tokens=cc.threshold_tokens + 1)running.join(5.0)diff --git a/tests/hermes_cli/test_shared_metrics_prepared_compaction.py b/tests/hermes_cli/test_shared_metrics_prepared_compaction.pyindex 9229b03d0f4..5dad1047530 100644--- a/tests/hermes_cli/test_shared_metrics_prepared_compaction.py+++ b/tests/hermes_cli/test_shared_metrics_prepared_compaction.py@@ -144,6 +144,8 @@ def test_waste_modes_say_why(monkeypatch, marks):spliced.compress(msgs, current_tokens=spliced.threshold_tokens + 1)attempt = spliced._last_compression_telemetryassert attempt["prepared_summary"] is True+ # A pre-commit cancel restores the previous attempt's telemetry (no prepared_summary) before the record.+ spliced._last_compression_telemetry = spliced._active_compression_telemetry = {"attempt_id": "previous"}_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",@@ -164,6 +166,26 @@ def test_waste_modes_say_why(monkeypatch, marks):("discarded", "none", "session_boundary", "none", "none"),]+ # A boundary between the pass publishing and the woken wait reading it: one discard, by the boundary.+ raced = _compressor()+ raced.gate = threading.Event()+ running = pc.maybe_prepare(_agent(raced), msgs, origin="tool-batch")+ state, real_await = raced.prepared_compaction, raced.prepared_compaction._await++ def publish_then_discard(pending):+ raced.gate.set()+ assert pending.done.wait(5) # the pass published its summary+ state.discard("session reset") # dropped before the wait reads it+ return real_await(pending)++ state._await = publish_then_discard+ before = len(marks)+ raced.compress(msgs, current_tokens=raced.threshold_tokens + 1)+ running.join(5.0)+ assert [row for row in _events(marks[before:]) if row[0] == "discarded"] == [+ ("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")