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): keep the service lock off the event loop and its holder's identity off the wall clock (#2494)

Call White1ec426f7e1ab
diff --git a/tests/test_install_generation_retirement.py b/tests/test_install_generation_retirement.py
index d53bd3d41..9add051eb 100644
--- a/tests/test_install_generation_retirement.py
+++ b/tests/test_install_generation_retirement.py
@@ -419,14 +419,14 @@ def test_real_official_child_is_kept_until_exit(installation, monkeypatch, tmp_p
cwd=tmp_path, text=True,
)
monkeypatch.setattr(retention, "_runtime_paths", OFFICIAL_PATHS)
- monkeypatch.setattr(runtime, "service_instance_lock_available", lambda: (True, None))
+ monkeypatch.setattr(runtime, "service_instance_lock_available", lambda **kwargs: (True, None))
try:
assert process.stdout.readline().strip() == "ready"
paths.get_runtime_dir().mkdir(parents=True, exist_ok=True)
if record == "status":
paths.get_runtime_status_path().write_text(json.dumps({"service_pid": process.pid}))
elif record == "lock-holder":
- monkeypatch.setattr(runtime, "service_instance_lock_available", lambda: (False, process.pid))
+ monkeypatch.setattr(runtime, "service_instance_lock_available", lambda **kwargs: (False, process.pid))
else:
path = paths.get_runtime_pid_path() if record == "service-pid" else paths.get_runtime_ui_pid_path()
path.write_text(str(process.pid))
@@ -436,7 +436,7 @@ def test_real_official_child_is_kept_until_exit(installation, monkeypatch, tmp_p
assert current.exists()
finally:
process.communicate("\n", timeout=10)
- monkeypatch.setattr(runtime, "service_instance_lock_available", lambda: (True, None))
+ monkeypatch.setattr(runtime, "service_instance_lock_available", lambda **kwargs: (True, None))
collect(launcher)
assert not exported.parent.parent.exists()
assert current.exists()
@@ -449,10 +449,10 @@ def test_unreadable_official_reference_defers_without_invalidating_activation(
root, launcher = installation
old = candidate(root, "official")
monkeypatch.setattr(retention, "_runtime_paths", OFFICIAL_PATHS)
- monkeypatch.setattr(runtime, "service_instance_lock_available", lambda: (True, None))
+ monkeypatch.setattr(runtime, "service_instance_lock_available", lambda **kwargs: (True, None))
paths.get_runtime_dir().mkdir(parents=True, exist_ok=True)
if boundary == "lock-owner":
- monkeypatch.setattr(runtime, "service_instance_lock_available", lambda: (False, None))
+ monkeypatch.setattr(runtime, "service_instance_lock_available", lambda **kwargs: (False, None))
elif boundary == "status":
paths.get_runtime_status_path().write_text("{")
elif boundary == "pid":
@@ -478,7 +478,7 @@ def test_windows_official_base_python_child_keeps_redirector_generation(installa
root, launcher = installation
old = candidate(root, "official-ui")
monkeypatch.setattr(retention, "_runtime_paths", OFFICIAL_PATHS)
- monkeypatch.setattr(runtime, "service_instance_lock_available", lambda: (True, None))
+ monkeypatch.setattr(runtime, "service_instance_lock_available", lambda **kwargs: (True, None))
monkeypatch.setattr(retention, "sys", SimpleNamespace(platform="win32"))
paths.get_runtime_dir().mkdir(parents=True, exist_ok=True)
paths.get_runtime_ui_pid_path().write_text("123")
@@ -501,7 +501,7 @@ def test_windows_redirector_loss_is_not_the_official_child_exiting(
root, launcher = installation
old = candidate(root, "official-ui")
monkeypatch.setattr(retention, "_runtime_paths", OFFICIAL_PATHS)
- monkeypatch.setattr(runtime, "service_instance_lock_available", lambda: (True, None))
+ monkeypatch.setattr(runtime, "service_instance_lock_available", lambda **kwargs: (True, None))
monkeypatch.setattr(retention, "sys", SimpleNamespace(platform="win32"))
paths.get_runtime_dir().mkdir(parents=True, exist_ok=True)
paths.get_runtime_ui_pid_path().write_text("123")
diff --git a/tests/test_restart_supervisor.py b/tests/test_restart_supervisor.py
index da4374de5..88b2df0ac 100644
--- a/tests/test_restart_supervisor.py
+++ b/tests/test_restart_supervisor.py
@@ -768,7 +768,7 @@ def test_restart_job_waits_for_service_lock_release_before_start(monkeypatch, tm
lock_checks = iter([(False, 111), (True, None)])
- def service_instance_lock_available():
+ def service_instance_lock_available(**kwargs):
calls.append("lock_available")
return next(lock_checks)
diff --git a/tests/test_service_lock_record.py b/tests/test_service_lock_record.py
index 1ea7a24a8..3460a20e9 100644
--- a/tests/test_service_lock_record.py
+++ b/tests/test_service_lock_record.py
@@ -305,7 +305,7 @@ class ServiceLockContentionTests(unittest.TestCase):
unrelated = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"])
self.addCleanup(unrelated.wait, 10)
self.addCleanup(unrelated.kill)
- self._hold_like_a_check(record=json.dumps({"pid": unrelated.pid, "started_at": 1.0}))
+ self._hold_like_a_check(record=json.dumps({"pid": unrelated.pid, "start_token": "not-its-start"}))
self._acquire()
def test_a_record_without_a_start_time_names_no_one_while_a_check_holds_the_lock(self):
@@ -341,6 +341,35 @@ class ServiceLockContentionTests(unittest.TestCase):
self.assertLess(time.monotonic() - began, runtime._SERVICE_LOCK_SETTLE_SECONDS)
self.assertEqual(refused.exception.holder_pid, holder.pid)
+ @unittest.skipUnless(sys.platform.startswith("linux"), "only Linux derives a start time from the boot time")
+ def test_a_running_service_is_still_recognised_after_the_clock_is_stepped(self):
+ """psutil's Linux start time moves with the clock; the holder's identity must not.
+
+ A VM's time sync, a WSL2 resume or NTP after boot steps the wall clock,
+ and psutil derives a Linux process's start time from the boot time that
+ step moves: the same holder then reads as started 21 seconds away from
+ its record. Recognising it by that time made every check wait out the
+ bound for a service that was running.
+ """
+
+ holder = self._holder()
+ real_create_time = runtime.psutil.Process.create_time
+ with patch.object(
+ runtime.psutil.Process, "create_time", lambda process: real_create_time(process) - 21.0
+ ), patch.object(runtime.time, "sleep", side_effect=AssertionError("waited for a running service")):
+ 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."""
+
+ self._hold_like_a_check()
+ with patch.object(runtime.time, "sleep", side_effect=AssertionError("a check waited")):
+ self.assertEqual(runtime.service_instance_lock_available(), (False, None))
+ self.assertFalse(runtime.service_lock_held_by(os.getpid()))
+
def test_a_check_still_reads_a_running_service_at_once(self):
holder = self._holder()
began = time.monotonic()
@@ -348,6 +377,54 @@ class ServiceLockContentionTests(unittest.TestCase):
self.assertLess(time.monotonic() - began, runtime._SERVICE_LOCK_SETTLE_SECONDS)
+class ServiceOwnsItsLockTests(unittest.TestCase):
+ """The running service's own question, asked on its event loop by every lane.
+
+ It is answered from the handle the service holds: taking the lock again,
+ or reading a record that a clock step can make unrecognisable, cost each
+ call the full wait and stalled turns, scheduled tasks and watches.
+ """
+
+ def setUp(self) -> None:
+ tmp = TemporaryDirectory()
+ self.addCleanup(tmp.cleanup)
+ runtime_dir = Path(tmp.name) / "runtime"
+ runtime_dir.mkdir(parents=True)
+ self.lock_path = runtime_dir / "service.lock"
+ for started in (
+ patch("vibe.runtime.ensure_dirs", return_value=None),
+ patch("vibe.runtime.paths.get_runtime_service_lock_path", return_value=self.lock_path),
+ patch("vibe.runtime.paths.get_runtime_pid_path", return_value=runtime_dir / "vibe.pid"),
+ ):
+ started.start()
+ self.addCleanup(started.stop)
+ self.addCleanup(runtime.release_service_instance_lock)
+ runtime.acquire_service_instance_lock()
+
+ def test_the_owner_knows_without_taking_the_lock_or_waiting(self):
+ with patch.object(runtime, "_take_lock_file", side_effect=AssertionError("took the lock")), patch.object(
+ runtime.time, "sleep", side_effect=AssertionError("waited")
+ ), patch.object(runtime, "process_start_token", side_effect=AssertionError("read its start")):
+ self.assertTrue(runtime.current_process_owns_service_instance())
+
+ def test_a_released_lock_is_no_longer_owned(self):
+ runtime.release_service_instance_lock()
+ self.assertFalse(runtime.current_process_owns_service_instance())
+
+ def test_a_child_that_inherited_the_handle_does_not_own_it(self):
+ with patch.object(runtime, "_SERVICE_INSTANCE_LOCK_OWNER_PID", os.getpid() + 1):
+ self.assertFalse(runtime.current_process_owns_service_instance())
+
+ @unittest.skipIf(os.name == "nt", "Windows cannot remove a file this process holds open")
+ def test_a_lock_file_replaced_under_the_service_is_no_longer_owned(self):
+ """Another service could lock the new file, so this one must stop scheduling."""
+
+ self.lock_path.unlink()
+ self.assertFalse(runtime.current_process_owns_service_instance())
+ self.lock_path.write_text("", encoding="utf-8")
+ self.assertFalse(runtime.current_process_owns_service_instance())
+
+
@unittest.skipUnless(os.name == "nt", "Windows byte-range lock semantics")
class WindowsMandatoryLockFactTests(unittest.TestCase):
"""The platform fact the fix rests on, pinned so nobody re-derives it.
diff --git a/tests/test_service_logging_handlers.py b/tests/test_service_logging_handlers.py
index 553a932c9..32478b31b 100644
--- a/tests/test_service_logging_handlers.py
+++ b/tests/test_service_logging_handlers.py
@@ -58,7 +58,7 @@ def test_start_service_disables_stdout_logging_for_background_process(monkeypatc
monkeypatch.setattr(runtime.paths, "get_runtime_pid_path", lambda: pid_path)
monkeypatch.setattr(runtime, "pid_alive", lambda pid: False)
monkeypatch.setattr(runtime, "get_service_main_path", lambda: Path("/tmp/main.py"))
- monkeypatch.setattr(runtime, "service_instance_lock_available", lambda: (True, 0))
+ monkeypatch.setattr(runtime, "service_instance_lock_available", lambda **kwargs: (True, 0))
# Exercise the generic (non-scoped) spawn path deterministically: on a Linux
# dev host maybe_systemd_scope_prefix() is truthy and would route through the
# scoped poll-and-adopt path instead of wait_for_service_pid.
diff --git a/tests/test_vibe_cli.py b/tests/test_vibe_cli.py
index 612a3fe19..c69dfeb84 100644
--- a/tests/test_vibe_cli.py
+++ b/tests/test_vibe_cli.py
@@ -575,7 +575,7 @@ def test_status_and_doctor_report_a_service_older_than_the_last_activation(split
[sys.executable, "-c", "import time; time.sleep(60)", str(split.old / "uv" / "tools" / "avibe-os" / "bin" / "vibe")]
)
try:
- monkeypatch.setattr(runtime, "service_instance_lock_available", lambda: (False, service.pid))
+ monkeypatch.setattr(runtime, "service_instance_lock_available", lambda **kwargs: (False, service.pid))
expected = {
"generation": str(split.old),
"version": "1.4.0",
@@ -1376,7 +1376,7 @@ def start_runtime(monkeypatch):
monkeypatch.setattr(runtime, "ui_server_compatible", lambda host, port: True)
monkeypatch.setattr(runtime, "service_pid_recorded", lambda pid: True)
monkeypatch.setattr(runtime, "wait_for_service_ready", lambda pid, timeout: pid)
- monkeypatch.setattr(runtime, "service_instance_lock_available", lambda: (True, None))
+ monkeypatch.setattr(runtime, "service_instance_lock_available", lambda **kwargs: (True, None))
monkeypatch.setattr(runtime, "extra_service_process_pids", lambda **kwargs: [])
monkeypatch.setattr(runtime, "maybe_systemd_scope_prefix", lambda: [])
monkeypatch.setattr(runtime, "wait_for_service_pid", lambda pid, timeout: True)
@@ -1436,7 +1436,7 @@ def test_start_service_marks_every_existing_return_as_reused(monkeypatch, start_
monkeypatch.setattr(runtime, "_pid_reservation_is_fresh", lambda *args: True)
monkeypatch.setattr(runtime, "wait_for_service_ready", lambda pid, timeout: 9012)
monkeypatch.setattr(runtime, "_pid_mismatches_service", lambda pid: branch == "mismatched_command")
- monkeypatch.setattr(runtime, "service_instance_lock_available", lambda: (False, 1234))
+ monkeypatch.setattr(runtime, "service_instance_lock_available", lambda **kwargs: (False, 1234))
info = runtime.ProcessStartInfo()
expected_pid = 1234 if branch == "starting" else 9012
@@ -2802,7 +2802,7 @@ def _stub_service_liveness(
monkeypatch.setattr(cli.runtime, "resolve_service_owner_pid", resolve_owner)
monkeypatch.setattr(cli.runtime, "extra_service_process_pids", lambda *_a, **_kw: list(extra_pids))
- monkeypatch.setattr(cli.runtime, "service_instance_lock_available", lambda: (not holds_lock, owner_pid))
+ monkeypatch.setattr(cli.runtime, "service_instance_lock_available", lambda **kwargs: (not holds_lock, owner_pid))
monkeypatch.setattr(
cli.runtime,
"service_instance_started",
diff --git a/vibe/runtime.py b/vibe/runtime.py
index b90818811..7b57b50d7 100644
--- a/vibe/runtime.py
+++ b/vibe/runtime.py
@@ -19,6 +19,7 @@ import uuid
from dataclasses import dataclass
from datetime import datetime, timezone
from enum import Enum
+from functools import lru_cache
from pathlib import Path
from typing import Callable, NamedTuple
@@ -153,6 +154,7 @@ ROOT_DIR = get_project_root() # For backward compatibility
MAIN_PATH = get_service_main_path()
_SERVICE_LOCK = threading.Lock()
_SERVICE_INSTANCE_LOCK_HANDLE = None
+_SERVICE_INSTANCE_LOCK_OWNER_PID: int | None = None
_PENDING_SQLITE_BACKUP_READINESS: tuple[Path, str, tuple[str, ...], datetime] | None = None
_SERVICE_START_PROCESSES: dict[int, subprocess.Popen] = {}
# /ready can spend up to two seconds in the Controller health probe.
@@ -313,6 +315,12 @@ def _take_lock_file(lock_file) -> bool:
# its resources allow. Neither names a live process in the record, which a
# service writes the moment it takes the lock, so only that state is waited
# out, and only this long; a live holder is answered at once.
+#
+# Only a start or a stop waits: the service taking the lock, a launcher
+# deciding whether one already runs, and `vibe stop` deciding whether anything
+# still holds it. Every other check answers from a single attempt, because
+# the service asks some of them on its event loop, where a wait stalls every
+# turn and lane behind it.
_SERVICE_LOCK_SETTLE_SECONDS = 2.0
_SERVICE_LOCK_SETTLE_INTERVAL_SECONDS = 0.02
@@ -321,7 +329,7 @@ def _lock_file_names_live_holder(lock_file) -> bool:
"""Whether the record names a process that is running and is the one that wrote it.
A record outlives its holder when a service is killed or the machine stops,
- and its pid can pass to an unrelated process. The holder's start time,
+ and its pid can pass to an unrelated process. The holder's start token,
written beside the pid, tells the two apart. A record without one, as an
older release writes it, cannot be told apart and names no one: a holder
that wrote it keeps the lock, and is refused once the wait runs out.
@@ -332,13 +340,10 @@ def _lock_file_names_live_holder(lock_file) -> bool:
return False
try:
lock_file.seek(0)
- started_at = json.loads(lock_file.read() or "{}").get("started_at")
+ start_token = json.loads(lock_file.read() or "{}").get("start_token")
except (OSError, json.JSONDecodeError, TypeError, AttributeError):
return False
- if not isinstance(started_at, (int, float)):
- return False
- create_time = process_create_time(pid)
- return create_time is not None and abs(create_time - started_at) < 1.0
+ return isinstance(start_token, str) and process_start_token(pid) == start_token
def _take_service_lock(lock_file) -> bool:
@@ -356,9 +361,9 @@ def _take_service_lock(lock_file) -> bool:
return True
-def _try_lock_file(lock_file) -> bool:
+def _try_lock_file(lock_file, *, settle: bool = False) -> bool:
try:
- return _take_service_lock(lock_file)
+ return _take_service_lock(lock_file) if settle else _take_lock_file(lock_file)
except OSError:
return False
@@ -383,20 +388,21 @@ def _unlock_file(lock_file) -> None:
def acquire_service_instance_lock() -> None:
"""Acquire the data-dir scoped service runtime lock for this process lifetime."""
- global _SERVICE_INSTANCE_LOCK_HANDLE
+ global _SERVICE_INSTANCE_LOCK_HANDLE, _SERVICE_INSTANCE_LOCK_OWNER_PID
if _SERVICE_INSTANCE_LOCK_HANDLE is not None:
return
ensure_dirs()
lock_path = get_service_lock_path()
lock_path.parent.mkdir(parents=True, exist_ok=True)
lock_file = lock_path.open("a+", encoding="utf-8")
- if not _try_lock_file(lock_file):
+ if not _try_lock_file(lock_file, settle=True):
holder_pid = _lock_file_pid(lock_file)
lock_file.close()
raise ServiceAlreadyRunningError(lock_path=lock_path, holder_pid=holder_pid)
_write_service_instance_lock_record(lock_file, SERVICE_PHASE_STARTING)
paths.get_runtime_pid_path().write_text(str(os.getpid()), encoding="utf-8")
_SERVICE_INSTANCE_LOCK_HANDLE = lock_file
+ _SERVICE_INSTANCE_LOCK_OWNER_PID = os.getpid()
def _write_service_instance_lock_record(lock_file, phase: str) -> None:
@@ -409,6 +415,7 @@ def _write_service_instance_lock_record(lock_file, phase: str) -> None:
"instance_id": uuid.uuid4().hex,
"created_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
"started_at": process_create_time(os.getpid()),
+ "start_token": process_start_token(os.getpid()),
"phase": phase,
"command": get_process_command(os.getpid()),
},
@@ -534,12 +541,13 @@ def service_instance_still_starting(pid: int) -> bool:
def release_service_instance_lock() -> None:
- global _SERVICE_INSTANCE_LOCK_HANDLE, _PENDING_SQLITE_BACKUP_READINESS
+ global _SERVICE_INSTANCE_LOCK_HANDLE, _SERVICE_INSTANCE_LOCK_OWNER_PID, _PENDING_SQLITE_BACKUP_READINESS
_PENDING_SQLITE_BACKUP_READINESS = None
lock_file = _SERVICE_INSTANCE_LOCK_HANDLE
if lock_file is None:
return
_SERVICE_INSTANCE_LOCK_HANDLE = None
+ _SERVICE_INSTANCE_LOCK_OWNER_PID = None
try:
try:
paths.get_runtime_pid_path().unlink(missing_ok=True)
@@ -556,14 +564,19 @@ def release_service_instance_lock() -> None:
lock_file.close()
-def service_instance_lock_available() -> tuple[bool, int | None]:
- """Return whether the data-dir scoped service lock can be acquired."""
+def service_instance_lock_available(*, settle: bool = False) -> tuple[bool, int | None]:
+ """Return whether the data-dir scoped service lock can be acquired.
+
+ ``settle`` is for a caller deciding whether to start a service; see
+ ``_SERVICE_LOCK_SETTLE_SECONDS``. It may wait, so nothing on an event loop
+ passes it.
+ """
ensure_dirs()
lock_path = get_service_lock_path()
lock_path.parent.mkdir(parents=True, exist_ok=True)
lock_file = lock_path.open("a+", encoding="utf-8")
try:
- if _try_lock_file(lock_file):
+ if _try_lock_file(lock_file, settle=settle):
_unlock_file(lock_file)
return True, None
return False, _lock_file_pid(lock_file)
@@ -585,10 +598,22 @@ def current_process_owns_service_instance() -> bool:
at construction time. A real service process constructs them only after
acquiring the lock, so losing this handle later means the process must stop
scheduling work.
+
+ It is answered from the handle this process holds, and so asked freely on
+ the event loop: no lock is taken and nothing waits. The lease is gone once
+ the handle is released, in a child that inherited it, or when the file it
+ locks is no longer the one at the lock path -- removed or replaced, so that
+ another service could lock the new one.
"""
- if _SERVICE_INSTANCE_LOCK_HANDLE is None:
+ lock_file = _SERVICE_INSTANCE_LOCK_HANDLE
+ if lock_file is None or _SERVICE_INSTANCE_LOCK_OWNER_PID != os.getpid():
+ return False
+ try:
+ held = os.fstat(lock_file.fileno())
+ current = os.stat(get_service_lock_path())
+ except (OSError, ValueError):
return False
- return service_lock_held_by(os.getpid())
+ return (held.st_dev, held.st_ino) == (current.st_dev, current.st_ino)
def service_instance_lock_attached_to_process() -> bool:
@@ -800,6 +825,36 @@ def process_create_time(pid: int) -> float | None:
return None
+@lru_cache(maxsize=1)
+def _linux_boot_id() -> str:
+ try:
+ return Path("/proc/sys/kernel/random/boot_id").read_text(encoding="utf-8").strip()
+ except OSError:
+ return ""
+
+
+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.
+ """
+
+ if sys.platform.startswith("linux"):
+ try:
+ 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)
+
+
def _safe_resolve_path(value: str | Path) -> Path | None:
try:
return Path(value).expanduser().resolve()
@@ -2144,7 +2199,7 @@ def _resolve_service_pid(
"Ignoring stale service pid file pid=%s because it never acquired the service lock",
existing_pid,
)
- lock_available, lock_holder_pid = service_instance_lock_available()
+ lock_available, lock_holder_pid = service_instance_lock_available(settle=True)
if not lock_available:
if lock_holder_pid and pid_alive(lock_holder_pid):
if lock_holder_pid == existing_pid:
@@ -2161,7 +2216,7 @@ def _resolve_service_pid(
)
pid_path.unlink(missing_ok=True)
- lock_available, lock_holder_pid = service_instance_lock_available()
+ lock_available, lock_holder_pid = service_instance_lock_available(settle=True)
if not lock_available:
if lock_holder_pid and lock_holder_pid == existing_pid and pid_alive(lock_holder_pid):
return result(lock_holder_pid, reused=True)