Skip to content

The agent that grows with you

fix(gateway): park a profile whose startup Bot recovery fails

unsupportedpastels1caa071b3841
diff --git a/gateway/run_runtime.py b/gateway/run_runtime.py
index 0c2f4812ef7..cd054f80ef8 100644
--- a/gateway/run_runtime.py
+++ b/gateway/run_runtime.py
@@ -174,11 +174,17 @@ def release_profile_home(runner, home):
registry = getattr(runner, 'session_authorities', None)
if registry is not None and registry.for_home(home) is not None:
raise RuntimeError('Profile authority must retire before ownership is released')
+ _withdraw_profile_home(runner, home)
+ process_ownership.release(home)
+
+
+def _withdraw_profile_home(runner, home):
+ """Drop *home* from the served set every startup consumer reads (adapters, served status, cron
+ ticks, ingress, spool recovery) without releasing its ``gateway.lock``."""
reserved = getattr(runner.config, '_runtime_profile_homes', None)
if reserved is not None:
runner.config._runtime_profile_homes = tuple(
entry for entry in reserved if Path(entry[1]).resolve() != home)
- process_ownership.release(home)
def _authority_tasks(authority):
@@ -379,12 +385,39 @@ async def recover_bot_mailbox(authority):
async def start_gateway_runtime_api(runner):
from gateway.run_api import start_gateway_api
- from gateway.session_authorities import owner_scope
runner.session_api = await start_gateway_api(runner)
runner.session_runtime_descriptor['api_origin'] = runner.session_api.api_origin
for authority in _authorities(runner):
+ await _recover_profile_bot_mailbox(runner, authority)
+
+
+async def _recover_profile_bot_mailbox(runner, authority):
+ """Startup Bot Chat recovery of one served profile. A secondary whose durable leftovers cannot
+ be recovered is parked like one whose store cannot be opened (retired, unreserved, named under
+ ``parked_profiles``): under multiplex it would otherwise take every other profile down with it,
+ on every restart (#140018). The launch profile's failure still aborts the start."""
+ from gateway.session_authorities import owner_scope
+ try:
with owner_scope(authority):
await recover_bot_mailbox(authority)
+ except Exception as exc:
+ registry = getattr(runner, 'session_authorities', None)
+ name = None if registry is None else registry.profile_name(authority)
+ if name is None:
+ raise # the launch profile's store is the process's own; nothing to park it behind
+ logger.error("[MULTIPLEX] Profile '%s' not served: startup recovery failed: %s", name, exc,
+ exc_info=True)
+ home = await asyncio.to_thread(Path(authority.profile_id).resolve)
+ if not await _retire_profile_authority(authority):
+ # A writer outlived Stop: the lock and the retiring authority stay for shutdown to
+ # settle, but the profile leaves the served set, so later boot never starts it.
+ _withdraw_profile_home(runner, home)
+ park_profile(runner, name, f'startup recovery failed; ownership retained: {exc}')
+ return
+ registry.remove(home)
+ _publish_served_set(runner)
+ release_profile_home(runner, home)
+ park_profile(runner, name, f'startup recovery failed: {exc}')
async def recover_gateway_native_sessions(runner):
@@ -394,8 +427,8 @@ async def recover_gateway_native_sessions(runner):
transport. The authority preflights every queued sender before any claim.
"""
import logging
- from gateway.session_authorities import owner_scope
- authorities = _authorities(runner)
+ from gateway.session_authorities import owner_scope, serving_authorities
+ authorities = serving_authorities(runner)
if not authorities:
return {}
from gateway.session_hosted_service import ensure_hosted_service
diff --git a/gateway/run_startup.py b/gateway/run_startup.py
index b244ef7167d..24b69c142c8 100644
--- a/gateway/run_startup.py
+++ b/gateway/run_startup.py
@@ -37,6 +37,23 @@ from typing import Any, Dict, Optional, Tuple
logger = logging.getLogger("gateway.run")
+def _holds_admission(authority, session_id) -> bool:
+ """Whether *authority*'s store holds a canonical admission for *session_id*. A parked profile's
+ retained (retiring) store that cannot answer counts as holding one: auto-resume fails closed
+ for that entry instead of stopping the boot or resuming a turn that FIFO may own."""
+ from gateway.session_authorities import admission_owner
+ try:
+ return bool(authority.db._read_one(
+ 'SELECT 1 FROM session_admissions WHERE target_session_id IN (?,?) LIMIT 1',
+ (session_id, admission_owner(authority, session_id))))
+ except Exception as exc:
+ if not getattr(authority, 'retiring', False):
+ raise
+ logger.warning("Skipping auto-resume of %s: retained store %s cannot answer: %s",
+ session_id, getattr(authority, 'profile_id', '?'), exc)
+ return True
+
+
def recover_left_core_in(home: Path, *, hydrate_secrets: bool = True) -> None:
"""Install the catalog plugin of every feature that left core (Home Assistant) *home* uses, in
*home*'s runtime scope (its config, secrets and allow_lazy_installs); once per process per home.
@@ -613,11 +630,8 @@ class GatewayStartupMixin:
for entry in candidates:
# Canonical admissions own restart decisions, including unknown pauses.
# Legacy synthetic resume must not race their restored FIFO.
- from gateway.session_authorities import admission_owner, all_authorities
- if any(authority.db._read_one(
- 'SELECT 1 FROM session_admissions WHERE target_session_id IN (?,?) LIMIT 1',
- (entry.session_id, admission_owner(authority, entry.session_id)))
- for authority in all_authorities(self)):
+ from gateway.session_authorities import all_authorities
+ if any(_holds_admission(authority, entry.session_id) for authority in all_authorities(self)):
continue
# Epoch math: the marker was stamped naive-local by the previous process, possibly
# on the other side of a DST change; wall-clock subtraction is off by the shift.
diff --git a/gateway/session_api_turn.py b/gateway/session_api_turn.py
index c3587cf5962..448f0e29340 100644
--- a/gateway/session_api_turn.py
+++ b/gateway/session_api_turn.py
@@ -303,9 +303,10 @@ def owns_api_run(adapter, run_id, owner_scope):
def recover_api_turns(adapter):
- """Recover committed work only after the real API adapter is published."""
- from gateway.session_authorities import all_authorities, owner_scope
- for authority in all_authorities(adapter.gateway_runner):
+ """Recover committed work only after the real API adapter is published. A parked profile's
+ retained (retiring) authority is not served: its store is never read here."""
+ from gateway.session_authorities import owner_scope, serving_authorities
+ for authority in serving_authorities(adapter.gateway_runner):
# 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):
diff --git a/gateway/session_authorities.py b/gateway/session_authorities.py
index 54e713ef48a..69976f62499 100644
--- a/gateway/session_authorities.py
+++ b/gateway/session_authorities.py
@@ -192,6 +192,12 @@ def all_authorities(runner):
return [authority] if authority is not None else []
+def serving_authorities(runner):
+ """``all_authorities`` minus retiring ones: what startup recovery and service creation cover.
+ Shutdown keeps ``all_authorities``, so a retained authority's live writer is still settled."""
+ return [a for a in all_authorities(runner) if not getattr(a, 'retiring', False)]
+
+
def require_serving(authority):
"""Refuse a verb reached through a stale connection to a retired authority: its ownership is
released, and until a successor bumps the epoch its own epoch still passes the store fence."""
diff --git a/gateway/session_hosted_service.py b/gateway/session_hosted_service.py
index aee215434ad..c8f515c088f 100644
--- a/gateway/session_hosted_service.py
+++ b/gateway/session_hosted_service.py
@@ -4,7 +4,7 @@ from contextlib import nullcontext
from pathlib import Path
from gateway.session_contract import Principal
-from gateway.session_authorities import active_authority, all_authorities, owner_scope
+from gateway.session_authorities import active_authority, all_authorities, owner_scope, serving_authorities
from gateway.session_hosted_controls import HostedControls
from hermes_state_runtime import RuntimeStoreError, _epoch
from tui_gateway.hosted_room_service import HostedRoomService
@@ -237,7 +237,7 @@ async def ensure_hosted_service(runner):
active = active_authority(runner)
if active is None:
raise RuntimeStoreError('profile_mismatch')
- for authority in all_authorities(runner):
+ for authority in serving_authorities(runner):
await _ensure_hosted_service(runner, authority)
start_ready_hosted_services(runner)
return active.hosted_room_service
@@ -262,7 +262,7 @@ def start_ready_hosted_services(runner):
if (getattr(runner, 'session_runtime_descriptor', {}).get('state') != 'ready'
or getattr(runner, '_draining', False)):
return
- services = [getattr(authority, 'hosted_room_service', None) for authority in all_authorities(runner)]
+ services = [getattr(authority, 'hosted_room_service', None) for authority in serving_authorities(runner)]
if any(service is None or not getattr(service, '_transport_installed', False) for service in services):
return
for service in services:
diff --git a/tests/gateway/test_startup_recovery_parks_profile.py b/tests/gateway/test_startup_recovery_parks_profile.py
new file mode 100644
index 00000000000..9e793d22c76
--- /dev/null
+++ b/tests/gateway/test_startup_recovery_parks_profile.py
@@ -0,0 +1,195 @@
+"""Startup Bot Chat recovery of one served profile can never stop the gateway: a secondary whose
+durable leftovers cannot be recovered is parked like one whose store cannot be opened, and every
+other profile still starts (#140018)."""
+from __future__ import annotations
+
+import asyncio
+import sqlite3
+from contextlib import closing, contextmanager
+from types import SimpleNamespace
+
+import pytest
+
+from gateway import run_runtime
+from gateway.config import Platform
+
+
+def _runtime(tmp_path, monkeypatch, failing):
+ from gateway.session_authorities import SessionAuthorities
+ launch = (tmp_path / "root").resolve()
+ homes = {n: (tmp_path / "profiles" / n).resolve() for n in ("beta", "gamma")}
+ for home in (launch, *homes.values()):
+ home.mkdir(parents=True)
+ registry = SessionAuthorities(launch, multiplexed=True)
+ runner = SimpleNamespace(
+ session_authorities=registry, session_control_server=None, _running_agents={},
+ config=SimpleNamespace(multiplex_profiles=True, _runtime_profile_homes=tuple(homes.items())),
+ session_runtime_descriptor={"served_profiles": []},
+ session_ticket_store=SimpleNamespace(profile_ids=frozenset()),
+ session_store=SimpleNamespace(list_sessions=list))
+
+ async def no_native_sessions(bindings):
+ return {}
+
+ for name, home in (("default", launch), *homes.items()):
+ registry.add(home, SimpleNamespace(runner=runner, profile_id=str(home), sessions={}, pending_stops={},
+ adopted={}, retiring=False, hosted_room_service=None,
+ waiters={}, native_waiters=set(),
+ db=SimpleNamespace(_read_all=lambda *_a: []),
+ logical_owner=lambda sid: sid,
+ recover_native_sessions=no_native_sessions), name=name)
+ recovered, parked = [], {}
+
+ async def recover_bot(authority):
+ recovered.append(authority.profile_id)
+ if authority.profile_id == str(failing):
+ raise RuntimeError("leftover receipt the store cannot answer")
+
+ async def fake_api(runner_):
+ return SimpleNamespace(api_origin="http://127.0.0.1:1")
+
+ monkeypatch.setattr("gateway.run_api.start_gateway_api", fake_api)
+ monkeypatch.setattr("gateway.session_bot.recover_bot_deliveries", recover_bot)
+ monkeypatch.setattr("gateway.session_cron.unbind_owner", lambda authority: None)
+ monkeypatch.setattr(run_runtime, "_record_parked_profiles", lambda value: parked.update(value))
+ return runner, launch, homes, recovered, parked
+
+
+def test_a_secondary_whose_recovery_fails_is_parked_and_the_rest_start(tmp_path, monkeypatch):
+ from gateway.runtime_ownership import process_ownership
+ runner, launch, homes, recovered, parked = _runtime(tmp_path, monkeypatch, failing=tmp_path / "profiles" / "beta")
+ process_ownership.reserve([homes["beta"]])
+ try:
+ asyncio.run(run_runtime.start_gateway_runtime_api(runner))
+ assert runner.session_runtime_descriptor["api_origin"] == "http://127.0.0.1:1"
+ assert recovered == [str(launch), str(homes["beta"]), str(homes["gamma"])]
+ assert "beta" in parked and "leftover receipt" in parked["beta"]
+ assert runner.session_authorities.for_home(homes["beta"]) is None
+ assert not process_ownership.owns(homes["beta"]), "a parked profile keeps its reservation"
+ assert [n for n, _ in runner.config._runtime_profile_homes] == ["gamma"]
+ served = {p["profile_id"] for p in runner.session_runtime_descriptor["served_profiles"]}
+ assert served == {str(launch), str(homes["gamma"])}
+ finally:
+ process_ownership.release(homes["beta"])
+
+
+def test_a_secondary_whose_retirement_times_out_keeps_its_lock_but_is_never_started(tmp_path, monkeypatch):
+ """A writer that outlives Stop keeps the profile's lock and retiring authority (shutdown still
+ settles it), but nothing later in boot may serve it: no adapters, no served status, no cron
+ ticks, no native-session recovery, no hosted-room service."""
+ from gateway.run import GatewayRunner, _cron_tick_profile_homes
+ from gateway.runtime_ownership import process_ownership
+ from gateway.session_authorities import all_authorities
+ runner, launch, homes, _recovered, parked = _runtime(
+ tmp_path, monkeypatch, failing=tmp_path / "profiles" / "beta")
+ beta = runner.session_authorities.for_home(homes["beta"])
+
+ async def writer_outlives_stop(authority, timeout):
+ raise TimeoutError("Profile workers did not stop; ownership retained")
+
+ monkeypatch.setattr("gateway.session_runtime_workers.join_authority_work", writer_outlives_stop)
+ process_ownership.reserve([homes["beta"]])
+ try:
+ asyncio.run(run_runtime.start_gateway_runtime_api(runner))
+ assert "ownership retained" in parked["beta"]
+ assert process_ownership.owns(homes["beta"]), "the live writer's home lost its lock"
+ assert runner.session_authorities.for_home(homes["beta"]) is beta and beta.retiring
+ assert beta in all_authorities(runner), "shutdown must still settle the retained authority"
+
+ # Adapter startup and the adapter-level served status (the real runner methods).
+ monkeypatch.setenv("HERMES_HOME", str(launch))
+ started, published = [], {}
+ host = object.__new__(GatewayRunner)
+ host.config, host.adapters, host._profile_adapters = runner.config, {}, {}
+ host.pairing_store, host.pairing_stores, host._served_profile_signatures = None, {}, {}
+ host._primary_profile_name = "default"
+
+ async def start_one(name, home, claimed):
+ started.append(name)
+ return 0
+
+ host._start_one_profile_adapters = start_one
+ host._restore_secondary_completion_ledgers = lambda profile_homes: None
+ monkeypatch.setattr("hermes_cli.profiles.profiles_to_serve", lambda *a, **k: [])
+ monkeypatch.setattr("gateway.status.publish_runtime_status", lambda **kw: published.update(kw))
+ monkeypatch.setattr("gateway.pairing.PairingStore", lambda profile: SimpleNamespace(profile=profile))
+ asyncio.run(host._start_secondary_profile_adapters())
+ assert started == ["gamma"]
+ assert published["served_profiles"] == ["default", "gamma"]
+ assert "beta" not in {name for name, _home in _cron_tick_profile_homes(runner.config)}
+
+ # Native-session recovery and hosted-room service creation cover only serving profiles.
+ local, hosted = [], []
+
+ async def ensure_hosted(runner_, authority):
+ hosted.append(authority.profile_id)
+
+ async def no_webhooks(authority):
+ return None
+
+ monkeypatch.setattr("gateway.session_hosted_service._ensure_hosted_service", ensure_hosted)
+ monkeypatch.setattr("gateway.session_local_recovery.recover_local_sessions",
+ lambda authority, schedule=False: local.append(authority.profile_id))
+ monkeypatch.setattr("gateway.platforms.webhook_ingress.recover_webhook_finalizations", no_webhooks)
+ asyncio.run(run_runtime.recover_gateway_native_sessions(runner))
+ assert str(homes["beta"]) not in local
+ assert str(homes["beta"]) not in hosted
+ assert set(local) == set(hosted) == {str(launch), str(homes["gamma"])}
+
+ # The retained store may still fail every read: neither the launch API adapter's
+ # publication (API-turn recovery, the real publish path) nor the startup auto-resume guard
+ # may let that error stop the boot.
+ def unreadable(*_a, **_k):
+ raise sqlite3.OperationalError("disk I/O error")
+
+ @contextmanager
+ def no_admissions():
+ with closing(sqlite3.connect(":memory:")) as conn:
+ conn.execute("CREATE TABLE session_admissions (target_session_id, principal_id, status)")
+ yield conn
+
+ for authority in all_authorities(runner):
+ authority.db._read_ctx = unreadable if authority is beta else no_admissions
+ authority.db._read_one = unreadable if authority is beta else (lambda *_a: None)
+ api_read = []
+
+ def collect(db):
+ if db is beta.db:
+ unreadable()
+ api_read.append(db)
+
+ monkeypatch.setattr("gateway.session_ingress_media.collect_unheld_api_images", collect)
+ monkeypatch.setattr("gateway.session_api_media.compact_settled_api_payloads", lambda db: None)
+ host._sync_voice_mode_state_to_adapter = host._bind_voice_input_callback = lambda adapter: None
+ api_adapter = SimpleNamespace(gateway_runner=runner)
+ try:
+ host._publish_primary_adapter(Platform.API_SERVER, api_adapter)
+ except sqlite3.OperationalError as exc:
+ pytest.fail(f"the retained store's read error stopped API adapter publication: {exc}")
+ assert host.adapters[Platform.API_SERVER] is api_adapter
+ assert api_read == [a.db for a in all_authorities(runner) if a is not beta]
+
+ # Auto-resume fails closed on the retained store: the entry is held back, never resumed.
+ fresh_checks = []
+ monkeypatch.setattr("gateway.run._is_fresh_gateway_interruption",
+ lambda *a, **k: fresh_checks.append(a) or False)
+ host.session_authorities = runner.session_authorities
+ for authority in all_authorities(runner):
+ if authority is not beta:
+ authority.logical_owner = lambda sid: "" # no lineage: the bare id is the owner
+ entry = SimpleNamespace(session_id="s1", session_key="k1", last_resume_marked_at=None, updated_at=None)
+ host._resume_pending_candidates = lambda platform=None: [entry]
+ try:
+ assert host._schedule_resume_pending_sessions() == 0
+ except sqlite3.OperationalError as exc:
+ pytest.fail(f"the retained store's read error stopped startup auto-resume: {exc}")
+ assert fresh_checks == [], "an entry the retained store may own went on toward resume"
+ finally:
+ process_ownership.release(homes["beta"])
+
+
+def test_the_launch_profile_recovery_failure_still_stops_the_start(tmp_path, monkeypatch):
+ runner, _launch, _homes, _recovered, parked = _runtime(tmp_path, monkeypatch, failing=tmp_path / "root")
+ with pytest.raises(RuntimeError, match="leftover receipt"):
+ asyncio.run(run_runtime.start_gateway_runtime_api(runner))
+ assert parked == {}