A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
machine_lock: keep the lock until the whole command group has stopped (#1731)
Eyal Golan69e613447c6e
diff --git a/tools/machine_lock.py b/tools/machine_lock.pyindex 07979d9b5..b2be1c82c 100644--- a/tools/machine_lock.py+++ b/tools/machine_lock.py@@ -24,10 +24,17 @@ A waiting exclusive request holds the gate until it has the lock, so no new sharrunning ones drain (issue #207; before, a stream of shared jobs starved a profile, review M9).When STATECRAFT_LOCK_HOLDER names a file, it writes "<this pid> <command pid>" there once the command has started:-the holder record tools/unity_postmerge.py uses to stop a hung Unity by its PID (T72)."""+the holder record tools/unity_postmerge.py uses to stop a hung Unity by its PID (T72). The command starts in its own+session/process group; its PID in that unchanged pair is also its process-group ID. SIGTERM, SIGHUP and SIGINT to the+holder are forwarded to that group, followed by bounded TERM/KILL cleanup before the lock is released. A terminal+Ctrl-C no longer reaches the child directly across the new session; the holder forwards SIGINT. Error paths also+retire the whole group. Descendants that deliberately leave the group are outside this lifetime guarantee.+Residual risk on macOS: SIGKILL or an OOM-kill of the holder itself cannot be caught, and there is no PDEATHSIG;+its lock can still close while its workload survives. This does not make holder SIGKILL safe."""import argparseimport fcntlimport os+import signalimport subprocessimport sysimport time@@ -112,6 +119,40 @@ def wait_for_unity(timeout: float, pids=unity_pids, sleep=time.sleep, now=time.msleep(10)+def stop_command_group(child: subprocess.Popen, grace: float = 1.0) -> None:+ """Retire our child's session, including grandchildren, before releasing flock."""+ def send(sig):+ try:+ os.killpg(child.pid, sig)+ return True+ except ProcessLookupError:+ return False+ except PermissionError:+ # Darwin reports EPERM, not ESRCH, for a group holding only zombies: our own not-yet-reaped child+ # (a forwarded signal often kills it first) or orphans awaiting their reaper. That group is retired.+ rows = subprocess.check_output(["ps", "-axo", "pgid=,stat="], text=True)+ if not any(int(parts[0]) == child.pid and not parts[1].startswith("Z")+ for row in rows.splitlines() if len(parts := row.split()) == 2):+ return False+ if sig != 0:+ raise # A live member refused the signal: never treat that as successful retirement.+ return True++ if send(signal.SIGTERM):+ deadline = time.monotonic() + grace+ while time.monotonic() < deadline:+ child.poll() # reap the direct child even if grandchildren outlive it+ if not send(0):+ break+ time.sleep(0.02)+ send(signal.SIGKILL)+ child.wait()+ # Let killed descendants retire too; orphan zombies may await their system reaper.+ deadline = time.monotonic() + grace+ while send(0) and time.monotonic() < deadline:+ time.sleep(0.02)++def main(argv: list[str] | None = None) -> int:a = parse(sys.argv[1:] if argv is None else argv)LOCK.parent.mkdir(parents=True, exist_ok=True)@@ -126,17 +167,49 @@ def main(argv: list[str] | None = None) -> int:if a.wait_unity and not wait_for_unity(a.timeout):print("machine_lock: timed out waiting for Unity")return 3- child = subprocess.Popen(a.command)- if record := os.environ.get(HOLDER_ENV):- tmp = Path(record + ".tmp")- tmp.write_text(f"{os.getpid()} {child.pid}\n")- os.replace(tmp, record)+ child = None+ signals = (signal.SIGTERM, signal.SIGHUP, signal.SIGINT)+ previous = {}+ pending = None+ stopping = False++ def interrupted(signum, frame):+ nonlocal pending, stopping+ if child is None:+ # Popen may have spawned but not returned its handle yet. Defer until ownership is known.+ pending = pending or signum+ return+ try:+ os.killpg(child.pid, signum)+ except (ProcessLookupError, PermissionError):+ pass # gone, or only its zombie is left (Darwin EPERM); stop_command_group below decides+ if not stopping: # a second signal must not abort the cleanup already under way+ stopping = True+ raise SystemExit(128 + signum)+try:+ for sig in signals:+ previous[sig] = signal.signal(sig, interrupted)+ # Do not block signals around spawn: the exec'd child would inherit the blocked mask.+ child = subprocess.Popen(a.command, start_new_session=True)+ if pending is not None:+ interrupted(pending, None)+ if record := os.environ.get(HOLDER_ENV):+ tmp = Path(record + ".tmp")+ tmp.write_text(f"{os.getpid()} {child.pid}\n")+ os.replace(tmp, record)return child.wait()- except BaseException:- child.kill()- child.wait()- raise+ finally:+ # Cleanup must finish under the lock even if another terminal signal arrives.+ stopping = True+ for sig in previous:+ signal.signal(sig, signal.SIG_IGN)+ try:+ if child is not None:+ stop_command_group(child)+ finally:+ for sig, handler in previous.items():+ signal.signal(sig, handler)if __name__ == "__main__":diff --git a/tools/tests/test_machine_lock_group.py b/tools/tests/test_machine_lock_group.pynew file mode 100644index 000000000..b6f3334e3--- /dev/null+++ b/tools/tests/test_machine_lock_group.py@@ -0,0 +1,204 @@+"""Real subprocess lifetime tests; every lock is a tmp_path throwaway."""+import os+import signal+import subprocess+import sys+import time+from pathlib import Path++import pytest++pytest.importorskip('fcntl')+import machine_lock as ml+++def wait_for(predicate, seconds=6):+ deadline = time.monotonic() + seconds+ while time.monotonic() < deadline:+ if predicate():+ return+ time.sleep(.02)+ assert predicate(), 'process/receipt did not reach expected state'+++def live(pid):+ p = subprocess.run(['ps', '-p', str(pid), '-o', 'stat='], capture_output=True, text=True)+ return p.returncode == 0 and bool(p.stdout.strip()) and not p.stdout.strip().startswith('Z')+++def cleanup(procs, pids):+ # Test-owned receipts only; old-main red must not leave orphan sleepers.+ for pid in pids:+ if live(pid):+ try:+ os.kill(pid, signal.SIGKILL)+ except ProcessLookupError:+ pass+ for p in procs:+ if p.poll() is None:+ p.kill()+ p.wait(timeout=8)++[email protected]('sig', [signal.SIGTERM, signal.SIGHUP, signal.SIGINT])+def test_holder_signal_retires_whole_group_before_shared_waiter(tmp_path, sig):+ record = tmp_path / 'holder'+ child_pid = tmp_path / 'child'+ grand_pid = tmp_path / 'grand'+ ready = tmp_path / 'ready'+ child = tmp_path / 'child.py'+ # Descendants ignore catchable signals: escalation must retire both.+ grand_code = ('import os,signal,time; from pathlib import Path; '+ 'signal.signal(signal.SIGTERM,signal.SIG_IGN); '+ 'signal.signal(signal.SIGHUP,signal.SIG_IGN); '+ 'signal.signal(signal.SIGINT,signal.SIG_IGN); '+ f'Path({str(grand_pid)!r}).write_text(str(os.getpid())); time.sleep(30)')+ child.write_text('import os,signal,subprocess,sys,time\nfrom pathlib import Path\n'+ 'for sig in (signal.SIGTERM,signal.SIGHUP,signal.SIGINT): signal.signal(sig,signal.SIG_IGN)\n'+ f'Path({str(child_pid)!r}).write_text(str(os.getpid()))\n'+ f'p=subprocess.Popen([sys.executable,"-c",{grand_code!r}])\n'+ f'while not Path({str(grand_pid)!r}).exists(): time.sleep(.01)\n'+ f'Path({str(ready)!r}).touch()\n'+ 'p.wait()\n')+ env = {**os.environ, 'STATECRAFT_MACHINE_LOCK': str(tmp_path / 'machine.lock'), ml.HOLDER_ENV: str(record)}+ error_log = (tmp_path / 'holder-stderr.log').open('w')+ p = subprocess.Popen([sys.executable, ml.__file__, '--exclusive', '--', sys.executable, str(child)],+ env=env, stdout=subprocess.DEVNULL, stderr=error_log)+ procs = [p]+ pids = []+ try:+ wait_for(lambda: ready.exists() and record.exists())+ pids = [int(child_pid.read_text()), int(grand_pid.read_text())]+ assert list(map(int, record.read_text().split())) == [p.pid, pids[0]]+ probe = ('import subprocess,sys; '+ f'pids={pids!r}; '+ 'states=[subprocess.run(["ps","-p",str(p),"-o","stat="],capture_output=True,text=True).stdout.strip() for p in pids]; '+ 'print(repr(states),flush=True); '+ 'sys.exit(1 if any(s and not s.startswith("Z") for s in states) else 0)')+ wenv = {k: v for k, v in env.items() if k != ml.HOLDER_ENV}+ waiter = subprocess.Popen([sys.executable, ml.__file__, '--shared', '--', sys.executable, '-c', probe],+ env=wenv, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)+ procs.append(waiter)+ os.kill(p.pid, sig)+ stdout, stderr = waiter.communicate(timeout=10)+ assert waiter.returncode == 0, (stdout, stderr, 'shared acquired before workloads retired')+ assert p.wait(timeout=8) == 128 + sig, (tmp_path / 'holder-stderr.log').read_text()+ assert not any(live(pid) for pid in pids)+ finally:+ if not pids:+ pids = [int(f.read_text()) for f in (child_pid, grand_pid) if f.exists()]+ cleanup(procs, pids)+ error_log.close()+++def test_holder_record_failure_cleans_child_and_grandchild(tmp_path):+ ready = tmp_path / 'ready'+ pids_file = tmp_path / 'pids'+ runner = tmp_path / 'runner.py'+ runner.write_text('import time\nfrom pathlib import Path\nimport machine_lock as ml\n'+ 'original=Path.write_text\n'+ 'def fail(self,*args,**kwargs):\n'+ ' if self.name == "holder.tmp":\n'+ f' deadline=time.monotonic()+5\n while not Path({str(ready)!r}).exists() and time.monotonic()<deadline: time.sleep(.01)\n'+ ' raise OSError("test-only holder receipt failure")\n'+ ' return original(self,*args,**kwargs)\n'+ 'Path.write_text=fail\nraise SystemExit(ml.main())\n')+ grand = 'import signal,time; signal.signal(signal.SIGTERM,signal.SIG_IGN); time.sleep(30)'+ child = ('import os,subprocess,sys,time; from pathlib import Path; '+ f'p=subprocess.Popen([sys.executable,"-c",{grand!r}]); '+ f'Path({str(pids_file)!r}).write_text(str(os.getpid())+" "+str(p.pid)); '+ f'Path({str(ready)!r}).touch(); p.wait()')+ env = {**os.environ, 'PYTHONPATH': str(Path(ml.__file__).parent),+ 'STATECRAFT_MACHINE_LOCK': str(tmp_path / 'machine.lock'), ml.HOLDER_ENV: str(tmp_path / 'holder')}+ p = subprocess.Popen([sys.executable, str(runner), '--exclusive', '--', sys.executable, '-c', child],+ env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)+ pids = []+ try:+ wait_for(lambda: pids_file.exists())+ pids = list(map(int, pids_file.read_text().split()))+ assert p.wait(timeout=10) != 0+ assert not any(live(pid) for pid in pids), 'post-spawn exception leaked descendants'+ finally:+ cleanup([p], pids)++[email protected]('code', [0, 7])+def test_group_ownership_preserves_normal_exit_and_holder_pair(tmp_path, code):+ record = tmp_path / 'holder'+ evidence = tmp_path / 'identity'+ env = {**os.environ, 'STATECRAFT_MACHINE_LOCK': str(tmp_path / 'machine.lock'), ml.HOLDER_ENV: str(record)}+ command = ('import os; from pathlib import Path; '+ f'Path({str(evidence)!r}).write_text(f"{{os.getpid()}} {{os.getppid()}} {{os.getpgid(0)}}"); '+ f'raise SystemExit({code})')+ p = subprocess.run([sys.executable, ml.__file__, '--shared', '--', sys.executable, '-c', command],+ env=env, capture_output=True, text=True, timeout=10)+ assert p.returncode == code, (p.stdout, p.stderr)+ child, parent, group = map(int, evidence.read_text().split())+ assert record.read_text().split() == [str(parent), str(child)]+ assert group == child, 'workload needs its own process group'+++def test_dead_orphan_group_probe_does_not_replace_the_signal_exit(monkeypatch):+ class Child:+ pid = 4242+ def wait(self):+ return 0+ def poll(self):+ return 0+ sent = []+ def killpg(pid, sig):+ assert pid == 4242+ if sig == 0:+ raise PermissionError("Darwin orphan-zombie probe")+ sent.append(sig)+ monkeypatch.setattr(ml.os, "killpg", killpg)+ monkeypatch.setattr(ml.subprocess, "check_output", lambda *a, **k: "4242 Z\\n")+ ml.stop_command_group(Child(), grace=0)+ assert sent == [signal.SIGTERM, signal.SIGKILL]+++def test_real_cleanup_permission_errors_are_not_suppressed(monkeypatch):+ class Child:+ pid = 4242+ def denied(pid, sig):+ raise PermissionError("actual signal denied")+ monkeypatch.setattr(ml.os, "killpg", denied)+ monkeypatch.setattr(ml.subprocess, "check_output", lambda *a, **k: "4242 S\n") # a live member refused it+ with pytest.raises(PermissionError, match="actual signal denied"):+ ml.stop_command_group(Child(), grace=0)+++def test_zombie_only_group_eperm_on_cleanup_signal_counts_as_retired(monkeypatch):+ class Child:+ pid = 4242+ waited = False+ def wait(self):+ self.waited = True+ return -15+ def denied(pid, sig):+ raise PermissionError("Darwin: group holds only our unreaped zombie")+ monkeypatch.setattr(ml.os, "killpg", denied)+ monkeypatch.setattr(ml.subprocess, "check_output", lambda *a, **k: "4242 Z\n")+ child = Child()+ ml.stop_command_group(child, grace=0)+ assert child.waited++[email protected]('sig', [signal.SIGTERM, signal.SIGHUP, signal.SIGINT])+def test_holder_signal_with_default_action_child_exits_128_plus_sig(tmp_path, sig):+ # A plain child dies from the forwarded signal before cleanup runs; on Darwin its unreaped zombie made the+ # cleanup killpg raise EPERM, so the holder crashed with exit 1 (review of the C210 draft, 12 of 12 runs).+ ready = tmp_path / 'ready'+ env = {**os.environ, 'STATECRAFT_MACHINE_LOCK': str(tmp_path / 'machine.lock'), ml.HOLDER_ENV: str(ready)}+ p = subprocess.Popen([sys.executable, ml.__file__, '--exclusive', '--', 'sleep', '30'],+ env=env, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, text=True)+ child = None+ try:+ wait_for(lambda: ready.exists())+ child = int(ready.read_text().split()[1])+ os.kill(p.pid, sig)+ _, stderr = p.communicate(timeout=8)+ assert p.returncode == 128 + sig, stderr+ assert not live(child)+ finally:+ cleanup([p], [child] if child else [])diff --git a/tools/tests/test_machine_lock_signal_delivery.py b/tools/tests/test_machine_lock_signal_delivery.pynew file mode 100644index 000000000..0d2fbb27a--- /dev/null+++ b/tools/tests/test_machine_lock_signal_delivery.py@@ -0,0 +1,50 @@+"""Catchable signals must reach a new session without an inherited blocked mask."""+import os+import signal+import subprocess+import sys+import time+from pathlib import Path++import pytest++pytest.importorskip('fcntl')+import machine_lock as ml++[email protected]('sig', [signal.SIGTERM, signal.SIGHUP, signal.SIGINT])+def test_forwarded_signal_reaches_cooperative_child(tmp_path, sig):+ ready, heard = tmp_path / 'ready', tmp_path / 'heard'+ child_file = tmp_path / 'child'+ script = tmp_path / 'cooperative.py'+ script.write_text('import os,signal,time\nfrom pathlib import Path\n'+ 'def finish(sig,frame):\n'+ f' Path({str(heard)!r}).write_text(str(sig))\n'+ ' raise SystemExit(0)\n'+ 'for sig in (signal.SIGTERM,signal.SIGHUP,signal.SIGINT): signal.signal(sig,finish)\n'+ f'Path({str(child_file)!r}).write_text(str(os.getpid()))\n'+ f'Path({str(ready)!r}).touch()\n'+ 'time.sleep(30)\n')+ env = {**os.environ, 'STATECRAFT_MACHINE_LOCK': str(tmp_path / 'lock')}+ env.pop(ml.HOLDER_ENV, None)+ p = subprocess.Popen([sys.executable, ml.__file__, '--exclusive', '--', sys.executable, str(script)],+ env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)+ try:+ deadline = time.monotonic() + 6+ while not ready.exists() and time.monotonic() < deadline:+ time.sleep(.02)+ assert ready.exists()+ os.kill(p.pid, sig)+ assert p.wait(timeout=6) == 128 + sig+ assert heard.exists(), 'catchable signals must not be inherited as blocked'+ # Cleanup TERM may follow the requested signal; at least a catchable signal must reach the child.+ assert int(heard.read_text()) in (sig, signal.SIGTERM)+ finally:+ if p.poll() is None:+ p.kill()+ p.wait(timeout=6)+ if child_file.exists():+ try:+ os.kill(int(child_file.read_text()), signal.SIGKILL)+ except ProcessLookupError:+ pass