The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): bound compression fallback and preserve queued turns
thehugegatsby6fb41c9eabf9
diff --git a/agent/conversation_compression.py b/agent/conversation_compression.pyindex ad49bf077c1..66a978656d6 100644--- a/agent/conversation_compression.py+++ b/agent/conversation_compression.py@@ -501,6 +501,13 @@ class CompressionCommitFence:raise ValueError("total compression ceiling must be positive")self._deadline = time.monotonic() + seconds+ def set_precommit_deadline_monotonic(self, deadline: float) -> None:+ """Arm one absolute pre-commit deadline shared across route attempts (primary + stall retry)."""+ deadline = float(deadline)+ if deadline <= 0:+ raise ValueError("compression deadline must be positive")+ self._deadline = deadline+def touch_progress(self) -> None:"""Record forward progress (a streamed token); a bare float store is atomic, so no lock."""self._last_progress = time.monotonic()@@ -943,6 +950,7 @@ def request_exceeds_model_window(agent: Any, request_tokens: Any) -> Optional[bodef _retry_compression_on_fallback_chain(*, worker: Callable[[CompressionCommitFence], tuple[list, str]], messages: list,system_prompt_fallback: Any, idle_timeout_seconds: float, total_ceiling_seconds: float,+ precommit_deadline_monotonic: float,on_commit_overrun: Optional[Callable[[float, float], None]] = None,on_timeout_cause: Optional[Callable[[bool, bool], None]] = None, telemetry_agent: Any = None,new_fence: Optional[Callable[[], CompressionCommitFence]] = None, escalate_deterministic: bool = False,@@ -954,10 +962,12 @@ def _retry_compression_on_fallback_chain(before. The entry's ``timeout`` sets the idle window. Re-runs the whole worker, so pre-compressioncallbacks must be idempotent.- The retry is bounded the same way the primary was: silence for one idle window ends it, while a fallback- that is streaming keeps its ceiling. The entry's own ``timeout`` (when declared) sets that idle window,- so a fallback tuned for a slower-but-healthy backend is not held to a deadline the stalled primary- defined (#62452 semantics, applied to the stall path).+ A summary-model retry spends only the primary's REMAINING pre-commit budget+ (``precommit_deadline_monotonic``, shared with the primary attempt), so a stalled primary plus a+ stalled fallback cannot each burn a full ceiling; when the budget is spent the retry is skipped. The+ entry's own ``timeout`` (when declared) still sets the retry's idle window (#62452), clamped to that+ remaining budget. The deterministic route makes no provider call, so it keeps its own budget: it is+ the over-window last resort (#114594) and must not be starved by the routes that stalled before it.Known limitation (accepted, #96634 review): the retry re-runs the COMPLETE worker, which repeatsmemory/plugin pre-compression callbacks. Built-in callbacks are idempotent (re-reads and overwrites ofattempt-scoped state); third-party plugin callbacks are advised to be. Splitting the worker to resume@@ -972,6 +982,7 @@ def _retry_compression_on_fallback_chain(recovered = _run_pinned_compression_retry(route, worker=worker, messages=messages, system_prompt_fallback=system_prompt_fallback,idle_timeout_seconds=idle_timeout_seconds, total_ceiling_seconds=total_ceiling_seconds,+ precommit_deadline_monotonic=precommit_deadline_monotonic,on_commit_overrun=on_commit_overrun, on_timeout_cause=on_timeout_cause, telemetry_agent=telemetry_agent,new_fence=new_fence,)@@ -983,10 +994,17 @@ def _retry_compression_on_fallback_chain(def _run_pinned_compression_retry(route: dict, *, worker: Callable[[CompressionCommitFence], tuple[list, str]], messages: list,system_prompt_fallback: Any, idle_timeout_seconds: float, total_ceiling_seconds: float,+ precommit_deadline_monotonic: float,on_commit_overrun: Optional[Callable[[float, float], None]], on_timeout_cause: Optional[Callable[[bool, bool], None]],telemetry_agent: Any, new_fence: Optional[Callable[[], CompressionCommitFence]],) -> Optional[tuple[list, str]]:"""One bounded re-run of ``worker`` with ``route`` pinned; ``None`` when it produced no compression."""+ deterministic = route.get("deterministic") is True+ if not deterministic and time.monotonic() >= precommit_deadline_monotonic:+ logger.info(+ "Skipping compression stall fallback on %s: the shared pre-commit ceiling is spent", route["label"],+ )+ return None# The aborted fence refuses all commits; mint a fresh one via the host factory# so a /stop during the retry serializes against THIS attempt's commit boundary.retry_fence = None@@ -1006,8 +1024,19 @@ def _run_pinned_compression_retry()retry_fence = CompressionCommitFence()idle = float(route.get("timeout") or idle_timeout_seconds)- ceiling = max(float(total_ceiling_seconds), idle)- deterministic = route.get("deterministic") is True+ if deterministic:+ # No provider call to stall on: its own budget, not the leftover the stalled routes left.+ ceiling, deadline = max(float(total_ceiling_seconds), idle), None+ else:+ ceiling, deadline = precommit_deadline_monotonic - time.monotonic(), precommit_deadline_monotonic+ if ceiling <= 0:+ retry_fence.revoke_commit_admission()+ logger.info(+ "Skipping compression stall fallback on %s: its setup spent the shared pre-commit ceiling",+ route["label"],+ )+ return None+ idle = min(idle, ceiling)if deterministic:logger.warning("Context compression stalled on every summary route — committing the %s (no summary model) "@@ -1016,7 +1045,8 @@ def _run_pinned_compression_retry(else:logger.warning("Context compression stalled on the configured summary route — "- "retrying once on %s (%s) before continuing without compression", route["label"], route["model"],+ "retrying once on %s (%s) within %.1fs of the shared pre-commit budget before continuing "+ "without compression", route["label"], route["model"], ceiling,)compressor = getattr(telemetry_agent, "context_compressor", None)streak_before = getattr(compressor, "_fallback_compression_streak", 0)@@ -1027,7 +1057,7 @@ def _run_pinned_compression_retry(worker=worker, messages=messages, system_prompt_fallback=system_prompt_fallback,idle_timeout_seconds=idle, total_ceiling_seconds=ceiling, on_commit_overrun=on_commit_overrun,on_timeout_cause=on_timeout_cause, fence=retry_fence, telemetry_agent=telemetry_agent,- stall_fallback=False,+ stall_fallback=False, precommit_deadline_monotonic=deadline,)except Exception:# The primary already failed; a failing fallback must degrade, never@@ -1174,6 +1204,7 @@ def run_compress_context_with_progress_timeout(new_fence: Optional[Callable[[], CompressionCommitFence]] = None,fallback_worker: Optional[Callable[[CompressionCommitFence], tuple[list, str]]] = None,request_exceeds_window: bool = False,+ precommit_deadline_monotonic: Optional[float] = None,) -> tuple[list, str]:"""Run ``worker(fence)`` under a sync progress-aware (idle + ceiling) timeout.Budgets bound the PRE-commit phase only: an admitted commit always completes (overrun logged, surfaced@@ -1181,7 +1212,9 @@ def run_compress_context_with_progress_timeout(callable), detaching the worker; a stall first retries the chain once on ``new_fence``, then on_timeout.``request_exceeds_window``: the request this compaction must shrink is above the model's contextwindow, so "continue without compression" is not an option — a stall escalates to the deterministic- fallback summary on the FIRST timeout instead of waiting for a prior stall in the session (#114594)."""+ fallback summary on the FIRST timeout instead of waiting for a prior stall in the session (#114594).+ ``precommit_deadline_monotonic``: an absolute deadline inherited from an earlier attempt (the stall+ retry passes the primary's), clamping this attempt's ceiling so the attempts share one budget."""if idle_timeout_seconds <= 0:raise ValueError("run_compress_context_with_progress_timeout requires "@@ -1200,8 +1233,18 @@ def run_compress_context_with_progress_timeout(# the Desktop for 10 minutes per turn).if request_exceeds_window:ceiling = idle+ wait_started = time.monotonic()+ if precommit_deadline_monotonic is None:+ precommit_deadline_monotonic = wait_started + ceiling+ else:+ ceiling = min(ceiling, float(precommit_deadline_monotonic) - wait_started)+ if ceiling <= 0:+ if fence is not None:+ fence.revoke_commit_admission()+ return messages, _resolve_fallback_prompt()+ idle = min(idle, ceiling)fence = fence if fence is not None else CompressionCommitFence()- fence.set_total_ceiling_seconds(ceiling)+ fence.set_precommit_deadline_monotonic(precommit_deadline_monotonic)# Read BEFORE this attempt runs: the host's ``stalled`` record and the cancelled worker's# ``stall_interrupted`` record both land during the unwind below, and this stall must not count as# One prior timeout-class failure = the route already burned a full idle window. An over-window request@@ -1252,7 +1295,6 @@ def run_compress_context_with_progress_timeout(_release_compression_admission()raisefuture.add_done_callback(_release_compression_admission)- wait_started = time.monotonic()# EVERY host unwind must revoke commit admission or a detached worker could# later mutate durable state; handled_exit marks paths that settle it themselveshandled_exit = False@@ -1274,7 +1316,8 @@ def run_compress_context_with_progress_timeout(if stall_fallback:recovered = _retry_compression_on_fallback_chain(worker=fallback_worker or worker, messages=messages, system_prompt_fallback=system_prompt_fallback,- idle_timeout_seconds=idle, total_ceiling_seconds=ceiling, on_commit_overrun=on_commit_overrun,+ idle_timeout_seconds=idle, total_ceiling_seconds=ceiling,+ precommit_deadline_monotonic=precommit_deadline_monotonic, on_commit_overrun=on_commit_overrun,on_timeout_cause=on_timeout_cause, telemetry_agent=telemetry_agent, new_fence=new_fence,escalate_deterministic=escalate_deterministic,)diff --git a/gateway/run_turn.py b/gateway/run_turn.pyindex d8667c1e4f1..b10e72dc30c 100644--- a/gateway/run_turn.py+++ b/gateway/run_turn.py@@ -1716,6 +1716,16 @@ class GatewayTurnMixin(GatewayTurnPrepareMixin, GatewayTurnHygieneMixin, Gatewaypending = Noneif result and adapter and session_key:pending_event = _dequeue_pending_event(adapter, session_key)+ if result.get("compression_exhausted") and pending_event is not None:+ # The outer handler owns the reset. Preserve the exact event in the head slot so the+ # adapter's post-handler drain starts it against the fresh session; do not promote or+ # prepare native media on the exhausted session.+ adapter._pending_messages[session_key] = pending_event+ logger.info(+ "Deferring queued follow-up for session %s until after its compression-exhausted reset",+ session_key,+ )+ return None, None# /queue overflow: promote the next queued event into the consumed "next-up" slot so the# recursive drain sees it (keeps FIFO order; a mid-chain /queue can't jump the queue).pending_event = self._promote_queued_event(session_key, adapter, pending_event)diff --git a/tests/agent/test_compression_stall_fallback.py b/tests/agent/test_compression_stall_fallback.pyindex 5ec907b0a6b..3c694029592 100644--- a/tests/agent/test_compression_stall_fallback.py+++ b/tests/agent/test_compression_stall_fallback.py@@ -225,11 +225,33 @@ def test_fallback_that_also_stalls_degrades_after_one_attempt():worker.release.set()assert worker.attempts == 2, "the fallback is attempted once, not in a loop"+ assert worker.fences[1].deadline_monotonic == worker.fences[0].deadline_monotonic, (+ "the fallback must not mint a second total ceiling"+ )assert msgs is original, "no messages may be dropped when both routes stall"assert prompt == "degraded-prompt"assert len(timeouts) == 1, "the degrade must be reported exactly once"+def test_total_ceiling_exhaustion_does_not_start_fallback():+ original = [{"role": "user", "content": "keep-me"}]+ worker = _StalledSummaryWorker([{"role": "user", "content": "unused"}])+ timeouts = []++ try:+ msgs, prompt = _run(+ worker, chain=[dict(CHAIN_ENTRY, timeout=0.3)], timeouts=timeouts, messages=original,+ idle=0.3, ceiling=0.3,+ )+ finally:+ worker.release.set()++ assert worker.attempts == 1, "an exhausted shared budget cannot fund a retry"+ assert msgs is original+ assert prompt == "degraded-prompt"+ assert len(timeouts) == 1++def test_same_turn_fallback_retry_is_not_gated_by_the_primary_stall_backoff(tmp_path, monkeypatch):"""The cancelled primary worker persists ``stall_interrupted`` while the fallback retry is alreadyrunning; that cooldown must not no-op the retry (#112387). Real AIAgent, real ``compress_context``diff --git a/tests/gateway/test_queued_native_image_session_key.py b/tests/gateway/test_queued_native_image_session_key.pyindex 238e0dc2d18..9d8d6d06b5e 100644--- a/tests/gateway/test_queued_native_image_session_key.py+++ b/tests/gateway/test_queued_native_image_session_key.py@@ -68,6 +68,18 @@ class CaptureQueuedNativeImageAgent:}+class CompressionExhaustedAgent(CaptureQueuedNativeImageAgent):+ def run_conversation(self, message, conversation_history=None, task_id=None):+ type(self).calls.append(message)+ return {+ "final_response": "context exhausted",+ "messages": [{"role": "user", "content": "oversized"}],+ "api_calls": 1,+ "failed": True,+ "compression_exhausted": True,+ }++def _make_runner(adapter):gateway_run = importlib.import_module("gateway.run")runner = object.__new__(gateway_run.GatewayRunner)@@ -152,3 +164,77 @@ async def test_queued_followup_uses_pending_event_session_key_for_native_images(assert queued_message[0]["type"] == "text"assert queued_message[0]["text"].startswith("describe this")assert any(part.get("type") == "image_url" for part in queued_message)+++async def test_compression_exhaustion_defers_queued_event_for_fresh_session(+ monkeypatch, tmp_path+):+ CompressionExhaustedAgent.calls = []++ fake_dotenv = types.ModuleType("dotenv")+ fake_dotenv.load_dotenv = lambda *args, **kwargs: None+ monkeypatch.setitem(sys.modules, "dotenv", fake_dotenv)++ fake_run_agent = types.ModuleType("run_agent")+ fake_run_agent.AIAgent = CompressionExhaustedAgent+ monkeypatch.setitem(sys.modules, "run_agent", fake_run_agent)++ gateway_run = importlib.import_module("gateway.run")+ monkeypatch.setattr(gateway_run, "_hermes_home", tmp_path)+ monkeypatch.setattr(+ gateway_run, "_resolve_runtime_agent_kwargs", lambda: {"api_key": "***"}+ )++ adapter = CaptureAdapter()+ runner = _make_runner(adapter)+ session_key = "agent:main:telegram:group:-1001"+ source = SessionSource(+ platform=Platform.TELEGRAM,+ chat_id="-1001",+ chat_type="group",+ )+ pending_source = SessionSource(+ platform=Platform.TELEGRAM,+ chat_id="-1001",+ chat_type="group",+ thread_id="17585",+ )+ pending_event = MessageEvent(+ text="answer this after reset",+ message_type=MessageType.PHOTO,+ source=pending_source,+ media_urls=[str(tmp_path / "queued-image.png")],+ media_types=["image/png"],+ raw_message={"native": "metadata"},+ message_id="queued-after-exhaustion",+ platform_update_id=4242,+ )+ overflow_event = MessageEvent(+ text="second in fifo",+ message_type=MessageType.TEXT,+ source=pending_source,+ message_id="queued-second",+ )+ runner._enqueue_fifo(session_key, pending_event, adapter)+ runner._enqueue_fifo(session_key, overflow_event, adapter)++ result = await runner._run_agent(+ message="oversized turn",+ context_prompt="",+ history=[{"role": "user", "content": "old context"}],+ source=source,+ session_id="bloated-session",+ session_key=session_key,+ )++ assert result["compression_exhausted"] is True+ assert len(CompressionExhaustedAgent.calls) == 1, (+ "the queued turn must not recurse into the exhausted session"+ )+ assert adapter._pending_messages[session_key] is pending_event, (+ "the exact native event must survive for the post-reset adapter drain"+ )+ assert runner._queued_events[session_key] == [overflow_event], (+ "deferral must not promote or reorder later FIFO events"+ )