The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): retry uncertain completion ownership
Alexa481580f2565
diff --git a/gateway/run_notifications.py b/gateway/run_notifications.pyindex 0aa26773278..f77f2cdc902 100644--- a/gateway/run_notifications.py+++ b/gateway/run_notifications.py@@ -215,53 +215,37 @@ class GatewayNotificationsMixin:await adapter.send(source.chat_id, content, metadata=metadata)async def _resolve_compression_lineage_target(- self, session_db: Any, session_entry: SessionEntry, pinned_session_id: str,- ) -> Optional[str]:- """Return the live compression tip of ``pinned_session_id`` if the route owns that lineage, else None."""+ self, session_db: Any, session_entry: Optional[SessionEntry], pinned_session_id: str,+ ) -> tuple[str, Optional[str]]:+ """Distinguish uncertain compression ownership from a proven foreign route."""try:target_session_id = await session_db.get_compression_tip(pinned_session_id)- except Exception:- logger.debug("Async-delegation compression-tip lookup failed for %s", pinned_session_id, exc_info=True)- target_session_id = None- if not target_session_id or target_session_id == pinned_session_id:- logger.warning(- "Async-delegation completion pinned to compressed session %s "- "without a continuation; dropping injection.", pinned_session_id,- )- return None- try:+ if not target_session_id or target_session_id == pinned_session_id:+ return "retry", None # Rotation may not have published its continuation yet.tip_row = await session_db.get_session(target_session_id)- except Exception:- tip_row = None- if tip_row is None or tip_row.get("ended_at"):- logger.warning(- "Async-delegation compression continuation %s is %s; dropping injection.",- target_session_id, "unknown" if tip_row is None else "ended",- )- return None- route_owns_lineage = session_entry.session_id in {pinned_session_id, target_session_id}- if not route_owns_lineage:+ if tip_row is None or tip_row.get("ended_at"):+ return "retry", None+ if session_entry is None or session_entry.session_id in {pinned_session_id, target_session_id}:+ return "deliver", target_session_id# Across several rotations, accept a stale route only when its own tip is the same live target.- try:- route_row = await session_db.get_session(session_entry.session_id)- route_tip = (- await session_db.get_compression_tip(session_entry.session_id)- if route_row is not None- and route_row.get("ended_at")- and route_row.get("end_reason") == "compression"- else None- )- except Exception:- route_tip = None- route_owns_lineage = route_tip == target_session_id- if not route_owns_lineage:- logger.warning(- "Async-delegation completion for compression lineage %s -> %s "- "does not own current route %s; dropping injection.",- pinned_session_id, target_session_id, session_entry.session_id,- )- return None- return target_session_id+ route_row = await session_db.get_session(session_entry.session_id)+ if route_row is None:+ return "retry", None+ if route_row.get("ended_at") and route_row.get("end_reason") == "compression":+ route_tip = await session_db.get_compression_tip(session_entry.session_id)+ if not route_tip or route_tip == session_entry.session_id:+ return "retry", None+ if route_tip == target_session_id:+ return "deliver", target_session_id+ except Exception:+ logger.debug("Async-delegation compression ownership lookup failed for %s", pinned_session_id, exc_info=True)+ return "retry", None+ logger.warning(+ "Async-delegation completion for compression lineage %s -> %s "+ "does not own current route %s; dropping injection.",+ pinned_session_id, target_session_id, session_entry.session_id,+ )+ return "terminal", Noneasync def _lookup_completion_owner(self, session_id: str, current_session_id: str = ""):"""Nonmutating delegation proof shared by preflight and route resolution.@@ -364,10 +348,10 @@ class GatewayNotificationsMixin:)return session_entryfollows_compression = True- target_session_id = await self._resolve_compression_lineage_target(+ verdict, target_session_id = await self._resolve_compression_lineage_target(session_db, session_entry, pinned_session_id,)- if target_session_id is None:+ if verdict != "deliver" or target_session_id is None:return Noneif target_session_id == session_entry.session_id:return session_entry@@ -1492,22 +1476,10 @@ class GatewayNotificationsMixin:# Only a USER-closed session (/new, user_exit, session_switch) is unreachable; idle/timeout# ends stay routable and the resolver retargets. Boundary set shared with the resolver.return "terminal" if end_reason in _USER_BOUNDARY_END_REASONS else "deliver"- try:- tip_session_id = await session_db.get_compression_tip(parent_session_id)- if not tip_session_id or tip_session_id == parent_session_id:- # Rotation mid-flight: continuation not visible yet. Retry, don't drop.- return "retry"- tip = await session_db.get_session(tip_session_id)- except Exception:- logger.debug("Async-completion pre-flight tip lookup failed for %s", parent_session_id, exc_info=True)- return "retry"- if tip is None or tip.get("ended_at"):- return "retry"- if entry is not None and await self._resolve_compression_lineage_target(+ verdict, _ = await self._resolve_compression_lineage_target(session_db, entry, parent_session_id,- ) is None:- return "terminal"- return "deliver"+ )+ return verdict@staticmethoddef _settle_durable_claim(kind: str, delegation_id: str, claim_id: str) -> None:diff --git a/tests/gateway/test_async_delegation_session_binding.py b/tests/gateway/test_async_delegation_session_binding.pyindex 74c8a457572..0dfba29c820 100644--- a/tests/gateway/test_async_delegation_session_binding.py+++ b/tests/gateway/test_async_delegation_session_binding.py@@ -252,6 +252,122 @@ async def test_pending_pin_respects_concurrent_boundary(tmp_path, boundary):else:assert result is None[email protected]("phase", ["readiness", "claimed"])[email protected]("fault", [+ "parent_tip_error", "parent_tip_none", "parent_tip_self", "tip_row_error",+ "tip_row_missing", "tip_row_ended", "route_row_error", "route_row_missing",+ "route_tip_error", "route_tip_none",+])+async def test_compression_uncertainty_keeps_durable_completion_retryable(tmp_path, monkeypatch, phase, fault):+ """Uncertain lineage never consumes the result or mutates its route; replay recovers."""+ from types import SimpleNamespace+ from typing import Any, cast++ from gateway.config import GatewayConfig, Platform+ from gateway.platforms.base import BasePlatformAdapter+ from gateway.run import GatewayRunner, _profile_runtime_scope+ from gateway.session import SessionSource++ with _profile_runtime_scope(tmp_path):+ runner = GatewayRunner(GatewayConfig(sessions_dir=tmp_path / "sessions"))+ store = runner.session_store+ entry = store.get_or_create_session(SessionSource(+ platform=Platform.TELEGRAM, chat_id="compression-owner", chat_type="dm",+ ))+ db = store._db+ parent = entry.session_id+ db.end_session(parent, end_reason="compression")+ db.create_session("middle", source="telegram", parent_session_id=parent)+ entry = store.switch_session(entry.session_key, "middle")+ assert entry is not None+ db.end_session("middle", end_reason="compression")+ db.create_session("tip", source="telegram", parent_session_id="middle")+ before = {sid: db.get_session(sid) for sid in (parent, "middle", "tip")}+ async_db = runner._session_db+ get_session = async_db.get_session+ get_tip = async_db.get_compression_tip+ parent_reads = 0+ enabled = True+ resolver_probe = True++ def failing():+ return enabled and (resolver_probe or phase == "readiness" or parent_reads >= 2)++ async def lookup_session(sid):+ nonlocal parent_reads+ if sid == parent:+ parent_reads += 1+ if failing() and sid == {"tip_row_error": "tip", "tip_row_missing": "tip",+ "tip_row_ended": "tip", "route_row_error": "middle",+ "route_row_missing": "middle"}.get(fault):+ if fault.endswith("error"):+ raise RuntimeError("temporary session lookup failure")+ if fault.endswith("missing"):+ return None+ row = await get_session(sid)+ return dict(row, ended_at=1, end_reason="compression")+ return await get_session(sid)++ async def lookup_tip(sid):+ if failing() and ((sid == parent and fault.startswith("parent_tip"))+ or (sid == "middle" and fault.startswith("route_tip"))):+ if fault.endswith("error"):+ raise RuntimeError("temporary compression lookup failure")+ return sid if fault.endswith("self") else None+ return await get_tip(sid)++ monkeypatch.setattr(async_db, "get_session", lookup_session)+ monkeypatch.setattr(async_db, "get_compression_tip", lookup_tip)+ assert await runner._resolve_async_delegation_session(entry, parent) is None+ current = store.lookup_by_session_key(entry.session_key)+ assert current is not None and current.session_id == "middle"+ for sid, row in before.items():+ assert db.get_session(sid) == row+ resolver_probe = False+ parent_reads = 0+ resolved = []++ async def accept(event):+ current = store.lookup_by_session_key(entry.session_key)+ assert current is not None+ result = await runner._resolve_async_delegation_session(current, event.metadata["gateway_session_id"])+ assert result is not None+ resolved.append(result.session_id)+ event._gateway_accepted = True++ runner.adapters[Platform.TELEGRAM] = cast(BasePlatformAdapter, SimpleNamespace(handle_message=accept))+ event: dict[str, Any] = {"type": "async_delegation", "delegation_id": "uncertain-compression",+ "session_key": entry.session_key, "parent_session_id": parent,+ "dispatched_at": 1.0, "summary": "completed result", "status": "completed"}+ ad._persist_dispatch(event)+ ad._persist_completion(event, {"status": "completed", "summary": event["summary"]})+ assert await runner._deliver_completion_notification("completed result", event) is False+ row = ad.get_durable_delegation(event["delegation_id"])+ assert row is not None+ assert (row["delivery_state"], row["delivery_attempts"]) == (+ "pending", 0 if phase == "readiness" else 1,+ )+ import sqlite3+ with sqlite3.connect(ad._db_path()) as conn:+ assert conn.execute("SELECT delivery_claim FROM async_delegations WHERE delegation_id=?",+ (event["delegation_id"],)).fetchone() == (None,)+ assert not resolved+ current = store.lookup_by_session_key(entry.session_key)+ assert current is not None and current.session_id == "middle"+ for sid, original in before.items():+ assert db.get_session(sid) == original+ enabled = False+ assert await runner._deliver_completion_notification("completed result", event) is True+ assert resolved == ["tip"]+ current = store.lookup_by_session_key(entry.session_key)+ assert current is not None and current.session_id == "tip"+ row = ad.get_durable_delegation(event["delegation_id"])+ assert row is not None and row["delivery_state"] == "delivered"+ assert await runner._deliver_completion_notification("completed result", event) is None+ assert resolved == ["tip"]++@pytest.mark.asyncio@pytest.mark.parametrize("delivery", ["single", "group"])@pytest.mark.parametrize("case", [