The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): preserve rate-limit failure metadata
atakan g5423e26a7de5
diff --git a/gateway/run.py b/gateway/run.pyindex 9ac80d72305..bad550857e5 100644--- a/gateway/run.py+++ b/gateway/run.py@@ -23000,6 +23000,10 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatew"last_reasoning": result.get("last_reasoning"),"messages": result_holder[0].get("messages", []) if result_holder[0] else [],"api_calls": result_holder[0].get("api_calls", 0) if result_holder[0] else 0,+ "failed": result_holder[0].get("failed", False) if result_holder[0] else False,+ "failure_reason": (+ result_holder[0].get("failure_reason") if result_holder[0] else None+ ),"completed": result_holder[0].get("completed") if result_holder[0] else None,"interrupted": result_holder[0].get("interrupted", False) if result_holder[0] else False,"partial": result_holder[0].get("partial", False) if result_holder[0] else False,diff --git a/tests/gateway/test_42039_duplicate_user_message.py b/tests/gateway/test_42039_duplicate_user_message.pyindex 129b1ce9266..f365a688fbb 100644--- a/tests/gateway/test_42039_duplicate_user_message.py+++ b/tests/gateway/test_42039_duplicate_user_message.py@@ -290,3 +290,43 @@ async def test_normal_path_skip_db_when_agent_has_session_db(_assert_user_call_has_skip_db(runner.session_store.append_to_transcript.call_args_list, True)+++async def test_nonempty_rate_limit_error_is_not_persisted_as_assistant_message(+ monkeypatch, tmp_path+):+ runner = _bootstrap(monkeypatch, tmp_path)++ error_response = "API call failed after 3 retries: 429 Too Many Requests"+ runner._run_agent = AsyncMock(+ return_value={+ "failed": True,+ "failure_reason": "rate_limit",+ "completed": False,+ "final_response": error_response,+ "error": "429 Too Many Requests",+ "messages": [+ {"role": "user", "content": "hello world"},+ ],+ "history_offset": 0,+ "last_prompt_tokens": 0,+ }+ )++ await runner._handle_message_with_agent(+ _event(), _source(), "agent:main:telegram:group:-1001:12345", 1+ )++ persisted_entries = [+ call.args[1]+ for call in runner.session_store.append_to_transcript.call_args_list+ if len(call.args) >= 2 and isinstance(call.args[1], dict)+ ]++ assert any(entry.get("role") == "user" for entry in persisted_entries)+ assert not any(+ entry.get("role") == "assistant"+ and error_response in str(entry.get("content", ""))+ for entry in persisted_entries+ )diff --git a/tests/gateway/test_compression_failure_session_sync.py b/tests/gateway/test_compression_failure_session_sync.pyindex 0cfd4f076f1..022a490f2ea 100644--- a/tests/gateway/test_compression_failure_session_sync.py+++ b/tests/gateway/test_compression_failure_session_sync.py@@ -44,7 +44,9 @@ class _CompressionThenFailureAgent:self.session_prompt_tokens = 4321self.session_completion_tokens = 0- def run_conversation(self, user_message, conversation_history=None, task_id=None, **_kwargs):+ def run_conversation(+ self, user_message, conversation_history=None, task_id=None, **_kwargs+ ):self.session_id = "session-after-compression"return {"failed": True,@@ -125,9 +127,9 @@ def _runner(session_store):return runner-def _install_compression_failure_agent(monkeypatch):+def _install_compression_failure_agent(monkeypatch, agent_cls=_CompressionThenFailureAgent):fake_run_agent = types.ModuleType("run_agent")- fake_run_agent.AIAgent = _CompressionThenFailureAgent+ fake_run_agent.AIAgent = agent_clsmonkeypatch.setitem(sys.modules, "run_agent", fake_run_agent)monkeypatch.setenv("HERMES_TOOL_PROGRESS_MODE", "off")monkeypatch.setenv("HERMES_AGENT_TIMEOUT", "0")@@ -229,3 +231,180 @@ def test_session_split_sync_skips_when_binding_already_moved(monkeypatch):assert session_store.save_calls == 0assert session_store.peer_records == []assert getattr(runner._sync_telegram_topic_binding, "call_count") == 0+++class _RateLimitFailureAgent(_CompressionThenFailureAgent):+ def run_conversation(self, user_message, conversation_history=None, task_id=None, **_kwargs):+ return {+ "final_response": "API call failed after 3 retries: 429 Too Many Requests",+ "failed": True,+ "completed": False,+ "error": "429 Too Many Requests",+ "failure_reason": "rate_limit",+ "messages": [+ *(conversation_history or []),+ {"role": "user", "content": user_message},+ ],+ "api_calls": 3,+ }+++def test_nonempty_rate_limit_response_preserves_failure_metadata(monkeypatch):+ _install_compression_failure_agent(monkeypatch, _RateLimitFailureAgent)++ session_store = _SessionStore()+ runner = _runner(session_store)+ source = SessionSource(+ platform=Platform.TELEGRAM,+ chat_id="12345",+ chat_type="dm",+ user_id="user-1",+ )++ result = _run_compression_failure_turn(runner, source)++ assert result["final_response"].startswith("API call failed after 3 retries")+ assert result["failed"] is True+ assert result["failure_reason"] == "rate_limit"+ assert result["completed"] is False++class _ProviderSwitchAgent(_CompressionThenFailureAgent):+ created_providers = []+ second_turn_history = None++ def __init__(self, **kwargs):+ super().__init__(**kwargs)+ self.provider = kwargs.get("provider")+ self.base_url = kwargs.get("base_url")+ self.api_key = kwargs.get("api_key")+ self.api_mode = kwargs.get("api_mode")+ type(self).created_providers.append(self.provider)++ def run_conversation(+ self, user_message, conversation_history=None, task_id=None, **_kwargs+ ):+ history = list(conversation_history or [])++ if self.provider == "provider-a":+ return {+ "final_response": (+ "API call failed after 3 retries: 429 Too Many Requests"+ ),+ "failed": True,+ "completed": False,+ "error": "429 Too Many Requests",+ "failure_reason": "rate_limit",+ "messages": [+ *history,+ {"role": "user", "content": user_message},+ ],+ "api_calls": 3,+ }++ type(self).second_turn_history = history+ response = "Provider B completed the next turn"+ return {+ "final_response": response,+ "failed": False,+ "completed": True,+ "messages": [+ *history,+ {"role": "user", "content": user_message},+ {"role": "assistant", "content": response},+ ],+ "api_calls": 1,+ }+++def test_rate_limit_then_provider_switch_continues_without_replaying_error(+ monkeypatch+):+ _ProviderSwitchAgent.created_providers = []+ _ProviderSwitchAgent.second_turn_history = None+ _install_compression_failure_agent(monkeypatch, _ProviderSwitchAgent)++ monkeypatch.setattr(+ gateway_run,+ "_resolve_gateway_model",+ lambda _config=None: "model-a",+ )+ monkeypatch.setattr(+ gateway_run,+ "_resolve_runtime_agent_kwargs",+ lambda: {+ "provider": "provider-a",+ "model": "model-a",+ "api_key": "key-a",+ "base_url": "https://provider-a.example/v1",+ "api_mode": "chat_completions",+ },+ )++ session_store = _SessionStore()+ runner = _runner(session_store)+ runner._resolve_session_agent_runtime = (+ gateway_run.GatewayRunner._resolve_session_agent_runtime.__get__(+ runner, gateway_run.GatewayRunner+ )+ )+ runner._agent_config_signature = (+ gateway_run.GatewayRunner._agent_config_signature+ )++ source = SessionSource(+ platform=Platform.TELEGRAM,+ chat_id="12345",+ chat_type="dm",+ user_id="user-1",+ )+ initial_history = [+ {"role": "user", "content": "Earlier question"},+ {"role": "assistant", "content": "Earlier answer"},+ ]++ first_result = asyncio.run(+ runner._run_agent(+ message="First request",+ context_prompt="",+ history=initial_history,+ source=source,+ session_id="session-before-compression",+ session_key=SESSION_KEY,+ )+ )++ assert first_result["failed"] is True+ assert first_result["failure_reason"] == "rate_limit"++ runner._session_model_overrides[SESSION_KEY] = {+ "model": "model-b",+ "provider": "provider-b",+ "api_key": "key-b",+ "base_url": "https://provider-b.example/v1",+ "api_mode": "chat_completions",+ }++ second_result = asyncio.run(+ runner._run_agent(+ message="Second request",+ context_prompt="",+ history=first_result["messages"],+ source=source,+ session_id="session-before-compression",+ session_key=SESSION_KEY,+ )+ )++ assert _ProviderSwitchAgent.created_providers == [+ "provider-a",+ "provider-b",+ ]+ assert second_result["failed"] is False+ assert second_result["completed"] is True+ assert second_result["final_response"] == (+ "Provider B completed the next turn"+ )+ assert not any(+ "429 Too Many Requests" in str(message.get("content", ""))+ for message in (_ProviderSwitchAgent.second_turn_history or [])+ )