Skip to content

The agent that grows with you

fix(gateway): stop delegate walks at the chat's own conversation

unsupportedpastels116aa8011b0e
diff --git a/gateway/run_notifications_ownership.py b/gateway/run_notifications_ownership.py
index 3b2dc09ff3b..ffe09a176e0 100644
--- a/gateway/run_notifications_ownership.py
+++ b/gateway/run_notifications_ownership.py
@@ -119,6 +119,15 @@ class GatewayNotificationOwnershipMixin:
return "terminal", session_id, row
if session_id == current_session_id:
return "deliver", session_id, row
+ # A hop compressed into the current route is its conversation (a resumed delegate run), as
+ # admission rules: climbing past it would reach the parent the run was spawned from.
+ if current_session_id and row.get("end_reason") == "compression":
+ try:
+ if await session_db.get_compression_tip(session_id) == current_session_id:
+ return "deliver", session_id, row
+ except Exception:
+ logger.debug("Completion compression lookup failed for %s", session_id, exc_info=True)
+ return "retry", session_id, None
config = row.get("model_config")
try:
if isinstance(config, str):
diff --git a/gateway/session_automation.py b/gateway/session_automation.py
index 625c5b4c3b0..f1aaf2452df 100644
--- a/gateway/session_automation.py
+++ b/gateway/session_automation.py
@@ -258,18 +258,22 @@ def _route_owner(authority, entry):
else authority.logical_owner(entry.session_id))
-def _delegating_session(db, session_id):
- """The conversation a (nested) delegate_task child runs under, else ``session_id``. As in the
+def _owned_by(db, session_id, current):
+ """Whether ``session_id``, or a (nested) delegate_task conversation it runs under, is the route's
+ live ``current`` session or compressed into it. The walk stops at the first such hop: a resumed
+ delegate run is the chat's own conversation, never the parent it was spawned from. As in the
completion pre-flight (``_lookup_completion_owner``), only ``model_config._delegate_from`` leads
out of an execution transcript: ``parent_session_id`` also records compression and branches.
Likewise a session closed at a user boundary (/new, a resume away) leads nowhere."""
from gateway.run import _USER_BOUNDARY_END_REASONS
lineage = [session_id]
- while (not ((row := db.get_session(lineage[-1]) or {}).get('ended_at')
- and row.get('end_reason') in _USER_BOUNDARY_END_REASONS)
- and (parent := db.get_session_model_config_value(lineage[-1], '_delegate_from')) not in (None, *lineage)):
+ while lineage[-1] != current and db.get_compression_tip(lineage[-1]) != current:
+ row = db.get_session(lineage[-1]) or {}
+ parent = db.get_session_model_config_value(lineage[-1], '_delegate_from')
+ if (row.get('ended_at') and row.get('end_reason') in _USER_BOUNDARY_END_REASONS) or parent in (None, *lineage):
+ return False
lineage.append(parent)
- return lineage[-1]
+ return True
def _owner(runner, event, authority):
@@ -280,14 +284,10 @@ def _owner(runner, event, authority):
if runner.session_store._generate_session_key(event.source) != route:
raise RuntimeStoreError('admission_conflict')
expected = event.metadata.get('gateway_session_id')
- if not expected:
+ # A completed child may follow compression, and a process a subagent started its parent
+ # conversation, but never /new or an unrelated resume.
+ if not expected or not _owned_by(authority.db, expected, entry.session_id):
raise RuntimeStoreError('admission_conflict')
- if expected != entry.session_id:
- # A completed child may follow compression, and a process a subagent started its parent
- # conversation, but never /new or an unrelated resume.
- expected = _delegating_session(authority.db, expected)
- if expected != entry.session_id and authority.db.get_compression_tip(expected) != entry.session_id:
- raise RuntimeStoreError('admission_conflict')
return entry
diff --git a/tests/gateway/test_automation_wake_route.py b/tests/gateway/test_automation_wake_route.py
index 49ad38d3c79..8b38b4ab0aa 100644
--- a/tests/gateway/test_automation_wake_route.py
+++ b/tests/gateway/test_automation_wake_route.py
@@ -106,6 +106,70 @@ async def test_subagent_notice_is_dropped_after_its_resumed_child_was_switched_a
assert len(list_session_admissions(authority.db, session_id=root, pending_only=False)) == 1
+async def _resumed_delegate_route(tmp_path, monkeypatch):
+ runner, _, authority, source = await _discord_owner(tmp_path, monkeypatch)
+ root = (await _admit_human(runner, authority, MessageEvent(text='human', source=source, message_id='h1'))).ref.session_id
+ key = runner.session_store._generate_session_key(source)
+ child = root + '-worker'
+ # A delegate run (shaped like reserve_child_execution's row) resumed on the chat with /resume <id> --all.
+ authority.db.create_session(child, source='subagent', parent_session_id=root, model_config={'_delegate_from': root})
+ assert runner.session_store.switch_session(key, child) is not None
+ await _admit_human(runner, authority, MessageEvent(text='on child', source=source, message_id='h2'))
+ return runner, authority, source, key, child
+
+
+def _compress(runner, authority, key, child):
+ tip = child + '-tip'
+ authority.db.append_message(child, 'user', 'on child')
+ authority.db.publish_compression_child(parent_session_id=child, child_session_id=tip, source='discord',
+ messages=[{'role': 'user', 'content': 'summary'}],
+ require_compression_lease=False)
+ assert runner.session_store.advance_compression_session(key, child, tip) is not None
+ return tip
+
+
+async def test_wake_on_a_resumed_delegate_passes_preflight_after_compression(tmp_path, monkeypatch):
+ from gateway.session_contract import SessionRef
+ from gateway.session_envelope import check_native_route
+ runner, authority, source, key, child = await _resumed_delegate_route(tmp_path, monkeypatch)
+ tip = _compress(runner, authority, key, child)
+ event = {'type': 'completion', 'session_id': 'proc', 'started_at': 1, 'session_key': key, 'parent_session_id': tip}
+ assert await runner._inject_watch_notification('done', event) is True
+ wake = list_session_admissions(authority.db, session_id=child)[-1]
+ # The drain's pre-claim check (and startup recovery's): a refusal pauses the chat behind the wake.
+ await check_native_route(runner, wake['payload'], authority.physical_target(SessionRef(authority.profile_id, child)),
+ source, runner._adapter_for_source(source))
+ authority.db.close()
+ await asyncio.sleep(0)
+
+
+async def test_notice_pinned_before_compression_reaches_the_resumed_delegate_chat(tmp_path, monkeypatch):
+ runner, authority, _, key, child = await _resumed_delegate_route(tmp_path, monkeypatch)
+ tip = _compress(runner, authority, key, child)
+ # A process the resumed run started before compressing: the pre-flight and admission agree on the tip.
+ assert (await runner._classify_completion_owner(child, key))[::2] == ('deliver', tip)
+ event = {'type': 'completion', 'session_id': 'proc-before', 'started_at': 1, 'session_key': key,
+ 'parent_session_id': child}
+ assert await runner._inject_watch_notification('before', event) is True
+ authority.db.close()
+ await asyncio.sleep(0)
+
+
+async def test_process_notice_from_a_subagent_of_a_resumed_delegate_reaches_the_chat(tmp_path, monkeypatch):
+ runner, authority, _, key, child = await _resumed_delegate_route(tmp_path, monkeypatch)
+ nested = child + '-nested' # delegate_task inside the resumed conversation
+ authority.db.create_session(nested, source='subagent', parent_session_id=child, model_config={'_delegate_from': child})
+ event = {'type': 'completion', 'session_id': 'proc-nested', 'started_at': 1, 'session_key': key,
+ 'parent_session_id': nested}
+ assert await runner._inject_watch_notification('nested done', event) is True
+ assert 'nested done' in list_session_admissions(authority.db, session_id=child)[-1]['payload']['text']
+ authority.db.close()
+ await asyncio.sleep(0)
+
+
def _relay_adapter():
from gateway.relay.adapter import RelayAdapter
from gateway.relay.descriptor import CapabilityDescriptor