Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(runtime): log process diagnostics on shutdown

cyhf516e717bf21
diff --git a/core/process_diagnostics.py b/core/process_diagnostics.py
new file mode 100644
index 000000000..75e5ca82d
--- /dev/null
+++ b/core/process_diagnostics.py
@@ -0,0 +1,135 @@
+"""Lightweight process diagnostics for shutdown investigations."""
+
+from __future__ import annotations
+
+import logging
+import os
+import subprocess
+from typing import Callable
+
+
+def _run_ps(args: list[str]) -> str:
+ try:
+ result = subprocess.run(
+ ["ps", *args],
+ check=False,
+ capture_output=True,
+ text=True,
+ timeout=1.5,
+ )
+ except Exception as exc:
+ return f"<ps failed: {exc}>"
+ output = (result.stdout or result.stderr or "").strip()
+ if not output:
+ return "<none>"
+ return output
+
+
+def process_identity(pid: int | None = None) -> dict[str, int | None]:
+ """Return best-effort POSIX process identity fields."""
+ target_pid = pid if pid is not None else os.getpid()
+ identity: dict[str, int | None] = {"pid": target_pid}
+
+ if target_pid == os.getpid():
+ identity["ppid"] = os.getppid()
+ identity["pgid"] = os.getpgrp() if hasattr(os, "getpgrp") else None
+ identity["sid"] = os.getsid(0) if hasattr(os, "getsid") else None
+ return identity
+
+ identity["ppid"] = None
+ try:
+ identity["pgid"] = os.getpgid(target_pid) if hasattr(os, "getpgid") else None
+ except ProcessLookupError:
+ identity["pgid"] = None
+ except Exception:
+ identity["pgid"] = None
+ try:
+ identity["sid"] = os.getsid(target_pid) if hasattr(os, "getsid") else None
+ except ProcessLookupError:
+ identity["sid"] = None
+ except Exception:
+ identity["sid"] = None
+ return identity
+
+
+def process_row(pid: int) -> str:
+ return _run_ps(["-p", str(pid), "-o", "pid=,ppid=,pgid=,sess=,stat=,command="])
+
+
+def _process_table_rows(predicate: Callable[[list[str]], bool], *, limit: int) -> tuple[int, list[str]]:
+ output = _run_ps(["-axo", "pid=,ppid=,pgid=,sess=,stat=,command="])
+ if output.startswith("<"):
+ return 0, [output]
+
+ rows: list[str] = []
+ total = 0
+ for line in output.splitlines():
+ parts = line.split(None, 5)
+ if len(parts) < 6:
+ continue
+ if not predicate(parts):
+ continue
+ total += 1
+ if len(rows) < limit:
+ rows.append(line.strip())
+ return total, rows
+
+
+def _format_rows(total: int, rows: list[str]) -> str:
+ if not rows:
+ return "<none>"
+ suffix = "" if total <= len(rows) else f" ... (+{total - len(rows)} more)"
+ return " | ".join(rows) + suffix
+
+
+def log_process_snapshot(
+ logger: logging.Logger,
+ reason: str,
+ *,
+ pid: int | None = None,
+ limit: int = 30,
+) -> None:
+ """Log a compact process snapshot around service lifecycle events."""
+ if not logger.isEnabledFor(logging.INFO):
+ return
+
+ target_pid = pid if pid is not None else os.getpid()
+ identity = process_identity(target_pid)
+ own_pid = os.getpid()
+ own_pgid = os.getpgrp() if hasattr(os, "getpgrp") else None
+ target_pgid = identity.get("pgid")
+
+ logger.info(
+ "Process snapshot (%s): pid=%s ppid=%s pgid=%s sid=%s service_pid=%s service_pgid=%s",
+ reason,
+ identity.get("pid"),
+ identity.get("ppid"),
+ target_pgid,
+ identity.get("sid"),
+ own_pid,
+ own_pgid,
+ )
+
+ parent_pid = identity.get("ppid")
+ if parent_pid:
+ logger.info("Process snapshot (%s) parent: %s", reason, process_row(parent_pid))
+
+ logger.info("Process snapshot (%s) target: %s", reason, process_row(target_pid))
+
+ if target_pgid is not None:
+ total, rows = _process_table_rows(lambda parts: parts[2] == str(target_pgid), limit=limit)
+ logger.info(
+ "Process snapshot (%s) pgid=%s members (%s): %s",
+ reason,
+ target_pgid,
+ total,
+ _format_rows(total, rows),
+ )
+
+ total, rows = _process_table_rows(lambda parts: parts[1] == str(target_pid), limit=limit)
+ logger.info(
+ "Process snapshot (%s) direct children (%s): %s",
+ reason,
+ total,
+ _format_rows(total, rows),
+ )
diff --git a/core/process_isolation.py b/core/process_isolation.py
index 5e67404ee..a8ad55756 100644
--- a/core/process_isolation.py
+++ b/core/process_isolation.py
@@ -39,6 +39,14 @@ def _safe_signal_process_group(pid: int, sig: int, logger: logging.Logger, label
)
return False
try:
+ logger.info(
+ "Signaling %s process group pgid=%s pid=%s signal=%s service_pgid=%s",
+ label,
+ pgid,
+ pid,
+ sig,
+ own_pgid,
+ )
os.killpg(pgid, sig)
return True
except ProcessLookupError:
@@ -55,6 +63,7 @@ def signal_process_tree(process: Any, sig: int, logger: logging.Logger, label: s
return
try:
+ logger.info("Signaling %s direct process pid=%s signal=%s", label, pid, sig)
if sig == signal.SIGTERM:
process.terminate()
elif sig == KILL_SIGNAL:
diff --git a/main.py b/main.py
index df069b994..b47d9778d 100644
--- a/main.py
+++ b/main.py
@@ -7,8 +7,10 @@ import asyncio
from config.paths import ensure_data_dirs, get_logs_dir
from config.v2_config import V2Config
from core.controller import Controller
+from core.process_diagnostics import log_process_snapshot
from storage.importer import ensure_sqlite_state
from vibe.sentry_integration import init_sentry
+from vibe.runtime import consume_shutdown_intent, shutdown_intent_required
def _build_logging_handlers(logs_dir: str) -> list[logging.Handler]:
@@ -82,6 +84,7 @@ def main():
logger.info("Starting vibe-remote service...")
logger.info(f"Working directory: {config.runtime.default_cwd}")
+ log_process_snapshot(logger, "service-start")
report = prepare_sqlite_state(config)
logger.info(
"SQLite state ready: imported=%s db_path=%s backup_path=%s",
@@ -104,6 +107,17 @@ def main():
shutdown_initiated = True
try:
logger.info(f"Received signal {signum}, shutting down...")
+ log_process_snapshot(logger, f"signal-{signum}")
+ if signum == signal.SIGTERM and shutdown_intent_required():
+ intent = consume_shutdown_intent(os.getpid(), signum)
+ if intent is None:
+ logger.warning(
+ "Ignoring unmanaged SIGTERM for pid=%s because no valid shutdown intent was present",
+ os.getpid(),
+ )
+ shutdown_initiated = False
+ return
+ logger.info("Accepted managed shutdown intent: %s", intent)
except Exception:
pass
try:
diff --git a/modules/agents/codex/transport.py b/modules/agents/codex/transport.py
index 48adf1eac..17586cb09 100644
--- a/modules/agents/codex/transport.py
+++ b/modules/agents/codex/transport.py
@@ -10,6 +10,7 @@ import signal
from asyncio.subprocess import Process
from typing import Any, Awaitable, Callable, Optional
+from core.process_diagnostics import log_process_snapshot, process_identity
from core.process_isolation import KILL_SIGNAL, isolated_subprocess_kwargs, signal_process_tree
logger = logging.getLogger(__name__)
@@ -74,7 +75,15 @@ class CodexTransport:
limit=STREAM_BUFFER_LIMIT,
**isolated_subprocess_kwargs(),
)
- logger.info("Codex app-server started (pid=%s)", self._process.pid)
+ identity = process_identity(self._process.pid)
+ logger.info(
+ "Codex app-server started (pid=%s pgid=%s sid=%s service_pgid=%s)",
+ self._process.pid,
+ identity.get("pgid"),
+ identity.get("sid"),
+ os.getpgrp() if hasattr(os, "getpgrp") else None,
+ )
+ log_process_snapshot(logger, "codex-app-server-start", pid=self._process.pid, limit=10)
# Start background readers
self._reader_task = asyncio.create_task(self._reader_loop())
diff --git a/tests/test_vibe_cli.py b/tests/test_vibe_cli.py
index 11c2dbacc..e2fa5b37a 100644
--- a/tests/test_vibe_cli.py
+++ b/tests/test_vibe_cli.py
@@ -368,6 +368,7 @@ def test_restart_parser_rejects_non_finite_delay_seconds(raw_value):
def test_stop_pid_handles_process_lookup_race(monkeypatch):
monkeypatch.setattr(runtime.os, "name", "posix", raising=False)
monkeypatch.setattr(runtime, "pid_alive", lambda pid: True)
+ monkeypatch.setattr(runtime, "write_shutdown_intent", lambda *args, **kwargs: None)
def _kill(pid, sig):
raise ProcessLookupError()
@@ -380,6 +381,7 @@ def test_stop_pid_handles_process_lookup_race(monkeypatch):
def test_stop_pid_handles_permission_error(monkeypatch):
monkeypatch.setattr(runtime.os, "name", "posix", raising=False)
monkeypatch.setattr(runtime, "pid_alive", lambda pid: True)
+ monkeypatch.setattr(runtime, "write_shutdown_intent", lambda *args, **kwargs: None)
def _kill(pid, sig):
raise PermissionError()
@@ -387,3 +389,54 @@ def test_stop_pid_handles_permission_error(monkeypatch):
monkeypatch.setattr(runtime.os, "kill", _kill)
assert runtime.stop_pid(12345) is False
+
+
+def test_stop_pid_writes_shutdown_intent_before_sigterm(monkeypatch):
+ monkeypatch.setattr(runtime.os, "name", "posix", raising=False)
+ alive_results = iter([True, False])
+ monkeypatch.setattr(runtime, "pid_alive", lambda pid: next(alive_results))
+ calls = []
+
+ def _kill(pid, sig):
+ calls.append((pid, sig))
+
+ monkeypatch.setattr(runtime.os, "kill", _kill)
+ monkeypatch.setattr(runtime.time, "sleep", lambda _seconds: None)
+ monkeypatch.setattr(runtime, "write_shutdown_intent", lambda *args, **kwargs: calls.append(("intent", args, kwargs)))
+
+ assert runtime.stop_pid(12345) is True
+ assert calls[0][0] == "intent"
+ assert calls[0][1] == (12345,)
+ assert calls[0][2]["signum"] == signal.SIGTERM
+ assert calls[1] == (12345, signal.SIGTERM)
+
+
+def test_shutdown_intent_round_trip(tmp_path, monkeypatch):
+ monkeypatch.setattr(paths, "get_vibe_remote_dir", lambda: tmp_path / ".vibe_remote")
+ runtime.ensure_dirs()
+ monkeypatch.setattr(runtime.time, "time", lambda: 1000.0)
+ monkeypatch.setattr(runtime, "get_process_command", lambda pid: f"cmd-{pid}")
+
+ runtime.write_shutdown_intent(12345, reason="test")
+ payload = runtime.consume_shutdown_intent(12345, signal.SIGTERM)
+
+ assert payload is not None
+ assert payload["target_pid"] == 12345
+ assert payload["sender_pid"] == os.getpid()
+ assert not runtime.get_shutdown_intent_path().exists()
+
+
+def test_shutdown_intent_rejects_stale_payload(tmp_path, monkeypatch):
+ monkeypatch.setattr(paths, "get_vibe_remote_dir", lambda: tmp_path / ".vibe_remote")
+ runtime.ensure_dirs()
+ monkeypatch.setattr(runtime.time, "time", lambda: 1000.0)
+ runtime.write_json(
+ runtime.get_shutdown_intent_path(),
+ {
+ "target_pid": 12345,
+ "signum": signal.SIGTERM,
+ "created_at": 900.0,
+ },
+ )
+
+ assert runtime.consume_shutdown_intent(12345, signal.SIGTERM) is None
diff --git a/vibe/runtime.py b/vibe/runtime.py
index c482b48d8..7c06c6a59 100644
--- a/vibe/runtime.py
+++ b/vibe/runtime.py
@@ -23,6 +23,8 @@ from config.v2_config import (
logger = logging.getLogger(__name__)
+SHUTDOWN_INTENT_TTL_SECONDS = 30
+SHUTDOWN_INTENT_ENV = "VIBE_REQUIRE_SHUTDOWN_INTENT"
def get_package_root() -> Path:
@@ -129,6 +131,62 @@ def read_json(path):
return None
+def get_shutdown_intent_path() -> Path:
+ return paths.get_runtime_dir() / "shutdown_intent.json"
+
+
+def write_shutdown_intent(
+ target_pid: int,
+ *,
+ signum: int = signal.SIGTERM,
+ reason: str = "managed-stop",
+) -> None:
+ """Record a short-lived intent before sending a managed shutdown signal."""
+ if not isinstance(target_pid, int) or target_pid <= 0:
+ return
+ payload = {
+ "target_pid": target_pid,
+ "signum": int(signum),
+ "reason": reason,
+ "created_at": time.time(),
+ "sender_pid": os.getpid(),
+ "sender_command": get_process_command(os.getpid()),
+ "target_command": get_process_command(target_pid),
+ }
+ try:
+ write_json(get_shutdown_intent_path(), payload)
+ except OSError:
+ logger.warning("Failed to write shutdown intent for pid=%s", target_pid, exc_info=True)
+
+
+def consume_shutdown_intent(target_pid: int, signum: int = signal.SIGTERM) -> dict | None:
+ """Return and remove a valid managed shutdown intent for this process."""
+ path = get_shutdown_intent_path()
+ payload = read_json(path)
+ if not isinstance(payload, dict):
+ return None
+ try:
+ age = time.time() - float(payload.get("created_at", 0))
+ matches = (
+ payload.get("target_pid") == target_pid
+ and int(payload.get("signum", 0)) == int(signum)
+ and 0 <= age <= SHUTDOWN_INTENT_TTL_SECONDS
+ )
+ except (TypeError, ValueError):
+ matches = False
+ if not matches:
+ return None
+ try:
+ path.unlink(missing_ok=True)
+ except OSError:
+ logger.debug("Failed to remove consumed shutdown intent", exc_info=True)
+ return payload
+
+
+def shutdown_intent_required() -> bool:
+ return os.environ.get(SHUTDOWN_INTENT_ENV, "").lower() in {"1", "true", "yes"}
+
+
def _pid_alive_windows(pid: int) -> bool:
if pid <= 0:
return False
@@ -274,6 +332,7 @@ def stop_pid(pid: int, timeout: float = 5) -> bool:
if os.name == "nt":
return _terminate_process_windows(pid, timeout=timeout)
+ write_shutdown_intent(pid, signum=signal.SIGTERM, reason="stop_pid")
try:
os.kill(pid, signal.SIGTERM)
except ProcessLookupError:
@@ -395,6 +454,7 @@ def start_service():
env={
**os.environ,
"VIBE_DISABLE_STDOUT_LOGGING": "1",
+ SHUTDOWN_INTENT_ENV: "1",
},
)