The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(agent): stop compression retries after host timeout (#98722)
fangliquanflq53c0df6de92f
diff --git a/agent/conversation_compression.py b/agent/conversation_compression.pyindex 19056ad185f..322d8744113 100644--- a/agent/conversation_compression.py+++ b/agent/conversation_compression.py@@ -1899,6 +1899,76 @@ def compression_skipped_due_to_lock(agent: Any) -> bool:return _sig is True or isinstance(_sig, str)+def _get_context_compression_timeout_state(+ agent: Any,+ *,+ create: bool,+) -> Optional[Tuple[Any, Optional[threading.local]]]:+ """Return the stable lock and thread-local timeout state for an agent."""+ try:+ attributes = vars(agent)+ except TypeError:+ return None++ lock = attributes.setdefault(+ "_context_compression_timeout_state_lock",+ threading.Lock(),+ )+ with lock:+ state = attributes.get("_context_compression_timeout_state")+ if create and not isinstance(state, threading.local):+ state = threading.local()+ attributes["_context_compression_timeout_state"] = state+ return lock, state if isinstance(state, threading.local) else None+++def reset_context_compression_timeout_outcome(agent: Any) -> None:+ """Clear the current thread's owned-compression timeout outcome.++ The compatibility mirror ``agent._last_compression_timed_out`` is the+ simple per-attempt flag landed by #98424 (turn-start preflight fail-closed+ boundary); it stays authoritative for minimal/older agent doubles that do+ not support ``vars()``.+ """+ locked_state = _get_context_compression_timeout_state(agent, create=True)+ if locked_state is None or locked_state[1] is None:+ agent._last_compression_timed_out = False+ return+ lock, state = locked_state+ with lock:+ state.timed_out = False+ agent._last_compression_timed_out = False+++def mark_context_compression_timed_out(agent: Any) -> None:+ """Mark the current owned compression as host-timed-out."""+ locked_state = _get_context_compression_timeout_state(agent, create=True)+ if locked_state is None or locked_state[1] is None:+ agent._last_compression_timed_out = True+ return+ lock, state = locked_state+ with lock:+ state.timed_out = True+ agent._last_compression_timed_out = True+++def context_compression_timed_out(agent: Any) -> bool:+ """Return whether this thread's owned compression hit its host timeout.++ A single agent may receive overlapping automatic/manual entrypoints. The+ thread-local outcome prevents one entrypoint's reset from hiding another's+ timeout. The attribute fallback supports older/minimal agent doubles.+ Every read is type-pinned to avoid MagicMock auto-attributes.+ """+ locked_state = _get_context_compression_timeout_state(agent, create=False)+ if locked_state is not None:+ lock, state = locked_state+ with lock:+ if isinstance(state, threading.local):+ return getattr(state, "timed_out", None) is True+ return getattr(agent, "_last_compression_timed_out", None) is True++def compression_blocked_transiently(agent: Any) -> bool:"""Type-pinned read of the transient-block signal (#97488).diff --git a/agent/conversation_loop.py b/agent/conversation_loop.pyindex c67550de78e..f38c406ee73 100644--- a/agent/conversation_loop.py+++ b/agent/conversation_loop.py@@ -35,6 +35,7 @@ from agent.conversation_compression import (PRE_API_COMPRESSION_STATUS_TEMPLATE,compression_blocked_transiently,compression_skipped_due_to_lock,+ context_compression_timed_out,conversation_history_after_compression,)from agent.context_engine import automatic_compaction_status_message@@ -297,6 +298,16 @@ _HANDOFF_SKIP_FINAL_RESPONSE = ("awaiting your next message.")+# Terminal final_response for a turn ended because context compression hit its+# host progress-aware timeout while the request was still oversized (#98722,+# salvaged from #98741). Sending the unchanged request would only bounce off+# the provider's overflow error and re-enter compression in the same turn.+_COMPRESSION_TIMEOUT_FINAL_RESPONSE = (+ "Context compression timed out without reducing this conversation. "+ "No messages were dropped. Start a fresh session with /new, or check "+ "auxiliary.compression before retrying /compress."+)+# Stable prefix of the local interrupt status string emitted when a turn is# cancelled while waiting on the provider. Surfaces (ACP, TUI) match on this@@ -2046,6 +2057,10 @@ def run_conversation(max_compression_attempts = getattr(agent, "max_compression_attempts", 3)_last_preflight_pressure: Optional[int] = None_preflight_compression_blocked = _ctx.preflight_compression_blocked+ # Armed when a compression host-timeout terminates the turn (#98722,+ # salvaged from #98741); finalize below reuses the gateway's existing+ # context-recovery contract (error/partial/compression_exhausted).+ _compression_timeout_exhausted = False_turn_exit_reason = "unknown" # Diagnostic: why the loop ended# Last composed answer intentionally held back by a verification gate. If# that continuation consumes the remaining budget, this is the best@@ -2848,6 +2863,22 @@ def run_conversation(approx_tokens=request_pressure_tokens,task_id=effective_task_id,)+ if context_compression_timed_out(agent):+ # Host progress-aware timeout (#98722, salvaged from #98741):+ # this preflight iteration never reached the provider. Refund+ # its provisional call/budget exactly like a successful+ # pre-API compaction, then stop before the unchanged oversized+ # request reaches the provider — its overflow error would only+ # invoke compression again on the same transcript with the+ # wait budget already spent.+ api_call_count -= 1+ agent._api_call_count = api_call_count+ agent.iteration_budget.refund()+ final_response = _COMPRESSION_TIMEOUT_FINAL_RESPONSE+ failed = True+ _compression_timeout_exhausted = True+ _turn_exit_reason = "context_compression_timeout"+ breakif messages is _pre_api_input and (compression_skipped_due_to_lock(agent)or compression_blocked_transiently(agent)@@ -6190,6 +6221,28 @@ def run_conversation(agent, messages, api_call_count,reason="transient_block",)+ if context_compression_timed_out(agent):+ # Host progress-aware timeout (#98722, salvaged from+ # #98741): the provider proved the request does not+ # fit, but this recovery pass spent the full wait+ # budget without a committed summary. Re-sending the+ # unchanged request would bounce off the same overflow+ # error and re-enter compression in the same turn. End+ # the turn with the typed recovery contract instead —+ # transcript intact, no further doomed provider sends.+ agent._persist_session(messages, conversation_history)+ _final_response = _COMPRESSION_TIMEOUT_FINAL_RESPONSE+ return {+ "final_response": _final_response,+ "messages": messages,+ "completed": False,+ "api_calls": api_call_count,+ "error": _final_response,+ "partial": True,+ "failed": True,+ "compression_exhausted": True,+ "turn_exit_reason": "context_compression_timeout",+ }conversation_history = conversation_history_after_compression(agent, messages, conversation_history)@@ -8807,7 +8860,7 @@ def run_conversation(# Post-loop turn finalization extracted to agent/turn_finalizer.finalize_turn# (god-file decomposition Phase 1 step 4). Behavior-neutral: the assembled# result dict is returned exactly as before.- return finalize_turn(+ result = finalize_turn(agent,final_response=final_response,api_call_count=api_call_count,@@ -8824,6 +8877,15 @@ def run_conversation(_pending_verification_response=_pending_verification_response,_pending_verification_response_previewed=_pending_verification_response_previewed,)+ if _compression_timeout_exhausted:+ # Reuse the gateway's existing context-recovery contract (#98722,+ # salvaged from #98741). The bloated transcript remains intact while+ # future input can move to a clean session instead of replaying the+ # summarize-timeout loop.+ result["error"] = _COMPRESSION_TIMEOUT_FINAL_RESPONSE+ result["partial"] = True+ result["compression_exhausted"] = True+ return resultdiff --git a/agent/turn_context.py b/agent/turn_context.pyindex e250b79cdd3..d6882e9129b 100644--- a/agent/turn_context.py+++ b/agent/turn_context.py@@ -411,7 +411,9 @@ class PreflightCompressionTimedOut(RuntimeError):def _fail_closed_after_preflight_timeout(agent, request_tokens: int) -> None:"""Stop an oversized turn instead of sending its unchanged provider payload."""- if not getattr(agent, "_last_compression_timed_out", False):+ from agent.conversation_compression import context_compression_timed_out++ if not context_compression_timed_out(agent):returnraise PreflightCompressionTimedOut("Context compression timed out before it could commit while the request "diff --git a/run_agent.py b/run_agent.pyindex e42248329a6..4d5ea6f5ab8 100644--- a/run_agent.py+++ b/run_agent.py@@ -8134,17 +8134,22 @@ class AIAgent:auto-compress abort. Auto-compress callers use the default``force=False``."""- # Per-attempt signal consumed by turn-start preflight. A stalled- # compression must not be mistaken for a structural no-op and followed- # by the oversized provider request it was meant to prevent.- self._last_compression_timed_out = False-+ # Per-attempt signal consumed by turn-start preflight (#98424) and the+ # in-loop pre-API/overflow consumers. A stalled compression must not+ # be mistaken for a structural no-op and followed by the oversized+ # provider request it was meant to prevent. The typed helper upgrades+ # the simple attribute to thread-local state guarded by a per-agent+ # lock so overlapping automatic/manual entrypoints cannot clobber each+ # other's outcome (#98741).from agent.conversation_compression import (CompressionCommitFence,compress_context,+ mark_context_compression_timed_out,+ reset_context_compression_timeout_outcome,resolve_context_compression_timeouts,run_compress_context_with_progress_timeout,)+ reset_context_compression_timeout_outcome(self)from agent.portal_tags import (get_conversation_context,reset_conversation_context,@@ -8265,7 +8270,7 @@ class AIAgent:timeout_cause["progress_observed"] = progress_observeddef _on_timeout(idle, waited, since_progress):- self._last_compression_timed_out = True+ mark_context_compression_timed_out(self)total_exhausted = timeout_cause["total_exhausted"]progress_observed = timeout_cause["progress_observed"]if total_exhausted:diff --git a/tests/agent/test_compress_context_progress_timeout.py b/tests/agent/test_compress_context_progress_timeout.pyindex 7bed4a32fc3..3a5ed5b06c9 100644--- a/tests/agent/test_compress_context_progress_timeout.py+++ b/tests/agent/test_compress_context_progress_timeout.py@@ -18,11 +18,111 @@ import pytestimport agent.conversation_compression as ccfrom agent.conversation_compression import (CompressionCommitFence,+ context_compression_timed_out,+ mark_context_compression_timed_out,+ reset_context_compression_timeout_outcome,resolve_context_compression_timeouts,run_compress_context_with_progress_timeout,)+class TestContextCompressionTimeoutState:+ """Thread-safe typed timeout state (#98741, on top of #98424's flag)."""++ def test_timeout_state_first_use_is_atomic(self, monkeypatch):+ from types import SimpleNamespace++ agent = SimpleNamespace()+ reset_constructor_entered = threading.Event()+ marker_constructor_finished = threading.Event()+ release_reset_constructor = threading.Event()+ reset_finished = threading.Event()+ marker_finished = threading.Event()+ seen = {}+ original_local = threading.local++ class DelayedLocal(original_local):+ def __new__(cls):+ state = super().__new__(cls)+ if threading.current_thread().name == "timeout-resetter":+ reset_constructor_entered.set()+ assert release_reset_constructor.wait(timeout=2)+ else:+ marker_constructor_finished.set()+ return state++ monkeypatch.setattr(cc.threading, "local", DelayedLocal)++ def resetter():+ reset_context_compression_timeout_outcome(agent)+ reset_finished.set()+ assert marker_finished.wait(timeout=2)+ seen["resetter"] = context_compression_timed_out(agent)++ def marker():+ mark_context_compression_timed_out(agent)+ marker_finished.set()+ assert reset_finished.wait(timeout=2)+ seen["marker"] = context_compression_timed_out(agent)++ reset_thread = threading.Thread(target=resetter, name="timeout-resetter")+ mark_thread = threading.Thread(target=marker, name="timeout-marker")+ reset_thread.start()+ assert reset_constructor_entered.wait(timeout=2)+ mark_thread.start()++ # A fixed implementation publishes the initialization lock before+ # constructing the state. The old implementation lets the marker+ # publish a competing state while the resetter is paused here.+ if "_context_compression_timeout_state_lock" not in vars(agent):+ assert marker_constructor_finished.wait(timeout=2)+ release_reset_constructor.set()++ reset_thread.join(timeout=2)+ mark_thread.join(timeout=2)++ assert not reset_thread.is_alive()+ assert not mark_thread.is_alive()+ assert seen == {"resetter": False, "marker": True}++ def test_timeout_outcome_is_isolated_between_overlapping_entrypoints(self):+ from types import SimpleNamespace++ agent = SimpleNamespace()+ worker_marked = threading.Event()+ main_reset = threading.Event()+ seen = {}++ def worker():+ reset_context_compression_timeout_outcome(agent)+ mark_context_compression_timed_out(agent)+ worker_marked.set()+ assert main_reset.wait(timeout=2)+ seen["worker"] = context_compression_timed_out(agent)++ thread = threading.Thread(target=worker)+ thread.start()+ assert worker_marked.wait(timeout=2)++ reset_context_compression_timeout_outcome(agent)+ seen["main"] = context_compression_timed_out(agent)+ main_reset.set()+ thread.join(timeout=2)++ assert not thread.is_alive()+ assert seen == {"main": False, "worker": True}++ def test_attribute_fallback_for_minimal_doubles(self):+ class Slotted:+ __slots__ = ("_last_compression_timed_out",)++ agent = Slotted()+ mark_context_compression_timed_out(agent)+ assert context_compression_timed_out(agent) is True+ reset_context_compression_timeout_outcome(agent)+ assert context_compression_timed_out(agent) is False++class TestResolveContextCompressionTimeouts:def test_defaults_when_empty_cfg(self):idle, ceiling = resolve_context_compression_timeouts({})diff --git a/tests/run_agent/test_compression_timeout_terminal.py b/tests/run_agent/test_compression_timeout_terminal.pynew file mode 100644index 00000000000..9aa4dfe5ec9--- /dev/null+++ b/tests/run_agent/test_compression_timeout_terminal.py@@ -0,0 +1,178 @@+"""Host compression timeout terminates the turn before provider re-entry (#98722).++Salvaged from #98741 and composed with the already-merged #98424 turn-start+fail-closed boundary:++- #98424 covers the TURN-START preflight (raises+ ``PreflightCompressionTimedOut`` before the loop starts).+- These tests pin the two consumers unique to #98741: the provider-overflow+ recovery path must not re-enter compression / re-send the unchanged request+ once the wait budget was spent, and the mid-turn pre-API pass must end the+ turn with the typed ``compression_exhausted`` recovery contract.+"""++from __future__ import annotations++from types import SimpleNamespace+from unittest.mock import MagicMock, patch++import pytest++import run_agent+from run_agent import AIAgent++[email protected](autouse=True)+def _no_compression_sleep(monkeypatch):+ import time as _time++ monkeypatch.setattr(_time, "sleep", lambda *_a, **_k: None)+ monkeypatch.setattr(run_agent, "jittered_backoff", lambda *a, **k: 0.0)+++def _make_agent():+ with (+ patch("run_agent.get_tool_definitions", return_value=[]),+ patch("run_agent.check_toolset_requirements", return_value={}),+ patch("run_agent.OpenAI"),+ ):+ agent = AIAgent(+ api_key="test-key-1234567890",+ base_url="https://openrouter.ai/api/v1",+ quiet_mode=True,+ skip_context_files=True,+ skip_memory=True,+ )+ agent.client = MagicMock()+ agent._cached_system_prompt = "You are helpful."+ agent._use_prompt_caching = False+ agent.tool_delay = 0+ agent.save_trajectories = False+ agent.compression_enabled = True+ return agent+++def _mock_response(content="Hello", finish_reason="stop"):+ msg = SimpleNamespace(+ content=content, tool_calls=None, reasoning_content=None, reasoning=None+ )+ choice = SimpleNamespace(message=msg, finish_reason=finish_reason)+ resp = SimpleNamespace(choices=[choice], model="test/model")+ resp.usage = None+ return resp+++def test_overflow_recovery_timeout_ends_turn_without_provider_reentry():+ """Provider 400 overflow + host-timed-out compression = typed terminal.++ Before the fix, the timed-out pass was indistinguishable from an+ ordinary no-op: the loop re-sent the unchanged oversized request, the+ provider overflowed again, and compression was re-entered in the same+ turn (#98722 "Summarizing" loop).+ """+ agent = _make_agent()++ err_400 = Exception(+ "This model's maximum context length is 8192 tokens. However, "+ "your messages resulted in 95000 tokens. Please reduce the length "+ "of the messages."+ )+ err_400.status_code = 400+ agent.client.chat.completions.create.side_effect = [err_400, err_400]++ compression_calls = []++ def _timed_out(messages, _system_message, **_kwargs):+ compression_calls.append(1)+ from agent.conversation_compression import (+ mark_context_compression_timed_out,+ reset_context_compression_timeout_outcome,+ )++ reset_context_compression_timeout_outcome(agent)+ mark_context_compression_timed_out(agent)+ return messages, agent._cached_system_prompt++ agent._compress_context = _timed_out++ history = [+ {"role": "user", "content": "old request"},+ {"role": "assistant", "content": "old response"},+ ]+ with (+ patch.object(agent, "_persist_session"),+ patch.object(agent, "_save_trajectory"),+ patch.object(agent, "_cleanup_task_resources"),+ ):+ result = agent.run_conversation("continue", conversation_history=history)++ # Exactly one doomed send proved the overflow; the timed-out recovery+ # pass must not be followed by a second identical send.+ assert compression_calls == [1]+ assert agent.client.chat.completions.create.call_count == 1+ assert result["failed"] is True+ assert result["completed"] is False+ assert result["compression_exhausted"] is True+ assert "No messages were dropped" in result["final_response"]+ assert result["error"] == result["final_response"]+++def test_pre_api_compression_timeout_is_typed_terminal():+ """Mid-turn pre-API pass that hits the host timeout ends the turn."""+ agent = _make_agent()+ agent.context_compressor.protect_first_n = 0+ agent.context_compressor.protect_last_n = 0+ agent.context_compressor._threshold_tokens = 1+ agent.context_compressor.should_compress = MagicMock(return_value=True)+ agent.context_compressor.should_compress_info = MagicMock(+ return_value=(True, None)+ )+ agent.context_compressor.should_defer_preflight_to_real_usage = MagicMock(+ return_value=False+ )+ agent.context_compressor.get_active_compression_failure_cooldown = MagicMock(+ return_value=None+ )++ compression_calls = []++ def _timed_out(messages, _system_message, **_kwargs):+ compression_calls.append(1)+ from agent.conversation_compression import (+ mark_context_compression_timed_out,+ reset_context_compression_timeout_outcome,+ )++ reset_context_compression_timeout_outcome(agent)+ mark_context_compression_timed_out(agent)+ return messages, agent._cached_system_prompt++ agent._compress_context = _timed_out++ from agent.turn_context import PreflightCompressionTimedOut++ history = [+ {"role": "user", "content": "old request"},+ {"role": "assistant", "content": "old response"},+ ]+ with (+ patch.object(agent, "_persist_session"),+ patch.object(agent, "_save_trajectory"),+ patch.object(agent, "_cleanup_task_resources"),+ ):+ # The turn-start boundary (#98424) may fire first and raise; both+ # outcomes satisfy the invariant under test: the unchanged oversized+ # request never reaches the provider after a host timeout.+ try:+ result = agent.run_conversation(+ "continue", conversation_history=history+ )+ except PreflightCompressionTimedOut:+ result = None++ assert compression_calls == [1]+ agent.client.chat.completions.create.assert_not_called()+ if result is not None:+ assert result["failed"] is True+ assert result["compression_exhausted"] is True+ assert result["turn_exit_reason"] == "context_compression_timeout"