The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(compression): stop work at the total deadline
fangliquanflq8d567ccd229b
diff --git a/agent/context_compressor.py b/agent/context_compressor.pyindex 521af63b6b9..6961cd43ad2 100644--- a/agent/context_compressor.py+++ b/agent/context_compressor.py@@ -3027,6 +3027,17 @@ class ContextCompressor(ContextEngine):except Exception as exc:logger.debug("compression failure cooldown clear failed (non-sqlite): %s", exc)+ def _compression_cancelled(self) -> bool:+ """Read the host-owned cooperative cancellation signal, if installed."""+ cancelled_check = getattr(self, "_compression_cancelled_check", None)+ if not callable(cancelled_check):+ return False+ try:+ return bool(cancelled_check())+ except Exception:+ logger.debug("compression cancellation check failed", exc_info=True)+ return False+def update_model(self,model: str,@@ -4832,6 +4843,8 @@ Summary generation was unavailable, so this is a best-effort deterministic fallbplaceholder."""prompt_started_at = time.monotonic()+ if self._compression_cancelled():+ raise AuxiliaryExplicitCancellation()now = prompt_started_atif now < self._summary_failure_cooldown_until:logger.debug(@@ -5210,6 +5223,8 @@ This compaction should PRIORITISE preserving all information related to the focueffective_aux_context=_aux_context,phase_timings=_latency_info,)+ if self._compression_cancelled():+ raise AuxiliaryExplicitCancellation()# ``_validate_llm_response`` only guarantees ``choices[0].message``# exists, not that it's an object with ``.content``. Some# OpenAI-compatible proxies / local backends return a dict- ordiff --git a/agent/conversation_compression.py b/agent/conversation_compression.pyindex 0dffea6b8e4..cd3b574e0ee 100644--- a/agent/conversation_compression.py+++ b/agent/conversation_compression.py@@ -637,7 +637,7 @@ class CompressionCommitFence:fully complete before the caller proceeds."""- def __init__(self) -> None:+ def __init__(self, total_ceiling_seconds: float | None = None) -> None:self._lock = threading.Lock()self._cancelled = Falseself._commit_started = False@@ -672,6 +672,18 @@ class CompressionCommitFence:# a SLOW-but-alive summary model from a HUNG one, so slow models are# not killed by a fixed wall-clock deadline while tokens are moving.self._last_progress = time.monotonic()+ self._progress_observed = False+ self._deadline: float | None = None+ self._retain_cancelled_lock_until_worker_done = False+ if total_ceiling_seconds is not None:+ self.set_total_ceiling_seconds(total_ceiling_seconds)++ def set_total_ceiling_seconds(self, seconds: float) -> None:+ """Arm the wall-clock deadline shared by the host and worker."""+ seconds = float(seconds)+ if seconds <= 0:+ raise ValueError("total compression ceiling must be positive")+ self._deadline = time.monotonic() + secondsdef touch_progress(self) -> None:"""Record forward progress (e.g. a streamed summary token arriving).@@ -681,6 +693,17 @@ class CompressionCommitFence:CPython, so no lock is needed."""self._last_progress = time.monotonic()+ self._progress_observed = True++ @property+ def progress_observed(self) -> bool:+ """Whether semantic provider progress was reported for this attempt."""+ return self._progress_observed++ @property+ def deadline_exceeded(self) -> bool:+ deadline = self._deadline+ return deadline is not None and time.monotonic() >= deadlinedef seconds_since_progress(self) -> float:"""Seconds since the worker last reported forward progress."""@@ -723,7 +746,7 @@ class CompressionCommitFence:"""Atomically admit commit unless a hard cancellation already won."""self._lock.acquire()if (- self._cancelled+ self.is_cancelledor self._admission_revokedor (cancel_event is not None and bool(cancel_event.is_set()))):@@ -771,7 +794,11 @@ class CompressionCommitFence:@propertydef is_cancelled(self) -> bool:"""True after cancellation won before the commit boundary."""- return self._cancelled or self._admission_revoked+ return self._cancelled or self._admission_revoked or self.deadline_exceeded++ def retain_compression_lock_until_worker_done(self) -> None:+ """Prevent a timed-out live worker from overlapping a retry."""+ self._retain_cancelled_lock_until_worker_done = Truedef revoke_commit_admission(self) -> None:"""Revoke FUTURE commit admission without blocking on the fence lock.@@ -830,7 +857,7 @@ class CompressionCommitFence:the durable lock and making its cancellation cleanup callable."""self._lock.acquire()- if self._cancelled or self._admission_revoked:+ if self.is_cancelled or self._admission_revoked:self._lock.release()return Falsereturn True@@ -868,6 +895,8 @@ class CompressionCommitFence:publication is retained and fulfilled synchronously when the workerpublishes the hook."""+ if self._retain_cancelled_lock_until_worker_done:+ returnwith self._lock_release_guard:self._cancelled_lock_release_requested = Truerelease = self._cancelled_lock_release@@ -1244,9 +1273,10 @@ def run_compress_context_with_progress_timeout(return system_prompt_fallback()return system_prompt_fallback- fence = fence if fence is not None else CompressionCommitFence()ceiling = max(float(total_ceiling_seconds), float(idle_timeout_seconds))idle = float(idle_timeout_seconds)+ fence = fence if fence is not None else CompressionCommitFence()+ fence.set_total_ceiling_seconds(ceiling)# Sync mirror of gateway session-hygiene's run_in_executor(None, ...) +# wait_for loop (gateway/run.py): offload compress_context onto the shared# daemon pool, poll with an inactivity budget + total ceiling, then@@ -1348,6 +1378,15 @@ def run_compress_context_with_progress_timeout(# cancel() is a no-op for a running worker (fence handles that path).future.cancel()+ total_exhausted = (+ time.monotonic() - wait_started >= ceiling or fence.deadline_exceeded+ )+ if total_exhausted:+ # A total-ceiling candidate can still be unwinding a healthy+ # provider call. Keep its session lease until that worker exits so+ # another automatic attempt cannot overlap the unchanged source.+ fence.retain_compression_lock_until_worker_done()+cancelled: Optional[bool] = Nonewhile cancelled is None:# F1: ``begin_commit`` retains the fence lock untildiff --git a/gateway/run.py b/gateway/run.pyindex 6c7838398b5..293010310d5 100644--- a/gateway/run.py+++ b/gateway/run.py@@ -288,6 +288,32 @@ def hygiene_compaction_recovered()+def _hygiene_compression_timeout_message(+ *,+ total_exhausted: bool,+ elapsed: float,+ idle_timeout: float,+ progress_observed: bool,+) -> str:+ """Describe the host timeout that actually ended hygiene compression."""+ if total_exhausted:+ progress = (+ " after summary output was observed" if progress_observed else ""+ )+ return (+ "⚠️ Context compression reached its total ceiling after "+ f"{elapsed:.1f}s{progress}. No messages were dropped — continuing "+ "without compression. Run /compress to retry or /reset for a clean "+ "session."+ )+ return (+ f"⚠️ Context compression timed out after {idle_timeout:.1f}s with no "+ "output from the summary model. No messages were dropped — continuing "+ "without compression. Run /compress to retry, /reset for a clean "+ "session, or check your auxiliary.compression model configuration."+ )++def _record_hygiene_cooldown(gateway,session_id: str,@@ -20581,7 +20607,9 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatew_hyg_agent._print_fn = lambda *a, **kw: Noneloop = asyncio.get_running_loop()- _hyg_commit_fence = CompressionCommitFence()+ _hyg_commit_fence = CompressionCommitFence(+ total_ceiling_seconds=_hyg_total_ceiling_seconds+ )_hyg_future = loop.run_in_executor(None,lambda: _hyg_agent._compress_context(@@ -20609,10 +20637,20 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatew# from the start of this wait slice —# otherwise silence can approach 2x# the configured timeout.- _slice = max(- _hyg_timeout_seconds- - _hyg_commit_fence.seconds_since_progress(),- 0.005,+ _hyg_waited = (+ time.monotonic() - _hyg_wait_started+ )+ _slice = min(+ max(+ _hyg_timeout_seconds+ - _hyg_commit_fence.seconds_since_progress(),+ 0.005,+ ),+ max(+ _hyg_total_ceiling_seconds+ - _hyg_waited,+ 0.005,+ ),)# Bounded turn-hold (#TKT-0029): cap# this slice at the remaining@@ -20786,6 +20824,20 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatew)raiseexcept asyncio.TimeoutError:+ _hyg_waited = time.monotonic() - _hyg_wait_started+ _hyg_total_exhausted = (+ _hyg_waited >= _hyg_total_ceiling_seconds+ or _hyg_commit_fence.deadline_exceeded+ )+ if _hyg_total_exhausted:+ # The worker cooperatively checks this+ # deadline between digest calls. Keep+ # its lease until it exits so an+ # unchanged session cannot overlap a+ # retry. Inactivity timeouts retain the+ # established release behavior for a+ # provider call that may never return.+ _hyg_commit_fence.retain_compression_lock_until_worker_done()_cancelled = Nonewhile _cancelled is None:# #76354 F1: a hung commit retains the@@ -20813,13 +20865,9 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatew# successful compaction as a timeout._compressed, _ = await _hyg_futureelse:- # #76354 F4: release the timed-out- # worker's durable lease via the- # holder-qualified hook so the next- # compressor can acquire the lock- # immediately (no ABA against a new- # holder — release is holder-scoped).- _hyg_commit_fence.release_cancelled_compression_lock()+ # Cleanup follows worker completion;+ # its holder-qualified lease remains+ # live until then to exclude retries.self._defer_agent_cleanup_until_future_done(_hyg_future,_hyg_agent,@@ -20833,12 +20881,18 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatewsession_key,_hyg_failure_cooldown_seconds,)+ _timeout_reason = (+ "session hygiene compression total "+ "ceiling exhausted"+ if _hyg_total_exhausted+ else "session hygiene compression "+ "timed out with no output from the "+ "summary model"+ )_record_hygiene_cooldown(self, session_entry.session_id,_hyg_cooldown,- "session hygiene compression "- "timed out with no output from "- "the summary model",+ _timeout_reason,)from agent.session_activity import (ActivityProvenance,@@ -20850,24 +20904,39 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatew"hygiene compression timeout ""activity stamp failed",)- logger.warning(- "Session hygiene compression for session %s "- "made no progress for %.1fs "- "(total wait %.1fs, ceiling %.1fs); "- "continuing without compression",- session_entry.session_id,- _hyg_commit_fence.seconds_since_progress(),- time.monotonic() - _hyg_wait_started,- _hyg_total_ceiling_seconds,+ _hyg_elapsed = (+ time.monotonic() - _hyg_wait_started)+ if _hyg_total_exhausted:+ logger.warning(+ "Session hygiene compression for session %s "+ "reached its total ceiling after %.1fs "+ "(progress observed=%s); continuing without "+ "compression",+ session_entry.session_id,+ _hyg_elapsed,+ _hyg_commit_fence.progress_observed,+ )+ else:+ logger.warning(+ "Session hygiene compression for session %s "+ "made no progress for %.1fs (total wait "+ "%.1fs, ceiling %.1fs); continuing without "+ "compression",+ session_entry.session_id,+ _hyg_commit_fence.seconds_since_progress(),+ _hyg_elapsed,+ _hyg_total_ceiling_seconds,+ )_timeout_msg = (- "⚠️ Context compression timed out "- f"after {_hyg_timeout_seconds:.1f}s "- "with no output from the summary model. "- "No messages were dropped — continuing without "- "compression. Run /compress to retry, /reset for "- "a clean session, or check your "- "auxiliary.compression model configuration."+ _hygiene_compression_timeout_message(+ total_exhausted=_hyg_total_exhausted,+ elapsed=_hyg_elapsed,+ idle_timeout=_hyg_timeout_seconds,+ progress_observed=(+ _hyg_commit_fence.progress_observed+ ),+ ))try:_adapter = self._adapter_for_source(source)diff --git a/tests/agent/test_compress_context_progress_timeout.py b/tests/agent/test_compress_context_progress_timeout.pyindex bd4aec6c7a3..1b83f38773a 100644--- a/tests/agent/test_compress_context_progress_timeout.py+++ b/tests/agent/test_compress_context_progress_timeout.py@@ -70,7 +70,10 @@ class TestRunCompressContextWithProgressTimeout:messages=original,system_prompt_fallback="fallback-prompt",idle_timeout_seconds=0.05,- total_ceiling_seconds=0.2,+ # Leave enough total budget for a busy Windows runner to start the+ # daemon worker; this case exercises inactivity cancellation, not+ # the separate total-ceiling path.+ total_ceiling_seconds=2.0,on_timeout=lambda idle, waited, since: warnings.append((idle, waited, since)),diff --git a/tests/agent/test_compression_concurrent_fork.py b/tests/agent/test_compression_concurrent_fork.pyindex 9f5fa89d5de..1030f58abb0 100644--- a/tests/agent/test_compression_concurrent_fork.py+++ b/tests/agent/test_compression_concurrent_fork.py@@ -820,6 +820,27 @@ def test_commit_fence_waits_for_an_active_commit() -> None:assert result["cancelled"] is False+def test_total_deadline_cancellation_retains_lock_until_worker_cleanup() -> None:+ """A total-ceiling timeout must exclude retries while its worker is alive."""+ from agent.conversation_compression import CompressionCommitFence++ released = threading.Event()+ fence = CompressionCommitFence(total_ceiling_seconds=1.0)+ fence.register_cancelled_lock_release(released.set)+ fence.retain_compression_lock_until_worker_done()++ now = time.monotonic()+ with patch(+ "agent.conversation_compression.time.monotonic",+ return_value=now + 2.0,+ ):+ assert fence.is_cancelled+ assert fence.try_cancel_before_commit() is True+ fence.release_cancelled_compression_lock()++ assert not released.is_set()++def test_delayed_contender_adopts_unique_rotated_child(tmp_path: Path) -> None:"""A stale agent must continue on the winner's compacted child transcript."""db = SessionDB(db_path=tmp_path / "state.db")diff --git a/tests/agent/test_context_compressor.py b/tests/agent/test_context_compressor.pyindex c052c3fb1ad..513819ef0ca 100644--- a/tests/agent/test_context_compressor.py+++ b/tests/agent/test_context_compressor.py@@ -4,6 +4,7 @@ import jsonimport sqlite3import pytestimport time+from types import SimpleNamespacefrom unittest.mock import patch, MagicMockfrom agent.context_compressor import (@@ -25,6 +26,60 @@ class StubProviderError(Exception):self.response = response+def test_lean_chunk_digests_stop_after_host_cancellation(compressor, monkeypatch):+ """A cancelled total-deadline candidate must not dispatch another digest."""+ import agent.context_compressor as context_compressor_module++ cancelled = False+ calls = 0++ def fake_call_llm(**_kwargs):+ nonlocal cancelled, calls+ calls += 1+ cancelled = True+ return SimpleNamespace(+ choices=[SimpleNamespace(message=SimpleNamespace(content="digest"))]+ )++ monkeypatch.setattr(context_compressor_module, "_LEAN_DIGEST_CHUNK_CHARS", 20)+ monkeypatch.setattr(context_compressor_module, "_LEAN_DIGEST_MAX_CHUNKS", 8)+ monkeypatch.setattr("agent.auxiliary_client.call_llm", fake_call_llm)+ compressor._compression_cancelled_check = lambda: cancelled++ result = compressor._build_chunk_digests(+ [{"role": "tool", "content": "x" * 200, "tool_call_id": "call-1"}]+ )++ assert calls == 1+ assert "Segment 2/" not in result+++def test_lean_chunk_digests_do_not_start_after_deadline(compressor, monkeypatch):+ """The shared compaction deadline is checked before the first digest."""+ import agent.context_compressor as context_compressor_module+ from agent.conversation_compression import CompressionCommitFence++ calls = 0++ def fake_call_llm(**_kwargs):+ nonlocal calls+ calls += 1+ raise AssertionError("digest request started after total deadline")++ fence = CompressionCommitFence(total_ceiling_seconds=1.0)+ compressor._compression_cancelled_check = lambda: fence.is_cancelled+ monkeypatch.setattr("agent.auxiliary_client.call_llm", fake_call_llm)++ with patch(+ "agent.conversation_compression.time.monotonic",+ return_value=time.monotonic() + 2.0,+ ):+ assert compressor._build_chunk_digests(+ [{"role": "user", "content": "late digest"}]+ ) == ""+ assert calls == 0++@pytest.fixture()def compressor():"""Create a ContextCompressor with mocked dependencies."""diff --git a/tests/gateway/test_session_hygiene.py b/tests/gateway/test_session_hygiene.pyindex 54f440bc0a1..bac5b3ea26b 100644--- a/tests/gateway/test_session_hygiene.py+++ b/tests/gateway/test_session_hygiene.py@@ -149,6 +149,22 @@ class TestSessionHygieneThresholds:assert approx_tokens < huge_model_threshold+def test_hygiene_total_ceiling_warning_reports_elapsed_and_progress():+ from gateway.run import _hygiene_compression_timeout_message++ warning = _hygiene_compression_timeout_message(+ total_exhausted=True,+ elapsed=600.4,+ idle_timeout=30.0,+ progress_observed=True,+ )++ assert "total ceiling after 600.4s" in warning+ assert "summary output was observed" in warning+ assert "30.0s" not in warning+ assert "no output" not in warning++class TestSessionHygieneWarnThreshold:"""Test the post-compression warning threshold (95% of context)."""@@ -600,16 +616,9 @@ async def test_session_hygiene_timeout_continues_to_agent_and_sets_cooldown(monkmessage_id="1",)- started = time.monotonic()result = await runner._handle_message(event)- elapsed = time.monotonic() - startedassert result == "ok"- # Loose wall-clock bound per flake policy: this asserts the handler did- # NOT block on the hygiene-compression timeout path (which would take- # multiple seconds), not a precise latency. 0.15s missed by ~1-8ms on- # busy CI shards twice on 2026-07-23.- assert elapsed < 2.0assert worker_started.is_set()assert runner._run_agent.await_count == 1# Cooldown must be persisted to the state DB (survives restart, #74136),@@ -621,6 +630,9 @@ async def test_session_hygiene_timeout_continues_to_agent_and_sets_cooldown(monktimeout_warnings = [s for s in adapter.sent if "Context compression timed out" in s["content"]]assert len(timeout_warnings) == 1fake_db.archive_and_compact.assert_not_called()+ # Event/state assertions prove the host returned before the detached+ # worker's two-second wait completed without a scheduler-sensitive clock+ # bound: cleanup runs only when that worker actually exits.SlowCompressAgent.last_instance.close.assert_not_called()release_worker.set()