The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): restore completion routes after restart; bind sibling scope on teardown
unsupportedpastels21c35c6115a6
diff --git a/gateway/run_notifications.py b/gateway/run_notifications.pyindex 04d07fcad48..538123325f1 100644--- a/gateway/run_notifications.py+++ b/gateway/run_notifications.py@@ -1235,10 +1235,12 @@ class GatewayNotificationsMixin(GatewayUpdateNotificationsMixin, GatewayNotificaasync def _deliver_completion_notification_scoped(self, synth_text: str, evt: dict, *, sibling_claims=(),) -> Optional[bool]:+ from gateway.session_local_recovery import restore_completion_routefrom gateway.wake import WakeNotAcceptedfrom tools.process_registry_notifications import should_surface_notificationif not should_surface_notification(evt):return None # Suppressed noise is terminal, not a consumed process result.+ restore_completion_route(self, str(evt.get("session_key") or ""))identity = self._completion_delivery_identity(evt)claim = self._CompletionClaim()accepted = identity_claimed = refused = False@@ -1474,7 +1476,9 @@ class GatewayNotificationsMixin(GatewayUpdateNotificationsMixin, GatewayNotificaasync def _deliver_async_delegation_group_scoped(self, group: list[dict]) -> Optional[bool]:from gateway.run import _format_gateway_process_notification+ from gateway.session_local_recovery import restore_completion_routefrom tools.process_registry import process_registry as _pr+ restore_completion_route(self, str(group[0].get("session_key") or ""))# API delivery does not start a model turn, so there is nothing to coalesce.# Keep each unit's stable identity with its row across partial delivery/retry.if group and group[0].get("origin_session_id"):diff --git a/gateway/session_controls.py b/gateway/session_controls.pyindex 63a0f4baef8..ff14af2dc90 100644--- a/gateway/session_controls.py+++ b/gateway/session_controls.py@@ -880,10 +880,13 @@ class AuthorityConnection:forget(self) # nobody is left to read its one-shot replies# Deletion may already have evicted a subscribed session; its membership died# with it, and one retired ID must not leave the others (or the transport) attached.- for session_id, subscription in list(self.subscriptions.items()):- live = self.authority.sessions.get(session_id)- if live is not None and subscription in live.subscribers:- await self.authority.detach(self.actor, subscription)+ # A sibling's teardown runs under the primary socket's scope: detach as this owner, as dispatch does.+ from gateway.session_authorities import owner_scope+ with owner_scope(self.authority):+ for session_id, subscription in list(self.subscriptions.items()):+ live = self.authority.sessions.get(session_id)+ if live is not None and subscription in live.subscribers:+ await self.authority.detach(self.actor, subscription)from gateway.session_local_migration import unbind_native_transportunbind_native_transport(self.authority, self.actor)self.subscriptions.clear()diff --git a/gateway/session_local_recovery.py b/gateway/session_local_recovery.pyindex e588e18676e..10d061d54a5 100644--- a/gateway/session_local_recovery.py+++ b/gateway/session_local_recovery.py@@ -1,5 +1,6 @@"""Restore only private, profile-bound local policy into the existing authority."""import asyncio+import contextlibimport jsonimport loggingfrom pathlib import Path@@ -374,6 +375,19 @@ _BOOT_RECEIPTS_SQL = ("OR EXISTS (SELECT 1 FROM state_meta c WHERE c.key = ? || substr(m.key, ?)))")+def restore_completion_route(runner, session_key):+ """Background work that outlived its local session reports after a restart: boot left that ended+ session unrestored, so restore it first, as ``authorize`` does on a viewer's first touch, and its+ completion is noted on it as before. Anything else is left to the delivery's own checks."""+ from gateway.run import _parse_session_key+ from gateway.session_authorities import active_authority+ authority, parsed = active_authority(runner), _parse_session_key(session_key) or {}+ if authority is None or parsed.get('platform') != Platform.LOCAL.value or parsed['chat_id'] in authority.sessions:+ return+ with contextlib.suppress(RuntimeStoreError):+ restore_local_session(authority, parsed['chat_id'])++def local_receipt_ids(authority):from gateway.session_viewer_close import CLOSE_PREFIXstart = len(POLICY_PREFIX) + 1diff --git a/tests/gateway/test_local_session_orphan_end.py b/tests/gateway/test_local_session_orphan_end.pyindex 42230d6256b..e97407fd617 100644--- a/tests/gateway/test_local_session_orphan_end.py+++ b/tests/gateway/test_local_session_orphan_end.py@@ -181,6 +181,39 @@ async def test_boot_restores_only_open_sessions_and_an_ended_one_on_first_touch(assert ended in authority.sessions[email protected]('producer', ['delegation', 'process'])+async def test_work_finishing_after_close_and_restart_is_noted_on_the_ended_session(tmp_path, monkeypatch, producer):+ """Boot leaves ended sessions unrestored, but not one whose background work has not reported yet."""+ from hermes_state_local import end_idle_local_session+ from tests.gateway.test_completion_admission import pending+ from tests.gateway.test_session_end_delegations import _local+ from tests.gateway.test_unviewed_completion_notes import _delegation_note, _process_event, _restart, _target+ import tools.async_delegation as delegation++ delegation._reset_for_tests()+ runner, authority, ref, _actor = await _local(tmp_path, monkeypatch)+ route, target = authority.sessions[ref.session_id].route, _target(runner, authority, ref)+ if producer == 'delegation':+ evt = dict(pending(route, 'deleg_late'), parent_session_id=target)+ else:+ evt = _process_event(authority, ref, target, 'proc_late')+ assert end_idle_local_session(authority.db, epoch=authority.epoch, session_id=ref.session_id,+ target_id=target, reason='cli_close')+ runner, authority = await _restart(tmp_path, monkeypatch, authority)+ try:+ if producer == 'delegation':+ assert await runner._deliver_async_delegation_group([evt]) is True+ else:+ assert await runner._deliver_completion_notification('[finished] RESULT_proc_late', evt) is True+ await authority._drain(ref)+ assert len(_delegation_note(authority, target, evt.get('delegation_id', 'proc_late'))) == 1+ assert authority.db.get_session(target)['end_reason'] == 'cli_close'+ finally:+ authority.db.close()+ delegation._reset_for_tests()++@pytest.mark.asyncio@pytest.mark.parametrize('viewer_returns', [False, True])async def test_a_session_open_when_the_gateway_stopped_ends_after_boot(tmp_path, monkeypatch, viewer_returns):@@ -291,6 +324,31 @@ async def test_a_dropped_viewer_expands_the_grace_against_its_own_profile(tmp_paassert [delay for delay, _ in armed] == [7.0]+async def test_a_sibling_torn_down_with_the_shared_socket_reads_its_own_grace(tmp_path, monkeypatch):+ """A shared socket's close tears its sibling connections down under the primary profile's scope;+ each still detaches as its own owner, so the sibling's grace expands against its own ``.env``."""+ from agent.secret_scope import build_profile_secret_scope, reset_secret_scope, set_secret_scope+ from hermes_constants import get_hermes_home++ armed = _capture_timers(monkeypatch)+ home, primary = get_hermes_home(), tmp_path / 'primary'+ primary.mkdir()+ (home / 'config.yaml').write_text('sessions:\n orphan_end_grace_s: ${ORPHAN_GRACE}\n')+ (home / '.env').write_text('ORPHAN_GRACE=900\n')+ (primary / '.env').write_text('ORPHAN_GRACE=1\n')+ sibling, _ = await _owner(home, monkeypatch) # profile id, store and config share one home+ sibling.runner.config = SimpleNamespace(multiplex_profiles=True)+ viewer, _ = await _attach(sibling, _create(sibling).session_id)++ token = set_secret_scope(build_profile_secret_scope(primary), profile_home=str(primary))+ try:+ await viewer.close() # reached from the primary connection's close: its scope is bound+ finally:+ reset_secret_scope(token)+ assert [delay for delay, _ in armed] == [900.0]++@pytest.mark.asyncioasync def test_a_zero_grace_never_ends_a_detached_session(tmp_path, monkeypatch):armed = _capture_timers(monkeypatch)