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.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(tests): fail fake pids loudly instead of reading whatever holds them (#2308)
Call Whitef432f0217819
diff --git a/tests/conftest.py b/tests/conftest.pyindex 479a2a915..d3c6b705d 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -63,6 +63,8 @@ import psutilimport pytestfrom sqlalchemy.exc import SAWarning+from tests.fake_pid_helpers import PID_LIMIT+REAL_USER_HOME = Path.home()_SQLITE_DEFAULT_STATE_MODULES: dict[Path, bool] = {}@@ -376,9 +378,14 @@ _REAL_OS_GETPGID = getattr(os, "getpgid", None)_REAL_OS_GETSID = getattr(os, "getsid", None)_REAL_OS_GETPGRP = getattr(os, "getpgrp", None)_REAL_PSUTIL_PROCESS = psutil.Process+_REAL_PSUTIL_PROCESS_INIT = psutil.Process.__init___REAL_PSUTIL_PIDS = psutil.pids_REAL_POPEN_INIT = subprocess.Popen.__init__+# The packages the wheel ships: a process lookup made from one of them is the+# product's, and that is where a test's fake pid must not reach the real table.+_PRODUCT_PACKAGES = frozenset({"vibe", "config", "core", "modules", "storage"})+def _describe_pid(pid: int) -> str:try:@@ -410,6 +417,19 @@ class _ForeignSignalGuard:gets the ESRCH the real call would raise, delivered to nothing, because adescendant the test collected may exit before it is signalled. Signal 0 isa liveness probe and passes.++ The same record bounds what the product may look up. A ``psutil.Process``,+ or a signal-0 probe of a pid or a group, made from the product's packages+ must name this pytest process, a process the test owns, one psutil listed+ during the test, or a pid no process can hold: for any other pid the answer depends on which+ process, if any, holds it on the machine running the test, which is how a+ fake pid such as 1234 turned into a refusal on the one CI runner where a+ real process held it. With nothing holding the pid the lookup fails at+ once, so such a test fails everywhere instead; the pids+ ``tests.fake_pid_helpers.fake_pid`` hands out are the ones that stand for+ no process. A listing makes every pid it saw fair, so a fake pid that+ collides with one the test listed earlier still slips through; that test+ has failed on every machine where the pid was free."""def __init__(self, test_temp: Path) -> None:@@ -417,6 +437,8 @@ class _ForeignSignalGuard:# The whole final component: `test_x1` must not claim `test_x10`.self.names_test_temp = re.compile(re.escape(str(test_temp)) + r"(?![\w.-])").searchself.owned: set[int] = set()+ # Every pid psutil listed while this test ran: a scan finds real processes by design.+ self.listed: set[int] = set()self.violations: list[str] = []def _owns(self, pid: int) -> bool:@@ -521,15 +543,39 @@ class _ForeignSignalGuard:# cannot swallow it; the teardown check covers anything broader.pytest.fail(message)+ def refuse_unknown_lookup(self, lookup: str, pid: int, caller) -> None:+ """Fail the test when the product's ``lookup`` of ``pid`` would read whatever the machine holds there."""++ __tracebackhide__ = True+ if pid == self.me or pid >= PID_LIMIT or pid in self.listed or self._owns(pid):+ return+ message = (+ f"{caller.f_globals.get('__name__')}.{caller.f_code.co_name} looked up pid "+ f"{_describe_pid(pid)} through {lookup}, a pid this test neither started nor found "+ "by listing processes, so what the product reads depends on which process, if any, "+ "holds that pid on the machine running the test. Use "+ "tests.fake_pid_helpers.fake_pid() for a pid that stands for no process, or start a "+ "real process when the product must read its identity."+ )+ self.violations.append(message)+ pytest.fail(message)+# The running test's guard, or None between tests and in opted-out tests._active_signal_guard: _ForeignSignalGuard | None = None+def _called_from_product(caller) -> bool:+ return caller.f_globals.get("__name__", "").partition(".")[0] in _PRODUCT_PACKAGES++def _guarded_kill(pid, sig):__tracebackhide__ = Trueguard = _active_signal_guardif guard is not None:+ caller = sys._getframe(1)+ if sig == 0 and isinstance(pid, int) and pid > 0 and _called_from_product(caller):+ guard.refuse_unknown_lookup("os.kill(pid, 0)", pid, caller)guard.refuse_foreign("kill", pid, sig, pid)return _REAL_OS_KILL(pid, sig)@@ -538,6 +584,10 @@ def _guarded_killpg(pgid, sig):__tracebackhide__ = Trueguard = _active_signal_guardif guard is not None:+ caller = sys._getframe(1)+ # A group is named by its leader's pid.+ if sig == 0 and isinstance(pgid, int) and pgid > 0 and _called_from_product(caller):+ guard.refuse_unknown_lookup("os.killpg(pgid, 0)", pgid, caller)# libc's killpg(pgid) is kill(-pgid): on macOS a negative pgid names one pid.guard.refuse_foreign("killpg", pgid, sig, -pgid if isinstance(pgid, int) else pgid)return _REAL_OS_KILLPG(pgid, sig)@@ -551,6 +601,30 @@ def _recording_popen_init(popen, *args, **kwargs):guard.owned.add(popen.pid)+@wraps(_REAL_PSUTIL_PROCESS_INIT)+def _guarded_process_init(process, pid=None):+ __tracebackhide__ = True+ guard = _active_signal_guard+ caller = sys._getframe(1)+ # The guard reads the real table through this same constructor.+ if guard is not None and caller.f_globals is not globals() and isinstance(pid, int) and pid > 0:+ if caller.f_globals.get("__name__", "").partition(".")[0] == "psutil":+ # What psutil constructs itself it has listed: process_iter, children(), parents().+ guard.listed.add(pid)+ elif _called_from_product(caller):+ guard.refuse_unknown_lookup("psutil.Process", pid, caller)+ _REAL_PSUTIL_PROCESS_INIT(process, pid)+++@wraps(_REAL_PSUTIL_PIDS)+def _listing_pids():+ pids = _REAL_PSUTIL_PIDS()+ guard = _active_signal_guard+ if guard is not None:+ guard.listed.update(pids)+ return pids++# Installed once for the whole run rather than per test through `monkeypatch`:# a test's own `monkeypatch.undo()` would otherwise remove the guard mid-test.# psutil's `send_signal`/`terminate`/`kill` and `subprocess.Popen`'s all end in@@ -558,12 +632,16 @@ def _recording_popen_init(popen, *args, **kwargs):# on Windows `os.kill` is TerminateProcess (and signal 0 is CTRL_C_EVENT, not a# probe), `os.killpg` does not exist, and the product's Windows stop path calls# TerminateProcess through ctypes, so wrapping `os.kill` there would guard-# nothing the product reaches.+# nothing the product reaches. Every psutil lookup constructs a `Process`, and+# `process_iter` lists through the module's `pids`; a test that replaces+# `psutil.Process` with its own fake bypasses both, as it means to._SIGNAL_GUARD_SUPPORTED = os.name != "nt" and _REAL_OS_KILLPG is not Noneif _SIGNAL_GUARD_SUPPORTED:os.kill = _guarded_killos.killpg = _guarded_killpgsubprocess.Popen.__init__ = _recording_popen_init+ psutil.Process.__init__ = _guarded_process_init+ psutil.pids = _listing_pids@pytest.fixture(autouse=True)@@ -575,6 +653,11 @@ def _foreign_signal_guard(request, tmp_path):pid -- on a CI runner that was the pytest process itself, on a developermachine it can be the live Avibe service. Processes a test starts staysignalable; ``allow_foreign_signals(reason=...)`` opts a test out.++ A fake pid the product only reads is as machine-dependent: a desktop start+ that asked psutil for pid 1234's environment was refused on the one runner+ where a root process held 1234. So the product's lookups are bounded the+ same way."""global _active_signal_guard@@ -595,7 +678,7 @@ def _foreign_signal_guard(request, tmp_path):_active_signal_guard = None__tracebackhide__ = Trueif guard.violations:- pytest.fail("signals to processes this test did not start were blocked:\n" + "\n".join(guard.violations))+ pytest.fail("signals and lookups this test may not make were blocked:\n" + "\n".join(guard.violations))@pytest.fixturediff --git a/tests/fake_pid_helpers.py b/tests/fake_pid_helpers.pynew file mode 100644index 000000000..ed294cc0b--- /dev/null+++ b/tests/fake_pid_helpers.py@@ -0,0 +1,23 @@+"""Pids that stand for no process in a test.++A small literal such as 1234 reads whatever process holds that pid on the+machine running the test: a desktop start that asked psutil for pid 1234's+environment was refused on the one CI runner where a root process held it.+Linux keeps every pid below 2**22 (PID_MAX_LIMIT) and macOS below 99999, so no+process, the test's own included, can hold a pid from ``fake_pid``: psutil+raises ``NoSuchProcess`` for it and every signal raises ``ProcessLookupError``,+on any Linux or macOS machine.+"""++PID_LIMIT = 2**22+++def fake_pid(index: int = 0) -> int:+ """The ``index``-th pid no process can hold; distinct indexes give distinct pids.++ On Linux and macOS no process can hold the value, so the kernel answers "no+ such process". Windows is out of scope: its pids have no ceiling below this,+ and the guard is POSIX-only and these tests do not run there.+ """++ return PID_LIMIT + 1 + indexdiff --git a/tests/test_command_runner.py b/tests/test_command_runner.pyindex 28aaa00c2..ae3d4c4d3 100644--- a/tests/test_command_runner.py+++ b/tests/test_command_runner.py@@ -16,6 +16,7 @@ from core.command_runner import (SupervisedCommandStartupError,run_supervised_command,)+from tests.fake_pid_helpers import fake_pidclass _FakeStdin:@@ -45,7 +46,8 @@ class _FakeProcess:stdin: _FakeStdin | None = None,stderr: bytes = b"",) -> None:- self.pid = 1234+ # A supervisor that never ran: its pid stands for no process.+ self.pid = fake_pid()self.returncode = 0self.stdin = stdin or _FakeStdin()self.stderr = stderrdiff --git a/tests/test_conftest_signal_guard.py b/tests/test_conftest_signal_guard.pyindex b809dbdbd..0142dc747 100644--- a/tests/test_conftest_signal_guard.py+++ b/tests/test_conftest_signal_guard.py@@ -5,10 +5,15 @@ Without it, a fixture that made ``pid_alive`` true for fake pids let a failedstart roll back through the real ``stop_ui()``, which sent SIGTERM to pid 5678:on a CI runner that pid was the pytest process itself, and the shard died withexit code 143.++The same guard bounds the product's process lookups. A desktop start that read+fake pid 1234's environment through psutil was refused on the one runner where a+root process held 1234, and passed everywhere else."""from __future__ import annotations+import loggingimport osimport signalimport subprocess@@ -19,13 +24,15 @@ from contextlib import suppressimport psutilimport pytest+from core.process_isolation import process_group_existsfrom tests.conftest import _REAL_OS_KILL+from tests.fake_pid_helpers import fake_pid+from vibe import runtimepytestmark = pytest.mark.skipif(os.name == "nt", reason="the guard is POSIX-only; see tests/conftest.py")_SLEEP = [sys.executable, "-c", "import time; time.sleep(60)"]-# Above every pid_max Linux and macOS allow, so no process can ever hold it.-_NO_SUCH_PID = 2**22 + 1+_NO_SUCH_PID = fake_pid()def _spawn_detached(@@ -246,3 +253,48 @@ def test_signal_zero_still_probes_any_pid(stranger):def test_the_opt_out_marker_delivers_a_signal_the_guard_would_refuse(stranger):os.kill(stranger, signal.SIGTERM)assert _wait_until_gone(stranger)+++def _free_pid() -> int:+ """A pid nothing holds right now, below every pid limit, so the guard is what answers."""++ for pid in range(99_998, 1, -1):+ try:+ _REAL_OS_KILL(pid, 0)+ except ProcessLookupError:+ return pid+ except PermissionError:+ continue+ pytest.skip("every pid below 99999 is taken")+++ "lookup",+ [+ pytest.param(runtime.process_create_time, id="psutil.Process"),+ pytest.param(runtime.pid_alive, id="signal-0-probe"),+ pytest.param(lambda pid: process_group_exists(pid, logging.getLogger(__name__), "test"), id="group-probe"),+ ],+)[email protected]("holder", ["a-stranger", "nothing"])+def test_a_product_lookup_of_a_pid_the_test_did_not_start_fails_whatever_holds_it(+ request, lookup, holder, _foreign_signal_guard+):+ # Failing while nothing holds the pid is what makes a fake pid fail on every+ # machine, instead of only where a real process happens to hold it. The+ # stranger leads its own session, so its pid names a live group too.+ pid = request.getfixturevalue("stranger") if holder == "a-stranger" else _free_pid()+ with pytest.raises(pytest.fail.Exception, match="neither started nor found by listing"):+ lookup(pid)+ _foreign_signal_guard.violations.clear()+++def test_a_fake_pid_names_no_process_on_any_machine(_foreign_signal_guard):+ pid = fake_pid()++ assert runtime.process_create_time(pid) is None+ assert runtime.pid_alive(pid) is False+ assert process_group_exists(pid, logging.getLogger(__name__), "test") is False+ with pytest.raises(ProcessLookupError):+ os.kill(pid, signal.SIGTERM)+ assert _foreign_signal_guard.violations == []diff --git a/tests/test_desktop_runtime.py b/tests/test_desktop_runtime.pyindex 7db07278c..92ff9c14f 100644--- a/tests/test_desktop_runtime.py+++ b/tests/test_desktop_runtime.py@@ -5,6 +5,7 @@ import ioimport jsonimport osimport socket+import subprocessimport sysimport threadingimport urllib.error@@ -1342,6 +1343,7 @@ def test_ready_rejects_an_invalid_bundled_ui_identity(monkeypatch):def test_cmd_start_reused_controller_starts_missing_ui_and_emits_untagged_ready(monkeypatch,capsys,+ request,):"""The reused-service path must start only the missing UI and become adoptable."""@@ -1353,19 +1355,28 @@ def test_cmd_start_reused_controller_starts_missing_ui_and_emits_untagged_ready(spawned = []monkeypatch.setenv("AVIBE_DESKTOP_RUNTIME_ID", "a" * 64)+ # The reused Controller is this Runtime's: a live process carrying its id,+ # which the start's claim reads before it reuses anything.+ controller = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"])++ def stop_controller():+ controller.kill()+ controller.wait(timeout=10)++ request.addfinalizer(stop_controller)monkeypatch.setattr(cli, "_guard_cli_default_state_migration", lambda: None)monkeypatch.setattr(cli, "_ensure_config", lambda: config)monkeypatch.setattr(cli, "_write_status", lambda *args: None)monkeypatch.setattr(cli, "_in_ssh_session", lambda: False)monkeypatch.setattr(cli.runtime, "effective_ui_bind_host", lambda _config: "127.0.0.1")- monkeypatch.setattr(cli.runtime, "resolve_service_owner_pid", lambda **_kwargs: 1234)+ monkeypatch.setattr(cli.runtime, "resolve_service_owner_pid", lambda **_kwargs: controller.pid)monkeypatch.setattr(cli.runtime, "wait_for_service_ready", lambda pid, timeout: pid)monkeypatch.setattr(cli.runtime, "write_status", lambda *args: None)monkeypatch.setattr(cli, "_open_browser", lambda _url: pytest.fail("browser is disabled"))def reused_service(**kwargs):- kwargs["start_info"].capture(1234, reused=True)- return 1234+ kwargs["start_info"].capture(controller.pid, reused=True)+ return controller.pidmonkeypatch.setattr(cli.runtime, "start_service", reused_service)monkeypatch.setattr(diff --git a/tests/test_opencode_server.py b/tests/test_opencode_server.pyindex 068184115..9ec95e2f4 100644--- a/tests/test_opencode_server.py+++ b/tests/test_opencode_server.py@@ -14,6 +14,7 @@ from unittest.mock import AsyncMock, Mock, patchsys.path.insert(0, str(Path(__file__).resolve().parents[1]))from storage import message_deliveries as delivery_store+from tests.fake_pid_helpers import fake_pidfrom vibe.opencode_config import OPENCODE_REASONING_VARIANTS@@ -188,7 +189,7 @@ class OpenCodeServerTests(unittest.IsolatedAsyncioTestCase):async def test_start_server_reaps_a_live_process_after_cold_start_timeout(self):manager = OpenCodeServerManager(binary="opencode", port=4096)- process = types.SimpleNamespace(pid=4321, returncode=None)+ process = types.SimpleNamespace(pid=fake_pid(), returncode=None)manager._is_healthy = AsyncMock(return_value=False) # type: ignore[method-assign]manager._write_pid_file = Mock() # type: ignore[method-assign]manager._clear_pid_file = Mock() # type: ignore[method-assign]@@ -619,7 +620,7 @@ class OpenCodeServerTests(unittest.IsolatedAsyncioTestCase):async def create_subprocess_exec(*args, **kwargs):launched["args"] = argslaunched["env"] = kwargs["env"]- return types.SimpleNamespace(pid=4321, returncode=None)+ return types.SimpleNamespace(pid=fake_pid(), returncode=None)with (patch.object(SERVER_MODULE, "is_model_hub_enabled", return_value=True),@@ -905,7 +906,7 @@ class OpenCodeServerTests(unittest.IsolatedAsyncioTestCase):manager._restart_for_auth_refresh_locked = AsyncMock() # type: ignore[method-assign]manager._start_server = AsyncMock() # type: ignore[method-assign]manager._read_pid_file = lambda: { # type: ignore[method-assign]- "pid": 123,+ "pid": fake_pid(),"port": 4096,"caller_context_path": adopted_path,"active_run_sessions": ["ses-active"],@@ -1092,7 +1093,7 @@ class OpenCodeServerTests(unittest.IsolatedAsyncioTestCase):async def test_ensure_running_retires_generation_when_adopted_pid_changes(self):manager = OpenCodeServerManager(binary="opencode", port=4096)retired = []- manager._runtime_generation_token = (111, 1.0)+ manager._runtime_generation_token = (fake_pid(0), 1.0)manager.set_runtime_activation_retire(lambda force, native_turns_drained: retired.append((force, native_turns_drained)@@ -1102,7 +1103,7 @@ class OpenCodeServerTests(unittest.IsolatedAsyncioTestCase):manager._is_healthy = AsyncMock(return_value=True) # type: ignore[method-assign]manager._cleanup_orphaned_managed_server = AsyncMock() # type: ignore[method-assign]manager._read_pid_file = lambda: { # type: ignore[method-assign]- "pid": 222,+ "pid": fake_pid(1),"port": 4096,"started_at": 2.0,"caller_context_path": manager._caller_context_path(),@@ -1118,7 +1119,7 @@ class OpenCodeServerTests(unittest.IsolatedAsyncioTestCase):await manager.ensure_running()self.assertEqual(retired, [(True, False)])- self.assertEqual(manager._runtime_generation_token, (222, 2.0))+ self.assertEqual(manager._runtime_generation_token, (fake_pid(1), 2.0))async def test_prompt_async_percent_encodes_directory_header(self):manager = OpenCodeServerManager(binary="opencode", port=4096)diff --git a/tests/test_runtime_service_lock.py b/tests/test_runtime_service_lock.pyindex 67cb94f8d..08622bee2 100644--- a/tests/test_runtime_service_lock.py+++ b/tests/test_runtime_service_lock.py@@ -9,8 +9,13 @@ from unittest.mock import patchsys.path.insert(0, str(Path(__file__).resolve().parents[1]))+from tests.fake_pid_helpers import fake_pidfrom vibe import runtime+# Pids no process can hold: the one a record or lock names, and the one a spawn returns.+_RECORDED_PID = fake_pid(0)+_SPAWNED_PID = fake_pid(1)+def _spawned(process):"""Stand in for the spawn primitive, which hands a child over before returning it."""@@ -54,7 +59,7 @@ class RuntimeServiceLockTests(unittest.TestCase):def test_start_service_reuses_existing_live_pid(self):with tempfile.TemporaryDirectory() as tmpdir:pid_path = Path(tmpdir) / "service.pid"- pid_path.write_text("12345", encoding="utf-8")+ pid_path.write_text(str(_RECORDED_PID), 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):@@ -66,17 +71,17 @@ class RuntimeServiceLockTests(unittest.TestCase):with patch("vibe.runtime.spawn_service_background_process") as spawn_background:pid = runtime.start_service()- self.assertEqual(pid, 12345)+ self.assertEqual(pid, _RECORDED_PID)spawn_background.assert_not_called()def test_start_service_ignores_reused_unrelated_pid(self):with tempfile.TemporaryDirectory() as tmpdir:pid_path = Path(tmpdir) / "service.pid"- pid_path.write_text("12345", encoding="utf-8")+ pid_path.write_text(str(_RECORDED_PID), encoding="utf-8")def fake_spawn(args, stdout_name, stderr_name, env=None, *, hand_over, **kwargs):# The primitive hands the child over before it returns it.- process = SimpleNamespace(pid=67890, poll=lambda: None)+ process = SimpleNamespace(pid=_SPAWNED_PID, poll=lambda: None)hand_over(process)return process@@ -90,25 +95,25 @@ class RuntimeServiceLockTests(unittest.TestCase):with patch("vibe.runtime.wait_for_service_pid", return_value=True):pid = runtime.start_service()- self.assertEqual(pid, 67890)+ self.assertEqual(pid, _SPAWNED_PID)spawn_background.assert_called_once()- self.assertEqual(pid_path.read_text(encoding="utf-8"), "67890")+ self.assertEqual(pid_path.read_text(encoding="utf-8"), str(_SPAWNED_PID))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")+ pid_path.write_text(str(_RECORDED_PID), 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.service_instance_lock_available", return_value=(False, _RECORDED_PID)):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")+ self.assertEqual(pid, _RECORDED_PID)+ self.assertEqual(pid_path.read_text(encoding="utf-8"), str(_RECORDED_PID))spawn_background.assert_not_called()def test_start_service_refuses_duplicate_when_pidfile_missing_but_lock_is_held(self):@@ -116,7 +121,7 @@ class RuntimeServiceLockTests(unittest.TestCase):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.service_instance_lock_available", return_value=(False, _RECORDED_PID)):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):@@ -127,7 +132,7 @@ class RuntimeServiceLockTests(unittest.TestCase):def test_start_service_reuses_live_pid_when_command_is_unreadable(self):with tempfile.TemporaryDirectory() as tmpdir:pid_path = Path(tmpdir) / "service.pid"- pid_path.write_text("12345", encoding="utf-8")+ pid_path.write_text(str(_RECORDED_PID), 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):@@ -136,7 +141,7 @@ class RuntimeServiceLockTests(unittest.TestCase):with patch("vibe.runtime.spawn_service_background_process") as spawn_background:pid = runtime.start_service()- self.assertEqual(pid, 12345)+ self.assertEqual(pid, _RECORDED_PID)spawn_background.assert_not_called()def test_start_service_errors_when_lock_holder_is_not_recorded_pid(self):@@ -144,7 +149,7 @@ class RuntimeServiceLockTests(unittest.TestCase):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.service_instance_lock_available", return_value=(False, _RECORDED_PID)):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):@@ -168,7 +173,7 @@ class RuntimeServiceLockTests(unittest.TestCase):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")+ pid_path.write_text(str(_RECORDED_PID), encoding="utf-8")stale_time = runtime.time.time() - runtime.SERVICE_SLOW_START_TIMEOUT_SECONDS - 10os.utime(pid_path, (stale_time, stale_time))@@ -181,7 +186,7 @@ class RuntimeServiceLockTests(unittest.TestCase):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.extra_service_process_pids", return_value=[_RECORDED_PID]):with patch("vibe.runtime.wait_for_service_pid") as wait_for_pid:with patch("vibe.runtime.spawn_service_background_process"@@ -195,7 +200,7 @@ class RuntimeServiceLockTests(unittest.TestCase):def test_start_service_returns_live_pid_when_lock_write_is_slow(self):with tempfile.TemporaryDirectory() as tmpdir:pid_path = Path(tmpdir) / "service.pid"- process = SimpleNamespace(pid=67890, poll=lambda: None)+ process = SimpleNamespace(pid=_SPAWNED_PID, poll=lambda: None)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)):@@ -204,13 +209,13 @@ class RuntimeServiceLockTests(unittest.TestCase):with patch("vibe.runtime.pid_alive", return_value=True):pid = runtime.start_service(wait_for_ready=False)- self.assertEqual(pid, 67890)- self.assertEqual(pid_path.read_text(encoding="utf-8"), "67890")+ self.assertEqual(pid, _SPAWNED_PID)+ self.assertEqual(pid_path.read_text(encoding="utf-8"), str(_SPAWNED_PID))def test_start_service_can_skip_initial_ready_wait(self):with tempfile.TemporaryDirectory() as tmpdir:pid_path = Path(tmpdir) / "service.pid"- process = SimpleNamespace(pid=67890, poll=lambda: None)+ process = SimpleNamespace(pid=_SPAWNED_PID, poll=lambda: None)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)):@@ -219,14 +224,14 @@ class RuntimeServiceLockTests(unittest.TestCase):with patch("vibe.runtime.pid_alive", return_value=True):pid = runtime.start_service(wait_for_ready=False, initial_ready_timeout=0)- self.assertEqual(pid, 67890)+ self.assertEqual(pid, _SPAWNED_PID)wait_for_pid.assert_not_called()- self.assertEqual(pid_path.read_text(encoding="utf-8"), "67890")+ self.assertEqual(pid_path.read_text(encoding="utf-8"), str(_SPAWNED_PID))def test_start_service_errors_when_spawned_process_dies_before_lock(self):with tempfile.TemporaryDirectory() as tmpdir:pid_path = Path(tmpdir) / "service.pid"- process = SimpleNamespace(pid=67890, poll=lambda: 1)+ process = SimpleNamespace(pid=_SPAWNED_PID, poll=lambda: 1)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)):@@ -241,7 +246,7 @@ class RuntimeServiceLockTests(unittest.TestCase):def test_start_service_waits_for_readiness_by_default(self):with tempfile.TemporaryDirectory() as tmpdir:pid_path = Path(tmpdir) / "service.pid"- process = SimpleNamespace(pid=67890, poll=lambda: None)+ process = SimpleNamespace(pid=_SPAWNED_PID, poll=lambda: None)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)):@@ -250,13 +255,13 @@ class RuntimeServiceLockTests(unittest.TestCase):with patch("vibe.runtime.pid_alive", return_value=True):pid = runtime.start_service()- self.assertEqual(pid, 67890)+ self.assertEqual(pid, _SPAWNED_PID)self.assertEqual(wait_for_pid.call_count, 2)def test_start_service_reuses_pending_reservation_without_spawning_second_worker(self):with tempfile.TemporaryDirectory() as tmpdir:pid_path = Path(tmpdir) / "service.pid"- pid_path.write_text("67890", encoding="utf-8")+ pid_path.write_text(str(_SPAWNED_PID), 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):@@ -268,13 +273,13 @@ class RuntimeServiceLockTests(unittest.TestCase):with patch("vibe.runtime.spawn_service_background_process") as spawn_background:pid = runtime.start_service(wait_for_ready=False)- self.assertEqual(pid, 67890)+ self.assertEqual(pid, _SPAWNED_PID)spawn_background.assert_not_called()def test_start_service_reuses_scoped_wrapper_reservation(self):with tempfile.TemporaryDirectory() as tmpdir:pid_path = Path(tmpdir) / "service.pid"- pid_path.write_text("67890", encoding="utf-8")+ pid_path.write_text(str(_SPAWNED_PID), encoding="utf-8")command = runtime.shlex.join(["systemd-run",@@ -296,13 +301,13 @@ class RuntimeServiceLockTests(unittest.TestCase):with patch("vibe.runtime.spawn_service_background_process") as spawn_background:pid = runtime.start_service(wait_for_ready=False)- self.assertEqual(pid, 67890)+ self.assertEqual(pid, _SPAWNED_PID)spawn_background.assert_not_called()def test_start_service_adopts_scoped_wrapper_lock_holder(self):with tempfile.TemporaryDirectory() as tmpdir:pid_path = Path(tmpdir) / "service.pid"- pid_path.write_text("67890", encoding="utf-8")+ pid_path.write_text(str(_SPAWNED_PID), encoding="utf-8")command = runtime.shlex.join(["systemd-run",@@ -332,7 +337,7 @@ class RuntimeServiceLockTests(unittest.TestCase):# bound is asserted as a bound; `ServiceReadinessGateTests` pins how# it is spent.wait_for_ready.assert_called_once()- self.assertEqual(wait_for_ready.call_args.args, (67890,))+ self.assertEqual(wait_for_ready.call_args.args, (_SPAWNED_PID,))self.assertLessEqual(wait_for_ready.call_args.kwargs["timeout"],runtime.SERVICE_SLOW_START_TIMEOUT_SECONDS,@@ -342,14 +347,14 @@ class RuntimeServiceLockTests(unittest.TestCase):def test_stop_service_stops_pending_pid_reservation(self):with tempfile.TemporaryDirectory() as tmpdir:pid_path = Path(tmpdir) / "service.pid"- pid_path.write_text("67890", encoding="utf-8")+ pid_path.write_text(str(_SPAWNED_PID), 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.stop_pid", return_value=True) as stop_pid:self.assertTrue(runtime.stop_service())- stop_pid.assert_called_once_with(67890, timeout=5)+ stop_pid.assert_called_once_with(_SPAWNED_PID, timeout=5)self.assertFalse(pid_path.exists())def test_stop_service_targets_lock_holder_when_pidfile_is_missing(self):@@ -357,12 +362,12 @@ class RuntimeServiceLockTests(unittest.TestCase):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.service_instance_lock_available", return_value=(False, _RECORDED_PID)):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)+ stop_pid.assert_called_once_with(_RECORDED_PID, timeout=5)def test_stop_service_prefers_lock_holder_over_live_pidfile_reservation(self):with tempfile.TemporaryDirectory() as tmpdir:@@ -592,37 +597,37 @@ class RuntimeServiceLockTests(unittest.TestCase):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.service_instance_lock_available", return_value=(False, _RECORDED_PID)):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)+ self.assertEqual(payload["service_pid"], _RECORDED_PID)+ self.assertEqual(payload["pid"], _RECORDED_PID)def test_render_status_skips_extra_process_scan_when_requested(self):with tempfile.TemporaryDirectory() as tmpdir:status_path = Path(tmpdir) / "status.json"- runtime.write_json(status_path, {"state": "running", "service_pid": 12345})+ runtime.write_json(status_path, {"state": "running", "service_pid": _RECORDED_PID})with patch("vibe.runtime.paths.get_runtime_status_path", return_value=status_path):- with patch("vibe.runtime.resolve_service_owner_pid", return_value=12345):+ with patch("vibe.runtime.resolve_service_owner_pid", return_value=_RECORDED_PID):with patch("vibe.runtime.extra_service_process_pids") as extra_service_process_pids:payload = runtime.json.loads(runtime.render_status(detect_extra_processes=False))extra_service_process_pids.assert_not_called()self.assertTrue(payload["running"])self.assertEqual(payload["state"], "running")- self.assertEqual(payload["service_pid"], 12345)- self.assertEqual(payload["pid"], 12345)- self.assertEqual(payload["service_owner_pid"], 12345)+ self.assertEqual(payload["service_pid"], _RECORDED_PID)+ self.assertEqual(payload["pid"], _RECORDED_PID)+ self.assertEqual(payload["service_owner_pid"], _RECORDED_PID)self.assertNotIn("extra_service_pids", payload)def test_render_status_fast_path_skips_extra_process_scan_when_owner_is_missing(self):with tempfile.TemporaryDirectory() as tmpdir:status_path = Path(tmpdir) / "status.json"- runtime.write_json(status_path, {"state": "running", "service_pid": 12345})+ runtime.write_json(status_path, {"state": "running", "service_pid": _RECORDED_PID})with patch("vibe.runtime.paths.get_runtime_status_path", return_value=status_path):with patch("vibe.runtime.resolve_service_owner_pid", return_value=None):@@ -639,19 +644,19 @@ class RuntimeServiceLockTests(unittest.TestCase):def test_render_status_can_surface_extra_processes_when_owner_is_running(self):with tempfile.TemporaryDirectory() as tmpdir:status_path = Path(tmpdir) / "status.json"- runtime.write_json(status_path, {"state": "running", "service_pid": 12345})+ runtime.write_json(status_path, {"state": "running", "service_pid": _RECORDED_PID})with patch("vibe.runtime.paths.get_runtime_status_path", return_value=status_path):- with patch("vibe.runtime.resolve_service_owner_pid", return_value=12345):+ with patch("vibe.runtime.resolve_service_owner_pid", return_value=_RECORDED_PID):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"], "running")- self.assertEqual(payload["service_pid"], 12345)- self.assertEqual(payload["service_owner_pid"], 12345)+ self.assertEqual(payload["service_pid"], _RECORDED_PID)+ self.assertEqual(payload["service_owner_pid"], _RECORDED_PID)self.assertEqual(payload["extra_service_pids"], [22222])- self.assertEqual(payload["detail"], "pid=12345; extra_service_pids=22222")+ self.assertEqual(payload["detail"], f"pid={_RECORDED_PID}; extra_service_pids=22222")def test_render_status_surfaces_lockless_service_process(self):with tempfile.TemporaryDirectory() as tmpdir:@@ -686,9 +691,9 @@ class RuntimeServiceLockTests(unittest.TestCase):with patch("vibe.runtime.service_pid_recorded", side_effect=fake_service_pid_recorded):with patch("vibe.runtime.pid_alive", return_value=True):with patch("vibe.runtime.time.sleep", return_value=None):- self.assertTrue(runtime.wait_for_service_pid(67890, timeout=1.0))+ self.assertTrue(runtime.wait_for_service_pid(_SPAWNED_PID, timeout=1.0))- self.assertEqual(calls, [67890, 67890])+ self.assertEqual(calls, [_SPAWNED_PID, _SPAWNED_PID])def test_wait_for_service_pid_fails_only_when_worker_dies(self):with tempfile.TemporaryDirectory() as tmpdir:@@ -697,7 +702,7 @@ class RuntimeServiceLockTests(unittest.TestCase):with patch("vibe.runtime.paths.get_runtime_pid_path", return_value=pid_path):with patch("vibe.runtime.service_pid_recorded", return_value=False):with patch("vibe.runtime.pid_alive", return_value=False):- self.assertFalse(runtime.wait_for_service_pid(67890, timeout=1.0))+ self.assertFalse(runtime.wait_for_service_pid(_SPAWNED_PID, timeout=1.0))def test_service_instance_lock_blocks_second_holder(self):with tempfile.TemporaryDirectory() as tmpdir:@@ -1009,7 +1014,7 @@ class ServiceReadinessGateTests(unittest.TestCase):runtime_dir.mkdir(parents=True)lock_path = runtime_dir / "service.lock"pid_path = runtime_dir / "vibe.pid"- pid = 12345+ pid = _RECORDED_PIDlock_path.write_text(json.dumps({"pid": pid, "phase": phase}), encoding="utf-8")if already_recorded:pid_path.write_text(str(pid), encoding="utf-8")@@ -1050,7 +1055,7 @@ class ServiceReadinessGateTests(unittest.TestCase):def test_a_service_that_reported_itself_up_is_returned(self):for already_recorded in (True, False):with self.subTest(already_recorded=already_recorded):- self.assertEqual(self._start_with_phase("running", already_recorded=already_recorded), 12345)+ self.assertEqual(self._start_with_phase("running", already_recorded=already_recorded), _RECORDED_PID)def _start_against_a_lock_phase_lasting(self, seconds: float):"""Run `start_service()` with the phases on a clock this test drives.@@ -1064,7 +1069,7 @@ class ServiceReadinessGateTests(unittest.TestCase):def slow_resolve(**kwargs):clock["now"] += seconds- return 12345+ return _RECORDED_PIDdef record_timeout(pid, timeout=None):handed.append(timeout)@@ -1075,7 +1080,7 @@ class ServiceReadinessGateTests(unittest.TestCase):with patch("vibe.runtime.wait_for_service_ready", side_effect=record_timeout):pid = runtime.start_service()- self.assertEqual(pid, 12345)+ self.assertEqual(pid, _RECORDED_PID)self.assertEqual(len(handed), 1)return handed[0]diff --git a/tests/test_vibe_cli.py b/tests/test_vibe_cli.pyindex f050f2402..67ae1355c 100644--- a/tests/test_vibe_cli.py+++ b/tests/test_vibe_cli.py@@ -24,6 +24,7 @@ from vibe import internal_clientfrom vibe import remote_accessfrom vibe import upgradefrom storage.lock import MigrationLockTimeout+from tests.fake_pid_helpers import fake_piddef _make_fake_uv_tool(@@ -869,7 +870,7 @@ def test_doctor_surfaces_configuration_recovery_warnings(monkeypatch, tmp_path):def test_status_and_doctor_use_running_checkpoint_service_state(monkeypatch):- monkeypatch.setattr(runtime, "resolve_service_owner_pid", lambda **_kwargs: 1234)+ monkeypatch.setattr(runtime, "resolve_service_owner_pid", lambda **_kwargs: fake_pid())monkeypatch.setattr("core.show_git.show_git_checkpointing_active", lambda: False)monkeypatch.setattr("core.git_binary.resolve_git", lambda: object())diff --git a/tests/test_watches.py b/tests/test_watches.pyindex c836a448e..79c467e14 100644--- a/tests/test_watches.py+++ b/tests/test_watches.py@@ -51,6 +51,11 @@ from storage.background import (WATCH_HOOK_OUTCOME_WAITER_FAILURE,SQLiteBackgroundTaskStore,)+from tests.fake_pid_helpers import fake_pid++# Pids no process can hold: a supervisor that never ran, and a recorded watch worker.+_SUPERVISOR_PID = fake_pid(0)+_WORKER_PID = fake_pid(1)TEST_MARKER = "test-watch-worker"TEST_FINGERPRINT = fingerprint_process_marker(TEST_MARKER)@@ -112,7 +117,7 @@ class _FakeProcess:stdin: _FakeStdin | None = None,stderr: bytes = b"",) -> None:- self.pid = 1234+ self.pid = _SUPERVISOR_PIDself.returncode = 0self.stdin = stdin or _FakeStdin()self.stderr = stderr@@ -206,7 +211,7 @@ def _record_watch_pid(def _live_identity(*,- pid: int = 4321,+ pid: int = _WORKER_PID,create_time: float = 123.0,worker_fingerprint: str | None = TEST_FINGERPRINT,) -> ProcessIdentity:@@ -219,7 +224,7 @@ def _live_identity(def _persisted_identity(*,- pid: int = 4321,+ pid: int = _WORKER_PID,create_time: float = 123.0,worker_fingerprint: str = TEST_FINGERPRINT,) -> PersistedProcessIdentity:@@ -750,7 +755,7 @@ def test_sqlite_remove_watch_soft_deletes_watch_but_keeps_runtime(tmp_path: Path"watches": {watch.id: {"running": True,- "pid": 1234,+ "pid": _WORKER_PID,"started_at": "2026-05-15T00:00:00+00:00","updated_at": "2026-05-15T00:00:00+00:00",}@@ -779,7 +784,7 @@ def test_watch_runtime_store_uses_sqlite_when_path_is_default(tmp_path: Path, mo"watches": {"watch-1": {"running": True,- "pid": 1234,+ "pid": _WORKER_PID,"started_at": "2026-05-15T00:00:00+00:00","updated_at": "2026-05-15T00:00:01+00:00",}@@ -788,7 +793,7 @@ def test_watch_runtime_store_uses_sqlite_when_path_is_default(tmp_path: Path, mo)assert not (tmp_path / "runtime" / "watch_runtime.json").exists()- assert store.load()["watches"]["watch-1"]["pid"] == 1234+ assert store.load()["watches"]["watch-1"]["pid"] == _WORKER_PIDdef test_managed_watch_service_once_success_enqueues_hook_and_disables(tmp_path: Path) -> None:@@ -2652,8 +2657,8 @@ def test_managed_watch_service_start_reaps_stale_worker_for_deleted_watch() -> None:store = ManagedWatchStore(tmp_path / "watches.json")runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")- identity = _persisted_identity(pid=1234)- _record_watch_pid(runtime_store, "stale-watch", 1234, identity=identity)+ identity = _persisted_identity(pid=_WORKER_PID)+ _record_watch_pid(runtime_store, "stale-watch", _WORKER_PID, identity=identity)service = ManagedWatchService(controller=SimpleNamespace(),store=store,@@ -2661,7 +2666,7 @@ def test_managed_watch_service_start_reaps_stale_worker_for_deleted_watch(runtime_store=runtime_store,)terminated: list[int] = []- monkeypatch.setattr("core.watches.runtime.pid_alive", lambda pid: pid == 1234)+ monkeypatch.setattr("core.watches.runtime.pid_alive", lambda pid: pid == _WORKER_PID)monkeypatch.setattr("core.watches.inspect_process_identity", lambda pid: _live_identity(pid=pid))monkeypatch.setattr("core.watches.terminate_process_tree_by_pid",@@ -2676,7 +2681,7 @@ def test_managed_watch_service_start_reaps_stale_worker_for_deleted_watch(await service.stop()asyncio.run(_run())- assert terminated == [1234]+ assert terminated == [_WORKER_PID]@pytest.mark.parametrize(@@ -2698,7 +2703,7 @@ def test_managed_watch_service_start_reaps_matching_stale_worker_before_reconcilruntime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")watch = _add_recovery_watch(store, command=command, shell_command=shell_command)identity = _persisted_identity()- _record_watch_pid(runtime_store, watch.id, 4321, identity=identity)+ _record_watch_pid(runtime_store, watch.id, _WORKER_PID, identity=identity)service = ManagedWatchService(controller=SimpleNamespace(),store=store,@@ -2707,7 +2712,7 @@ def test_managed_watch_service_start_reaps_matching_stale_worker_before_reconcil)events: list[tuple[str, int | None]] = []- monkeypatch.setattr("core.watches.runtime.pid_alive", lambda pid: pid == 4321)+ monkeypatch.setattr("core.watches.runtime.pid_alive", lambda pid: pid == _WORKER_PID)monkeypatch.setattr("core.watches.inspect_process_identity",lambda pid: _live_identity(pid=pid),@@ -2731,7 +2736,7 @@ def test_managed_watch_service_start_reaps_matching_stale_worker_before_reconcilasyncio.run(_run())- assert events[0] == ("terminate", 4321)+ assert events[0] == ("terminate", _WORKER_PID)assert events[1:] and all(event == ("reconcile", None) for event in events[1:])@@ -2744,7 +2749,7 @@ def test_managed_watch_service_start_does_not_reap_reused_pid(command = [sys.executable, "wait.py"]watch = _add_recovery_watch(store, command=command)identity = _persisted_identity()- _record_watch_pid(runtime_store, watch.id, 4321, identity=identity)+ _record_watch_pid(runtime_store, watch.id, _WORKER_PID, identity=identity)service = ManagedWatchService(controller=SimpleNamespace(),store=store,@@ -2753,7 +2758,7 @@ def test_managed_watch_service_start_does_not_reap_reused_pid()reconciles = 0- monkeypatch.setattr("core.watches.runtime.pid_alive", lambda pid: pid == 4321)+ monkeypatch.setattr("core.watches.runtime.pid_alive", lambda pid: pid == _WORKER_PID)monkeypatch.setattr("core.watches.inspect_process_identity",lambda pid: _live_identity(pid=pid, create_time=456.0, worker_fingerprint=None),@@ -2800,7 +2805,7 @@ def test_blocked_watch_recheck_decides_by_marker_not_a_shifted_birth_time()identity = _persisted_identity()entry = {- "pid": 4321,+ "pid": _WORKER_PID,"process_identity": {"pid": identity.pid,"create_time": identity.create_time,@@ -2825,7 +2830,7 @@ def test_managed_watch_service_start_blocks_respawn_when_worker_marker_changed(command = [sys.executable, "wait.py"]watch = _add_recovery_watch(store, command=command)identity = _persisted_identity()- _record_watch_pid(runtime_store, watch.id, 4321, identity=identity)+ _record_watch_pid(runtime_store, watch.id, _WORKER_PID, identity=identity)service = ManagedWatchService(controller=SimpleNamespace(),store=store,@@ -2833,7 +2838,7 @@ def test_managed_watch_service_start_blocks_respawn_when_worker_marker_changed(runtime_store=runtime_store,)- monkeypatch.setattr("core.watches.runtime.pid_alive", lambda pid: pid == 4321)+ monkeypatch.setattr("core.watches.runtime.pid_alive", lambda pid: pid == _WORKER_PID)monkeypatch.setattr("core.watches.inspect_process_identity",lambda pid: _live_identity(@@ -2855,7 +2860,7 @@ def test_managed_watch_service_start_blocks_respawn_when_worker_marker_changed(asyncio.run(_run())assert watch.id in service._recovery_blocked_watch_ids- assert runtime_store.load()["watches"][watch.id]["pid"] == 4321+ assert runtime_store.load()["watches"][watch.id]["pid"] == _WORKER_PIDdef test_managed_watch_service_start_blocks_legacy_live_worker_without_identity(@@ -2865,7 +2870,7 @@ def test_managed_watch_service_start_blocks_legacy_live_worker_without_identity(store = ManagedWatchStore(tmp_path / "watches.json")runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")watch = _add_recovery_watch(store, command=[sys.executable, "wait.py"])- _record_watch_pid(runtime_store, watch.id, 4321)+ _record_watch_pid(runtime_store, watch.id, _WORKER_PID)service = ManagedWatchService(controller=SimpleNamespace(),store=store,@@ -2873,7 +2878,7 @@ def test_managed_watch_service_start_blocks_legacy_live_worker_without_identity(runtime_store=runtime_store,)- monkeypatch.setattr("core.watches.runtime.pid_alive", lambda pid: pid == 4321)+ monkeypatch.setattr("core.watches.runtime.pid_alive", lambda pid: pid == _WORKER_PID)monkeypatch.setattr("core.watches.inspect_process_identity",lambda _pid: _live_identity(),@@ -2891,7 +2896,7 @@ def test_managed_watch_service_start_blocks_legacy_live_worker_without_identity(asyncio.run(_run())assert watch.id in service._recovery_blocked_watch_ids- assert runtime_store.load()["watches"][watch.id]["pid"] == 4321+ assert runtime_store.load()["watches"][watch.id]["pid"] == _WORKER_PIDdef test_managed_watch_service_start_rejects_overflowing_process_identity(@@ -2906,11 +2911,11 @@ def test_managed_watch_service_start_rejects_overflowing_process_identity("watches": {watch.id: {"running": True,- "pid": 4321,+ "pid": _WORKER_PID,"started_at": "2026-05-15T00:00:00+00:00","updated_at": "2026-05-15T00:00:01+00:00","process_identity": {- "pid": 4321,+ "pid": _WORKER_PID,"create_time": 10**1000,"worker_fingerprint": TEST_FINGERPRINT,},@@ -2925,7 +2930,7 @@ def test_managed_watch_service_start_rejects_overflowing_process_identity(runtime_store=runtime_store,)- monkeypatch.setattr("core.watches.runtime.pid_alive", lambda pid: pid == 4321)+ monkeypatch.setattr("core.watches.runtime.pid_alive", lambda pid: pid == _WORKER_PID)monkeypatch.setattr("core.watches.inspect_process_identity",lambda pid: _live_identity(pid=pid),@@ -2952,7 +2957,7 @@ def test_managed_watch_service_start_ignores_dead_recorded_pid(store = ManagedWatchStore(tmp_path / "watches.json")runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")watch = _add_recovery_watch(store, command=[sys.executable, "wait.py"])- _record_watch_pid(runtime_store, watch.id, 4321)+ _record_watch_pid(runtime_store, watch.id, _WORKER_PID)service = ManagedWatchService(controller=SimpleNamespace(),store=store,@@ -2996,7 +3001,7 @@ def test_managed_watch_service_start_reaps_group_after_leader_exit(runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")watch = _add_recovery_watch(store, command=[sys.executable, "wait.py"])identity = _persisted_identity()- _record_watch_pid(runtime_store, watch.id, 4321, identity=identity)+ _record_watch_pid(runtime_store, watch.id, _WORKER_PID, identity=identity)service = ManagedWatchService(controller=SimpleNamespace(),store=store,@@ -3039,7 +3044,7 @@ def test_managed_watch_service_does_not_reap_unverified_group_after_leader_exit(store = ManagedWatchStore(tmp_path / "watches.json")runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")watch = _add_recovery_watch(store, command=[sys.executable, "wait.py"])- _record_watch_pid(runtime_store, watch.id, 4321)+ _record_watch_pid(runtime_store, watch.id, _WORKER_PID)service = ManagedWatchService(controller=SimpleNamespace(),store=store,@@ -3734,7 +3739,7 @@ def test_managed_watch_service_start_retries_unavailable_watch_list_before_reconstore = ManagedWatchStore(tmp_path / "watches.json")runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")watch = _add_recovery_watch(store, command=[sys.executable, "wait.py"])- _record_watch_pid(runtime_store, watch.id, 4321)+ _record_watch_pid(runtime_store, watch.id, _WORKER_PID)service = ManagedWatchService(controller=SimpleNamespace(),store=store,@@ -3793,7 +3798,7 @@ def test_managed_watch_service_start_does_not_reap_with_malformed_watch_store(original_store = ManagedWatchStore(watches_path)watch = _add_recovery_watch(original_store, command=[sys.executable, "wait.py"])runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")- _record_watch_pid(runtime_store, watch.id, 4321)+ _record_watch_pid(runtime_store, watch.id, _WORKER_PID)watches_path.write_text("{not-json", encoding="utf-8")with caplog.at_level("WARNING"):@@ -3832,27 +3837,27 @@ def test_managed_watch_service_start_preserves_worker_state_when_reap_fails(command = [sys.executable, "wait.py"]watch = _add_recovery_watch(store, command=command)identity = _persisted_identity()- _record_watch_pid(runtime_store, watch.id, 4321, identity=identity)+ _record_watch_pid(runtime_store, watch.id, _WORKER_PID, identity=identity)service = ManagedWatchService(controller=SimpleNamespace(),store=store,request_store=TaskExecutionStore(tmp_path / "task_requests"),runtime_store=runtime_store,)- monkeypatch.setattr("core.watches.runtime.pid_alive", lambda pid: pid == 4321)+ monkeypatch.setattr("core.watches.runtime.pid_alive", lambda pid: pid == _WORKER_PID)monkeypatch.setattr("core.watches.inspect_process_identity", lambda pid: _live_identity(pid=pid))monkeypatch.setattr("core.watches.terminate_process_tree_by_pid", lambda *_args, **_kwargs: False)async def _run() -> None:await _start_watch_service(service)assert service._active_tasks == {}- assert runtime_store.load()["watches"][watch.id]["pid"] == 4321+ assert runtime_store.load()["watches"][watch.id]["pid"] == _WORKER_PIDawait service.stop()asyncio.run(_run())assert watch.id in service._recovery_blocked_watch_ids- assert runtime_store.load()["watches"][watch.id]["pid"] == 4321+ assert runtime_store.load()["watches"][watch.id]["pid"] == _WORKER_PIDdef test_managed_watch_service_periodically_unblocks_after_stale_worker_exits(@@ -3864,7 +3869,7 @@ def test_managed_watch_service_periodically_unblocks_after_stale_worker_exits(command = [sys.executable, "wait.py"]watch = _add_recovery_watch(store, command=command)identity = _persisted_identity()- _record_watch_pid(runtime_store, watch.id, 4321, identity=identity)+ _record_watch_pid(runtime_store, watch.id, _WORKER_PID, identity=identity)service = ManagedWatchService(controller=SimpleNamespace(),store=store,