The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(agent): surface preflight compression timeout as typed result, not generic error
kshitijk4poor1e8f6a04913a
diff --git a/agent/conversation_loop.py b/agent/conversation_loop.pyindex 5d2ac2688ec..cd196415424 100644--- a/agent/conversation_loop.py+++ b/agent/conversation_loop.py@@ -43,6 +43,7 @@ from agent.display import KawaiiSpinnerfrom agent.error_classifier import FailoverReason, classify_api_errorfrom agent.message_metadata import append_messagefrom agent.turn_context import (+ PreflightCompressionTimedOut,_compression_warrants_another_preflight_pass,_review_fork_first_request_pending,build_turn_context,@@ -1989,29 +1990,68 @@ def run_conversation(# ``build_turn_context``. It mutates ``agent`` exactly as the inline code# did and returns the locals the loop below reads back. See# ``agent/turn_context.py``.- _ctx = build_turn_context(- agent,- user_message,- system_message,- conversation_history,- task_id,- stream_callback,- persist_user_message,- persist_user_timestamp,- persist_user_display_kind=persist_user_display_kind,- persist_user_display_metadata=persist_user_display_metadata,- persist_user_platform_id=persist_user_platform_id,- restore_or_build_system_prompt=_restore_or_build_system_prompt,- install_safe_stdio=_install_safe_stdio,- sanitize_surrogates=_sanitize_surrogates,- summarize_user_message_for_log=_summarize_user_message_for_log,- set_session_context=set_session_context,- set_current_write_origin=set_current_write_origin,- ra=_ra,- # MoA turns append per-call aggregated context to the API copy of the- # user message, so no byte-stable api_content sidecar can be stamped.- moa_active=bool(moa_config),- )+ try:+ _ctx = build_turn_context(+ agent,+ user_message,+ system_message,+ conversation_history,+ task_id,+ stream_callback,+ persist_user_message,+ persist_user_timestamp,+ persist_user_display_kind=persist_user_display_kind,+ persist_user_display_metadata=persist_user_display_metadata,+ persist_user_platform_id=persist_user_platform_id,+ restore_or_build_system_prompt=_restore_or_build_system_prompt,+ install_safe_stdio=_install_safe_stdio,+ sanitize_surrogates=_sanitize_surrogates,+ summarize_user_message_for_log=_summarize_user_message_for_log,+ set_session_context=set_session_context,+ set_current_write_origin=set_current_write_origin,+ ra=_ra,+ # MoA turns append per-call aggregated context to the API copy of the+ # user message, so no byte-stable api_content sidecar can be stamped.+ moa_active=bool(moa_config),+ )+ except PreflightCompressionTimedOut as _preflight_timeout_exc:+ # Turn-start fail-closed boundary (#98424): preflight compression hit+ # the host's progress-aware timeout while the request was still+ # oversized, so no provider call was sent. Convert the typed exception+ # into the same typed recovery result the in-loop consumers return+ # (salvaged #98741 / PR #99710) instead of letting it escape to the+ # surfaces' generic exception handlers — the gateway deliberately+ # hides raw exception text from users, which would bury the+ # actionable "run /compress and retry" guidance and skip the+ # compression_exhausted clean-session recovery contract.+ logger.warning(+ "Turn-start preflight compression timed out — ending turn with "+ "typed recovery result: %s",+ _preflight_timeout_exc,+ )+ # build_turn_context registered this turn's in-flight tripwire slot+ # (note_turn_start) but the early return skips the persist funnel+ # that normally clears it — clear it here so the next turn does not+ # log a spurious "concurrent turns on one session" warning. The+ # inbound user row is intentionally NOT persisted on this path: the+ # gateway skips transcript persistence for compression_exhausted+ # results to prevent the session-growth loop (#7100), and the+ # auto-reset moves future input to a clean session.+ from agent.agent_runtime_helpers import note_turn_persisted++ note_turn_persisted(agent)+ _final_response = str(_preflight_timeout_exc)+ return {+ "final_response": _final_response,+ "messages": list(conversation_history or []),+ "completed": False,+ "api_calls": 0,+ "error": _final_response,+ "partial": True,+ "failed": True,+ "compression_exhausted": True,+ "turn_exit_reason": "context_compression_timeout",+ }user_message = _ctx.user_messageoriginal_user_message = _ctx.original_user_messagemessages = _ctx.messagesdiff --git a/tests/run_agent/test_preflight_timeout_typed_result.py b/tests/run_agent/test_preflight_timeout_typed_result.pynew file mode 100644index 00000000000..a9a06476cb2--- /dev/null+++ b/tests/run_agent/test_preflight_timeout_typed_result.py@@ -0,0 +1,82 @@+"""The turn-start preflight timeout surfaces as a typed result, not a traceback.++Companion to the #98424 fail-closed boundary and the #98741/#99710 typed+timeout chain: when ``build_turn_context`` raises+``PreflightCompressionTimedOut``, ``run_conversation`` must convert it into+the same typed recovery dict the in-loop timeout consumers return —+``failed=True`` + ``compression_exhausted=True`` + the actionable message —+because the gateway's generic exception handler deliberately hides raw+exception text from users (it would deliver "Sorry, I encountered an+unexpected error" and skip the clean-session recovery contract).+"""++from __future__ import annotations++from unittest.mock import MagicMock, patch+++def test_turn_start_preflight_timeout_returns_typed_result_not_exception():+ from run_agent import AIAgent++ 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+ 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_defer_preflight_to_real_usage = MagicMock(+ return_value=False+ )+ agent.context_compressor.get_active_compression_failure_cooldown = MagicMock(+ return_value=None+ )++ def _timed_out(messages, _system_message, **_kwargs):+ 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"),+ ):+ # Must NOT raise PreflightCompressionTimedOut out of run_conversation.+ result = agent.run_conversation("continue", conversation_history=history)++ agent.client.chat.completions.create.assert_not_called()+ assert result["failed"] is True+ assert result["completed"] is False+ assert result["compression_exhausted"] is True+ assert result["turn_exit_reason"] == "context_compression_timeout"+ # The actionable preflight guidance survives into both user-facing fields.+ assert "provider call was not sent" in result["final_response"]+ assert "provider call was not sent" in result["error"]