#!/usr/bin/env python3 """Visible, cancellable subprocess runner with heartbeat and receipts. POSIX process groups: each task starts a new session (start_new_session). Timeouts / interrupts signal only that task's PGID via killpg — never pkill/killall. """ from __future__ import annotations import argparse import json import os import signal import subprocess import sys import threading import time from datetime import datetime, timezone from pathlib import Path from typing import Any try: import psutil # type: ignore except ImportError: # pragma: no cover psutil = None # Keys that must never leak from a prior TD invocation into ordinary tasks. _TD_POLLUTE_KEYS = ("LD_LIBRARY_PATH", "LD_PRELOAD", "QT_PLUGIN_PATH") def _utc_now() -> str: return datetime.now(timezone.utc).isoformat() def _atomic_write(path: Path, payload: dict[str, Any]) -> None: path.parent.mkdir(parents=True, exist_ok=True) tmp = path.with_suffix(path.suffix + ".tmp") tmp.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8") tmp.replace(path) def _clean_env(extra: dict[str, str] | None = None, *, keep_td_libs: bool = False) -> dict[str, str]: clean = os.environ.copy() if not keep_td_libs: for key in _TD_POLLUTE_KEYS: clean.pop(key, None) if extra: clean.update(extra) return clean def _resource_snapshot(pid: int) -> dict[str, Any]: """Real process metrics only — never invent progress percentages.""" if psutil is None: return {"cpu_percent": None, "rss_bytes": None, "children": None} try: proc = psutil.Process(pid) children = proc.children(recursive=True) rss = proc.memory_info().rss + sum(c.memory_info().rss for c in children) # interval=None returns rate since last call (or 0.0 on first sample). cpu = proc.cpu_percent(interval=None) + sum(c.cpu_percent(interval=None) for c in children) return {"cpu_percent": round(cpu, 1), "rss_bytes": rss, "children": len(children)} except Exception: return {"cpu_percent": None, "rss_bytes": None, "children": None} def _terminate_group(pgid: int | None) -> None: """Kill only the given process group. Never use pkill/killall.""" if pgid is None: return try: os.killpg(pgid, signal.SIGTERM) except ProcessLookupError: return deadline = time.monotonic() + 5.0 while time.monotonic() < deadline: try: os.killpg(pgid, 0) except ProcessLookupError: return time.sleep(0.2) try: os.killpg(pgid, signal.SIGKILL) except ProcessLookupError: return def run_visible( command: list[str], *, cwd: Path | None = None, env: dict[str, str] | None = None, log_path: Path, status_path: Path, name: str = "task", heartbeat_s: float = 5.0, timeout_s: float | None = None, no_progress_s: float | None = None, keep_td_libs: bool = False, ) -> int: log_path.parent.mkdir(parents=True, exist_ok=True) status: dict[str, Any] = { "schema": "prod2u-run-visible-status-v1", "name": name, "command": command, "cwd": str(cwd or Path.cwd()), "state": "running", "started_at_utc": _utc_now(), "pid": None, "pgid": None, "exit_code": None, "log_path": str(log_path), "heartbeat": [], } _atomic_write(status_path, status) clean_env = _clean_env(env, keep_td_libs=keep_td_libs) with log_path.open("w", encoding="utf-8", errors="replace") as log_file: proc = subprocess.Popen( command, cwd=str(cwd) if cwd else None, env=clean_env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1, start_new_session=True, # new POSIX process group / session ) status["pid"] = proc.pid try: status["pgid"] = os.getpgid(proc.pid) except Exception: status["pgid"] = proc.pid _atomic_write(status_path, status) # Prime CPU percent baseline so the first heartbeat is meaningful. _resource_snapshot(proc.pid) last_output = time.monotonic() last_heartbeat = time.monotonic() started = time.monotonic() last_log_bytes = 0 def reader() -> None: nonlocal last_output assert proc.stdout is not None for line in proc.stdout: sys.stdout.write(line) sys.stdout.flush() log_file.write(line) log_file.flush() last_output = time.monotonic() thread = threading.Thread(target=reader, daemon=True) thread.start() try: while True: code = proc.poll() now = time.monotonic() if now - last_heartbeat >= heartbeat_s: resources = _resource_snapshot(proc.pid) log_size = log_path.stat().st_size if log_path.exists() else 0 log_delta = log_size - last_log_bytes last_log_bytes = log_size beat = { "task": name, "elapsed_s": round(now - started, 1), "pid": status["pid"], "pgid": status["pgid"], "log_bytes": log_size, "log_growth_bytes": log_delta, "seconds_since_output": round(now - last_output, 1), **resources, } status["heartbeat"].append(beat) # Cap retained heartbeat history to keep status files small. if len(status["heartbeat"]) > 200: status["heartbeat"] = status["heartbeat"][-100:] status["last_heartbeat"] = beat _atomic_write(status_path, status) print( f"[heartbeat] task={name} elapsed={beat['elapsed_s']}s " f"pid={beat['pid']} pgid={beat['pgid']} " f"cpu={beat['cpu_percent']} rss={beat['rss_bytes']} " f"children={beat['children']} " f"log={log_size}B (+{log_delta}B) " f"quiet={beat['seconds_since_output']}s", flush=True, ) last_heartbeat = now if code is not None: thread.join(timeout=2) status["state"] = "pass" if code == 0 else "fail" status["exit_code"] = code status["ended_at_utc"] = _utc_now() _atomic_write(status_path, status) return code if timeout_s is not None and (now - started) > timeout_s: status["state"] = "timeout" status["timeout_reason"] = "total_timeout" _terminate_group(status["pgid"]) try: proc.wait(timeout=30) except subprocess.TimeoutExpired: _terminate_group(status["pgid"]) proc.wait(timeout=10) status["exit_code"] = 124 status["ended_at_utc"] = _utc_now() _atomic_write(status_path, status) return 124 if no_progress_s is not None: resources = _resource_snapshot(proc.pid) quiet = (now - last_output) > no_progress_s idle_cpu = (resources.get("cpu_percent") or 0) < 1.0 if quiet and idle_cpu: # Diagnostic only — do not kill solely for quiet logs. status["suspect_stall"] = True _atomic_write(status_path, status) time.sleep(0.2) except KeyboardInterrupt: status["state"] = "interrupted" _terminate_group(status["pgid"]) try: proc.wait(timeout=30) except subprocess.TimeoutExpired: _terminate_group(status["pgid"]) status["exit_code"] = proc.returncode status["ended_at_utc"] = _utc_now() _atomic_write(status_path, status) raise def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--name", default="task") parser.add_argument("--cwd", type=Path, default=None) parser.add_argument("--log", type=Path, required=True) parser.add_argument("--status", type=Path, required=True) parser.add_argument("--timeout-s", type=float, default=None) parser.add_argument("--heartbeat-s", type=float, default=5.0) parser.add_argument( "--keep-td-libs", action="store_true", help="Keep LD_LIBRARY_PATH/QT vars (TD subprocess only).", ) parser.add_argument("command", nargs=argparse.REMAINDER) args = parser.parse_args() command = args.command if command and command[0] == "--": command = command[1:] if not command: parser.error("command required after --") return run_visible( command, cwd=args.cwd, log_path=args.log, status_path=args.status, name=args.name, heartbeat_s=args.heartbeat_s, timeout_s=args.timeout_s, keep_td_libs=args.keep_td_libs, ) if __name__ == "__main__": raise SystemExit(main())