Skip to content

The agent that grows with you

fix(gateway): bound the delegate provenance walk

wodesiku38c82c81fbfa
diff --git a/gateway/run_notifications.py b/gateway/run_notifications.py
index 76f048249ab..ff0653db49d 100644
--- a/gateway/run_notifications.py
+++ b/gateway/run_notifications.py
@@ -39,6 +39,13 @@ def _update_failed_notice() -> str:
# deferred line on every poll, in every process, forever. Stop waiting past this age.
_UPDATE_NOTIFY_MAX_ADAPTER_WAIT_SECONDS = 3600.0
+# Upper bound on the ``model_config._delegate_from`` chain walked by _resolve_async_delegation_session
+# when canonicalizing a delegate child to its human-facing gateway parent (#92611). Real nesting is
+# bounded far lower by delegation.max_spawn_depth (default 2); this only stops a corrupt chain from
+# turning one completion event into an unbounded run of sequential session reads. Exceeding it is
+# fail-closed, like every other unresolved provenance.
+_MAX_DELEGATE_PROVENANCE_HOPS = 16
+
def _served_notice_target_key(profile: Optional[str], platform_value: str, chat_id, thread_id) -> tuple:
"""Notice-dedupe key for one SERVED profile's home channel.
@@ -264,6 +271,14 @@ class GatewayNotificationsMixin:
Follow compression-rotation lineage (parent row ended, child continues), but never let a
late completion override an unrelated /new or restored route. Unknown ownership fails
closed; the result stays in the delegation records.
+
+ A pinned *delegate* row is likewise canonicalized to its human-facing parent through
+ ``model_config._delegate_from`` before any route check or mutation (#92611). Unresolvable
+ provenance — a cycle, a missing parent, a malformed config, or a chain longer than
+ ``_MAX_DELEGATE_PROVENANCE_HOPS`` — drops the injection rather than falling back to the
+ current route entry. That is deliberate: routing an internal child's output into a session
+ whose ownership was never verified is the same class of defect this canonicalization fixes,
+ and the completion remains readable in the delegation records either way.
"""
from gateway.run import _USER_BOUNDARY_END_REASONS
session_db = cast(Any, self._session_db)
@@ -292,8 +307,12 @@ class GatewayNotificationsMixin:
# `_delegate_from`. Follow that durable provenance before any route verification or mutation;
# otherwise switch_session() can end the real parent and rebind the platform chat to an
# internal child (#92611).
+ #
+ # Real nesting is bounded by delegation.max_spawn_depth (default 2), so the hop cap only
+ # guards a corrupt/hand-edited chain: without it a single completion event could fan out
+ # into hundreds of sequential get_session() reads before terminating.
delegate_chain: set[str] = set()
- while True:
+ for _ in range(_MAX_DELEGATE_PROVENANCE_HOPS + 1):
if pinned_session_id in delegate_chain:
logger.warning(
"Async-delegation completion has cyclic delegate provenance at session %s; "
@@ -334,6 +353,12 @@ class GatewayNotificationsMixin:
return None
pinned_session_id = delegate_parent_id
pinned_row = delegate_parent_row
+ else:
+ logger.warning(
+ "Async-delegation completion exceeded %d delegate provenance hops (last session %s); "
+ "dropping injection (#92611).", _MAX_DELEGATE_PROVENANCE_HOPS, pinned_session_id,
+ )
+ return None
target_session_id = pinned_session_id
follows_compression = False
if pinned_row.get("ended_at"):
diff --git a/tests/gateway/test_async_delegation_session_binding.py b/tests/gateway/test_async_delegation_session_binding.py
index 2380d6662aa..1c392ca7729 100644
--- a/tests/gateway/test_async_delegation_session_binding.py
+++ b/tests/gateway/test_async_delegation_session_binding.py
@@ -181,6 +181,71 @@ class TestGatewayPinningFailsClosed:
assert resolved is None
self._assert_no_route_change(runner)
+ @pytest.mark.asyncio
+ async def test_self_referential_delegate_provenance_fails_closed(self):
+ current = self._entry("sess_current")
+ runner = self._make_runner(
+ {
+ "sess_self": {
+ "id": "sess_self",
+ "ended_at": None,
+ "model_config": {"_delegate_from": "sess_self"},
+ },
+ },
+ )
+
+ resolved = await runner._resolve_async_delegation_session(current, "sess_self")
+
+ assert resolved is None
+ self._assert_no_route_change(runner)
+
+ @pytest.mark.asyncio
+ async def test_overlong_delegate_chain_fails_closed_without_route_change(self):
+ from gateway.run_notifications import _MAX_DELEGATE_PROVENANCE_HOPS
+
+ # One acyclic hop past the cap: the cycle guard cannot catch this, so
+ # only the hop bound stops the walk (#92620 review).
+ depth = _MAX_DELEGATE_PROVENANCE_HOPS + 2
+ rows = {
+ f"sess_{i}": {
+ "id": f"sess_{i}",
+ "ended_at": None,
+ "model_config": {"_delegate_from": f"sess_{i + 1}"},
+ }
+ for i in range(depth)
+ }
+ rows[f"sess_{depth}"] = {"id": f"sess_{depth}", "ended_at": None}
+ current = self._entry("sess_current")
+ runner = self._make_runner(rows)
+
+ resolved = await runner._resolve_async_delegation_session(current, "sess_0")
+
+ assert resolved is None
+ self._assert_no_route_change(runner)
+
+ @pytest.mark.asyncio
+ async def test_delegate_chain_at_the_hop_limit_still_resolves(self):
+ from gateway.run_notifications import _MAX_DELEGATE_PROVENANCE_HOPS
+
+ # Exactly at the bound: the cap must not reject a resolvable chain.
+ depth = _MAX_DELEGATE_PROVENANCE_HOPS
+ rows = {
+ f"sess_{i}": {
+ "id": f"sess_{i}",
+ "ended_at": None,
+ "model_config": {"_delegate_from": f"sess_{i + 1}"},
+ }
+ for i in range(depth)
+ }
+ rows[f"sess_{depth}"] = {"id": f"sess_{depth}", "ended_at": None}
+ current = self._entry(f"sess_{depth}")
+ runner = self._make_runner(rows)
+
+ resolved = await runner._resolve_async_delegation_session(current, "sess_0")
+
+ assert resolved is current
+ self._assert_no_route_change(runner)
+
@pytest.mark.asyncio
async def test_delegate_with_missing_parent_fails_closed_without_route_change(self):
current = self._entry("sess_current")