The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(api): keep an API session's id after compression exhaustion
David Dudok de Witfdc3d4517bdd
diff --git a/agent/session_persistence.py b/agent/session_persistence.pyindex 14b70932b43..9fc8a0207c3 100644--- a/agent/session_persistence.py+++ b/agent/session_persistence.py@@ -157,11 +157,13 @@ def adopt_unanswered_turn(history: list[dict[str, Any]], query: Any, agent: Any)A dispatcher's re-run of a failed delivery turn resumes the DM its first attempt already persistedinstead of appending it again. Rows loaded from the store are born durable (``_rows_to_conversation``),so handing the tail row back as ``agent._pending_cli_user_message`` makes ``_stage_turn_user_message``- reuse it as this turn's user dict and the flush writes no second row. The one caller is- ``gateway.platforms.api_server`` (``resume_unanswered_turn``): the peer-DM lane re-runs the turn- in-process and calls this on the agent it just built for the re-run (#115325). The owner-side Bot- Chat retry (``gateway.session_bot._maybe_retry``) does not adopt: its failed turn is already closed- by the durable failed-turn boundary, which this function declines by design.+ reuse it as this turn's user dict and the flush writes no second row. The one user is the peer-DM+ lane's re-run (``resume_unanswered_turn`` in ``gateway.platforms.api_server``, #115325): in process it+ calls this on the agent it just built for the re-run; under the session authority the admission+ carries ``resume_unanswered`` and ``gateway.run_turn_runner`` calls it on the admitted history+ when its tail is that bare user row (a tool suffix there keeps the completed work in view).+ The owner-side Bot Chat retry (``gateway.session_bot._maybe_retry``) does not adopt: its failed+ turn is already closed by the durable failed-turn boundary, which this function declines by design.The DM is not always the literal tail: a turn that died mid-way persisted its tool scaffolding — assistant``tool_calls`` rows and their ``tool`` results — behind the DM before the failure text was built, and thediff --git a/gateway/run_turn_persistence.py b/gateway/run_turn_persistence.pyindex 3aa7d3fbaff..5d0fe75165f 100644--- a/gateway/run_turn_persistence.py+++ b/gateway/run_turn_persistence.py@@ -337,6 +337,12 @@ class GatewayTurnPersistenceMixin:"session intact; the next message retries normally.",session_entry.session_id if session_entry else "?",)+ elif agent_result.get("compression_exhausted") and getattr(source, "platform", None) == Platform.API_SERVER:+ # The caller addresses an API conversation by its id and every API door re-validates that+ # binding (``restore_api_session``): a rotated entry would refuse each later request to it+ # (``admission_conflict``). The caller gets the typed ``compression_exhausted`` result instead.+ logger.info("Keeping API session %s after compression exhaustion.",+ session_entry.session_id if session_entry else "?")elif agent_result.get("compression_exhausted") and session_entry and session_key:logger.info("Auto-resetting session %s after compression exhaustion.", session_entry.session_id)from gateway.session_automation import move_route_wakes, reset_and_rehome_messagesdiff --git a/gateway/run_turn_runner.py b/gateway/run_turn_runner.pyindex ffd0f69d90e..e2f2100db81 100644--- a/gateway/run_turn_runner.py+++ b/gateway/run_turn_runner.py@@ -781,6 +781,13 @@ class TurnRunner(GatewayTurnProgressMixin, GatewaySessionAgentMixin):if api is not None and api['history'] is not None:from gateway.run import _collect_history_media_pathshistory = api['history']+ tail = history[-1] if history else None+ if api.get('resume_unanswered') and isinstance(tail, dict) and tail.get('role') == 'user':+ # The door's re-run continues the row its failed attempt persisted (#115325). Only a+ # bare user tail: a tool suffix is completed work the re-run must still see.+ from agent.session_persistence import adopt_unanswered_turn+ history = list(history)+ adopt_unanswered_turn(history, api['content'], agent)return history, None, _collect_history_media_paths(history)# Transcript rows ({role, content, timestamp}) lose timestamps; interrupt-path agent messages# (tool_calls/tool_call_id/reasoning) pass through intact so the API sees valid assistant→tooldiff --git a/gateway/session_api_turn.py b/gateway/session_api_turn.pyindex 3ac39727032..8e0fa76e0bf 100644--- a/gateway/session_api_turn.py+++ b/gateway/session_api_turn.py@@ -55,7 +55,8 @@ def check_api_turn(authority, ref, payload):if 'api_turn_v1' in payload:data = payload['api_turn_v1']if (set(data) - {'history', 'settings', 'turn_author', 'media', 'run_owner_scope', 'browser_control',- 'relay_metadata'}+ 'relay_metadata', 'resume_unanswered'}+ or data.get('resume_unanswered', True) is not Trueor not {'history', 'settings'} <= set(data)or not isinstance(data.get('relay_metadata', {}), dict)or (data['history'] is not None and not isinstance(data['history'], list))@@ -223,6 +224,10 @@ def admit_api_steps(adapter, **kwargs):if author is None:raise RuntimeStoreError('invalid_params')payload['api_turn_v1']['turn_author'] = author+ if kwargs.get('resume_unanswered_turn'):+ # The session-chat door's one policy-gated re-run (#115325): its failed attempt left this text as+ # the transcript's unanswered tail, which the turn adopts instead of appending it again.+ payload['api_turn_v1']['resume_unanswered'] = Trueif kwargs.get('relay_metadata'):# The request's Relay metadata rides the admission to the turn it describes (main passed it# to ``run_conversation``); it is client JSON, so it is part of the exact-retry identity.@@ -481,6 +486,7 @@ def prepare_api_execution(authority, ref, payload):return {'adapter': adapter, 'settings': settings, 'history': data['history'] if data else None,'content': content, 'turn_author': data.get('turn_author') if data else None,'relay_metadata': data.get('relay_metadata') if data else None,+ 'resume_unanswered': bool(data and data.get('resume_unanswered')),'browser_control': _rebind_browser_control(adapter, data)}diff --git a/tests/gateway/test_api_session_compression_exhaustion.py b/tests/gateway/test_api_session_compression_exhaustion.pynew file mode 100644index 00000000000..6293afa2891--- /dev/null+++ b/tests/gateway/test_api_session_compression_exhaustion.py@@ -0,0 +1,102 @@+"""An API conversation whose turn exhausts compression stays addressable, and the session-chat+door's re-run continues the failed attempt's row (#115325) on the admitted path too, never past+completed tool work."""+from types import SimpleNamespace++import pytest++from gateway.session_api_turn import admit_api_turn++DM = "disk status?"+++async def test_api_session_keeps_its_id_after_compression_exhaustion(monkeypatch):+ """The messaging auto-reset rotated the API route to a fresh id, so every later request to the+ id the caller addresses was refused (``admission_conflict``; the session-chat door's 500)."""+ from gateway.config import GatewayConfig, Platform, PlatformConfig+ from gateway.platforms.api_server import APIServerAdapter+ from gateway.run import GatewayRunner+ from gateway.session_authority import SessionAuthority, initialize_session_authority++ monkeypatch.setattr(SessionAuthority, "_schedule", lambda self, ref: None)+ runner = GatewayRunner(GatewayConfig())+ adapter = APIServerAdapter(PlatformConfig(enabled=True))+ adapter.gateway_runner = runner+ runner.adapters = {Platform.API_SERVER: adapter}+ authority = await initialize_session_authority(runner, profile_id="default", instance_id="fixture")+ adapter._session_db = authority.db+ try:+ admit_api_turn(adapter, session_id="dm1", user_message=DM, conversation_history=[])+ source = authority.sessions["dm1"].source+ route = runner.session_store._generate_session_key(source)+ exhausted = {"failed": True, "compression_exhausted": True, "failure_reason": "context_overflow",+ "messages": []}+ response, entry = await runner._hmwa_compression_exhaustion_reset(+ exhausted, "copy", runner.session_store.lookup_by_session_key(route), route, source)+ admit_api_turn(adapter, session_id="dm1", user_message="next", conversation_history=[])+ assert (response, entry.session_id) == ("copy", "dm1")+ finally:+ adapter._response_store.close()+ adapter._run_idempotency_store.close()+ authority.db.close()+++def test_session_chat_rerun_continues_the_failed_attempts_row(api, owner):+ """The re-run's history ends with the DM its failed attempt persisted: the turn adopts that row+ instead of sending (and storing) a second copy. A fresh admission never adopts."""+ from gateway.run_turn_runner import TurnRunner+ from gateway.session_api_turn import api_execution, prepare_api_execution+ from gateway.turn_context import TurnContext++ history = [{"role": "user", "content": "earlier"}, {"role": "assistant", "content": "ok"},+ {"role": "user", "content": DM}]+ loaded = {}+ for rerun in (True, False):+ _, ref, row = admit_api_turn(api, session_id=f"dm-{rerun}", user_message=DM,+ conversation_history=history, resume_unanswered_turn=rerun)+ agent = SimpleNamespace()+ turn = TurnRunner(SimpleNamespace(session_authority=None),+ TurnContext(message=DM, session_id=ref.session_id, session_key="api"))+ token = api_execution.set(prepare_api_execution(owner, ref, row["payload"]))+ try:+ rows, _, _ = turn._load_turn_history(agent, False)+ finally:+ api_execution.reset(token)+ loaded[rerun] = [r["content"] for r in rows], getattr(agent, "_pending_cli_user_message", None)+ rows, adopted = loaded[True]+ assert rows == ["earlier", "ok"] and adopted["content"] == DM+ assert loaded[False] == (["earlier", "ok", DM], None)+++def test_admitted_retry_preserves_completed_tool_evidence(api, owner):+ """A 429/5xx re-run after a tool completed keeps ``user → assistant(tool_calls) → tool`` in view+ (as on main), so it can't repeat the side effect or answer without its result."""+ from gateway.run_turn_runner import TurnRunner+ from gateway.session_api_turn import api_execution, prepare_api_execution+ from gateway.turn_context import TurnContext+ from tools.bot_failure_reasons import RETRY_RESUME, result_retry_action++ sid = "retry-completed-tool"+ message = "Create exactly one draft and return its ID."+ owner.db.create_session(sid, "api_server")+ owner.db.append_message(sid, "user", content=message)+ owner.db.append_message(sid, "assistant", content=None, tool_calls=[+ {"id": "call_1", "type": "function", "function": {"name": "create_draft", "arguments": "{}"}}])+ owner.db.append_message(sid, "tool", content="Created draft 73.", tool_call_id="call_1")+ # Realistic state after the next provider request exhausts its retries.+ assert owner.db.latest_conversation_role(sid) == "tool"+ assert result_retry_action({"failed": True, "failure_reason": "rate_limit",+ "error": "429 Too Many Requests"}) == RETRY_RESUME++ _, ref, row = admit_api_turn(api, session_id=sid, user_message=message,+ conversation_history=owner.db.get_messages_as_conversation(sid),+ resume_unanswered_turn=True)+ turn = TurnRunner(SimpleNamespace(session_authority=None),+ TurnContext(message=message, session_id=sid, session_key="api"))+ token = api_execution.set(prepare_api_execution(owner, ref, row["payload"]))+ try:+ history, _, _ = turn._load_turn_history(SimpleNamespace(), False)+ finally:+ api_execution.reset(token)+ assert any(m.get("role") == "tool" and m.get("content") == "Created draft 73." for m in history)