A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
Nightly launcher: a refused launch marks the night as run, under the run lock (Refs #2694) (#3007)
Eyal Golanb5dab0ce6e56
diff --git a/tools/nightly_launch.py b/tools/nightly_launch.pyindex 5b6c53b00..8571793c1 100644--- a/tools/nightly_launch.py+++ b/tools/nightly_launch.py@@ -7,7 +7,8 @@ copy of nightly_state.py, so it depends on no checkout's working tree. It takesdedicated clone's own `main` to `origin/main` (resetting and cleaning only that clone, keeping its Unity Library) andruns tools/nightly.py from the clone, so a merged change to the script takes effect on the next night. The clone iscreated by hand at install time (tools/README.md, "Nightly release"): a missing clone is a recorded REFUSED night,-never a clone made here. When a run is in progress the launcher exits 0 and touches nothing.+never a clone made here. A refusal also sets state.json's last_run_day, under the run lock, so the next night does+not record it as MISSED. When a run is in progress the launcher exits 0 and touches nothing.The lock is held only while the clone is prepared: nightly.py takes the same lock itself and would find it taken.@@ -15,13 +16,15 @@ Usage: uv run nightly_launch.py --uv PATH --home JOB_FOLDER"""from __future__ import annotationsimport argparse+import contextlibimport subprocessimport sysfrom datetime import datetimefrom pathlib import Pathfrom typing import Callable-from nightly_state import TZ, Config, Refused, load_config, log_line, notify, record, run_lock, write_refusal_log+from nightly_state import (TZ, Config, Refused, load_config, load_state, log_line, night_of, notify, record, run_lock,+ save_state, write_refusal_log)# What `git clean -x` keeps in the clone: Unity's import cache and the Unity-MCP plugin's NuGet download. The same# list as unity_postmerge.KEEP (a test keeps them equal; this file runs without the checkout, so it cannot import it).@@ -60,7 +63,24 @@ def prepare_clone(cfg: Config, git: Callable[..., str] = _git,raise Refused("clone", f"could not prepare the clone: {type(e).__name__}: {e}") from e-def _refuse(cfg: Config, home: Path, e: Refused, now: datetime) -> None:+def _mark_night(home: Path, now: datetime, *, locked: bool) -> None:+ """Sets state.json's last_run_day to tonight, as nightly.py's run_night does for every night it records, so a+ refused launch is never counted as MISSED on the next night (#2694). Written only under run.lock: `locked` says+ the caller holds it; otherwise it is taken here, and a run that holds it already writes the day itself. A state+ file nightly.py would refuse is left alone (the next night records that refusal as gate=state)."""+ try:+ with (contextlib.nullcontext(True) if locked else run_lock(home)) as held:+ if not held:+ return+ path = home / "state.json"+ state = load_state(path)+ state.last_run_day = night_of(now).isoformat()+ save_state(path, state)+ except (Refused, OSError) as error:+ print(f"could not mark {night_of(now)} as run in {home / 'state.json'}: {error}", file=sys.stderr)+++def _refuse(cfg: Config, home: Path, e: Refused, now: datetime, *, locked: bool = False) -> None:run_dir = home / "runs" / f"{now.astimezone(TZ):%Y%m%d-%H%M%S}"detail = e.detailtry:@@ -73,6 +93,7 @@ def _refuse(cfg: Config, home: Path, e: Refused, now: datetime) -> None:record(home / "LOG.md", cfg.handoff, f"{line} {detail}")except OSError as record_error:print(f"could not record refusal: {record_error}", file=sys.stderr)+ _mark_night(home, now, locked=locked) # after the record, as in run_night, so a failed save keeps the linenotify("Nightly refused", str(e)[:200])print(e, file=sys.stderr)@@ -90,14 +111,21 @@ def main(argv: list[str] | None = None, *, git: Callable[..., str] = _git,except Refused as e: # a corrupt config is a recorded REFUSED night, not a night on defaults_refuse(Config(), a.home, e, now)return 1+ recorded: Refused | None = Nonetry:with run_lock(a.home) as held:if not held:print("nightly_launch: a run is in progress")return 0- prepare_clone(cfg, git, copy)+ try:+ prepare_clone(cfg, git, copy)+ except Refused as e: # recorded while the lock is held, so the state write is under it; re-raised so+ recorded = e # a lock release failure is only a note beside it, never a second record+ _refuse(cfg, a.home, e, now, locked=True)+ raiseexcept Refused as e:- _refuse(cfg, a.home, e, now)+ if e is not recorded: # the lock itself failed+ _refuse(cfg, a.home, e, now)return 1try:return call([a.uv, "run", str(cfg.clone / "tools" / "nightly.py"), "run"])diff --git a/tools/tests/test_nightly_launch.py b/tools/tests/test_nightly_launch.pyindex f5e9f041e..36d5afa67 100644--- a/tools/tests/test_nightly_launch.py+++ b/tools/tests/test_nightly_launch.py@@ -233,3 +233,88 @@ def test_no_nightly_module_pushes_merges_or_deletes_tags():src = "".join((TOOLS / n).read_text() for n in ("nightly.py", "nightly_publish.py", "nightly_state.py", "nightly_checks.py", "nightly_launch.py"))for banned in ("git push", "\"push\", \"--force\"", "--cleanup-tag", "\"tag\", \"-d\"", "pr merge", "push --force"):assert banned not in src+++# #2694 item 5: a launcher refusal is a night that ran, so the next night must not record that day as MISSED.++def _seed_state(home):+ home.mkdir(parents=True, exist_ok=True)+ ns.save_state(home / "state.json", ns.State(boot_baseline=[8000.0], last_run_day="2026-10-26",+ site_pending="0.3.1"))+++def _assert_night_marked(home):+ state = ns.load_state(home / "state.json")+ assert state.last_run_day == "2026-10-28"+ assert state.boot_baseline == [8000.0] and state.site_pending == "0.3.1" # the rest of the state is kept+ assert ns.missed_days(state.last_run_day, ns.night_of(NOW).replace(day=29)) == []+++def _save_checking_the_lock(home, seen):+ real = ns.save_state++ def save(path, state):+ with (home / "run.lock").open("a") as fh: # a second open file: flock conflicts unless nobody holds it+ try:+ fcntl.flock(fh, fcntl.LOCK_EX | fcntl.LOCK_NB)+ fcntl.flock(fh, fcntl.LOCK_UN)+ seen.append(False)+ except BlockingIOError:+ seen.append(True)+ real(path, state)+ return save++[email protected]("failure", ["clone", "launch"])+def test_a_launcher_refusal_marks_the_night_as_run_under_the_lock(tmp_path, monkeypatch, failure):+ home = tmp_path / "job"+ cfg = cfg_for(tmp_path, clone=failure != "clone")+ write_config(home, cfg)+ _seed_state(home)+ monkeypatch.setattr(nl, "notify", lambda *a, **k: None)+ seen: list[bool] = []+ monkeypatch.setattr(nl, "save_state", _save_checking_the_lock(home, seen), raising=False)+ rec = Recorder()++ def call(cmd):+ raise OSError("uv would not start")++ assert nl.main(["--uv", "/opt/uv", "--home", str(home)], git=rec.git, copy=rec.copy, call=call, now=NOW) == 1+ assert f"gate={failure}" in (home / "LOG.md").read_text()+ _assert_night_marked(home)+ assert seen == [True] # the state was written while run.lock was held+++def test_a_corrupt_config_refusal_marks_the_night_as_run(tmp_path, monkeypatch):+ home = tmp_path / "job"+ _seed_state(home)+ (home / "config.json").write_text("{not json")+ monkeypatch.setattr(nl, "notify", lambda *a, **k: None)+ monkeypatch.setattr(nl, "Config", lambda: ns.Config(handoff=tmp_path / "HANDOFF.md"))+ rec, ran = Recorder(), []+ assert nl.main(["--uv", "/opt/uv", "--home", str(home)], git=rec.git, copy=rec.copy, call=ran.append, now=NOW) == 1+ assert "gate=config" in (home / "LOG.md").read_text()+ _assert_night_marked(home)+++def test_a_launcher_refusal_leaves_a_corrupt_state_file_alone(tmp_path, monkeypatch, capsys):+ home = tmp_path / "job"+ cfg = cfg_for(tmp_path, clone=False)+ write_config(home, cfg)+ (home / "state.json").write_text("{not json")+ monkeypatch.setattr(nl, "notify", lambda *a, **k: None)+ rec, ran = Recorder(), []+ assert nl.main(["--uv", "/opt/uv", "--home", str(home)], git=rec.git, copy=rec.copy, call=ran.append, now=NOW) == 1+ assert "gate=clone" in (home / "LOG.md").read_text() # the refusal is still recorded+ assert (home / "state.json").read_text() == "{not json" # nightly.py refuses it itself, as gate=state+ assert "could not mark" in capsys.readouterr().err+++def test_a_launcher_refusal_with_no_state_file_starts_one(tmp_path, monkeypatch):+ home = tmp_path / "job"+ cfg = cfg_for(tmp_path, clone=False)+ write_config(home, cfg)+ monkeypatch.setattr(nl, "notify", lambda *a, **k: None)+ rec, ran = Recorder(), []+ assert nl.main(["--uv", "/opt/uv", "--home", str(home)], git=rec.git, copy=rec.copy, call=ran.append, now=NOW) == 1+ assert ns.load_state(home / "state.json").last_run_day == "2026-10-28"