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): do not take a check of the service lock for a running service (#2491)

Call White2dd243092817
diff --git a/tests/test_service_lock_record.py b/tests/test_service_lock_record.py
index a8ce141b4..1ea7a24a8 100644
--- a/tests/test_service_lock_record.py
+++ b/tests/test_service_lock_record.py
@@ -22,7 +22,10 @@ change.
import json
import os
+import subprocess
import sys
+import threading
+import time
import unittest
from pathlib import Path
from tempfile import TemporaryDirectory
@@ -197,6 +200,154 @@ class PosixServiceLockUnchangedTests(unittest.TestCase):
self.assertEqual(observed[-1][1], fcntl.LOCK_UN)
+# Holds the service lock the way a running service does, through the entry
+# point `main.py` uses, until it is killed. With a third argument it holds it
+# as an older release did: the lock, and a record naming only its pid.
+_HOLDER = """
+import json, os, sys, time
+from pathlib import Path
+from unittest.mock import patch
+sys.path.insert(0, sys.argv[1])
+from vibe import runtime
+lock_path = Path(sys.argv[2])
+if len(sys.argv) > 3:
+ held = lock_path.open("a+", encoding="utf-8")
+ assert runtime._take_lock_file(held)
+ held.seek(0)
+ held.truncate()
+ held.write(json.dumps({"pid": os.getpid()}))
+ held.flush()
+else:
+ with patch("vibe.runtime.ensure_dirs", return_value=None), patch(
+ "vibe.runtime.paths.get_runtime_service_lock_path", return_value=lock_path
+ ), patch("vibe.runtime.paths.get_runtime_pid_path", return_value=lock_path.with_name("vibe.pid")):
+ runtime.acquire_service_instance_lock()
+print("held", flush=True)
+time.sleep(600)
+"""
+
+
+class ServiceLockContentionTests(unittest.TestCase):
+ """Who holds the lock, as a starting service and a launcher must read it.
+
+ The lock is held by a running service, and also, for an instant, by every
+ check of it: a lock cannot be tested without being taken. ``vibe start``
+ checks every 100 ms while it waits for the service it launched, and a
+ service whose single attempt landed in one of those instants took the check
+ for another service and exited ("Vibe service process pid=... did not
+ acquire the service lock" on a fresh Windows home). A holder that was just
+ killed can also keep the lock a while on Windows. Neither names a live
+ process in the record; a running service does, and must still be refused
+ at once.
+ """
+
+ 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)
+
+ def _hold_like_a_check(self, *, record: str = "") -> None:
+ """Hold the lock through another handle, naming whatever ``record`` says, for 200 ms."""
+
+ check = self.lock_path.open("a+", encoding="utf-8")
+ self.addCleanup(check.close)
+ self.assertTrue(runtime._take_lock_file(check))
+ check.seek(0)
+ check.truncate()
+ check.write(record)
+ check.flush()
+ release = threading.Timer(0.2, runtime._unlock_file, args=(check,))
+ release.start()
+ self.addCleanup(release.join)
+
+ def _acquire(self) -> None:
+ runtime.acquire_service_instance_lock()
+ self.addCleanup(runtime.release_service_instance_lock)
+ self.assertEqual(json.loads(self.lock_path.read_text(encoding="utf-8"))["pid"], os.getpid())
+
+ def _holder(self, *, older_release: bool = False) -> subprocess.Popen:
+ holder = subprocess.Popen(
+ [
+ sys.executable, "-c", _HOLDER, str(Path(__file__).resolve().parents[1]), str(self.lock_path),
+ *(["older-release"] if older_release else []),
+ ],
+ stdout=subprocess.PIPE,
+ text=True,
+ )
+ self.addCleanup(holder.wait, 10)
+ self.addCleanup(holder.kill)
+ self.addCleanup(holder.stdout.close)
+ self.assertEqual(holder.stdout.readline().strip(), "held")
+ return holder
+
+ def test_a_service_starting_during_a_check_takes_the_lock_once_the_check_ends(self):
+ self._hold_like_a_check()
+ self._acquire()
+
+ def test_a_service_starting_while_a_dead_holder_s_lock_is_released_takes_it(self):
+ gone = subprocess.Popen([sys.executable, "-c", "pass"])
+ gone.wait(timeout=10)
+ self._hold_like_a_check(record=json.dumps({"pid": gone.pid}))
+ self._acquire()
+
+ def test_a_record_whose_pid_passed_to_another_process_is_not_a_running_service(self):
+ """After a kill or a reboot the record's pid can belong to anything."""
+
+ 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._acquire()
+
+ def test_a_record_without_a_start_time_names_no_one_while_a_check_holds_the_lock(self):
+ """An older release's record cannot tell its holder from a pid reused since."""
+
+ 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}))
+ self._acquire()
+
+ def test_a_holder_from_a_release_that_wrote_no_start_time_is_still_refused(self):
+ """It keeps the lock past the wait, so the refusal comes when the wait runs out."""
+
+ holder = self._holder(older_release=True)
+ with self.assertRaises(runtime.ServiceAlreadyRunningError) as refused:
+ runtime.acquire_service_instance_lock()
+ self.assertEqual(refused.exception.holder_pid, holder.pid)
+
+ 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."""
+
+ holder = self._holder()
+ holder.kill()
+ holder.wait(timeout=10)
+ self._acquire()
+
+ def test_a_running_service_is_still_refused_at_once(self):
+ holder = self._holder()
+ began = time.monotonic()
+ with self.assertRaises(runtime.ServiceAlreadyRunningError) as refused:
+ runtime.acquire_service_instance_lock()
+ self.assertLess(time.monotonic() - began, runtime._SERVICE_LOCK_SETTLE_SECONDS)
+ self.assertEqual(refused.exception.holder_pid, holder.pid)
+
+ def test_a_check_still_reads_a_running_service_at_once(self):
+ holder = self._holder()
+ began = time.monotonic()
+ self.assertEqual(runtime.service_instance_lock_available(), (False, holder.pid))
+ self.assertLess(time.monotonic() - began, runtime._SERVICE_LOCK_SETTLE_SECONDS)
+
+
@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/vibe/runtime.py b/vibe/runtime.py
index baf589fa1..b90818811 100644
--- a/vibe/runtime.py
+++ b/vibe/runtime.py
@@ -301,9 +301,64 @@ def _take_lock_file(lock_file) -> bool:
return True
+# How long a service lock that no live service holds may take to come free.
+#
+# Holding the lock is how a service says it is running, but it is not the only
+# way the lock gets held. It cannot be tested without being taken -- a Windows
+# byte-range lock has no other test -- so every check holds it for an instant,
+# and `vibe start` checks it every 100 ms while it waits for the service it
+# launched. A service whose single attempt landed in one of those instants
+# took the check for another service and exited. A holder that is gone can
+# also keep it a while: Windows releases a terminated process's locks only as
+# 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.
+_SERVICE_LOCK_SETTLE_SECONDS = 2.0
+_SERVICE_LOCK_SETTLE_INTERVAL_SECONDS = 0.02
+
+
+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,
+ 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.
+ """
+
+ pid = _lock_file_pid(lock_file)
+ if pid is None or not pid_alive(pid):
+ return False
+ try:
+ lock_file.seek(0)
+ started_at = json.loads(lock_file.read() or "{}").get("started_at")
+ 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
+
+
+def _take_service_lock(lock_file) -> bool:
+ """Take the service lock unless a service holds it; raises ``OSError`` when an attempt itself failed.
+
+ False when the record names a live holder, or when the lock stays held for
+ ``_SERVICE_LOCK_SETTLE_SECONDS`` with none named.
+ """
+
+ deadline = time.monotonic() + _SERVICE_LOCK_SETTLE_SECONDS
+ while not _take_lock_file(lock_file):
+ if _lock_file_names_live_holder(lock_file) or time.monotonic() >= deadline:
+ return False
+ time.sleep(_SERVICE_LOCK_SETTLE_INTERVAL_SECONDS)
+ return True
+
+
def _try_lock_file(lock_file) -> bool:
try:
- return _take_lock_file(lock_file)
+ return _take_service_lock(lock_file)
except OSError:
return False
@@ -2998,7 +3053,7 @@ def desktop_service_lock_presence(while_absent: Callable[[], None] | None = None
with lock_file:
# Only another holder is a mismatch; a lock call that failed says nothing.
try:
- taken = _take_lock_file(lock_file)
+ taken = _take_service_lock(lock_file)
except OSError:
logger.warning("Could not probe the service instance lock", exc_info=True)
return DesktopRuntimePresence.UNKNOWN