Skip to content

The agent that grows with you

fix(gateway): an old conversation's reminders, heartbeats and queued results follow it

Teknium6ed6ad73be55
diff --git a/gateway/run_notifications.py b/gateway/run_notifications.py
index 340cd2bc251..e92893d34c5 100644
--- a/gateway/run_notifications.py
+++ b/gateway/run_notifications.py
@@ -666,7 +666,8 @@ class GatewayNotificationsMixin(GatewayUpdateNotificationsMixin, GatewayNotifica
return self._restored_source(entry)
except Exception as exc:
logger.debug("Synthetic process-event session-store lookup failed for %s: %s", session_key, exc)
- cached_source = self._get_cached_session_source(session_key)
+ from gateway.session_detached import detached_live_source
+ cached_source = detached_live_source(self, session_key) or self._get_cached_session_source(session_key)
if cached_source is not None:
return cached_source
derived = _parse_session_key(session_key) or {}
diff --git a/gateway/session_automation.py b/gateway/session_automation.py
index 9ad69bc4590..626e033e7d9 100644
--- a/gateway/session_automation.py
+++ b/gateway/session_automation.py
@@ -110,8 +110,9 @@ async def prepare_heartbeat(runner, event):
queues behind it. A retry of a tick already admitted is dropped."""
import asyncio
from gateway.session_authorities import active_authority
+ from gateway.session_detached import route_entry
authority = active_authority(runner)
- entry = runner.session_store.lookup_by_session_key(str(event.get('session_key') or '')) if authority else None
+ entry = route_entry(authority, str(event.get('session_key') or '')) if authority else None
if entry is None:
return event
owner, process = _route_owner(authority, entry), str(event.get('session_id') or '')
@@ -169,8 +170,9 @@ async def withdraw_process_ticks(runner, event):
import asyncio
from gateway.session_authorities import active_authority
try:
+ from gateway.session_detached import route_entry
authority = active_authority(runner)
- entry = runner.session_store.lookup_by_session_key(str(event.get('session_key') or '')) if authority else None
+ entry = route_entry(authority, str(event.get('session_key') or '')) if authority else None
if entry is None:
return
finished = {identity[1] for identity in _identities(
@@ -466,12 +468,14 @@ def check_local_automation(authority, ref, row, *, route=None):
route = route or (live.route if live is not None else None)
payload = row['payload']
descriptor = payload['local_automation_v1']
+ from gateway.session_detached import own_detached_key, route_entry
+ # Admitted while its chat was elsewhere: the conversation's own key, whichever route it is on now.
+ admitted = descriptor.get('route') if own_detached_key(descriptor.get('route'), ref.session_id) else route
if (not route or set(payload) != {'text', 'local_automation_v1'}
- or row['principal_id'] != 'automation:' + route
- or descriptor['owner'] != ref.session_id or descriptor['route'] != route
+ or row['principal_id'] != 'automation:' + admitted
+ or descriptor['owner'] != ref.session_id or descriptor['route'] != admitted
or descriptor['identity'] != row['request_id']):
raise RuntimeStoreError('permission_denied')
- from gateway.session_detached import route_entry
entry = route_entry(authority, route)
if (entry is None or entry.suspended or (entry.session_id != descriptor['target']
and authority.db.get_compression_tip(descriptor['target']) != entry.session_id)):
@@ -717,18 +721,21 @@ async def admit_route_wake(runner, adapter, source, text, producer, metadata=Non
path (nothing is queued there either). Raises ``RuntimeStoreError`` on a refusal."""
from gateway.session_authorities import active_authority
from gateway.session_local_recovery import restore_completion_route
+ from gateway.session_detached import detached_live, detached_route_of, route_entry
authority = active_authority(runner)
key = runner._session_key_for_source(source)
restore_completion_route(runner, key) # a closed local session boot left unrestored has no store entry yet
- entry = runner.session_store.lookup_by_session_key(key) if authority is not None else None
+ entry = route_entry(authority, key) if authority is not None else None
if authority is None or entry is None:
return False
import uuid
identity = json.dumps([producer, key, uuid.uuid4().hex], separators=(',', ':'))
- if source.platform == Platform.LOCAL:
- # A local route has no messaging provenance to borrow: its wake rides local_automation_v1 on
- # the live session's own source object (``snapshot_local_automation`` checks identity).
- live = authority.sessions.get(source.chat_id)
+ if source.platform == Platform.LOCAL or detached_route_of(source):
+ # A local route (or a conversation its chat moved past, answered by its app viewers) has no
+ # messaging provenance to borrow: its wake rides local_automation_v1 on the live session's own
+ # source object (``snapshot_local_automation`` checks identity).
+ found = detached_live(authority, key)
+ live = found[1] if found is not None else authority.sessions.get(source.chat_id)
if live is None or live.route != key:
return False
event = MessageEvent(text=text, message_type=MessageType.TEXT, source=live.source, internal=True,
diff --git a/gateway/session_cron.py b/gateway/session_cron.py
index 406e8621de2..b5bb977958e 100644
--- a/gateway/session_cron.py
+++ b/gateway/session_cron.py
@@ -44,7 +44,9 @@ async def _admit_local_delivery(authority, chat_id, text, metadata):
from gateway.session_automation import admit_route_wake
from gateway.session_local_recovery import local_adapter_map, restore_local_session
with owner_scope(authority):
- restore_local_session(authority, chat_id) # a chat closed before this fire, as for completions
+ live = authority.sessions.get(chat_id)
+ if live is None or not live.detached: # a conversation its chat moved past is live in the apps
+ restore_local_session(authority, chat_id) # a chat closed before this fire, as for completions
source = authority.sessions[chat_id].source
return await admit_route_wake(authority.runner, local_adapter_map(authority)[Platform.LOCAL], source,
text, 'cron', metadata)
diff --git a/gateway/session_detached.py b/gateway/session_detached.py
index 040e1ef0d88..76b6ff87640 100644
--- a/gateway/session_detached.py
+++ b/gateway/session_detached.py
@@ -184,6 +184,19 @@ def detached_live(authority, route):
return SessionRef(authority.profile_id, session_id), live
+def own_detached_key(key, session_id) -> bool:
+ """*key* is *session_id*'s own detached key (the route it was on while its chat was elsewhere)."""
+ return isinstance(key, str) and detached_session_id(key) == session_id
+
+
+def detached_live_source(runner, key):
+ """The source of the conversation still live on detached key *key*, else None."""
+ from gateway.session_authorities import active_authority
+ authority = active_authority(runner) if detached_session_id(key) else None
+ found = detached_live(authority, key) if authority is not None else None
+ return found[1].source if found is not None else None
+
+
def route_entry(authority, route):
"""The routing entry *route* names: the store's, or a detached key's live conversation (a
background result it started finds it there, never on the chat's route)."""
diff --git a/tests/gateway/test_detached_conversation_lifecycle.py b/tests/gateway/test_detached_conversation_lifecycle.py
index a797c07b9c7..82e7d2ba221 100644
--- a/tests/gateway/test_detached_conversation_lifecycle.py
+++ b/tests/gateway/test_detached_conversation_lifecycle.py
@@ -127,36 +127,45 @@ async def test_the_chats_resume_drops_the_agent_the_app_cached_for_the_old_conve
assert key not in runner._agent_cache
[email protected]('viewer', [False, True], ids=['no-viewer', 'app-viewing'])
-async def test_a_background_result_of_the_old_conversation_reaches_the_app_not_the_chat(monkeypatch, viewer):
- """A process the app's turn on A started finishes: its result lands in A (a note in its history
- with no viewer, a turn of A with the app watching), never in the chat, and is not retried."""
+def _process_event(runner, live, session_id, kind='completion', **fields):
+ """A process event as the registry records it for a process the turn on *live* started."""
import time
from gateway.session import build_session_context
from gateway.session_context import get_session_env
+ entry = runner.session_store.get_or_create_session(live.source)
+ with runner._session_env_scope(build_session_context(live.source, runner.config, entry)):
+ env = {name: get_session_env(f'HERMES_SESSION_{name}') for name in ('KEY', 'PLATFORM', 'CHAT_ID', 'CHAT_TYPE')}
+ return {'type': kind, 'event_id': f'{kind}-1', 'session_id': 'proc_1', 'started_at': 1000.0,
+ 'session_key': env['KEY'], 'parent_session_id': session_id, 'command': 'sleep 1',
+ 'platform': env['PLATFORM'], 'chat_id': env['CHAT_ID'], 'chat_type': env['CHAT_TYPE'],
+ 'user_id': '42', 'emitted_at': time.time(), **fields}
+
+
+def _automation_rows(authority, session_id, route):
from hermes_state_runtime import list_session_admissions
+ return [row for row in list_session_admissions(authority.db, session_id=session_id, pending_only=False)
+ if row['principal_id'] == 'automation:' + route]
+
+
[email protected]('viewer', [False, True], ids=['no-viewer', 'app-viewing'])
+async def test_a_background_result_of_the_old_conversation_reaches_the_app_not_the_chat(monkeypatch, viewer):
+ """A process the app's turn on A started finishes: its result lands in A (a note in its history
+ with no viewer, a turn of A with the app watching), never in the chat, and is not retried. The
+ runner's bounded source cache no longer holds A's source by then."""
runner, _adapter, authority, _source, sent, ran, _gates, _lane, ref_a = await _moved_on(monkeypatch)
assert await _app_turn(authority, ref_a, 'start a job') == ('terminal', 'completed')
live = authority.sessions[ref_a.session_id]
if viewer:
await authority.attach(_app(), ref_a)
- entry = runner.session_store.get_or_create_session(live.source)
- with runner._session_env_scope(build_session_context(live.source, runner.config, entry)):
- # What the process registry records for a process the turn starts.
- env = {name: get_session_env(f'HERMES_SESSION_{name}') for name in ('KEY', 'PLATFORM', 'CHAT_ID', 'CHAT_TYPE')}
- evt = {'type': 'completion', 'event_id': 'e1', 'session_id': 'proc_1', 'started_at': time.time(),
- 'session_key': env['KEY'], 'parent_session_id': ref_a.session_id, 'command': 'sleep 1',
- 'exit_code': 0, 'output': 'done', 'platform': env['PLATFORM'], 'chat_id': env['CHAT_ID'],
- 'chat_type': env['CHAT_TYPE'], 'user_id': '42'}
+ evt = _process_event(runner, live, ref_a.session_id, exit_code=0, output='done')
+ runner._session_sources.clear()
chat_before, ran_before = len(sent), len(ran)
assert await runner._inject_watch_notification('[process proc_1 finished]', evt) is True
def settled():
- rows = list_session_admissions(authority.db, session_id=ref_a.session_id, pending_only=False)
- return [row for row in rows if row['principal_id'] == 'automation:' + live.route
- and row['status'] == 'terminal']
+ return [row for row in _automation_rows(authority, ref_a.session_id, live.route) if row['status'] == 'terminal']
rows = await async_wait_until(settled, timeout=10, what="the result's admission on A")
assert rows[0]['outcome'] == 'completed'
if viewer:
@@ -167,3 +176,68 @@ async def test_a_background_result_of_the_old_conversation_reaches_the_app_not_t
assert any('[process proc_1 finished]' in str(message.get('content'))
for message in authority.db.get_messages(ref_a.session_id))
assert sent[chat_before:] == [], f'the chat got the old conversation\'s result: {sent[chat_before:]}'
+
+
+async def test_a_result_queued_on_the_old_conversation_still_runs_once_the_chat_resumes_it(monkeypatch):
+ """The result is queued behind the app's running turn when the chat ``/resume``s A: it runs as A's
+ turn on the chat's route, not refused as admitted under another route."""
+ from gateway.session_contract import Submission
+ runner, adapter, authority, source, sent, ran, gates, lane, ref_a = await _moved_on(monkeypatch)
+ await authority.attach(_app(), ref_a)
+ live = authority.sessions[ref_a.session_id]
+ detached_route = live.route
+ gates['slow app turn'] = asyncio.Event()
+ await authority.submit(_app(), Submission('slow', ref_a, {'text': 'slow app turn'}, 'queue'))
+ await async_wait_until(lambda: ran and ran[-1][0] == 'slow app turn', what='the app turn to start')
+ evt = _process_event(runner, live, ref_a.session_id, exit_code=0, output='done')
+ assert await runner._inject_watch_notification('[process proc_1 finished]', evt) is True
+ await _chat(adapter, source, sent, '/resume First chat')
+ assert live.route == lane
+ gates['slow app turn'].set()
+
+ def settled():
+ return [row for row in _automation_rows(authority, ref_a.session_id, detached_route)
+ if row['status'] == 'terminal']
+ rows = await async_wait_until(settled, timeout=10, what="the result's admission on A")
+ assert rows[0]['outcome'] == 'completed'
+ assert [turn[1:] for turn in ran if turn[0].startswith('[process proc_1 finished]')] == [(ref_a.session_id, lane)]
+
+
+async def test_the_old_conversations_finished_process_withdraws_its_waiting_heartbeat(monkeypatch):
+ """A liveness tick of A's process waits behind the app's running turn; the process's completion
+ cancels it, as on any route, instead of leaving a stale "still running" turn queued."""
+ from gateway.session_automation import deliver_heartbeat
+ from gateway.session_contract import Submission
+ runner, _adapter, authority, _source, _sent, ran, gates, _lane, ref_a = await _moved_on(monkeypatch)
+ live = authority.sessions[ref_a.session_id]
+ gates['slow app turn'] = asyncio.Event()
+ await authority.submit(_app(), Submission('slow', ref_a, {'text': 'slow app turn'}, 'queue'))
+ await async_wait_until(lambda: ran and ran[-1][0] == 'slow app turn', what='the app turn to start')
+ tick = _process_event(runner, live, ref_a.session_id, 'heartbeat', seq=1, elapsed=60, interval=60,
+ output='still building', omitted=0)
+ assert await deliver_heartbeat(runner, tick) is True
+ completion = _process_event(runner, live, ref_a.session_id, exit_code=0, output='done')
+ assert await runner._inject_watch_notification('[process proc_1 finished]', completion) is True
+ ticks = [row for row in _automation_rows(authority, ref_a.session_id, live.route)
+ if row['request_id'].startswith('["heartbeat"')]
+ assert [(row['status'], row['outcome']) for row in ticks] == [('terminal', 'cancelled')]
+ gates['slow app turn'].set()
+
+
+async def test_a_reminder_the_app_set_on_the_old_conversation_fires_into_it(monkeypatch):
+ """A reminder created from the app on A names A (``platform: local``): its fire is written into A,
+ never refused for a local session A never was, and never sent to the chat."""
+ from pathlib import Path
+ from gateway.session_cron import deliver_to_local_chat
+ _runner, _adapter, authority, _source, sent, _ran, _gates, _lane, ref_a = await _moved_on(monkeypatch)
+ chat_before = len(sent)
+ home = Path(authority.db.db_path).parent
+
+ assert await asyncio.to_thread(deliver_to_local_chat, home, ref_a.session_id, 'reminder from A') is None
+ await async_wait_until(lambda: any('reminder from A' in str(message.get('content'))
+ for message in authority.db.get_messages(ref_a.session_id)),
+ timeout=10, what='the reminder note in A')
+ assert sent[chat_before:] == []