A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
Keep nightly managed gates under the machine lock (#1968)
Eyal Golan17607c76ec39
diff --git a/changelog.d/nightly-managed-lock.md b/changelog.d/nightly-managed-lock.mdnew file mode 100644index 000000000..629ba9e19--- /dev/null+++ b/changelog.d/nightly-managed-lock.md@@ -0,0 +1,2 @@+- Keep nightly managed gates and compiler shutdown under the shared machine lock, with node reuse and shared+ compilation disabled.diff --git a/tools/build_sim_for_unity.py b/tools/build_sim_for_unity.pyindex cfc6fab12..2f283c73e 100644--- a/tools/build_sim_for_unity.py+++ b/tools/build_sim_for_unity.py@@ -14,7 +14,8 @@ def main() -> int:output = REPO / "unity/Assets/Plugins/Statecraft"try:subprocess.run(["dotnet", "publish", str(REPO / "sim/Statecraft.Sim"),- "-c", "Release", "-o", str(output)], cwd=REPO, check=True)+ "-c", "Release", "-o", str(output),+ "-nodeReuse:false", "-p:UseSharedCompilation=false"], cwd=REPO, check=True)except FileNotFoundError:print("Cannot find dotnet. Install the .NET SDK and add it to PATH (see docs/dev-setup.md).",file=sys.stderr)diff --git a/tools/machine_lock.py b/tools/machine_lock.pyindex b2be1c82c..886a4bbbc 100644--- a/tools/machine_lock.py+++ b/tools/machine_lock.py@@ -38,7 +38,7 @@ import signalimport subprocessimport sysimport time-from contextlib import ExitStack+from contextlib import ExitStack, contextmanagerfrom pathlib import PathLOCK = Path(os.environ.get("STATECRAFT_MACHINE_LOCK", str(Path.home() / ".cache" / "statecraft" / "machine.lock")))@@ -153,14 +153,25 @@ def stop_command_group(child: subprocess.Popen, grace: float = 1.0) -> None:time.sleep(0.02)-def main(argv: list[str] | None = None) -> int:- a = parse(sys.argv[1:] if argv is None else argv)+@contextmanager+def hold(*, exclusive: bool = False):+ """Hold the canonical fair gate while cooperating Python tools run several related commands.++ Acquisition has no deadline: a waiting holder is never cancelled merely because its work deadline expired.+ Callers must check that deadline after acquisition, before starting their commands.+ """LOCK.parent.mkdir(parents=True, exist_ok=True)- with open(GATE, "a+") as gate, open(LOCK, "a+") as f, ExitStack() as reservations:- print(f"machine_lock: taking the machine lock ({'exclusive' if a.exclusive else 'shared'})", flush=True)+ with open(GATE, "a+") as gate, open(LOCK, "a+") as lock:+ print(f"machine_lock: taking the machine lock ({'exclusive' if exclusive else 'shared'})", flush=True)fcntl.flock(gate, fcntl.LOCK_EX)- fcntl.flock(f, fcntl.LOCK_EX if a.exclusive else fcntl.LOCK_SH)+ fcntl.flock(lock, fcntl.LOCK_EX if exclusive else fcntl.LOCK_SH)fcntl.flock(gate, fcntl.LOCK_UN)+ yield+++def main(argv: list[str] | None = None) -> int:+ a = parse(sys.argv[1:] if argv is None else argv)+ with hold(exclusive=a.exclusive), ExitStack() as reservations:if a.shared and a.wait_unity:unity_lock = reservations.enter_context(open(UNITY_LOCK, "a+"))fcntl.flock(unity_lock, fcntl.LOCK_EX)diff --git a/tools/nightly.py b/tools/nightly.pyindex ca7c3082f..919a195e4 100644--- a/tools/nightly.py+++ b/tools/nightly.py@@ -50,7 +50,8 @@ class ProcRunner(Runner):self.grace = gracedef run(self, cmd: list[str], *, cwd: Path, log: Path, deadline: float,- env: dict[str, str] | None = None, holder: Path | None = None) -> int:+ env: dict[str, str] | None = None, holder: Path | None = None,+ stop_on_interrupt: bool = False) -> int:full = dict(os.environ if env is None else env)if holder is not None:holder.unlink(missing_ok=True)@@ -63,6 +64,14 @@ class ProcRunner(Runner):return proc.wait(timeout=max(0.0, deadline - time.monotonic()))except subprocess.TimeoutExpired:pass+ except BaseException as primary:+ # Managed phases already hold the lock. Default callers may still be waiting for one.+ if stop_on_interrupt:+ try:+ self._stop_group(proc)+ except BaseException as cleanup:+ primary.add_note(f"managed child cleanup raised {type(cleanup).__name__}: {cleanup}")+ raiseif holder is not None:self._stop_holder(holder)self._stop_group(proc)@@ -87,18 +96,20 @@ class ProcRunner(Runner):def _stop_group(self, proc: subprocess.Popen) -> None:try:- os.killpg(proc.pid, signal.SIGTERM)- proc.wait(timeout=self.grace)- except (ProcessLookupError, subprocess.TimeoutExpired):- pass- try: # always: a member that ignores SIGTERM (a build's grandchild) must not outlive the deadline- os.killpg(proc.pid, signal.SIGKILL)- except ProcessLookupError:- pass- try:- proc.wait(timeout=self.grace + 5)- except subprocess.TimeoutExpired:- pass+ try:+ os.killpg(proc.pid, signal.SIGTERM)+ proc.wait(timeout=self.grace)+ except (ProcessLookupError, subprocess.TimeoutExpired):+ pass+ finally: # a second interrupt during the grace period must not skip the final kill and reap+ try:+ os.killpg(proc.pid, signal.SIGKILL)+ except ProcessLookupError:+ pass+ try:+ proc.wait(timeout=self.grace + 5)+ except subprocess.TimeoutExpired:+ passdef capture(self, cmd: list[str], *, cwd: Path, timeout: float = 300) -> str:try:@@ -213,35 +224,79 @@ def _limit(night: Night, minutes: float) -> float:def _step(night: Night, runner: Runner, name: str, cmd: list[str], minutes: float,- env: dict[str, str] | None = None) -> tuple[int, str]:+ env: dict[str, str] | None = None, *, stop_on_interrupt: bool = False) -> tuple[int, str]:log = night.run_dir / f"{name}.log"- code = runner.run(cmd, cwd=night.cfg.clone, log=log, deadline=_limit(night, minutes), env=env)+ kwargs = {"stop_on_interrupt": True} if stop_on_interrupt else {}+ code = runner.run(cmd, cwd=night.cfg.clone, log=log, deadline=_limit(night, minutes), env=env, **kwargs)return code, log.read_text(encoding="utf-8", errors="replace") if log.is_file() else ""def run_gates(night: Night, runner: Runner) -> None:- clone = night.cfg.clone- code, _ = _step(night, runner, "build-sim", ["uv", "run", str(clone / "tools/build_sim_for_unity.py")], 15)- if code != 0:- raise Refused("build-sim", "timed out" if code == 124 else f"build_sim_for_unity exited {code}")- code, text = _step(night, runner, "check", ["bash", "scripts/check.sh", "origin/main"], 45)- why = nightly_checks.check_sh_verdict(text, code)- if why:- raise Refused("check", "timed out" if code == 124 else why)- code, text = _step(night, runner, "release-gate", ["bash", "scripts/oss/release_gate.sh"], 60)- why = nightly_checks.release_gate_verdict(text, code)- if why:- raise Refused("release-gate", "timed out" if code == 124 else why)- for locale in ("he_IL", "en_US"):- lang = f"{locale}.UTF-8"- env = {**os.environ, "LANG": lang, "LC_ALL": lang}- code, text = _step(night, runner, f"sim-{locale}",- ["dotnet", "test", "sim/Statecraft.sln", "-c", "Release", "--nologo"], 30, env)- failed, total = nightly_checks.dotnet_totals(text)- if code == 124:- raise Refused(f"sim-{locale}", "timed out")- if code != 0 or failed or total == 0:- raise Refused(f"sim-{locale}", f"dotnet test exited {code}: {failed} failed of {total} tests")+ base_env = {**os.environ, "MSBUILDDISABLENODEREUSE": "1", "DOTNET_CLI_USE_MSBUILD_SERVER": "0",+ "UseSharedCompilation": "false"}++ def admitted():+ check_window(night)+ if time.monotonic() >= night.deadline:+ raise Refused("managed-deadline", "work deadline expired before a managed command could start")++ def step(name, cmd, minutes, env=None):+ admitted()+ return _step(night, runner, name, cmd, minutes, base_env if env is None else env, stop_on_interrupt=True)++ check_window(night)+ with unity_postmerge.machine_lock.hold():+ # A long acquisition must drain normally; expired work starts no child after it gets the lock.+ admitted()+ pending = None+ try:+ clone = night.cfg.clone+ code, _ = step("build-sim", ["uv", "run", str(clone / "tools/build_sim_for_unity.py")], 15)+ if code != 0:+ raise Refused("build-sim", "timed out" if code == 124 else f"build_sim_for_unity exited {code}")+ code, text = step("check", ["bash", "scripts/check.sh", "origin/main"], 45)+ why = nightly_checks.check_sh_verdict(text, code)+ if why:+ raise Refused("check", "timed out" if code == 124 else why)+ code, text = step("release-gate", ["bash", "scripts/oss/release_gate.sh"], 60)+ why = nightly_checks.release_gate_verdict(text, code)+ if why:+ raise Refused("release-gate", "timed out" if code == 124 else why)+ for locale in ("he_IL", "en_US"):+ lang = f"{locale}.UTF-8"+ env = {**base_env, "LANG": lang, "LC_ALL": lang}+ code, text = step(f"sim-{locale}",+ ["dotnet", "test", "sim/Statecraft.sln", "-c", "Release", "--nologo",+ "-nodeReuse:false", "-p:UseSharedCompilation=false"], 30, env)+ failed, total = nightly_checks.dotnet_totals(text)+ if code == 124:+ raise Refused(f"sim-{locale}", "timed out")+ if code != 0 or failed or total == 0:+ raise Refused(f"sim-{locale}", f"dotnet test exited {code}: {failed} failed of {total} tests")+ except BaseException as primary:+ pending = primary+ raise+ finally:+ # Preserve only this invocation's primary failure, never an exception handled by its caller.+ shutdown_failure = None+ try:+ code = runner.run(["dotnet", "build-server", "shutdown"], cwd=night.cfg.clone,+ log=night.run_dir / "build-server-shutdown.log",+ deadline=time.monotonic() + 120, env=base_env, stop_on_interrupt=True)+ if code != 0:+ shutdown_failure = f"compiler server shutdown exited {code}"+ except BaseException as error:+ if pending is None and not isinstance(error, (OSError, subprocess.SubprocessError)):+ raise+ shutdown_failure = f"compiler server shutdown raised {type(error).__name__}: {error}"+ if shutdown_failure is not None:+ if pending is None:+ raise Refused("build-server-shutdown", shutdown_failure)+ night.notes.append(shutdown_failure)+ try:+ (night.run_dir / "build-server-shutdown.note").write_text(shutdown_failure + "\n", encoding="utf-8")+ except OSError:+ print(shutdown_failure, file=sys.stderr)def unity_argv(night: Night, unity_args: list[str], *, webgl: bool) -> list[str]:diff --git a/tools/nightly_state.py b/tools/nightly_state.pyindex 17a50ebea..a3649a4a5 100644--- a/tools/nightly_state.py+++ b/tools/nightly_state.py@@ -65,7 +65,8 @@ class Runner(Protocol):at the deadline. `capture` raises Refused("command", ...) on a non-zero exit."""def run(self, cmd: list[str], *, cwd: Path, log: Path, deadline: float,- env: dict[str, str] | None = None, holder: Path | None = None) -> int: ...+ env: dict[str, str] | None = None, holder: Path | None = None,+ stop_on_interrupt: bool = False) -> int: ...def capture(self, cmd: list[str], *, cwd: Path, timeout: float = 300) -> str: ...diff --git a/tools/tests/conftest.py b/tools/tests/conftest.pyindex 55f01b9a5..3e2d8022c 100644--- a/tools/tests/conftest.py+++ b/tools/tests/conftest.py@@ -45,7 +45,7 @@ class FakeRunner(Runner):return code, out, effectraise AssertionError(f"unexpected command {cmd}")- def run(self, cmd, *, cwd, log, deadline, env=None, holder=None):+ def run(self, cmd, *, cwd, log, deadline, env=None, holder=None, stop_on_interrupt=False):code, out, effect = self._match(cmd)Path(log).parent.mkdir(parents=True, exist_ok=True)Path(log).write_text(out, encoding="utf-8")diff --git a/tools/tests/test_build_sim_for_unity.py b/tools/tests/test_build_sim_for_unity.pyindex f01d73d69..5cf402367 100644--- a/tools/tests/test_build_sim_for_unity.py+++ b/tools/tests/test_build_sim_for_unity.py@@ -17,7 +17,8 @@ class BuildSimForUnityTests(unittest.TestCase):def publish(command, **kwargs):self.assertEqual(command, ["dotnet", "publish", str(repo / "sim/Statecraft.Sim"),- "-c", "Release", "-o", str(output)])+ "-c", "Release", "-o", str(output),+ "-nodeReuse:false", "-p:UseSharedCompilation=false"])self.assertEqual(kwargs, {"cwd": repo, "check": True})output.mkdir(parents=True)for name in ("Statecraft.Sim.dll", "YamlDotNet.dll"):diff --git a/tools/tests/test_machine_lock.py b/tools/tests/test_machine_lock.pyindex 3e5fbfd3e..c1188d31d 100644--- a/tools/tests/test_machine_lock.py+++ b/tools/tests/test_machine_lock.py@@ -219,3 +219,34 @@ def test_a_shared_wait_timeout_does_not_launch_and_releases_its_locks(tmp_path):assert not marker.exists(), "a command started after the Unity wait timed out"assert run("idle", "raise SystemExit(7)").returncode == 7assert run("idle", command).returncode == 0 and marker.exists()++[email protected]("raises", [False, True])+def test_python_hold_uses_the_same_shared_lock_and_releases_on_exit(tmp_path, monkeypatch, raises):+ lock, gate = tmp_path / "machine.lock", tmp_path / "machine.lock.gate"+ monkeypatch.setattr(ml, "LOCK", lock)+ monkeypatch.setattr(ml, "GATE", gate)++ def held():+ with ml.hold():+ with open(lock, "a+") as exclusive:+ with pytest.raises(BlockingIOError):+ fcntl.flock(exclusive, fcntl.LOCK_EX | fcntl.LOCK_NB)+ with open(lock, "a+") as shared:+ fcntl.flock(shared, fcntl.LOCK_SH | fcntl.LOCK_NB)+ fcntl.flock(shared, fcntl.LOCK_UN)+ with open(gate, "a+") as fairness:+ fcntl.flock(fairness, fcntl.LOCK_EX | fcntl.LOCK_NB)+ fcntl.flock(fairness, fcntl.LOCK_UN)+ if raises:+ raise ValueError("fixture")++ if raises:+ with pytest.raises(ValueError, match="fixture"):+ held()+ else:+ held()+ for path in (lock, gate):+ with open(path, "a+") as released:+ fcntl.flock(released, fcntl.LOCK_EX | fcntl.LOCK_NB)+ fcntl.flock(released, fcntl.LOCK_UN)diff --git a/tools/tests/test_nightly.py b/tools/tests/test_nightly.pyindex 3245f7d55..5802815e0 100644--- a/tools/tests/test_nightly.py+++ b/tools/tests/test_nightly.py@@ -1,9 +1,11 @@import dataclassesimport json+import signalimport subprocessimport sysimport timeimport zipfile+from contextlib import contextmanagerfrom datetime import date, datetimefrom pathlib import Path@@ -15,6 +17,8 @@ import nightlyimport nightly_state as nsfrom conftest import FakeRunner+REAL_POPEN = subprocess.Popen+SHA = "a" * 40OLD = "b" * 40NOW = datetime(2026, 10, 28, 3, 0, tzinfo=ns.TZ)@@ -165,6 +169,13 @@ class Env:@pytest.fixturedef env(tmp_path, monkeypatch, no_processes):+ original_lock = nightly.unity_postmerge.machine_lock.LOCK+ original_gate = nightly.unity_postmerge.machine_lock.GATE+ # Real managed-lock contexts stay on test-local files, never the machine-wide runtime gate.+ monkeypatch.setattr(nightly.unity_postmerge.machine_lock, "LOCK", tmp_path / "machine.lock")+ monkeypatch.setattr(nightly.unity_postmerge.machine_lock, "GATE", tmp_path / "machine.lock.gate")+ assert nightly.unity_postmerge.machine_lock.LOCK != original_lock+ assert nightly.unity_postmerge.machine_lock.GATE != original_gatemonkeypatch.setattr(nightly, "notify", lambda *a, **k: env_notes.append(a))env_notes.clear()return Env(tmp_path, monkeypatch)@@ -450,7 +461,7 @@ class EnvRunner(FakeRunner):super().__init__()self.envs = []- def run(self, cmd, *, cwd, log, deadline, env=None, holder=None):+ def run(self, cmd, *, cwd, log, deadline, env=None, holder=None, stop_on_interrupt=False):self.envs.append((list(cmd), env, holder))return super().run(cmd, cwd=cwd, log=log, deadline=deadline, env=env, holder=holder)@@ -484,7 +495,7 @@ class LocaleRunner(EnvRunner):super().__init__()self.by_lang = {"he_IL.UTF-8": he, "en_US.UTF-8": en}- def run(self, cmd, *, cwd, log, deadline, env=None, holder=None):+ def run(self, cmd, *, cwd, log, deadline, env=None, holder=None, stop_on_interrupt=False):if cmd[:2] == ["dotnet", "test"]:self.calls.append(list(cmd))self.envs.append((list(cmd), env, holder))@@ -502,6 +513,7 @@ def gates_runner(night, env, *, check=(0, OK_CHECK), rg=(0, "RELEASE GATE OK\n")r.add(["uv", "run", f"{clone}/tools/build_sim_for_unity.py"], 0, "")r.add(["bash", "scripts/check.sh", "origin/main"], *check)r.add(["bash", "scripts/oss/release_gate.sh"], *rg)+ r.add(["dotnet", "build-server", "shutdown"], out="servers stopped")return r@@ -512,10 +524,13 @@ def test_gates_run_in_order_with_both_locales(night, env):["uv", "run", f"{night.cfg.clone}/tools/build_sim_for_unity.py"],["bash", "scripts/check.sh", "origin/main"],["bash", "scripts/oss/release_gate.sh"],- ["dotnet", "test", "sim/Statecraft.sln", "-c", "Release", "--nologo"],- ["dotnet", "test", "sim/Statecraft.sln", "-c", "Release", "--nologo"],+ ["dotnet", "test", "sim/Statecraft.sln", "-c", "Release", "--nologo",+ "-nodeReuse:false", "-p:UseSharedCompilation=false"],+ ["dotnet", "test", "sim/Statecraft.sln", "-c", "Release", "--nologo",+ "-nodeReuse:false", "-p:UseSharedCompilation=false"],+ ["dotnet", "build-server", "shutdown"],]- langs = [(e["LANG"], e["LC_ALL"]) for c, e, _ in r.envs if c[0] == "dotnet"]+ langs = [(e["LANG"], e["LC_ALL"]) for c, e, _ in r.envs if c[:2] == ["dotnet", "test"]]assert langs == [("he_IL.UTF-8", "he_IL.UTF-8"), ("en_US.UTF-8", "en_US.UTF-8")]@@ -543,7 +558,7 @@ def test_a_later_gate_does_not_run_after_a_refusal(night, env):r = gates_runner(night, env, check=(1, OK_CHECK))with pytest.raises(Refused):nightly.run_gates(night, r)- assert not any(c[0] == "dotnet" or c[:2] == ["bash", "scripts/oss/release_gate.sh"] for c in r.calls)+ assert not any(c[:2] == ["dotnet", "test"] or c[:2] == ["bash", "scripts/oss/release_gate.sh"] for c in r.calls)WARM_OK = "UnityMcpGuard warm-up: gate defines in place\n"@@ -557,7 +572,7 @@ class EditRunner(EnvRunner):self.night, self.xml, self.code, self.warm_code = night, xml, code, warm_codeself.warm_log, self.restore_code = warm_log, restore_code- def run(self, cmd, *, cwd, log, deadline, env=None, holder=None):+ def run(self, cmd, *, cwd, log, deadline, env=None, holder=None, stop_on_interrupt=False):self.envs.append((list(cmd), env, holder))self.calls.append(list(cmd))d = self.night.run_dir@@ -729,7 +744,7 @@ class WebRunner(EnvRunner):self.stamped_at_build = []self.restores = 0- def run(self, cmd, *, cwd, log, deadline, env=None, holder=None):+ def run(self, cmd, *, cwd, log, deadline, env=None, holder=None, stop_on_interrupt=False):self.envs.append((list(cmd), env, holder))self.calls.append(list(cmd))if cmd[0] == "git" and cmd[1:3] == ["checkout", "--"]:@@ -890,7 +905,7 @@ class CheckRunner(EnvRunner):super().__init__()self.ok, self.answers, self.cwds = ok, answers or {}, []- def run(self, cmd, *, cwd, log, deadline, env=None, holder=None):+ def run(self, cmd, *, cwd, log, deadline, env=None, holder=None, stop_on_interrupt=False):self.envs.append((list(cmd), env, holder))self.calls.append(list(cmd))self.cwds.append(cwd)@@ -1818,7 +1833,7 @@ class SaveRunner(FakeRunner):super().__init__()self.saved, self.loads, self.runs = saved, list(loads), []- def run(self, cmd, *, cwd, log, deadline, env=None, holder=None):+ def run(self, cmd, *, cwd, log, deadline, env=None, holder=None, stop_on_interrupt=False):self.runs.append(list(cmd))code, text = self.saved if "--first-save" in cmd else self.loads.pop(0)Path(log).parent.mkdir(parents=True, exist_ok=True)@@ -2111,3 +2126,300 @@ def test_a_corrupt_config_on_the_savetest_path_is_recorded_not_an_attribute_erromonkeypatch.setattr(nightly, "notify", lambda *a, **k: None)assert nightly.main(["savetest", "--tag", "v0.3.1-nightly.20261028"]) == 1assert "gate=config" in (job / "LOG.md").read_text()+++def test_managed_gates_hold_the_canonical_shared_lock_until_shutdown(night, env, monkeypatch):+ import fcntl+ r = gates_runner(night, env)+ original = r.run+ seen = []++ def probe(cmd, **kwargs):+ with open(nightly.unity_postmerge.machine_lock.LOCK, "a+") as other:+ try:+ fcntl.flock(other, fcntl.LOCK_EX | fcntl.LOCK_NB)+ except BlockingIOError:+ pass+ else:+ fcntl.flock(other, fcntl.LOCK_UN)+ pytest.fail("managed stage escaped the canonical shared lock")+ with open(nightly.unity_postmerge.machine_lock.LOCK, "a+") as shared:+ fcntl.flock(shared, fcntl.LOCK_SH | fcntl.LOCK_NB)+ fcntl.flock(shared, fcntl.LOCK_UN)+ with open(nightly.unity_postmerge.machine_lock.GATE, "a+") as gate:+ fcntl.flock(gate, fcntl.LOCK_EX | fcntl.LOCK_NB)+ fcntl.flock(gate, fcntl.LOCK_UN)+ seen.append(cmd[:2])+ return original(cmd, **kwargs)++ monkeypatch.setattr(r, "run", probe)+ nightly.run_gates(night, r)+ assert seen == [["uv", "run"], ["bash", "scripts/check.sh"],+ ["bash", "scripts/oss/release_gate.sh"], ["dotnet", "test"],+ ["dotnet", "test"], ["dotnet", "build-server"]]+ with open(nightly.unity_postmerge.machine_lock.LOCK, "a+") as released:+ fcntl.flock(released, fcntl.LOCK_EX | fcntl.LOCK_NB)+ fcntl.flock(released, fcntl.LOCK_UN)++++def test_managed_gates_disable_reuse_and_shut_down_before_return(night, env):+ r = gates_runner(night, env)+ nightly.run_gates(night, r)+ tests = [cmd for cmd in r.calls if cmd[:2] == ["dotnet", "test"]]+ assert len(tests) == 2+ for cmd in tests:+ assert "-nodeReuse:false" in cmd and "-p:UseSharedCompilation=false" in cmd+ assert len(r.envs) == 6 and all(passed_env is not None for _, passed_env, _ in r.envs)+ for _, passed_env, _ in r.envs:+ assert passed_env["MSBUILDDISABLENODEREUSE"] == "1"+ assert passed_env["DOTNET_CLI_USE_MSBUILD_SERVER"] == "0"+ assert passed_env["UseSharedCompilation"] == "false"+ assert r.calls[-1] == ["dotnet", "build-server", "shutdown"]+++def test_managed_gate_refusal_still_shuts_down_servers(night, env):+ r = gates_runner(night, env, check=(1, OK_CHECK))+ with pytest.raises(Refused) as error:+ nightly.run_gates(night, r)+ assert error.value.gate == "check"+ assert r.calls[-1] == ["dotnet", "build-server", "shutdown"]+++def test_expired_managed_work_after_lock_acquisition_starts_no_command(night, env, monkeypatch):+ from contextlib import contextmanager++ @contextmanager+ def acquired_after_deadline():+ night.deadline = time.monotonic() - 1+ yield++ monkeypatch.setattr(nightly.unity_postmerge.machine_lock, "hold", acquired_after_deadline)+ r = gates_runner(night, env)+ with pytest.raises(Refused) as error:+ nightly.run_gates(night, r)+ assert error.value.gate == "managed-deadline"+ assert r.calls == []++[email protected]("check_failed", [False, True])+def test_compiler_shutdown_failure_refuses_instead_of_passing(night, env, check_failed):+ r = gates_runner(night, env, check=(1 if check_failed else 0, OK_CHECK))+ r.rules.insert(0, (("dotnet", "build-server", "shutdown"), 1, "shutdown failed", None))+ with pytest.raises(Refused) as error:+ nightly.run_gates(night, r)+ assert error.value.gate == ("check" if check_failed else "build-server-shutdown")+ assert r.calls.count(["dotnet", "build-server", "shutdown"]) == 1+ assert r.calls[-1] == ["dotnet", "build-server", "shutdown"]+ if check_failed:+ assert "shutdown" in (night.run_dir / "build-server-shutdown.note").read_text()+ else:+ assert len(r.calls) == 6+++def test_sim_publisher_explicitly_disables_node_and_compiler_reuse(monkeypatch, no_processes, tmp_path):+ import build_sim_for_unity+ monkeypatch.setattr(build_sim_for_unity, "REPO", tmp_path)+ output = tmp_path / "unity/Assets/Plugins/Statecraft"+ output.mkdir(parents=True)+ for name in ("Statecraft.Sim.dll", "YamlDotNet.dll"):+ (output / name).write_bytes(b"fixture")+ calls = []+ monkeypatch.setattr(build_sim_for_unity.subprocess, "run", lambda cmd, **kw: calls.append((cmd, kw)))+ assert build_sim_for_unity.main() == 0+ assert len(calls) == 1+ cmd, kwargs = calls[0]+ assert cmd[:2] == ["dotnet", "publish"]+ assert "-nodeReuse:false" in cmd and "-p:UseSharedCompilation=false" in cmd+ assert kwargs["check"] is True+ assert kwargs["cwd"] == tmp_path and cmd[cmd.index("-o") + 1] == str(output)++[email protected]("primary", [KeyboardInterrupt, SystemExit])[email protected]("cleanup_raises", [False, True])+def test_shutdown_never_replaces_a_primary_interrupt(night, env, monkeypatch, primary, cleanup_raises):+ r = gates_runner(night, env)+ original = r.run+ interruption = primary()++ def run(cmd, **kwargs):+ if cmd[:2] == ["bash", "scripts/check.sh"]:+ raise interruption+ if cmd == ["dotnet", "build-server", "shutdown"]:+ if cleanup_raises:+ raise OSError("cleanup failed")+ return 1+ return original(cmd, **kwargs)++ monkeypatch.setattr(r, "run", run)+ with pytest.raises(primary) as error:+ nightly.run_gates(night, r)+ assert error.value is interruption+ assert "shutdown" in (night.run_dir / "build-server-shutdown.note").read_text()+++def test_mid_sequence_deadline_stops_work_but_keeps_shutdown_budget(night, env, monkeypatch):+ r = gates_runner(night, env)+ r.rules[0] = (*r.rules[0][:3], lambda cmd: setattr(night, "deadline", time.monotonic() - 1))+ original = r.run+ cleanup_deadlines = []++ def run(cmd, **kwargs):+ if cmd == ["dotnet", "build-server", "shutdown"]:+ cleanup_deadlines.append(kwargs["deadline"])+ return original(cmd, **kwargs)++ monkeypatch.setattr(r, "run", run)+ with pytest.raises(Refused) as error:+ nightly.run_gates(night, r)+ assert error.value.gate == "managed-deadline"+ assert r.calls == [["uv", "run", str(night.cfg.clone / "tools/build_sim_for_unity.py")],+ ["dotnet", "build-server", "shutdown"]]+ assert len(cleanup_deadlines) == 1 and cleanup_deadlines[0] > time.monotonic()+++++def test_shutdown_refuses_inside_a_callers_except(night, env):+ r = gates_runner(night, env)+ r.rules.insert(0, (("dotnet", "build-server", "shutdown"), 1, "shutdown failed", None))+ try:+ raise ValueError("handled by caller")+ except ValueError:+ with pytest.raises(Refused) as error:+ nightly.run_gates(night, r)+ assert error.value.gate == "build-server-shutdown"+ assert len(r.calls) == 6++[email protected]("kind", [KeyboardInterrupt, SystemExit])+def test_shutdown_interrupt_propagates_inside_a_callers_except(night, env, monkeypatch, kind):+ r = gates_runner(night, env)+ original = r.run+ raised = kind()+ def run(cmd, **kwargs):+ if cmd == ["dotnet", "build-server", "shutdown"]:+ raise raised+ return original(cmd, **kwargs)+ monkeypatch.setattr(r, "run", run)+ try:+ raise ValueError("handled by caller")+ except ValueError:+ with pytest.raises(kind) as error:+ nightly.run_gates(night, r)+ assert error.value is raised++[email protected]("kind", [KeyboardInterrupt, SystemExit])+def test_managed_child_is_reaped_before_shared_hold_releases(night, env, tmp_path, monkeypatch, kind):+ marker = tmp_path / "child-started"+ instances = []+ real_popen = REAL_POPEN+ interruption = kind()+ class InterruptingPopen(real_popen):+ def __init__(self, *args, **kwargs):+ super().__init__(*args, **kwargs)+ self.injected = False+ instances.append(self)+ def wait(self, timeout=None):+ if not self.injected:+ self.injected = True+ end = time.monotonic() + 10+ while not marker.exists() and time.monotonic() < end:+ time.sleep(.02)+ assert marker.exists(), "infrastructure: owned child never started"+ raise interruption+ return super().wait(timeout)+ argv = [sys.executable, "-c", "import os,pathlib,time;pathlib.Path(" + repr(str(marker)) + ").write_text(str(os.getpid())+' '+str(os.getpgid(0)));time.sleep(120)"]+ real = nightly.ProcRunner(grace=.2)+ class R:+ def run(self, cmd, **kwargs):+ if cmd == ["dotnet", "build-server", "shutdown"]:+ return 0+ return real.run(argv, **kwargs)+ old_hold = nightly.unity_postmerge.machine_lock.hold+ reaped_at_release = []+ @contextmanager+ def checked_hold():+ with old_hold():+ try:+ yield+ finally:+ reaped_at_release.append(bool(instances) and instances[0].poll() is not None)+ monkeypatch.setattr(nightly.unity_postmerge.machine_lock, "hold", checked_hold)+ monkeypatch.setattr(nightly.subprocess, "Popen", InterruptingPopen)+ try:+ with pytest.raises(kind) as error:+ nightly.run_gates(night, R())+ assert error.value is interruption+ assert marker.exists(), "infrastructure: no positive child start proof"+ pid, pgid = map(int, marker.read_text().split())+ assert pid == pgid and pgid != os.getpgid(0)+ assert reaped_at_release == [True], "managed child still running when the shared hold releases"+ with pytest.raises(ProcessLookupError):+ os.killpg(pgid, 0)+ finally:+ for proc in instances:+ if proc.pid != os.getpgid(0):+ try:+ os.killpg(proc.pid, signal.SIGKILL)+ except ProcessLookupError:+ pass+ real_popen.wait(proc, timeout=5)+++def test_interrupt_cleanup_is_opt_in_for_managed_commands(tmp_path, monkeypatch):+ calls = []+ interruption = KeyboardInterrupt()+ class Child:+ def wait(self, timeout):+ raise interruption+ monkeypatch.setattr(nightly.subprocess, "Popen", lambda *args, **kwargs: Child())+ runner = nightly.ProcRunner()+ monkeypatch.setattr(runner, "_stop_group", lambda child: calls.append(child))+ with pytest.raises(KeyboardInterrupt) as error:+ runner.run(["possible-lock-wait"], cwd=tmp_path, log=tmp_path / "log", deadline=time.monotonic() + 5)+ assert error.value is interruption and calls == []+++def test_every_managed_command_opts_into_interrupt_cleanup(night, env, monkeypatch):+ r = gates_runner(night, env)+ original = r.run+ flags = []+ def run(cmd, **kwargs):+ flags.append(kwargs.get("stop_on_interrupt", False))+ return original(cmd, **kwargs)+ monkeypatch.setattr(r, "run", run)+ nightly.run_gates(night, r)+ assert flags == [True] * 6+++def test_second_interrupt_during_grace_still_kills_and_reaps_own_group(tmp_path, monkeypatch):+ marker = tmp_path / "term-resistant-started"+ argv = [sys.executable, "-c", "import os,pathlib,signal,time;signal.signal(signal.SIGTERM,signal.SIG_IGN);pathlib.Path(" + repr(str(marker)) + ").write_text(str(os.getpid()));time.sleep(120)"]+ proc = REAL_POPEN(argv, start_new_session=True)+ original_wait = proc.wait+ injected = False+ def interrupted_wait(timeout=None):+ nonlocal injected+ if not injected:+ injected = True+ raise KeyboardInterrupt()+ return original_wait(timeout=timeout)+ try:+ end = time.monotonic() + 10+ while not marker.exists() and time.monotonic() < end:+ time.sleep(.02)+ assert marker.exists(), "infrastructure: owned TERM-resistant child did not start"+ monkeypatch.setattr(proc, "wait", interrupted_wait)+ with pytest.raises(KeyboardInterrupt):+ nightly.ProcRunner(grace=.2)._stop_group(proc)+ assert proc.poll() is not None+ with pytest.raises(ProcessLookupError):+ os.killpg(proc.pid, 0)+ finally:+ try:+ os.killpg(proc.pid, signal.SIGKILL)+ except ProcessLookupError:+ pass+ original_wait(timeout=5)