Skip to content

The agent that grows with you

fix(gateway): a failed hot-serve whose writer outlives Stop parks the profile, never re-adopts it

Teknium2250bda4fb8a
diff --git a/gateway/run_profile_reconcile.py b/gateway/run_profile_reconcile.py
index fdb0957f403..0aaea9ae043 100644
--- a/gateway/run_profile_reconcile.py
+++ b/gateway/run_profile_reconcile.py
@@ -261,7 +261,7 @@ class GatewayProfileReconcileMixin:
from gateway.run_runtime import parked_profile_map
return list(parked_profile_map(self))
- async def _serve_profile_runtime(self, name: str, home: "Path") -> Optional[str]:
+ async def _serve_profile_runtime(self, name: str, home: Path) -> Optional[str]:
"""Grow the reservation by *home* and build its session authority (boot's per-secondary
steps). Returns the park reason — reservation released — when another gateway owns the home
(a stray per-profile daemon) or its store cannot be opened; None when served. An
@@ -278,6 +278,13 @@ class GatewayProfileReconcileMixin:
try:
await serve_profile_runtime(self, name, home)
except Exception as exc:
+ if self.session_authorities.for_home(home) is not None:
+ # Retirement of the failed attempt missed its deadline: its writer may still use
+ # this home, so the reservation and authority stay; the profile is parked (no
+ # adapters) and the batch goes on for every other profile.
+ logger.error("[MULTIPLEX] Profile '%s' not served (%s); a turn outlived its Stop, "
+ "ownership retained", name, exc, exc_info=True)
+ return f"stopping after a failed serve; ownership retained: {exc}"
logger.error("[MULTIPLEX] Profile '%s' not served: its session store is unusable (%s): %s",
name, home, exc, exc_info=True)
release_profile_home(self, home)
diff --git a/gateway/run_runtime.py b/gateway/run_runtime.py
index 440f5c97a07..8d93c587e76 100644
--- a/gateway/run_runtime.py
+++ b/gateway/run_runtime.py
@@ -242,7 +242,7 @@ def stop_managed_turns(runner):
return sum(stop_authority_turns(authority) for authority in _authorities(runner))
-async def _retire_profile_authority(authority):
+async def _retire_profile_authority(authority, timeout=None):
"""Stop profile-local services and turns before its ownership is released.
Claims are refused from here on; every executing turn gets a cooperative Stop, and its session
@@ -250,11 +250,11 @@ async def _retire_profile_authority(authority):
admission settled). The hosted-room stop runs alongside that join under the same deadline: it
never interrupts accepted turns and its room threads wait for the member turns they observe, so
those turns must be signalled first or the room stop cannot finish. False when a turn or room
- thread misses TURN_SETTLE_SECONDS: it may still call tools and write history, so the
- caller must keep the profile's reservation and store handles."""
+ thread misses *timeout* (default TURN_SETTLE_SECONDS): it may still call tools and write
+ history, so the caller must keep the profile's reservation and store handles."""
from gateway.session_cron import unbind_owner
from gateway.session_runtime_workers import join_authority_work, stop_authority_work
- timeout = TURN_SETTLE_SECONDS
+ timeout = TURN_SETTLE_SECONDS if timeout is None else timeout
authority.retiring = True
stop_authority_work(authority)
service = getattr(authority, 'hosted_room_service', None)
@@ -280,6 +280,10 @@ async def _retire_profile_authority(authority):
return True
+class ProfileOwnershipRetained(RuntimeError):
+ """A retired attempt's writer is still live: the profile keeps its reservation and authority."""
+
+
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
@@ -291,8 +295,16 @@ async def serve_profile_runtime(runner, name, home):
from gateway.platforms.webhook_ingress import recover_webhook_finalizations
home = await asyncio.to_thread(Path(home).resolve)
registry = runner.session_authorities
- if registry.for_home(home) is not None:
- return registry.for_home(home)
+ existing = registry.for_home(home)
+ if existing is not None and getattr(existing, 'retiring', False):
+ # An earlier failed attempt kept this authority because its writer outlived Stop. It refuses
+ # every admission, so serving it would start adapters on a dead profile: finish its
+ # retirement without waiting, or refuse (the caller parks and keeps the reservation).
+ if not await _retire_profile_authority(existing, timeout=0):
+ raise ProfileOwnershipRetained(f'an earlier serve of {home} is still stopping')
+ registry.remove(home)
+ elif existing is not None:
+ return existing
authority = await _build_profile_authority(runner, name, home, register=False)
try:
with owner_scope(authority):
diff --git a/tests/gateway/test_run_runtime_hot_serve_cleanup.py b/tests/gateway/test_run_runtime_hot_serve_cleanup.py
index 39280faca40..46bcd24b863 100644
--- a/tests/gateway/test_run_runtime_hot_serve_cleanup.py
+++ b/tests/gateway/test_run_runtime_hot_serve_cleanup.py
@@ -156,3 +156,79 @@ async def test_settle_gateway_runtime_waits_for_bot_receipt_tasks():
assert task.done()
assert finished.is_set()
+
+
+async def test_failed_hot_serve_with_a_live_writer_parks_without_aborting_or_re_adopting(monkeypatch, tmp_path):
+ """A serve-time failure whose retirement misses its deadline keeps the reservation and the
+ retiring authority, parks the profile without adapters, lets the rest of the batch serve, and
+ is never handed back as served by the next reconcile."""
+ from gateway.run_profile_reconcile import GatewayProfileReconcileMixin
+ from gateway.runtime_ownership import process_ownership
+ from gateway.session_authorities import SessionAuthorities
+
+ launch = tmp_path / "root"
+ 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)
+ writer = asyncio.create_task(asyncio.Event().wait()) # a turn that outlives its Stop
+ started, parked = [], {}
+ runner = SimpleNamespace(
+ session_authorities=registry, session_control_server=None, _running_agents={},
+ config=SimpleNamespace(multiplex_profiles=False, _runtime_profile_homes=()),
+ session_runtime_descriptor={"served_profiles": []},
+ session_ticket_store=SimpleNamespace(profile_ids=frozenset()),
+ _served_profile_homes={}, _served_profile_signatures={},
+ _live_resource_claims=lambda active: {}, _record_served_profiles=lambda active, homes: None)
+ runner.served_profile_names = lambda: sorted(runner._served_profile_homes)
+ runner._serve_profile_runtime = GatewayProfileReconcileMixin._serve_profile_runtime.__get__(runner)
+
+ async def start_adapters(name, home, claimed):
+ started.append(name)
+ return 0
+
+ async def after_added(profile_homes):
+ return None
+
+ runner._start_one_profile_adapters, runner._after_profiles_added = start_adapters, after_added
+
+ async def build(runner_, name, home, *, register):
+ live = SimpleNamespace(task=writer if name == "beta" else None, route=name,
+ event_stream=SimpleNamespace(execution={"execution_generation": 1}))
+ authority = SimpleNamespace(runner=runner_, profile_id=str(home), sessions={"s": live},
+ pending_stops={}, retiring=False, hosted_room_service=None)
+ registry.add(home, authority, name=name)
+ return authority
+
+ async def recover_bot(authority):
+ if authority.sessions["s"].task is writer:
+ raise RuntimeError("serve-time recovery failure")
+
+ async def no_webhooks(authority):
+ return None
+
+ monkeypatch.setattr(run_runtime, "_build_profile_authority", build)
+ monkeypatch.setattr(run_runtime, "TURN_SETTLE_SECONDS", 0.05)
+ monkeypatch.setattr(run_runtime, "_record_parked_profiles", lambda value: parked.update(value))
+ monkeypatch.setattr("gateway.session_bot.recover_bot_deliveries", recover_bot)
+ monkeypatch.setattr("gateway.session_local_recovery.recover_local_sessions", lambda a, schedule: None)
+ monkeypatch.setattr("gateway.platforms.webhook_ingress.recover_webhook_finalizations", no_webhooks)
+ monkeypatch.setattr("gateway.session_cron.unbind_owner", lambda authority: None)
+ monkeypatch.setattr("hermes_cli.profiles.profiles_to_serve", lambda **kw: list(homes.items()))
+ try:
+ for attempt in range(2):
+ result = await GatewayProfileReconcileMixin._apply_profile_changes(
+ runner, {}, list(homes) if attempt == 0 else ["beta"], [], [], reason="control-socket",
+ live=dict(homes))
+ assert result["parked"] == ["beta"], result
+ assert "beta" in parked and "beta" not in started, (attempt, started)
+ assert process_ownership.owns(homes["beta"]), "the live writer's home was released"
+ assert registry.for_home(homes["beta"]).retiring is True
+ assert started == ["gamma"], "one profile's failed serve aborted the batch"
+ assert result["served_profiles"] == [] # served_profile_names reads the stubbed record
+ finally:
+ writer.cancel()
+ await asyncio.gather(writer, return_exceptions=True)
+ for home in homes.values():
+ process_ownership.release(home)