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(runtime): give the service lock and restart jobs a process identity no clock adjustment moves (#2504)

Call White8b485137c675
diff --git a/scripts/incus_regression_supervisor.py b/scripts/incus_regression_supervisor.py
index fe6bced15..b3c7f8028 100644
--- a/scripts/incus_regression_supervisor.py
+++ b/scripts/incus_regression_supervisor.py
@@ -13,6 +13,7 @@ from config import paths
from config.v2_config import V2Config
from scripts.incus_regression import SERVICE_HOME, regression_show_runtime_env
from vibe import runtime
+from vibe.upgrade import restart_record_is_pending
def _read_pid_file(pid_path: Path) -> int | None:
@@ -60,7 +61,8 @@ def _adoptable_service_pid(pid: int | None) -> bool:
def _restart_in_progress() -> bool:
- status = runtime.read_json(runtime.get_restart_status_path()) or {}
+ path = runtime.get_restart_status_path()
+ status = runtime.read_json(path) or {}
# Only the active stop/start phase ("running") should suppress the supervisor's
# own recovery. A "scheduled" (delayed) restart is just sleeping and hasn't
# touched the service yet, so a crash during the delay must still be recovered
@@ -74,15 +76,9 @@ def _restart_in_progress() -> bool:
restart_pid = status.get("supervisor_pid")
if not (isinstance(restart_pid, int) and restart_pid > 0 and runtime.pid_alive(restart_pid)):
return False
- # Defend against pid reuse (notably across a reboot): confirm the live pid is
- # still the same process the restart job recorded, by start time. Only treat a
- # mismatch as stale; if either start time is unavailable, fall back to the
- # liveness check above.
- recorded_started_at = status.get("supervisor_started_at")
- current_started_at = runtime.process_create_time(restart_pid)
- if isinstance(recorded_started_at, (int, float)) and current_started_at is not None:
- return abs(current_started_at - recorded_started_at) < 1.0
- return True
+ # A live pid is the job only while its recorded identity matches (pid reuse,
+ # notably across a reboot), and one that cannot be verified only for a bounded time.
+ return restart_record_is_pending(status, path)
def _config() -> V2Config:
diff --git a/tests/test_incus_regression_supervisor.py b/tests/test_incus_regression_supervisor.py
index 88d538062..c5cb375e9 100644
--- a/tests/test_incus_regression_supervisor.py
+++ b/tests/test_incus_regression_supervisor.py
@@ -101,22 +101,22 @@ def test_preserved_custom_archive_path_cannot_split_build_and_supervisor(
def test_restart_in_progress_true_while_job_pid_alive(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
paths.ensure_data_dirs()
- _write_restart_status({"ok": None, "state": "running", "supervisor_pid": 4242, "supervisor_started_at": 1000.0})
+ _write_restart_status({"ok": None, "state": "running", "supervisor_pid": 4242, "supervisor_start_token": "1000.0"})
monkeypatch.setattr(runtime, "pid_alive", lambda pid: pid == 4242)
- monkeypatch.setattr(runtime, "process_create_time", lambda pid: 1000.0)
+ monkeypatch.setattr(runtime, "process_start_token", lambda pid: "1000.0")
assert supervisor._restart_in_progress() is True
def test_restart_in_progress_false_when_pid_reused(monkeypatch, tmp_path):
- # Pid is alive but its start time no longer matches what the job recorded —
+ # Pid is alive but its start token no longer matches what the job recorded —
# the pid was reused (e.g. after a reboot) by an unrelated process, so the
# restart is not actually in progress and recovery must proceed.
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
paths.ensure_data_dirs()
- _write_restart_status({"ok": None, "state": "running", "supervisor_pid": 4242, "supervisor_started_at": 1000.0})
+ _write_restart_status({"ok": None, "state": "running", "supervisor_pid": 4242, "supervisor_start_token": "1000.0"})
monkeypatch.setattr(runtime, "pid_alive", lambda pid: pid == 4242)
- monkeypatch.setattr(runtime, "process_create_time", lambda pid: 9999.0)
+ monkeypatch.setattr(runtime, "process_start_token", lambda pid: "9999.0")
assert supervisor._restart_in_progress() is False
diff --git a/tests/test_install_generation_retirement.py b/tests/test_install_generation_retirement.py
index 9add051eb..826187181 100644
--- a/tests/test_install_generation_retirement.py
+++ b/tests/test_install_generation_retirement.py
@@ -1301,12 +1301,12 @@ def test_pending_followup_respects_restart_ownership(
"supervisor_pid": None if owner == "seed" else 123,
}
if owner not in {"legacy", "seed"}:
- payload["supervisor_started_at"] = 100.0
+ payload["supervisor_start_token"] = "100.0"
runtime.write_json(status, payload)
if old_status:
os.utime(status, (1, 1))
monkeypatch.setattr(runtime, "pid_alive", lambda pid: owner not in {"dead", "seed"})
- monkeypatch.setattr(runtime, "process_create_time", lambda pid: 200.0 if owner == "reused" else 100.0)
+ monkeypatch.setattr(runtime, "process_start_token", lambda pid: "200.0" if owner == "reused" else "100.0")
if state == "unreadable":
original_read = Path.read_text
diff --git a/tests/test_process_start_token.py b/tests/test_process_start_token.py
new file mode 100644
index 000000000..53928935d
--- /dev/null
+++ b/tests/test_process_start_token.py
@@ -0,0 +1,207 @@
+"""A process's start token: the one identity of a running process, which no clock adjustment moves.
+
+Every record that names a process by its token -- the service lock and restart jobs -- must keep naming
+the same execution after the wall clock or the boot time moves, and must never name a process that
+later reused the pid.
+"""
+
+from __future__ import annotations
+
+import os
+import subprocess
+import sys
+import time
+from contextlib import contextmanager
+from pathlib import Path
+from unittest.mock import patch
+
+import pytest
+
+from vibe import runtime
+
+
+@contextmanager
+def _clock_adjusted():
+ """psutil's own view of the platform after the clock moved: its wall-clock start times shift."""
+
+ if sys.platform == "darwin":
+ from psutil import _psosx
+
+ # kern.boottime crossed a whole second, as routine time-daemon adjustments make it.
+ with patch.object(_psosx, "boot_time", lambda: _psosx.INIT_BOOT_TIME - 1):
+ yield 1.0
+ elif sys.platform.startswith("linux"):
+ from psutil import _pslinux
+
+ real_boot_time = _pslinux.boot_time
+ # The wall clock was stepped, which moves the boot time /proc/stat reports.
+ with patch.object(_pslinux, "boot_time", lambda: real_boot_time() - 21.0):
+ yield -21.0
+ else:
+ pytest.skip("Windows stores a process's creation time and psutil reads it back unchanged")
+
+
+def live_process():
+ process = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"])
+ try:
+ yield process
+ finally:
+ process.kill()
+ process.wait(10)
+
+
+def test_a_clock_adjustment_moves_the_wall_clock_start_but_not_the_start_token(live_process) -> None:
+ pid = live_process.pid
+ token = runtime.process_start_token(pid)
+ created = runtime.process_create_time(pid)
+ assert token is not None and created is not None
+
+ with _clock_adjusted() as shift:
+ # The adjustment is real for psutil: the wall-clock start it reports moved.
+ assert runtime.process_create_time(pid) == pytest.approx(created + shift)
+ assert runtime.process_start_token(pid) == token
+
+
[email protected]("platform", ["freebsd14", "openbsd7", "sunos5"])
+def test_a_platform_without_a_stable_start_gives_no_process_a_token(live_process, monkeypatch, platform) -> None:
+ """There psutil's start moves with system clock updates: no exact token, so every record is unverifiable."""
+
+ monkeypatch.setattr(sys, "platform", platform)
+
+ assert runtime.process_start_token(live_process.pid) is None
+
+
[email protected]("contents", ["", "\n", OSError("unreadable")], ids=["empty", "blank", "unreadable"])
+def test_a_linux_boot_id_that_cannot_be_read_is_none(monkeypatch, contents) -> None:
+ real_read_text = Path.read_text
+
+ def read_text(path, *args, **kwargs):
+ if str(path) == "/proc/sys/kernel/random/boot_id":
+ if isinstance(contents, Exception):
+ raise contents
+ return contents
+ return real_read_text(path, *args, **kwargs)
+
+ monkeypatch.setattr(Path, "read_text", read_text)
+
+ assert runtime._linux_boot_id.__wrapped__() is None
+
+
[email protected](not sys.platform.startswith("linux"), reason="the Linux token is the boot id and the start ticks")
+def test_a_linux_process_has_no_token_without_its_boot_id(live_process, monkeypatch) -> None:
+ """Start ticks restart at every boot: alone they would name a later boot's process with the same pid."""
+
+ assert runtime.process_start_token(live_process.pid).startswith(f"{runtime._linux_boot_id()}:")
+
+ monkeypatch.setattr(runtime, "_linux_boot_id", lambda: None)
+
+ assert runtime.process_start_token(live_process.pid) is None
+
+
+def _restart_job_reader(name: str, monkeypatch):
+ """One of the readers that decide whether a recorded restart job still runs."""
+
+ if name == "web-restart":
+ from vibe import ui_server
+
+ return ui_server._restart_in_flight
+ if name == "upgrade":
+ from vibe import upgrade
+
+ return upgrade.restart_is_pending
+ import importlib.util
+
+ script = Path(__file__).resolve().parents[1] / "scripts" / "incus_regression_supervisor.py"
+ spec = importlib.util.spec_from_file_location("incus_regression_supervisor", script)
+ assert spec and spec.loader
+ supervisor = importlib.util.module_from_spec(spec)
+ monkeypatch.setitem(sys.modules, spec.name, supervisor)
+ spec.loader.exec_module(supervisor)
+ return supervisor._restart_in_progress
+
+
+# Older than every reader's bound for a status it cannot verify (60 s for Web restarts, 300 s otherwise).
+_PAST_EVERY_BOUND = 3600
+
+
[email protected]("reader", ["web-restart", "upgrade", "incus-supervisor"])
+ ("record", "age", "blocks"),
+ [
+ pytest.param("token-its-job", _PAST_EVERY_BOUND, True, id="token-its-job"),
+ pytest.param("token-reused-pid", 0, False, id="token-reused-pid"),
+ pytest.param("released-its-job", _PAST_EVERY_BOUND, True, id="released-its-job"),
+ pytest.param("released-reused-pid", 0, False, id="released-reused-pid"),
+ pytest.param("no-token", 0, True, id="no-token-within-bound"),
+ pytest.param("no-token", _PAST_EVERY_BOUND, False, id="no-token-past-bound"),
+ pytest.param("token-unreadable-now", 0, True, id="unreadable-now-within-bound"),
+ pytest.param("token-unreadable-now", _PAST_EVERY_BOUND, False, id="unreadable-now-past-bound"),
+ ],
+)
+def test_every_restart_status_reader_applies_one_ownership_policy(
+ live_process, tmp_path, monkeypatch, reader, record, age, blocks
+) -> None:
+ """A running status blocks while its job is verified, and one that cannot be verified only for a bounded time.
+
+ The live process stands for the pid the status names: the job itself, or an unrelated process that
+ took its pid. A status written where no token could be read, or whose token cannot be read now,
+ cannot tell the two apart.
+ """
+
+ from config import paths
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ paths.ensure_data_dirs()
+ pid = live_process.pid
+ status = {"ok": None, "state": "running", "supervisor_pid": pid}
+ if record == "token-its-job":
+ status["supervisor_start_token"] = runtime.process_start_token(pid)
+ elif record == "token-reused-pid":
+ status["supervisor_start_token"] = "an-earlier-process"
+ elif record.startswith("released-"):
+ # A released build recorded psutil's create time; the job that had this pid started an hour earlier.
+ created = runtime.process_create_time(pid)
+ status["supervisor_started_at"] = created if record == "released-its-job" else created - 3600
+ elif record == "no-token":
+ status["supervisor_start_token"] = None
+ else:
+ status["supervisor_start_token"] = runtime.process_start_token(pid)
+ monkeypatch.setattr(runtime, "process_start_token", lambda _pid: None)
+ path = runtime.get_restart_status_path()
+ runtime.write_json(path, status)
+ written = time.time() - age
+ os.utime(path, (written, written))
+
+ assert _restart_job_reader(reader, monkeypatch)() is blocks
+
+
[email protected]("reader", ["web-restart", "upgrade", "incus-supervisor"])
+def test_a_running_restart_job_is_still_its_job_after_a_clock_adjustment(live_process, tmp_path, monkeypatch, reader) -> None:
+ from config import paths
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ paths.ensure_data_dirs()
+ pid = live_process.pid
+ path = runtime.get_restart_status_path()
+ runtime.write_json(
+ path,
+ {"ok": None, "state": "running", "supervisor_pid": pid, "supervisor_start_token": runtime.process_start_token(pid)},
+ )
+ # Past every bound, so only its identity can keep it the job.
+ written = time.time() - _PAST_EVERY_BOUND
+ os.utime(path, (written, written))
+ in_flight = _restart_job_reader(reader, monkeypatch)
+
+ with _clock_adjusted():
+ assert in_flight() is True
+
+
[email protected](sys.platform != "darwin", reason="the unadjusted start time is read through psutil on macOS")
+def test_psutil_still_offers_the_unadjusted_start_time_its_identity_uses() -> None:
+ """``create_time(monotonic=True)`` is private to psutil; a release without it must fail here, not in the field."""
+
+
+ import psutil
+
+ assert isinstance(psutil.Process(os.getpid())._proc.create_time(monotonic=True), float)
diff --git a/tests/test_restart_supervisor.py b/tests/test_restart_supervisor.py
index 88b2df0ac..8c554ee1a 100644
--- a/tests/test_restart_supervisor.py
+++ b/tests/test_restart_supervisor.py
@@ -364,7 +364,7 @@ def test_restart_job_stops_and_starts_service(monkeypatch, tmp_path, scope, read
# The job records its own pid + start time so a watcher can validate the
# restart is live and not a reused pid.
assert status["supervisor_pid"] == os.getpid()
- assert isinstance(status["supervisor_started_at"], (int, float))
+ assert status["supervisor_start_token"] == runtime.process_start_token(os.getpid())
assert status["stage_durations"]["stop_remote_access_seconds"] == 0.01
assert status["stage_durations"]["stop_remote_access_skipped"] is True
assert "stop_ui_total_seconds" in status["stage_durations"]
diff --git a/tests/test_service_lock_record.py b/tests/test_service_lock_record.py
index 3460a20e9..bba1ba479 100644
--- a/tests/test_service_lock_record.py
+++ b/tests/test_service_lock_record.py
@@ -325,6 +325,18 @@ class ServiceLockContentionTests(unittest.TestCase):
runtime.acquire_service_instance_lock()
self.assertEqual(refused.exception.holder_pid, holder.pid)
+ def test_a_holder_whose_start_cannot_be_read_now_is_refused_once_the_wait_runs_out(self):
+ """Unverifiable, it names no one: the wait is bounded, and the lock it holds is never taken."""
+
+ holder = self._holder()
+ began = time.monotonic()
+ with patch.object(runtime, "process_start_token", return_value=None), self.assertRaises(
+ runtime.ServiceAlreadyRunningError
+ ) as refused:
+ runtime.acquire_service_instance_lock()
+ self.assertEqual(refused.exception.holder_pid, holder.pid)
+ self.assertLess(time.monotonic() - began, runtime._SERVICE_LOCK_SETTLE_SECONDS + 3)
+
def test_a_service_started_right_after_the_last_was_killed_takes_the_lock(self):
"""The acceptance test's own order: kill the service outright, start the next."""
@@ -362,6 +374,29 @@ class ServiceLockContentionTests(unittest.TestCase):
runtime.acquire_service_instance_lock()
self.assertEqual(refused.exception.holder_pid, holder.pid)
+ @unittest.skipUnless(sys.platform == "darwin", "macOS moves kern.boottime in routine clock adjustments")
+ def test_a_running_service_is_still_recognised_after_kern_boottime_ticks(self):
+ """psutil's macOS start time moves with kern.boottime; the holder's identity must not.
+
+ psutil adds the change in whole seconds of kern.boottime since it was
+ imported, and the system time daemon moves kern.boottime across a whole
+ second in routine adjustments. The holder then reads exactly one second
+ away from its record, in this process and in no fresh one.
+ """
+
+ from psutil import _psosx
+
+ holder = self._holder()
+ before = runtime.process_create_time(holder.pid)
+ with patch.object(_psosx, "boot_time", lambda: _psosx.INIT_BOOT_TIME - 1), patch.object(
+ runtime.time, "sleep", side_effect=AssertionError("waited for a running service")
+ ):
+ self.assertEqual(runtime.process_create_time(holder.pid), before + 1.0)
+ self.assertEqual(runtime.service_instance_lock_available(settle=True), (False, holder.pid))
+ with self.assertRaises(runtime.ServiceAlreadyRunningError) as refused:
+ runtime.acquire_service_instance_lock()
+ self.assertEqual(refused.exception.holder_pid, holder.pid)
+
def test_checks_outside_a_start_answer_from_one_attempt(self):
"""The service asks these on its event loop, where a wait stalls everything behind it."""
diff --git a/tests/test_vibe_cli.py b/tests/test_vibe_cli.py
index c69dfeb84..40c48dc68 100644
--- a/tests/test_vibe_cli.py
+++ b/tests/test_vibe_cli.py
@@ -2739,7 +2739,7 @@ def _restart_status_payload(**overrides) -> dict:
"ok": False,
"job_id": "0d1f2e3a4b5c",
"supervisor_pid": 4242,
- "supervisor_started_at": 1.0,
+ "supervisor_start_token": "1.0",
"state": "failed",
"trigger": "auto-update",
"delay_seconds": 0.0,
diff --git a/tests/test_web_ui_watchdog.py b/tests/test_web_ui_watchdog.py
index a4b67419a..b281467f2 100644
--- a/tests/test_web_ui_watchdog.py
+++ b/tests/test_web_ui_watchdog.py
@@ -108,7 +108,7 @@ def _restart_job(state: str) -> None:
"ok": None,
"state": state,
"supervisor_pid": os.getpid(),
- "supervisor_started_at": runtime.process_create_time(os.getpid()),
+ "supervisor_start_token": runtime.process_start_token(os.getpid()),
},
)
diff --git a/vibe/restart_supervisor.py b/vibe/restart_supervisor.py
index 3e8ab8b2f..09b0d45d5 100644
--- a/vibe/restart_supervisor.py
+++ b/vibe/restart_supervisor.py
@@ -429,7 +429,7 @@ def _run_restart_job(
# process that later reused the pid. Matches the key schedule_restart
# seeds with the spawned subprocess pid (this process is that pid).
"supervisor_pid": os.getpid(),
- "supervisor_started_at": runtime.process_create_time(os.getpid()),
+ "supervisor_start_token": runtime.process_start_token(os.getpid()),
"state": RestartState.SCHEDULED.value if delay_seconds > 0 else RestartState.RUNNING.value,
"trigger": trigger,
"delay_seconds": delay_seconds,
diff --git a/vibe/runtime.py b/vibe/runtime.py
index 7b57b50d7..b0392ac9b 100644
--- a/vibe/runtime.py
+++ b/vibe/runtime.py
@@ -826,23 +826,44 @@ def process_create_time(pid: int) -> float | None:
@lru_cache(maxsize=1)
-def _linux_boot_id() -> str:
+def _linux_boot_id() -> str | None:
try:
- return Path("/proc/sys/kernel/random/boot_id").read_text(encoding="utf-8").strip()
+ boot_id = Path("/proc/sys/kernel/random/boot_id").read_text(encoding="utf-8").strip()
except OSError:
- return ""
+ return None
+ return boot_id or None
def process_start_token(pid: int) -> str | None:
- """When a process started, as a value no clock step changes; None if it cannot be read.
-
- Linux counts a process's start in clock ticks since boot (field 22 of
- ``/proc/<pid>/stat``). psutil turns that into wall-clock time through the
- boot time, which moves whenever the clock is stepped -- by a VM's time
- sync, a WSL2 resume, NTP catching up after boot -- so the same process
- reads as started at another time afterwards. The ticks, with the boot they
- count from, do not move. Elsewhere the start time is stored when the
- process is created, and reads back unchanged.
+ """When a process started, as a value no clock adjustment changes; None if it cannot be read.
+
+ This is the one identity of a running process: a recorded ``(pid, token)``
+ still names the same execution after the wall clock or the boot time moves,
+ or the machine reboots, and never names a process that later reused the
+ pid. A token is returned only when every part of it was read; otherwise
+ None, which every caller treats as unverifiable.
+
+ - Linux counts a process's start in clock ticks since boot (field 22 of
+ ``/proc/<pid>/stat``). psutil turns that into wall-clock time through the
+ boot time, which moves whenever the clock is stepped -- by a VM's time
+ sync, a WSL2 resume, NTP catching up after boot. The ticks, with the boot
+ they count from, do not move. Ticks restart at every boot, so without
+ the boot id there is no token.
+ - macOS (and NetBSD) store the wall-clock time a process started, but
+ psutil's ``create_time()`` adds the change in whole seconds of
+ ``kern.boottime`` since psutil was imported, and the system time daemon
+ moves ``kern.boottime`` in routine adjustments. The same process then
+ reads a second later or earlier, and differently in two processes that
+ imported psutil at different times. The stored value is what psutil
+ itself uses for process identity (``Process._get_ident``), through
+ ``create_time(monotonic=True)``. That accessor is private, so a psutil
+ without it reads as None.
+ - Windows stores the creation time with the process, and psutil reads it
+ back unchanged.
+ - Elsewhere (FreeBSD, OpenBSD, ...) the start psutil reads moves with
+ system clock updates, as psutil itself warns, and no stable one is
+ available: no process there has a token, so a record of one is
+ unverifiable.
"""
if sys.platform.startswith("linux"):
@@ -850,9 +871,19 @@ def process_start_token(pid: int) -> str | None:
ticks = Path(f"/proc/{pid}/stat").read_text(encoding="utf-8").rsplit(")", 1)[1].split()[19]
except (OSError, IndexError, ValueError):
return None
- return f"{_linux_boot_id()}:{ticks}"
- create_time = process_create_time(pid)
- return None if create_time is None else repr(create_time)
+ boot_id = _linux_boot_id()
+ if boot_id is None or not ticks.isdigit():
+ return None
+ return f"{boot_id}:{ticks}"
+ monotonic = sys.platform == "darwin" or sys.platform.startswith("netbsd")
+ if not monotonic and sys.platform != "win32":
+ return None
+ try:
+ process = psutil.Process(pid)
+ start = process._proc.create_time(monotonic=True) if monotonic else process.create_time()
+ return repr(float(start))
+ except (psutil.Error, AttributeError, TypeError, ValueError, OSError):
+ return None
def _safe_resolve_path(value: str | Path) -> Path | None:
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index c777780ff..bca13b6ba 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -6812,9 +6812,10 @@ def version():
# could both pass the check before either seeds restart_status.json, scheduling
# two supervisors that race on the same pid files + lock.
_RESTART_CONTROL_LOCK = threading.Lock()
-# How long a just-seeded, pid-less "scheduled" status is treated as in flight
-# (its supervisor is still starting up). Past this, a pid-less status is stale
-# (the supervisor died before recording its pid) and must NOT block restarts.
+# How long a restart status whose job cannot be verified is treated as in
+# flight: a just-seeded, pid-less status (its supervisor is still starting up),
+# or a live pid whose identity cannot be read. Past this such a status is stale
+# and must NOT block restarts.
_RESTART_SEED_GRACE_SECONDS = 60.0
@@ -6822,32 +6823,18 @@ def _restart_in_flight() -> bool:
"""True only when a restart is genuinely still running, so a stale status
can never permanently block Web restarts."""
from vibe import runtime
+ from vibe.upgrade import restart_record_is_pending
- status = runtime.read_json(runtime.get_restart_status_path()) or {}
- if status.get("state") not in ("scheduled", "running"):
- return False
+ path = runtime.get_restart_status_path()
+ status = runtime.read_json(path) or {}
sup_pid = status.get("supervisor_pid")
- if isinstance(sup_pid, int):
- if not runtime.pid_alive(sup_pid):
- return False
- # Guard against PID reuse: a dead supervisor's pid can be reclaimed by an
- # unrelated process (notably across a reboot), which would otherwise keep
- # blocking restarts until that process exits. The job records its
- # ``supervisor_started_at`` (process create time), so only treat the pid
- # as the live supervisor when the create time still matches.
- started_at = status.get("supervisor_started_at")
- if started_at is not None:
- current = runtime.process_create_time(sup_pid)
- if current is not None and current != started_at:
- return False
- return True
- # No supervisor pid recorded yet: in flight only while the seed is fresh
- # (the child is still starting). An older pid-less status is stale.
- try:
- age = time.time() - runtime.get_restart_status_path().stat().st_mtime
- except OSError:
+ if isinstance(sup_pid, int) and not runtime.pid_alive(sup_pid):
+ # A job that has exited runs no restart, whatever its status says.
return False
- return age < _RESTART_SEED_GRACE_SECONDS
+ # A live pid is the job only while its recorded identity matches: a pid
+ # reclaimed by an unrelated process (notably across a reboot) would
+ # otherwise keep blocking restarts until that process exits.
+ return restart_record_is_pending(status, path, grace_seconds=_RESTART_SEED_GRACE_SECONDS)
def _runtime_refusal_payload(action: str, refusal: "DesktopRuntimeClaimRefused") -> dict[str, Any]:
diff --git a/vibe/upgrade.py b/vibe/upgrade.py
index 3d614953b..00049b3aa 100644
--- a/vibe/upgrade.py
+++ b/vibe/upgrade.py
@@ -253,7 +253,14 @@ def restart_record_is_pending(
*,
grace_seconds: float = RESTART_PENDING_GRACE_SECONDS,
) -> bool:
- """Apply the restart ownership policy to one persisted status record."""
+ """Apply the restart ownership policy to one persisted status record.
+
+ The one policy every reader of the restart status applies. A live
+ supervisor pid is the job while its recorded identity matches: its start
+ token, or the create time a job a released build ran recorded. A record
+ that cannot be verified -- no pid yet, no identity recorded, or none
+ readable now -- owns the restart only until it is ``grace_seconds`` old.
+ """
try:
state = RestartState(payload.get("state"))
@@ -263,14 +270,21 @@ def restart_record_is_pending(
return False
supervisor_pid = payload.get("supervisor_pid")
if isinstance(supervisor_pid, int) and supervisor_pid > 0 and runtime_mod.pid_alive(supervisor_pid):
+ start_token = payload.get("supervisor_start_token")
started_at = payload.get("supervisor_started_at")
- if started_at is not None:
+ if start_token is not None:
+ current_start_token = runtime_mod.process_start_token(supervisor_pid)
+ if current_start_token is not None:
+ return current_start_token == start_token
+ elif started_at is not None:
+ # A job a released build ran recorded its create time instead.
current_started_at = runtime_mod.process_create_time(supervisor_pid)
if current_started_at is not None:
return current_started_at == started_at
- # Legacy records do not carry a process identity, and process metadata
- # can be unavailable. In both cases a reused PID must not block upgrades
- # for the lifetime of an unrelated process, so fall through to age.
+ # A record with no identity (from before identities, or written where
+ # none could be read) and one whose identity cannot be read now cannot
+ # tell the job from a reused PID, which must not block upgrades for the
+ # lifetime of an unrelated process, so fall through to age.
try:
age = time.time() - path.stat().st_mtime
except OSError: