The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): resolve flush session_key to session_id at recovery
yoyodine-industries4aac98342b75
diff --git a/gateway/run.py b/gateway/run.pyindex 5890b002173..75238b59285 100644--- a/gateway/run.py+++ b/gateway/run.py@@ -5398,7 +5398,7 @@ async def start_gateway(config: Optional[GatewayConfig] = None, replace: bool =def _recover_pending() -> None:from gateway.shutdown_flush import recover_pending_to_dbrecovered = recover_pending_to_db(- session_resolver=runner.session_store.peek_session_id,+ session_resolver=runner.session_store.resolve_session_id_for_key,)if recovered:logger.info("Recovered %d pending message(s) from shutdown flush", recovered)diff --git a/gateway/session_recovery.py b/gateway/session_recovery.pyindex cfe0a99cb4c..22d94a51eac 100644--- a/gateway/session_recovery.py+++ b/gateway/session_recovery.py@@ -178,6 +178,78 @@ class SessionRecoveryMixin:raisereturn None+ @staticmethod+ def _platform_from_session_key(session_key: Optional[str]) -> Optional[str]:+ """Platform value encoded in a gateway session key (``parts[2]``), or None."""+ if not session_key:+ return None+ parts = str(session_key).split(":")+ if len(parts) < 3 or parts[0] != "agent":+ return None+ return parts[2] or None++ @staticmethod+ def _whatsapp_alias_session_keys(session_key: str, chat_id: Optional[str] = None) -> list:+ """Rebuild *session_key* under every WhatsApp alias of its chat id (phone<->LID drift).++ The flush key may carry the phone-form chat id while the durable row's key carries the+ LID form (or vice versa); ``expand_whatsapp_aliases`` lets each alias resolve. Non-WhatsApp+ keys yield no aliases. ``chat_id`` overrides the key's chat-id slot when provided.+ """+ parts = str(session_key).split(":")+ if len(parts) < 5 or parts[0] != "agent" or parts[2] != Platform.WHATSAPP.value:+ return []+ source_id = chat_id or parts[4]+ try:+ from gateway.whatsapp_identity import expand_whatsapp_aliases+ aliases = expand_whatsapp_aliases(str(source_id))+ except Exception as exc:+ logger.debug("WhatsApp alias expansion failed for %s: %s", source_id, exc)+ return []+ rebuilt = []+ for alias in aliases:+ alias = str(alias)+ if alias and alias != parts[4]:+ rebuilt.append(":".join(parts[:4] + [alias] + parts[5:]))+ return rebuilt++ def resolve_session_id_for_key(+ self, session_key: str, *, chat_id: Optional[str] = None, not_after=None,+ ) -> Optional[tuple]:+ """Resolve a gateway session key to a live session_id at shutdown-flush recovery.++ Recovery runs before the in-memory routing map is rebuilt, so this reads the durable row+ directly (via the profile-aware ``_db_for_key`` and the exact-key peer finder, which keeps+ the reset fence: rows ended only by recoverable reasons match; explicit boundaries do not).+ WhatsApp keys are also tried under every phone<->LID alias of their chat id. Never mints a+ session; returns ``(session_id, db)`` — the row id plus the store owning the key, so the+ caller appends into the right profile DB — or None when the row is absent or unrecoverable+ (the caller must then preserve the flush file). ``chat_id`` optionally overrides the key's+ chat-id slot for alias expansion.+ """+ if not session_key:+ return None+ db = self._db_for_key(session_key)+ finder = getattr(db, "find_latest_gateway_session_for_peer", None) if db else None+ if not callable(finder):+ return None+ platform = self._platform_from_session_key(session_key)+ if not platform:+ return None+ candidates = [session_key]+ for alias_key in self._whatsapp_alias_session_keys(session_key, chat_id=chat_id):+ if alias_key and alias_key not in candidates:+ candidates.append(alias_key)+ for candidate in candidates:+ try:+ row = finder(source=platform, session_key=candidate)+ except Exception as exc:+ logger.debug("Session key->id resolution failed for %s: %s", candidate, exc)+ continue+ if isinstance(row, dict) and row.get("id"):+ return str(row["id"]), db+ return None+def _recover_session_from_db(self, *, session_key: str, source: SessionSource, now: datetime,raise_on_lookup_error: bool = False) -> Optional[SessionEntry]:diff --git a/gateway/shutdown_flush.py b/gateway/shutdown_flush.pyindex e13dc72d291..afce3a19f01 100644--- a/gateway/shutdown_flush.py+++ b/gateway/shutdown_flush.py@@ -204,10 +204,11 @@ 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.+ ``session_resolver`` (optional ``(session_key, not_after=ts) -> (session_id, db) | None``, e.g.+ ``SessionStore.resolve_session_id_for_key``) is required for real flush files: adapter+ ``MessageEvent`` objects carry no ``session_id``, so without it every recovery lands in the skip+ branch. A returned ``db`` routes the append to the profile store owning the key (multiplexed+ gateways); ``None`` falls back to ``session_db``. Returns the number of messages recovered."""flush_files = sorted(_get_flush_dir().glob("*.json"))if not flush_files:@@ -261,19 +262,23 @@ def _recover_one_payload(session_db, path: Path, payload: Dict[str, Any], *,return False# session_key is a gateway routing key (e.g. "agent:main:telegram:..."); appending a row# needs the real session_id, which real payloads lack — the resolver supplies it.- session_id = data.get("session_id", "")+ session_id, target_db = data.get("session_id", ""), session_dbif not session_id and session_resolver is not None:try:- session_id = session_resolver(session_key) or ""- except Exception:- session_id = ""+ resolved = session_resolver(session_key, not_after=payload.get("ts"))+ except Exception as exc:+ logger.debug("Session key->id resolution failed for %s: %s", session_key, exc)+ resolved = None+ if resolved:+ session_id, routed_db = resolved+ target_db = routed_db if routed_db is not None else session_dbif not session_id:logger.warning("Cannot recover pending message for %s: no session_id in flush file and ""session_key-to-id resolution failed. ""The message text is preserved in %s", session_key, path)return False- session_db.append_message(session_id=session_id, role="user", content=text,- timestamp=payload.get("ts", int(time.time())))+ target_db.append_message(session_id=session_id, role="user", content=text,+ timestamp=payload.get("ts", int(time.time())))return Truediff --git a/tests/gateway/test_session_recovery.py b/tests/gateway/test_session_recovery.pynew file mode 100644index 00000000000..1a1db905470--- /dev/null+++ b/tests/gateway/test_session_recovery.py@@ -0,0 +1,79 @@+"""Tests for SessionRecoveryMixin.resolve_session_id_for_key — flush-recovery+session_key → session_id resolution (profile- and WhatsApp-alias aware)."""++from unittest.mock import patch++from gateway.config import GatewayConfig+from gateway.session import SessionStore+++class _FakeGatewayDB:+ """Minimal SessionDB stand-in exposing only the peer finder the resolver uses."""++ def __init__(self, rows_by_key):+ self.rows_by_key = rows_by_key+ self.queries = []++ def find_latest_gateway_session_for_peer(self, *, source, session_key=None, **kwargs):+ self.queries.append(session_key)+ return self.rows_by_key.get(session_key)+++def _store(tmp_path, db):+ config = GatewayConfig(multiplex_profiles=True)+ with patch("gateway.session.SessionStore._ensure_loaded"):+ store = SessionStore(sessions_dir=tmp_path, config=config)+ store._loaded = True+ store._db = db # pin: _db_for_key returns this db for every key (no profile I/O)+ return store+++def _no_aliases(identifier):+ return {identifier}+++def test_resolve_exact_key_returns_row_id(tmp_path):+ db = _FakeGatewayDB({"agent:main:telegram:dm:99": {"id": "tel-row"}})+ store = _store(tmp_path, db)+ assert store.resolve_session_id_for_key("agent:main:telegram:dm:99") == ("tel-row", db)+ assert db.queries == ["agent:main:telegram:dm:99"]+++def test_resolve_whatsapp_phone_key_to_lid_row(tmp_path, monkeypatch):+ lid = "1234567890123456789"+ key = f"agent:test-bot:whatsapp:dm:{lid}"+ db = _FakeGatewayDB({key: {"id": "lid-row"}})+ store = _store(tmp_path, db)+ monkeypatch.setattr(+ "gateway.whatsapp_identity.expand_whatsapp_aliases",+ lambda ident: {"15551234567", lid} if ident == "15551234567" else {ident},+ )+ resolved = store.resolve_session_id_for_key(+ "agent:test-bot:whatsapp:dm:15551234567"+ )+ assert resolved == ("lid-row", db)+ assert key in db.queries+++def test_resolve_profile_namespaced_key_does_not_adopt_main_row(tmp_path, monkeypatch):+ """A profile-namespaced key must never resolve into the root store's+ ``agent:main`` row: the exact-key finder only matches the namespaced key."""+ db = _FakeGatewayDB({"agent:main:whatsapp:dm:15551234567": {"id": "main-row"}})+ store = _store(tmp_path, db)+ monkeypatch.setattr("gateway.whatsapp_identity.expand_whatsapp_aliases", _no_aliases)+ assert (+ store.resolve_session_id_for_key("agent:test-bot:whatsapp:dm:15551234567")+ is None+ )+ assert db.queries and all("agent:test-bot" in q for q in db.queries)+ assert not any(q.startswith("agent:main") for q in db.queries)+++def test_resolve_returns_none_when_no_matching_row(tmp_path, monkeypatch):+ db = _FakeGatewayDB({})+ store = _store(tmp_path, db)+ monkeypatch.setattr("gateway.whatsapp_identity.expand_whatsapp_aliases", _no_aliases)+ assert (+ store.resolve_session_id_for_key("agent:test-bot:whatsapp:dm:15551234567")+ is None+ )diff --git a/tests/gateway/test_shutdown_flush.py b/tests/gateway/test_shutdown_flush.pyindex e96f2dc51ec..619151349ed 100644--- a/tests/gateway/test_shutdown_flush.py+++ b/tests/gateway/test_shutdown_flush.py@@ -98,6 +98,78 @@ def test_recover_inserts_via_append_message_and_deletes_file(tmp_path, monkeypatassert not flush_file.exists()+def test_recover_payload_without_session_id_uses_resolver_and_deletes_file(+ tmp_path, monkeypatch+):+ """A str-pending payload carries session_key but no session_id; a resolver+ maps key→id so the message replays and the file is removed."""+ 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:whatsapp:dm:15551234567",+ "reason": "shutdown",+ "ts": ts,+ "data": {"text": "lost message"},+ }+ flush_file = flush_dir / "no_sid.json"+ flush_file.write_text(json.dumps(payload), encoding="utf-8")++ mock_db = MagicMock()+ resolver = MagicMock(return_value=("sid-resolved", None))+ count = recover_pending_to_db(mock_db, session_resolver=resolver)++ assert count == 1+ resolver.assert_called_once_with("agent:main:whatsapp:dm:15551234567", not_after=ts)+ mock_db.append_message.assert_called_once_with(+ session_id="sid-resolved", role="user", content="lost message", timestamp=ts+ )+ assert not flush_file.exists()+++def test_recover_payload_without_session_id_resolver_none_preserves_file(+ tmp_path, monkeypatch+):+ """When the resolver cannot map the key, the file is preserved (never delete an+ unrecoverable message)."""+ flush_dir = _make_flush_dir(tmp_path)+ monkeypatch.setattr("gateway.shutdown_flush._get_flush_dir", lambda: flush_dir)+ payload = {+ "session_key": "agent:main:whatsapp:dm:15551234567",+ "data": {"text": "lost message"},+ }+ flush_file = flush_dir / "no_sid.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, not_after=None: None)++ assert count == 0+ mock_db.append_message.assert_not_called()+ assert flush_file.exists()+++def test_recover_payload_without_session_id_no_resolver_preserves_file(+ tmp_path, monkeypatch+):+ """Existing behaviour: without a resolver, a session_id-less payload is preserved."""+ flush_dir = _make_flush_dir(tmp_path)+ monkeypatch.setattr("gateway.shutdown_flush._get_flush_dir", lambda: flush_dir)+ payload = {+ "session_key": "agent:main:whatsapp:dm:15551234567",+ "data": {"text": "lost message"},+ }+ flush_file = flush_dir / "no_sid.json"+ flush_file.write_text(json.dumps(payload), encoding="utf-8")++ mock_db = MagicMock()+ count = recover_pending_to_db(mock_db)++ assert count == 0+ mock_db.append_message.assert_not_called()+ assert flush_file.exists()++def test_recover_closes_owned_db_when_unexpected_exception_escapes(tmp_path, monkeypatch):@@ -260,7 +332,8 @@ def test_recover_resolves_session_key_via_resolver(tmp_path, monkeypatch):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,+ session_resolver=lambda key, not_after=None: (+ ("20260731_abc123", None) if key == "agent:main:telegram:dm:42" else None),)assert count == 1