Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(model-hub): reap engine processes orphaned by a dead service (#2129)

Call White1f9c65929288
diff --git a/core/process_isolation.py b/core/process_isolation.py
index 16fc2bd6e..34ce4b0a5 100644
--- a/core/process_isolation.py
+++ b/core/process_isolation.py
@@ -42,6 +42,9 @@ class ProcessIdentity:
pid: int
create_time: float
worker_fingerprint: str | None
+ # False when the environment could not be read: the marker is unknown, which
+ # is not the same as absent (``worker_fingerprint`` is then ``None`` too).
+ marker_readable: bool = True
@dataclass(frozen=True)
@@ -95,7 +98,7 @@ def serialize_process_identity(identity: PersistedProcessIdentity) -> dict[str,
}
-def _valid_worker_fingerprint(value: Any) -> bool:
+def is_valid_worker_fingerprint(value: Any) -> bool:
if not isinstance(value, str) or not value.startswith("sha256:") or len(value) != 71:
return False
return all(char in "0123456789abcdef" for char in value[7:])
@@ -130,7 +133,7 @@ def process_identity_from_payload(
or isinstance(create_time, bool)
or not math.isfinite(normalized_create_time)
or normalized_create_time <= 0
- or not _valid_worker_fingerprint(worker_fingerprint)
+ or not is_valid_worker_fingerprint(worker_fingerprint)
):
return None
return PersistedProcessIdentity(
@@ -140,35 +143,56 @@ def process_identity_from_payload(
)
+def _marker_matches(expected: PersistedProcessIdentity, live: ProcessIdentity) -> bool:
+ return live.worker_fingerprint is not None and hmac.compare_digest(
+ expected.worker_fingerprint,
+ live.worker_fingerprint,
+ )
+
+
def process_identity_matches(
expected: PersistedProcessIdentity,
live: ProcessIdentity,
) -> bool:
- return (
- expected.pid == live.pid
- and expected.create_time == live.create_time
- and live.worker_fingerprint is not None
- and hmac.compare_digest(
- expected.worker_fingerprint,
- live.worker_fingerprint,
- )
- )
+ """Whether ``live`` is the recorded process, by its inherited marker.
+
+ The marker is the authority, not the birth time: on macOS psutil's displayed
+ create time can shift while the same execution keeps running (see
+ ``docs/plans/memory-macos-identity-recovery-1990.md``), and a 256-bit marker only
+ the managed tree inherits cannot be carried by a stranger holding a recycled pid.
+ """
+
+ return expected.pid == live.pid and _marker_matches(expected, live)
+
+
+def process_identity_recycled(expected: PersistedProcessIdentity, live: ProcessIdentity) -> bool:
+ """Whether the recorded pid now provably belongs to another process.
+
+ Only a different birth time AND a readable environment without the matching
+ marker says so; a marker match wins over a shifted birth time, and an
+ unreadable marker proves nothing either way.
+ """
+
+ return live.marker_readable and live.create_time != expected.create_time and not _marker_matches(expected, live)
def _open_process_identity(pid: int) -> tuple[psutil.Process, ProcessIdentity]:
process = psutil.Process(pid)
create_time = float(process.create_time())
worker_fingerprint = None
+ marker_readable = True
try:
marker = process.environ().get(PROCESS_IDENTITY_ENV)
except (psutil.Error, OSError):
marker = None
+ marker_readable = False
if isinstance(marker, str) and marker:
worker_fingerprint = fingerprint_process_marker(marker)
return process, ProcessIdentity(
pid=pid,
create_time=create_time,
worker_fingerprint=worker_fingerprint,
+ marker_readable=marker_readable,
)
@@ -386,6 +410,8 @@ def process_group_identity_status(
)
continue
live_identity = inspect_process_identity(pid)
+ if live_identity is not None and _marker_matches(expected_identity, live_identity):
+ return "match"
if (
live_identity is None
or live_identity.create_time < expected_identity.create_time
@@ -394,11 +420,6 @@ def process_group_identity_status(
saw_unverified_member = True
continue
saw_marker = True
- if hmac.compare_digest(
- expected_identity.worker_fingerprint,
- live_identity.worker_fingerprint,
- ):
- return "match"
except Exception:
logger.debug(
"Failed to enumerate %s process group pgid=%s",
@@ -528,7 +549,7 @@ def _terminate_windows_process_tree(
except (psutil.Error, OSError, ValueError):
logger.debug("Failed to revalidate Windows supervisor for %s", label, exc_info=True)
return False
- if live_identity.create_time != expected_identity.create_time:
+ if process_identity_recycled(expected_identity, live_identity):
return True
if not process_identity_matches(expected_identity, live_identity):
logger.warning("Refusing to signal %s because its supervisor marker changed", label)
@@ -602,7 +623,7 @@ def terminate_process_tree_by_pid(
except (psutil.Error, OSError, ValueError):
logger.debug("Failed to inspect %s pid=%s before termination", label, pid, exc_info=True)
return False
- if live_identity.create_time != expected_identity.create_time:
+ if process_identity_recycled(expected_identity, live_identity):
logger.warning("Refusing to terminate %s pid=%s because its process identity changed", label, pid)
return True
if not process_identity_matches(expected_identity, live_identity):
@@ -796,6 +817,84 @@ def reap_orphaned_process_tree(
return "unconfirmed"
+def _processes_carrying_marker(worker_fingerprint: str) -> list[psutil.Process]:
+ """This user's live, inspectable processes whose marker hashes to ``worker_fingerprint``.
+
+ Best effort by design. The marked tree is a same-user, non-setuid process
+ this service spawned, so its ownership and environment are readable; a process
+ whose ownership or environment cannot be read (another user's, a setuid
+ ``login``, a non-dumpable Linux daemon) is not one of ours and is skipped. No
+ birth-time heuristic is applied: create_time can drift, the marker cannot.
+ """
+
+ own_pid = os.getpid()
+ own_uid = os.getuid() if hasattr(os, "getuid") else None
+ own_user = None if own_uid is not None else psutil.Process(own_pid).username()
+ found: list[psutil.Process] = []
+ for process in psutil.process_iter(["uids", "username"]):
+ if process.pid == own_pid:
+ continue
+ if own_uid is not None:
+ uids = process.info.get("uids")
+ if uids is None or {uids.real, uids.effective, uids.saved} != {own_uid}:
+ continue
+ elif process.info.get("username") != own_user:
+ continue
+ try:
+ marker = process.environ().get(PROCESS_IDENTITY_ENV)
+ except (psutil.Error, OSError):
+ # Exited, or not inspectable and therefore not a tree this service spawned.
+ continue
+ try:
+ fingerprint = fingerprint_process_marker(marker) if isinstance(marker, str) and marker else None
+ except UnicodeError:
+ continue
+ if fingerprint is not None and hmac.compare_digest(fingerprint, worker_fingerprint):
+ found.append(process)
+ return found
+
+
+def reap_marked_processes(
+ logger: logging.Logger,
+ label: str,
+ *,
+ worker_fingerprint: str,
+ terminate_timeout: float = DEFAULT_PROCESS_TERMINATE_TIMEOUT_SECONDS,
+) -> ProcessReapOutcome:
+ """Stop every process that inherited a managed tree's marker, wherever it is.
+
+ Needs no pid: this finds a tree whose owner died before recording one, and
+ members that left the leader's process group. Each victim is signalled through
+ its retained ``psutil.Process``, which refuses a pid reused since the scan.
+ ``unconfirmed`` only when a found process could not be confirmed stopped.
+ """
+
+ if not is_valid_worker_fingerprint(worker_fingerprint):
+ return "gone"
+ try:
+ victims = _processes_carrying_marker(worker_fingerprint)
+ if not victims:
+ return "gone"
+ logger.warning("Reaping %d %s process(es) found by their identity marker", len(victims), label)
+ for victim in victims:
+ try:
+ victim.terminate()
+ except psutil.NoSuchProcess:
+ continue
+ _gone, alive = psutil.wait_procs(victims, timeout=terminate_timeout)
+ for victim in alive:
+ try:
+ victim.kill()
+ except psutil.NoSuchProcess:
+ continue
+ _gone, alive = psutil.wait_procs(alive, timeout=terminate_timeout)
+ if not alive and not _processes_carrying_marker(worker_fingerprint):
+ return "reaped"
+ except Exception:
+ logger.warning("Could not confirm every %s process carrying its marker exited", label, exc_info=True)
+ return "unconfirmed"
+
+
async def terminate_process_tree(
process: Any,
logger: logging.Logger,
diff --git a/core/watches.py b/core/watches.py
index 123395cce..e7a60747f 100644
--- a/core/watches.py
+++ b/core/watches.py
@@ -27,6 +27,7 @@ from core.process_isolation import (
process_group_identity_status,
process_identity_from_payload,
process_identity_matches,
+ process_identity_recycled,
serialize_process_identity,
terminate_process_group_by_pgid,
terminate_process_tree_by_pid,
@@ -1434,7 +1435,7 @@ class ManagedWatchService:
)
block(watch_id, entry)
continue
- if live_identity.create_time != expected_identity.create_time:
+ if process_identity_recycled(expected_identity, live_identity):
logger.info(
"Recorded stale watch worker pid=%s watch_id=%s no longer exists; "
"the pid belongs to a newer process",
@@ -1529,10 +1530,7 @@ class ManagedWatchService:
live_identity.create_time,
)
else:
- worker_is_gone = (
- live_identity.create_time
- != expected_identity.create_time
- )
+ worker_is_gone = process_identity_recycled(expected_identity, live_identity)
except Exception:
logger.debug(
"Failed to recheck blocked stale watch pid=%s watch_id=%s",
diff --git a/tests/test_model_hub_api.py b/tests/test_model_hub_api.py
index bd15befb5..49706a6e1 100644
--- a/tests/test_model_hub_api.py
+++ b/tests/test_model_hub_api.py
@@ -7184,6 +7184,9 @@ def test_completed_orphan_cleanup_replay_clears_surviving_service_journal(
def client_if_running(self):
return self._client
+ def with_engine_excluded(self, operation):
+ return operation(self._client)
+
class RuntimeCleanupAdapter(FakeAdapter):
def __init__(self, runtime_adapter):
super().__init__()
diff --git a/tests/test_model_hub_oauth_takeover.py b/tests/test_model_hub_oauth_takeover.py
index e06fc1c03..196685ce5 100644
--- a/tests/test_model_hub_oauth_takeover.py
+++ b/tests/test_model_hub_oauth_takeover.py
@@ -161,6 +161,9 @@ class _FakeSupervisor:
def client(self) -> _FakeEngineClient:
return self.client_value
+ def with_engine_excluded(self, operation):
+ return operation(self.client_value)
+
def restart_if_running(self) -> None:
if self.client_value.on_restart is not None:
self.client_value.on_restart()
@@ -180,6 +183,40 @@ class _FakeSupervisor:
]
+async def test_activation_publishes_the_grant_only_under_the_engine_exclusion(
+ tmp_path: Path,
+) -> None:
+ # An engine a previous service left running must be reaped before the grant is
+ # visible in the watched auth dir, or it could load and rotate it.
+ store = EngineStateStore(tmp_path / "engine")
+
+ class _ExcludingSupervisor:
+ state_store = store
+
+ def __init__(self) -> None:
+ self.excluded = False
+
+ def with_engine_excluded(self, operation):
+ assert not list(store.auth_dir.glob("*.json"))
+ self.excluded = True
+ try:
+ return operation(None)
+ finally:
+ self.excluded = False
+
+ def client_if_running(self):
+ raise AssertionError("activation must learn the engine state under the exclusion")
+
+ supervisor = _ExcludingSupervisor()
+ adapter = CLIProxyEngineAdapter(supervisor=supervisor, state_store=store) # type: ignore[arg-type]
+ ref = await adapter.provision_oauth_credential("src_fixture123", "openai", _oauth_material())
+
+ await adapter.activate_oauth_credential(ref)
+
+ assert len(list(store.auth_dir.glob("*.json"))) == 1
+
+
@pytest.mark.asyncio
async def test_adapter_activation_is_idempotent_and_does_not_reupload(
tmp_path: Path,
diff --git a/tests/test_model_hub_runtime.py b/tests/test_model_hub_runtime.py
index 08b7b6810..c36da64e4 100644
--- a/tests/test_model_hub_runtime.py
+++ b/tests/test_model_hub_runtime.py
@@ -18,10 +18,12 @@ from types import SimpleNamespace
from urllib.parse import urlsplit
import pytest
+import psutil
import yaml
from jsonschema import Draft7Validator
from core import managed_runtime
+from core.process_isolation import PROCESS_IDENTITY_ENV, fingerprint_process_marker
from core.handlers.model_hub.adapter import (
DiscoveredModel,
EngineHealth,
@@ -767,6 +769,9 @@ def test_orphaned_oauth_cleanup_keeps_ref_until_deletes_are_confirmed(
def client_if_running(self):
return self._client
+ def with_engine_excluded(self, operation):
+ return operation(self._client)
+
async def run() -> None:
store = EngineStateStore(tmp_path / "state")
store.prepare_instance("install-1")
@@ -814,6 +819,9 @@ def test_orphaned_oauth_cleanup_retry_converges_after_journal_crash(
def client_if_running(self):
return self._client
+ def with_engine_excluded(self, operation):
+ return operation(self._client)
+
async def run() -> None:
store = EngineStateStore(tmp_path / "state")
store.prepare_instance("install-1")
@@ -2611,6 +2619,7 @@ import sys
import time
from http.server import BaseHTTPRequestHandler, HTTPServer
+import psutil
import yaml
config_path = sys.argv[sys.argv.index('-config') + 1]
@@ -2956,6 +2965,492 @@ def test_supervisor_keeps_installing_state_unverified_until_settlement(
assert status["verified"] is False
+def _recorded_engine_pids(record: Path) -> list[int]:
+ return [entry["pid"] for entry in json.loads(record.read_text(encoding="utf-8"))["engines"]]
+
+
+def _wait_for(condition, timeout: float = 5.0) -> None:
+ deadline = time.monotonic() + timeout
+ while not condition():
+ assert time.monotonic() < deadline
+ time.sleep(0.02)
+
+
+def _orphan_engine(tmp_path: Path) -> subprocess.Popen:
+ """Start an engine, then forget it the way a SIGKILLed service would."""
+
+ first, _store = _fixture_supervisor(tmp_path)
+ first.ensure_running()
+ orphan = first._process
+ assert orphan is not None
+ first._process = None
+ first._connection = None
+ # The dead service's orphan is re-parented to init, which reaps it; here it is
+ # still this test's child, so stand in for init.
+ threading.Thread(target=orphan.wait, daemon=True).start()
+ return orphan
+
+
+def test_supervisor_stop_without_a_handle_reaps_the_recorded_engine(tmp_path: Path) -> None:
+ orphan = _orphan_engine(tmp_path)
+ supervisor, store = _fixture_supervisor(tmp_path)
+
+ supervisor.stop()
+
+ _wait_for(lambda: orphan.poll() is not None)
+ assert not (store.root / "engine-process.json").exists()
+
+
+def test_supervisor_refuses_to_start_beside_an_unconfirmed_engine(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ # A survivor shares the watched OAuth auth dir; a second engine must not join it.
+ from vibe.model_hub_runtime import supervisor as supervisor_module
+
+ orphan = _orphan_engine(tmp_path)
+ real_reap = supervisor_module.reap_marked_processes
+ monkeypatch.setattr(supervisor_module, "reap_marked_processes", lambda *a, **k: "unconfirmed")
+ spawned: list[object] = []
+ supervisor, store = _fixture_supervisor(
+ tmp_path,
+ process_factory=lambda *a, **k: spawned.append(a) or subprocess.Popen(*a, **k),
+ )
+ record = store.root / "engine-process.json"
+
+ with pytest.raises(EngineUnavailableError) as raised:
+ supervisor.ensure_running()
+
+ assert raised.value.reason == "previous_engine_alive"
+ assert spawned == []
+ assert _recorded_engine_pids(record) == [orphan.pid]
+ monkeypatch.setattr(supervisor_module, "reap_marked_processes", real_reap)
+ supervisor.ensure_running()
+ _wait_for(lambda: orphan.poll() is not None)
+ assert _recorded_engine_pids(record) == [supervisor._process.pid]
+ supervisor.stop()
+ assert not record.exists()
+
+
[email protected]("operation", ["disable", "invalidate_configs"])
+def test_supervisor_does_not_report_stopped_while_an_engine_is_unconfirmed(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ operation: str,
+) -> None:
+ from vibe.model_hub_runtime import supervisor as supervisor_module
+
+ orphan = _orphan_engine(tmp_path)
+ monkeypatch.setattr(supervisor_module, "reap_marked_processes", lambda *a, **k: "unconfirmed")
+ supervisor, store = _fixture_supervisor(tmp_path)
+ cleared: list[bool] = []
+ monkeypatch.setattr(store, "clear_runtime_configs", lambda: cleared.append(True))
+
+ with pytest.raises(EngineUnavailableError) as raised:
+ getattr(supervisor, operation)()
+
+ assert raised.value.reason == "previous_engine_alive"
+ # Revocation callers run only after invalidation returns.
+ assert cleared == []
+ assert _recorded_engine_pids(store.root / "engine-process.json") == [orphan.pid]
+ orphan.kill()
+
+
+def test_supervisor_shutdown_stop_keeps_an_unconfirmed_engine_recorded(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from vibe.model_hub_runtime import supervisor as supervisor_module
+
+ orphan = _orphan_engine(tmp_path)
+ monkeypatch.setattr(supervisor_module, "reap_marked_processes", lambda *a, **k: "unconfirmed")
+ supervisor, store = _fixture_supervisor(tmp_path)
+
+ supervisor.stop()
+
+ assert _recorded_engine_pids(store.root / "engine-process.json") == [orphan.pid]
+ orphan.kill()
+
+
+def test_supervisor_refuses_to_start_over_an_unreadable_engine_record(tmp_path: Path) -> None:
+ spawned: list[object] = []
+ supervisor, store = _fixture_supervisor(
+ tmp_path,
+ process_factory=lambda *a, **k: spawned.append(a) or subprocess.Popen(*a, **k),
+ )
+ record = store.root / "engine-process.json"
+ record.mkdir(parents=True)
+
+ with pytest.raises(EngineUnavailableError) as raised:
+ supervisor.ensure_running()
+
+ assert raised.value.reason == "previous_engine_alive"
+ assert spawned == []
+ assert record.is_dir()
+
+
+def test_supervisor_refuses_an_engine_whose_identity_was_not_captured(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from vibe.model_hub_runtime import supervisor as supervisor_module
+
+ monkeypatch.setattr(supervisor_module, "capture_spawned_process_identity", lambda *_: None)
+ supervisor, store = _fixture_supervisor(tmp_path)
+
+ with pytest.raises(EngineUnavailableError):
+ supervisor.ensure_running()
+
+ assert supervisor._process is None
+ assert not (store.root / "engine-process.json").exists()
+
+
+def test_supervisor_credential_invalidation_reaps_a_recorded_engine(tmp_path: Path) -> None:
+ orphan = _orphan_engine(tmp_path)
+ supervisor, store = _fixture_supervisor(tmp_path)
+
+ supervisor.invalidate_configs()
+
+ _wait_for(lambda: orphan.poll() is not None)
+ assert not (store.root / "engine-process.json").exists()
+ assert supervisor._process is None
+
+
+def test_supervisor_reaps_an_engine_left_running_by_a_dead_service(tmp_path: Path) -> None:
+ # A SIGKILLed service never runs atexit; its isolated engine group survives.
+ orphan = _orphan_engine(tmp_path)
+ record = _fixture_supervisor(tmp_path)[1].root / "engine-process.json"
+ assert _recorded_engine_pids(record) == [orphan.pid]
+
+ second, _store = _fixture_supervisor(tmp_path)
+ second.ensure_running()
+
+ _wait_for(lambda: orphan.poll() is not None)
+ assert second._process is not None and second._process.pid != orphan.pid
+ assert _recorded_engine_pids(record) == [second._process.pid]
+ second.stop()
+ assert not record.exists()
+
+
+def test_supervisor_never_signals_a_recycled_pid_from_its_record(tmp_path: Path) -> None:
+ stranger = subprocess.Popen(
+ [sys.executable, "-c", "import time; time.sleep(30)"],
+ start_new_session=True,
+ )
+ try:
+ supervisor, store = _fixture_supervisor(tmp_path)
+ store.root.mkdir(parents=True, exist_ok=True)
+ (store.root / "engine-process.json").write_text(
+ json.dumps(
+ {
+ "engines": [
+ {
+ "pid": stranger.pid,
+ # A recycled pid never shares its predecessor's birth time.
+ "create_time": psutil.Process(stranger.pid).create_time() - 1000,
+ "worker_fingerprint": "sha256:" + "0" * 64,
+ }
+ ]
+ }
+ ),
+ encoding="utf-8",
+ )
+
+ supervisor.ensure_running()
+
+ assert stranger.poll() is None
+ assert stranger.pid not in _recorded_engine_pids(store.root / "engine-process.json")
+ supervisor.stop()
+ finally:
+ stranger.kill()
+ stranger.wait(timeout=5)
+
+
+def test_supervisor_ignores_a_corrupt_engine_record(tmp_path: Path) -> None:
+ supervisor, store = _fixture_supervisor(tmp_path)
+ store.root.mkdir(parents=True, exist_ok=True)
+ (store.root / "engine-process.json").write_text("{not json", encoding="utf-8")
+
+ supervisor.ensure_running()
+
+ assert supervisor._process is not None
+ supervisor.stop()
+
+
+def test_supervisor_ignores_an_engine_record_that_is_not_utf8(tmp_path: Path) -> None:
+ supervisor, store = _fixture_supervisor(tmp_path)
+ store.root.mkdir(parents=True, exist_ok=True)
+ (store.root / "engine-process.json").write_bytes(b'{"engines": [\xff\xfe')
+
+ supervisor.ensure_running()
+
+ assert supervisor._process is not None
+ supervisor.stop()
+ assert not (store.root / "engine-process.json").exists()
+
+
+def test_supervisor_records_the_launch_before_spawning(tmp_path: Path) -> None:
+ # A service killed between spawn and pid capture must still leave the engine findable.
+ seen: list[list[dict]] = []
+
+ def spawn(*args, **kwargs):
+ record = tmp_path / "state" / "engine-process.json"
+ seen.append(json.loads(record.read_text(encoding="utf-8"))["engines"])
+ return subprocess.Popen(*args, **kwargs)
+
+ supervisor, _store = _fixture_supervisor(tmp_path, process_factory=spawn)
+ supervisor.ensure_running()
+
+ [launch] = seen[0]
+ assert set(launch) == {"worker_fingerprint"}
+ assert launch["worker_fingerprint"] == fingerprint_process_marker(
+ psutil.Process(supervisor._process.pid).environ()[PROCESS_IDENTITY_ENV]
+ )
+ supervisor.stop()
+
+
+def test_supervisor_retires_the_launch_record_when_the_spawn_fails(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ # No process exists to carry the marker, so no scan may keep the record alive.
+ from vibe.model_hub_runtime import supervisor as supervisor_module
+
+ def spawn(*_args, **_kwargs):
+ raise OSError("spawn failed")
+
+ monkeypatch.setattr(supervisor_module, "reap_marked_processes", lambda *_a, **_k: "unconfirmed")
+ supervisor, store = _fixture_supervisor(tmp_path, process_factory=spawn)
+
+ with pytest.raises(EngineUnavailableError) as raised:
+ supervisor.ensure_running()
+
+ assert raised.value.reason is None
+ assert not (store.root / "engine-process.json").exists()
+
+
+def test_supervisor_reaps_an_engine_whose_pid_was_never_recorded(tmp_path: Path) -> None:
+ orphan = _orphan_engine(tmp_path)
+ record = tmp_path / "state" / "engine-process.json"
+ # The service died after the spawn and before the pid was written.
+ [entry] = json.loads(record.read_text(encoding="utf-8"))["engines"]
+ record.write_text(
+ json.dumps({"engines": [{"worker_fingerprint": entry["worker_fingerprint"]}]}),
+ encoding="utf-8",
+ )
+
+ second, _store = _fixture_supervisor(tmp_path)
+ second.ensure_running()
+
+ _wait_for(lambda: orphan.poll() is not None)
+ assert _recorded_engine_pids(record) == [second._process.pid]
+ second.stop()
+ assert not record.exists()
+
+
+def test_supervisor_refresh_and_reap_stop_an_engine_a_previous_service_left_running(tmp_path: Path) -> None:
+ record = tmp_path / "state" / "engine-process.json"
+ for operation in ("restart_if_running", "with_engine_excluded"):
+ orphan = _orphan_engine(tmp_path)
+ second, _store = _fixture_supervisor(tmp_path)
+
+ if operation == "with_engine_excluded":
+ assert second.with_engine_excluded(lambda client: client) is None
+ else:
+ second.restart_if_running()
+
+ _wait_for(lambda: orphan.poll() is not None)
+ assert second._process is None
+ assert not record.exists()
+
+
+def test_supervisor_holds_engine_starts_until_grant_removal_returns(tmp_path: Path) -> None:
+ spawned = threading.Event()
+
+ def spawn(args, **kwargs):
+ spawned.set()
+ return subprocess.Popen(args, **kwargs)
+
+ supervisor, _store = _fixture_supervisor(tmp_path, process_factory=spawn)
+
+ def remove_grant(client) -> str:
+ assert client is None
+ threading.Thread(target=supervisor.ensure_running, daemon=True).start()
+ # A start requested mid-removal must wait for it, or it could load the grant.
+ assert not spawned.wait(0.5)
+ return "removed"
+
+ assert supervisor.with_engine_excluded(remove_grant) == "removed"
+ assert spawned.wait(10)
+ _wait_for(lambda: supervisor.client_if_running() is not None)
+ supervisor.stop()
+
+
+def test_supervisor_refresh_refuses_while_a_previous_engine_is_unconfirmed(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from vibe.model_hub_runtime import supervisor as supervisor_module
+
+ orphan = _orphan_engine(tmp_path)
+ monkeypatch.setattr(supervisor_module, "reap_marked_processes", lambda *_a, **_k: "unconfirmed")
+ second, _store = _fixture_supervisor(tmp_path)
+
+ for call in (second.restart_if_running, lambda: second.with_engine_excluded(pytest.fail)):
+ with pytest.raises(EngineUnavailableError) as raised:
+ call()
+ assert raised.value.reason == "previous_engine_alive"
+ monkeypatch.undo()
+ second.stop()
+ _wait_for(lambda: orphan.poll() is not None)
+
+
+def test_oauth_revoke_keeps_the_grant_while_a_previous_engine_is_unconfirmed(tmp_path: Path) -> None:
+ class Supervisor:
+ def __init__(self, store: EngineStateStore) -> None:
+ self.state_store = store
+
+ def with_engine_excluded(self, operation):
+ raise EngineUnavailableError("models.engine.stop_unconfirmed", reason="previous_engine_alive")
+
+ async def run() -> None:
+ store = EngineStateStore(tmp_path / "state")
+ store.prepare_instance("install-1")
+ auth_file = store.auth_dir / "claude-account.json"
+ auth_file.write_text("{}", encoding="utf-8")
+ auth_file.chmod(0o600)
+ credential_ref = store.bind_oauth_credential("src_fixture123", "anthropic", auth_file.name)
+ store.sync_sources([])
+ adapter = CLIProxyEngineAdapter(
+ supervisor=Supervisor(store), # type: ignore[arg-type]
+ state_store=store,
+ )
+
+ with pytest.raises(EngineUnavailableError):
+ await adapter.revoke_credential(credential_ref)
+
+ assert auth_file.exists()
+ assert store.credential_metadata_if_present(credential_ref) is not None
+
+ asyncio.run(run())
+
+
+def test_orphaned_oauth_cleanup_keeps_the_grant_while_a_previous_engine_is_unconfirmed(tmp_path: Path) -> None:
+ class Supervisor:
+ def __init__(self, store: EngineStateStore) -> None:
+ self.state_store = store
+
+ def with_engine_excluded(self, operation):
+ raise EngineUnavailableError("models.engine.stop_unconfirmed", reason="previous_engine_alive")
+
+ async def run() -> None:
+ store = EngineStateStore(tmp_path / "state")
+ store.prepare_instance("install-1")
+ auth_file = store.auth_dir / "claude-account.json"
+ auth_file.write_text("{}", encoding="utf-8")
+ auth_file.chmod(0o600)
+ credential_ref = store.bind_oauth_credential("src_fixture123", "anthropic", auth_file.name)
+ store.sync_sources([])
+ adapter = CLIProxyEngineAdapter(
+ supervisor=Supervisor(store), # type: ignore[arg-type]
+ state_store=store,
+ )
+
+ assert await adapter.cleanup_orphaned_oauth_material(credential_ref) is False
+
+ assert auth_file.exists()
+ assert store.credential_metadata_if_present(credential_ref) is not None
+
+ asyncio.run(run())
+
+
+def test_supervisor_keeps_a_marker_only_record_while_the_sweep_is_unconfirmed(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from vibe.model_hub_runtime import supervisor as supervisor_module
+
+ orphan = _orphan_engine(tmp_path)
+ record = tmp_path / "state" / "engine-process.json"
+ [entry] = json.loads(record.read_text(encoding="utf-8"))["engines"]
+ marker_only = {"engines": [{"worker_fingerprint": entry["worker_fingerprint"]}]}
+ record.write_text(json.dumps(marker_only), encoding="utf-8")
+ monkeypatch.setattr(supervisor_module, "reap_marked_processes", lambda *_a, **_k: "unconfirmed")
+ second, _store = _fixture_supervisor(tmp_path)
+
+ with pytest.raises(EngineUnavailableError) as raised:
+ second.ensure_running()
+
+ assert raised.value.reason == "previous_engine_alive"
+ assert orphan.poll() is None
+ assert json.loads(record.read_text(encoding="utf-8")) == marker_only
+ monkeypatch.undo()
+ second.ensure_running()
+ _wait_for(lambda: orphan.poll() is not None)
+ second.stop()
+
+
+def test_supervisor_retires_a_record_the_marker_sweep_confirms_gone(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ # An inconclusive pid/group path must not pin a record the authoritative sweep cleared.
+ from vibe.model_hub_runtime import supervisor as supervisor_module
+
+ orphan = _orphan_engine(tmp_path)
+ monkeypatch.setattr(supervisor_module, "reap_orphaned_process_tree", lambda *_a, **_k: "unconfirmed")
+ supervisor, store = _fixture_supervisor(tmp_path)
+
+ supervisor.stop()
+
+ _wait_for(lambda: orphan.poll() is not None)
+ assert not (store.root / "engine-process.json").exists()
+
+
+def test_supervisor_failed_tracking_reaps_a_descendant_that_ignores_sigterm(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from vibe.model_hub_runtime import supervisor as supervisor_module
+
+ stubborn = tmp_path / "stubborn-engine"
+ stubborn.write_text(
+ "#!/bin/sh\n"
+ f"'{sys.executable}' -c 'import signal, time; signal.signal(signal.SIGTERM, signal.SIG_IGN); "
+ "time.sleep(60)' &\n"
+ "exec sleep 60\n",
+ encoding="utf-8",
+ )
+ stubborn.chmod(0o755)
+ markers: list[str] = []
+
+ def spawn(args, **kwargs):
+ markers.append(kwargs["env"][PROCESS_IDENTITY_ENV])
+ process = subprocess.Popen([str(stubborn)], **kwargs)
+ time.sleep(0.5)
+ return process
+
+ monkeypatch.setattr(supervisor_module, "capture_spawned_process_identity", lambda *_: None)
+ supervisor, store = _fixture_supervisor(tmp_path, process_factory=spawn)
+
+ with pytest.raises(EngineUnavailableError) as raised:
+ supervisor.ensure_running()
+
+ assert raised.value.reason == "engine_untracked"
+ assert _processes_with_marker(markers[0]) == []
+ assert not (store.root / "engine-process.json").exists()
+
+
+def _processes_with_marker(marker: str) -> list[int]:
+ found = []
+ for process in psutil.process_iter():
+ try:
+ if process.environ().get(PROCESS_IDENTITY_ENV) == marker:
+ found.append(process.pid)
+ except (psutil.Error, OSError):
+ continue
+ return found
+
+
def test_supervisor_starts_checks_health_and_stops_mock_engine(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
@@ -2983,6 +3478,8 @@ def test_supervisor_starts_checks_health_and_stops_mock_engine(
assert "OPENAI_API_KEY" not in captured_env
assert "GITHUB_TOKEN" not in captured_env
assert "HTTP_PROXY" not in captured_env
+ marker = captured_env.pop("AVIBE_PROCESS_IDENTITY")
+ assert len(marker) == 64
assert captured_env == engine_subprocess_environment()
assert captured_stdio == {
"stdout": subprocess.DEVNULL,
@@ -3492,6 +3989,9 @@ def test_adapter_serializes_source_sync_with_new_invocations(tmp_path: Path) ->
def client_if_running(self):
return self._client
+ def with_engine_excluded(self, operation):
+ return operation(self._client)
+
def restart_if_running(self) -> None:
restart_started.set()
assert allow_restart.wait(timeout=2)
@@ -7265,6 +7765,10 @@ def test_oauth_flow_handles_new_refreshed_and_conflicting_auth_records(
def client_if_running(self):
return None
+ def with_engine_excluded(self, operation):
+ # The flow started this engine, so it is the running one.
+ return operation(self._client)
+
def invalidate_configs(self) -> None:
self.state_store.clear_runtime_configs()
diff --git a/tests/test_model_hub_takeover_integration.py b/tests/test_model_hub_takeover_integration.py
index fc3b3b0c2..43d8d133a 100644
--- a/tests/test_model_hub_takeover_integration.py
+++ b/tests/test_model_hub_takeover_integration.py
@@ -36,6 +36,9 @@ class FixtureSupervisor:
def client(self):
return self.client_if_running()
+ def with_engine_excluded(self, operation):
+ return operation(self.client_if_running())
+
def ensure_running(self):
return self.connection
diff --git a/tests/test_process_isolation.py b/tests/test_process_isolation.py
index 9f1854efe..3be098085 100644
--- a/tests/test_process_isolation.py
+++ b/tests/test_process_isolation.py
@@ -6,6 +6,7 @@ import os
import signal
import subprocess
import sys
+import time
from contextlib import suppress
from pathlib import Path
from types import SimpleNamespace
@@ -27,8 +28,11 @@ from core.process_isolation import (
process_group_exists,
process_group_identity_status,
process_identity_matches,
+ process_identity_recycled,
process_identity_subprocess_env,
probe_process_liveness,
+ _processes_carrying_marker,
+ reap_marked_processes,
reap_orphaned_process_tree,
signal_process_tree,
terminate_process_group_by_pgid,
@@ -434,7 +438,8 @@ def test_terminate_process_tree_by_pid_does_not_signal_reused_pid(monkeypatch: p
pytest.skip("process group signalling assertion is POSIX-specific")
expected_identity = _persisted_identity()
- reused_identity = _live_identity(create_time=456.0)
+ # A stranger holding a recycled pid: another birth time and none of our marker.
+ reused_identity = _live_identity(create_time=456.0, worker_fingerprint=None)
monkeypatch.setattr(
"core.process_isolation._open_process_identity",
lambda _pid: (SimpleNamespace(pid=12345), reused_identity),
@@ -457,6 +462,118 @@ def test_terminate_process_tree_by_pid_does_not_signal_reused_pid(monkeypatch: p
)
+ ("live_create_time", "live_fingerprint", "matches", "recycled"),
+ [
+ (123.0, TEST_FINGERPRINT, True, False),
+ # macOS: the displayed birth time shifts while the same execution runs on.
+ (123.7, TEST_FINGERPRINT, True, False),
+ (456.0, None, False, True),
+ (456.0, fingerprint_process_marker("other-tree"), False, True),
+ # Same birth, no readable marker: neither ours nor provably someone else's.
+ (123.0, None, False, False),
+ ],
+)
+def test_process_identity_is_decided_by_marker_not_a_shifted_birth_time(
+ live_create_time: float,
+ live_fingerprint: str | None,
+ matches: bool,
+ recycled: bool,
+) -> None:
+ expected = _persisted_identity()
+ live = _live_identity(create_time=live_create_time, worker_fingerprint=live_fingerprint)
+
+ assert process_identity_matches(expected, live) is matches
+ assert process_identity_recycled(expected, live) is recycled
+
+
+def test_unreadable_marker_with_a_shifted_birth_time_is_not_recycled() -> None:
+ expected = PersistedProcessIdentity(pid=4321, create_time=123.0, worker_fingerprint=fingerprint_process_marker("m"))
+ unreadable = ProcessIdentity(pid=4321, create_time=456.0, worker_fingerprint=None, marker_readable=False)
+ stranger = ProcessIdentity(pid=4321, create_time=456.0, worker_fingerprint=None)
+
+ assert process_identity_recycled(expected, unreadable) is False
+ assert process_identity_recycled(expected, stranger) is True
+
+
+def test_open_process_identity_reports_an_unreadable_environment(monkeypatch: pytest.MonkeyPatch) -> None:
+ def deny(_process):
+ raise psutil.AccessDenied(os.getpid())
+
+ monkeypatch.setattr(psutil.Process, "environ", deny)
+
+ identity = inspect_process_identity(os.getpid())
+
+ assert identity is not None
+ assert identity.worker_fingerprint is None and identity.marker_readable is False
+
+
+def test_reap_marked_processes_finds_a_tree_by_marker_alone() -> None:
+ marker = new_process_identity_marker()
+ child = subprocess.Popen(
+ [sys.executable, "-c", "import time; time.sleep(30)"],
+ env={**os.environ, PROCESS_IDENTITY_ENV: marker},
+ start_new_session=True,
+ )
+ try:
+ deadline = time.monotonic() + 5
+ while (identity := inspect_process_identity(child.pid)) is None or identity.worker_fingerprint is None:
+ assert time.monotonic() < deadline
+ time.sleep(0.02)
+ outcome = reap_marked_processes(
+ logging.getLogger(__name__),
+ "test process",
+ worker_fingerprint=fingerprint_process_marker(marker),
+ )
+ assert outcome == "reaped"
+ assert child.wait(timeout=5) is not None
+ assert (
+ reap_marked_processes(
+ logging.getLogger(__name__),
+ "test process",
+ worker_fingerprint=fingerprint_process_marker(marker),
+ )
+ == "gone"
+ )
+ finally:
+ with suppress(ProcessLookupError):
+ child.kill()
+ child.wait(timeout=5)
+
+
+def test_marker_scan_skips_processes_it_cannot_inspect(monkeypatch: pytest.MonkeyPatch) -> None:
+ # A tree this service spawned is always inspectable; an unreadable or foreign
+ # process is not ours and must not block recovery forever (non-dumpable daemons).
+ own_uid = os.getuid()
+ marker = new_process_identity_marker()
+ ours = SimpleNamespace(
+ pid=4141,
+ info={"uids": SimpleNamespace(real=own_uid, effective=own_uid, saved=own_uid), "username": "me"},
+ environ=lambda: {PROCESS_IDENTITY_ENV: marker},
+ )
+ unreadable = SimpleNamespace(
+ pid=4242,
+ info={"uids": SimpleNamespace(real=own_uid, effective=own_uid, saved=own_uid), "username": "me"},
+ environ=lambda: (_ for _ in ()).throw(psutil.AccessDenied(4242)),
+ )
+ setuid = SimpleNamespace(
+ pid=4343,
+ info={"uids": SimpleNamespace(real=own_uid, effective=0, saved=0), "username": "me"},
+ environ=lambda: pytest.fail("a setuid process cannot carry our marker"),
+ )
+ monkeypatch.setattr(psutil, "process_iter", lambda _attrs: iter([setuid, unreadable, ours]))
+
+ assert _processes_carrying_marker(fingerprint_process_marker(marker)) == [ours]
+ assert (
+ reap_marked_processes(
+ logging.getLogger(__name__),
+ "test process",
+ worker_fingerprint=fingerprint_process_marker(new_process_identity_marker()),
+ )
+ == "gone"
+ )
+
+
def test_terminate_process_tree_by_pid_refuses_changed_marker(monkeypatch: pytest.MonkeyPatch) -> None:
expected_identity = _persisted_identity()
changed_identity = _live_identity(
diff --git a/tests/test_watches.py b/tests/test_watches.py
index 35d17332b..f34fdac93 100644
--- a/tests/test_watches.py
+++ b/tests/test_watches.py
@@ -2591,7 +2591,7 @@ def test_managed_watch_service_start_reaps_stale_worker_for_deleted_watch(
)
terminated: list[int] = []
monkeypatch.setattr("core.watches.runtime.pid_alive", lambda pid: pid == 1234)
- monkeypatch.setattr("core.watches.inspect_process_identity", lambda _pid: identity)
+ monkeypatch.setattr("core.watches.inspect_process_identity", lambda pid: _live_identity(pid=pid))
monkeypatch.setattr(
"core.watches.terminate_process_tree_by_pid",
lambda pid, *_args, **_kwargs: terminated.append(pid) or True,
@@ -2685,7 +2685,7 @@ def test_managed_watch_service_start_does_not_reap_reused_pid(
monkeypatch.setattr("core.watches.runtime.pid_alive", lambda pid: pid == 4321)
monkeypatch.setattr(
"core.watches.inspect_process_identity",
- lambda pid: _live_identity(pid=pid, create_time=456.0),
+ lambda pid: _live_identity(pid=pid, create_time=456.0, worker_fingerprint=None),
)
monkeypatch.setattr(
"core.watches.terminate_process_tree_by_pid",
@@ -2709,6 +2709,42 @@ def test_managed_watch_service_start_does_not_reap_reused_pid(
assert watch.id not in service._recovery_blocked_watch_ids
+ ("live_fingerprint", "unblocked"),
+ [(TEST_FINGERPRINT, ()), (None, ("watch-a",))],
+)
+def test_blocked_watch_recheck_decides_by_marker_not_a_shifted_birth_time(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ live_fingerprint: str | None,
+ unblocked: tuple[str, ...],
+) -> None:
+ """macOS may report a shifted create_time for the same live worker."""
+
+ service = ManagedWatchService(
+ controller=SimpleNamespace(),
+ store=ManagedWatchStore(tmp_path / "watches.json"),
+ request_store=TaskExecutionStore(tmp_path / "task_requests"),
+ runtime_store=WatchRuntimeStateStore(tmp_path / "watch_runtime.json"),
+ )
+ identity = _persisted_identity()
+ entry = {
+ "pid": 4321,
+ "process_identity": {
+ "pid": identity.pid,
+ "create_time": identity.create_time,
+ "worker_fingerprint": identity.worker_fingerprint,
+ },
+ }
+ monkeypatch.setattr("core.watches.runtime.pid_alive", lambda pid: True)
+ monkeypatch.setattr(
+ "core.watches.inspect_process_identity",
+ lambda pid: _live_identity(pid=pid, create_time=456.0, worker_fingerprint=live_fingerprint),
+ )
+
+ assert service._inspect_recovery_blocked_watches({"watch-a": entry}) == unblocked
+
+
def test_managed_watch_service_start_blocks_respawn_when_worker_marker_changed(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
@@ -3708,7 +3744,7 @@ def test_managed_watch_service_start_preserves_worker_state_when_reap_fails(
runtime_store=runtime_store,
)
monkeypatch.setattr("core.watches.runtime.pid_alive", lambda pid: pid == 4321)
- monkeypatch.setattr("core.watches.inspect_process_identity", lambda _pid: identity)
+ monkeypatch.setattr("core.watches.inspect_process_identity", lambda pid: _live_identity(pid=pid))
monkeypatch.setattr("core.watches.terminate_process_tree_by_pid", lambda *_args, **_kwargs: False)
async def _run() -> None:
@@ -3744,7 +3780,7 @@ def test_managed_watch_service_periodically_unblocks_after_stale_worker_exits(
monkeypatch.setattr("core.watches.WATCH_RECONCILE_INTERVAL_SECONDS", 0.01)
monkeypatch.setattr("core.watches.runtime.pid_alive", lambda _pid: worker["alive"])
monkeypatch.setattr("core.watches.process_group_exists", lambda *_args: False)
- monkeypatch.setattr("core.watches.inspect_process_identity", lambda _pid: identity)
+ monkeypatch.setattr("core.watches.inspect_process_identity", lambda pid: _live_identity(pid=pid))
monkeypatch.setattr("core.watches.terminate_process_tree_by_pid", lambda *_args, **_kwargs: False)
async def fake_run_watch(_watch_id: str) -> None:
diff --git a/vibe/model_hub_runtime/adapter.py b/vibe/model_hub_runtime/adapter.py
index 9f9a7a654..eb04827ef 100644
--- a/vibe/model_hub_runtime/adapter.py
+++ b/vibe/model_hub_runtime/adapter.py
@@ -1774,11 +1774,16 @@ class CLIProxyEngineAdapter:
async with self._routing_lock:
await self._transports_idle.wait()
- auth_name, payload, _prefix, _already_active = await run_owned_in_thread(
- self.state_store.activate_oauth_auth_file,
- credential_ref,
+ def publish_grant(running: EngineClient | None):
+ return (*self.state_store.activate_oauth_auth_file(credential_ref), running)
+
+ # Published under the lifecycle exclusion: an engine a previous service
+ # left running is reaped first, so none can load or rotate the new grant
+ # outside this service's reconcile below.
+ auth_name, payload, _prefix, _already_active, client = await run_owned_in_thread(
+ self.supervisor.with_engine_excluded,
+ publish_grant,
)
- client = await asyncio.to_thread(self.supervisor.client_if_running)
if client is None:
# The next ordered lifecycle step starts CPA. The atomically
# published watched file is the source of truth; no management
@@ -2036,24 +2041,24 @@ class CLIProxyEngineAdapter:
)
if auth_name:
if metadata.get("activation_state") != "staged":
- client = await asyncio.to_thread(self.supervisor.client_if_running)
- if client is not None:
- try:
- await asyncio.to_thread(
- client.management_request,
- "DELETE",
- "/auth-files",
- query={"name": str(auth_name)},
- timeout=1.0,
- )
- except EngineClientError as exc:
- raise EngineStateError(
- "unable to remove OAuth auth file"
- ) from exc
- await asyncio.to_thread(
- self.state_store.delete_oauth_auth_file,
- str(auth_name),
- )
+
+ def remove_grant(client: EngineClient | None) -> None:
+ if client is not None:
+ try:
+ client.management_request(
+ "DELETE",
+ "/auth-files",
+ query={"name": str(auth_name)},
+ timeout=1.0,
+ )
+ except EngineClientError as exc:
+ raise EngineStateError("unable to remove OAuth auth file") from exc
+ self.state_store.delete_oauth_auth_file(str(auth_name))
+
+ # One supervisor operation: an engine left running by a previous
+ # service is reaped first, and none can start and load the grant
+ # before its file is gone.
+ await asyncio.to_thread(self.supervisor.with_engine_excluded, remove_grant)
await asyncio.to_thread(
self.state_store.audit_auth_permissions,
enforce=True,
@@ -2099,12 +2104,7 @@ class CLIProxyEngineAdapter:
auth_name = metadata.get("auth_name")
if not isinstance(auth_name, str) or not auth_name:
return False
- client = await asyncio.to_thread(self.supervisor.client_if_running)
- return await self._cleanup_oauth_material(
- client,
- auth_name,
- credential_ref,
- )
+ return await self._cleanup_oauth_material(auth_name, credential_ref)
async def discover_models(
self,
@@ -2755,7 +2755,6 @@ class CLIProxyEngineAdapter:
# may remain behind it. Both auth-file deletions must be
# confirmed before revocation can discard the minted ref.
if auth.identity not in flow.before_auth_fingerprints and await self._cleanup_oauth_material(
- client,
auth.name,
credential_ref,
):
@@ -2780,37 +2779,26 @@ class CLIProxyEngineAdapter:
flow.state = "success"
self._release_provider(flow)
- async def _cleanup_oauth_material(
- self,
- client: EngineClient | None,
- auth_name: str,
- credential_ref: str,
- ) -> bool:
- engine_delete_succeeded = client is None
- if client is not None:
+ async def _cleanup_oauth_material(self, auth_name: str, credential_ref: str) -> bool:
+ def remove_grant(client: EngineClient | None) -> bool:
+ engine_delete_succeeded = True
+ if client is not None:
+ try:
+ client.management_request("DELETE", "/auth-files", query={"name": auth_name})
+ except EngineClientError:
+ engine_delete_succeeded = False
try:
- await asyncio.to_thread(
- client.management_request,
- "DELETE",
- "/auth-files",
- query={"name": auth_name},
- )
- except EngineClientError:
- engine_delete_succeeded = False
- else:
- engine_delete_succeeded = True
+ self.state_store.delete_oauth_auth_file(auth_name)
+ except EngineStateError:
+ return False
+ return engine_delete_succeeded
+ # Atomic with the engine lifecycle: see ``revoke_credential``.
try:
- await asyncio.to_thread(
- self.state_store.delete_oauth_auth_file,
- auth_name,
- )
- except EngineStateError:
- local_delete_succeeded = False
- else:
- local_delete_succeeded = True
-
- if not (engine_delete_succeeded and local_delete_succeeded):
+ removed = await asyncio.to_thread(self.supervisor.with_engine_excluded, remove_grant)
+ except EngineUnavailableError:
+ return False
+ if not removed:
return False
try:
await asyncio.to_thread(
diff --git a/vibe/model_hub_runtime/supervisor.py b/vibe/model_hub_runtime/supervisor.py
index 07ac6cf78..85bdcb865 100644
--- a/vibe/model_hub_runtime/supervisor.py
+++ b/vibe/model_hub_runtime/supervisor.py
@@ -1,18 +1,35 @@
from __future__ import annotations
import atexit
+import json
import logging
import signal
import socket
import subprocess
import threading
import time
+from dataclasses import dataclass
from datetime import datetime, timezone
from pathlib import Path
-from typing import Any, Callable
+from typing import Any, Callable, TypeVar
from config import paths
-from core.process_isolation import KILL_SIGNAL, isolated_subprocess_kwargs, signal_process_tree
+from config.atomic_io import write_atomic
+from core.process_isolation import (
+ KILL_SIGNAL,
+ PROCESS_IDENTITY_ENV,
+ PersistedProcessIdentity,
+ capture_spawned_process_identity,
+ fingerprint_process_marker,
+ is_valid_worker_fingerprint,
+ isolated_subprocess_kwargs,
+ new_process_identity_marker,
+ process_identity_from_payload,
+ reap_marked_processes,
+ reap_orphaned_process_tree,
+ serialize_process_identity,
+ signal_process_tree,
+)
from vibe.model_hub_runtime.client import EngineClient, EngineConnection
from vibe.model_hub_runtime.config import write_engine_config
from vibe.model_hub_runtime.environment import engine_subprocess_environment
@@ -21,9 +38,21 @@ from vibe.model_hub_runtime.state import EngineStateStore
logger = logging.getLogger(__name__)
+_T = TypeVar("_T")
MODEL_HUB_STARTUP_TIMEOUT_SECONDS = 30.0
+# Durable identity of the engine this state root last spawned. A service that
+# dies without running ``atexit`` (SIGKILL, crash, forced restart) leaves its
+# isolated engine group running; the next start reaps it by identity. The marker
+# is recorded before the spawn, so an engine is findable before its pid is known.
+_ENGINE_PROCESS_RECORD = "engine-process.json"
+
+
+@dataclass(frozen=True)
+class _EngineRecord:
+ worker_fingerprint: str
+ identity: PersistedProcessIdentity | None = None
_STARTUP_POLL_INTERVAL_SECONDS = 0.05
@@ -70,22 +99,46 @@ class EngineSupervisor:
return self._start_locked()
def stop(self) -> None:
+ """Shutdown stop: an unconfirmed survivor stays recorded for the next start."""
with self._lock:
- self._stop_locked()
+ if not self._stop_locked():
+ logger.warning("Model Hub engine exit unconfirmed at shutdown; left recorded")
def disable(self) -> None:
"""Stop the managed engine and restore explicit lazy-start idleness."""
with self._lock:
- self._stop_locked()
+ self._require_stopped_locked()
self._start_attempted = False
def restart_if_running(self) -> None:
with self._lock:
if not self._is_running_locked():
+ # Not running here, but a previous service may have left an engine
+ # serving the old config: a refresh must not succeed beside it.
+ self._require_no_untracked_engine_locked()
return
self._stop_locked()
self._start_locked()
+ def with_engine_excluded(self, operation: Callable[[EngineClient | None], _T]) -> _T:
+ """Run ``operation`` while no engine can start, and return its result.
+
+ For removing material an engine may hold (an OAuth grant). ``operation``
+ gets the running engine's client, or ``None`` once no engine a previous
+ service left running remains (raising if that cannot be confirmed). The
+ lifecycle lock is held throughout, so no request can start an engine that
+ loads the material between this check and its removal.
+ """
+ with self._lock:
+ if self._is_running_locked() and self._connection is not None:
+ return operation(EngineClient(self._connection))
+ self._require_no_untracked_engine_locked()
+ return operation(None)
+
+ def _require_no_untracked_engine_locked(self) -> None:
+ if not self._reap_recorded_engines_locked():
+ raise EngineUnavailableError("models.engine.stop_unconfirmed", reason="previous_engine_alive")
+
def note_installation_settled(self) -> None:
"""Expose a newly verified binary as lazy-started, not previously down."""
with self._lock:
@@ -96,8 +149,10 @@ class EngineSupervisor:
"""Remove secret-bearing configs and recreate one only for a live engine."""
with self._lock:
should_restart = self._is_running_locked() and self._healthy_locked()
- if self._is_running_locked():
- self._stop_locked()
+ # Always stop: with no local handle this still reaps a recorded engine a
+ # previous service left running with the credential being revoked, and
+ # revocation must not proceed while that engine may still hold it.
+ self._require_stopped_locked()
self.state_store.clear_runtime_configs()
if should_restart:
try:
@@ -169,6 +224,11 @@ class EngineSupervisor:
def _start_locked(self) -> EngineConnection:
self._start_attempted = True
+ # A survivor shares the watched OAuth auth dir, whose grants the engine
+ # rotates in place; a second engine beside it is never safe. Each later
+ # start retries the reap, so this clears once the survivor is confirmed gone.
+ if not self._reap_recorded_engines_locked():
+ raise EngineUnavailableError("models.engine.start_failed", reason="previous_engine_alive")
managed = self.installer.status()
binary = self.installer.resolve_engine_path()
if binary is None:
@@ -195,11 +255,19 @@ class EngineSupervisor:
management_key=runtime_secrets.management_key,
gateway_token=runtime_secrets.gateway_token,
)
+ marker = new_process_identity_marker()
+ environment = engine_subprocess_environment()
+ environment[PROCESS_IDENTITY_ENV] = marker
+ launch = _EngineRecord(fingerprint_process_marker(marker))
+ if not self._store_engine_records_locked([launch]):
+ # A launch no record names would become a permanent orphan if this
+ # service died, so it never runs untracked.
+ raise EngineUnavailableError("models.engine.start_failed", reason="engine_untracked")
try:
process = self._process_factory(
[str(binary), "-config", str(config_path)],
cwd=instance_dir,
- env=engine_subprocess_environment(),
+ env=environment,
stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
@@ -207,9 +275,18 @@ class EngineSupervisor:
**isolated_subprocess_kwargs(),
)
except (OSError, ValueError) as exc:
+ # No process was created, so nothing can carry this marker: retire the
+ # launch record directly instead of scanning for a tree that never was.
+ if not self._store_engine_records_locked([]):
+ raise EngineUnavailableError("models.engine.start_failed", reason="engine_untracked") from exc
raise EngineUnavailableError("models.engine.start_failed") from exc
self._process = process
self._connection = connection
+ if not self._record_engine_locked(process, marker):
+ # The marker-only launch record still names the tree, so the stop below
+ # confirms every process it forked is gone before the record retires.
+ self._stop_locked()
+ raise EngineUnavailableError("models.engine.start_failed", reason="engine_untracked")
started_at = time.monotonic()
deadline = started_at + self.startup_timeout
exit_code: int | None = None
@@ -276,19 +353,136 @@ class EngineSupervisor:
def _is_running_locked(self) -> bool:
return self._process is not None and self._process.poll() is None
- def _stop_locked(self) -> None:
+ def _require_stopped_locked(self) -> None:
+ if not self._stop_locked():
+ raise EngineUnavailableError("models.engine.stop_unconfirmed", reason="previous_engine_alive")
+
+ def _stop_locked(self) -> bool:
+ """Stop the engine; return whether no engine it may have started remains."""
+
process = self._process
self._process = None
self._connection = None
self._health_failure_signature = None
- if process is None or process.poll() is not None:
- return
- signal_process_tree(process, signal.SIGTERM, logger, "Model Hub engine")
+ if process is not None and process.poll() is None:
+ signal_process_tree(process, signal.SIGTERM, logger, "Model Hub engine")
+ try:
+ process.wait(timeout=3)
+ except subprocess.TimeoutExpired:
+ signal_process_tree(process, KILL_SIGNAL, logger, "Model Hub engine")
+ process.wait(timeout=3)
+ # Also reached with no local handle (a restarted service): the record may
+ # still name an engine the previous service left running.
+ return self._reap_recorded_engines_locked()
+
+ @property
+ def _engine_record_path(self) -> Path:
+ return self.state_store.root / _ENGINE_PROCESS_RECORD
+
+ def _load_engine_records_locked(self) -> list[_EngineRecord] | None:
+ """Return the recorded engines, or ``None`` if the record is unreadable."""
+
+ try:
+ text: str | None = self._engine_record_path.read_text(encoding="utf-8")
+ except FileNotFoundError:
+ return []
+ except UnicodeDecodeError:
+ # Corrupt contents, like malformed JSON: nothing in it can be trusted.
+ text = None
+ except OSError:
+ logger.warning("Model Hub engine process record could not be read", exc_info=True)
+ return None
+ try:
+ payload = json.loads(text) if text is not None else None
+ except ValueError:
+ payload = None
+ entries = payload.get("engines") if isinstance(payload, dict) else None
+ records: list[_EngineRecord] = []
+ for entry in entries if isinstance(entries, list) else ():
+ fingerprint = entry.get("worker_fingerprint") if isinstance(entry, dict) else None
+ if not is_valid_worker_fingerprint(fingerprint):
+ continue
+ pid = entry.get("pid")
+ identity = process_identity_from_payload(entry, pid) if isinstance(pid, int) else None
+ records.append(_EngineRecord(fingerprint, identity))
+ return records
+
+ def _store_engine_records_locked(self, records: list[_EngineRecord]) -> bool:
+ path = self._engine_record_path
try:
- process.wait(timeout=3)
- except subprocess.TimeoutExpired:
- signal_process_tree(process, KILL_SIGNAL, logger, "Model Hub engine")
- process.wait(timeout=3)
+ if not records:
+ path.unlink(missing_ok=True)
+ return True
+ path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
+ write_atomic(
+ path,
+ json.dumps(
+ {
+ "engines": [_serialize_engine_record(record) for record in records]
+ },
+ sort_keys=True,
+ )
+ + "\n",
+ )
+ except OSError:
+ logger.warning("Model Hub engine process record could not be written", exc_info=True)
+ return False
+ return True
+
+ def _record_engine_locked(self, process: Any, marker: str) -> bool:
+ """Complete the launch record with the engine's pid; return whether it is tracked."""
+
+ pid = getattr(process, "pid", None)
+ identity = capture_spawned_process_identity(pid, marker) if isinstance(pid, int) else None
+ if identity is None:
+ return False
+ return self._store_engine_records_locked([_EngineRecord(identity.worker_fingerprint, identity)])
+
+ def _reap_recorded_engines_locked(self) -> bool:
+ """Stop every recorded engine tree; return whether all are confirmed gone.
+
+ A record with a pid is reaped by identity and group; every record is also
+ swept by its marker, which finds a launch whose pid was never recorded and
+ members that left the group, and whose answer decides the record. An
+ unreadable record is left untouched and counts as unconfirmed; unconfirmed
+ records stay for the next attempt.
+ """
+
+ records = self._load_engine_records_locked()
+ if records is None:
+ return False
+ survivors: list[_EngineRecord] = []
+ for record in records:
+ outcomes = []
+ if record.identity is not None:
+ outcomes.append(
+ reap_orphaned_process_tree(logger, "Model Hub engine", expected_identity=record.identity)
+ )
+ outcomes.append(
+ reap_marked_processes(
+ logger,
+ "Model Hub engine",
+ worker_fingerprint=record.worker_fingerprint,
+ )
+ )
+ # The marker sweep is the authority: it sees every process of the tree,
+ # including members that left the group, so its conclusive answer
+ # retires the record even when the narrower pid/group path could not.
+ if outcomes[-1] == "unconfirmed":
+ survivors.append(record)
+ elif "reaped" in outcomes:
+ logger.warning("Reaped a Model Hub engine left running by an earlier service")
+ if survivors:
+ logger.warning(
+ "Could not confirm %d earlier Model Hub engine(s) exited; keeping them tracked",
+ len(survivors),
+ )
+ return self._store_engine_records_locked(survivors) and not survivors
+
+def _serialize_engine_record(record: _EngineRecord) -> dict[str, Any]:
+ if record.identity is not None:
+ return serialize_process_identity(record.identity)
+ return {"worker_fingerprint": record.worker_fingerprint}
def _allocate_loopback_port() -> int: