from __future__ import annotations import os import signal import subprocess import sys import tempfile import time import unittest from pathlib import Path from k2_evalop.common import load_json class IndependentSupervisorIntegrationTest(unittest.TestCase): def test_killed_controller_cannot_orphan_term_ignoring_grandchild(self) -> None: with tempfile.TemporaryDirectory() as td: root = Path(td) fake_bin = root / "bin" fake_bin.mkdir() smi = fake_bin / "nvidia-smi" smi.write_text( "#!/bin/sh\n" "case \"$*\" in\n" " *--query-gpu=*) echo 'GPU-test, NVIDIA H200, 0, 686' ;;\n" " *--query-compute-apps=*) exit 0 ;;\n" " *) exit 2 ;;\n" "esac\n", encoding="utf-8", ) smi.chmod(0o755) grandchild_pid = root / "grandchild.pid" grandchild_code = ( "import os,signal,time; signal.signal(signal.SIGTERM,signal.SIG_IGN); " f"open({str(grandchild_pid)!r},'w').write(str(os.getpid())); time.sleep(60)" ) child_code = ( "import subprocess,sys,time; " f"subprocess.Popen([sys.executable,'-c',{grandchild_code!r}]); time.sleep(60)" ) controller_code = """ import os, subprocess, sys state, log, child = sys.argv[1:4] cmd = [sys.executable, '-m', 'k2_evalop.supervisor', '--state-root', state, '--phase', 'kill_fixture', '--lease-id', 'kill-fixture', '--controller-pid', str(os.getpid()), '--identity-json', '{}', '--command-sha256', '1' * 64, '--log-path', log, '--cwd', state, '--budget-seconds', '100', '--term-margin-seconds', '1', '--kill-grace-seconds', '0.5', '--', sys.executable, '-c', child] raise SystemExit(subprocess.call(cmd)) """ env = os.environ.copy() env["PATH"] = str(fake_bin) + os.pathsep + env.get("PATH", "") controller = subprocess.Popen( [sys.executable, "-c", controller_code, str(root), str(root / "owned.log"), child_code], env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, ) active = root / "leases" / "active" / "kill-fixture.json" deadline = time.time() + 12 while time.time() < deadline and not (active.exists() and grandchild_pid.exists()): time.sleep(0.05) self.assertTrue(active.exists(), "supervisor never opened its active lease") self.assertTrue(grandchild_pid.exists(), "fixture grandchild never started") pid = int(grandchild_pid.read_text()) os.kill(controller.pid, signal.SIGKILL) controller.wait(timeout=5) closed = root / "leases" / "closed" / "kill-fixture.json" deadline = time.time() + 8 while time.time() < deadline and not closed.exists(): time.sleep(0.05) self.assertTrue(closed.exists(), "independent supervisor did not close after controller death") value = load_json(closed) self.assertEqual(value["status"], "failed") self.assertTrue(value["controller_lost"]) self.assertTrue(value["process_group_proven_empty"]) self.assertFalse(active.exists()) self.assertFalse(Path(f"/proc/{pid}").exists(), "TERM-ignoring grandchild survived KILL") if __name__ == "__main__": unittest.main()