#!/usr/bin/env python3 """Run a local Python check with disposable job-owned caches. Only this invocation's scratch is removed, after its process group has ended. Existing caches, source, dependencies and results are outside this lifecycle. """ import argparse import os import signal import subprocess import tempfile import time from contextlib import suppress from pathlib import Path from k1link.cache_budget import cache_publication def stop_group(process): try: os.killpg(process.pid, signal.SIGTERM) except ProcessLookupError: return deadline = time.monotonic() + 5 while time.monotonic() < deadline: process.poll() try: os.killpg(process.pid, 0) except ProcessLookupError: return time.sleep(0.05) with suppress(ProcessLookupError): os.killpg(process.pid, signal.SIGKILL) process.wait(timeout=5) def run(tool, arguments, *, root=None): root = root or Path(__file__).resolve().parents[1] parent = root / ".runtime/python-checks" ancestor = parent while not ancestor.exists(): ancestor = ancestor.parent if ancestor.resolve() != ancestor: raise ValueError("Check scratch ancestor must be canonical") parent.mkdir(parents=True, exist_ok=True, mode=0o700) if parent.resolve() != parent: raise ValueError("Check scratch must be canonical") with cache_publication(parent, 64 * 1024**2, limit=512 * 1024**2, max_files=50000): if sum(p.is_dir() for p in parent.iterdir()) >= 4: raise ValueError("Four active or unreconciled check directories; new check refused") owned = tempfile.TemporaryDirectory(prefix=tool + "-", dir=parent) with owned as scratch: env = dict( os.environ, PYTHONDONTWRITEBYTECODE="1", RUFF_NO_CACHE="true", MYPY_CACHE_DIR=str(Path(scratch) / "mypy"), TMPDIR=scratch, ) command = [str(root / ".venv/bin/python"), "-m", tool] if tool == "pytest": command += ["-p", "no:cacheprovider", "--basetemp", str(Path(scratch) / "pytest")] if tool == "ruff": command += ["check", "--no-cache"] process = subprocess.Popen( [*command, *arguments], cwd=root, env=env, start_new_session=True ) try: return process.wait() finally: stop_group(process) def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("tool", choices=["pytest", "mypy", "ruff"]) parser.add_argument("arguments", nargs=argparse.REMAINDER) args = parser.parse_args() return run(args.tool, args.arguments) if __name__ == "__main__": raise SystemExit(main())