#!/usr/bin/env python3 """Visible, cancellable subprocess runner with heartbeat and receipts.""" 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 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 _resource_snapshot(pid: int) -> dict[str, Any]: 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) cpu = proc.cpu_percent(interval=None) + sum(c.cpu_percent(interval=None) for c in children) return {"cpu_percent": cpu, "rss_bytes": rss, "children": len(children)} except Exception: return {"cpu_percent": None, "rss_bytes": None, "children": None} 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 = 8.0, timeout_s: float | None = None, no_progress_s: float | None = None, ) -> 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 = os.environ.copy() if env: clean_env.update(env) 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, ) status["pid"] = proc.pid try: status["pgid"] = os.getpgid(proc.pid) except Exception: status["pgid"] = proc.pid _atomic_write(status_path, status) last_output = time.monotonic() last_heartbeat = time.monotonic() started = time.monotonic() stop_reader = threading.Event() 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 beat = { "elapsed_s": round(now - started, 1), "log_bytes": log_size, "seconds_since_output": round(now - last_output, 1), **resources, } status["heartbeat"].append(beat) status["last_heartbeat"] = beat _atomic_write(status_path, status) print( f"[heartbeat] {name} elapsed={beat['elapsed_s']}s " f"cpu={beat['cpu_percent']} rss={beat['rss_bytes']} " f"children={beat['children']} log={log_size}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"]) proc.wait(timeout=30) status["exit_code"] = proc.returncode status["ended_at_utc"] = _utc_now() _atomic_write(status_path, status) return status["exit_code"] or 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 if CPU active. status["suspect_stall"] = True _atomic_write(status_path, status) time.sleep(0.2) except KeyboardInterrupt: status["state"] = "interrupted" _terminate_group(status["pgid"]) proc.wait(timeout=30) status["exit_code"] = proc.returncode status["ended_at_utc"] = _utc_now() _atomic_write(status_path, status) raise finally: stop_reader.set() def _terminate_group(pgid: int | None) -> None: if pgid is None: return try: os.killpg(pgid, signal.SIGTERM) except ProcessLookupError: return time.sleep(5) try: os.killpg(pgid, signal.SIGKILL) except ProcessLookupError: return 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=8.0) 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, ) if __name__ == "__main__": raise SystemExit(main())