Skip to content

The agent that grows with you

fix(gateway): a rescan after a park serves the profile fully

unsupportedpastels617f9fe1c927
diff --git a/gateway/run_profile_reconcile.py b/gateway/run_profile_reconcile.py
index 0ec21501a1d..aab7bb29c85 100644
--- a/gateway/run_profile_reconcile.py
+++ b/gateway/run_profile_reconcile.py
@@ -227,6 +227,8 @@ class GatewayProfileReconcileMixin:
if name in added:
logger.info("[MULTIPLEX] Now serving profile '%s' (%s adapter(s) connected; %s)", name, connected, reason)
result["added"].append(name)
+ from gateway.run_runtime import recover_served_profile_native
+ await recover_served_profile_native(self, current[name])
else:
logger.info("[MULTIPLEX] Re-scanned profile '%s' after config/.env change (%s adapter(s) connected)", name, connected)
result["rescanned"].append(name)
diff --git a/gateway/run_runtime.py b/gateway/run_runtime.py
index f4c6b20028d..bd17863af7d 100644
--- a/gateway/run_runtime.py
+++ b/gateway/run_runtime.py
@@ -311,7 +311,8 @@ class ProfileOwnershipRetained(RuntimeError):
async def serve_profile_runtime(runner, name, home):
"""Hot-serve one reserved profile's runtime: build its authority, recover its durable state and
publish it in the descriptor/ticket store — the steps boot performs per secondary. Raises when
- the profile's store is unusable; the caller parks it (and releases the reservation)."""
+ the profile's store is unusable; the caller parks it (and releases the reservation). Its
+ queued native rows are recovered once its adapters connect (``recover_served_profile_native``)."""
from gateway.session_authorities import owner_scope
from gateway.session_hosted_service import _ensure_hosted_service, start_ready_hosted_services
from gateway.session_local_recovery import recover_local_sessions
@@ -331,9 +332,11 @@ async def serve_profile_runtime(runner, name, home):
authority = await _build_profile_authority(runner, name, home, register=False)
try:
with owner_scope(authority):
+ _drop_retired_local_adapter(authority)
await recover_bot_mailbox(authority)
recover_local_sessions(authority, schedule=True)
await recover_webhook_finalizations(authority)
+ _recover_published_api_turns(runner, authority)
if getattr(runner, 'session_control_server', None) is not None:
await _ensure_hosted_service(runner, authority)
except BaseException:
@@ -345,6 +348,45 @@ async def serve_profile_runtime(runner, name, home):
return authority
+def _drop_retired_local_adapter(authority):
+ """A LOCAL adapter still bound to this profile's previous authority, once that authority fully
+ retired, gives way to *authority*'s own: restore and create otherwise refuse every local session
+ of the served profile as ``runtime_draining``. A retained writer never gets here (the serve is
+ refused while the previous authority is still retiring)."""
+ from gateway.config import Platform
+ from gateway.session_local_recovery import local_adapter_map
+ adapters = local_adapter_map(authority)
+ previous = getattr(adapters.get(Platform.LOCAL), 'authority', None)
+ if previous is not None and previous is not authority and getattr(previous, 'retired', False):
+ del adapters[Platform.LOCAL]
+
+
+def _recover_published_api_turns(runner, authority):
+ """Boot recovers queued API turns when the launch API adapter is published
+ (``recover_api_turns``); a profile served after that runs the same pass on its own store."""
+ from gateway.config import Platform
+ api = (getattr(runner, 'adapters', None) or {}).get(Platform.API_SERVER)
+ if api is not None:
+ from gateway.session_api_turn import recover_authority_api_turns
+ recover_authority_api_turns(api, authority)
+
+
+async def recover_served_profile_native(runner, home):
+ """Boot's native-row recovery for one hot-served profile, run once its adapters connected (boot
+ runs it after every adapter connects). A store that cannot answer leaves the rows queued for
+ the next start and never stops the reconcile of the other profiles."""
+ registry = getattr(runner, 'session_authorities', None)
+ if registry is None:
+ return
+ authority = registry.for_home(await asyncio.to_thread(Path(home).resolve))
+ if authority is None or getattr(authority, 'retiring', False):
+ return
+ try:
+ await recover_profile_native_sessions(runner, authority)
+ except Exception: # health: allow BLE001 -- logged; the rows stay queued for the next start
+ logger.error('Native session recovery failed for %s', authority.profile_id, exc_info=True)
+
+
async def unserve_profile_runtime(runner, home):
"""Retire one profile's authority (deleted while running) and shrink the published set.
False when one of its turns outlived the Stop deadline (keep the reservation); True otherwise,
@@ -428,7 +470,6 @@ async def recover_gateway_native_sessions(runner):
Stored envelopes are input, not authority to create a route or reconnect a
transport. The authority preflights every queued sender before any claim.
"""
- import logging
from gateway.session_authorities import owner_scope, serving_authorities
authorities = serving_authorities(runner)
if not authorities:
@@ -437,24 +478,30 @@ async def recover_gateway_native_sessions(runner):
await ensure_hosted_service(runner)
from gateway.session_local_recovery import recover_local_sessions
from gateway.platforms.webhook_ingress import recover_webhook_finalizations
- logger = logging.getLogger(__name__)
results = {}
for authority in authorities:
with owner_scope(authority):
recover_local_sessions(authority, schedule=True)
await recover_webhook_finalizations(authority)
- pending = {row['target_session_id'] for row in authority.db._read_all(
- "SELECT DISTINCT target_session_id FROM session_admissions WHERE status IN ('queued','unknown')")}
- bindings = [(owner, entry.origin, runner._adapter_for_source(entry.origin))
- for entry in runner.session_store.list_sessions() if entry.origin is not None
- for owner in [authority.logical_owner(entry.session_id)] if owner in pending]
- outcome = await authority.recover_native_sessions(bindings)
- for sid, verdict in outcome.items():
- logger.info('Native session startup recovery %s (%s): %s', sid, authority.profile_id, verdict)
- results.update(outcome)
+ results.update(await recover_profile_native_sessions(runner, authority))
return results
+async def recover_profile_native_sessions(runner, authority):
+ """Bind one authority's queued native rows to the adapters connected now."""
+ from gateway.session_authorities import owner_scope
+ with owner_scope(authority):
+ pending = {row['target_session_id'] for row in authority.db._read_all(
+ "SELECT DISTINCT target_session_id FROM session_admissions WHERE status IN ('queued','unknown')")}
+ bindings = [(owner, entry.origin, runner._adapter_for_source(entry.origin))
+ for entry in runner.session_store.list_sessions() if entry.origin is not None
+ for owner in [authority.logical_owner(entry.session_id)] if owner in pending]
+ outcome = await authority.recover_native_sessions(bindings)
+ for sid, verdict in outcome.items():
+ logger.info('Native session startup recovery %s (%s): %s', sid, authority.profile_id, verdict)
+ return outcome
+
+
def publish_gateway_runtime_ready(runner):
descriptor = runner.session_runtime_descriptor
if runner.session_api.task.done() or not runner._running or runner._draining:
diff --git a/gateway/session_api_turn.py b/gateway/session_api_turn.py
index 448f0e29340..0aada2dcb9c 100644
--- a/gateway/session_api_turn.py
+++ b/gateway/session_api_turn.py
@@ -310,10 +310,10 @@ def recover_api_turns(adapter):
# Startup is unscoped (the launch profile's home): each profile's media root, config and
# API bindings must pair with its own state.db, never the launch profile's.
with owner_scope(authority):
- _recover_api_turns(adapter, authority)
+ recover_authority_api_turns(adapter, authority)
-def _recover_api_turns(adapter, authority):
+def recover_authority_api_turns(adapter, authority):
from hermes_state_runtime import list_session_admissions
from gateway.session_ingress_media import collect_unheld_api_images
import logging
diff --git a/tests/gateway/test_parked_profile_rescan.py b/tests/gateway/test_parked_profile_rescan.py
new file mode 100644
index 00000000000..c3b67ab276c
--- /dev/null
+++ b/tests/gateway/test_parked_profile_rescan.py
@@ -0,0 +1,152 @@
+"""A secondary parked at boot (its startup Bot recovery failed) and served again by the
+control-socket rescan is fully served: its local sessions work, and the durable work queued
+before the park is recovered the way a cold boot recovers it (local, API turns, native rows).
+"""
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+
+from gateway.config import GatewayConfig, Platform
+from gateway.run import GatewayRunner
+from gateway.runtime_ownership import process_ownership
+
+
+def multiplexed(tmp_path, monkeypatch):
+ """``(runner, beta_home)``: a multiplexed runner serving the default profile and ``beta``."""
+ from gateway import run
+ monkeypatch.setattr(run, '_load_gateway_config', lambda *a: {
+ 'platform_toolsets': {'cli': [], 'tui': []},
+ 'model': {'provider': 'custom', 'base_url': 'http://127.0.0.1:9/v1', 'api_key': 'test-key'}})
+ root = tmp_path / '.hermes'
+ root.mkdir(mode=0o700)
+ monkeypatch.setattr(Path, 'home', lambda: tmp_path)
+ monkeypatch.setenv('HERMES_HOME', str(root))
+ import hermes_state
+ monkeypatch.setattr(hermes_state, 'DEFAULT_DB_PATH', hermes_state._IMPORT_DEFAULT_DB_PATH)
+ beta = root / 'profiles' / 'beta'
+ beta.mkdir(parents=True, mode=0o700)
+ (beta / 'config.yaml').write_text('{}')
+ homes = [('default', root), ('beta', beta)]
+ config = GatewayConfig()
+ config.multiplex_profiles = True
+ config._runtime_profile_homes = tuple(homes)
+ runner = GatewayRunner(config)
+ process_ownership.reserve([home for _, home in homes])
+ yield runner, beta.resolve()
+ for authority in list(getattr(runner, 'session_authorities', None) or []):
+ if authority is not None:
+ authority.db.close()
+ for _, home in homes:
+ process_ownership.release(home)
+
+
+async def _boot_with_beta_parked(runner, beta, monkeypatch):
+ """Boot's API start with beta's startup Bot recovery failing once: beta is parked."""
+ from gateway import session_bot
+ from gateway.run_runtime import parked_profile_map, start_gateway_runtime_api
+ real, failed = session_bot.recover_bot_deliveries, []
+
+ async def recover_once_failing(authority):
+ if Path(authority.profile_id).resolve() == beta and not failed:
+ failed.append(authority)
+ raise OSError('mailbox write failed')
+ return await real(authority)
+
+ async def api(_runner):
+ return SimpleNamespace(api_origin='http://127.0.0.1:1')
+
+ monkeypatch.setattr(session_bot, 'recover_bot_deliveries', recover_once_failing)
+ monkeypatch.setattr('gateway.run_api.start_gateway_api', api)
+ await start_gateway_runtime_api(runner)
+ assert 'beta' in parked_profile_map(runner)
+
+
+async def _rescan(runner, beta, monkeypatch, connected=None):
+ """The control-socket rescan serves beta again (its adapters connect without a network)."""
+ async def start_adapters(name, home, claimed):
+ if connected is not None:
+ connected.append(name)
+ return 0
+
+ async def nothing(*_a, **_k):
+ return None
+
+ monkeypatch.setattr(runner, '_start_one_profile_adapters', start_adapters)
+ monkeypatch.setattr(runner, '_after_profiles_added', nothing)
+ result = await runner._apply_profile_changes({}, ['beta'], [], [], reason='control-socket',
+ live={'beta': beta})
+ assert result['added'] == ['beta'], result
+ return runner.session_authorities.for_home(beta)
+
+
+def _actor(authority):
+ from gateway.session_controls import AuthorityConnection
+ return AuthorityConnection(authority, object(), {'user_id': 'human'}).actor
+
+
+async def test_local_sessions_work_after_the_rescan(multiplexed, tmp_path, monkeypatch):
+ from gateway.run_runtime import initialize_gateway_runtime
+ from gateway.session_authorities import owner_scope
+ from gateway.session_local import create_local_session
+ from gateway.session_local_recovery import restore_local_session
+ runner, beta = multiplexed
+ await initialize_gateway_runtime(runner)
+ first = runner.session_authorities.for_home(beta)
+ params = dict(source='tui', cwd=str(tmp_path), model='m', toolsets=[])
+ with owner_scope(first):
+ existing = create_local_session(first, _actor(first), dict(params, request_id='before-park'))
+ await _boot_with_beta_parked(runner, beta, monkeypatch)
+ served = await _rescan(runner, beta, monkeypatch)
+ assert served is not first
+ with owner_scope(served):
+ restore_local_session(served, existing.session_id)
+ create_local_session(served, _actor(served), dict(params, request_id='after-rescan'))
+
+
+async def test_api_work_queued_before_the_park_is_recovered_by_the_rescan(multiplexed, monkeypatch):
+ from gateway.run_runtime import initialize_gateway_runtime
+ from gateway.session_api import bind_api_session
+ from gateway.session_authority import SessionAuthority
+ from hermes_state_runtime import admit_session_input
+ runner, beta = multiplexed
+ api = SimpleNamespace(gateway_runner=runner)
+ runner.adapters[Platform.API_SERVER] = api # the launch API adapter is already published
+ monkeypatch.setattr(runner, '_adapter_for_source', lambda source: api)
+ scheduled = []
+ monkeypatch.setattr(SessionAuthority, '_schedule',
+ lambda self, ref: scheduled.append((Path(self.profile_id).name, ref.session_id)))
+ await initialize_gateway_runtime(runner)
+ first = runner.session_authorities.for_home(beta)
+ ref = bind_api_session(first, 'api-queued')
+ admit_session_input(first.db, epoch=first.epoch, principal_id='api', session_id=ref.session_id,
+ request_id='chat:scope:queued',
+ payload={'text': 'do the queued work', 'api_turn_v1': {'history': [], 'settings': {}}})
+ await _boot_with_beta_parked(runner, beta, monkeypatch)
+ await _rescan(runner, beta, monkeypatch)
+ # A cold boot schedules it when the API adapter is published (recover_api_turns).
+ assert ('beta', 'api-queued') in scheduled, f'not scheduled after the rescan: {scheduled}'
+
+
+async def test_native_recovery_runs_once_the_rescanned_adapters_connect(multiplexed, monkeypatch):
+ """Boot recovers queued native rows after the adapters connect
+ (``recover_gateway_native_sessions``); the rescan runs the same step for the served profile."""
+ from gateway.run_runtime import initialize_gateway_runtime
+ from gateway.session_authority import SessionAuthority
+ runner, beta = multiplexed
+ connected, recovered = [], []
+ real = SessionAuthority.recover_native_sessions
+
+ async def record(self, bindings):
+ recovered.append((Path(self.profile_id).name, list(connected)))
+ return await real(self, bindings)
+
+ monkeypatch.setattr(SessionAuthority, 'recover_native_sessions', record)
+ await initialize_gateway_runtime(runner)
+ await _boot_with_beta_parked(runner, beta, monkeypatch)
+ await _rescan(runner, beta, monkeypatch, connected)
+ assert recovered == [('beta', ['beta'])], f'native recovery after the rescan: {recovered}'