The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): adopt live compression continuation for /v1/runs delivery
liuhao10240efb52542066
diff --git a/gateway/platforms/api_server_runs.py b/gateway/platforms/api_server_runs.pyindex 86918e0bcef..d2dab4fef35 100644--- a/gateway/platforms/api_server_runs.py+++ b/gateway/platforms/api_server_runs.py@@ -354,6 +354,23 @@ def _drop_run_transport(self, run_id: str) -> None:_forget_run(self, run_id, self._run_streams, self._run_streams_created)+async def _resolve_live_session_id(self, session_id: str) -> str:+ """Adopt the live compression-continuation tip for a client-addressed session (#98619):+ a /v1/runs run bound to a pre-rotation id would otherwise load a stale history slice and+ write its turn into the closed parent (CompressionSessionClosedError). Same canonical+ resolution ``/api/sessions/{id}/messages`` reads use; fails open to the original id."""+ db = await self._ensure_session_db_async()+ resolver = getattr(db, "resolve_resume_session_id", None) if db is not None else None+ if not callable(resolver):+ return session_id+ try:+ resolved = await asyncio.to_thread(resolver, session_id)+ return str(resolved) if resolved else session_id+ except Exception:+ logger.debug("/v1/runs live-session resolve failed for %s", session_id, exc_info=True)+ return session_id++async def _handle_runs(self, request: "web.Request", *, _api_server) -> "web.Response":"""POST /v1/runs — start an agent run, return run_id immediately."""_openai_error = _api_server._openai_error@@ -427,6 +444,11 @@ async def _handle_runs(self, request: "web.Request", *, _api_server) -> "web.Res_declared_selected = not session_id and bool(gateway_session_key)selected_session_id = session_id or (self._declared_conversation_session(gateway_session_key) if _declared_selected else None)+ # A client-addressed id from before a compression rotation must adopt the live tip (#98619):+ # history loads from it, the turn writes to it, and a detached delivery row persisted to it+ # is what the next same-id run consumes below.+ if selected_session_id:+ selected_session_id = await _resolve_live_session_id(self, str(selected_session_id))session_id = selected_session_id or run_id# History loads for the session the request actually selected — including one resolved from# a declared X-Hermes-Session-Key, whose persisted delivery rows must reach the nextdiff --git a/gateway/wake.py b/gateway/wake.pyindex 4b70daf5a76..e60bea22c59 100644--- a/gateway/wake.py+++ b/gateway/wake.py@@ -108,6 +108,20 @@ async def persist_delegation_delivery(adapter: Any, *, text: str, session_id: stif db is None:raise RuntimeError("persist_delegation_delivery: api_server SessionDB unavailable — "f"cannot persist completion for session {session_id}")+ # #98619: the parent run may have compressed/rotated between dispatch and this detached+ # completion — the captured origin id is then a closed parent and the append below is+ # rejected with CompressionSessionClosedError forever (the watcher retries the same stale+ # id). Adopt the live continuation tip first, the same canonical resolution+ # /api/sessions/{id}/messages reads use, so the delivery row lands where the next run and+ # the messages endpoint both resolve. Fails open to the original id.+ resolver = getattr(db, "resolve_resume_session_id", None)+ if callable(resolver):+ try:+ resolved = await asyncio.to_thread(resolver, session_id)+ if resolved:+ session_id = str(resolved)+ except Exception:+ logger.debug("delegation delivery continuation resolve failed for %s", session_id, exc_info=True)await asyncio.to_thread(db.append_message, session_id, "user", content=text,display_kind="async_delegation_complete", display_metadata=_delegation_display_metadata(evt or {}),diff --git a/tests/gateway/test_api_server_runs.py b/tests/gateway/test_api_server_runs.pyindex eb5a057b173..393cfb0db9f 100644--- a/tests/gateway/test_api_server_runs.py+++ b/tests/gateway/test_api_server_runs.py@@ -1481,6 +1481,7 @@ class TestRunIdempotency:mock_db.find_latest_gateway_session_for_peer.return_value = {"id": "declared-session"}+ mock_db.resolve_resume_session_id.side_effect = lambda sid: sidmock_db.get_messages_as_conversation.return_value = deliveredadapter._session_db = mock_dbapp = _create_runs_app(adapter)@@ -1599,6 +1600,7 @@ class TestRunIdempotency:(explicit body session_id, loaded from SessionDB) stays wake-capable."""_use_idempotency_db(adapter, tmp_path / "idem.db")mock_db = MagicMock()+ mock_db.resolve_resume_session_id.side_effect = lambda sid: sidmock_db.get_messages_as_conversation.return_value = []adapter._session_db = mock_dbbind = MagicMock(return_value=[])@@ -1625,6 +1627,66 @@ class TestRunIdempotency:await asyncio.sleep(0.05)assert bind.call_args.kwargs["wake_capable"] == "1"+ @pytest.mark.asyncio+ async def test_compressed_parent_delivery_row_lands_on_live_tip(+ self, adapter, tmp_path+ ):+ """#98619 e2e: the parent run compresses before the detached delegate+ completes — the persisted delivery row must land on the live+ continuation tip (not be rejected on the closed parent forever), and the+ next run addressing the original id must load it and bind the tip."""+ from hermes_state import SessionDB+ from gateway.wake import persist_delegation_delivery++ _use_idempotency_db(adapter, tmp_path / "idem.db")+ db = SessionDB(db_path=tmp_path / "state.db")+ # Rotation: parent closed by compression, live continuation child holds the messages.+ db.create_session("parent-session", source="api_server")+ db.append_message("parent-session", "user", "run the batch")+ db.end_session("parent-session", "compression")+ db.create_session(+ "child-session", source="api_server", parent_session_id="parent-session"+ )+ adapter._session_db = db+ bind = MagicMock(return_value=[])+ app = _create_runs_app(adapter)+ async with TestClient(TestServer(app)) as cli:+ # The detached completion arrives after the rotation, addressed to the+ # captured (now-stale) origin id — exactly what the watcher persists.+ await persist_delegation_delivery(+ adapter,+ text="[delegated task complete] rotated result",+ session_id="parent-session",+ evt={"type": "async_delegation"},+ )+ with (+ patch.object(adapter, "_bind_api_server_session", new=bind),+ patch.object(adapter, "_create_agent") as create,+ ):+ agent = MagicMock()+ agent.run_conversation.return_value = {"final_response": "done"}+ agent.session_prompt_tokens = agent.session_completion_tokens = (+ agent.session_total_tokens+ ) = 0+ create.return_value = agent+ response = await cli.post(+ "/v1/runs",+ json={"input": "follow up", "session_id": "parent-session"},+ )+ assert response.status == 202+ for _ in range(40):+ if agent.run_conversation.called:+ break+ await asyncio.sleep(0.05)+ # The run adopted the live tip: the delivery row (persisted to the tip)+ # loaded as the run's history, and the turn/wake binding targeted the tip.+ history = agent.run_conversation.call_args.kwargs["conversation_history"]+ assert any("rotated result" in m.get("content", "") for m in history)+ assert bind.call_args.kwargs["session_id"] == "child-session"+ # The delivery row itself landed on the live tip, never on the closed parent.+ child_rows = db.get_messages_as_conversation("child-session")+ assert any("rotated result" in m.get("content", "") for m in child_rows)+class TestHostedRoomRuns:@pytest.mark.asyncio