The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): resolve session_key in shutdown-flush recovery
spfcraze9dbe5d7af7a1
diff --git a/gateway/run.py b/gateway/run.pyindex 0eac13a0e5f..5890b002173 100644--- a/gateway/run.py+++ b/gateway/run.py@@ -5397,7 +5397,9 @@ async def start_gateway(config: Optional[GatewayConfig] = None, replace: bool =def _recover_pending() -> None:from gateway.shutdown_flush import recover_pending_to_db- recovered = recover_pending_to_db()+ recovered = recover_pending_to_db(+ session_resolver=runner.session_store.peek_session_id,+ )if recovered:logger.info("Recovered %d pending message(s) from shutdown flush", recovered)diff --git a/gateway/shutdown_flush.py b/gateway/shutdown_flush.pyindex b0af857d891..e13dc72d291 100644--- a/gateway/shutdown_flush.py+++ b/gateway/shutdown_flush.py@@ -200,10 +200,13 @@ def _serialise_value(value: Any) -> Optional[dict]:return {"text": str(value)}-def recover_pending_to_db(session_db=None) -> int:+def recover_pending_to_db(session_db=None, *, session_resolver=None) -> int:"""Replay flush-dir ``*.json`` files via ``SessionDB.append_message``, deleting each on success.``session_db=None`` opens (and afterwards releases) the shared default ``state.db``.+ ``session_resolver`` (optional ``session_key -> session_id``, e.g.+ ``SessionStore.peek_session_id``) is required for real flush files: adapter ``MessageEvent``+ objects carry no ``session_id``, so without it every recovery lands in the skip branch.Returns the number of messages recovered."""flush_files = sorted(_get_flush_dir().glob("*.json"))@@ -220,7 +223,7 @@ def recover_pending_to_db(session_db=None) -> int:# Agent-history snapshots are for manual operator recovery, not automatic DB insertion.if payload.get("reason") == "shutdown-with-unpersisted-agent-history":continue- if _recover_one_payload(session_db, path, payload):+ if _recover_one_payload(session_db, path, payload, session_resolver=session_resolver):recovered += 1path.unlink(missing_ok=True)finally:@@ -233,7 +236,8 @@ def recover_pending_to_db(session_db=None) -> int:return recovered-def _recover_one_payload(session_db, path: Path, payload: Dict[str, Any]) -> bool:+def _recover_one_payload(session_db, path: Path, payload: Dict[str, Any], *,+ session_resolver=None) -> bool:"""Append one flush payload to ``session_db``; False (file kept) when structurally invalid."""# Cap-dropped transcript payloads carry the full message dict keyed by session_id — replay directly# (#78182). This handles spool files that were never drained before a restart.@@ -256,11 +260,16 @@ def _recover_one_payload(session_db, path: Path, payload: Dict[str, Any]) -> boo"the flush file has been preserved", path)return False# session_key is a gateway routing key (e.g. "agent:main:telegram:..."); appending a row- # needs the real session_id, which only the serialised data can supply at this stage.+ # needs the real session_id, which real payloads lack — the resolver supplies it.session_id = data.get("session_id", "")+ if not session_id and session_resolver is not None:+ try:+ session_id = session_resolver(session_key) or ""+ except Exception:+ session_id = ""if not session_id:logger.warning("Cannot recover pending message for %s: no session_id in flush file and "- "session_key-to-id resolution is not available at this recovery stage. "+ "session_key-to-id resolution failed. ""The message text is preserved in %s", session_key, path)return Falsesession_db.append_message(session_id=session_id, role="user", content=text,diff --git a/tests/gateway/test_shutdown_flush.py b/tests/gateway/test_shutdown_flush.pyindex 2f79303b57b..e96f2dc51ec 100644--- a/tests/gateway/test_shutdown_flush.py+++ b/tests/gateway/test_shutdown_flush.py@@ -238,3 +238,36 @@ def test_flushed_overflow_is_replayed_by_recover_pending_to_db(tmp_path, monkeypdef test_flush_overflow_noop_on_empty():assert flush_overflow_to_file({}) == 0assert flush_overflow_to_file({"k": []}) == 0+++def test_recover_resolves_session_key_via_resolver(tmp_path, monkeypatch):+ """Real flush files carry only `text` (MessageEvent has no session_id+ attribute). Without a resolver they were skipped forever; with one,+ the message must be recovered and the file cleaned up."""+ flush_dir = _make_flush_dir(tmp_path)+ monkeypatch.setattr(+ "gateway.shutdown_flush._get_flush_dir", lambda: flush_dir+ )+ ts = int(time.time())+ payload = {+ "session_key": "agent:main:telegram:dm:42",+ "ts": ts,+ "data": {"text": "are you there?"}, # what _serialise_value actually produces+ }+ flush_file = flush_dir / "pending-test.json"+ flush_file.write_text(json.dumps(payload), encoding="utf-8")++ mock_db = MagicMock()+ count = recover_pending_to_db(+ mock_db,+ session_resolver=lambda key: "20260731_abc123" if key == "agent:main:telegram:dm:42" else None,+ )++ assert count == 1+ mock_db.append_message.assert_called_once_with(+ session_id="20260731_abc123",+ role="user",+ content="are you there?",+ timestamp=ts,+ )+ assert not flush_file.exists()