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(watches): reap stale watch workers left by a previous service instance (#1002)

qihan-bot4d7a4938b7ef
diff --git a/core/process_isolation.py b/core/process_isolation.py
index 0bcf546d5..fa067678f 100644
--- a/core/process_isolation.py
+++ b/core/process_isolation.py
@@ -3,13 +3,114 @@
from __future__ import annotations
import asyncio
+import hashlib
+import hmac
import logging
+import math
import os
+import secrets
import signal
import subprocess
+import time
+from dataclasses import dataclass
from typing import Any
+import psutil
+
KILL_SIGNAL = getattr(signal, "SIGKILL", signal.SIGTERM)
+PROCESS_IDENTITY_ENV = "AVIBE_PROCESS_IDENTITY"
+DEFAULT_PROCESS_TERMINATE_TIMEOUT_SECONDS = 3.0
+
+
+@dataclass(frozen=True)
+class ProcessIdentity:
+ pid: int
+ create_time: float
+ worker_fingerprint: str | None
+
+
+@dataclass(frozen=True)
+class PersistedProcessIdentity:
+ pid: int
+ create_time: float
+ worker_fingerprint: str
+
+
+def new_process_identity_marker() -> str:
+ """Return a high-entropy marker inherited by a managed process tree."""
+ return secrets.token_hex(32)
+
+
+def fingerprint_process_marker(marker: str) -> str:
+ return f"sha256:{hashlib.sha256(marker.encode('ascii')).hexdigest()}"
+
+
+def process_identity_subprocess_env(marker: str) -> dict[str, str]:
+ env = dict(os.environ)
+ env[PROCESS_IDENTITY_ENV] = marker
+ return env
+
+
+def capture_spawned_process_identity(
+ pid: int,
+ marker: str,
+) -> PersistedProcessIdentity | None:
+ if not isinstance(pid, int) or isinstance(pid, bool) or pid <= 0:
+ return None
+ try:
+ create_time = float(psutil.Process(pid).create_time())
+ except (psutil.Error, OSError, TypeError, ValueError, OverflowError):
+ return None
+ if not math.isfinite(create_time) or create_time <= 0:
+ return None
+ return PersistedProcessIdentity(
+ pid=pid,
+ create_time=create_time,
+ worker_fingerprint=fingerprint_process_marker(marker),
+ )
+
+
+def process_identity_matches(
+ expected: PersistedProcessIdentity,
+ live: ProcessIdentity,
+) -> bool:
+ return (
+ expected.pid == live.pid
+ and expected.create_time == live.create_time
+ and live.worker_fingerprint is not None
+ and hmac.compare_digest(
+ expected.worker_fingerprint,
+ live.worker_fingerprint,
+ )
+ )
+
+
+def _open_process_identity(pid: int) -> tuple[psutil.Process, ProcessIdentity]:
+ process = psutil.Process(pid)
+ create_time = float(process.create_time())
+ worker_fingerprint = None
+ try:
+ marker = process.environ().get(PROCESS_IDENTITY_ENV)
+ except (psutil.Error, OSError):
+ marker = None
+ if isinstance(marker, str) and marker:
+ worker_fingerprint = fingerprint_process_marker(marker)
+ return process, ProcessIdentity(
+ pid=pid,
+ create_time=create_time,
+ worker_fingerprint=worker_fingerprint,
+ )
+
+
+def inspect_process_identity(pid: int) -> ProcessIdentity | None:
+ """Return the birth identity and inherited marker for a live process."""
+ if not isinstance(pid, int) or isinstance(pid, bool) or pid <= 0:
+ return None
+ try:
+ _process, identity = _open_process_identity(pid)
+ except (psutil.Error, OSError, ValueError):
+ return None
+ return identity
def isolated_subprocess_kwargs() -> dict[str, Any]:
@@ -19,16 +120,22 @@ def isolated_subprocess_kwargs() -> dict[str, Any]:
return {"start_new_session": True}
-def _safe_signal_process_group(pid: int, sig: int, logger: logging.Logger, label: str) -> bool:
+def _safe_signal_known_process_group(
+ pgid: int,
+ pid: int,
+ sig: int,
+ logger: logging.Logger,
+ label: str,
+ *,
+ expected_identity: PersistedProcessIdentity | None = None,
+ require_leader: bool = True,
+) -> bool:
if os.name == "nt" or not hasattr(os, "getpgid") or not hasattr(os, "killpg"):
return False
try:
- pgid = os.getpgid(pid)
own_pgid = os.getpgrp()
- except ProcessLookupError:
- return True
except Exception:
- logger.debug("Failed to inspect process group for %s pid=%s", label, pid, exc_info=True)
+ logger.debug("Failed to inspect the service process group while signaling %s pid=%s", label, pid, exc_info=True)
return False
if pgid == own_pgid:
logger.error(
@@ -38,6 +145,40 @@ def _safe_signal_process_group(pid: int, sig: int, logger: logging.Logger, label
own_pgid,
)
return False
+ if expected_identity is not None:
+ if require_leader:
+ try:
+ _process, live_identity = _open_process_identity(expected_identity.pid)
+ live_pgid = os.getpgid(expected_identity.pid)
+ except (ProcessLookupError, psutil.NoSuchProcess):
+ logger.warning(
+ "Refusing to signal %s process group pgid=%s because its supervisor exited",
+ label,
+ pgid,
+ )
+ return False
+ except Exception:
+ logger.debug(
+ "Failed to revalidate %s process group pgid=%s before signaling",
+ label,
+ pgid,
+ exc_info=True,
+ )
+ return False
+ if live_pgid != pgid or not process_identity_matches(expected_identity, live_identity):
+ logger.warning(
+ "Refusing to signal %s process group pgid=%s because its supervisor identity changed",
+ label,
+ pgid,
+ )
+ return False
+ elif not process_group_matches_identity(pgid, expected_identity, logger, label):
+ logger.warning(
+ "Refusing to signal %s process group pgid=%s without a matching supervisor marker",
+ label,
+ pgid,
+ )
+ return False
try:
logger.info(
"Signaling %s process group pgid=%s pid=%s signal=%s service_pgid=%s",
@@ -56,6 +197,19 @@ def _safe_signal_process_group(pid: int, sig: int, logger: logging.Logger, label
return False
+def _safe_signal_process_group(pid: int, sig: int, logger: logging.Logger, label: str) -> bool:
+ if os.name == "nt" or not hasattr(os, "getpgid") or not hasattr(os, "killpg"):
+ return False
+ try:
+ pgid = os.getpgid(pid)
+ except ProcessLookupError:
+ return True
+ except Exception:
+ logger.debug("Failed to inspect process group for %s pid=%s", label, pid, exc_info=True)
+ return False
+ return _safe_signal_known_process_group(pgid, pid, sig, logger, label)
+
+
def signal_process_tree(process: Any, sig: int, logger: logging.Logger, label: str) -> None:
"""Signal a managed process group, falling back to the direct process."""
pid = getattr(process, "pid", None)
@@ -74,12 +228,348 @@ def signal_process_tree(process: Any, sig: int, logger: logging.Logger, label: s
return
+def _process_group_exists(pgid: int, logger: logging.Logger, label: str) -> bool:
+ if os.name == "nt" or not hasattr(os, "killpg"):
+ return False
+ try:
+ os.killpg(pgid, 0)
+ except ProcessLookupError:
+ return False
+ except PermissionError:
+ return True
+ except Exception:
+ logger.debug("Failed to inspect %s process group pgid=%s", label, pgid, exc_info=True)
+ return True
+ return True
+
+
+def process_group_exists(pgid: int, logger: logging.Logger, label: str) -> bool:
+ """Return whether an isolated POSIX process group still has members."""
+ if not isinstance(pgid, int) or isinstance(pgid, bool) or pgid <= 0:
+ return False
+ return _process_group_exists(pgid, logger, label)
+
+
+def process_group_identity_status(
+ pgid: int,
+ expected_identity: PersistedProcessIdentity,
+ logger: logging.Logger,
+ label: str,
+) -> str:
+ """Return match, mismatch, or unknown for a persisted process group."""
+ if (
+ os.name == "nt"
+ or not isinstance(pgid, int)
+ or isinstance(pgid, bool)
+ or pgid <= 0
+ or not isinstance(expected_identity, PersistedProcessIdentity)
+ ):
+ return "unknown"
+ saw_marker = False
+ saw_unverified_member = False
+ try:
+ processes = psutil.process_iter(["pid"])
+ for process in processes:
+ pid = process.info.get("pid")
+ if not isinstance(pid, int) or isinstance(pid, bool) or pid <= 0:
+ continue
+ try:
+ if os.getpgid(pid) != pgid:
+ continue
+ except (ProcessLookupError, PermissionError):
+ continue
+ except Exception:
+ logger.debug(
+ "Failed to inspect %s process group member pid=%s",
+ label,
+ pid,
+ exc_info=True,
+ )
+ continue
+ live_identity = inspect_process_identity(pid)
+ if (
+ live_identity is None
+ or live_identity.create_time < expected_identity.create_time
+ or live_identity.worker_fingerprint is None
+ ):
+ saw_unverified_member = True
+ continue
+ saw_marker = True
+ if hmac.compare_digest(
+ expected_identity.worker_fingerprint,
+ live_identity.worker_fingerprint,
+ ):
+ return "match"
+ except Exception:
+ logger.debug(
+ "Failed to enumerate %s process group pgid=%s",
+ label,
+ pgid,
+ exc_info=True,
+ )
+ return "mismatch" if saw_marker and not saw_unverified_member else "unknown"
+
+
+def process_group_matches_identity(
+ pgid: int,
+ expected_identity: PersistedProcessIdentity,
+ logger: logging.Logger,
+ label: str,
+) -> bool:
+ return (
+ process_group_identity_status(
+ pgid,
+ expected_identity,
+ logger,
+ label,
+ )
+ == "match"
+ )
+
+
+def _wait_for_process_group_exit(
+ pgid: int,
+ logger: logging.Logger,
+ label: str,
+ *,
+ timeout: float,
+) -> bool:
+ deadline = time.monotonic() + max(0.0, timeout)
+ while _process_group_exists(pgid, logger, label):
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ return False
+ time.sleep(min(0.1, remaining))
+ return True
+
+
+def terminate_process_group_by_pgid(
+ pgid: int,
+ logger: logging.Logger,
+ label: str,
+ *,
+ expected_identity: PersistedProcessIdentity,
+ terminate_timeout: float = DEFAULT_PROCESS_TERMINATE_TIMEOUT_SECONDS,
+) -> bool:
+ """Terminate a persisted isolated group after its original leader exited."""
+ if not isinstance(pgid, int) or isinstance(pgid, bool) or pgid <= 0:
+ return False
+ if os.name == "nt":
+ return False
+ try:
+ own_pgid = os.getpgrp()
+ except Exception:
+ logger.debug("Failed to inspect the service process group before recovering %s", label, exc_info=True)
+ return False
+ if pgid == own_pgid:
+ logger.error(
+ "Refusing to terminate %s process group because pgid=%s matches the avibe service",
+ label,
+ pgid,
+ )
+ return False
+ if not _process_group_exists(pgid, logger, label):
+ return True
+ if not _safe_signal_known_process_group(
+ pgid,
+ expected_identity.pid,
+ signal.SIGTERM,
+ logger,
+ label,
+ expected_identity=expected_identity,
+ require_leader=False,
+ ):
+ return False
+ if _wait_for_process_group_exit(pgid, logger, label, timeout=terminate_timeout):
+ return True
+
+ logger.warning("Escalating termination of %s process group pgid=%s", label, pgid)
+ if not _safe_signal_known_process_group(
+ pgid,
+ expected_identity.pid,
+ KILL_SIGNAL,
+ logger,
+ label,
+ expected_identity=expected_identity,
+ require_leader=False,
+ ):
+ return False
+ if _wait_for_process_group_exit(pgid, logger, label, timeout=terminate_timeout):
+ return True
+ logger.error("%s process group pgid=%s survived forced termination", label, pgid)
+ return False
+
+
+def _windows_process_tree(process: psutil.Process) -> list[psutil.Process]:
+ try:
+ children = process.children(recursive=True)
+ except psutil.NoSuchProcess:
+ return []
+ except psutil.Error:
+ children = []
+ return children + [process]
+
+
+def _terminate_windows_process_tree(
+ logger: logging.Logger,
+ label: str,
+ *,
+ expected_identity: PersistedProcessIdentity,
+ terminate_timeout: float,
+) -> bool:
+ control_signal = getattr(signal, "CTRL_BREAK_EVENT", None)
+ if control_signal is None:
+ logger.error("Refusing to terminate %s because Windows process-group signaling is unavailable", label)
+ return False
+
+ try:
+ process, live_identity = _open_process_identity(expected_identity.pid)
+ except psutil.NoSuchProcess:
+ return True
+ except (psutil.Error, OSError, ValueError):
+ logger.debug("Failed to revalidate Windows supervisor for %s", label, exc_info=True)
+ return False
+ if live_identity.create_time != expected_identity.create_time:
+ return True
+ if not process_identity_matches(expected_identity, live_identity):
+ logger.warning("Refusing to signal %s because its supervisor marker changed", label)
+ return False
+
+ victims = _windows_process_tree(process)
+ try:
+ process.send_signal(control_signal)
+ except psutil.NoSuchProcess:
+ return True
+ except (psutil.Error, OSError):
+ logger.debug("Failed to signal the Windows process group for %s", label, exc_info=True)
+ return False
+
+ _gone, alive = psutil.wait_procs(victims, timeout=terminate_timeout)
+ if not alive:
+ return True
+
+ logger.warning("Escalating termination of %s after graceful timeout", label)
+ for victim in reversed(alive):
+ try:
+ victim.terminate()
+ except psutil.NoSuchProcess:
+ continue
+ except psutil.Error:
+ logger.debug("Failed to terminate %s descendant pid=%s", label, victim.pid, exc_info=True)
+ _gone, alive = psutil.wait_procs(alive, timeout=terminate_timeout)
+ for victim in alive:
+ try:
+ victim.kill()
+ except psutil.NoSuchProcess:
+ continue
+ except psutil.Error:
+ logger.debug("Failed to kill %s descendant pid=%s", label, victim.pid, exc_info=True)
+ _gone, alive = psutil.wait_procs(alive, timeout=terminate_timeout)
+ if alive:
+ logger.error("%s process tree survived forced termination", label)
+ return False
+ return True
+
+
+def terminate_process_tree_by_pid(
+ pid: int,
+ logger: logging.Logger,
+ label: str,
+ *,
+ expected_identity: PersistedProcessIdentity,
+ terminate_timeout: float = DEFAULT_PROCESS_TERMINATE_TIMEOUT_SECONDS,
+) -> bool:
+ """Terminate an isolated process tree identified only by its root PID.
+
+ This is intended for recovering persisted children after their original
+ ``asyncio.subprocess.Process`` handle has been lost. Unlike
+ :func:`signal_process_tree`, it never falls back to a direct signal when a
+ POSIX target is in the service's own process group or its group cannot be
+ verified.
+ """
+ if not isinstance(pid, int) or isinstance(pid, bool) or pid <= 0:
+ return False
+ if pid == os.getpid():
+ logger.error("Refusing to terminate %s because pid=%s is the current process", label, pid)
+ return False
+ if not isinstance(expected_identity, PersistedProcessIdentity) or expected_identity.pid != pid:
+ logger.error("Refusing to terminate %s pid=%s without a matching inspected identity", label, pid)
+ return False
+
+ try:
+ process, live_identity = _open_process_identity(pid)
+ except psutil.NoSuchProcess:
+ return True
+ except (psutil.Error, OSError, ValueError):
+ logger.debug("Failed to inspect %s pid=%s before termination", label, pid, exc_info=True)
+ return False
+ if live_identity.create_time != expected_identity.create_time:
+ logger.warning("Refusing to terminate %s pid=%s because its process identity changed", label, pid)
+ return True
+ if not process_identity_matches(expected_identity, live_identity):
+ logger.warning("Refusing to terminate %s pid=%s because its worker marker changed", label, pid)
+ return False
+
+ if os.name == "nt":
+ return _terminate_windows_process_tree(
+ logger,
+ label,
+ expected_identity=expected_identity,
+ terminate_timeout=terminate_timeout,
+ )
+
+ try:
+ pgid = os.getpgid(pid)
+ except ProcessLookupError:
+ return True
+ except Exception:
+ logger.debug("Failed to inspect %s process group pid=%s", label, pid, exc_info=True)
+ return False
+ if pgid != pid:
+ logger.error(
+ "Refusing to terminate %s pid=%s because its pgid=%s does not identify an isolated worker group",
+ label,
+ pid,
+ pgid,
+ )
+ return False
+
+ if not _safe_signal_known_process_group(
+ pgid,
+ pid,
+ signal.SIGTERM,
+ logger,
+ label,
+ expected_identity=expected_identity,
+ require_leader=True,
+ ):
+ return False
+ if _wait_for_process_group_exit(pgid, logger, label, timeout=terminate_timeout):
+ return True
+
+ logger.warning("Escalating termination of %s process group pgid=%s", label, pgid)
+ if not _safe_signal_known_process_group(
+ pgid,
+ pid,
+ KILL_SIGNAL,
+ logger,
+ label,
+ expected_identity=expected_identity,
+ require_leader=True,
+ ):
+ return False
+ if _wait_for_process_group_exit(pgid, logger, label, timeout=terminate_timeout):
+ return True
+ logger.error("%s process group pgid=%s survived forced termination", label, pgid)
+ return False
+
+
async def terminate_process_tree(
process: Any,
logger: logging.Logger,
label: str,
*,
- terminate_timeout: float = 3.0,
+ terminate_timeout: float = DEFAULT_PROCESS_TERMINATE_TIMEOUT_SECONDS,
) -> None:
"""Terminate a managed subprocess without signaling the service group."""
if getattr(process, "returncode", None) is not None:
@@ -104,7 +594,7 @@ async def terminate_and_communicate(
logger: logging.Logger,
label: str,
*,
- terminate_timeout: float = 3.0,
+ terminate_timeout: float = DEFAULT_PROCESS_TERMINATE_TIMEOUT_SECONDS,
) -> tuple[bytes, bytes]:
"""Terminate a process tree and drain stdout/stderr."""
if getattr(process, "returncode", None) is None:
diff --git a/core/watch_worker.py b/core/watch_worker.py
new file mode 100644
index 000000000..b8c1d4a4c
--- /dev/null
+++ b/core/watch_worker.py
@@ -0,0 +1,328 @@
+"""Stable supervisor for one managed watch command."""
+
+from __future__ import annotations
+
+import ctypes
+import json
+import os
+import signal
+import subprocess
+import sys
+import threading
+import time
+from typing import Any, BinaryIO
+
+import psutil
+
+PROCESS_IDENTITY_ENV = "AVIBE_PROCESS_IDENTITY"
+WATCH_WORKER_PROTOCOL_VERSION = 1
+WATCH_WORKER_ERROR_PREFIX = "AVIBE_WATCH_WORKER_ERROR:"
+_MAX_SPEC_BYTES = 16 * 1024 * 1024
+
+
+class WatchWorkerProtocolError(ValueError):
+ def __init__(self, code: str):
+ super().__init__(code)
+ self.code = code
+
+
+def encode_watch_worker_spec(
+ *,
+ command: list[str],
+ shell_command: str | None,
+) -> bytes:
+ payload = {
+ "version": WATCH_WORKER_PROTOCOL_VERSION,
+ "command": command,
+ "shell_command": shell_command,
+ }
+ return json.dumps(payload, ensure_ascii=True, separators=(",", ":")).encode("ascii")
+
+
+def encode_watch_worker_error(code: str, detail: str | None = None) -> str:
+ payload = {"code": code}
+ if detail:
+ payload["detail"] = detail
+ return WATCH_WORKER_ERROR_PREFIX + json.dumps(
+ payload,
+ ensure_ascii=True,
+ separators=(",", ":"),
+ )
+
+
+def decode_watch_worker_error(stderr: str) -> tuple[str, str | None] | None:
+ if not stderr.startswith(WATCH_WORKER_ERROR_PREFIX):
+ return None
+ try:
+ payload = json.loads(stderr[len(WATCH_WORKER_ERROR_PREFIX) :].strip())
+ except (json.JSONDecodeError, UnicodeDecodeError):
+ return ("supervisorFailed", None)
+ if not isinstance(payload, dict) or not isinstance(payload.get("code"), str):
+ return ("supervisorFailed", None)
+ detail = payload.get("detail")
+ return payload["code"], detail if isinstance(detail, str) else None
+
+
+def _read_watch_worker_spec() -> tuple[list[str], str | None]:
+ payload = sys.stdin.buffer.read(_MAX_SPEC_BYTES + 1)
+ if len(payload) > _MAX_SPEC_BYTES:
+ raise WatchWorkerProtocolError("specTooLarge")
+ try:
+ decoded = payload.decode("utf-8")
+ except UnicodeDecodeError as exc:
+ raise WatchWorkerProtocolError("invalidEncoding") from exc
+ try:
+ parsed = json.loads(decoded)
+ except json.JSONDecodeError as exc:
+ raise WatchWorkerProtocolError("invalidJson") from exc
+ if not isinstance(parsed, dict) or parsed.get("version") != WATCH_WORKER_PROTOCOL_VERSION:
+ raise WatchWorkerProtocolError("unsupportedVersion")
+
+ command = parsed.get("command")
+ shell_command = parsed.get("shell_command")
+ if (
+ not isinstance(command, list)
+ or any(not isinstance(part, str) for part in command)
+ or not isinstance(shell_command, (str, type(None)))
+ or bool(command) == bool(shell_command)
+ or (command and not command[0])
+ or (isinstance(shell_command, str) and not shell_command.strip())
+ ):
+ raise WatchWorkerProtocolError("invalidCommand")
+ return command, shell_command
+
+
+def _install_windows_kill_on_close_job() -> Any:
+ if os.name != "nt":
+ return None
+
+ from ctypes import wintypes
+
+ class JobObjectBasicLimitInformation(ctypes.Structure):
+ _fields_ = [
+ ("PerProcessUserTimeLimit", ctypes.c_longlong),
+ ("PerJobUserTimeLimit", ctypes.c_longlong),
+ ("LimitFlags", wintypes.DWORD),
+ ("MinimumWorkingSetSize", ctypes.c_size_t),
+ ("MaximumWorkingSetSize", ctypes.c_size_t),
+ ("ActiveProcessLimit", wintypes.DWORD),
+ ("Affinity", ctypes.c_size_t),
+ ("PriorityClass", wintypes.DWORD),
+ ("SchedulingClass", wintypes.DWORD),
+ ]
+
+ class IoCounters(ctypes.Structure):
+ _fields_ = [
+ ("ReadOperationCount", ctypes.c_ulonglong),
+ ("WriteOperationCount", ctypes.c_ulonglong),
+ ("OtherOperationCount", ctypes.c_ulonglong),
+ ("ReadTransferCount", ctypes.c_ulonglong),
+ ("WriteTransferCount", ctypes.c_ulonglong),
+ ("OtherTransferCount", ctypes.c_ulonglong),
+ ]
+
+ class JobObjectExtendedLimitInformation(ctypes.Structure):
+ _fields_ = [
+ ("BasicLimitInformation", JobObjectBasicLimitInformation),
+ ("IoInfo", IoCounters),
+ ("ProcessMemoryLimit", ctypes.c_size_t),
+ ("JobMemoryLimit", ctypes.c_size_t),
+ ("PeakProcessMemoryUsed", ctypes.c_size_t),
+ ("PeakJobMemoryUsed", ctypes.c_size_t),
+ ]
+
+ kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
+ kernel32.CreateJobObjectW.argtypes = [ctypes.c_void_p, wintypes.LPCWSTR]
+ kernel32.CreateJobObjectW.restype = wintypes.HANDLE
+ kernel32.SetInformationJobObject.argtypes = [
+ wintypes.HANDLE,
+ ctypes.c_int,
+ ctypes.c_void_p,
+ wintypes.DWORD,
+ ]
+ kernel32.SetInformationJobObject.restype = wintypes.BOOL
+ kernel32.AssignProcessToJobObject.argtypes = [wintypes.HANDLE, wintypes.HANDLE]
+ kernel32.AssignProcessToJobObject.restype = wintypes.BOOL
+ kernel32.GetCurrentProcess.restype = wintypes.HANDLE
+ kernel32.CloseHandle.argtypes = [wintypes.HANDLE]
+ kernel32.CloseHandle.restype = wintypes.BOOL
+
+ job = kernel32.CreateJobObjectW(None, None)
+ if not job:
+ raise ctypes.WinError(ctypes.get_last_error())
+
+ information = JobObjectExtendedLimitInformation()
+ information.BasicLimitInformation.LimitFlags = 0x00002000
+ if not kernel32.SetInformationJobObject(
+ job,
+ 9,
+ ctypes.byref(information),
+ ctypes.sizeof(information),
+ ):
+ error = ctypes.get_last_error()
+ kernel32.CloseHandle(job)
+ raise ctypes.WinError(error)
+ if not kernel32.AssignProcessToJobObject(job, kernel32.GetCurrentProcess()):
+ error = ctypes.get_last_error()
+ kernel32.CloseHandle(job)
+ raise ctypes.WinError(error)
+ return job
+
+
+def _forward_stream(source: BinaryIO, target: BinaryIO) -> None:
+ while True:
+ chunk = source.read(64 * 1024)
+ if not chunk:
+ return
+ target.write(chunk)
+ target.flush()
+
+
+def _handle_posix_termination(_signal_number: int, _frame: Any) -> None:
+ # The signal is delivered to the entire process group. The command should
+ # decide whether to exit; the supervisor must remain for forced escalation.
+ return None
+
+
+def _install_posix_supervisor_signal_handlers() -> None:
+ if os.name != "nt":
+ signal.signal(signal.SIGTERM, _handle_posix_termination)
+
+
+def _posix_process_group_has_other_members(identity_anchor_pid: int | None = None) -> bool:
+ if os.name == "nt":
+ return False
+ own_pid = os.getpid()
+ try:
+ own_pgid = os.getpgrp()
+ processes = psutil.process_iter(["pid"])
+ for process in processes:
+ pid = process.info.get("pid")
+ if (
+ not isinstance(pid, int)
+ or isinstance(pid, bool)
+ or pid <= 0
+ or pid == own_pid
+ or pid == identity_anchor_pid
+ ):
+ continue
+ try:
+ if os.getpgid(pid) == own_pgid:
+ return True
+ except (ProcessLookupError, PermissionError, psutil.Error):
+ continue
+ except (OSError, psutil.Error):
+ # Fail closed: retaining the supervisor is safer than orphaning an
+ # unverified descendant and clearing its persisted recovery identity.
+ return True
+ return False
+
+
+def _wait_for_posix_process_group_exit(identity_anchor_pid: int | None = None) -> None:
+ while _posix_process_group_has_other_members(identity_anchor_pid):
+ time.sleep(0.1)
+
+
+def _run_posix_identity_anchor() -> int:
+ signal.signal(signal.SIGTERM, _handle_posix_termination)
+ while True:
+ signal.pause()
+
+
+def _start_posix_identity_anchor() -> subprocess.Popen[bytes] | None:
+ marker = os.environ.get(PROCESS_IDENTITY_ENV)
+ if os.name == "nt" or not marker:
+ return None
+ return subprocess.Popen(
+ [sys.executable, os.path.abspath(__file__), "--identity-anchor"],
+ env={PROCESS_IDENTITY_ENV: marker},
+ stdin=subprocess.DEVNULL,
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL,
+ )
+
+
+def _stop_posix_identity_anchor(anchor: subprocess.Popen[bytes] | None) -> None:
+ if anchor is None or anchor.poll() is not None:
+ return
+ anchor.kill()
+ anchor.wait()
+
+
+def _run_watch_worker() -> int:
+ _install_posix_supervisor_signal_handlers()
+ # The handle must stay open for the supervisor lifetime so Windows keeps
+ # every descendant in the kill-on-close job.
+ _job_handle = _install_windows_kill_on_close_job()
+ command, shell_command = _read_watch_worker_spec()
+ child_env = dict(os.environ)
+ child_env.pop(PROCESS_IDENTITY_ENV, None)
+ identity_anchor = _start_posix_identity_anchor()
+
+ try:
+ popen_args: Any = shell_command if shell_command is not None else command
+ process = subprocess.Popen(
+ popen_args,
+ shell=shell_command is not None,
+ env=child_env,
+ stdin=subprocess.DEVNULL,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ )
+ if process.stdout is None or process.stderr is None:
+ raise RuntimeError("watch worker output pipes are unavailable")
+
+ stdout_thread = threading.Thread(
+ target=_forward_stream,
+ args=(process.stdout, sys.stdout.buffer),
+ daemon=False,
+ )
+ stderr_thread = threading.Thread(
+ target=_forward_stream,
+ args=(process.stderr, sys.stderr.buffer),
+ daemon=False,
+ )
+ stdout_thread.start()
+ stderr_thread.start()
+ return_code = process.wait()
+ stdout_thread.join()
+ stderr_thread.join()
+ _wait_for_posix_process_group_exit(
+ identity_anchor.pid if identity_anchor is not None else None
+ )
+ return return_code
+ finally:
+ _stop_posix_identity_anchor(identity_anchor)
+
+
+def main() -> int:
+ if os.name != "nt" and sys.argv[1:] == ["--identity-anchor"]:
+ return _run_posix_identity_anchor()
+ try:
+ return_code = _run_watch_worker()
+ except WatchWorkerProtocolError as exc:
+ print(encode_watch_worker_error(exc.code), file=sys.stderr, flush=True)
+ return 1
+ except Exception as exc:
+ print(
+ encode_watch_worker_error("supervisorFailed", str(exc)),
+ file=sys.stderr,
+ flush=True,
+ )
+ return 1
+
+ if os.name == "nt":
+ return return_code
+ if os.name != "nt" and return_code < 0:
+ signal_number = -return_code
+ if signal_number == signal.SIGTERM:
+ signal.signal(signal.SIGTERM, signal.SIG_DFL)
+ os.kill(os.getpid(), signal_number)
+ return 128 + signal_number
+ if 0 <= return_code <= 255:
+ return return_code
+ return 1
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/core/watches.py b/core/watches.py
index 97aa32953..ca1f16ae2 100644
--- a/core/watches.py
+++ b/core/watches.py
@@ -5,6 +5,9 @@ from __future__ import annotations
import asyncio
import json
import logging
+import math
+import os
+import sys
import tempfile
from dataclasses import asdict, dataclass, field
from datetime import datetime, timezone
@@ -13,16 +16,33 @@ from typing import Any, Optional
from uuid import uuid4
from config import paths
-from core.process_isolation import isolated_subprocess_kwargs, terminate_and_communicate
+from core import watch_worker
+from core.process_isolation import (
+ DEFAULT_PROCESS_TERMINATE_TIMEOUT_SECONDS,
+ PersistedProcessIdentity,
+ capture_spawned_process_identity,
+ inspect_process_identity,
+ isolated_subprocess_kwargs,
+ new_process_identity_marker,
+ process_group_exists,
+ process_group_identity_status,
+ process_identity_matches,
+ process_identity_subprocess_env,
+ terminate_and_communicate,
+ terminate_process_group_by_pgid,
+ terminate_process_tree_by_pid,
+)
from core.scheduled_tasks import TaskExecutionStore
from storage.background import SQLiteBackgroundTaskStore
from vibe import runtime
+from vibe.i18n import t as i18n_t
logger = logging.getLogger(__name__)
DEFAULT_RETRY_EXIT_CODE = 75
WATCH_RECONCILE_INTERVAL_SECONDS = 2.0
WATCH_STORE_RECONCILE_FUSE_FAILURES = 3
+WATCH_RECOVERY_ENTRY_TIMEOUT_SECONDS = 2 * DEFAULT_PROCESS_TERMINATE_TIMEOUT_SECONDS
def _utc_now_iso() -> str:
@@ -43,6 +63,67 @@ def _payload_float(payload: dict[str, Any], key: str, default: float) -> float:
return float(payload[key])
+def _serialize_process_identity(identity: PersistedProcessIdentity) -> dict[str, Any]:
+ return {
+ "pid": identity.pid,
+ "create_time": identity.create_time,
+ "worker_fingerprint": identity.worker_fingerprint,
+ }
+
+
+def _valid_worker_fingerprint(value: Any) -> bool:
+ if not isinstance(value, str) or not value.startswith("sha256:") or len(value) != 71:
+ return False
+ return all(char in "0123456789abcdef" for char in value[7:])
+
+
+def _process_identity_from_runtime_entry(
+ entry: dict[str, Any],
+ pid: int,
+) -> PersistedProcessIdentity | None:
+ payload = entry.get("process_identity")
+ if not isinstance(payload, dict):
+ return None
+ identity_pid = payload.get("pid")
+ create_time = payload.get("create_time")
+ worker_fingerprint = payload.get("worker_fingerprint")
+ try:
+ normalized_create_time = float(create_time)
+ except (TypeError, ValueError, OverflowError):
+ return None
+ if (
+ not isinstance(identity_pid, int)
+ or isinstance(identity_pid, bool)
+ or identity_pid != pid
+ or not isinstance(create_time, (int, float))
+ or isinstance(create_time, bool)
+ or not math.isfinite(normalized_create_time)
+ or normalized_create_time <= 0
+ or not _valid_worker_fingerprint(worker_fingerprint)
+ ):
+ return None
+ return PersistedProcessIdentity(
+ pid=identity_pid,
+ create_time=normalized_create_time,
+ worker_fingerprint=worker_fingerprint,
+ )
+
+
+def _entry_updated_timestamp(entry: dict[str, Any]) -> float | None:
+ updated_at = entry.get("updated_at")
+ if not isinstance(updated_at, str) or not updated_at:
+ return None
+ try:
+ return datetime.fromisoformat(updated_at).timestamp()
+ except ValueError:
+ return None
+
+
+def _legacy_pid_was_reused(entry: dict[str, Any], create_time: float) -> bool:
+ updated_timestamp = _entry_updated_timestamp(entry)
+ return updated_timestamp is not None and create_time > updated_timestamp
+
+
@dataclass
class ManagedWatch:
id: str
@@ -192,6 +273,41 @@ class ManagedWatchStore:
def list_watches(self) -> list[ManagedWatch]:
return sorted(self._watches.values(), key=lambda item: (item.created_at, item.id))
+ def list_watches_for_recovery(self) -> list[ManagedWatch]:
+ """Return a strict, current snapshot suitable for process recovery."""
+ if self._sqlite is not None:
+ raw_watches = self._sqlite.list_watches()
+ elif not self.path.exists():
+ raw_watches = []
+ else:
+ payload = json.loads(self.path.read_text(encoding="utf-8"))
+ if not isinstance(payload, dict) or not isinstance(payload.get("watches"), list):
+ raise ValueError("managed watch store must contain a watches list")
+ raw_watches = payload["watches"]
+
+ watches: list[ManagedWatch] = []
+ seen_ids: set[str] = set()
+ for item in raw_watches:
+ if not isinstance(item, dict):
+ raise ValueError("managed watch store contains an invalid watch entry")
+ watch_id = item.get("id")
+ if not isinstance(watch_id, str) or not watch_id or watch_id in seen_ids:
+ raise ValueError("managed watch store contains a missing or duplicate watch id")
+ command = item.get("command")
+ if command is not None and (
+ not isinstance(command, list)
+ or any(not isinstance(part, str) for part in command)
+ or (command and not command[0])
+ ):
+ raise ValueError(f"managed watch {watch_id} contains an invalid command")
+ shell_command = item.get("shell_command")
+ if shell_command is not None and not isinstance(shell_command, str):
+ raise ValueError(f"managed watch {watch_id} contains an invalid shell command")
+ watch = ManagedWatch.from_dict(item)
+ watches.append(watch)
+ seen_ids.add(watch.id)
+ return sorted(watches, key=lambda item: (item.created_at, item.id))
+
def get_watch(self, watch_id: str) -> Optional[ManagedWatch]:
return self._watches.get(watch_id)
@@ -387,14 +503,31 @@ class WatchRuntimeStateStore:
def load(self) -> dict[str, Any]:
if self._sqlite is not None:
return self._sqlite.load_watch_runtime()
- if not self.path.exists():
- return {"watches": {}}
try:
- payload = json.loads(self.path.read_text(encoding="utf-8"))
+ return self.load_for_recovery()
except Exception:
return {"watches": {}}
+
+ def load_for_recovery(self) -> dict[str, Any]:
+ """Load and validate state used to identify workers from a prior service."""
+ if self._sqlite is not None:
+ payload = self._sqlite.load_watch_runtime()
+ elif not self.path.exists():
+ payload = {"watches": {}}
+ else:
+ payload = json.loads(self.path.read_text(encoding="utf-8"))
if not isinstance(payload, dict):
- return {"watches": {}}
+ raise ValueError("watch runtime state must be a JSON object")
+ watches = payload.get("watches")
+ if not isinstance(watches, dict):
+ raise ValueError("watch runtime state must contain a watches object")
+ if any(
+ not isinstance(watch_id, str)
+ or not isinstance(entry, dict)
+ or not isinstance(entry.get("running"), bool)
+ for watch_id, entry in watches.items()
+ ):
+ raise ValueError("watch runtime state contains an invalid watch entry")
return payload
@@ -419,17 +552,47 @@ class ManagedWatchService:
self.request_store = request_store or TaskExecutionStore()
self.runtime_store = runtime_store or WatchRuntimeStateStore()
self._running = False
+ self._startup_task: Optional[asyncio.Task] = None
self._reconcile_task: Optional[asyncio.Task] = None
self._active_tasks: dict[str, asyncio.Task] = {}
self._active_pids: dict[str, int] = {}
+ self._active_process_identities: dict[str, PersistedProcessIdentity] = {}
self._watch_started_at: dict[str, str] = {}
self._fused_watch_ids: set[str] = set()
+ self._recovery_blocked_watch_ids: set[str] = set()
+ self._unreaped_runtime_entries: dict[str, dict[str, Any]] = {}
self._store_error_fused = False
self._store_reconcile_failures = 0
+ self._recovery_pending = True
self._requires_service_lease = runtime.service_instance_lock_attached_to_process()
self._reconcile_dirty = True
self._runtime_state_dirty = True
+ def _t(self, key: str, **kwargs: Any) -> str:
+ controller_translator = getattr(self.controller, "_t", None)
+ if callable(controller_translator):
+ return controller_translator(key, **kwargs)
+ language = getattr(getattr(self.controller, "config", None), "language", "en")
+ return i18n_t(key, language, **kwargs)
+
+ def _localize_watch_worker_error(self, stderr: str) -> str:
+ error = watch_worker.decode_watch_worker_error(stderr)
+ if error is None:
+ return stderr
+ code, detail = error
+ protocol_error_keys = {
+ "specTooLarge": "harness.watch.protocolErrors.specTooLarge",
+ "invalidEncoding": "harness.watch.protocolErrors.invalidEncoding",
+ "invalidJson": "harness.watch.protocolErrors.invalidJson",
+ "unsupportedVersion": "harness.watch.protocolErrors.unsupportedVersion",
+ "invalidCommand": "harness.watch.protocolErrors.invalidCommand",
+ }
+ if code in protocol_error_keys:
+ detail = self._t(protocol_error_keys[code])
+ elif not detail:
+ detail = self._t("harness.watch.unknownSupervisorFailure")
+ return self._t("harness.watch.supervisorFailed", detail=detail)
+
def active_process_pids(self) -> set[int]:
"""Return active waiter process roots owned by managed watches."""
return {pid for pid in self._active_pids.values() if isinstance(pid, int) and pid > 0}
@@ -438,18 +601,261 @@ class ManagedWatchService:
if self._running:
return
self._running = True
- self._reconcile_task = asyncio.create_task(self._watch_store())
+ self._startup_task = asyncio.create_task(self._start_after_recovery())
+
+ async def _start_after_recovery(self) -> None:
try:
- if self.reconcile_watches():
- self._runtime_state_dirty = True
- self._write_runtime_state()
- self._reconcile_dirty = False
- except Exception as exc:
- self._reconcile_dirty = True
- self._handle_reconcile_store_error(exc)
+ recovered = await asyncio.to_thread(self._reap_stale_workers)
+ except Exception:
+ recovered = False
+ logger.exception("Unexpected error during stale watch worker recovery")
+ try:
+ if not self._running or not self._owns_service_instance():
+ return
+ self._recovery_pending = not recovered
+ if recovered:
+ try:
+ if self.reconcile_watches():
+ self._runtime_state_dirty = True
+ self._write_runtime_state()
+ self._reconcile_dirty = False
+ except Exception as exc:
+ self._reconcile_dirty = True
+ self._handle_reconcile_store_error(exc)
+ if self._running and self._owns_service_instance():
+ self._reconcile_task = asyncio.create_task(self._watch_store())
+ finally:
+ if self._startup_task is asyncio.current_task():
+ self._startup_task = None
+
+ def _reap_stale_workers(self) -> bool:
+ try:
+ runtime_state = self.runtime_store.load_for_recovery()
+ except Exception:
+ logger.warning(
+ "Unable to read prior watch runtime state; deferring watch reconciliation",
+ exc_info=True,
+ )
+ return False
+
+ if not isinstance(runtime_state, dict):
+ logger.warning("Prior watch runtime state is malformed; deferring watch reconciliation")
+ return False
+ runtime_watches = runtime_state.get("watches")
+ if not isinstance(runtime_watches, dict) or any(
+ not isinstance(watch_id, str)
+ or not isinstance(entry, dict)
+ or not isinstance(entry.get("running"), bool)
+ for watch_id, entry in runtime_watches.items()
+ ):
+ logger.warning("Prior watch runtime state is malformed; deferring watch reconciliation")
+ return False
+ if not runtime_watches:
+ return True
+
+ try:
+ watches = self.store.list_watches_for_recovery()
+ if not isinstance(watches, list) or any(not isinstance(watch, ManagedWatch) for watch in watches):
+ raise ValueError("managed watch store returned an invalid watch list")
+ except Exception:
+ logger.warning(
+ "Unable to read managed watch definitions; deferring watch reconciliation",
+ exc_info=True,
+ )
+ return False
+ watch_ids = {watch.id for watch in watches}
+
+ for watch_id, entry in runtime_watches.items():
+ if not entry.get("running"):
+ continue
+ pid = entry.get("pid")
+ if not isinstance(pid, int) or isinstance(pid, bool) or pid <= 0 or pid == os.getpid():
+ continue
+ expected_identity = _process_identity_from_runtime_entry(entry, pid)
+ try:
+ pid_is_alive = runtime.pid_alive(pid)
+ group_is_alive = process_group_exists(pid, logger, f"stale watch {watch_id}")
+ if not pid_is_alive:
+ if not group_is_alive:
+ continue
+ if expected_identity is None:
+ logger.warning(
+ "Unable to verify historical identity for stale watch process group "
+ "pgid=%s watch_id=%s; leaving it untouched",
+ pid,
+ watch_id,
+ )
+ self._block_watch_after_failed_recovery(watch_id, entry)
+ continue
+ logger.warning(
+ "Reaping stale watch process group pgid=%s watch_id=%s after its leader exited",
+ pid,
+ watch_id,
+ )
+ if not terminate_process_group_by_pgid(
+ pid,
+ logger,
+ f"stale watch {watch_id}",
+ expected_identity=expected_identity,
+ ):
+ self._block_watch_after_failed_recovery(watch_id, entry)
+ continue
+ except Exception:
+ logger.warning(
+ "Unable to inspect stale watch worker pid=%s watch_id=%s; leaving it untouched",
+ pid,
+ watch_id,
+ exc_info=True,
+ )
+ self._block_watch_after_failed_recovery(watch_id, entry)
+ continue
+ if expected_identity is None:
+ live_identity = inspect_process_identity(pid)
+ if live_identity is not None and _legacy_pid_was_reused(
+ entry,
+ live_identity.create_time,
+ ):
+ logger.info(
+ "Legacy stale watch worker pid=%s watch_id=%s no longer exists; "
+ "the pid belongs to a newer process",
+ pid,
+ watch_id,
+ )
+ continue
+ logger.warning(
+ "Unable to verify historical identity for stale watch worker pid=%s watch_id=%s; "
+ "leaving it untouched",
+ pid,
+ watch_id,
+ )
+ self._block_watch_after_failed_recovery(watch_id, entry)
+ continue
+ try:
+ live_identity = inspect_process_identity(pid)
+ except Exception:
+ live_identity = None
+ logger.warning(
+ "Unable to inspect stale watch worker identity pid=%s watch_id=%s; leaving it untouched",
+ pid,
+ watch_id,
+ exc_info=True,
+ )
+ if live_identity is None:
+ logger.warning(
+ "Unable to verify stale watch worker identity pid=%s watch_id=%s; leaving it untouched",
+ pid,
+ watch_id,
+ )
+ self._block_watch_after_failed_recovery(watch_id, entry)
+ continue
+ if live_identity.create_time != expected_identity.create_time:
+ logger.info(
+ "Recorded stale watch worker pid=%s watch_id=%s no longer exists; "
+ "the pid belongs to a newer process",
+ pid,
+ watch_id,
+ )
+ continue
+ if not process_identity_matches(expected_identity, live_identity):
+ logger.warning(
+ "Refusing to reap stale watch worker pid=%s watch_id=%s because its marker changed",
+ pid,
+ watch_id,
+ )
+ self._block_watch_after_failed_recovery(watch_id, entry)
+ continue
+
+ watch_label = f"stale watch {watch_id}"
+ if watch_id not in watch_ids:
+ watch_label += " (deleted definition)"
+ logger.warning("Reaping stale watch worker pid=%s watch_id=%s", pid, watch_id)
+ try:
+ terminated = terminate_process_tree_by_pid(
+ pid,
+ logger,
+ watch_label,
+ expected_identity=expected_identity,
+ )
+ except Exception:
+ terminated = False
+ logger.exception("Unexpected error reaping stale watch worker pid=%s watch_id=%s", pid, watch_id)
+ if not terminated:
+ logger.error("Failed to reap stale watch worker pid=%s watch_id=%s", pid, watch_id)
+ self._block_watch_after_failed_recovery(watch_id, entry)
+ return True
+
+ def _block_watch_after_failed_recovery(self, watch_id: str, entry: dict[str, Any]) -> None:
+ self._recovery_blocked_watch_ids.add(watch_id)
+ self._unreaped_runtime_entries[watch_id] = dict(entry)
+ self._runtime_state_dirty = True
+
+ def _recheck_recovery_blocked_watches(self) -> bool:
+ unblocked = False
+ for watch_id in list(self._recovery_blocked_watch_ids):
+ entry = self._unreaped_runtime_entries.get(watch_id)
+ if not isinstance(entry, dict):
+ continue
+ pid = entry.get("pid")
+ if not isinstance(pid, int) or isinstance(pid, bool) or pid <= 0:
+ continue
+ try:
+ if not runtime.pid_alive(pid):
+ label = f"blocked stale watch {watch_id}"
+ if not process_group_exists(pid, logger, label):
+ worker_is_gone = True
+ else:
+ expected_identity = _process_identity_from_runtime_entry(entry, pid)
+ if expected_identity is None:
+ continue
+ group_status = process_group_identity_status(
+ pid,
+ expected_identity,
+ logger,
+ label,
+ )
+ if group_status != "mismatch":
+ continue
+ worker_is_gone = True
+ else:
+ live_identity = inspect_process_identity(pid)
+ if live_identity is None:
+ continue
+ expected_identity = _process_identity_from_runtime_entry(entry, pid)
+ if expected_identity is None:
+ worker_is_gone = _legacy_pid_was_reused(
+ entry,
+ live_identity.create_time,
+ )
+ else:
+ worker_is_gone = (
+ live_identity.create_time
+ != expected_identity.create_time
+ )
+ except Exception:
+ logger.debug(
+ "Failed to recheck blocked stale watch pid=%s watch_id=%s",
+ pid,
+ watch_id,
+ exc_info=True,
+ )
+ continue
+ if not worker_is_gone:
+ continue
+ logger.info(
+ "Unblocking recovered watch_id=%s after its prior worker exited",
+ watch_id,
+ )
+ self._recovery_blocked_watch_ids.discard(watch_id)
+ self._unreaped_runtime_entries.pop(watch_id, None)
+ unblocked = True
+ return unblocked
async def stop(self) -> None:
self._begin_stop()
+ startup_task = self._startup_task
+ if startup_task and startup_task is not asyncio.current_task():
+ await startup_task
+ self._startup_task = None
if self._reconcile_task:
self._reconcile_task.cancel()
try:
@@ -461,6 +867,7 @@ class ManagedWatchService:
await asyncio.gather(*self._active_tasks.values(), return_exceptions=True)
self._active_tasks.clear()
self._active_pids.clear()
+ self._active_process_identities.clear()
self._watch_started_at.clear()
self._runtime_state_dirty = True
self._write_runtime_state()
@@ -469,10 +876,29 @@ class ManagedWatchService:
while self._running:
if not self._owns_service_instance():
return
+ if self._recovery_pending:
+ try:
+ recovered = await asyncio.to_thread(self._reap_stale_workers)
+ except asyncio.CancelledError:
+ raise
+ except Exception:
+ recovered = False
+ logger.exception("Unexpected error retrying stale watch worker recovery")
+ if not recovered:
+ await asyncio.sleep(WATCH_RECONCILE_INTERVAL_SECONDS)
+ continue
+ self._recovery_pending = False
+ self._reconcile_dirty = True
+ self._runtime_state_dirty = True
if self._store_error_fused:
await asyncio.sleep(WATCH_RECONCILE_INTERVAL_SECONDS)
continue
try:
+ if self._recovery_blocked_watch_ids and await asyncio.to_thread(
+ self._recheck_recovery_blocked_watches
+ ):
+ self._reconcile_dirty = True
+ self._runtime_state_dirty = True
should_reconcile = self.store.maybe_reload() or self._reconcile_dirty
if should_reconcile:
if self.reconcile_watches():
@@ -497,7 +923,12 @@ class ManagedWatchService:
desired_ids = {watch.id for watch in watches if watch.enabled}
changed = False
for watch in watches:
- if not watch.enabled or watch.id in self._active_tasks or watch.id in self._fused_watch_ids:
+ if (
+ not watch.enabled
+ or watch.id in self._active_tasks
+ or watch.id in self._fused_watch_ids
+ or watch.id in self._recovery_blocked_watch_ids
+ ):
continue
task = asyncio.create_task(self._run_watch(watch.id))
self._active_tasks[watch.id] = task
@@ -515,21 +946,33 @@ class ManagedWatchService:
def _on_watch_done(self, watch_id: str) -> None:
self._active_tasks.pop(watch_id, None)
self._active_pids.pop(watch_id, None)
+ self._active_process_identities.pop(watch_id, None)
self._watch_started_at.pop(watch_id, None)
self._runtime_state_dirty = True
self._write_runtime_state()
self._reconcile_dirty = True
def _write_runtime_state(self) -> None:
- payload = {"watches": {}}
+ if self._recovery_pending:
+ return
+ payload = {
+ "watches": {
+ watch_id: dict(entry)
+ for watch_id, entry in self._unreaped_runtime_entries.items()
+ }
+ }
now = _utc_now_iso()
for watch_id, task in self._active_tasks.items():
- payload["watches"][watch_id] = {
+ entry = {
"running": not task.done(),
"pid": self._active_pids.get(watch_id),
"started_at": self._watch_started_at.get(watch_id),
"updated_at": now,
}
+ identity = self._active_process_identities.get(watch_id)
+ if identity is not None:
+ entry["process_identity"] = _serialize_process_identity(identity)
+ payload["watches"][watch_id] = entry
try:
self.runtime_store.write(payload)
self._runtime_state_dirty = False
@@ -745,28 +1188,52 @@ class ManagedWatchService:
async def _run_cycle(self, watch: ManagedWatch, *, timeout_seconds: float) -> _CycleResult:
spawn_cwd = _watch_spawn_cwd(watch)
- if watch.shell_command:
- process = await asyncio.create_subprocess_shell(
- watch.shell_command,
- cwd=spawn_cwd,
- stdin=asyncio.subprocess.DEVNULL,
- stdout=asyncio.subprocess.PIPE,
- stderr=asyncio.subprocess.PIPE,
- **isolated_subprocess_kwargs(),
- )
+ worker_marker = new_process_identity_marker()
+ spawn_env = process_identity_subprocess_env(worker_marker)
+ process = await asyncio.create_subprocess_exec(
+ os.path.abspath(sys.executable),
+ os.fspath(Path(watch_worker.__file__).resolve()),
+ cwd=spawn_cwd,
+ env=spawn_env,
+ stdin=asyncio.subprocess.PIPE,
+ stdout=asyncio.subprocess.PIPE,
+ stderr=asyncio.subprocess.PIPE,
+ **isolated_subprocess_kwargs(),
+ )
+ self._active_pids[watch.id] = process.pid
+ identity = capture_spawned_process_identity(process.pid, worker_marker)
+ if identity is not None:
+ self._active_process_identities[watch.id] = identity
else:
- process = await asyncio.create_subprocess_exec(
- *watch.command,
- cwd=spawn_cwd,
- stdin=asyncio.subprocess.DEVNULL,
- stdout=asyncio.subprocess.PIPE,
- stderr=asyncio.subprocess.PIPE,
- **isolated_subprocess_kwargs(),
+ logger.warning(
+ "Unable to capture process identity for watch worker pid=%s watch_id=%s; "
+ "a future recovery will leave it untouched",
+ process.pid,
+ watch.id,
)
- self._active_pids[watch.id] = process.pid
self._runtime_state_dirty = True
self._write_runtime_state()
try:
+ if process.stdin is None:
+ await terminate_and_communicate(process, logger, f"watch {watch.id}")
+ raise RuntimeError("watch worker supervisor stdin is unavailable")
+ try:
+ process.stdin.write(
+ watch_worker.encode_watch_worker_spec(
+ command=watch.command,
+ shell_command=watch.shell_command,
+ )
+ )
+ await process.stdin.drain()
+ except (BrokenPipeError, ConnectionResetError):
+ stdout, stderr = await process.communicate()
+ detail = stderr.decode("utf-8", errors="replace").strip()
+ detail = self._localize_watch_worker_error(detail)
+ raise RuntimeError(
+ detail or self._t("harness.watch.supervisorExitedDuringStartup")
+ ) from None
+ finally:
+ process.stdin.close()
if timeout_seconds > 0:
stdout, stderr = await asyncio.wait_for(process.communicate(), timeout=timeout_seconds)
else:
@@ -780,13 +1247,16 @@ class ManagedWatchService:
return _CycleResult(exit_code=124, stdout="", stderr=stderr.decode("utf-8", errors="replace"), timed_out=True)
finally:
self._active_pids.pop(watch.id, None)
+ self._active_process_identities.pop(watch.id, None)
self._runtime_state_dirty = True
self._write_runtime_state()
return _CycleResult(
exit_code=process.returncode or 0,
stdout=stdout.decode("utf-8", errors="replace").strip(),
- stderr=stderr.decode("utf-8", errors="replace").strip(),
+ stderr=self._localize_watch_worker_error(
+ stderr.decode("utf-8", errors="replace").strip()
+ ),
timed_out=timed_out,
)
diff --git a/tests/test_cli_watch_command.py b/tests/test_cli_watch_command.py
index 52fb61d34..e813a5b8f 100644
--- a/tests/test_cli_watch_command.py
+++ b/tests/test_cli_watch_command.py
@@ -712,6 +712,31 @@ def test_default_watch_startup_timeout_exceeds_reconcile_and_stable_windows() ->
assert timeout_seconds > cli.WATCH_RECONCILE_INTERVAL_SECONDS + cli.WATCH_STARTUP_STABLE_RUNNING_SECONDS
+def test_default_watch_startup_timeout_accounts_for_recovery_entries(tmp_path: Path) -> None:
+ runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")
+ runtime_store.write(
+ {
+ "watches": {
+ "first": {"running": True, "pid": 1234},
+ "second": {"running": True, "pid": 5678},
+ "finished": {"running": False, "pid": 9012},
+ }
+ }
+ )
+
+ recovery_entry_count = cli._watch_recovery_entry_count(runtime_store)
+ timeout_seconds = cli._default_watch_startup_timeout_seconds(
+ stable_running_seconds=cli.WATCH_STARTUP_STABLE_RUNNING_SECONDS,
+ recovery_entry_count=recovery_entry_count,
+ )
+ base_timeout = cli._default_watch_startup_timeout_seconds(
+ stable_running_seconds=cli.WATCH_STARTUP_STABLE_RUNNING_SECONDS,
+ )
+
+ assert recovery_entry_count == 2
+ assert timeout_seconds == base_timeout + (2 * cli.WATCH_RECOVERY_ENTRY_TIMEOUT_SECONDS)
+
+
def test_wait_for_watch_startup_rejects_watch_that_fails_before_stable_window(tmp_path: Path) -> None:
store = ManagedWatchStore(tmp_path / "watches.json")
runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")
diff --git a/tests/test_process_isolation.py b/tests/test_process_isolation.py
index 2c472357b..b8ceb3937 100644
--- a/tests/test_process_isolation.py
+++ b/tests/test_process_isolation.py
@@ -4,11 +4,59 @@ import asyncio
import logging
import os
import signal
+import sys
+from pathlib import Path
from types import SimpleNamespace
import pytest
-from core.process_isolation import KILL_SIGNAL, isolated_subprocess_kwargs, signal_process_tree
+from core import watch_worker
+from core.process_isolation import (
+ KILL_SIGNAL,
+ PROCESS_IDENTITY_ENV,
+ PersistedProcessIdentity,
+ ProcessIdentity,
+ capture_spawned_process_identity,
+ fingerprint_process_marker,
+ inspect_process_identity,
+ isolated_subprocess_kwargs,
+ new_process_identity_marker,
+ process_group_identity_status,
+ process_identity_matches,
+ process_identity_subprocess_env,
+ signal_process_tree,
+ terminate_process_group_by_pgid,
+ terminate_process_tree_by_pid,
+)
+
+TEST_MARKER = "test-worker-marker"
+TEST_FINGERPRINT = fingerprint_process_marker(TEST_MARKER)
+
+
+def _live_identity(
+ *,
+ pid: int = 12345,
+ create_time: float = 123.0,
+ worker_fingerprint: str | None = TEST_FINGERPRINT,
+) -> ProcessIdentity:
+ return ProcessIdentity(
+ pid=pid,
+ create_time=create_time,
+ worker_fingerprint=worker_fingerprint,
+ )
+
+
+def _persisted_identity(
+ *,
+ pid: int = 12345,
+ create_time: float = 123.0,
+ worker_fingerprint: str = TEST_FINGERPRINT,
+) -> PersistedProcessIdentity:
+ return PersistedProcessIdentity(
+ pid=pid,
+ create_time=create_time,
+ worker_fingerprint=worker_fingerprint,
+ )
def test_isolated_subprocess_kwargs_start_new_session_on_posix() -> None:
@@ -18,6 +66,60 @@ def test_isolated_subprocess_kwargs_start_new_session_on_posix() -> None:
assert isolated_subprocess_kwargs() == {"start_new_session": True}
+def test_process_identity_reads_inherited_worker_marker(monkeypatch: pytest.MonkeyPatch) -> None:
+ process = SimpleNamespace(
+ create_time=lambda: 123.0,
+ environ=lambda: {PROCESS_IDENTITY_ENV: TEST_MARKER},
+ )
+ monkeypatch.setattr("core.process_isolation.psutil.Process", lambda _pid: process)
+
+ identity = inspect_process_identity(12345)
+
+ assert identity == _live_identity()
+
+
+def test_process_identity_survives_exec_transition() -> None:
+ if os.name == "nt":
+ pytest.skip("exec transition is POSIX-specific")
+
+ async def _run() -> None:
+ marker = new_process_identity_marker()
+ process = await asyncio.create_subprocess_exec(
+ os.path.abspath(sys.executable),
+ str(Path(watch_worker.__file__).resolve()),
+ env=process_identity_subprocess_env(marker),
+ stdin=asyncio.subprocess.PIPE,
+ **isolated_subprocess_kwargs(),
+ )
+ try:
+ expected = capture_spawned_process_identity(process.pid, marker)
+ assert expected is not None
+ assert process.stdin is not None
+ process.stdin.write(
+ watch_worker.encode_watch_worker_spec(
+ command=[
+ "/usr/bin/env",
+ "-i",
+ sys.executable,
+ "-c",
+ "import time; time.sleep(30)",
+ ],
+ shell_command=None,
+ )
+ )
+ await process.stdin.drain()
+ process.stdin.close()
+ await asyncio.sleep(0.1)
+ live = inspect_process_identity(process.pid)
+ assert live is not None
+ assert process_identity_matches(expected, live)
+ finally:
+ signal_process_tree(process, KILL_SIGNAL, logging.getLogger(__name__), "test process")
+ await process.wait()
+
+ asyncio.run(_run())
+
+
def test_signal_process_tree_refuses_own_process_group_on_posix(monkeypatch: pytest.MonkeyPatch) -> None:
if os.name == "nt":
pytest.skip("process group guard is POSIX-specific")
@@ -36,6 +138,345 @@ def test_signal_process_tree_refuses_own_process_group_on_posix(monkeypatch: pyt
assert sent == [("terminate", 0)]
+def test_terminate_process_tree_by_pid_refuses_current_process(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(os, "getpid", lambda: 12345)
+ monkeypatch.setattr(
+ "core.process_isolation._open_process_identity",
+ lambda _pid: pytest.fail("the current process must not be inspected for termination"),
+ )
+
+ assert (
+ terminate_process_tree_by_pid(
+ 12345,
+ logging.getLogger(__name__),
+ "test process",
+ expected_identity=_persisted_identity(),
+ )
+ is False
+ )
+
+
+def test_terminate_process_tree_by_pid_refuses_service_process_group(monkeypatch: pytest.MonkeyPatch) -> None:
+ if os.name == "nt":
+ pytest.skip("process group guard is POSIX-specific")
+
+ identity = _live_identity()
+ process = SimpleNamespace(pid=12345)
+ monkeypatch.setattr("core.process_isolation._open_process_identity", lambda _pid: (process, identity))
+ monkeypatch.setattr(os, "getpid", lambda: 99999)
+ monkeypatch.setattr(os, "getpgid", lambda _pid: 12345)
+ monkeypatch.setattr(os, "getpgrp", lambda: 12345)
+ monkeypatch.setattr(
+ os,
+ "killpg",
+ lambda *_args: pytest.fail("the service process group must not be signaled"),
+ )
+
+ assert (
+ terminate_process_tree_by_pid(
+ 12345,
+ logging.getLogger(__name__),
+ "test process",
+ expected_identity=_persisted_identity(),
+ )
+ is False
+ )
+
+
+def test_terminate_process_tree_by_pid_escalates_after_timeout(monkeypatch: pytest.MonkeyPatch) -> None:
+ if os.name == "nt":
+ pytest.skip("process group signalling assertion is POSIX-specific")
+
+ identity = _live_identity()
+ signals: list[int] = []
+ waits = iter([False, True])
+ identity_checks = 0
+
+ def open_identity(_pid: int):
+ nonlocal identity_checks
+ identity_checks += 1
+ return SimpleNamespace(pid=12345), identity
+
+ monkeypatch.setattr("core.process_isolation._open_process_identity", open_identity)
+ monkeypatch.setattr(os, "getpid", lambda: 99999)
+ monkeypatch.setattr(os, "getpgid", lambda _pid: 12345)
+ monkeypatch.setattr(os, "killpg", lambda _pgid, sig: signals.append(sig))
+ monkeypatch.setattr(
+ "core.process_isolation._wait_for_process_group_exit",
+ lambda *_args, **_kwargs: next(waits),
+ )
+
+ assert (
+ terminate_process_tree_by_pid(
+ 12345,
+ logging.getLogger(__name__),
+ "test process",
+ expected_identity=_persisted_identity(),
+ )
+ is True
+ )
+ assert signals == [signal.SIGTERM, KILL_SIGNAL]
+ assert identity_checks == 3
+
+
+def test_terminate_process_tree_by_pid_revalidates_before_group_signal(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ if os.name == "nt":
+ pytest.skip("process group signalling assertion is POSIX-specific")
+
+ identities = iter(
+ [
+ _live_identity(),
+ _live_identity(worker_fingerprint=fingerprint_process_marker("replacement")),
+ ]
+ )
+ monkeypatch.setattr(
+ "core.process_isolation._open_process_identity",
+ lambda _pid: (SimpleNamespace(pid=12345), next(identities)),
+ )
+ monkeypatch.setattr(os, "getpid", lambda: 99999)
+ monkeypatch.setattr(os, "getpgid", lambda _pid: 12345)
+ monkeypatch.setattr(
+ os,
+ "killpg",
+ lambda *_args: pytest.fail("a changed supervisor must not be signaled"),
+ )
+
+ assert (
+ terminate_process_tree_by_pid(
+ 12345,
+ logging.getLogger(__name__),
+ "test process",
+ expected_identity=_persisted_identity(),
+ )
+ is False
+ )
+
+
+def test_terminate_process_tree_by_pid_does_not_signal_reused_pid(monkeypatch: pytest.MonkeyPatch) -> None:
+ if os.name == "nt":
+ pytest.skip("process group signalling assertion is POSIX-specific")
+
+ expected_identity = _persisted_identity()
+ reused_identity = _live_identity(create_time=456.0)
+ monkeypatch.setattr(
+ "core.process_isolation._open_process_identity",
+ lambda _pid: (SimpleNamespace(pid=12345), reused_identity),
+ )
+ monkeypatch.setattr(os, "getpid", lambda: 99999)
+ monkeypatch.setattr(
+ os,
+ "getpgid",
+ lambda _pid: pytest.fail("a reused pid must not have its process group inspected"),
+ )
+
+ assert (
+ terminate_process_tree_by_pid(
+ 12345,
+ logging.getLogger(__name__),
+ "test process",
+ expected_identity=expected_identity,
+ )
+ is True
+ )
+
+
+def test_terminate_process_tree_by_pid_refuses_changed_marker(monkeypatch: pytest.MonkeyPatch) -> None:
+ expected_identity = _persisted_identity()
+ changed_identity = _live_identity(
+ worker_fingerprint=fingerprint_process_marker("other-worker-marker")
+ )
+ monkeypatch.setattr(
+ "core.process_isolation._open_process_identity",
+ lambda _pid: (SimpleNamespace(pid=12345), changed_identity),
+ )
+ monkeypatch.setattr(os, "getpid", lambda: 99999)
+ monkeypatch.setattr(
+ os,
+ "getpgid",
+ lambda _pid: pytest.fail("a changed worker marker must not have its process group inspected"),
+ )
+
+ assert (
+ terminate_process_tree_by_pid(
+ 12345,
+ logging.getLogger(__name__),
+ "test process",
+ expected_identity=expected_identity,
+ )
+ is False
+ )
+
+
+def test_terminate_process_tree_by_pid_refuses_non_leader(monkeypatch: pytest.MonkeyPatch) -> None:
+ if os.name == "nt":
+ pytest.skip("process group signalling assertion is POSIX-specific")
+
+ identity = _live_identity()
+ monkeypatch.setattr(
+ "core.process_isolation._open_process_identity",
+ lambda _pid: (SimpleNamespace(pid=12345), identity),
+ )
+ monkeypatch.setattr(os, "getpid", lambda: 99999)
+ monkeypatch.setattr(os, "getpgid", lambda _pid: 54321)
+ monkeypatch.setattr(
+ os,
+ "killpg",
+ lambda *_args: pytest.fail("a non-leader process group must not be signaled"),
+ )
+
+ assert (
+ terminate_process_tree_by_pid(
+ 12345,
+ logging.getLogger(__name__),
+ "test process",
+ expected_identity=_persisted_identity(),
+ )
+ is False
+ )
+
+
+def test_terminate_process_group_by_pgid_recovers_after_leader_exit(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ if os.name == "nt":
+ pytest.skip("process group signalling assertion is POSIX-specific")
+
+ signals: list[int] = []
+ waits = iter([False, True])
+ monkeypatch.setattr(os, "getpgrp", lambda: 99999)
+ monkeypatch.setattr("core.process_isolation._process_group_exists", lambda *_args: True)
+ monkeypatch.setattr(
+ "core.process_isolation.process_group_matches_identity",
+ lambda *_args: True,
+ )
+ monkeypatch.setattr(os, "killpg", lambda _pgid, sig: signals.append(sig))
+ monkeypatch.setattr(
+ "core.process_isolation._wait_for_process_group_exit",
+ lambda *_args, **_kwargs: next(waits),
+ )
+
+ assert (
+ terminate_process_group_by_pgid(
+ 12345,
+ logging.getLogger(__name__),
+ "test process group",
+ expected_identity=_persisted_identity(),
+ )
+ is True
+ )
+ assert signals == [signal.SIGTERM, KILL_SIGNAL]
+
+
+def test_terminate_process_group_by_pgid_refuses_unverified_group(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ if os.name == "nt":
+ pytest.skip("process group signalling assertion is POSIX-specific")
+
+ monkeypatch.setattr(os, "getpgrp", lambda: 99999)
+ monkeypatch.setattr("core.process_isolation._process_group_exists", lambda *_args: True)
+ monkeypatch.setattr(
+ "core.process_isolation.process_group_matches_identity",
+ lambda *_args: False,
+ )
+ monkeypatch.setattr(
+ os,
+ "killpg",
+ lambda *_args: pytest.fail("an unverified process group must not be signaled"),
+ )
+
+ assert (
+ terminate_process_group_by_pgid(
+ 12345,
+ logging.getLogger(__name__),
+ "test process group",
+ expected_identity=_persisted_identity(),
+ )
+ is False
+ )
+
+
+ ("live_fingerprint", "expected_status"),
+ [
+ (TEST_FINGERPRINT, "match"),
+ (fingerprint_process_marker("other-worker-marker"), "mismatch"),
+ ],
+)
+def test_process_group_identity_status_checks_inherited_worker_marker(
+ monkeypatch: pytest.MonkeyPatch,
+ live_fingerprint: str,
+ expected_status: str,
+) -> None:
+ if os.name == "nt":
+ pytest.skip("process group identity is POSIX-specific")
+
+ process = SimpleNamespace(info={"pid": 54321})
+ monkeypatch.setattr(
+ "core.process_isolation.psutil.process_iter",
+ lambda _attrs: [process],
+ )
+ monkeypatch.setattr(os, "getpgid", lambda _pid: 12345)
+ monkeypatch.setattr(
+ "core.process_isolation.inspect_process_identity",
+ lambda pid: _live_identity(
+ pid=pid,
+ create_time=124.0,
+ worker_fingerprint=live_fingerprint,
+ ),
+ )
+
+ assert (
+ process_group_identity_status(
+ 12345,
+ _persisted_identity(),
+ logging.getLogger(__name__),
+ "test process group",
+ )
+ == expected_status
+ )
+
+
+def test_process_group_identity_status_fails_closed_for_unverified_member(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ if os.name == "nt":
+ pytest.skip("process group identity is POSIX-specific")
+
+ processes = [
+ SimpleNamespace(info={"pid": 54321}),
+ SimpleNamespace(info={"pid": 54322}),
+ ]
+ monkeypatch.setattr(
+ "core.process_isolation.psutil.process_iter",
+ lambda _attrs: processes,
+ )
+ monkeypatch.setattr(os, "getpgid", lambda _pid: 12345)
+
+ def inspect(pid: int) -> ProcessIdentity | None:
+ if pid == 54321:
+ return _live_identity(
+ pid=pid,
+ create_time=124.0,
+ worker_fingerprint=fingerprint_process_marker("other-worker-marker"),
+ )
+ return None
+
+ monkeypatch.setattr("core.process_isolation.inspect_process_identity", inspect)
+
+ assert (
+ process_group_identity_status(
+ 12345,
+ _persisted_identity(),
+ logging.getLogger(__name__),
+ "test process group",
+ )
+ == "unknown"
+ )
+
+
def test_asyncio_subprocess_is_spawned_outside_parent_process_group_on_posix() -> None:
if os.name == "nt":
pytest.skip("POSIX process-group assertion")
diff --git a/tests/test_watch_worker.py b/tests/test_watch_worker.py
new file mode 100644
index 000000000..43d1413bc
--- /dev/null
+++ b/tests/test_watch_worker.py
@@ -0,0 +1,353 @@
+from __future__ import annotations
+
+import logging
+import os
+import signal
+import subprocess
+import sys
+import time
+from pathlib import Path
+
+import psutil
+import pytest
+
+from core import watch_worker
+from core.process_isolation import (
+ PROCESS_IDENTITY_ENV,
+ PersistedProcessIdentity,
+ fingerprint_process_marker,
+ process_group_identity_status,
+)
+
+
+def _supervisor_command() -> list[str]:
+ return [
+ os.path.abspath(sys.executable),
+ str(Path(watch_worker.__file__).resolve()),
+ ]
+
+
+def _supervisor_isolation_kwargs() -> dict[str, object]:
+ if os.name == "nt":
+ return {"creationflags": subprocess.CREATE_NEW_PROCESS_GROUP}
+ return {"start_new_session": True}
+
+
+def test_watch_worker_hides_supervisor_identity_and_preserves_empty_arguments() -> None:
+ marker = "supervisor-only-marker"
+ env = dict(os.environ)
+ env[PROCESS_IDENTITY_ENV] = marker
+ spec = watch_worker.encode_watch_worker_spec(
+ command=[
+ sys.executable,
+ "-c",
+ (
+ "import os,sys; "
+ "print(os.environ.get('AVIBE_PROCESS_IDENTITY', 'missing')); "
+ "print(repr(sys.argv[1])); "
+ "print('worker-stderr', file=sys.stderr)"
+ ),
+ "",
+ ],
+ shell_command=None,
+ )
+
+ result = subprocess.run(
+ _supervisor_command(),
+ input=spec,
+ capture_output=True,
+ env=env,
+ timeout=10,
+ check=False,
+ **_supervisor_isolation_kwargs(),
+ )
+
+ assert result.returncode == 0
+ assert result.stdout.decode().splitlines() == ["missing", "''"]
+ assert result.stderr.decode().strip() == "worker-stderr"
+ assert marker not in result.stdout.decode()
+ assert marker not in result.stderr.decode()
+
+
+def test_watch_worker_rejects_invalid_specification() -> None:
+ result = subprocess.run(
+ _supervisor_command(),
+ input=b'{"version":1,"command":[],"shell_command":null}',
+ capture_output=True,
+ timeout=10,
+ check=False,
+ **_supervisor_isolation_kwargs(),
+ )
+
+ assert result.returncode == 1
+ assert watch_worker.decode_watch_worker_error(result.stderr.decode()) == (
+ "invalidCommand",
+ None,
+ )
+
+
[email protected](os.name == "nt", reason="POSIX surrogateescape contract")
[email protected]("use_shell", [False, True])
+def test_posix_watch_worker_preserves_non_utf8_arguments(use_shell: bool) -> None:
+ value = os.fsdecode(b"watch-\xff")
+ if use_shell:
+ import shlex
+
+ command = []
+ shell_command = (
+ f"{shlex.quote(sys.executable)} -c "
+ f"{shlex.quote('import os,sys; print(os.fsencode(sys.argv[1]).hex())')} "
+ f"{shlex.quote(value)}"
+ )
+ else:
+ command = [
+ sys.executable,
+ "-c",
+ "import os,sys; print(os.fsencode(sys.argv[1]).hex())",
+ value,
+ ]
+ shell_command = None
+
+ result = subprocess.run(
+ _supervisor_command(),
+ input=watch_worker.encode_watch_worker_spec(
+ command=command,
+ shell_command=shell_command,
+ ),
+ capture_output=True,
+ timeout=10,
+ check=False,
+ **_supervisor_isolation_kwargs(),
+ )
+
+ assert result.returncode == 0
+ assert result.stdout.decode().strip() == b"watch-\xff".hex()
+
+
[email protected](os.name == "nt", reason="POSIX signal exit contract")
+def test_posix_watch_worker_preserves_waiter_signal_exit() -> None:
+ result = subprocess.run(
+ _supervisor_command(),
+ input=watch_worker.encode_watch_worker_spec(
+ command=[
+ sys.executable,
+ "-c",
+ "import os,signal; os.kill(os.getpid(), signal.SIGTERM)",
+ ],
+ shell_command=None,
+ ),
+ capture_output=True,
+ timeout=10,
+ check=False,
+ **_supervisor_isolation_kwargs(),
+ )
+
+ assert result.returncode == -signal.SIGTERM
+
+
[email protected](os.name == "nt", reason="POSIX process group contract")
+def test_posix_watch_worker_survives_term_until_waiter_exits(tmp_path: Path) -> None:
+ waiter_pid_path = tmp_path / "waiter.pid"
+ process = subprocess.Popen(
+ _supervisor_command(),
+ stdin=subprocess.PIPE,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ **_supervisor_isolation_kwargs(),
+ )
+ assert process.stdin is not None
+ process.stdin.write(
+ watch_worker.encode_watch_worker_spec(
+ command=[
+ sys.executable,
+ "-c",
+ (
+ "import os,signal,time; from pathlib import Path; "
+ "signal.signal(signal.SIGTERM, signal.SIG_IGN); "
+ f"Path({str(waiter_pid_path)!r}).write_text(str(os.getpid())); "
+ "time.sleep(30)"
+ ),
+ ],
+ shell_command=None,
+ )
+ )
+ process.stdin.close()
+
+ try:
+ deadline = time.monotonic() + 5
+ while not waiter_pid_path.exists() and time.monotonic() < deadline:
+ time.sleep(0.05)
+ waiter_pid = int(waiter_pid_path.read_text())
+ os.killpg(process.pid, signal.SIGTERM)
+ time.sleep(0.2)
+ assert process.poll() is None
+ assert psutil.pid_exists(waiter_pid)
+ finally:
+ if process.poll() is None:
+ os.killpg(process.pid, signal.SIGKILL)
+ process.wait(timeout=10)
+
+
[email protected](os.name == "nt", reason="POSIX process group contract")
+def test_posix_watch_worker_waits_for_descendant_after_command_root_exits() -> None:
+ child_script = (
+ "import subprocess,sys; "
+ "child=subprocess.Popen("
+ "[sys.executable,'-c','import time; time.sleep(30)'],"
+ "stdin=subprocess.DEVNULL,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL"
+ "); "
+ "print(child.pid, flush=True)"
+ )
+ process = subprocess.Popen(
+ _supervisor_command(),
+ stdin=subprocess.PIPE,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ **_supervisor_isolation_kwargs(),
+ )
+ assert process.stdin is not None
+ assert process.stdout is not None
+ process.stdin.write(
+ watch_worker.encode_watch_worker_spec(
+ command=[sys.executable, "-c", child_script],
+ shell_command=None,
+ )
+ )
+ process.stdin.close()
+ descendant_pid = int(process.stdout.readline().decode().strip())
+
+ try:
+ time.sleep(0.2)
+ assert process.poll() is None
+ assert psutil.pid_exists(descendant_pid)
+ finally:
+ if process.poll() is None:
+ os.killpg(process.pid, signal.SIGKILL)
+ process.wait(timeout=10)
+ if psutil.pid_exists(descendant_pid):
+ psutil.Process(descendant_pid).kill()
+
+
[email protected](os.name == "nt", reason="POSIX process group identity contract")
+def test_posix_watch_worker_leaves_identity_anchor_if_supervisor_is_killed(
+ tmp_path: Path,
+) -> None:
+ marker = "surviving-anchor-marker"
+ env = dict(os.environ)
+ env[watch_worker.PROCESS_IDENTITY_ENV] = marker
+ waiter_pid_path = tmp_path / "waiter.pid"
+ process = subprocess.Popen(
+ _supervisor_command(),
+ stdin=subprocess.PIPE,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ env=env,
+ **_supervisor_isolation_kwargs(),
+ )
+ assert process.stdin is not None
+ process.stdin.write(
+ watch_worker.encode_watch_worker_spec(
+ command=[
+ sys.executable,
+ "-c",
+ (
+ "import os,signal,time; from pathlib import Path; "
+ "signal.signal(signal.SIGTERM, signal.SIG_IGN); "
+ f"Path({str(waiter_pid_path)!r}).write_text(str(os.getpid())); "
+ "time.sleep(30)"
+ ),
+ ],
+ shell_command=None,
+ )
+ )
+ process.stdin.close()
+
+ try:
+ deadline = time.monotonic() + 5
+ while not waiter_pid_path.exists() and time.monotonic() < deadline:
+ time.sleep(0.05)
+ waiter_pid = int(waiter_pid_path.read_text())
+ identity = psutil.Process(process.pid)
+ expected = PersistedProcessIdentity(
+ pid=process.pid,
+ create_time=identity.create_time(),
+ worker_fingerprint=fingerprint_process_marker(marker),
+ )
+ os.kill(process.pid, signal.SIGKILL)
+ process.wait(timeout=10)
+
+ assert psutil.pid_exists(waiter_pid)
+ assert (
+ process_group_identity_status(
+ process.pid,
+ expected,
+ logging.getLogger(__name__),
+ "test watch",
+ )
+ == "match"
+ )
+ finally:
+ try:
+ os.killpg(process.pid, signal.SIGKILL)
+ except ProcessLookupError:
+ pass
+ if process.poll() is None:
+ process.wait(timeout=10)
+
+
[email protected](os.name != "nt", reason="Windows Job Object contract")
+def test_windows_watch_worker_job_tracks_descendant_after_command_root_exits() -> None:
+ child_script = (
+ "import subprocess,sys; "
+ "child=subprocess.Popen([sys.executable,'-c','import time; time.sleep(30)']); "
+ "print(child.pid, flush=True)"
+ )
+ process = subprocess.Popen(
+ _supervisor_command(),
+ stdin=subprocess.PIPE,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ **_supervisor_isolation_kwargs(),
+ )
+ assert process.stdin is not None
+ assert process.stdout is not None
+ process.stdin.write(
+ watch_worker.encode_watch_worker_spec(
+ command=[sys.executable, "-c", child_script],
+ shell_command=None,
+ )
+ )
+ process.stdin.close()
+ descendant_pid = int(process.stdout.readline().decode().strip())
+
+ try:
+ assert process.poll() is None
+ process.terminate()
+ process.wait(timeout=10)
+ deadline = time.monotonic() + 10
+ while psutil.pid_exists(descendant_pid) and time.monotonic() < deadline:
+ time.sleep(0.05)
+ assert not psutil.pid_exists(descendant_pid)
+ finally:
+ if process.poll() is None:
+ process.kill()
+ process.wait(timeout=10)
+ if psutil.pid_exists(descendant_pid):
+ psutil.Process(descendant_pid).kill()
+
+
[email protected](os.name != "nt", reason="Windows exit code contract")
+def test_windows_watch_worker_preserves_full_exit_code() -> None:
+ result = subprocess.run(
+ _supervisor_command(),
+ input=watch_worker.encode_watch_worker_spec(
+ command=[sys.executable, "-c", "import os; os._exit(513)"],
+ shell_command=None,
+ ),
+ capture_output=True,
+ timeout=10,
+ check=False,
+ **_supervisor_isolation_kwargs(),
+ )
+
+ assert result.returncode == 513
diff --git a/tests/test_watches.py b/tests/test_watches.py
index b76596876..003347949 100644
--- a/tests/test_watches.py
+++ b/tests/test_watches.py
@@ -4,6 +4,7 @@ import asyncio
import json
import os
import sys
+import time
from datetime import datetime
from pathlib import Path
from types import SimpleNamespace
@@ -13,17 +14,138 @@ import pytest
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from config import paths
+from core import watch_worker
+from core.process_isolation import (
+ PersistedProcessIdentity,
+ ProcessIdentity,
+ fingerprint_process_marker,
+)
from core.scheduled_tasks import TaskExecutionStore
from core.watches import ManagedWatchService, ManagedWatchStore, WatchRuntimeStateStore, _CycleResult
from storage.background import SQLiteBackgroundTaskStore
+TEST_MARKER = "test-watch-worker"
+TEST_FINGERPRINT = fingerprint_process_marker(TEST_MARKER)
+
+
+class _FakeStdin:
+ def __init__(self) -> None:
+ self.payload = bytearray()
+ self.closed = False
+
+ def write(self, payload: bytes) -> None:
+ self.payload.extend(payload)
+
+ async def drain(self) -> None:
+ return None
+
+ def close(self) -> None:
+ self.closed = True
+
+
+class _BrokenStdin(_FakeStdin):
+ async def drain(self) -> None:
+ raise BrokenPipeError
+
class _FakeProcess:
- pid = 1234
- returncode = 0
+ def __init__(
+ self,
+ *,
+ stdin: _FakeStdin | None = None,
+ stderr: bytes = b"",
+ ) -> None:
+ self.pid = 1234
+ self.returncode = 0
+ self.stdin = stdin or _FakeStdin()
+ self.stderr = stderr
+
+ async def communicate(self) -> tuple[bytes, bytes]:
+ return b"ok\n", self.stderr
+
+
+async def _start_watch_service(service: ManagedWatchService) -> None:
+ service.start()
+ startup_task = service._startup_task
+ if startup_task is not None:
+ await startup_task
+
+
+def _add_recovery_watch(
+ store: ManagedWatchStore,
+ *,
+ command: list[str],
+ shell_command: str | None = None,
+):
+ return store.add_watch(
+ name="Recovery watch",
+ session_key="slack::channel::C123",
+ command=command,
+ shell_command=shell_command,
+ prefix=None,
+ cwd=None,
+ mode="forever",
+ timeout_seconds=0,
+ lifetime_timeout_seconds=0,
+ retry_exit_codes=[75],
+ retry_delay_seconds=30,
+ post_to=None,
+ deliver_key=None,
+ )
+
+
+def _record_watch_pid(
+ runtime_store: WatchRuntimeStateStore,
+ watch_id: str,
+ pid: int,
+ *,
+ identity: PersistedProcessIdentity | None = None,
+) -> None:
+ entry = {
+ "running": True,
+ "pid": pid,
+ "started_at": "2026-05-15T00:00:00+00:00",
+ "updated_at": "2026-05-15T00:00:01+00:00",
+ }
+ if identity is not None:
+ entry["process_identity"] = {
+ "pid": identity.pid,
+ "create_time": identity.create_time,
+ "worker_fingerprint": identity.worker_fingerprint,
+ }
+ runtime_store.write(
+ {
+ "watches": {
+ watch_id: entry,
+ }
+ }
+ )
+
+
+def _live_identity(
+ *,
+ pid: int = 4321,
+ create_time: float = 123.0,
+ worker_fingerprint: str | None = TEST_FINGERPRINT,
+) -> ProcessIdentity:
+ return ProcessIdentity(
+ pid=pid,
+ create_time=create_time,
+ worker_fingerprint=worker_fingerprint,
+ )
- async def communicate(self):
- return b"ok\n", b""
+
+def _persisted_identity(
+ *,
+ pid: int = 4321,
+ create_time: float = 123.0,
+ worker_fingerprint: str = TEST_FINGERPRINT,
+) -> PersistedProcessIdentity:
+ return PersistedProcessIdentity(
+ pid=pid,
+ create_time=create_time,
+ worker_fingerprint=worker_fingerprint,
+ )
def test_managed_watch_store_round_trip(tmp_path: Path) -> None:
@@ -83,7 +205,17 @@ def test_managed_watch_store_preserves_zero_values_on_reload(tmp_path: Path) ->
assert saved.retry_delay_seconds == 0
-def test_managed_watch_exec_detaches_waiter_stdin(tmp_path: Path, monkeypatch) -> None:
+def test_managed_watch_store_recovery_accepts_empty_command_arguments(tmp_path: Path) -> None:
+ store = ManagedWatchStore(tmp_path / "watches.json")
+ watch = _add_recovery_watch(store, command=[sys.executable, "wait.py", ""])
+
+ recovered = store.list_watches_for_recovery()
+
+ assert [item.id for item in recovered] == [watch.id]
+ assert recovered[0].command == [sys.executable, "wait.py", ""]
+
+
+def test_managed_watch_exec_uses_stable_supervisor(tmp_path: Path, monkeypatch) -> None:
captured: dict[str, object] = {}
store = ManagedWatchStore(tmp_path / "watches.json")
runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")
@@ -112,20 +244,34 @@ def test_managed_watch_exec_detaches_waiter_stdin(tmp_path: Path, monkeypatch) -
async def fake_create_subprocess_exec(*args, **kwargs):
captured["args"] = args
captured["kwargs"] = kwargs
- return _FakeProcess()
+ process = _FakeProcess()
+ captured["process"] = process
+ return process
monkeypatch.setattr(asyncio, "create_subprocess_exec", fake_create_subprocess_exec)
result = asyncio.run(service._run_cycle(watch, timeout_seconds=5))
assert result.exit_code == 0
- assert captured["kwargs"]["stdin"] == asyncio.subprocess.DEVNULL
+ assert captured["args"] == (
+ os.path.abspath(sys.executable),
+ str(Path(watch_worker.__file__).resolve()),
+ )
+ assert captured["kwargs"]["stdin"] == asyncio.subprocess.PIPE
assert captured["kwargs"]["stdout"] == asyncio.subprocess.PIPE
assert captured["kwargs"]["stderr"] == asyncio.subprocess.PIPE
assert captured["kwargs"]["cwd"] == str(paths.get_vibe_remote_dir())
+ process = captured["process"]
+ assert isinstance(process, _FakeProcess)
+ assert process.stdin.closed is True
+ assert json.loads(process.stdin.payload) == {
+ "version": 1,
+ "command": ["python3", "-c", "print('ok')"],
+ "shell_command": None,
+ }
-def test_managed_watch_shell_detaches_waiter_stdin(tmp_path: Path, monkeypatch) -> None:
+def test_managed_watch_shell_uses_stable_supervisor(tmp_path: Path, monkeypatch) -> None:
captured: dict[str, object] = {}
store = ManagedWatchStore(tmp_path / "watches.json")
runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")
@@ -151,20 +297,110 @@ def test_managed_watch_shell_detaches_waiter_stdin(tmp_path: Path, monkeypatch)
deliver_key=None,
)
- async def fake_create_subprocess_shell(*args, **kwargs):
+ async def fake_create_subprocess_exec(*args, **kwargs):
captured["args"] = args
captured["kwargs"] = kwargs
- return _FakeProcess()
+ process = _FakeProcess()
+ captured["process"] = process
+ return process
- monkeypatch.setattr(asyncio, "create_subprocess_shell", fake_create_subprocess_shell)
+ monkeypatch.setattr(asyncio, "create_subprocess_exec", fake_create_subprocess_exec)
result = asyncio.run(service._run_cycle(watch, timeout_seconds=5))
assert result.exit_code == 0
- assert captured["kwargs"]["stdin"] == asyncio.subprocess.DEVNULL
+ assert captured["args"] == (
+ os.path.abspath(sys.executable),
+ str(Path(watch_worker.__file__).resolve()),
+ )
+ assert captured["kwargs"]["stdin"] == asyncio.subprocess.PIPE
assert captured["kwargs"]["stdout"] == asyncio.subprocess.PIPE
assert captured["kwargs"]["stderr"] == asyncio.subprocess.PIPE
assert captured["kwargs"]["cwd"] == str(paths.get_vibe_remote_dir())
+ process = captured["process"]
+ assert isinstance(process, _FakeProcess)
+ assert process.stdin.closed is True
+ assert json.loads(process.stdin.payload) == {
+ "version": 1,
+ "command": [],
+ "shell_command": "python3 -c 'print(\"ok\")'",
+ }
+
+
+def test_managed_watch_clears_supervisor_state_when_startup_pipe_breaks(tmp_path: Path, monkeypatch) -> None:
+ store = ManagedWatchStore(tmp_path / "watches.json")
+ runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")
+ service = ManagedWatchService(
+ controller=SimpleNamespace(),
+ store=store,
+ request_store=TaskExecutionStore(tmp_path / "task_requests"),
+ runtime_store=runtime_store,
+ )
+ watch = store.add_watch(
+ name="Broken supervisor",
+ session_key="slack::channel::C123",
+ command=["python3", "-c", "print('ok')"],
+ shell_command=None,
+ prefix=None,
+ 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,
+ )
+ process = _FakeProcess(stdin=_BrokenStdin())
+
+ async def fake_create_subprocess_exec(*_args, **_kwargs):
+ return process
+
+ monkeypatch.setattr(asyncio, "create_subprocess_exec", fake_create_subprocess_exec)
+
+ with pytest.raises(RuntimeError, match="Watch worker supervisor exited during startup"):
+ asyncio.run(service._run_cycle(watch, timeout_seconds=5))
+
+ assert process.stdin.closed is True
+ assert service._active_pids == {}
+ assert service._active_process_identities == {}
+
+
+def test_managed_watch_localizes_supervisor_startup_failure(tmp_path: Path, monkeypatch) -> None:
+ store = ManagedWatchStore(tmp_path / "watches.json")
+ service = ManagedWatchService(
+ controller=SimpleNamespace(config=SimpleNamespace(language="zh")),
+ store=store,
+ request_store=TaskExecutionStore(tmp_path / "task_requests"),
+ runtime_store=WatchRuntimeStateStore(tmp_path / "watch_runtime.json"),
+ )
+ watch = store.add_watch(
+ name="Broken supervisor",
+ session_key="slack::channel::C123",
+ command=["python3", "-c", "print('ok')"],
+ shell_command=None,
+ prefix=None,
+ 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,
+ )
+ process = _FakeProcess(
+ stdin=_BrokenStdin(),
+ stderr=watch_worker.encode_watch_worker_error("invalidCommand").encode(),
+ )
+
+ async def fake_create_subprocess_exec(*_args, **_kwargs):
+ return process
+
+ monkeypatch.setattr(asyncio, "create_subprocess_exec", fake_create_subprocess_exec)
+
+ with pytest.raises(RuntimeError, match="Watch 监控进程失败:Watch 工作进程命令无效。"):
+ asyncio.run(service._run_cycle(watch, timeout_seconds=5))
def test_managed_watch_legacy_none_cwd_survives_deleted_process_cwd(tmp_path: Path) -> None:
@@ -329,7 +565,7 @@ def test_managed_watch_service_once_success_enqueues_hook_and_disables(tmp_path:
)
async def _run() -> None:
- service.start()
+ await _start_watch_service(service)
for _ in range(100):
if watch.id not in service._active_tasks:
break
@@ -422,7 +658,7 @@ def test_managed_watch_service_forever_timeout_disables_and_enqueues_failure(tmp
)
async def _run() -> None:
- service.start()
+ await _start_watch_service(service)
await asyncio.sleep(0.2)
await service.stop()
@@ -466,7 +702,7 @@ def test_managed_watch_service_forever_timeout_retries_when_explicitly_allowed(t
)
async def _run() -> None:
- service.start()
+ await _start_watch_service(service)
await asyncio.sleep(0.2)
await service.stop()
@@ -506,7 +742,7 @@ def test_managed_watch_service_stop_terminates_running_waiter(tmp_path: Path) ->
)
async def _run() -> tuple[int, int | None]:
- service.start()
+ await _start_watch_service(service)
for _ in range(100):
pid = service._active_pids.get(watch.id)
if pid:
@@ -557,7 +793,7 @@ def test_managed_watch_service_lease_loss_terminates_running_waiter(tmp_path: Pa
monkeypatch.setattr("core.watches.runtime.current_process_owns_service_instance", lambda: owner_state["owns"])
async def _run() -> tuple[int, int | None]:
- service.start()
+ await _start_watch_service(service)
for _ in range(100):
pid = service._active_pids.get(watch.id)
if pid:
@@ -587,15 +823,23 @@ def test_managed_watch_service_lease_loss_terminates_running_waiter(tmp_path: Pa
os.kill(pid, 0)
-def test_managed_watch_service_records_wall_clock_started_at(tmp_path: Path) -> None:
+def test_managed_watch_service_records_non_secret_process_identity(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ secret = "runtime-expanded-secret"
+ monkeypatch.setenv("WATCH_RUNTIME_SECRET", secret)
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,
+ command=[],
+ shell_command=(
+ "exec python3 -c 'import time; time.sleep(30)' "
+ '"$WATCH_RUNTIME_SECRET"'
+ ),
prefix=None,
cwd=None,
mode="forever",
@@ -613,19 +857,27 @@ def test_managed_watch_service_records_wall_clock_started_at(tmp_path: Path) ->
runtime_store=runtime_store,
)
- async def _run() -> str:
- service.start()
+ async def _run() -> dict[str, object]:
+ await _start_watch_service(service)
for _ in range(100):
- started_at = runtime_store.load().get("watches", {}).get(watch.id, {}).get("started_at")
- if started_at:
+ entry = runtime_store.load().get("watches", {}).get(watch.id, {})
+ if entry.get("process_identity"):
await service.stop()
- return started_at
+ return entry
await asyncio.sleep(0.02)
await service.stop()
- raise AssertionError("started_at was never written")
+ raise AssertionError("process identity was never written")
- started_at = asyncio.run(_run())
- assert datetime.fromisoformat(started_at).year >= 2024
+ entry = asyncio.run(_run())
+ identity = entry["process_identity"]
+ assert isinstance(entry["pid"], int)
+ assert datetime.fromisoformat(str(entry["started_at"])).year >= 2024
+ assert isinstance(identity, dict)
+ assert identity["pid"] == entry["pid"]
+ assert identity["create_time"] > 0
+ assert identity["worker_fingerprint"].startswith("sha256:")
+ assert "cmdline" not in identity
+ assert secret not in json.dumps(entry)
def test_managed_watch_service_turns_spawn_error_into_failed_cycle(tmp_path: Path) -> None:
@@ -655,7 +907,7 @@ def test_managed_watch_service_turns_spawn_error_into_failed_cycle(tmp_path: Pat
)
async def _run() -> None:
- service.start()
+ await _start_watch_service(service)
for _ in range(100):
if watch.id not in service._active_tasks:
break
@@ -782,7 +1034,7 @@ def test_missing_watch_cwd_does_not_stop_other_watches(tmp_path: Path) -> None:
)
async def _run() -> None:
- service.start()
+ await _start_watch_service(service)
for _ in range(100):
broken_saved = store.get_watch(broken.id)
healthy_saved = store.get_watch(healthy.id)
@@ -832,7 +1084,7 @@ def test_managed_watch_service_forever_retries_only_allowed_exit_code(tmp_path:
)
async def _run() -> None:
- service.start()
+ await _start_watch_service(service)
await asyncio.sleep(0.08)
await service.stop()
@@ -872,7 +1124,7 @@ def test_managed_watch_service_forever_non_retry_error_disables_and_enqueues_fai
)
async def _run() -> None:
- service.start()
+ await _start_watch_service(service)
for _ in range(100):
if watch.id not in service._active_tasks:
break
@@ -930,7 +1182,7 @@ def test_managed_watch_service_fuses_watch_after_store_error(tmp_path: Path) ->
)
async def _run() -> None:
- service.start()
+ await _start_watch_service(service)
await asyncio.sleep(0.12)
assert watch.id in service._fused_watch_ids
await asyncio.sleep(0.08)
@@ -1019,6 +1271,7 @@ def test_managed_watch_service_idle_tick_does_not_write_runtime_state(tmp_path:
runtime_store=runtime_store,
)
service._running = True
+ service._recovery_pending = False
service._reconcile_dirty = False
service._runtime_state_dirty = False
@@ -1039,17 +1292,237 @@ def test_managed_watch_service_idle_tick_does_not_write_runtime_state(tmp_path:
assert runtime_store.writes == 0
-def test_managed_watch_service_start_clears_stale_runtime_state(tmp_path: Path) -> None:
+def test_managed_watch_service_start_reaps_stale_worker_for_deleted_watch(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> 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)
+ service = ManagedWatchService(
+ controller=SimpleNamespace(),
+ store=store,
+ request_store=TaskExecutionStore(tmp_path / "task_requests"),
+ runtime_store=runtime_store,
+ )
+ terminated: list[int] = []
+ monkeypatch.setattr("core.watches.runtime.pid_alive", lambda pid: pid == 1234)
+ monkeypatch.setattr("core.watches.inspect_process_identity", lambda _pid: identity)
+ monkeypatch.setattr(
+ "core.watches.terminate_process_tree_by_pid",
+ lambda pid, *_args, **_kwargs: terminated.append(pid) or True,
+ )
+
+ async def _run() -> None:
+ await _start_watch_service(service)
+ try:
+ assert runtime_store.load()["watches"] == {}
+ finally:
+ await service.stop()
+
+ asyncio.run(_run())
+ assert terminated == [1234]
+
+
+ ("command", "shell_command"),
+ [
+ ([sys.executable, "-c", "print('watch')"], None),
+ (["/tmp/wait.py"], None),
+ ([], "python3 wait.py --forever"),
+ ],
+ ids=["exec", "shebang-interpreter", "shell-wrapper"],
+)
+def test_managed_watch_service_start_reaps_matching_stale_worker_before_reconcile(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ command: list[str],
+ shell_command: str | None,
+) -> None:
+ store = ManagedWatchStore(tmp_path / "watches.json")
+ runtime_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)
+ service = ManagedWatchService(
+ controller=SimpleNamespace(),
+ store=store,
+ request_store=TaskExecutionStore(tmp_path / "task_requests"),
+ runtime_store=runtime_store,
+ )
+ events: list[tuple[str, int | None]] = []
+
+ monkeypatch.setattr("core.watches.runtime.pid_alive", lambda pid: pid == 4321)
+ monkeypatch.setattr(
+ "core.watches.inspect_process_identity",
+ lambda pid: _live_identity(pid=pid),
+ )
+
+ def fake_terminate(pid, _logger, _label, *, expected_identity):
+ assert expected_identity == identity
+ events.append(("terminate", pid))
+ return True
+
+ def fake_reconcile():
+ events.append(("reconcile", None))
+ return False
+
+ monkeypatch.setattr("core.watches.terminate_process_tree_by_pid", fake_terminate)
+ monkeypatch.setattr(service, "reconcile_watches", fake_reconcile)
+
+ async def _run() -> None:
+ await _start_watch_service(service)
+ await service.stop()
+
+ asyncio.run(_run())
+
+ assert events == [("terminate", 4321), ("reconcile", None)]
+
+
+def test_managed_watch_service_start_does_not_reap_reused_pid(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ store = ManagedWatchStore(tmp_path / "watches.json")
+ runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")
+ 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)
+ service = ManagedWatchService(
+ controller=SimpleNamespace(),
+ store=store,
+ request_store=TaskExecutionStore(tmp_path / "task_requests"),
+ runtime_store=runtime_store,
+ )
+ reconciles = 0
+
+ monkeypatch.setattr("core.watches.runtime.pid_alive", lambda pid: pid == 4321)
+ monkeypatch.setattr(
+ "core.watches.inspect_process_identity",
+ lambda pid: _live_identity(pid=pid, create_time=456.0),
+ )
+ monkeypatch.setattr(
+ "core.watches.terminate_process_tree_by_pid",
+ lambda *_args, **_kwargs: pytest.fail("a reused pid must not be terminated"),
+ )
+
+ def fake_reconcile():
+ nonlocal reconciles
+ reconciles += 1
+ return False
+
+ monkeypatch.setattr(service, "reconcile_watches", fake_reconcile)
+
+ async def _run() -> None:
+ await _start_watch_service(service)
+ await service.stop()
+
+ asyncio.run(_run())
+
+ assert reconciles == 1
+ assert watch.id not in service._recovery_blocked_watch_ids
+
+
+def test_managed_watch_service_start_blocks_respawn_when_worker_marker_changed(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ store = ManagedWatchStore(tmp_path / "watches.json")
+ runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")
+ 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)
+ 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.inspect_process_identity",
+ lambda pid: _live_identity(
+ pid=pid,
+ worker_fingerprint=fingerprint_process_marker("other-watch-worker"),
+ ),
+ )
+ monkeypatch.setattr(
+ "core.watches.terminate_process_tree_by_pid",
+ lambda *_args, **_kwargs: pytest.fail("a changed worker marker must not be terminated"),
+ )
+
+ async def _run() -> None:
+ await _start_watch_service(service)
+ assert watch.id not in service._active_tasks
+ assert runtime_store.load()["watches"][watch.id]["process_identity"]["create_time"] == 123.0
+ await service.stop()
+
+ asyncio.run(_run())
+
+ assert watch.id in service._recovery_blocked_watch_ids
+ assert runtime_store.load()["watches"][watch.id]["pid"] == 4321
+
+
+def test_managed_watch_service_start_blocks_legacy_live_worker_without_identity(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ 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)
+ 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.inspect_process_identity",
+ lambda _pid: _live_identity(),
+ )
+ monkeypatch.setattr(
+ "core.watches.terminate_process_tree_by_pid",
+ lambda *_args, **_kwargs: pytest.fail("a legacy entry must not cause termination"),
+ )
+
+ async def _run() -> None:
+ await _start_watch_service(service)
+ assert watch.id not in service._active_tasks
+ await service.stop()
+
+ asyncio.run(_run())
+
+ assert watch.id in service._recovery_blocked_watch_ids
+ assert runtime_store.load()["watches"][watch.id]["pid"] == 4321
+
+
+def test_managed_watch_service_start_rejects_overflowing_process_identity(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ store = ManagedWatchStore(tmp_path / "watches.json")
+ runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")
+ watch = _add_recovery_watch(store, command=[sys.executable, "wait.py"])
runtime_store.write(
{
"watches": {
- "stale-watch": {
+ watch.id: {
"running": True,
- "pid": 1234,
+ "pid": 4321,
"started_at": "2026-05-15T00:00:00+00:00",
"updated_at": "2026-05-15T00:00:01+00:00",
+ "process_identity": {
+ "pid": 4321,
+ "create_time": 10**1000,
+ "worker_fingerprint": TEST_FINGERPRINT,
+ },
}
}
}
@@ -1061,13 +1534,498 @@ def test_managed_watch_service_start_clears_stale_runtime_state(tmp_path: Path)
runtime_store=runtime_store,
)
+ monkeypatch.setattr("core.watches.runtime.pid_alive", lambda pid: pid == 4321)
+ 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: pytest.fail("a malformed identity must not cause termination"),
+ )
+
async def _run() -> None:
+ await _start_watch_service(service)
+ assert service._running is True
+ assert watch.id in service._recovery_blocked_watch_ids
+ assert watch.id not in service._active_tasks
+ await service.stop()
+
+ asyncio.run(_run())
+
+
+def test_managed_watch_service_start_ignores_dead_recorded_pid(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ 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)
+ service = ManagedWatchService(
+ controller=SimpleNamespace(),
+ store=store,
+ request_store=TaskExecutionStore(tmp_path / "task_requests"),
+ runtime_store=runtime_store,
+ )
+ reconciles = 0
+
+ monkeypatch.setattr("core.watches.runtime.pid_alive", lambda _pid: False)
+ monkeypatch.setattr("core.watches.process_group_exists", lambda *_args: False)
+ monkeypatch.setattr(
+ "core.watches.inspect_process_identity",
+ lambda _pid: pytest.fail("a dead pid must not have its identity inspected"),
+ )
+ monkeypatch.setattr(
+ "core.watches.terminate_process_tree_by_pid",
+ lambda *_args, **_kwargs: pytest.fail("a dead pid must not be terminated"),
+ )
+
+ def fake_reconcile():
+ nonlocal reconciles
+ reconciles += 1
+ return False
+
+ monkeypatch.setattr(service, "reconcile_watches", fake_reconcile)
+
+ async def _run() -> None:
+ await _start_watch_service(service)
+ await service.stop()
+
+ asyncio.run(_run())
+
+ assert reconciles == 1
+
+
+def test_managed_watch_service_start_reaps_group_after_leader_exit(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ store = ManagedWatchStore(tmp_path / "watches.json")
+ 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)
+ service = ManagedWatchService(
+ controller=SimpleNamespace(),
+ store=store,
+ request_store=TaskExecutionStore(tmp_path / "task_requests"),
+ runtime_store=runtime_store,
+ )
+ events: list[str] = []
+
+ monkeypatch.setattr("core.watches.runtime.pid_alive", lambda _pid: False)
+ monkeypatch.setattr("core.watches.process_group_exists", lambda *_args: True)
+ monkeypatch.setattr(
+ "core.watches.terminate_process_group_by_pgid",
+ lambda *_args, **_kwargs: events.append("terminate-group") or True,
+ )
+ monkeypatch.setattr(
+ "core.watches.inspect_process_identity",
+ lambda _pid: pytest.fail("an exited leader must not have its identity inspected"),
+ )
+
+ def fake_reconcile() -> bool:
+ events.append("reconcile")
+ return False
+
+ monkeypatch.setattr(service, "reconcile_watches", fake_reconcile)
+
+ async def _run() -> None:
+ await _start_watch_service(service)
+ await service.stop()
+
+ asyncio.run(_run())
+
+ assert events == ["terminate-group", "reconcile"]
+
+
+def test_managed_watch_service_does_not_reap_unverified_group_after_leader_exit(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ 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)
+ 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: False)
+ monkeypatch.setattr("core.watches.process_group_exists", lambda *_args: True)
+ monkeypatch.setattr(
+ "core.watches.terminate_process_group_by_pgid",
+ lambda *_args, **_kwargs: pytest.fail("an unverified process group must not be terminated"),
+ )
+
+ async def _run() -> None:
+ await _start_watch_service(service)
+ assert watch.id in service._recovery_blocked_watch_ids
+ assert watch.id not in service._active_tasks
+ await service.stop()
+
+ asyncio.run(_run())
+
+
+def test_managed_watch_service_start_keeps_recovery_off_event_loop(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ service = ManagedWatchService(
+ controller=SimpleNamespace(),
+ store=ManagedWatchStore(tmp_path / "watches.json"),
+ request_store=TaskExecutionStore(tmp_path / "task_requests"),
+ runtime_store=WatchRuntimeStateStore(tmp_path / "watch_runtime.json"),
+ )
+ monkeypatch.setattr(service, "_reap_stale_workers", lambda: time.sleep(0.15))
+ monkeypatch.setattr(service, "reconcile_watches", lambda: False)
+
+ async def _run() -> None:
+ started = time.monotonic()
service.start()
- try:
- assert runtime_store.load()["watches"] == {}
- finally:
+ assert time.monotonic() - started < 0.05
+ startup_task = service._startup_task
+ assert startup_task is not None
+ await asyncio.sleep(0.01)
+ assert not startup_task.done()
+ await startup_task
+ await service.stop()
+
+ asyncio.run(_run())
+
+
+def test_managed_watch_service_start_retries_unreadable_runtime_before_reconcile(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ class UnreadableRuntimeStore(WatchRuntimeStateStore):
+ def __init__(self) -> None:
+ self.writes = 0
+ self.readable = False
+
+ def load_for_recovery(self) -> dict:
+ if not self.readable:
+ raise OSError("runtime state is temporarily unavailable")
+ return {"watches": {}}
+
+ def write(self, payload: dict) -> None:
+ self.writes += 1
+
+ store = ManagedWatchStore(tmp_path / "watches.json")
+ runtime_store = UnreadableRuntimeStore()
+ monkeypatch.setattr("core.watches.WATCH_RECONCILE_INTERVAL_SECONDS", 0.01)
+ service = ManagedWatchService(
+ controller=SimpleNamespace(),
+ store=store,
+ request_store=TaskExecutionStore(tmp_path / "task_requests"),
+ runtime_store=runtime_store,
+ )
+ reconciles = 0
+
+ monkeypatch.setattr(
+ "core.watches.terminate_process_tree_by_pid",
+ lambda *_args, **_kwargs: pytest.fail("unreadable state must not cause termination"),
+ )
+
+ def fake_reconcile():
+ nonlocal reconciles
+ reconciles += 1
+ return False
+
+ monkeypatch.setattr(service, "reconcile_watches", fake_reconcile)
+
+ async def _run() -> None:
+ await _start_watch_service(service)
+ assert service._recovery_pending is True
+ assert reconciles == 0
+ assert runtime_store.writes == 0
+ runtime_store.readable = True
+ for _ in range(100):
+ if reconciles:
+ break
+ await asyncio.sleep(0.01)
+ await service.stop()
+
+ with caplog.at_level("WARNING"):
+ asyncio.run(_run())
+
+ assert reconciles >= 1
+ assert runtime_store.writes > 0
+ assert "Unable to read prior watch runtime state" in caplog.text
+
+
+def test_managed_watch_service_start_retries_malformed_runtime_before_reconcile(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ store = ManagedWatchStore(tmp_path / "watches.json")
+ runtime_path = tmp_path / "watch_runtime.json"
+ runtime_path.write_text("{not-json", encoding="utf-8")
+ runtime_store = WatchRuntimeStateStore(runtime_path)
+ monkeypatch.setattr("core.watches.WATCH_RECONCILE_INTERVAL_SECONDS", 0.01)
+ service = ManagedWatchService(
+ controller=SimpleNamespace(),
+ store=store,
+ request_store=TaskExecutionStore(tmp_path / "task_requests"),
+ runtime_store=runtime_store,
+ )
+ reconciles = 0
+
+ monkeypatch.setattr(
+ "core.watches.terminate_process_tree_by_pid",
+ lambda *_args, **_kwargs: pytest.fail("malformed state must not cause termination"),
+ )
+
+ def fake_reconcile():
+ nonlocal reconciles
+ reconciles += 1
+ return False
+
+ monkeypatch.setattr(service, "reconcile_watches", fake_reconcile)
+
+ async def _run() -> None:
+ await _start_watch_service(service)
+ assert service._recovery_pending is True
+ assert reconciles == 0
+ runtime_path.write_text('{"watches": {}}', encoding="utf-8")
+ for _ in range(100):
+ if reconciles:
+ break
+ await asyncio.sleep(0.01)
+ await service.stop()
+
+ with caplog.at_level("WARNING"):
+ asyncio.run(_run())
+
+ assert reconciles >= 1
+ assert "Unable to read prior watch runtime state" in caplog.text
+
+
+def test_managed_watch_service_start_retries_unavailable_watch_list_before_reconcile(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ 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)
+ service = ManagedWatchService(
+ controller=SimpleNamespace(),
+ store=store,
+ request_store=TaskExecutionStore(tmp_path / "task_requests"),
+ runtime_store=runtime_store,
+ )
+ list_calls = 0
+ available = {"value": False}
+ monkeypatch.setattr("core.watches.WATCH_RECONCILE_INTERVAL_SECONDS", 0.01)
+
+ def failing_list():
+ nonlocal list_calls
+ list_calls += 1
+ if not available["value"]:
+ raise RuntimeError("watch definitions are temporarily unavailable")
+ return store.list_watches()
+
+ monkeypatch.setattr(store, "list_watches_for_recovery", failing_list)
+ monkeypatch.setattr(
+ "core.watches.terminate_process_tree_by_pid",
+ lambda *_args, **_kwargs: pytest.fail("an unavailable watch list must not cause termination"),
+ )
+
+ async def fake_run_watch(_watch_id: str) -> None:
+ await asyncio.Future()
+
+ monkeypatch.setattr(service, "_run_watch", fake_run_watch)
+
+ async def _run() -> None:
+ await _start_watch_service(service)
+ assert service._running is True
+ assert service._recovery_pending is True
+ assert watch.id not in service._active_tasks
+ available["value"] = True
+ for _ in range(100):
+ if watch.id in service._active_tasks:
+ break
+ await asyncio.sleep(0.01)
+ assert watch.id in service._active_tasks
+ await service.stop()
+
+ with caplog.at_level("WARNING"):
+ asyncio.run(_run())
+
+ assert list_calls >= 2
+ assert service._store_reconcile_failures == 0
+ assert "Unable to read managed watch definitions" in caplog.text
+
+
+def test_managed_watch_service_start_does_not_reap_with_malformed_watch_store(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ watches_path = tmp_path / "watches.json"
+ 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)
+ watches_path.write_text("{not-json", encoding="utf-8")
+
+ with caplog.at_level("WARNING"):
+ store = ManagedWatchStore(watches_path)
+ 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: pytest.fail("a malformed watch store must not cause pid inspection"),
+ )
+ monkeypatch.setattr(
+ "core.watches.terminate_process_tree_by_pid",
+ lambda *_args, **_kwargs: pytest.fail("a malformed watch store must not cause termination"),
+ )
+
+ async def _run() -> None:
+ await _start_watch_service(service)
+ assert service._active_tasks == {}
await service.stop()
+ asyncio.run(_run())
+
+ assert "Unable to read managed watch definitions" in caplog.text
+
+
+def test_managed_watch_service_start_preserves_worker_state_when_reap_fails(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ store = ManagedWatchStore(tmp_path / "watches.json")
+ runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")
+ 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)
+ 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.inspect_process_identity", lambda _pid: identity)
+ 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
+ await service.stop()
+
+ asyncio.run(_run())
+
+ assert watch.id in service._recovery_blocked_watch_ids
+ assert runtime_store.load()["watches"][watch.id]["pid"] == 4321
+
+
+def test_managed_watch_service_periodically_unblocks_after_stale_worker_exits(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ store = ManagedWatchStore(tmp_path / "watches.json")
+ runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")
+ 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)
+ service = ManagedWatchService(
+ controller=SimpleNamespace(),
+ store=store,
+ request_store=TaskExecutionStore(tmp_path / "task_requests"),
+ runtime_store=runtime_store,
+ )
+ worker = {"alive": True}
+
+ monkeypatch.setattr("core.watches.WATCH_RECONCILE_INTERVAL_SECONDS", 0.01)
+ monkeypatch.setattr("core.watches.runtime.pid_alive", lambda _pid: worker["alive"])
+ monkeypatch.setattr("core.watches.process_group_exists", lambda *_args: False)
+ monkeypatch.setattr("core.watches.inspect_process_identity", lambda _pid: identity)
+ monkeypatch.setattr("core.watches.terminate_process_tree_by_pid", lambda *_args, **_kwargs: False)
+
+ async def fake_run_watch(_watch_id: str) -> None:
+ await asyncio.Future()
+
+ monkeypatch.setattr(service, "_run_watch", fake_run_watch)
+
+ async def _run() -> None:
+ await _start_watch_service(service)
+ assert watch.id in service._recovery_blocked_watch_ids
+ assert watch.id not in service._active_tasks
+
+ worker["alive"] = False
+ for _ in range(100):
+ if watch.id in service._active_tasks:
+ break
+ await asyncio.sleep(0.01)
+
+ assert watch.id not in service._recovery_blocked_watch_ids
+ assert watch.id not in service._unreaped_runtime_entries
+ assert watch.id in service._active_tasks
+ await service.stop()
+
+ asyncio.run(_run())
+
+
+def test_managed_watch_service_start_without_prior_runtime_state_reconciles_normally(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ store = ManagedWatchStore(tmp_path / "watches.json")
+ runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")
+ watch = _add_recovery_watch(store, command=[sys.executable, "wait.py"])
+ service = ManagedWatchService(
+ controller=SimpleNamespace(),
+ store=store,
+ request_store=TaskExecutionStore(tmp_path / "task_requests"),
+ runtime_store=runtime_store,
+ )
+
+ monkeypatch.setattr(
+ store,
+ "list_watches_for_recovery",
+ lambda: pytest.fail("empty runtime state must not reload watch definitions"),
+ )
+ monkeypatch.setattr(
+ "core.watches.runtime.pid_alive",
+ lambda _pid: pytest.fail("empty runtime state must not inspect any pids"),
+ )
+ monkeypatch.setattr(
+ "core.watches.inspect_process_identity",
+ lambda _pid: pytest.fail("empty runtime state must not inspect any processes"),
+ )
+ monkeypatch.setattr(
+ "core.watches.terminate_process_tree_by_pid",
+ lambda *_args, **_kwargs: pytest.fail("empty runtime state must not cause termination"),
+ )
+
+ async def fake_run_watch(_watch_id: str) -> None:
+ await asyncio.Future()
+
+ monkeypatch.setattr(service, "_run_watch", fake_run_watch)
+
+ async def _run() -> None:
+ await _start_watch_service(service)
+ assert watch.id in service._active_tasks
+ await service.stop()
+
asyncio.run(_run())
@@ -1131,9 +2089,9 @@ def test_managed_watch_service_start_retries_initial_reconcile_error(tmp_path: P
)
async def _run() -> None:
- service.start()
+ await _start_watch_service(service)
assert service._store_error_fused is False
- assert service._store_reconcile_failures == 1
+ assert 1 <= service._store_reconcile_failures < 3
await service.stop()
asyncio.run(_run())
@@ -1151,6 +2109,9 @@ def test_managed_watch_service_ignores_runtime_state_write_failure(tmp_path: Pat
def load(self) -> dict:
return {"watches": {}}
+ def load_for_recovery(self) -> dict:
+ return {"watches": {}}
+
store = ManagedWatchStore(tmp_path / "watches.json")
request_store = TaskExecutionStore(tmp_path / "task_requests")
runtime_store = FailingRuntimeStore()
@@ -1177,7 +2138,7 @@ def test_managed_watch_service_ignores_runtime_state_write_failure(tmp_path: Pat
)
async def _run() -> None:
- service.start()
+ await _start_watch_service(service)
for _ in range(100):
if watch.id not in service._active_tasks:
break
diff --git a/vibe/cli.py b/vibe/cli.py
index ca704b88b..7411d0a91 100644
--- a/vibe/cli.py
+++ b/vibe/cli.py
@@ -46,6 +46,7 @@ from core.caller_context import caller_context_from_env
from core.vibe_agents import VibeAgent, VibeAgentStore, iter_global_agent_files, parse_agent_file, validate_agent_backend
from core.watches import (
DEFAULT_RETRY_EXIT_CODE,
+ WATCH_RECOVERY_ENTRY_TIMEOUT_SECONDS,
WATCH_RECONCILE_INTERVAL_SECONDS,
ManagedWatchStore,
WatchRuntimeStateStore,
@@ -2389,8 +2390,37 @@ def _seconds_since_iso(timestamp: object) -> float | None:
return max(0.0, (datetime.now(timezone.utc) - started_at).total_seconds())
-def _default_watch_startup_timeout_seconds(*, stable_running_seconds: float = WATCH_STARTUP_STABLE_RUNNING_SECONDS) -> float:
- return WATCH_RECONCILE_INTERVAL_SECONDS + stable_running_seconds + WATCH_STARTUP_JITTER_BUFFER_SECONDS
+def _watch_recovery_entry_count(runtime_store: WatchRuntimeStateStore) -> int:
+ try:
+ runtime_state = runtime_store.load_for_recovery()
+ except Exception:
+ return 1
+ runtime_watches = runtime_state.get("watches") if isinstance(runtime_state, dict) else None
+ if not isinstance(runtime_watches, dict):
+ return 1
+ return sum(
+ 1
+ for entry in runtime_watches.values()
+ if isinstance(entry, dict)
+ and entry.get("running") is True
+ and isinstance(entry.get("pid"), int)
+ and not isinstance(entry.get("pid"), bool)
+ and entry["pid"] > 0
+ )
+
+
+def _default_watch_startup_timeout_seconds(
+ *,
+ stable_running_seconds: float = WATCH_STARTUP_STABLE_RUNNING_SECONDS,
+ recovery_entry_count: int = 0,
+) -> float:
+ recovery_budget = max(0, recovery_entry_count) * WATCH_RECOVERY_ENTRY_TIMEOUT_SECONDS
+ return (
+ WATCH_RECONCILE_INTERVAL_SECONDS
+ + recovery_budget
+ + stable_running_seconds
+ + WATCH_STARTUP_JITTER_BUFFER_SECONDS
+ )
def _wait_for_watch_startup(
@@ -2404,7 +2434,10 @@ def _wait_for_watch_startup(
):
inspect_command = f"vibe watch show {watch_id}"
if timeout_seconds is None:
- timeout_seconds = _default_watch_startup_timeout_seconds(stable_running_seconds=stable_running_seconds)
+ timeout_seconds = _default_watch_startup_timeout_seconds(
+ stable_running_seconds=stable_running_seconds,
+ recovery_entry_count=_watch_recovery_entry_count(runtime_store),
+ )
deadline = time.monotonic() + timeout_seconds
while time.monotonic() < deadline:
store.maybe_reload()
diff --git a/vibe/i18n/en.json b/vibe/i18n/en.json
index d48b8a24a..ffe7f1425 100644
--- a/vibe/i18n/en.json
+++ b/vibe/i18n/en.json
@@ -13,6 +13,18 @@
"titleUntitled": "Fork"
},
"harness": {
+ "watch": {
+ "supervisorFailed": "Watch worker supervisor failed: {detail}",
+ "supervisorExitedDuringStartup": "Watch worker supervisor exited during startup.",
+ "unknownSupervisorFailure": "Unknown supervisor failure.",
+ "protocolErrors": {
+ "specTooLarge": "The watch worker specification is too large.",
+ "invalidEncoding": "The watch worker specification is not valid UTF-8.",
+ "invalidJson": "The watch worker specification is not valid JSON.",
+ "unsupportedVersion": "The watch worker specification version is unsupported.",
+ "invalidCommand": "The watch worker command is invalid."
+ }
+ },
"queueCoalesced": {
"summary": "[Avibe Harness] The same watch/task callback fired {count} times within a rolling {window}-second window. The queued callbacks were coalesced into this single Agent turn.",
"messagesLabel": "Coalesced callback messages:",
diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.json
index 43a172ca3..a617acb6f 100644
--- a/vibe/i18n/zh.json
+++ b/vibe/i18n/zh.json
@@ -13,6 +13,18 @@
"titleUntitled": "复刻"
},
"harness": {
+ "watch": {
+ "supervisorFailed": "Watch 监控进程失败:{detail}",
+ "supervisorExitedDuringStartup": "Watch 监控进程在启动期间退出。",
+ "unknownSupervisorFailure": "未知的监控进程错误。",
+ "protocolErrors": {
+ "specTooLarge": "Watch 工作进程配置过大。",
+ "invalidEncoding": "Watch 工作进程配置不是有效的 UTF-8。",
+ "invalidJson": "Watch 工作进程配置不是有效的 JSON。",
+ "unsupportedVersion": "不支持此 Watch 工作进程配置版本。",
+ "invalidCommand": "Watch 工作进程命令无效。"
+ }
+ },
"queueCoalesced": {
"summary": "[Avibe Harness] 同一个 watch/task callback 在滚动 {window} 秒窗口内触发了 {count} 次。已将这些排队 callback 合并为一次 Agent turn。",
"messagesLabel": "已合并的 callback 消息:",