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): recover service ownership from lock

Call White5a47eeb6bd95
diff --git a/core/scheduled_tasks.py b/core/scheduled_tasks.py
index 26385de85..ce1515813 100644
--- a/core/scheduled_tasks.py
+++ b/core/scheduled_tasks.py
@@ -26,6 +26,7 @@ from storage.db import create_sqlite_engine
from storage.background import SQLiteBackgroundTaskStore
from storage.models import agent_sessions, scope_settings, scopes
from storage.pagination import PageRequest, PageResult, page_sequence
+from vibe import runtime
logger = logging.getLogger(__name__)
@@ -1426,6 +1427,7 @@ class ScheduledTaskService:
self._inflight_sessions: set[str] = set()
# Cache of session_id -> canonical lock key (resolution hits SQLite).
self._session_lock_cache: Dict[str, str] = {}
+ self._requires_service_lease = runtime.service_instance_lock_attached_to_process()
self.request_store.recover_processing()
def validate_platform(self, platform: str) -> None:
@@ -1472,8 +1474,36 @@ class ScheduledTaskService:
)
self._spawn_watch_store()
- async def stop(self) -> None:
+ def _current_asyncio_task(self) -> Optional["asyncio.Task[Any]"]:
+ try:
+ return asyncio.current_task()
+ except RuntimeError:
+ return None
+
+ def _begin_stop(self, *, cancel_reconcile: bool = True) -> None:
self._running = False
+ current_task = self._current_asyncio_task()
+ if cancel_reconcile and self._reconcile_task and self._reconcile_task is not current_task:
+ self._reconcile_task.cancel()
+ for task in list(self._inflight_executions.values()):
+ if task is not current_task:
+ task.cancel()
+ try:
+ self.scheduler.shutdown(wait=False)
+ except Exception:
+ logger.debug("Failed to shut down scheduler", exc_info=True)
+
+ def _owns_service_instance(self) -> bool:
+ if not self._requires_service_lease:
+ return True
+ if runtime.current_process_owns_service_instance():
+ return True
+ logger.error("Scheduled task service stopping because this process no longer owns the service lock")
+ self._begin_stop()
+ return False
+
+ async def stop(self) -> None:
+ self._begin_stop()
if self._reconcile_task:
self._reconcile_task.cancel()
try:
@@ -1486,8 +1516,6 @@ class ScheduledTaskService:
# is picked up again on the next start (and ``recover_processing`` on
# init backstops anything left ``running`` after a hard crash).
inflight = list(self._inflight_executions.values())
- for task in inflight:
- task.cancel()
for task in inflight:
try:
await task
@@ -1495,10 +1523,11 @@ class ScheduledTaskService:
pass
self._inflight_executions.clear()
self._inflight_sessions.clear()
- self.scheduler.shutdown(wait=False)
async def _watch_store(self) -> None:
while self._running:
+ if not self._owns_service_instance():
+ return
try:
if self.store.maybe_reload():
self.reconcile_jobs()
@@ -1515,6 +1544,8 @@ class ScheduledTaskService:
raise
def reconcile_jobs(self) -> None:
+ if not self._owns_service_instance():
+ return
desired_ids = set()
for task in self.store.list_tasks():
if not task.enabled:
@@ -1569,6 +1600,8 @@ class ScheduledTaskService:
raise ValueError(f"unknown schedule type: {task.schedule_type}")
async def _run_task(self, task_id: str) -> None:
+ if not self._owns_service_instance():
+ return
self.store.maybe_reload()
task = self.store.get_task(task_id)
if not task or not task.enabled:
@@ -1577,9 +1610,21 @@ class ScheduledTaskService:
request = self.request_store.claim(queued.id)
if request is None:
return
- await self._execute_claimed_request(request)
+ lock_key = self._execution_lock_key(request)
+ if len(self._inflight_executions) >= self._MAX_CONCURRENT_EXECUTIONS:
+ self.request_store.requeue(request.id)
+ return
+ if lock_key is not None and lock_key in self._inflight_sessions:
+ self.request_store.requeue(request.id)
+ return
+ self._spawn_execution(request, lock_key)
+ execution = self._inflight_executions.get(request.id)
+ if execution is not None:
+ await execution
async def _drain_requests(self) -> None:
+ if not self._owns_service_instance():
+ return
# Claim eligible pending requests and dispatch each as its own task,
# then return immediately. The previous implementation awaited every
# execution inline in this loop, so one turn that hung (e.g. an agent
@@ -1605,6 +1650,8 @@ class ScheduledTaskService:
self._spawn_execution(request, lock_key)
async def _drain_callbacks(self) -> None:
+ if not self._owns_service_instance():
+ return
for run in self.request_store.list_pending_callbacks():
run_id = str(run.get("id") or "")
if not run_id:
diff --git a/core/watches.py b/core/watches.py
index 3983adf5a..5cd5f363f 100644
--- a/core/watches.py
+++ b/core/watches.py
@@ -16,6 +16,7 @@ from config import paths
from core.process_isolation import isolated_subprocess_kwargs, terminate_and_communicate
from core.scheduled_tasks import TaskExecutionStore
from storage.background import SQLiteBackgroundTaskStore
+from vibe import runtime
logger = logging.getLogger(__name__)
@@ -411,6 +412,7 @@ class ManagedWatchService:
self._fused_watch_ids: set[str] = set()
self._store_error_fused = False
self._store_reconcile_failures = 0
+ self._requires_service_lease = runtime.service_instance_lock_attached_to_process()
def active_process_pids(self) -> set[int]:
"""Return active waiter process roots owned by managed watches."""
@@ -427,7 +429,7 @@ class ManagedWatchService:
self._handle_reconcile_store_error(exc)
async def stop(self) -> None:
- self._running = False
+ self._begin_stop()
if self._reconcile_task:
self._reconcile_task.cancel()
try:
@@ -435,8 +437,6 @@ class ManagedWatchService:
except asyncio.CancelledError:
pass
self._reconcile_task = None
- for task in list(self._active_tasks.values()):
- task.cancel()
if self._active_tasks:
await asyncio.gather(*self._active_tasks.values(), return_exceptions=True)
self._active_tasks.clear()
@@ -446,6 +446,8 @@ class ManagedWatchService:
async def _watch_store(self) -> None:
while self._running:
+ if not self._owns_service_instance():
+ return
if self._store_error_fused:
await asyncio.sleep(WATCH_RECONCILE_INTERVAL_SECONDS)
continue
@@ -461,6 +463,8 @@ class ManagedWatchService:
await asyncio.sleep(WATCH_RECONCILE_INTERVAL_SECONDS)
def reconcile_watches(self) -> None:
+ if not self._owns_service_instance():
+ return
if self._store_error_fused:
return
desired_ids = {watch.id for watch in self.store.list_watches() if watch.enabled}
@@ -534,12 +538,39 @@ class ManagedWatchService:
self._fuse_store_after_error(operation, exc, watch_id=watch_id)
return False
+ def _current_asyncio_task(self) -> Optional["asyncio.Task[Any]"]:
+ try:
+ return asyncio.current_task()
+ except RuntimeError:
+ return None
+
+ def _begin_stop(self, *, cancel_reconcile: bool = True) -> None:
+ self._running = False
+ current_task = self._current_asyncio_task()
+ if cancel_reconcile and self._reconcile_task and self._reconcile_task is not current_task:
+ self._reconcile_task.cancel()
+ for task in list(self._active_tasks.values()):
+ if task is not current_task:
+ task.cancel()
+ self._write_runtime_state()
+
+ def _owns_service_instance(self) -> bool:
+ if not self._requires_service_lease:
+ return True
+ if runtime.current_process_owns_service_instance():
+ return True
+ logger.error("Managed watch service stopping because this process no longer owns the service lock")
+ self._begin_stop()
+ return False
+
async def _run_watch(self, watch_id: str) -> None:
lifetime_started = asyncio.get_running_loop().time()
self._watch_started_at[watch_id] = _utc_now_iso()
self._write_runtime_state()
while self._running:
+ if not self._owns_service_instance():
+ return
if watch_id in self._fused_watch_ids:
return
if not self._watch_store_call(watch_id, "reload", self.store.maybe_reload):
@@ -593,6 +624,9 @@ class ManagedWatchService:
timed_out=False,
)
+ if not self._owns_service_instance():
+ return
+
if result.exit_code == 0:
prompt = _build_prompt(watch.message or watch.prefix, result.stdout)
if prompt:
diff --git a/tests/test_restart_supervisor.py b/tests/test_restart_supervisor.py
index 73cf54fcd..a1396fc15 100644
--- a/tests/test_restart_supervisor.py
+++ b/tests/test_restart_supervisor.py
@@ -150,6 +150,26 @@ def test_restart_job_stops_and_starts_service(monkeypatch, tmp_path):
assert "restart_total_seconds" in status["stage_durations"]
+def test_restart_job_uses_lock_holder_when_pidfile_is_missing(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ paths.ensure_data_dirs()
+ calls = []
+
+ monkeypatch.setattr(runtime, "resolve_service_owner_pid", lambda: 111)
+ monkeypatch.setattr(restart_supervisor, "_stop_runtime_for_restart", lambda stop_ui=True: _fake_stop_runtime(calls))
+ monkeypatch.setattr(restart_supervisor, "_start_runtime_processes", lambda start_ui=True: _fake_start_runtime(calls))
+ monkeypatch.setattr(restart_supervisor, "_wait_for_service_lock_release", lambda: True)
+ monkeypatch.setattr(runtime, "pid_alive", lambda pid: pid == 222)
+ monkeypatch.setattr(runtime, "service_pid_recorded", lambda pid: pid == 222)
+
+ rc = restart_supervisor._run_restart_job(job_id="joblockowner", delay_seconds=0, vibe_path="/bin/vibe", trigger="test")
+
+ assert rc == 0
+ status = runtime.read_json(runtime.get_restart_status_path())
+ assert status["old_pid"] == 111
+ assert status["new_pid"] == 222
+
+
def test_restart_job_prepares_show_runtime_after_service_start(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
paths.ensure_data_dirs()
@@ -249,7 +269,7 @@ def test_restart_job_aborts_when_stop_fails(monkeypatch, tmp_path):
"_stop_runtime_for_restart",
lambda stop_ui=True: _fake_stop_runtime(calls, service_stopped=False),
)
- monkeypatch.setattr(runtime, "pid_alive", lambda pid: pid == 111)
+ monkeypatch.setattr(restart_supervisor, "_remaining_service_pids_after_stop", lambda: [111])
monkeypatch.setattr(restart_supervisor, "_wait_for_service_lock_release", lambda: True)
monkeypatch.setattr(restart_supervisor.subprocess, "run", lambda *args, **kwargs: calls.append("run"))
@@ -260,7 +280,8 @@ def test_restart_job_aborts_when_stop_fails(monkeypatch, tmp_path):
status = runtime.read_json(runtime.get_restart_status_path())
assert status["ok"] is False
assert status["state"] == "failed"
- assert "did not stop" in status["error"]
+ assert "remaining service pid(s): 111" in status["error"]
+ assert status["remaining_service_pids"] == [111]
def test_restart_job_continues_when_old_pid_already_exited(monkeypatch, tmp_path):
@@ -276,6 +297,7 @@ def test_restart_job_continues_when_old_pid_already_exited(monkeypatch, tmp_path
)
monkeypatch.setattr(restart_supervisor, "_start_runtime_processes", lambda start_ui=True: _fake_start_runtime(calls))
monkeypatch.setattr(restart_supervisor, "_wait_for_service_lock_release", lambda: True)
+ monkeypatch.setattr(restart_supervisor, "_remaining_service_pids_after_stop", lambda: [])
monkeypatch.setattr(runtime, "pid_alive", lambda pid: pid == 222)
monkeypatch.setattr(runtime, "service_pid_recorded", lambda pid: pid == 222)
@@ -286,6 +308,36 @@ def test_restart_job_continues_when_old_pid_already_exited(monkeypatch, tmp_path
assert runtime.read_json(runtime.get_restart_status_path())["state"] == "succeeded"
+def test_restart_job_aborts_when_extra_service_survives_stop(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ paths.ensure_data_dirs()
+ calls = []
+
+ monkeypatch.setattr(
+ restart_supervisor,
+ "_stop_runtime_for_restart",
+ lambda stop_ui=True: _fake_stop_runtime(calls, service_stopped=False),
+ )
+ monkeypatch.setattr(restart_supervisor, "_remaining_service_pids_after_stop", lambda: [333])
+ monkeypatch.setattr(restart_supervisor, "_start_runtime_processes", lambda start_ui=True: _fake_start_runtime(calls))
+ monkeypatch.setattr(restart_supervisor, "_wait_for_service_lock_release", lambda: True)
+
+ rc = restart_supervisor._run_restart_job(
+ job_id="jobextra",
+ delay_seconds=0,
+ vibe_path="/bin/vibe",
+ trigger="test",
+ )
+
+ assert rc == 2
+ assert calls == ["stop_runtime"]
+ status = runtime.read_json(runtime.get_restart_status_path())
+ assert status["ok"] is False
+ assert status["state"] == "failed"
+ assert status["remaining_service_pids"] == [333]
+ assert "remaining service pid(s): 333" in status["error"]
+
+
def test_restart_job_adopts_slow_starting_service_pid(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
paths.ensure_data_dirs()
diff --git a/tests/test_runtime_service_lock.py b/tests/test_runtime_service_lock.py
index e3e355a3b..00bf27186 100644
--- a/tests/test_runtime_service_lock.py
+++ b/tests/test_runtime_service_lock.py
@@ -12,6 +12,13 @@ from vibe import runtime
class RuntimeServiceLockTests(unittest.TestCase):
+ def setUp(self):
+ self._extra_service_pids = patch("vibe.runtime.extra_service_process_pids", return_value=[])
+ self._extra_service_pids.start()
+
+ def tearDown(self):
+ self._extra_service_pids.stop()
+
def test_start_service_reuses_existing_live_pid(self):
with tempfile.TemporaryDirectory() as tmpdir:
pid_path = Path(tmpdir) / "service.pid"
@@ -52,6 +59,36 @@ class RuntimeServiceLockTests(unittest.TestCase):
spawn_background.assert_called_once()
self.assertEqual(pid_path.read_text(encoding="utf-8"), "67890")
+ def test_start_service_preserves_mismatched_pidfile_when_lock_is_held(self):
+ with tempfile.TemporaryDirectory() as tmpdir:
+ pid_path = Path(tmpdir) / "service.pid"
+ pid_path.write_text("12345", encoding="utf-8")
+
+ with patch("vibe.runtime.paths.get_runtime_pid_path", return_value=pid_path):
+ with patch("vibe.runtime.pid_alive", return_value=True):
+ with patch("vibe.runtime.get_process_command", return_value="/other/worktree/main.py"):
+ with patch("vibe.runtime.service_pid_recorded", return_value=False):
+ with patch("vibe.runtime.service_instance_lock_available", return_value=(False, 12345)):
+ with patch("vibe.runtime.spawn_service_background_process") as spawn_background:
+ pid = runtime.start_service()
+
+ self.assertEqual(pid, 12345)
+ self.assertEqual(pid_path.read_text(encoding="utf-8"), "12345")
+ spawn_background.assert_not_called()
+
+ def test_start_service_refuses_duplicate_when_pidfile_missing_but_lock_is_held(self):
+ with tempfile.TemporaryDirectory() as tmpdir:
+ pid_path = Path(tmpdir) / "service.pid"
+
+ with patch("vibe.runtime.paths.get_runtime_pid_path", return_value=pid_path):
+ with patch("vibe.runtime.service_instance_lock_available", return_value=(False, 12345)):
+ with patch("vibe.runtime.pid_alive", return_value=True):
+ with patch("vibe.runtime.spawn_service_background_process") as spawn_background:
+ with self.assertRaises(runtime.ServiceAlreadyRunningError):
+ runtime.start_service()
+
+ spawn_background.assert_not_called()
+
def test_start_service_reuses_live_pid_when_command_is_unreadable(self):
with tempfile.TemporaryDirectory() as tmpdir:
pid_path = Path(tmpdir) / "service.pid"
@@ -80,6 +117,46 @@ class RuntimeServiceLockTests(unittest.TestCase):
spawn_background.assert_not_called()
+ def test_start_service_refuses_duplicate_when_extra_service_process_exists(self):
+ with tempfile.TemporaryDirectory() as tmpdir:
+ pid_path = Path(tmpdir) / "service.pid"
+
+ with patch("vibe.runtime.paths.get_runtime_pid_path", return_value=pid_path):
+ with patch("vibe.runtime.service_instance_lock_available", return_value=(True, None)):
+ with patch("vibe.runtime.extra_service_process_pids", return_value=[22222]):
+ with patch("vibe.runtime.spawn_service_background_process") as spawn_background:
+ with self.assertRaises(runtime.ServiceAlreadyRunningError):
+ runtime.start_service()
+
+ spawn_background.assert_not_called()
+
+ def test_start_service_does_not_adopt_stale_lockless_pidfile(self):
+ with tempfile.TemporaryDirectory() as tmpdir:
+ pid_path = Path(tmpdir) / "service.pid"
+ pid_path.write_text("12345", encoding="utf-8")
+ stale_time = runtime.time.time() - runtime.SERVICE_SLOW_START_TIMEOUT_SECONDS - 10
+ os.utime(pid_path, (stale_time, stale_time))
+
+ with patch("vibe.runtime.paths.get_runtime_pid_path", return_value=pid_path):
+ with patch("vibe.runtime.pid_alive", return_value=True):
+ with patch(
+ "vibe.runtime.get_process_command",
+ return_value=f"{sys.executable} {runtime.get_service_main_path()}",
+ ):
+ with patch("vibe.runtime.service_pid_recorded", return_value=False):
+ with patch("vibe.runtime.process_create_time", return_value=stale_time):
+ with patch("vibe.runtime.service_instance_lock_available", return_value=(True, None)):
+ with patch("vibe.runtime.extra_service_process_pids", return_value=[12345]):
+ with patch("vibe.runtime.wait_for_service_pid") as wait_for_pid:
+ with patch(
+ "vibe.runtime.spawn_service_background_process"
+ ) as spawn_background:
+ with self.assertRaises(runtime.ServiceAlreadyRunningError):
+ runtime.start_service(wait_for_ready=False)
+
+ wait_for_pid.assert_not_called()
+ spawn_background.assert_not_called()
+
def test_start_service_returns_live_pid_when_lock_write_is_slow(self):
with tempfile.TemporaryDirectory() as tmpdir:
pid_path = Path(tmpdir) / "service.pid"
@@ -172,6 +249,238 @@ class RuntimeServiceLockTests(unittest.TestCase):
stop_pid.assert_called_once_with(67890, timeout=5)
self.assertFalse(pid_path.exists())
+ def test_stop_service_targets_lock_holder_when_pidfile_is_missing(self):
+ with tempfile.TemporaryDirectory() as tmpdir:
+ pid_path = Path(tmpdir) / "service.pid"
+
+ with patch("vibe.runtime.paths.get_runtime_pid_path", return_value=pid_path):
+ with patch("vibe.runtime.service_instance_lock_available", return_value=(False, 12345)):
+ with patch("vibe.runtime.pid_alive", return_value=True):
+ with patch("vibe.runtime.stop_pid", return_value=True) as stop_pid:
+ self.assertTrue(runtime.stop_service())
+
+ stop_pid.assert_called_once_with(12345, timeout=5)
+
+ def test_stop_service_prefers_lock_holder_over_live_pidfile_reservation(self):
+ with tempfile.TemporaryDirectory() as tmpdir:
+ pid_path = Path(tmpdir) / "service.pid"
+ pid_path.write_text("11111", encoding="utf-8")
+
+ with patch("vibe.runtime.paths.get_runtime_pid_path", return_value=pid_path):
+ with patch("vibe.runtime.pid_alive", return_value=True):
+ with patch("vibe.runtime.service_pid_recorded", return_value=False):
+ with patch("vibe.runtime.service_instance_lock_available", return_value=(False, 22222)):
+ with patch("vibe.runtime.stop_pid", return_value=True) as stop_pid:
+ self.assertTrue(runtime.stop_service())
+
+ stop_pid.assert_called_once_with(22222, timeout=5)
+ self.assertEqual(pid_path.read_text(encoding="utf-8"), "11111")
+
+ def test_stop_service_stops_extra_lockless_service_processes(self):
+ with tempfile.TemporaryDirectory() as tmpdir:
+ pid_path = Path(tmpdir) / "service.pid"
+ pid_path.write_text("11111", encoding="utf-8")
+
+ with patch("vibe.runtime.paths.get_runtime_pid_path", return_value=pid_path):
+ with patch("vibe.runtime.resolve_service_owner_pid", return_value=11111):
+ with patch("vibe.runtime.extra_service_process_pids", return_value=[22222]):
+ with patch("vibe.runtime.stop_pid", return_value=True) as stop_pid:
+ self.assertTrue(runtime.stop_service())
+
+ self.assertEqual([call.args[0] for call in stop_pid.call_args_list], [11111, 22222])
+ self.assertFalse(pid_path.exists())
+
+ def test_stop_service_fails_if_extra_lockless_service_survives(self):
+ with tempfile.TemporaryDirectory() as tmpdir:
+ pid_path = Path(tmpdir) / "service.pid"
+ pid_path.write_text("11111", encoding="utf-8")
+
+ def fake_stop(pid, timeout=5):
+ return pid == 11111
+
+ with patch("vibe.runtime.paths.get_runtime_pid_path", return_value=pid_path):
+ with patch("vibe.runtime.resolve_service_owner_pid", return_value=11111):
+ with patch("vibe.runtime.extra_service_process_pids", return_value=[22222]):
+ with patch("vibe.runtime.stop_pid", side_effect=fake_stop) as stop_pid:
+ self.assertFalse(runtime.stop_service())
+
+ self.assertEqual([call.args[0] for call in stop_pid.call_args_list], [11111, 22222])
+ self.assertFalse(pid_path.exists())
+
+ def test_service_processes_detects_matching_service_entry_and_home(self):
+ with tempfile.TemporaryDirectory() as tmpdir:
+ home = Path(tmpdir) / "home"
+ home.mkdir()
+ package_dir = Path(tmpdir) / "pkg" / "vibe"
+ package_dir.mkdir(parents=True)
+ (package_dir / "service_main.py").write_text("", encoding="utf-8")
+ (package_dir / "runtime.py").write_text("", encoding="utf-8")
+
+ class FakeProcess:
+ info = {"pid": 33333, "cmdline": [sys.executable, str(package_dir / "service_main.py")]}
+
+ def cwd(self):
+ return str(package_dir)
+
+ def environ(self):
+ return {"AVIBE_HOME": str(home)}
+
+ with patch("vibe.runtime.paths.get_vibe_remote_dir", return_value=home):
+ with patch("vibe.runtime.psutil.process_iter", return_value=[FakeProcess()]):
+ with patch("vibe.runtime.pid_alive", return_value=True):
+ with patch("vibe.runtime.service_lock_held_by", return_value=False):
+ with patch("vibe.runtime._process_is_service_session_leader", return_value=True):
+ processes = runtime.service_processes()
+
+ self.assertEqual([process["pid"] for process in processes], [33333])
+ self.assertTrue(processes[0]["home_match"])
+ self.assertFalse(processes[0]["lock_owner"])
+
+ def test_service_processes_ignores_same_user_service_main_without_avibe_marker(self):
+ with tempfile.TemporaryDirectory() as tmpdir:
+ home = Path(tmpdir)
+ avibe_home = home / ".avibe"
+ avibe_home.mkdir()
+ package_dir = Path(tmpdir) / "pkg" / "vibe"
+ package_dir.mkdir(parents=True)
+ (package_dir / "service_main.py").write_text("", encoding="utf-8")
+ (package_dir / "runtime.py").write_text("", encoding="utf-8")
+
+ class FakeProcess:
+ info = {"pid": 33333, "cmdline": [sys.executable, str(package_dir / "service_main.py")]}
+
+ def cwd(self):
+ return str(package_dir)
+
+ def environ(self):
+ return {"HOME": str(home)}
+
+ with patch("vibe.runtime.paths.get_vibe_remote_dir", return_value=avibe_home):
+ with patch("vibe.runtime.psutil.process_iter", return_value=[FakeProcess()]):
+ with patch("vibe.runtime.pid_alive", return_value=True):
+ with patch("vibe.runtime.service_lock_held_by", return_value=False):
+ with patch("vibe.runtime._process_is_service_session_leader", return_value=True):
+ self.assertEqual(runtime.service_processes(), [])
+
+ def test_service_processes_detects_shell_launched_lockless_service(self):
+ with tempfile.TemporaryDirectory() as tmpdir:
+ home = Path(tmpdir) / "home"
+ home.mkdir()
+ repo_root = Path(tmpdir) / "repo"
+ (repo_root / "vibe").mkdir(parents=True)
+ (repo_root / "core").mkdir()
+ (repo_root / "main.py").write_text("", encoding="utf-8")
+ (repo_root / "vibe" / "runtime.py").write_text("", encoding="utf-8")
+ (repo_root / "core" / "controller.py").write_text("", encoding="utf-8")
+
+ class FakeProcess:
+ info = {"pid": 33333, "cmdline": [sys.executable, "main.py"]}
+
+ def cwd(self):
+ return str(repo_root)
+
+ def environ(self):
+ return {"AVIBE_HOME": str(home), "VIBE_REQUIRE_SHUTDOWN_INTENT": "1"}
+
+ with patch("vibe.runtime.paths.get_vibe_remote_dir", return_value=home):
+ with patch("vibe.runtime.psutil.process_iter", return_value=[FakeProcess()]):
+ with patch("vibe.runtime.pid_alive", return_value=True):
+ with patch("vibe.runtime.service_lock_held_by", return_value=False):
+ with patch("vibe.runtime._process_is_service_session_leader", return_value=False):
+ processes = runtime.service_processes()
+
+ self.assertEqual([process["pid"] for process in processes], [33333])
+ self.assertFalse(processes[0]["session_leader"])
+
+ def test_service_processes_ignores_service_entry_path_used_as_data_argument(self):
+ with tempfile.TemporaryDirectory() as tmpdir:
+ home = Path(tmpdir) / "home"
+ home.mkdir()
+ repo_root = Path(tmpdir) / "repo"
+ (repo_root / "vibe").mkdir(parents=True)
+ (repo_root / "core").mkdir()
+ (repo_root / "main.py").write_text("", encoding="utf-8")
+ (repo_root / "vibe" / "runtime.py").write_text("", encoding="utf-8")
+ (repo_root / "core" / "controller.py").write_text("", encoding="utf-8")
+
+ class FakeProcess:
+ info = {
+ "pid": 33333,
+ "cmdline": [sys.executable, "-c", "print('not service')", str(repo_root / "main.py")],
+ }
+
+ def cwd(self):
+ return str(repo_root)
+
+ def environ(self):
+ return {"AVIBE_HOME": str(home), "VIBE_REQUIRE_SHUTDOWN_INTENT": "1"}
+
+ with patch("vibe.runtime.paths.get_vibe_remote_dir", return_value=home):
+ with patch("vibe.runtime.psutil.process_iter", return_value=[FakeProcess()]):
+ with patch("vibe.runtime.pid_alive", return_value=True):
+ with patch("vibe.runtime._process_is_service_session_leader", return_value=True):
+ self.assertEqual(runtime.service_processes(), [])
+
+ def test_stop_service_ignores_pidfile_data_argument_that_references_service_entry(self):
+ with tempfile.TemporaryDirectory() as tmpdir:
+ pid_path = Path(tmpdir) / "service.pid"
+ pid_path.write_text("33333", encoding="utf-8")
+ repo_root = Path(tmpdir) / "repo"
+ (repo_root / "vibe").mkdir(parents=True)
+ (repo_root / "core").mkdir()
+ (repo_root / "main.py").write_text("", encoding="utf-8")
+ (repo_root / "vibe" / "runtime.py").write_text("", encoding="utf-8")
+ (repo_root / "core" / "controller.py").write_text("", encoding="utf-8")
+ command = runtime.shlex.join([sys.executable, "-c", "print('not service')", str(repo_root / "main.py")])
+
+ with patch("vibe.runtime.paths.get_runtime_pid_path", return_value=pid_path):
+ with patch("vibe.runtime.pid_alive", return_value=True):
+ with patch("vibe.runtime.service_pid_recorded", return_value=False):
+ with patch("vibe.runtime.service_instance_lock_available", return_value=(True, None)):
+ with patch("vibe.runtime.get_process_command", return_value=command):
+ with patch(
+ "vibe.runtime.psutil.Process",
+ return_value=SimpleNamespace(cwd=lambda: str(repo_root)),
+ ):
+ with patch("vibe.runtime.stop_pid") as stop_pid:
+ self.assertFalse(runtime.stop_service())
+
+ stop_pid.assert_not_called()
+
+ def test_render_status_uses_lock_holder_when_pidfile_is_missing(self):
+ with tempfile.TemporaryDirectory() as tmpdir:
+ status_path = Path(tmpdir) / "status.json"
+ pid_path = Path(tmpdir) / "service.pid"
+ runtime.write_json(status_path, {"state": "stopped", "service_pid": None})
+
+ with patch("vibe.runtime.paths.get_runtime_status_path", return_value=status_path):
+ with patch("vibe.runtime.paths.get_runtime_pid_path", return_value=pid_path):
+ with patch("vibe.runtime.service_instance_lock_available", return_value=(False, 12345)):
+ with patch("vibe.runtime.pid_alive", return_value=True):
+ payload = runtime.json.loads(runtime.render_status())
+
+ self.assertTrue(payload["running"])
+ self.assertEqual(payload["state"], "running")
+ self.assertEqual(payload["service_pid"], 12345)
+ self.assertEqual(payload["pid"], 12345)
+
+ def test_render_status_surfaces_lockless_service_process(self):
+ with tempfile.TemporaryDirectory() as tmpdir:
+ status_path = Path(tmpdir) / "status.json"
+ runtime.write_json(status_path, {"state": "running", "service_pid": None})
+
+ with patch("vibe.runtime.paths.get_runtime_status_path", return_value=status_path):
+ with patch("vibe.runtime.resolve_service_owner_pid", return_value=None):
+ with patch("vibe.runtime.extra_service_process_pids", return_value=[22222]):
+ payload = runtime.json.loads(runtime.render_status())
+
+ self.assertTrue(payload["running"])
+ self.assertEqual(payload["state"], "degraded")
+ self.assertEqual(payload["service_pid"], 22222)
+ self.assertEqual(payload["pid"], 22222)
+ self.assertEqual(payload["service_owner_pid"], None)
+ self.assertEqual(payload["extra_service_pids"], [22222])
+
def test_wait_for_service_pid_adopts_slow_pid_file_write(self):
with tempfile.TemporaryDirectory() as tmpdir:
pid_path = Path(tmpdir) / "service.pid"
@@ -221,5 +530,23 @@ class RuntimeServiceLockTests(unittest.TestCase):
self.assertEqual(holder_pid, os.getpid())
self.assertFalse(pid_path.exists())
+ def test_current_process_owns_service_instance_tracks_lock_lifetime(self):
+ with tempfile.TemporaryDirectory() as tmpdir:
+ runtime_dir = Path(tmpdir) / "runtime"
+ runtime_dir.mkdir(parents=True)
+ lock_path = runtime_dir / "service.lock"
+ pid_path = runtime_dir / "vibe.pid"
+
+ with patch("vibe.runtime.paths.get_runtime_service_lock_path", return_value=lock_path):
+ with patch("vibe.runtime.paths.get_runtime_pid_path", return_value=pid_path):
+ with patch("vibe.runtime.paths.ensure_data_dirs", return_value=None):
+ runtime.acquire_service_instance_lock()
+ try:
+ self.assertTrue(runtime.current_process_owns_service_instance())
+ finally:
+ runtime.release_service_instance_lock()
+
+ self.assertFalse(runtime.current_process_owns_service_instance())
+
if __name__ == "__main__":
unittest.main()
diff --git a/tests/test_scheduled_tasks.py b/tests/test_scheduled_tasks.py
index f2cac28ee..3b45a97f5 100644
--- a/tests/test_scheduled_tasks.py
+++ b/tests/test_scheduled_tasks.py
@@ -858,6 +858,29 @@ def test_reconcile_jobs_skips_invalid_tasks_and_keeps_valid_jobs(tmp_path: Path)
assert invalid.id not in service.scheduler.jobs
+def test_reconcile_jobs_stops_after_service_lease_loss(tmp_path: Path, monkeypatch) -> None:
+ store = ScheduledTaskStore(tmp_path / "scheduled_tasks.json")
+ task = store.add_task(
+ session_key="slack::channel::C123",
+ prompt="send digest",
+ schedule_type="cron",
+ cron="0 * * * *",
+ timezone_name="UTC",
+ )
+ controller = SimpleNamespace(platform_settings_managers={"slack": object()}, im_clients={})
+ service = ScheduledTaskService(controller=controller, store=store)
+ service.scheduler = _StubScheduler()
+ service._running = True
+ service._requires_service_lease = True
+ monkeypatch.setattr("core.scheduled_tasks.runtime.current_process_owns_service_instance", lambda: False)
+
+ service.reconcile_jobs()
+
+ assert task.id not in service.scheduler.jobs
+ assert service._running is False
+ assert service.scheduler.shutdown_calls == 1
+
+
def test_request_store_enqueue_claim_and_complete(tmp_path: Path) -> None:
store = TaskExecutionStore(tmp_path / "task_requests")
@@ -1396,6 +1419,89 @@ def test_drain_requests_requeues_cancelled_task_run(tmp_path: Path) -> None:
assert not (request_store.completed_dir / f"{request.id}.json").exists()
+def test_service_lease_loss_cancels_inflight_execution(tmp_path: Path, monkeypatch) -> None:
+ request_store = TaskExecutionStore(tmp_path / "task_requests")
+ request = request_store.enqueue_hook_send(session_key="slack::channel::C123", prompt="send digest")
+ controller = SimpleNamespace(platform_settings_managers={"slack": object()}, im_clients={})
+ service = ScheduledTaskService(
+ controller=controller,
+ store=ScheduledTaskStore(tmp_path / "scheduled_tasks.json"),
+ request_store=request_store,
+ )
+ service._running = True
+ service._requires_service_lease = True
+ owner_state = {"owns": True}
+ started = asyncio.Event()
+
+ async def fake_execute(claimed):
+ started.set()
+ await asyncio.Event().wait()
+
+ monkeypatch.setattr(
+ "core.scheduled_tasks.runtime.current_process_owns_service_instance",
+ lambda: owner_state["owns"],
+ )
+ service._execute_claimed_request = fake_execute # type: ignore[assignment]
+
+ async def _exercise() -> None:
+ await service._drain_requests()
+ execution = service._inflight_executions.get(request.id)
+ assert execution is not None
+ await started.wait()
+ owner_state["owns"] = False
+ assert service._owns_service_instance() is False
+ with pytest.raises(asyncio.CancelledError):
+ await execution
+
+ asyncio.run(_exercise())
+
+ assert service._running is False
+
+
+def test_run_task_uses_tracked_execution_for_lease_loss(tmp_path: Path, monkeypatch) -> None:
+ request_store = TaskExecutionStore(tmp_path / "task_requests")
+ store = ScheduledTaskStore(tmp_path / "scheduled_tasks.json")
+ task = store.add_task(
+ session_key="slack::channel::C123",
+ prompt="send digest",
+ schedule_type="at",
+ run_at="2026-03-31T09:00:00+08:00",
+ timezone_name="Asia/Shanghai",
+ )
+ controller = SimpleNamespace(platform_settings_managers={"slack": object()}, im_clients={})
+ service = ScheduledTaskService(controller=controller, store=store, request_store=request_store)
+ service._running = True
+ service._requires_service_lease = True
+ owner_state = {"owns": True}
+ started = asyncio.Event()
+
+ async def fake_execute(claimed):
+ started.set()
+ await asyncio.Event().wait()
+
+ monkeypatch.setattr(
+ "core.scheduled_tasks.runtime.current_process_owns_service_instance",
+ lambda: owner_state["owns"],
+ )
+ service._execute_claimed_request = fake_execute # type: ignore[assignment]
+
+ async def _exercise() -> None:
+ run_task = asyncio.create_task(service._run_task(task.id))
+ await started.wait()
+ assert len(service._inflight_executions) == 1
+ execution = next(iter(service._inflight_executions.values()))
+ owner_state["owns"] = False
+ assert service._owns_service_instance() is False
+ with pytest.raises(asyncio.CancelledError):
+ await execution
+ with pytest.raises(asyncio.CancelledError):
+ await run_task
+
+ asyncio.run(_exercise())
+
+ assert service._running is False
+
+
def test_drain_requests_executes_hook_send(tmp_path: Path) -> None:
request_store = TaskExecutionStore(tmp_path / "task_requests")
request = request_store.enqueue_hook_send(
diff --git a/tests/test_upgrade_flow.py b/tests/test_upgrade_flow.py
index 5680304a4..3d2c12bef 100644
--- a/tests/test_upgrade_flow.py
+++ b/tests/test_upgrade_flow.py
@@ -627,13 +627,10 @@ def test_api_runtime_process_was_running_checks_service_and_ui_pid_files(monkeyp
service_running = False
ui_running = False
- def fake_service_running(pid_path):
- return pid_path == service_pid_path and service_running
-
def fake_ui_running(pid_path):
return pid_path == ui_pid_path and ui_running
- monkeypatch.setattr(runtime, "service_pid_file_points_to_running_service", fake_service_running)
+ monkeypatch.setattr(runtime, "service_process_running", lambda: service_running)
monkeypatch.setattr(runtime, "ui_pid_file_points_to_running_ui", fake_ui_running)
assert api._runtime_process_was_running() is False
@@ -644,6 +641,17 @@ def test_api_runtime_process_was_running_checks_service_and_ui_pid_files(monkeyp
assert api._runtime_process_was_running() is True
+def test_cli_runtime_process_was_running_uses_service_process_state(monkeypatch):
+ service_running = False
+
+ monkeypatch.setattr(cli.runtime, "service_process_running", lambda: service_running)
+ monkeypatch.setattr(cli.runtime, "ui_pid_file_points_to_running_ui", lambda: False)
+
+ assert cli._runtime_process_was_running() is False
+ service_running = True
+ assert cli._runtime_process_was_running() is True
+
+
def test_cmd_upgrade_uses_upgrade_plan_env(monkeypatch):
plan = UpgradePlan(
command=["/usr/local/bin/uv", "tool", "install", "avibe-os", "--upgrade"],
@@ -760,7 +768,7 @@ def test_cmd_upgrade_keeps_runtime_stopped_when_it_was_not_running(monkeypatch):
monkeypatch.setattr(cli, "get_latest_version", lambda: {"error": None, "has_update": True, "latest": "2.2.0"})
monkeypatch.setattr(cli, "cache_running_vibe_path", lambda: "/custom/bin/vibe")
monkeypatch.setattr(cli, "build_upgrade_plan", lambda **kwargs: plan)
- monkeypatch.setattr(cli, "_pid_file_points_to_live_process", lambda path: False)
+ monkeypatch.setattr(cli, "_runtime_process_was_running", lambda: False)
def fail_restart(**kwargs):
raise AssertionError("schedule_restart should not run when Avibe was not running")
diff --git a/tests/test_vibe_cli.py b/tests/test_vibe_cli.py
index f1a6a7f00..1dc657fc9 100644
--- a/tests/test_vibe_cli.py
+++ b/tests/test_vibe_cli.py
@@ -433,6 +433,21 @@ def test_cmd_stop_fails_when_live_service_survives(monkeypatch, capsys):
assert "Avibe service did not stop" in capsys.readouterr().err
+def test_cmd_stop_fails_when_lock_owner_survives_without_pidfile(monkeypatch, capsys):
+ status = []
+
+ monkeypatch.setattr(cli.runtime, "resolve_service_owner_pid", lambda include_starting=False: 1234)
+ monkeypatch.setattr(cli.runtime, "ui_pid_file_points_to_running_ui", lambda: False)
+ monkeypatch.setattr(runtime, "stop_service", lambda: False)
+ monkeypatch.setattr(runtime, "stop_ui", lambda: False)
+ monkeypatch.setattr(cli, "_stop_opencode_server", lambda: False)
+ monkeypatch.setattr(cli, "_write_status", lambda state, detail=None: status.append((state, detail)))
+
+ assert cli.cmd_stop() == 2
+ assert status == [("error", "service stop failed")]
+ assert "Avibe service did not stop" in capsys.readouterr().err
+
+
def test_cmd_vibe_uses_start_compatibility_default(monkeypatch):
calls = []
@@ -614,6 +629,39 @@ def test_cmd_start_fails_only_when_slow_service_exits(monkeypatch):
assert ("error", "service process exited before startup completed", 1234, 5678) in statuses
+def test_service_lifecycle_doctor_warns_when_pidfile_missing_but_lock_owner_exists(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ cli.paths.ensure_data_dirs()
+ cli.runtime.write_status("running", "pid missing", None, None)
+ monkeypatch.setattr(cli.runtime, "resolve_service_owner_pid", lambda include_starting=False: 1234)
+ monkeypatch.setattr(cli.runtime, "service_lock_holder_pid", lambda: 1234)
+ monkeypatch.setattr(cli.runtime, "extra_service_process_pids", lambda owner_pid=None, include_unverified=False: [])
+
+ items = cli._service_lifecycle_items()
+
+ messages = [item["message"] for item in items if item["status"] == "warn"]
+ assert any("pid file does not match" in message for message in messages)
+ assert any("Runtime status service_pid does not match" in message for message in messages)
+
+
+def test_service_lifecycle_doctor_warns_when_extra_service_process_exists(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ cli.paths.ensure_data_dirs()
+ cli.runtime.write_status("running", "healthy", 1234, None)
+ monkeypatch.setattr(cli.runtime, "resolve_service_owner_pid", lambda include_starting=False: 1234)
+ monkeypatch.setattr(cli.runtime, "service_lock_holder_pid", lambda: 1234)
+ monkeypatch.setattr(
+ cli.runtime,
+ "extra_service_process_pids",
+ lambda owner_pid=None, include_unverified=False: [2222] if not include_unverified else [2222],
+ )
+
+ items = cli._service_lifecycle_items()
+
+ messages = [item["message"] for item in items if item["status"] == "warn"]
+ assert any("Extra Avibe service process detected" in message and "2222" in message for message in messages)
+
+
def test_restart_parser_accepts_delay_seconds():
parser = cli.build_parser()
args = parser.parse_args(["restart", "--delay-seconds", "60"])
diff --git a/tests/test_watches.py b/tests/test_watches.py
index 141a4953d..d00e1861b 100644
--- a/tests/test_watches.py
+++ b/tests/test_watches.py
@@ -13,7 +13,7 @@ import pytest
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from core.scheduled_tasks import TaskExecutionStore
-from core.watches import ManagedWatchService, ManagedWatchStore, WatchRuntimeStateStore
+from core.watches import ManagedWatchService, ManagedWatchStore, WatchRuntimeStateStore, _CycleResult
from storage.background import SQLiteBackgroundTaskStore
@@ -310,6 +310,49 @@ def test_managed_watch_service_once_success_enqueues_hook_and_disables(tmp_path:
assert saved.last_event_at is not None
+def test_managed_watch_service_does_not_enqueue_after_service_lease_loss(tmp_path: Path, monkeypatch) -> None:
+ store = ManagedWatchStore(tmp_path / "watches.json")
+ request_store = TaskExecutionStore(tmp_path / "task_requests")
+ runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")
+ watch = store.add_watch(
+ name="Wait once",
+ session_key="slack::channel::C123",
+ command=["python3", "-c", "print('waiter output')"],
+ shell_command=None,
+ prefix="The waiter finished.",
+ cwd=None,
+ mode="once",
+ timeout_seconds=5,
+ lifetime_timeout_seconds=0,
+ retry_exit_codes=[75],
+ retry_delay_seconds=30,
+ post_to=None,
+ deliver_key=None,
+ )
+ service = ManagedWatchService(
+ controller=SimpleNamespace(),
+ store=store,
+ request_store=request_store,
+ runtime_store=runtime_store,
+ )
+ service._running = True
+ service._requires_service_lease = True
+ owner_checks = iter([True, False])
+ monkeypatch.setattr(
+ "core.watches.runtime.current_process_owns_service_instance",
+ lambda: next(owner_checks),
+ )
+
+ async def fake_run_cycle(*args, **kwargs):
+ return _CycleResult(exit_code=0, stdout="waiter output", stderr="", timed_out=False)
+
+ monkeypatch.setattr(service, "_run_cycle", fake_run_cycle)
+
+ asyncio.run(service._run_watch(watch.id))
+
+ assert request_store.list_pending() == []
+
+
def test_managed_watch_service_forever_timeout_disables_and_enqueues_failure(tmp_path: Path) -> None:
store = ManagedWatchStore(tmp_path / "watches.json")
request_store = TaskExecutionStore(tmp_path / "task_requests")
@@ -442,6 +485,66 @@ def test_managed_watch_service_stop_terminates_running_waiter(tmp_path: Path) ->
os.kill(pid, 0)
+def test_managed_watch_service_lease_loss_terminates_running_waiter(tmp_path: Path, monkeypatch) -> None:
+ store = ManagedWatchStore(tmp_path / "watches.json")
+ request_store = TaskExecutionStore(tmp_path / "task_requests")
+ runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")
+ watch = store.add_watch(
+ name="Wait forever",
+ session_key="slack::channel::C123",
+ command=["python3", "-c", "import time; time.sleep(30)"],
+ shell_command=None,
+ prefix=None,
+ cwd=None,
+ mode="forever",
+ timeout_seconds=0,
+ lifetime_timeout_seconds=0,
+ retry_exit_codes=[75],
+ retry_delay_seconds=0.01,
+ post_to=None,
+ deliver_key=None,
+ )
+ service = ManagedWatchService(
+ controller=SimpleNamespace(),
+ store=store,
+ request_store=request_store,
+ runtime_store=runtime_store,
+ )
+ service._requires_service_lease = True
+ owner_state = {"owns": True}
+ monkeypatch.setattr("core.watches.runtime.current_process_owns_service_instance", lambda: owner_state["owns"])
+
+ async def _run() -> tuple[int, int | None]:
+ service.start()
+ for _ in range(100):
+ pid = service._active_pids.get(watch.id)
+ if pid:
+ break
+ await asyncio.sleep(0.02)
+ else:
+ raise AssertionError("waiter pid was never recorded")
+ pgid = os.getpgid(pid) if hasattr(os, "getpgid") else None
+ active_tasks = list(service._active_tasks.values())
+ owner_state["owns"] = False
+ assert service._owns_service_instance() is False
+ await asyncio.gather(*active_tasks, return_exceptions=True)
+ if service._reconcile_task:
+ try:
+ await service._reconcile_task
+ except asyncio.CancelledError:
+ pass
+ service._reconcile_task = None
+ return pid, pgid
+
+ pid, pgid = asyncio.run(_run())
+
+ if pgid is not None:
+ assert pgid != os.getpgrp()
+
+ with pytest.raises(ProcessLookupError):
+ os.kill(pid, 0)
+
+
def test_managed_watch_service_records_wall_clock_started_at(tmp_path: Path) -> None:
store = ManagedWatchStore(tmp_path / "watches.json")
request_store = TaskExecutionStore(tmp_path / "task_requests")
diff --git a/vibe/api.py b/vibe/api.py
index 2e9456bb8..6a1b409b4 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -3493,7 +3493,7 @@ def _pid_file_points_to_live_process(pid_path: Path) -> bool:
from vibe import runtime
if pid_path == paths.get_runtime_pid_path():
- return runtime.service_pid_file_points_to_running_service(pid_path)
+ return runtime.service_process_running()
if pid_path == paths.get_runtime_ui_pid_path():
return runtime.ui_pid_file_points_to_running_ui(pid_path)
return False
diff --git a/vibe/cli.py b/vibe/cli.py
index 22e12ff48..4fd554e04 100644
--- a/vibe/cli.py
+++ b/vibe/cli.py
@@ -449,6 +449,82 @@ def _runtime_architecture_items() -> list[dict[str, str]]:
return items
+def _service_lifecycle_items() -> list[dict[str, str]]:
+ items: list[dict[str, str]] = []
+ pid_path = paths.get_runtime_pid_path()
+ recorded_pid: int | None = None
+ try:
+ recorded_pid = int(pid_path.read_text(encoding="utf-8").strip())
+ except (OSError, ValueError):
+ recorded_pid = None
+
+ owner_pid = runtime.resolve_service_owner_pid(include_starting=False)
+ lock_holder_pid = runtime.service_lock_holder_pid()
+ extra_service_pids = runtime.extra_service_process_pids(owner_pid=owner_pid)
+ unverified_service_pids = runtime.extra_service_process_pids(
+ owner_pid=owner_pid,
+ include_unverified=True,
+ )
+ unverified_service_pids = [pid for pid in unverified_service_pids if pid not in set(extra_service_pids)]
+ status = runtime.read_status()
+ status_pid = status.get("service_pid")
+
+ if owner_pid:
+ _add_doctor_item(items, "pass", f"Service lock owner: pid={owner_pid}")
+ elif lock_holder_pid:
+ _add_doctor_item(
+ items,
+ "warn",
+ f"Service lock is held by pid={lock_holder_pid}, but the owner could not be verified",
+ "Run `vibe status` and inspect service logs before starting another service.",
+ )
+ else:
+ _add_doctor_item(items, "pass", "Service lock is free")
+
+ if owner_pid and recorded_pid != owner_pid:
+ _add_doctor_item(
+ items,
+ "warn",
+ f"Service pid file does not match the lock owner: pidfile={recorded_pid or 'missing'} lock_owner={owner_pid}",
+ "Run `vibe restart` once the current work is idle so Avibe can rewrite runtime ownership files.",
+ )
+ elif recorded_pid:
+ _add_doctor_item(items, "pass", f"Service pid file points to pid={recorded_pid}")
+ else:
+ _add_doctor_item(items, "pass", "Service pid file is absent")
+
+ if owner_pid and status_pid != owner_pid:
+ _add_doctor_item(
+ items,
+ "warn",
+ f"Runtime status service_pid does not match the lock owner: status={status_pid or 'missing'} lock_owner={owner_pid}",
+ "Refresh status; if it remains stale, restart Avibe when safe.",
+ )
+ elif status_pid:
+ _add_doctor_item(items, "pass", f"Runtime status service_pid: {status_pid}")
+ else:
+ _add_doctor_item(items, "pass", "Runtime status service_pid is absent")
+
+ if extra_service_pids:
+ _add_doctor_item(
+ items,
+ "warn",
+ f"Extra Avibe service process detected outside the service lock: pids={','.join(map(str, extra_service_pids))}",
+ "Run `vibe stop`; if the process remains, inspect the service log before starting again.",
+ )
+ elif unverified_service_pids:
+ _add_doctor_item(
+ items,
+ "warn",
+ f"Possible extra Avibe service process could not be matched to AVIBE_HOME: pids={','.join(map(str, unverified_service_pids))}",
+ "Inspect the process environment before starting another service.",
+ )
+ else:
+ _add_doctor_item(items, "pass", "No extra Avibe service process detected")
+
+ return items
+
+
def _remote_examples_text() -> str:
return dedent(
"""\
@@ -6840,7 +6916,7 @@ def _doctor():
)
summary["pass"] += 1
- for item in _runtime_architecture_items():
+ for item in [*_service_lifecycle_items(), *_runtime_architecture_items()]:
runtime_items.append(item)
status = item.get("status")
if status in summary:
@@ -7209,6 +7285,10 @@ def _stop_opencode_server():
def _pid_file_points_to_live_process(pid_path: Path) -> bool:
+ if pid_path == paths.get_runtime_pid_path():
+ return runtime.resolve_service_owner_pid(include_starting=True) is not None or bool(
+ runtime.extra_service_process_pids()
+ )
try:
raw_pid = pid_path.read_text(encoding="utf-8").strip()
pid = int(raw_pid)
@@ -7218,7 +7298,7 @@ def _pid_file_points_to_live_process(pid_path: Path) -> bool:
def _runtime_process_was_running() -> bool:
- return runtime.service_pid_file_points_to_running_service() or runtime.ui_pid_file_points_to_running_ui()
+ return runtime.service_process_running() or runtime.ui_pid_file_points_to_running_ui()
def cmd_stop():
diff --git a/vibe/restart_supervisor.py b/vibe/restart_supervisor.py
index 371300b08..f3bc1f3cd 100644
--- a/vibe/restart_supervisor.py
+++ b/vibe/restart_supervisor.py
@@ -99,8 +99,10 @@ def _read_recorded_pid() -> int | None:
try:
pid = int(pid_path.read_text(encoding="utf-8").strip())
except (OSError, ValueError):
- return None
- return pid if pid > 0 else None
+ pid = None
+ if pid and pid > 0:
+ return pid
+ return runtime.resolve_service_owner_pid()
def _read_recorded_ui_pid() -> int | None:
@@ -112,6 +114,15 @@ def _read_recorded_ui_pid() -> int | None:
return pid if pid > 0 else None
+def _remaining_service_pids_after_stop() -> list[int]:
+ owner_pid = runtime.resolve_service_owner_pid(include_starting=True)
+ pids: list[int] = []
+ if owner_pid:
+ pids.append(owner_pid)
+ pids.extend(runtime.extra_service_process_pids(owner_pid=owner_pid))
+ return sorted(set(pids))
+
+
def _read_starting_service_status() -> dict | None:
status = runtime.read_status()
if status.get("state") != "starting":
@@ -304,8 +315,18 @@ def _run_restart_job(
mark_duration("stop_runtime_seconds", stop_runtime_started_at)
if restart_ui and ui_pid and ui_stopped is False and runtime.pid_alive(ui_pid):
return _fail(payload, f"UI pid {ui_pid} did not stop", log, 2, started_at=restart_started_at)
- if old_pid and stopped is False and runtime.pid_alive(old_pid):
- return _fail(payload, f"service pid {old_pid} did not stop", log, 2, started_at=restart_started_at)
+ if stopped is False:
+ remaining_service_pids = _remaining_service_pids_after_stop()
+ if remaining_service_pids:
+ payload["remaining_service_pids"] = remaining_service_pids
+ pid_list = ",".join(str(pid) for pid in remaining_service_pids)
+ return _fail(
+ payload,
+ f"service stop failed; remaining service pid(s): {pid_list}",
+ log,
+ 2,
+ started_at=restart_started_at,
+ )
wait_lock_release_started_at = time.monotonic()
if not _wait_for_service_lock_release():
diff --git a/vibe/runtime.py b/vibe/runtime.py
index bfe77058c..c32d3acd2 100644
--- a/vibe/runtime.py
+++ b/vibe/runtime.py
@@ -12,6 +12,7 @@ import threading
import time
import urllib.error
import urllib.request
+import uuid
from pathlib import Path
import psutil
@@ -247,7 +248,10 @@ def acquire_service_instance_lock() -> None:
json.dumps(
{
"pid": os.getpid(),
+ "instance_id": uuid.uuid4().hex,
"created_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
+ "started_at": process_create_time(os.getpid()),
+ "phase": "running",
"command": get_process_command(os.getpid()),
},
indent=2,
@@ -299,6 +303,30 @@ def service_instance_lock_available() -> tuple[bool, int | None]:
lock_file.close()
+def service_lock_holder_pid() -> int | None:
+ available, holder_pid = service_instance_lock_available()
+ if available:
+ return None
+ return holder_pid
+
+
+def current_process_owns_service_instance() -> bool:
+ """Return whether this process is still the active service owner.
+
+ Controller-owned background services capture whether they require this gate
+ 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.
+ """
+ if _SERVICE_INSTANCE_LOCK_HANDLE is None:
+ return False
+ return service_lock_held_by(os.getpid())
+
+
+def service_instance_lock_attached_to_process() -> bool:
+ return _SERVICE_INSTANCE_LOCK_HANDLE is not None
+
+
def get_shutdown_intent_path() -> Path:
return paths.get_runtime_dir() / "shutdown_intent.json"
@@ -470,7 +498,7 @@ def get_process_command(pid: int) -> str | None:
)
except Exception:
return None
- command = (result.stdout or "").strip()
+ command = (getattr(result, "stdout", "") or "").strip()
return command or None
@@ -517,6 +545,191 @@ def process_create_time(pid: int) -> float | None:
return None
+def _safe_resolve_path(value: str | Path) -> Path | None:
+ try:
+ return Path(value).expanduser().resolve()
+ except (OSError, RuntimeError, ValueError):
+ return None
+
+
+def _path_is_service_entry(path: Path, current_main: Path | None) -> bool:
+ resolved = _safe_resolve_path(path)
+ if current_main is not None and resolved == current_main:
+ return True
+ if path.name == "service_main.py":
+ parent = resolved.parent if resolved is not None else path.parent
+ return parent.name == "vibe" and (parent / "runtime.py").exists()
+ if path.name == "main.py":
+ root = resolved.parent if resolved is not None else path.parent
+ return (root / "vibe" / "runtime.py").exists() and (root / "core" / "controller.py").exists()
+ return False
+
+
+def _service_entry_arg_from_argv(args: list[str]) -> str | None:
+ if not args:
+ return None
+ executable_name = Path(args[0].strip("\"'")).name.lower()
+ if executable_name.startswith("python"):
+ for arg in args[1:]:
+ cleaned_arg = arg.strip("\"'")
+ if cleaned_arg in {"-c", "-m"}:
+ return None
+ if cleaned_arg.startswith("-"):
+ continue
+ return cleaned_arg
+ return None
+ if Path(args[0].strip("\"'")).name in {"main.py", "service_main.py"}:
+ return args[0].strip("\"'")
+ return None
+
+
+def _command_looks_like_service_entry(command: str | None, *, cwd: str | None = None) -> bool:
+ if not command:
+ return False
+ try:
+ args = shlex.split(command, posix=(os.name != "nt"))
+ except ValueError:
+ return False
+ current_main = _safe_resolve_path(get_service_main_path())
+ cwd_path = _safe_resolve_path(cwd) if cwd else None
+ entry_arg = _service_entry_arg_from_argv(args)
+ if not entry_arg:
+ return False
+ path = Path(entry_arg)
+ if not path.is_absolute() and cwd_path is not None:
+ path = cwd_path / path
+ return _path_is_service_entry(path, current_main)
+
+
+def _process_is_service_session_leader(pid: int) -> bool:
+ if os.name == "nt":
+ return True
+ try:
+ return os.getsid(pid) == pid
+ except OSError:
+ return False
+
+
+def _process_command_from_info(proc) -> str | None:
+ info = getattr(proc, "info", {}) or {}
+ cmdline = info.get("cmdline")
+ if cmdline:
+ return shlex.join(str(part) for part in cmdline if str(part))
+ pid = info.get("pid")
+ if isinstance(pid, int):
+ return get_process_command(pid)
+ return None
+
+
+def _process_cwd(proc) -> str | None:
+ try:
+ return proc.cwd()
+ except (psutil.Error, OSError, AttributeError):
+ return None
+
+
+def _process_home_matches_current(proc) -> bool | None:
+ current_home = _safe_resolve_path(paths.get_vibe_remote_dir())
+ if current_home is None:
+ return None
+ try:
+ env = proc.environ()
+ except (psutil.Error, OSError, AttributeError):
+ return None
+ explicit_home = env.get(paths.AVIBE_HOME_ENV)
+ if explicit_home:
+ return _safe_resolve_path(explicit_home) == current_home
+ has_avibe_marker = str(env.get(SHUTDOWN_INTENT_ENV) or "").lower() in {"1", "true", "yes"}
+ has_avibe_marker = has_avibe_marker or str(env.get("VIBE_DISABLE_STDOUT_LOGGING") or "").lower() in {
+ "1",
+ "true",
+ "yes",
+ }
+ if not has_avibe_marker:
+ return None
+ home = env.get("HOME")
+ if not home:
+ return None
+ candidates = [
+ Path(home) / paths.AVIBE_HOME_DIRNAME,
+ Path(home) / paths.LEGACY_HOME_DIRNAME,
+ ]
+ return any(_safe_resolve_path(candidate) == current_home for candidate in candidates)
+
+
+def service_processes(*, include_unverified: bool = False) -> list[dict]:
+ """Return Avibe service processes associated with the current data dir.
+
+ The service lock remains the authoritative owner signal. This process scan is
+ deliberately secondary: it detects extra lock-less daemons left behind by
+ older lifecycle bugs, but only treats a process as actionable when its
+ command looks like Avibe's service entry point and its environment maps to
+ the current AVIBE_HOME. Do not require session leadership here: legacy and
+ container launchers may background ``python main.py`` from a shell without
+ creating a new session, and those lock-less services still need recovery.
+ """
+ processes: list[dict] = []
+ try:
+ iterator = psutil.process_iter(attrs=["pid", "cmdline"])
+ except psutil.Error:
+ return processes
+ for proc in iterator:
+ info = getattr(proc, "info", {}) or {}
+ pid = info.get("pid")
+ if not isinstance(pid, int) or pid <= 0 or pid == os.getpid():
+ continue
+ try:
+ alive = pid_alive(pid)
+ except Exception as exc:
+ logger.warning("Failed to inspect possible service process pid=%s: %s", pid, exc)
+ continue
+ if not alive:
+ continue
+ session_leader = _process_is_service_session_leader(pid)
+ command = _process_command_from_info(proc)
+ if not _command_looks_like_service_entry(command, cwd=_process_cwd(proc)):
+ continue
+ lock_owner = service_lock_held_by(pid)
+ home_match = _process_home_matches_current(proc)
+ if not (lock_owner or home_match is True or (include_unverified and home_match is None)):
+ continue
+ processes.append(
+ {
+ "pid": pid,
+ "command": command,
+ "lock_owner": lock_owner,
+ "home_match": home_match,
+ "session_leader": session_leader,
+ }
+ )
+ return processes
+
+
+def extra_service_process_pids(owner_pid: int | None = None, *, include_unverified: bool = False) -> list[int]:
+ pids: list[int] = []
+ for process in service_processes(include_unverified=include_unverified):
+ pid = process.get("pid")
+ if not isinstance(pid, int) or pid == owner_pid:
+ continue
+ if include_unverified or process.get("home_match") is True or process.get("lock_owner") is True:
+ pids.append(pid)
+ return sorted(set(pids))
+
+
+def service_process_running() -> bool:
+ return resolve_service_owner_pid(include_starting=False) is not None or bool(extra_service_process_pids())
+
+
+def _pid_reservation_is_fresh(pid_path: Path, pid: int, *, max_age: float = SERVICE_SLOW_START_TIMEOUT_SECONDS) -> bool:
+ try:
+ pidfile_mtime = pid_path.stat().st_mtime
+ except OSError:
+ return False
+ create_time = process_create_time(pid)
+ latest_signal = max(pidfile_mtime, create_time or 0)
+ return time.time() - latest_signal <= max_age
+
+
def stop_pid(pid: int, timeout: float = 5) -> bool:
if not isinstance(pid, int) or pid <= 0:
return False
@@ -688,6 +901,36 @@ def service_pid_file_points_to_running_service(pid_path: Path | None = None) ->
return bool(pid and service_pid_recorded(pid))
+def _pid_alive_for_owner_resolution(pid: int) -> bool:
+ try:
+ return pid_alive(pid)
+ except Exception as exc:
+ logger.warning("Failed to inspect service owner pid=%s: %s", pid, exc)
+ return False
+
+
+def resolve_service_owner_pid(*, include_starting: bool = True) -> int | None:
+ """Resolve the live service owner for this data dir.
+
+ The flock in ``service.lock`` is the authoritative owner signal. The pidfile
+ is still useful for fast reuse and for a just-spawned service that has not
+ acquired the lock yet, but it must not be the only lifecycle source of truth.
+ """
+ pid_path = paths.get_runtime_pid_path()
+ recorded_pid = _read_pid_file(pid_path)
+ if recorded_pid and _pid_alive_for_owner_resolution(recorded_pid):
+ if service_pid_recorded(recorded_pid):
+ return recorded_pid
+
+ available, lock_holder_pid = service_instance_lock_available()
+ if not available and lock_holder_pid and _pid_alive_for_owner_resolution(lock_holder_pid):
+ return lock_holder_pid
+ if include_starting and available and recorded_pid and _pid_alive_for_owner_resolution(recorded_pid):
+ if not _pid_mismatches_service(recorded_pid):
+ return recorded_pid
+ return None
+
+
def wait_for_service_pid(pid: int, timeout: float = SERVICE_LOCK_READY_TIMEOUT_SECONDS) -> bool:
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
@@ -764,24 +1007,6 @@ def read_status():
return read_json(paths.get_runtime_status_path()) or {}
-def _command_references_path(command: str | None, expected_path: Path) -> bool:
- if not command:
- return False
- try:
- args = shlex.split(command, posix=(os.name != "nt"))
- except ValueError:
- return False
- expected_resolved = expected_path.resolve()
- for arg in args:
- cleaned_arg = arg.strip("\"'")
- try:
- if Path(cleaned_arg).resolve() == expected_resolved:
- return True
- except (OSError, RuntimeError):
- continue
- return False
-
-
def _pid_mismatches_service(pid: int) -> bool:
command = get_process_command(pid)
if not command:
@@ -790,16 +1015,40 @@ def _pid_mismatches_service(pid: int) -> bool:
pid,
)
return False
- return not _command_references_path(command, get_service_main_path())
+ try:
+ cwd = psutil.Process(pid).cwd()
+ except (psutil.Error, OSError):
+ cwd = None
+ return not _command_looks_like_service_entry(command, cwd=cwd)
def render_status():
status = read_status()
- pid_path = paths.get_runtime_pid_path()
- pid = pid_path.read_text(encoding="utf-8").strip() if pid_path.exists() else None
- running = bool(pid and pid.isdigit() and service_pid_recorded(int(pid)))
+ owner_pid = resolve_service_owner_pid(include_starting=False)
+ extra_pids = extra_service_process_pids(owner_pid=owner_pid)
+ running = bool(owner_pid or extra_pids)
+ if owner_pid:
+ status["state"] = "running"
+ status["service_pid"] = owner_pid
+ if extra_pids:
+ status["detail"] = f"pid={owner_pid}; extra_service_pids={','.join(str(pid) for pid in extra_pids)}"
+ else:
+ status["detail"] = f"pid={owner_pid}"
+ elif extra_pids:
+ status["state"] = "degraded"
+ status["service_pid"] = extra_pids[0]
+ status["detail"] = f"lockless service process detected pid={extra_pids[0]}"
+ elif status.get("state") in {"running", "degraded"}:
+ status["state"] = "stopped"
+ status["detail"] = "process not running"
+ status["service_pid"] = None
+ if extra_pids:
+ status["extra_service_pids"] = extra_pids
+ else:
+ status.pop("extra_service_pids", None)
+ status["service_owner_pid"] = owner_pid
status["running"] = running
- status["pid"] = int(pid) if pid and pid.isdigit() else None
+ status["pid"] = owner_pid or (extra_pids[0] if extra_pids else None)
restart_status = read_json(get_restart_status_path())
if restart_status:
status["restart"] = restart_status
@@ -832,11 +1081,28 @@ def start_service(
if not _pid_mismatches_service(existing_pid):
if service_pid_recorded(existing_pid):
return existing_pid
- if not wait_for_ready:
- return existing_pid
- if wait_for_service_pid(existing_pid, timeout=SERVICE_SLOW_START_TIMEOUT_SECONDS):
- return existing_pid
- _raise_service_start_not_ready(existing_pid, timeout=SERVICE_SLOW_START_TIMEOUT_SECONDS)
+ if _pid_reservation_is_fresh(pid_path, existing_pid):
+ if not wait_for_ready:
+ return existing_pid
+ if wait_for_service_pid(existing_pid, timeout=SERVICE_SLOW_START_TIMEOUT_SECONDS):
+ return existing_pid
+ _raise_service_start_not_ready(existing_pid, timeout=SERVICE_SLOW_START_TIMEOUT_SECONDS)
+ logger.warning(
+ "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()
+ if not lock_available:
+ if lock_holder_pid and pid_alive(lock_holder_pid):
+ if lock_holder_pid == existing_pid:
+ logger.warning(
+ "Reusing service pid=%s from lock even though the pid file command does not "
+ "match this CLI install",
+ existing_pid,
+ )
+ return lock_holder_pid
+ raise ServiceAlreadyRunningError(lock_path=get_service_lock_path(), holder_pid=lock_holder_pid)
+ raise ServiceAlreadyRunningError(lock_path=get_service_lock_path(), holder_pid=lock_holder_pid)
logger.warning(
"Ignoring stale service pid file pid=%s because it does not match the Vibe service",
existing_pid,
@@ -849,6 +1115,10 @@ def start_service(
return lock_holder_pid
raise ServiceAlreadyRunningError(lock_path=get_service_lock_path(), holder_pid=lock_holder_pid)
+ extra_pids = extra_service_process_pids()
+ if extra_pids:
+ raise ServiceAlreadyRunningError(lock_path=get_service_lock_path(), holder_pid=extra_pids[0])
+
main_path = get_service_main_path()
process = spawn_service_background_process(
[sys.executable, str(main_path)],
@@ -1036,7 +1306,31 @@ def start_ui(host, port, *, wait_for_ready: bool = True):
def stop_service():
with _SERVICE_LOCK:
- return stop_process(paths.get_runtime_pid_path())
+ pid_path = paths.get_runtime_pid_path()
+ owner_pid = resolve_service_owner_pid()
+ target_pids: list[int] = []
+ if owner_pid is not None:
+ target_pids.append(owner_pid)
+ target_pids.extend(extra_service_process_pids(owner_pid=owner_pid))
+ target_pids = sorted(set(target_pids))
+ if not target_pids:
+ recorded_pid = _read_pid_file(pid_path)
+ if recorded_pid and not pid_alive(recorded_pid):
+ pid_path.unlink(missing_ok=True)
+ return False
+
+ stopped_all = True
+ for pid in target_pids:
+ stopped = stop_pid(pid, timeout=5)
+ if stopped:
+ _clear_service_pid_reservation(pid)
+ continue
+ stopped_all = False
+ logger.error(
+ "Failed to stop resolved service process pid=%s; preserving pid and lock state",
+ pid,
+ )
+ return stopped_all
def stop_ui(timings: dict[str, float | bool] | None = None, *, stop_remote_access: bool = True):
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index d362ab1db..ef4254877 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -258,10 +258,11 @@ def _runtime_pid_file_points_to_live_process(pid_path: Path) -> bool:
def _stop_runtime_process_or_error(pid_path: Path, label: str) -> tuple[bool, str | None]:
from vibe import runtime
- was_running = _runtime_pid_file_points_to_live_process(pid_path)
if pid_path == paths.get_runtime_pid_path():
+ was_running = runtime.resolve_service_owner_pid() is not None or bool(runtime.extra_service_process_pids())
stopped = runtime.stop_service()
else:
+ was_running = _runtime_pid_file_points_to_live_process(pid_path)
stopped = runtime.stop_process(pid_path)
if was_running and stopped is False:
return False, f"{label} did not stop"
@@ -2003,23 +2004,10 @@ def health():
def status():
from vibe import runtime
- payload = runtime.read_status()
- pid_path = paths.get_runtime_pid_path()
- pid = pid_path.read_text(encoding="utf-8").strip() if pid_path.exists() else None
- try:
- running = bool(pid and pid.isdigit() and runtime.service_pid_recorded(int(pid)))
- except Exception as exc:
- logger.warning("Failed to inspect service pid %s: %s", pid, exc)
- running = False
- payload["running"] = running
- payload["pid"] = int(pid) if pid and pid.isdigit() else None
- if running:
- payload["service_pid"] = payload.get("service_pid") or payload["pid"]
- elif payload.get("state") == "running":
+ payload = json.loads(runtime.render_status())
+ if not payload.get("running") and runtime.read_status().get("state") == "running":
runtime.write_status("stopped", "process not running", None, payload.get("ui_pid"))
- payload = runtime.read_status()
- payload["running"] = False
- payload["pid"] = None
+ payload = json.loads(runtime.render_status())
return jsonify(payload)