Skip to content

The agent that grows with you

fix(gateway): hot-serve of a new profile no longer parks it over a client's lock probe

Teknium24479b4529bd
diff --git a/gateway/run_bootstrap.py b/gateway/run_bootstrap.py
index e3d7402583a..3c33404a17e 100644
--- a/gateway/run_bootstrap.py
+++ b/gateway/run_bootstrap.py
@@ -581,53 +581,13 @@ def _browse_reconcile_reserve_wait_s() -> float:
return BROWSE_RECONCILE_BUDGET_S + 2.0
-def _conflicting_homes(homes):
- """The homes whose gateway.lock another holder has right now: each probed alone with its own open
- file description and released at once (the all-or-nothing reserve does not say which failed).
- A home freed meanwhile is simply not listed; the next reserve attempt takes it."""
- from gateway.runtime_ownership import OwnershipConflict, ProfileOwnership
- conflicting = []
- for home in homes:
- probe = ProfileOwnership()
- try:
- probe.reserve([home])
- except OwnershipConflict:
- conflicting.append(home)
- finally:
- probe.close()
- return conflicting
-
-
def _reserve_waiting_out_browse_reconcile(ownership, homes, *, wait_s: float | None = None):
- """Reserve *homes*, waiting (bounded) while a contender is a browse reconcile or has not yet
- published its lock record (flock taken, record unwritten). Only a positively identified holder
- that is not browse maintenance refuses at once; the flock exclusion itself is never weakened."""
- from gateway.runtime_ownership import OwnershipConflict, lock_record_unpublished, maintenance_holder
- from hermes_state_reconcile import BROWSE_RECONCILE_PURPOSE
+ """Boot's all-or-nothing reserve of every served home, waiting out transient holders (a browse
+ reconcile, an unpublished record, a client's lock probe) for up to the browse window."""
+ from gateway.runtime_ownership import reserve_waiting_out_transient_holders
if wait_s is None:
wait_s = _browse_reconcile_reserve_wait_s()
- deadline = time.monotonic() + wait_s
- logged = False
- while True:
- try:
- return ownership.reserve(homes)
- except OwnershipConflict:
- # Only the homes that actually conflict decide: a real owner on any of them refuses at
- # once, even while another home is mid-browse (multiplexer boot, all-or-nothing).
- conflicting = _conflicting_homes(homes)
- holders = [h for h in conflicting
- if maintenance_holder(h, BROWSE_RECONCILE_PURPOSE) or lock_record_unpublished(h)]
- if len(holders) < len(conflicting) or time.monotonic() >= deadline:
- raise
- if not conflicting:
- # The holder let go before the re-probe: a client's liveness probe
- # (gateway.status._probe_lock_file takes the flock for an instant), never an owner.
- continue
- if not logged:
- logger.info("Profile %s is held by a short session-store schema catch-up; waiting up to %.0fs",
- holders[0], wait_s)
- logged = True
- time.sleep(0.1)
+ return reserve_waiting_out_transient_holders(ownership, homes, wait_s=wait_s)
def _start_gateway_reserve_profiles(profile_homes) -> bool:
diff --git a/gateway/run_profile_reconcile.py b/gateway/run_profile_reconcile.py
index 3b13eba5378..59753a5c212 100644
--- a/gateway/run_profile_reconcile.py
+++ b/gateway/run_profile_reconcile.py
@@ -407,7 +407,7 @@ class GatewayProfileReconcileMixin:
from gateway.run_runtime import release_profile_home, reserve_profile_home, serve_profile_runtime
from gateway.runtime_ownership import OwnershipConflict
try:
- reserve_profile_home(self, name, home)
+ await asyncio.to_thread(reserve_profile_home, self, name, home)
except (OwnershipConflict, OSError) as exc:
logger.error("[MULTIPLEX] Profile '%s' not served: %s", name, exc)
return f"home owned by another gateway: {exc}"
diff --git a/gateway/run_runtime.py b/gateway/run_runtime.py
index b741c0769b5..527c8867980 100644
--- a/gateway/run_runtime.py
+++ b/gateway/run_runtime.py
@@ -235,10 +235,13 @@ def _publish_served_set(runner):
def reserve_profile_home(runner, name, home):
"""Grow the process reservation by one profile (hot-serve): take its ``gateway.lock`` and add it
to the frozen boot set, so every reader of the reservation — and the next restart's
- all-or-nothing reserve — sees it. ``OwnershipConflict`` when another gateway owns the home."""
- from gateway.runtime_ownership import process_ownership
+ all-or-nothing reserve — sees it. Waits out a transient holder within boot's window (blocking:
+ callers on the event loop run it in a worker thread). ``OwnershipConflict`` when another
+ gateway owns the home."""
+ from gateway.run_bootstrap import _browse_reconcile_reserve_wait_s
+ from gateway.runtime_ownership import process_ownership, reserve_waiting_out_transient_holders
home = Path(home).resolve()
- process_ownership.reserve([home])
+ reserve_waiting_out_transient_holders(process_ownership, [home], wait_s=_browse_reconcile_reserve_wait_s())
reserved = getattr(runner.config, '_runtime_profile_homes', None)
if reserved is not None and all(Path(h).resolve() != home for _n, h in reserved):
runner.config._runtime_profile_homes = (*reserved, (name, home))
diff --git a/gateway/runtime_ownership.py b/gateway/runtime_ownership.py
index fbd44864385..00ae835a31a 100644
--- a/gateway/runtime_ownership.py
+++ b/gateway/runtime_ownership.py
@@ -9,12 +9,16 @@ from __future__ import annotations
from contextlib import contextmanager
import json
+import logging
import os
from pathlib import Path
import stat
import threading
+import time
from hermes_dir_acl import make_user_dir
+logger = logging.getLogger(__name__)
+
class OwnershipConflict(RuntimeError):
pass
@@ -241,6 +245,58 @@ def lock_record_unpublished(home: Path) -> bool:
return not record or _live_pid_from_record(record) in (None, os.getpid())
+# A client's discovery probe (gateway.status._probe_lock_file) holds a gateway.lock flock for an
+# instant; the next attempt after this pause normally finds it gone.
+PROBE_RETRY_BACKOFF_S = 0.015
+TRANSIENT_HOLDER_POLL_S = 0.1
+
+
+def _conflicting_homes(homes):
+ """The homes whose gateway.lock another holder has right now: each probed alone with its own open
+ file description and released at once (the all-or-nothing reserve does not say which failed).
+ A home freed meanwhile is simply not listed; the next reserve attempt takes it."""
+ conflicting = []
+ for home in homes:
+ probe = ProfileOwnership()
+ try:
+ probe.reserve([home])
+ except OwnershipConflict:
+ conflicting.append(home)
+ finally:
+ probe.close()
+ return conflicting
+
+
+def reserve_waiting_out_transient_holders(ownership, homes, *, wait_s: float) -> None:
+ """``ownership.reserve(homes)``, retried until *wait_s* passes while every contender is
+ transient: a client's lock probe (gone by the re-check), a browse reconcile, or a holder that has
+ not published its record yet (flock taken, record unwritten). A positively identified live owner
+ on any home refuses at once. Every grant is a real ``reserve``: the flock is never bypassed.
+ Shared by the gateway boot and the running multiplexer's hot-serve of a new profile."""
+ from hermes_state_reconcile import BROWSE_RECONCILE_PURPOSE
+ deadline = time.monotonic() + wait_s
+ logged = False
+ while True:
+ try:
+ return ownership.reserve(homes)
+ except OwnershipConflict:
+ # Only the homes that actually conflict decide: a real owner on any of them refuses at
+ # once, even while another home is mid-browse (multiplexer boot, all-or-nothing).
+ conflicting = _conflicting_homes(homes)
+ holders = [h for h in conflicting
+ if maintenance_holder(h, BROWSE_RECONCILE_PURPOSE) or lock_record_unpublished(h)]
+ if len(holders) < len(conflicting) or time.monotonic() >= deadline:
+ raise
+ if not conflicting:
+ time.sleep(PROBE_RETRY_BACKOFF_S) # the holder already let go: a lock probe, never an owner
+ continue
+ if not logged:
+ logger.info("Profile %s is held by a short session-store schema catch-up; waiting up to %.0fs",
+ holders[0], wait_s)
+ logged = True
+ time.sleep(TRANSIENT_HOLDER_POLL_S)
+
+
def live_runtime_owner(home: Path) -> int | None:
"""PID of a live runtime owner of *home* (a gateway, or a reservation that is not marked as
maintenance), else None. A purpose-marked maintenance holder is never an owner."""
diff --git a/tests/gateway/test_boot_reserve_lock_probe.py b/tests/gateway/test_boot_reserve_lock_probe.py
index 7d67827dd25..99aca55df3d 100644
--- a/tests/gateway/test_boot_reserve_lock_probe.py
+++ b/tests/gateway/test_boot_reserve_lock_probe.py
@@ -6,13 +6,20 @@ non-blocking boot reserve lands in that instant used to exit 1 with ``Cannot res
profiles``, so the very client that started it read ``runtime_exited``. These tests hold a real
flock exactly where a probe holds it and boot through the real reserve.
"""
+import asyncio
+from contextlib import contextmanager
import fcntl
from pathlib import Path
+import subprocess
+import sys
+import time
+from types import SimpleNamespace
import pytest
-from gateway.run_bootstrap import _reserve_waiting_out_browse_reconcile
-from gateway.runtime_ownership import OwnershipConflict, ProfileOwnership
+from gateway.run_bootstrap import _browse_reconcile_reserve_wait_s, _reserve_waiting_out_browse_reconcile
+from gateway.run_profile_reconcile import GatewayProfileReconcileMixin
+from gateway.runtime_ownership import OwnershipConflict, ProfileOwnership, process_ownership
pytestmark = pytest.mark.platforms("linux", "macos")
@@ -88,28 +95,127 @@ def test_boot_reserve_survives_a_probe_during_the_recheck(tmp_path):
handle.close()
+_HOLDER = """
+import fcntl, sys
+from pathlib import Path
+sys.path.insert(0, sys.argv[3])
+home = Path(sys.argv[2])
+if sys.argv[1] == "owner":
+ from gateway.runtime_ownership import ProfileOwnership
+ owner = ProfileOwnership()
+ owner.reserve([home])
+else: # what _probe_lock_file holds: the flock on its own description, no record written
+ handle = open(home / "gateway.lock", "r+", encoding="utf-8")
+ fcntl.flock(handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
+print("held", flush=True)
+if sys.stdin.readline().strip() == "release" and sys.argv[1] == "probe":
+ fcntl.flock(handle.fileno(), fcntl.LOCK_UN)
+ print("released", flush=True)
+sys.stdin.readline()
+"""
+
+
+@contextmanager
+def _holder(kind, home):
+ """A separate process holding *home*'s flock as a client probe (``probe``) or a gateway
+ (``owner``, its record naming that live process)."""
+ proc = subprocess.Popen([sys.executable, "-c", _HOLDER, kind, str(home), str(Path(__file__).resolve().parents[2])],
+ stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True)
+ try:
+ assert proc.stdout.readline().strip() == "held"
+ yield proc
+ finally:
+ proc.kill()
+ proc.wait()
+
+
+def _release(proc):
+ proc.stdin.write("release\n")
+ proc.stdin.flush()
+ assert proc.stdout.readline().strip() == "released"
+
+
def test_a_live_foreign_owner_still_refuses_at_once(tmp_path):
"""Control: a holder whose record names another live process is an owner, not a probe."""
- import subprocess
- import sys
- import time
-
root, boot = _homes(tmp_path)
- holder = subprocess.Popen(
- [sys.executable, "-c",
- "import sys; sys.path.insert(0, sys.argv[2]); from pathlib import Path; import time\n"
- "from gateway.runtime_ownership import ProfileOwnership\n"
- "owner = ProfileOwnership(); owner.reserve([Path(sys.argv[1])]); print('held', flush=True); time.sleep(30)",
- str(boot), str(Path(__file__).resolve().parents[2])],
- stdout=subprocess.PIPE, text=True)
- try:
- assert holder.stdout is not None and holder.stdout.readline().strip() == "held"
+ wait_s = 10
+ with _holder("owner", boot):
booting = ProfileOwnership()
started = time.monotonic()
with pytest.raises(OwnershipConflict):
- _reserve_waiting_out_browse_reconcile(booting, [root, boot], wait_s=10)
- assert time.monotonic() - started < 2
+ _reserve_waiting_out_browse_reconcile(booting, [root, boot], wait_s=wait_s)
+ assert time.monotonic() - started < wait_s / 2
assert not booting.owns(root)
- finally:
- holder.kill()
- holder.wait()
+
+
+def test_a_persistent_probe_flicker_still_refuses_at_the_deadline(tmp_path):
+ """A probe that is back on every attempt is retried with a backoff, never spun on, and the
+ reserve still refuses once the deadline passes."""
+ root, boot = _homes(tmp_path)
+ wait_s = 0.3
+
+ class AlwaysProbed(ProfileOwnership):
+ refused_at = []
+ gaps = []
+
+ def reserve(self, homes, **kwargs):
+ if self.refused_at:
+ self.gaps.append(time.monotonic() - self.refused_at[-1])
+ try:
+ with _probe_hold(boot):
+ return super().reserve(homes, **kwargs)
+ finally:
+ self.refused_at.append(time.monotonic())
+
+ booting = AlwaysProbed()
+ started = time.monotonic()
+ with pytest.raises(OwnershipConflict):
+ _reserve_waiting_out_browse_reconcile(booting, [root, boot], wait_s=wait_s)
+ assert time.monotonic() - started >= wait_s
+ assert booting.gaps and min(booting.gaps) >= 0.01, booting.gaps # backed off, never spun
+ assert not booting.owns(root)
+
+
+class _HotServeRunner(GatewayProfileReconcileMixin):
+ """An adapters-only multiplexer (no authority registry): serving grows the reservation alone."""
+ session_authorities = None
+
+ def __init__(self, root):
+ self.config = SimpleNamespace(_runtime_profile_homes=(("default", root),))
+
+
+def test_hot_serve_of_a_new_profile_survives_a_probe(tmp_path, monkeypatch):
+ """A client probe on a new profile's lock while the running multiplexer serves it: the profile
+ is served, not parked as owned by another gateway."""
+ root, fresh = _homes(tmp_path)
+ attempts = []
+ with _holder("probe", fresh) as probe:
+ def reserve(homes, **kwargs):
+ attempts.append(homes)
+ try:
+ return ProfileOwnership.reserve(process_ownership, homes, **kwargs)
+ except OwnershipConflict:
+ _release(probe) # the probe lets go before the re-check, as _probe_lock_file does
+ raise
+
+ monkeypatch.setattr(process_ownership, "reserve", reserve)
+ runner = _HotServeRunner(root)
+ try:
+ assert asyncio.run(runner._serve_profile_runtime("boot", fresh)) is None
+ assert process_ownership.owns(fresh) and len(attempts) == 2
+ assert ("boot", fresh.resolve()) in runner.config._runtime_profile_homes
+ finally:
+ process_ownership.release(fresh)
+
+
+def test_hot_serve_still_parks_a_profile_another_gateway_owns(tmp_path):
+ """Control: a live gateway on the new profile's home parks it at once."""
+ root, fresh = _homes(tmp_path)
+ runner = _HotServeRunner(root)
+ with _holder("owner", fresh):
+ started = time.monotonic()
+ reason = asyncio.run(runner._serve_profile_runtime("boot", fresh))
+ assert reason and reason.startswith("home owned by another gateway")
+ assert time.monotonic() - started < _browse_reconcile_reserve_wait_s() / 2
+ assert not process_ownership.owns(fresh)
+ assert runner.config._runtime_profile_homes == (("default", root),)