The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(compression): keep a running attempt's record when an overlapping call stops at a gate
kshitijk4poorb862bfaaf0c6
diff --git a/agent/conversation_compression.py b/agent/conversation_compression.pyindex 184b48a65c9..3f2ce36b73b 100644--- a/agent/conversation_compression.py+++ b/agent/conversation_compression.py@@ -3935,6 +3935,11 @@ def _run_summary_phase(_activity_heartbeat = _CompressionActivityHeartbeat(agent, commit_fence=commit_fence, emit_client_status=lease.status_emitted,).start()+ # Start this attempt's telemetry clean (#118580) only now, under the lease: done at entry, a call that stops+ # at a gate or the lease erased a running attempt's record and seed.+ for _name, _value in zip(_ATTEMPT_TELEMETRY_FIELDS, (None, None, dict(attempt.seed))):+ with contextlib.suppress(Exception):+ setattr(agent.context_compressor, _name, _value)compressed = _run_summary_dispatch(agent, messages, compress_fn, compress_kwargs, commit_fence=commit_fence,attempt_generation=attempt.generation, hard_cancel_event=hard_cancel_event,@@ -4013,7 +4018,8 @@ def _begin_compression_attempt(agent: Any, *, force: bool, defer_notification: bool, trigger: Optional[str] = None,approx_tokens: Optional[int] = None, overflow_reason: Optional[str] = None,) -> _Attempt:- """Snapshot + claim the compressor, reset per-attempt agent signals, seed telemetry.+ """Snapshot + claim the compressor, reset per-attempt agent signals, build this attempt's telemetry seed+ (written to the compressor only at dispatch, in ``_run_summary_phase``).The claim stops a late-unwinding sibling (stall-fallback overlap) from restoring its snapshot over ours orclearing our cancellation consult. Signals are cleared at the VERY TOP, before codex/breakerearly-returns, so a stale value cannot make a later no-op look like lock contention;@@ -4021,13 +4027,6 @@ def _begin_compression_attempt(``conversation_history_after_compression()``."""snapshot = _snapshot_compressor_attempt_state(agent.context_compressor)generation = _claim_compressor_attempt(agent.context_compressor)- # A previous attempt's telemetry must not ride into this one (#118580 follow-up): the- # commit-time hold keeps the trio for THIS attempt's own emit, but the next attempt (and- # every emit before it re-seeds) must start clean. AFTER the snapshot so a late-unwind- # restore still round-trips the full pre-attempt state.- for _name in _ATTEMPT_TELEMETRY_FIELDS:- with contextlib.suppress(Exception):- setattr(agent.context_compressor, _name, None)if defer_notification and callable(getattr(agent, _PENDING_CONTEXT_ENGINE_NOTIFICATION, None)):raise RuntimeError("a compression notification is already pending")agent._last_compression_attempt_recorded = True@@ -4053,7 +4052,6 @@ def _begin_compression_attempt(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 = dict(seed)return _Attempt(snapshot, generation, started_at, seed)@@ -4349,13 +4347,14 @@ def compress_context(lifecycle.commit_status = ("committed" if split_status in {"not_applicable", "in_place_committed", "rotated_committed"} else "aborted")- if lifecycle.commit_status == "committed":+ # A rewrite that survived a later bookkeeping failure is still what the model sees: count it as saved.+ rewritten = commit.compacted_in_place or compressed is not messages+ if rewritten or lifecycle.commit_status == "committed":_record_committed_attempt_effect(agent, effect_messages_before, compressed, verbatim_tail, split_status)_emit_compression_attempt_telemetry(agent, started_at=attempt.started_at, commit_status=lifecycle.commit_status, split_status=split_status,failure_class=("session_split_failed" if split_status in {"failed_not_indexed", "aborted"} else None),- commit_started_at=commit.commit_started_at, attempt_seed=attempt.seed,- history_rewritten=commit.compacted_in_place or compressed is not messages,+ commit_started_at=commit.commit_started_at, attempt_seed=attempt.seed, history_rewritten=rewritten,)return compressed, new_system_promptfinally:diff --git a/agent/conversation_compression_telemetry.py b/agent/conversation_compression_telemetry.pyindex d98a3733216..1ab932dc93d 100644--- a/agent/conversation_compression_telemetry.py+++ b/agent/conversation_compression_telemetry.py@@ -101,9 +101,9 @@ def _emit_compression_attempt_telemetry(seed = _attempt_seed(agent, attempt_began=include_last_telemetry, attempt_seed=attempt_seed)own = isinstance(telemetry, dict) and telemetry.get("attempt_id") == seed["attempt_id"]if not own:- # The attempt-start clear leaves no dict before compress() seeds one, a pre-commit restore puts- # the previous attempt's back, and a newer attempt may have seeded its own: describe THIS attempt- # from its seed, never another's numbers.+ # Before dispatch the compressor still holds the previous attempt's dict, a pre-commit restore puts+ # it back, and a newer attempt may have seeded its own: describe THIS attempt from its seed, never+ # another's numbers.telemetry = {**seed, "method": "none"}payload = dict(telemetry)payload.setdefault("event", "compression_attempt")diff --git a/tests/agent/test_compaction_events.py b/tests/agent/test_compaction_events.pyindex 9dfc008509c..0502658c1a7 100644--- a/tests/agent/test_compaction_events.py+++ b/tests/agent/test_compaction_events.py@@ -454,6 +454,11 @@ def test_an_in_place_engine_whose_split_fails_after_the_archive_is_still_a_compafrom run_agent import AIAgentdef _in_place(msgs, **_kwargs):+ compressor = agent.context_compressor+ compressor._active_compression_telemetry = compressor._last_compression_telemetry = (+ compressor._begin_compression_telemetry(current_tokens=80_000)+ )+ compressor._active_compression_telemetry.update(messages_before=len(msgs), messages_after=999)msgs[:] = [msgs[0], {"role": "assistant", "content": "SANITIZED SUMMARY"}, msgs[-1]]return msgs@@ -477,3 +482,5 @@ def test_an_in_place_engine_whose_split_fails_after_the_archive_is_still_a_compaassert compressed is messages and len(compressed) < len(_messages())[(_sid, name, payload)] = publishedassert (name, payload["outcome"], payload["split_status"]) == ("compaction", "committed", "failed_not_indexed")+ # The candidate's counts are replaced by the transcript that survived.+ assert payload["messages_after"] == len(compressed)diff --git a/tests/agent/test_compression_attempt_telemetry.py b/tests/agent/test_compression_attempt_telemetry.pyindex 1aeac19375d..cedf807542d 100644--- a/tests/agent/test_compression_attempt_telemetry.py+++ b/tests/agent/test_compression_attempt_telemetry.py@@ -345,32 +345,57 @@ def test_in_place_commit_preserves_seeded_telemetry_fields(caplog):assert payload["middle_window_tokens"] is not None-def test_new_attempt_clears_previous_attempt_telemetry():- """A new attempt must not inherit the previous attempt's telemetry (#118580 follow-up).-- The commit-time hold keeps the trio for its own attempt's emit; the next attempt- (and any emit before it re-seeds) must start from a clean slate.- """+def test_an_overlapping_blocked_call_keeps_the_running_attempts_telemetry():+ """A call that stops at the automatic gate must not erase the record of an attempt still summarizing: the+ previous-attempt clear (#118580) happens only once an attempt owns the lease and dispatches its summary."""with patch("agent.context_compressor.get_model_context_length", return_value=100_000):compressor = ContextCompressor(model="test/main-model", provider="test-provider", threshold_percent=0.50, quiet_mode=True,config_context_length=100_000,)- compressor.tail_token_budget = 10- compressor._last_compression_telemetry = {- "event": "compression_attempt", "attempt_id": "prior-attempt", "session_id": "prior-session", "commit_ms": 73,- }- compressor._active_compression_telemetry = compressor._last_compression_telemetry- compressor._compression_telemetry_seed = {"attempt_id": "prior-attempt"}+ running = {"event": "compression_attempt", "attempt_id": "running-attempt", "method": "llm_summary"}+ compressor._last_compression_telemetry = compressor._active_compression_telemetry = running+ compressor._compression_telemetry_seed = {"attempt_id": "running-attempt"}+ compressor._summary_failure_cooldown_until = time.monotonic() + 600agent = _Agent(compressor)- from agent.conversation_compression import _begin_compression_attempt+ from agent.conversation_compression import compress_context++ with patch.object(type(compressor), "_refresh_durable_guards"):+ compress_context(agent, [{"role": "user", "content": "hi"}] * 4, "sys", approx_tokens=80_000)++ assert compressor._last_compression_telemetry is running+ assert compressor._active_compression_telemetry is running+ assert compressor._compression_telemetry_seed == {"attempt_id": "running-attempt"}- _begin_compression_attempt(agent, force=True, defer_notification=False)- assert compressor._last_compression_telemetry is None- assert compressor._active_compression_telemetry is None- assert compressor._compression_telemetry_seed["attempt_id"] == agent._compression_attempt_id+def test_a_lock_contended_call_keeps_the_running_attempts_telemetry(tmp_path):+ """The lock sit-out shares the gate's rule: the holder's record on a shared compressor must survive, and the+ contender logs its own ``lock_contended`` record from its seed."""+ import os++ from hermes_state import SessionDB++ db = SessionDB(db_path=tmp_path / "state.db")+ db.create_session("S", source="cli")+ assert db.try_acquire_compression_lock("S", "winner", ttl_seconds=60)+ with patch.dict(os.environ, {"OPENROUTER_API_KEY": "test-key"}):+ from run_agent import AIAgent++ agent = AIAgent(+ api_key="test-key", base_url="https://openrouter.ai/api/v1", model="test/model", quiet_mode=True,+ session_db=db, session_id="S", skip_context_files=True, skip_memory=True,+ )+ compressor = agent.context_compressor+ running = {"event": "compression_attempt", "attempt_id": "running-attempt", "method": "llm_summary"}+ compressor._last_compression_telemetry = compressor._active_compression_telemetry = running+ try:+ agent._compress_context([{"role": "user", "content": f"m{i}"} for i in range(20)], "sys", force=True)+ assert agent._compression_skipped_due_to_lock+ assert compressor._last_compression_telemetry is running+ assert compressor._active_compression_telemetry is running+ finally:+ agent.close()def test_pool_saturation_emit_does_not_inherit_previous_attempt_telemetry(caplog):