A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
import dataclasses
import json
import signal
import shutil
import subprocess
import sys
import time
import urllib.parse
import zipfile
from contextlib import contextmanager
from datetime import date, datetime
from pathlib import Path
from types import SimpleNamespace
import pytest
fcntl = pytest.importorskip("fcntl") # nightly imports unity_postmerge, which locks with flock
import nightly
import nightly_state as ns
from conftest import FakeRunner
REAL_POPEN = subprocess.Popen
SHA = "a" * 40
OLD = "b" * 40
NOW = datetime(2026, 10, 28, 3, 0, tzinfo=ns.TZ)
TAG = "v0.3.2"
class FakeGH:
"""The GitHub client as the night uses it. `releases` holds (tag, ID, state) rows, including same-tag replacements;
the last matching row is the tag lookup. `release` keeps older single-release tests readable. `fail` maps a
method name to an exception raised by it (a list raises one per call, then succeeds)."""
def __init__(self, release=None, *, fail=None, previous_tag="v0.3.1"):
self.releases = []
self.release = release
self.fail = fail or {}
self.previous_tag = previous_tag
self.latest = "v0.3.1" # deliberately different from the previous nightly asset tag
self.calls = []
self.baseline = None # a zip the download hands out
@property
def release(self):
return self.releases[-1][2] if self.releases else None
@release.setter
def release(self, value):
if value is None:
self.releases.clear()
elif self.releases:
tag, release_id, _ = self.releases[-1]
self.releases[-1] = (tag, release_id, value)
else:
self.releases.append((TAG, 101, value))
def at_tag(self, tag):
return next((r for r in reversed(self.releases) if r[0] == tag), None)
def _maybe_fail(self, name):
err = self.fail.get(name)
if isinstance(err, list):
err = err.pop(0) if err else None
if err is not None:
raise err
def release_state(self, tag):
self.calls.append(("release_state", tag))
row = self.at_tag(tag)
return row[2] if row else None
def next_version(self, override=None):
if override is None:
self.calls.append(("next_version",))
return "0.3.2"
self.calls.append(("next_version", override))
return ns.next_version([{"tag_name": "v0.3.1", "draft": False}], override=override)
def ensure_tag_available(self, tag):
self.calls.append(("ensure_tag_available", tag))
if self.at_tag(tag) is not None:
raise ns.Refused("tag-exists", f"a {self.release} release already has the tag {tag}")
def delete_draft(self, tag, release_id=...):
# Main calls by tag alone; model that deletion rather than failing on the signature.
row = self.at_tag(tag)
if release_id is ...:
release_id = row[1] if row else None
self.calls.append(("delete_draft", tag, release_id))
if release_id is None or row != (tag, release_id, "draft"):
raise ns.Refused("github-delete", f"{tag} has no matching owned draft ID; check by hand")
self.releases.remove(row)
def dispatch_site(self, deadline):
self.calls.append(("dispatch_site", deadline))
self._maybe_fail("dispatch_site")
def previous_build_tag(self, state_tag):
self.calls.append(("previous_build_tag", state_tag))
return state_tag or self.previous_tag
def download(self, tag, pattern, dest):
self.calls.append(("download", tag, pattern, dest))
self._maybe_fail("download")
return self.baseline
def create_draft(self, tag, sha, notes, assets, *, created=None):
self.calls.append(("create_draft", tag, sha, notes, list(assets)))
self._maybe_fail("create_draft")
self.releases.append((tag, 101, "draft"))
if created is not None:
created(101)
self._maybe_fail("upload")
return 101
def verify_draft(self, tag, local, dest):
self.calls.append(("verify_draft", tag, list(local), dest))
self._maybe_fail("verify_draft")
def publish(self, tag, sha):
self.calls.append(("publish", tag, sha))
self.latest = tag # the edit may succeed before verification fails
self._maybe_fail("publish")
self.release = "published"
def latest_tag(self):
self.calls.append(("latest_tag",))
self._maybe_fail("latest_tag")
return self.latest
def restore_latest(self, previous, failed):
self.calls.append(("restore_latest", previous, failed))
self._maybe_fail("restore_latest")
if self.latest != failed:
return False, self.latest
self.latest = previous
return True, previous
def merged_pr_bodies(self, shas):
self.calls.append(("merged_pr_bodies", set(shas)))
return []
def names(self):
return [c[0] for c in self.calls]
class Env:
"""A tmp job folder, a tmp clone with the files preflight reads, and a FakeRunner answering the clone checks."""
def __init__(self, tmp_path, monkeypatch):
self.job = tmp_path / "job"
self.job.mkdir()
clone = tmp_path / "clone"
(clone / "sim/Statecraft.Sim").mkdir(parents=True)
(clone / "sim/Statecraft.Sim/SimInfo.cs").write_text('public const string Version = "0.3.1";\n')
(clone / "sim/Statecraft.Sim.Tests/golden").mkdir(parents=True)
(clone / "sim/Statecraft.Sim.Tests/golden/manifest.txt").write_text("golden-manifest\n")
(clone / "unity/ProjectSettings").mkdir(parents=True)
(clone / "unity/ProjectSettings/ProjectVersion.txt").write_text("m_EditorVersion: 6000.3.25f1\n")
self.licence = tmp_path / "lic.xml"
self.licence.write_text("x")
self.editor = tmp_path / "Unity"
self.editor.write_text("x")
self.slots = tmp_path / "unity_slots.py"
self.slots.write_text("x")
self.marker = tmp_path / "EXCLUSIVE-WINDOW"
monkeypatch.setattr(nightly.unity_postmerge, "unity_path", lambda version: str(self.editor))
self.cfg = ns.Config(clone=clone, licence=self.licence, unity_slots=self.slots, exclusive_marker=self.marker,
handoff=tmp_path / "HANDOFF.md")
self.runner = FakeRunner()
self.branch, self.head, self.origin, self.dirty = "main", SHA, SHA, ""
self._rules()
self.state_path = self.job / "state.json"
def _rules(self):
clone = str(self.cfg.clone)
# FakeRunner answers fixed text, so rules are rebuilt by set() when a field changes
self.runner.rules.clear()
self.runner.add(["git", "-C", clone, "rev-parse", "--abbrev-ref", "HEAD"], out=self.branch + "\n")
self.runner.add(["git", "-C", clone, "rev-parse", "HEAD"], out=self.head + "\n")
self.runner.add(["git", "-C", clone, "rev-parse", "refs/remotes/origin/main"], out=self.origin + "\n")
self.runner.add(["git", "-C", clone, "status", "--porcelain", "--untracked-files=no"], out=self.dirty)
def set(self, **kw):
for k, v in kw.items():
setattr(self, k, v)
self._rules()
def pre(self, state=None, gh=None, *, now=NOW, manual=False, free=100.0, no_publish=False, **kw):
return nightly.preflight(self.cfg, state or ns.State(), self.runner, gh or FakeGH(), job=self.job, now=now,
manual=manual, free_gb=lambda p: free, no_publish=no_publish, **kw)
def night(self, state=None, gh=None, *, now=NOW, manual=False, free=100.0, no_publish=False, **kw):
if state is not None:
ns.save_state(self.state_path, state)
return nightly.run_night(self.cfg, self.state_path, self.job, self.runner, gh or FakeGH(), None, now=now,
manual=manual, no_publish=no_publish, free_gb=lambda p: free, **kw)
def log(self):
p = self.job / "LOG.md"
return p.read_text() if p.exists() else ""
@pytest.fixture
def 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_gate
monkeypatch.setattr(nightly, "notify", lambda *a, **k: env_notes.append(a))
env_notes.clear()
return Env(tmp_path, monkeypatch)
env_notes: list = []
def gate_of(env, **kw):
with pytest.raises(ns.Stop) as e:
env.pre(**kw)
return e.value
def read_pending_with_old_state(monkeypatch):
# Adapt only deserialization for baseline behavior tests. Main's State and run_night still do the work;
# raw JSON assertions below must detect missing persistence, not unknown-key rejection.
load = ns.load_state
def read(path):
if "latest_recovery_pending" in {f.name for f in dataclasses.fields(ns.State)}:
return load(path)
raw = json.loads(path.read_text())
pending = raw.pop("latest_recovery_pending", None)
state = ns._state_from(raw)
state.latest_recovery_pending = SimpleNamespace(**pending) if pending is not None else None
return state
monkeypatch.setattr(nightly, "load_state", read)
def test_a_clean_preflight_builds_the_night(env):
n = env.pre()
assert (n.sha, n.version, n.tag, n.day) == (SHA, "0.3.2", TAG, date(2026, 10, 28))
assert n.manifest.strip() == "golden-manifest"
assert n.run_dir == env.job / "runs" / "20261028-030000" and n.job == env.job
assert n.deadline > time.monotonic()
def test_preflight_selects_the_numeric_max_across_scripted_release_pages(env):
from nightly_publish import GitHub
cmd = ["gh", "api", f"repos/{env.cfg.repo_slug}/releases?per_page=100", "--paginate", "--slurp"]
env.runner.add(cmd, out=json.dumps([
[{"tag_name": "v0.9.9", "draft": False}, {"tag_name": "v99.0.0", "draft": True}],
[{"tag_name": "v0.10.0", "draft": False}, {"tag_name": "v99.0.0-nightly.20261028", "draft": False}],
]))
env.runner.add(["gh", "release", "view"], code=1,
effect=lambda cmd: (_ for _ in ()).throw(ns.Refused("command", "release not found")))
env.runner.add(["git", "-C", str(env.cfg.clone), "tag", "--list", "v0.10.1"])
env.runner.add(["git", "-C", str(env.cfg.clone), "ls-remote", "origin", "refs/tags/v0.10.1",
"refs/tags/v0.10.1^{}"])
gh = GitHub(env.runner, env.cfg.repo_slug, env.cfg.clone)
n = env.pre(gh=gh)
assert (n.version, n.tag) == ("0.10.1", "v0.10.1") and cmd in env.runner.calls
def test_an_unchanged_main_is_skipped(env):
st = ns.State(last_published=ns.Published("v0.3.0-nightly.20261027", SHA, "0.3.0", {}, None))
assert env.night(st) == "SKIPPED"
assert "SKIPPED" in env.log()
assert all(c[0] == "git" for c in env.runner.calls) # no Unity, no gh write
assert env.state_path.exists() and ns.load_state(env.state_path).last_run_day == "2026-10-28"
@pytest.mark.parametrize("tag", ["v0.3.1-nightly.20261027", "v0.3.2", "unrelated"])
def test_skip_uses_the_saved_sha_before_looking_up_a_version(env, tag):
gh = FakeGH()
st = ns.State(last_published=ns.Published(tag, SHA, "0.3.2", {}, None))
ns.save_state(env.state_path, st)
with pytest.raises(ns.Skipped):
env.pre(ns.load_state(env.state_path), gh)
assert gh.calls == []
def test_changed_sha_builds_even_when_the_saved_tag_matches(env):
gh = FakeGH()
st = ns.State(last_published=ns.Published(TAG, OLD, "0.3.2", {}, None))
assert env.pre(st, gh).sha == SHA
assert gh.calls == [("next_version",), ("release_state", TAG), ("ensure_tag_available", TAG)]
def test_a_manual_version_replaces_the_next_patch_and_flows_into_the_tag(env):
gh = FakeGH()
n = env.pre(ns.State(), gh, manual=True, version="0.4.0")
assert (n.version, n.tag) == ("0.4.0", "v0.4.0")
assert gh.calls == [("next_version", "0.4.0"), ("release_state", "v0.4.0"), ("ensure_tag_available", "v0.4.0")]
def test_without_a_manual_version_the_night_takes_the_next_patch(env):
gh = FakeGH()
n = env.pre(ns.State(), gh, manual=True)
assert (n.version, n.tag) == ("0.3.2", TAG)
assert gh.calls == [("next_version",), ("release_state", TAG), ("ensure_tag_available", TAG)]
def test_a_manual_version_needs_a_manual_run(env):
gh = FakeGH()
with pytest.raises(ns.Refused) as e:
env.pre(ns.State(), gh, version="0.4.0")
assert e.value.gate == "version" and gh.calls == []
def test_a_manual_version_at_or_below_the_latest_is_a_refused_night(env):
gh = FakeGH()
assert env.night(ns.State(), gh, manual=True, version="0.3.1") == "REFUSED"
assert gh.calls == [("next_version", "0.3.1")]
assert "REFUSED" in env.log() and "version" in env.log()
def test_a_manual_version_refuses_while_an_own_draft_of_another_tag_is_open(env):
gh = FakeGH()
st = ns.State(open_draft=TAG)
st.open_draft_id = 101
with pytest.raises(ns.Refused) as e:
env.pre(st, gh, manual=True, version="0.4.0")
assert e.value.gate == "version" and TAG in e.value.detail and "Nightly release" in e.value.detail
assert "without --version" not in e.value.detail # a run without it would publish the next patch
assert "delete_draft" not in [c[0] for c in gh.calls] and st.open_draft == TAG
def test_a_late_start_is_missed_and_earlier_gaps_are_reported(env):
late = datetime(2026, 10, 28, 9, 10, tzinfo=ns.TZ)
assert env.night(ns.State(last_run_day="2026-10-25"), now=late) == "MISSED"
missed = [ln for ln in env.log().splitlines() if "MISSED" in ln]
assert [ln[2:12] for ln in missed] == ["2026-10-26", "2026-10-27", "2026-10-28"]
assert env.runner.calls == [] # missed before any clone check
def test_a_manual_run_ignores_the_window(env):
late = datetime(2026, 10, 28, 9, 10, tzinfo=ns.TZ)
assert env.pre(now=late, manual=True).tag == TAG
def test_low_disk_refuses_before_anything_runs(env):
e = gate_of(env, free=39.9)
assert isinstance(e, ns.Refused) and e.gate == "disk"
assert all(c[0] == "git" for c in env.runner.calls)
def test_the_exclusive_window_marker_refuses(env):
env.marker.write_text("x")
assert gate_of(env).gate == "exclusive-window"
@pytest.mark.parametrize("what,gate", [("licence", "unity-licence"), ("editor", "unity-editor"),
("slots", "unity-slots")])
def test_a_missing_licence_unity_editor_or_unity_slots_refuses(env, what, gate):
getattr(env, what).unlink()
assert gate_of(env).gate == gate
@pytest.mark.parametrize("change", [{"branch": "feat/x"}, {"head": OLD}, {"dirty": " M a.cs\n"}])
def test_the_clone_must_be_main_at_origin_main_and_clean(env, change):
env.set(**change)
e = gate_of(env)
assert isinstance(e, ns.Refused) and e.gate == "clone"
def test_same_day_rerun_cleans_its_draft_and_refuses_a_published_tag(env):
gh = FakeGH("draft")
st = ns.State(open_draft=TAG)
st.open_draft_id = 101
env.pre(st, gh)
assert ("delete_draft", TAG, 101) in gh.calls
assert st.open_draft is None
gh = FakeGH("published")
with pytest.raises(ns.Refused) as e:
st.open_draft = TAG
st.open_draft_id = 101
env.pre(st, gh)
assert e.value.gate == "tag-exists" and "delete_draft" not in gh.names()
gh = FakeGH("draft") # a draft this job did not leave
with pytest.raises(ns.Refused) as e:
env.pre(ns.State(), gh)
assert e.value.gate == "tag-exists" and "delete_draft" not in gh.names()
def test_a_stranded_own_draft_is_cleaned_and_the_night_proceeds(env):
class Releases(FakeGH):
def next_version(self):
self.calls.append(("next_version",))
return ns.next_version([{"tag_name": "v0.3.1", "draft": False},
{"tag_name": TAG, "draft": True}])
gh, st = Releases("draft"), ns.State(open_draft=TAG)
st.open_draft_id = 101
assert env.pre(st, gh).tag == TAG
assert gh.calls == [("next_version",), ("release_state", TAG), ("delete_draft", TAG, 101),
("ensure_tag_available", TAG)]
assert st.open_draft is None
def test_a_foreign_draft_with_the_next_tag_refuses_without_deletion(env):
gh, st = FakeGH("draft"), ns.State(open_draft="v0.3.0")
with pytest.raises(ns.Refused) as e:
env.pre(st, gh)
assert e.value.gate == "tag-exists" and "delete_draft" not in gh.names()
assert st.open_draft == "v0.3.0"
def test_a_missing_tool_is_refused_and_recorded(env):
def gone(cmd):
raise FileNotFoundError("gh")
env.runner.rules.clear()
env.runner.add(["git"], effect=gone)
assert env.night() == "REFUSED"
assert "REFUSED" in env.log() and "gate=preflight" in env.log()
assert len(env_notes) == 1
def test_no_publish_writes_no_record(env):
st = ns.State(last_published=ns.Published("v0.3.0", SHA, "0.3.0", {}, None))
assert env.night(st, no_publish=True) == "SKIPPED"
assert env.log() == "" and ns.load_state(env.state_path).last_run_day is None
def test_a_corrupt_state_refuses_without_overwriting_it(env):
env.state_path.write_text("{nope")
assert env.night() == "REFUSED"
assert env.state_path.read_text() == "{nope" and "gate=state" in env.log()
def pending_state():
return ns.State(last_published=ns.Published("v0.3.0", SHA, "0.3.0", {}, None), site_pending="0.3.0-nightly.20261027")
def test_site_pending_is_retried_before_skipping(env, monkeypatch):
served = []
monkeypatch.setattr(nightly, "demo_serves", lambda url, version, *, deadline: served.append((url, version, deadline)))
gh = FakeGH()
gh.latest = "v0.3.0-nightly.20261027"
assert env.night(pending_state(), gh) == "SKIPPED"
assert gh.names() == ["latest_tag", "dispatch_site"] and gh.calls[1][1] > time.monotonic()
assert [s[:2] for s in served] == [(env.cfg.site_demo_url, "0.3.0-nightly.20261027")]
assert ns.load_state(env.state_path).site_pending is None # the retry worked, so nothing is pending
assert "SKIPPED" in env.log() and "now serves" in env.log()
@pytest.mark.parametrize("where", ["dispatch", "demo"])
def test_a_failing_site_retry_stays_pending_and_the_night_stays_skipped(env, monkeypatch, where):
def demo(url, version, *, deadline):
if where == "demo":
raise ns.Refused("site", "still serves 0.3.0")
monkeypatch.setattr(nightly, "demo_serves", demo)
gh = FakeGH(fail={"dispatch_site": ns.Refused("site", "run failed")} if where == "dispatch" else None)
gh.latest = "v0.3.1"
assert env.night(pending_state(), gh) == "SKIPPED"
assert ns.load_state(env.state_path).site_pending == "0.3.1"
assert "SKIPPED" in env.log() and "still failed" in env.log() and env_notes == []
@pytest.mark.parametrize("where", ["dispatch", "demo"])
def test_a_non_refusal_error_in_the_site_retry_keeps_the_night_skipped_and_pending(env, monkeypatch, where):
def demo(url, version, *, deadline):
if where == "demo":
raise KeyError("databaseId")
monkeypatch.setattr(nightly, "demo_serves", demo)
gh = FakeGH(fail={"dispatch_site": KeyError("databaseId")} if where == "dispatch" else None)
gh.latest = "v0.3.1"
assert env.night(pending_state(), gh) == "SKIPPED"
assert ns.load_state(env.state_path).site_pending == "0.3.1"
assert "KeyError" in env.log() and "still failed" in env.log()
def test_no_publish_never_retries_the_site(env, monkeypatch):
monkeypatch.setattr(nightly, "demo_serves", lambda *a, **k: pytest.fail("a store call under --no-publish"))
gh = FakeGH()
assert env.night(pending_state(), gh, no_publish=True) == "SKIPPED"
assert gh.calls == []
def test_no_publish_leaves_its_own_draft_alone(env):
gh = FakeGH("draft")
st = ns.State(open_draft=TAG)
st.open_draft_id = 101
with pytest.raises(ns.Refused) as e:
env.pre(st, gh, no_publish=True)
assert e.value.gate == "tag-exists"
assert "delete_draft" not in gh.names() and st.open_draft == TAG
def test_no_release_means_the_tag_is_free_and_any_release_refuses(env):
gh = FakeGH(None)
assert env.pre(gh=gh).tag == TAG
for state in ("draft", "published"):
with pytest.raises(ns.Refused) as e:
env.pre(gh=FakeGH(state))
assert e.value.gate == "tag-exists"
def test_run_bounded_terminates_at_the_deadline(tmp_path):
t = time.monotonic()
code = nightly.ProcRunner(grace=1).run([sys.executable, "-c", "import time; time.sleep(60)"],
cwd=tmp_path, log=tmp_path / "l", deadline=time.monotonic() + 1)
assert code == 124 and time.monotonic() - t < 10
def test_capture_refuses_on_a_non_zero_exit(tmp_path):
r = nightly.ProcRunner()
assert r.capture([sys.executable, "-c", "print('hi')"], cwd=tmp_path).strip() == "hi"
with pytest.raises(ns.Refused) as e:
r.capture([sys.executable, "-c", "raise SystemExit(3)"], cwd=tmp_path)
assert e.value.gate == "command"
def test_the_deadline_kills_a_grandchild_that_ignores_sigterm(tmp_path):
import threading
pidfile = tmp_path / "pid"
grand = ("import signal,time,pathlib;signal.signal(signal.SIGTERM,signal.SIG_IGN);"
f"pathlib.Path({str(pidfile)!r}).write_text(str(__import__('os').getpid()));time.sleep(60)")
top = ("import subprocess,sys,time;subprocess.Popen([sys.executable,'-c',sys.argv[1]]);time.sleep(60)")
code = nightly.ProcRunner(grace=1).run([sys.executable, "-c", top, grand], cwd=tmp_path, log=tmp_path / "l",
deadline=time.monotonic() + 8) # long enough for a busy machine to start both
assert code == 124
end = time.monotonic() + 30
while not pidfile.exists() and time.monotonic() < end: # the grandchild may only just have written it
time.sleep(0.1)
assert pidfile.exists(), "the grandchild never started, so the test proves nothing"
pid = int(pidfile.read_text())
time.sleep(0.5)
with pytest.raises(ProcessLookupError):
import os
os.kill(pid, 0)
def test_a_failed_state_save_still_writes_the_record(env, monkeypatch):
def boom(*a, **k):
raise OSError("disk full")
monkeypatch.setattr(nightly, "save_state", boom)
st = ns.State(last_published=ns.Published("v0.3.0", SHA, "0.3.0", {}, None))
assert env.night(st) == "SKIPPED"
assert "SKIPPED" in env.log()
# --- gates and the full EditMode run (Task 3) -------------------------------------------------------------------
import os
from nightly_state import Refused
OK_CHECK = "== unity compile (dotnet, outside Unity)\nALL CHECKS PASSED\n"
DOTNET_OK = "Passed! - Failed: 0, Passed: 10, Skipped: 0, Total: 10, Duration: 1 s"
class EnvRunner(FakeRunner):
"""Also records the env each command ran with."""
def __init__(self):
super().__init__()
self.envs = []
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)
@pytest.fixture
def night(env):
env.runner = EnvRunner()
env._rules()
n = env.pre()
n.run_dir.mkdir(parents=True)
return n
def test_unity_goes_through_slots_and_the_shared_lock(night):
argv = nightly.unity_argv(night, ["-runTests"], webgl=False)
assert argv[:3] == ["python3", "-I", str(night.cfg.unity_slots)] and "--webgl" not in argv
i = argv.index("--")
assert argv[i + 1:i + 6] == ["uv", "run", str(night.cfg.clone / "tools/machine_lock.py"), "--shared", "--"]
assert "--wait-unity" not in argv and "-nographics" not in argv
assert argv[-1] == "-runTests" and str(night.cfg.clone / "unity") in argv
assert nightly.unity_argv(night, ["-quit"], webgl=True)[3] == "--webgl"
env = nightly.unity_env(night)
assert env["UNITY_SLOTS"] == "3" and Path(env["UNITY_MCP_SERVER_PATH"]).is_file()
assert Path(env["UNITY_MCP_SERVER_PATH"]).read_text() == ""
class LocaleRunner(EnvRunner):
"""Answers `dotnet test` by the LANG it runs with."""
def __init__(self, he, en):
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, stop_on_interrupt=False):
if cmd[:2] == ["dotnet", "test"]:
self.calls.append(list(cmd))
self.envs.append((list(cmd), env, holder))
code, out = self.by_lang[env["LANG"]]
Path(log).parent.mkdir(parents=True, exist_ok=True)
Path(log).write_text(out)
return code
return super().run(cmd, cwd=cwd, log=log, deadline=deadline, env=env, holder=holder)
def gates_runner(night, env, *, check=(0, OK_CHECK), rg=(0, "RELEASE GATE OK\n"), he=(0, DOTNET_OK),
en=(0, DOTNET_OK)):
r = LocaleRunner(he, en)
clone = night.cfg.clone
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
def test_gates_run_in_order_with_both_locales(night, env):
r = gates_runner(night, env)
nightly.run_gates(night, r)
assert r.calls == [
["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",
"-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[:2] == ["dotnet", "test"]]
assert langs == [("he_IL.UTF-8", "he_IL.UTF-8"), ("en_US.UTF-8", "en_US.UTF-8")]
@pytest.mark.parametrize("which,gate,kw", [
("build", "build-sim", None),
("check", "check", dict(check=(1, OK_CHECK))),
("check-skip", "check", dict(check=(0, "== unity compile: SKIPPED, no unity/Library\nALL CHECKS PASSED\n"))),
("rg", "release-gate", dict(rg=(0, "RELEASE GATE FAILED\n"))),
("he", "sim-he_IL", dict(he=(0, "Build succeeded."))),
("he-fail", "sim-he_IL", dict(he=(1, "Failed! - Failed: 2, Passed: 8, Skipped: 0, Total: 10"))),
("en", "sim-en_US", dict(en=(0, "Build succeeded."))),
("en-fail", "sim-en_US", dict(en=(1, "Failed! - Failed: 1, Passed: 9, Skipped: 0, Total: 10"))),
("timeout", "check", dict(check=(124, OK_CHECK))),
])
def test_a_failing_gate_refuses_by_name(night, env, which, gate, kw):
r = gates_runner(night, env, **(kw or {}))
if which == "build":
r.rules.insert(0, (("uv", "run", f"{night.cfg.clone}/tools/build_sim_for_unity.py"), 2, "", None))
with pytest.raises(Refused) as e:
nightly.run_gates(night, r)
assert e.value.gate == gate
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[: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"
class EditRunner(EnvRunner):
"""Unity steps (python3 -I ...) answer by kind: the warm-up has -executeMethod, the test run -runTests."""
def __init__(self, night, xml, code, warm_code, warm_log, restore_code):
super().__init__()
self.night, self.xml, self.code, self.warm_code = night, xml, code, warm_code
self.warm_log, self.restore_code = warm_log, restore_code
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
if cmd[0] == "git":
return self.restore_code
if "-executeMethod" in cmd:
(d / "warmup.log").write_text(self.warm_log)
return self.warm_code
if self.xml is not None:
(d / "editmode.xml").write_text(self.xml)
return self.code
def editmode_runner(night, *, xml='<test-run total="5" passed="5" failed="0"/>', code=0, warm_code=0,
warm_log=WARM_OK, restore_code=0):
return EditRunner(night, xml, code, warm_code, warm_log, restore_code)
def test_editmode_needs_tests_and_no_failures_and_never_quits(night, env):
r = editmode_runner(night)
nightly.run_editmode(night, r)
warm, tests, restore = r.envs
assert "-executeMethod" in warm[0] and nightly.unity_postmerge.WARM_UP in warm[0] and "-quit" not in warm[0]
assert "-runTests" in tests[0] and "-quit" not in tests[0] and "-testPlatform" in tests[0]
assert "--webgl" not in tests[0] and warm[1]["UNITY_MCP_SERVER_PATH"] == tests[1]["UNITY_MCP_SERVER_PATH"]
assert tests[2] == night.run_dir / "lock-holder"
assert restore[0] == nightly.RESTORE_ARGV
def test_editmode_leaves_out_the_tests_that_need_gitignored_local_assets(night, env):
# #2655 item 6: the nightly's clean clone never has them, so they only padded its skip count.
r = editmode_runner(night)
nightly.run_editmode(night, r)
tests = r.envs[1][0]
assert tests[tests.index("-testCategory") + 1] == "!" + nightly.LOCAL_ONLY
tiles = Path(__file__).resolve().parents[2] / "unity/Assets/Editor/HexTiles/Tests"
for name in ("HexModelMeshTests.cs", "HexUnitTests.cs"):
assert f'[Test, Category("{nightly.LOCAL_ONLY}")]' in (tiles / name).read_text(encoding="utf-8"), name
def test_editmode_with_zero_tests_refuses_and_still_restores_settings(night, env):
r = editmode_runner(night, xml='<test-run total="0" passed="0" failed="0"/>')
with pytest.raises(Refused) as e:
nightly.run_editmode(night, r)
assert e.value.gate == "editmode"
assert r.envs[-1][0][0] == "git"
def test_editmode_failure_or_missing_results_or_timeout_refuses(night, env):
for kw in (dict(xml='<test-run total="5" passed="4" failed="1"/>'), dict(xml=None), dict(code=124)):
r = editmode_runner(night, **kw)
with pytest.raises(Refused) as e:
nightly.run_editmode(night, r)
assert e.value.gate == "editmode"
def test_editmode_unreadable_results_refuse_and_still_restore_settings(night, env, monkeypatch):
r = editmode_runner(night)
def unreadable(path):
assert Path(path).name == "editmode.xml"
raise OSError("permission denied")
monkeypatch.setattr(nightly.unity_postmerge.ET, "parse", unreadable)
with pytest.raises(Refused) as e:
nightly.run_editmode(night, r)
assert e.value.gate == "editmode" and "result file could not be read: permission denied" in e.value.detail
assert r.envs[-1][0] == nightly.RESTORE_ARGV
def test_settings_are_restored_when_the_runner_raises(night, env):
r = editmode_runner(night)
real = r.run
def boom(cmd, **k):
if "-runTests" in cmd:
raise OSError("disk gone")
return real(cmd, **k)
r.run = boom
with pytest.raises(Refused) as e: # #2667: a runner that cannot start is a recorded refusal with its log
nightly.run_editmode(night, r)
assert e.value.gate == "editmode" and isinstance(e.value.__cause__, OSError)
assert e.value.log == night.run_dir / "editmode.out"
assert r.envs[-1][0][0] == "git"
def test_the_exclusive_marker_appearing_before_a_unity_step_refuses(night, env):
env.marker.write_text("x")
r = editmode_runner(night)
with pytest.raises(Refused) as e:
nightly.run_editmode(night, r)
assert e.value.gate == "exclusive-window" and not r.envs
def test_a_warm_up_timeout_refuses_and_restores(night, env):
r = editmode_runner(night, warm_code=124)
with pytest.raises(Refused) as e:
nightly.run_editmode(night, r)
assert e.value.gate == "editmode" and "timed out" in e.value.detail
assert [c[0][0] for c in r.envs] == ["python3", "git"]
@pytest.mark.parametrize("kw", [dict(warm_code=1), dict(warm_log=""), dict(warm_code=1, warm_log=WARM_OK)])
def test_a_failed_or_unconfirmed_warm_up_refuses_before_any_test_run(night, env, kw):
r = editmode_runner(night, **kw)
with pytest.raises(Refused) as e:
nightly.run_editmode(night, r)
assert e.value.gate == "editmode" and "warm-up" in e.value.detail
assert not any("-runTests" in c for c in r.calls)
assert r.envs[-1][0][0] == "git"
def test_the_warm_up_and_the_test_run_share_the_lock_holder(night, env):
r = editmode_runner(night)
nightly.run_editmode(night, r)
assert r.envs[0][2] == night.run_dir / "lock-holder" == r.envs[1][2]
def test_a_failed_restore_does_not_replace_the_original_refusal(night, env, capsys):
r = editmode_runner(night, xml='<test-run total="5" passed="4" failed="1"/>', restore_code=1)
with pytest.raises(Refused) as e:
nightly.run_editmode(night, r)
assert e.value.gate == "editmode"
assert "restore-settings" in (night.run_dir / "restore-settings.note").read_text() + capsys.readouterr().err
def test_a_failed_restore_alone_refuses(night, env):
r = editmode_runner(night, restore_code=1)
with pytest.raises(Refused) as e:
nightly.run_editmode(night, r)
assert e.value.gate == "restore-settings"
@pytest.mark.parametrize("how", ["warm-up refusal", "runner raises"])
def test_a_pending_error_and_a_failed_restore_keep_the_original(night, env, how):
if how == "warm-up refusal":
r = editmode_runner(night, warm_code=1, restore_code=1)
expect, exc = "editmode", Refused
else:
r = editmode_runner(night, restore_code=1)
real = r.run
def boom(cmd, **k):
if "-runTests" in cmd:
raise OSError("disk gone")
return real(cmd, **k)
r.run = boom
expect, exc = "editmode", Refused # #2667: the runner's OSError is wrapped, not replaced by the restore failure
with pytest.raises(exc) as e:
nightly.run_editmode(night, r)
if expect:
assert e.value.gate == expect
if how == "runner raises":
assert isinstance(e.value.__cause__, OSError)
assert "restore-settings" in (night.run_dir / "restore-settings.note").read_text()
def test_a_restore_only_failure_is_not_swallowed_inside_a_caller_except_block(night, env):
r = editmode_runner(night, restore_code=1)
try:
raise ValueError("caller is handling something")
except ValueError:
with pytest.raises(Refused) as e:
nightly.run_editmode(night, r)
assert e.value.gate == "restore-settings"
# --- the stamp, the two web builds and packaging ----------------------------------------------------------------
STAMPED = "0.3.2"
RESTORE_CMD = nightly.RESTORE_ARGV
def test_the_stamp_replaces_exactly_the_one_bundle_version(tmp_path):
s = tmp_path / "ProjectSettings.asset"
s.write_text(" productName: X\n bundleVersion: 0.3.1\n other: 1\n")
nightly.stamp_bundle_version(s, STAMPED)
assert s.read_text() == f" productName: X\n bundleVersion: {STAMPED}\n other: 1\n"
s.write_text("no version here\n")
with pytest.raises(ValueError):
nightly.stamp_bundle_version(s, STAMPED)
s.write_text(" bundleVersion: 1\n bundleVersion: 2\n")
with pytest.raises(ValueError):
nightly.stamp_bundle_version(s, STAMPED)
class WebRunner(EnvRunner):
"""Answers the Build.Web runs (index.html carries `page_version`), the settings restore and the packaging."""
def __init__(self, night, *, page_version=STAMPED, build_code=0, package_out="PACKAGED x\nOK: notices inside x\n",
package_code=0):
super().__init__()
self.night, self.page_version, self.build_code = night, page_version, build_code
self.package_out, self.package_code = package_out, package_code
self.settings = night.cfg.clone / "unity/ProjectSettings/ProjectSettings.asset"
self.settings.parent.mkdir(parents=True, exist_ok=True)
self.settings.write_text(" bundleVersion: 0.3.1\n")
self.stamped_at_build = []
self.restores = 0
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", "--"]:
self.restores += 1
self.settings.write_text(" bundleVersion: 0.3.1\n")
return 0
if "-executeMethod" in cmd:
self.stamped_at_build.append(self.settings.read_text())
pages = "-decompressionFallback" in cmd
out = self.night.cfg.clone / "unity/Builds" / ("Web-pages" if pages else "Web-gzip")
out.mkdir(parents=True, exist_ok=True)
(out / "index.html").write_text(f'productVersion: "{self.page_version}",\n')
return self.build_code
if cmd[0] == "bash":
Path(log).parent.mkdir(parents=True, exist_ok=True)
Path(log).write_text(self.package_out)
return self.package_code
raise AssertionError(f"unexpected command {cmd}")
def builds(night, runner, *, free=100.0):
return (nightly.build_web(night, runner, pages=False, free_gb=lambda p: free),
nightly.build_web(night, runner, pages=True, free_gb=lambda p: free))
def test_builds_follow_releasing_step_5(night, env):
r = WebRunner(night)
gz, pg = builds(night, r)
clone = night.cfg.clone
assert gz == clone / "unity/Builds/Web-gzip" and pg == clone / "unity/Builds/Web-pages"
gz_cmd = next(c for c in r.calls if "-executeMethod" in c and "-decompressionFallback" not in c)
pg_cmd = next(c for c in r.calls if "-decompressionFallback" in c)
gz_log = str(night.run_dir / "unity-build-web-gz.log")
pg_log = str(night.run_dir / "unity-build-web-pages.log")
method = ["-quit", "-buildTarget", "WebGL", "-executeMethod", "Statecraft.Game.EditorTools.Build.Web"]
i = gz_cmd.index("-quit")
assert gz_cmd[i:] == [*method, "-compression", "gzip", "-shareable", "-logFile", gz_log]
j = pg_cmd.index("-quit")
assert pg_cmd[j:] == [*method, "-compression", "gzip", "-decompressionFallback", "-shareable", "-out",
"Builds/Web-pages", "-logFile", pg_log]
for c in (gz_cmd, pg_cmd):
assert c[3] == "--webgl" and c[0] == "python3" and "--wait-unity" not in c
envs = [e for cmd, e, h in r.envs if "-executeMethod" in cmd]
assert all(Path(e["UNITY_MCP_SERVER_PATH"]).is_file() for e in envs)
def test_the_stamp_is_applied_before_and_removed_after_each_build(night, env):
r = WebRunner(night)
builds(night, r)
assert r.stamped_at_build == [f" bundleVersion: {STAMPED}\n"] * 2
assert r.restores == 2 and r.settings.read_text() == " bundleVersion: 0.3.1\n"
kinds = ["restore" if c[0] == "git" else "build" for c in r.calls]
assert kinds == ["build", "restore", "build", "restore"]
assert r.calls[1] == RESTORE_CMD
def test_a_build_page_without_tonights_version_refuses(night, env):
for wrong in ("0.3.1", "0.3.1-nightly.20261027"):
r = WebRunner(night, page_version=wrong)
with pytest.raises(Refused) as e:
nightly.build_web(night, r, pages=False, free_gb=lambda p: 100.0)
assert e.value.gate == "version-stamp"
assert r.restores == 1 and r.settings.read_text() == " bundleVersion: 0.3.1\n"
r = WebRunner(night)
(night.cfg.clone / "unity/Builds/Web-gzip").mkdir(parents=True, exist_ok=True)
r.build_code = 0
r.page_version = "none"
with pytest.raises(Refused):
nightly.build_web(night, r, pages=False, free_gb=lambda p: 100.0)
@pytest.mark.parametrize("pages,gate", [(False, "build-web-gz"), (True, "build-web-pages")])
def test_a_failed_build_refuses_by_variant_and_restores(night, env, pages, gate):
r = WebRunner(night, build_code=1)
with pytest.raises(Refused) as e:
nightly.build_web(night, r, pages=pages, free_gb=lambda p: 100.0)
assert e.value.gate == gate and e.value.log == night.run_dir / f"unity-build-web-{'pages' if pages else 'gz'}.log"
assert r.restores == 1
def test_low_disk_before_the_second_build_refuses(night, env):
r = WebRunner(night)
seen = iter([100.0, 39.0])
nightly.build_web(night, r, pages=False, free_gb=lambda p: next(seen))
with pytest.raises(Refused) as e:
nightly.build_web(night, r, pages=True, free_gb=lambda p: next(seen))
assert e.value.gate == "disk"
assert sum("-executeMethod" in c for c in r.calls) == 1
assert r.settings.read_text() == " bundleVersion: 0.3.1\n"
def test_the_exclusive_marker_refuses_a_web_build(night, env):
env.marker.write_text("x")
r = WebRunner(night)
with pytest.raises(Refused) as e:
nightly.build_web(night, r, pages=False, free_gb=lambda p: 100.0)
assert e.value.gate == "exclusive-window" and r.calls == []
def test_a_build_timeout_restores_settings_and_refuses(night, env):
r = WebRunner(night, build_code=124)
with pytest.raises(Refused) as e:
nightly.build_web(night, r, pages=False, free_gb=lambda p: 100.0)
assert e.value.gate == "build-web-gz" and "timed out" in e.value.detail
assert r.restores == 1 and r.settings.read_text() == " bundleVersion: 0.3.1\n" # no stamp left behind
def test_a_failed_restore_does_not_mask_the_build_error(night, env, capsys):
r = WebRunner(night, build_code=124)
real = r.run
def run(cmd, **k):
return 1 if cmd[0] == "git" else real(cmd, **k)
r.run = run
with pytest.raises(Refused) as e:
nightly.build_web(night, r, pages=False, free_gb=lambda p: 100.0)
assert e.value.gate == "build-web-gz"
assert (night.run_dir / "restore-settings.note").is_file()
def test_packaging_needs_the_notices_line(night, env):
r = WebRunner(night)
build = night.cfg.clone / "unity/Builds/Web-gzip"
z = nightly.package_zip(night, r, build, False)
assert z == night.run_dir / f"statecraft-israel-v{STAMPED}-web.zip"
assert r.calls[-1] == ["bash", "scripts/oss/package_web.sh", str(build), str(z)]
zp = nightly.package_zip(night, r, night.cfg.clone / "unity/Builds/Web-pages", True)
assert zp == night.run_dir / f"statecraft-israel-v{STAMPED}-web-pages.zip"
for pages, gate in ((False, "package-gz"), (True, "package-pages")):
selected = night.cfg.clone / "unity/Builds" / ("Web-pages" if pages else "Web-gzip")
for kw in (dict(package_out="PACKAGED x\n"), dict(package_out="OK: notices inside x\n"),
dict(package_code=1), dict(package_code=124)):
with pytest.raises(Refused) as e:
nightly.package_zip(night, WebRunner(night, **kw), selected, pages)
assert e.value.gate == gate and e.value.log == night.run_dir / f"{gate}.log"
def test_the_tree_must_be_clean_after_the_builds(night, env):
nightly.assert_clean_tree(night, env.runner)
env.set(dirty=" M unity/ProjectSettings/ProjectSettings.asset\n")
with pytest.raises(Refused) as e:
nightly.assert_clean_tree(night, env.runner)
assert e.value.gate == "dirty-tree"
def test_a_malformed_bundle_version_surfaces_as_a_version_stamp_refusal(night, env):
r = WebRunner(night)
r.settings.write_text(" bundleVersion: 0.3.1\n bundleVersion: 0.3.2\n")
with pytest.raises(Refused) as e:
nightly.build_web(night, r, pages=False, free_gb=lambda p: 100.0)
assert e.value.gate == "version-stamp" and "bundleVersion" in e.value.detail
assert r.restores == 1 and r.settings.read_text() == " bundleVersion: 0.3.1\n"
assert not any("-executeMethod" in c for c in r.calls)
# --- Task 5: web checks, sizes, boot -----------------------------------------------------------------------------
class CheckRunner(EnvRunner):
"""Answers the web_check and boot runs: `answers` maps a marker in the argv to (code, text), else (0, `ok`)."""
def __init__(self, ok="PASS: saw x\n", answers=None):
super().__init__()
self.ok, self.answers, self.cwds = ok, answers or {}, []
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)
code, text = 0, self.ok
for marker, answer in self.answers.items():
if marker in cmd:
code, text = answer(len(self.calls)) if callable(answer) else answer
Path(log).parent.mkdir(parents=True, exist_ok=True)
with open(log, "a") as out: # appends, as ProcRunner does: measure_boot writes the machine state first
out.write(text)
return code
MANIFEST = "# c\nhash1950 aa\nsmoke5 cc\nsmoke-orders dd\n"
def test_a_manifest_without_the_smoke_goldens_refuses(night, env):
r = CheckRunner()
with pytest.raises(Refused) as e:
nightly.run_web_checks(night, r, night.cfg.clone / "unity/Builds/Web-gzip") # the fixture manifest is a stub
assert e.value.gate == "web-check" and r.calls == []
def test_web_checks_run_under_the_shared_lock_and_all_must_pass(night, env):
night.manifest = MANIFEST
build = night.cfg.clone / "unity/Builds/Web-gzip"
r = CheckRunner()
nightly.run_web_checks(night, r, build)
clone = night.cfg.clone
assert len(r.calls) == 7
for c in r.calls:
assert c[:8] == ["uv", "run", str(clone / "tools/machine_lock.py"), "--shared", "--", "uv", "run",
str(clone / "tools/web_check.py")]
assert c[8] == str(build) and "--wait-unity" not in c
assert set(r.cwds) == {clone}
assert (night.run_dir / "web-check-Web-gzip-7.log").is_file()
@pytest.mark.parametrize("answer", [(1, "PASS: saw x\n"), (0, "console: nothing\n"), (0, "TIMEOUT: never saw x\n"),
(124, "PASS: saw x\n")])
def test_a_failing_web_check_pass_refuses_and_stops(night, env, answer):
night.manifest = MANIFEST
r = CheckRunner(answers={"--persistence": answer, "--startscreen": answer})
with pytest.raises(Refused) as e:
nightly.run_web_checks(night, r, night.cfg.clone / "unity/Builds/Web-pages")
assert e.value.gate == "web-check" and "Web-pages" in e.value.detail
assert len(r.calls) == 3 # golden, smoke-orders, then the first startscreen pass fails
class FakeGhSizes:
def __init__(self, bodies=(), error=None):
self.bodies, self.error, self.calls = list(bodies), error, []
def merged_pr_bodies(self, shas):
self.calls.append(set(shas))
if self.error:
raise self.error
return self.bodies
@pytest.fixture
def fake_gh():
return FakeGhSizes
def sized_build(root, data):
from test_nightly_checks import make_build
return make_build(root, extra=False, data=data)
def baseline_zip(path, data=900):
with zipfile.ZipFile(path, "w") as z:
z.writestr("index.html", 'x "Build/h1.data.gz" "Build/h1.wasm.gz" "Build/h1.framework.js.gz"')
z.writestr("Build/h1.data.gz", b"d" * data)
z.writestr("Build/h1.wasm.gz", b"w" * 90)
z.writestr("Build/h1.framework.js.gz", b"f" * 10)
return path
def test_sizes_refuse_without_a_baseline_zip(night, env, fake_gh, tmp_path):
build = sized_build(tmp_path / "b", 900)
with pytest.raises(Refused) as e:
nightly.check_sizes(night, fake_gh(), build, tmp_path / "absent.zip", OLD, runner=env.runner)
assert e.value.gate == "sizes" and "baseline" in e.value.detail
bad = tmp_path / "bad.zip"
bad.write_text("not a zip")
with pytest.raises(Refused) as e:
nightly.check_sizes(night, fake_gh(), build, bad, OLD, runner=env.runner)
assert e.value.gate == "sizes"
def test_a_budget_is_looked_up_only_when_growth_exceeds_2_percent(night, env, fake_gh, tmp_path):
clone = str(night.cfg.clone)
env.runner.add(["git", "-C", clone, "rev-list", f"{OLD}..{SHA}"], out="c1\nc2\n")
z = baseline_zip(tmp_path / "prev.zip")
gh = fake_gh()
assert nightly.check_sizes(night, gh, sized_build(tmp_path / "ok", 920), z, OLD, runner=env.runner) == \
{"data": 920, "wasm": 90, "framework": 10}
assert gh.calls == [] # +20 of 1000 needs no lookup
with pytest.raises(Refused) as e:
nightly.check_sizes(night, gh, sized_build(tmp_path / "big", 921), z, OLD, runner=env.runner)
assert e.value.gate == "sizes" and "1021" in e.value.detail and gh.calls == [{"c1", "c2"}]
gh = fake_gh(["Nightly size budget: +0.001 MB"])
assert nightly.check_sizes(night, gh, sized_build(tmp_path / "b2", 921), z, OLD, runner=env.runner)["data"] == 921
with pytest.raises(Refused): # the budget is too small for +500
nightly.check_sizes(night, fake_gh(["Nightly size budget: +0.0001 MB"]),
sized_build(tmp_path / "b3", 1400), z, OLD, runner=env.runner)
def test_growth_with_an_unknown_previous_commit_refuses(night, env, fake_gh, tmp_path):
z = baseline_zip(tmp_path / "prev.zip")
with pytest.raises(Refused) as e:
nightly.check_sizes(night, fake_gh(), sized_build(tmp_path / "big", 1400), z, None, runner=env.runner)
assert e.value.gate == "sizes"
def test_a_truncated_pr_list_refuses(night, env, fake_gh, tmp_path):
env.runner.add(["git", "-C", str(night.cfg.clone), "rev-list"], out="c1\n")
gh = fake_gh(error=Refused("sizes", "500 merged PRs, the list may be truncated"))
with pytest.raises(Refused) as e:
nightly.check_sizes(night, gh, sized_build(tmp_path / "big", 1400), baseline_zip(tmp_path / "p.zip"), OLD,
runner=env.runner)
assert e.value.gate == "sizes" and "truncated" in e.value.detail
def boot_text(ms):
return f"console: BOOT phase=screens ready at={ms} ms dt=40 ms\nconsole: GAME OK 1948 turn 0 hash ab\nPASS: saw GAME OK\n"
class MachineRunner(CheckRunner):
"""Also answers the macOS state reads (#2914). `loads` are the 1-minute load averages `sysctl -n vm.loadavg`
reports, one per read (the last repeats); `broken` makes every state read fail as a missing command would."""
def __init__(self, *a, loads=(0.8,), broken=False, **k):
super().__init__(*a, **k)
self.loads, self.broken, self.reads = list(loads), broken, []
def capture(self, cmd, *, cwd, timeout=300):
self.reads.append(list(cmd))
if self.broken:
raise Refused("command", f"{cmd[0]} exited 127")
if cmd == ["sysctl", "-n", "vm.loadavg"]:
load = self.loads.pop(0) if len(self.loads) > 1 else self.loads[0]
return f"{{ {load:.2f} 1.10 1.05 }}\n"
if cmd == ["sysctl", "-n", "vm.swapusage"]:
return "total = 6144.00M used = 5324.50M free = 819.50M (encrypted)\n"
if cmd == ["memory_pressure"]:
return "The system has 8589934592 (2097152 pages)\nPages free: 3000\nSystem-wide memory free percentage: 41%\n"
if cmd == ["pmset", "-g", "therm"]:
return ("Note: No thermal warning level has been recorded\n"
"Note: No performance warning level has been recorded\n")
return super().capture(cmd, cwd=cwd, timeout=timeout)
def boot_runner(times, **k):
times = iter(times)
class BootRunner(MachineRunner):
def run(self, cmd, **kw):
self.ok = boot_text(next(times))
return super().run(cmd, **kw)
return BootRunner(**k)
def test_boot_takes_the_exclusive_lock_from_the_main_checkout_three_times(night, env):
r = boot_runner([8100, 8300, 8200])
build = night.cfg.clone / "unity/Builds/Web-gzip"
assert nightly.measure_boot(night, r, build, sleep=lambda s: None) == 8200.0
clone = night.cfg.clone
assert len(r.calls) == 3 and set(r.cwds) == {night.cfg.main_repo}
assert r.calls[0] == ["uv", "run", str(clone / "tools/machine_lock.py"), "--exclusive", "--wait-unity",
"--timeout", "2700", "--", "uv", "run", str(clone / "tools/web_check.py"), str(build),
"--query", "bootlog", "--expect", "GAME OK", "--timeout", "300", "--stall", "90"]
@pytest.mark.parametrize("answer,word", [((3, ""), "Unity"), ((124, ""), "timed out"), ((1, boot_text(1)), "exited 1"),
((0, "PASS: saw GAME OK\n"), "BOOT"), ((0, "TIMEOUT\n"), "pass")])
def test_a_bad_boot_run_refuses_with_gate_boot(night, env, answer, word):
r = MachineRunner(answers={"--exclusive": answer})
with pytest.raises(Refused) as e:
nightly.measure_boot(night, r, night.cfg.clone / "unity/Builds/Web-gzip", sleep=lambda s: None)
assert e.value.gate == "boot" and word in e.value.detail
assert len(r.calls) == 1
def boot_logs(night):
return [(night.run_dir / f"boot-{i}.log").read_text() for i in (1, 2, 3)]
def test_each_boot_log_starts_with_the_machine_state(night, env):
r = boot_runner([4400, 4500, 4450])
assert nightly.measure_boot(night, r, night.cfg.clone / "unity/Builds/Web-gzip", sleep=lambda s: None) == 4450.0
for text in boot_logs(night):
head = text.splitlines()[:4]
assert head == ["state: load averages 0.80 1.10 1.05",
"state: vm.swapusage total = 6144.00M used = 5324.50M free = 819.50M (encrypted)",
"state: memory_pressure System-wide memory free percentage: 41%",
"state: pmset -g therm Note: No thermal warning level has been recorded; "
"Note: No performance warning level has been recorded"]
assert "console: BOOT phase=screens ready" in text # the boot's own output follows, unchanged
assert all(c[0] in ("sysctl", "memory_pressure", "pmset") for c in r.reads) # read-only commands only
def test_a_settled_machine_boots_at_once(night, env):
sleeps = []
r = boot_runner([4400, 4500, 4450], loads=[0.8])
nightly.measure_boot(night, r, night.cfg.clone / "unity/Builds/Web-gzip", sleep=sleeps.append)
assert sleeps == []
first, second, _ = boot_logs(night)
assert "settle: 1-minute load 0.80 under 2.0 after 0 s" in first and "settle:" not in second
def test_a_slow_to_settle_machine_waits_then_logs_the_wait(night, env):
sleeps = []
r = boot_runner([4400, 4500, 4450], loads=[3.5, 2.6, 1.2, 4.0])
nightly.measure_boot(night, r, night.cfg.clone / "unity/Builds/Web-gzip", sleep=sleeps.append)
assert sleeps == [nightly.SETTLE_POLL_S] * 2
assert f"settle: 1-minute load 1.20 under 2.0 after {2 * nightly.SETTLE_POLL_S} s" in boot_logs(night)[0]
assert len(r.calls) == 3 # the boots run only after the wait
def test_a_machine_that_never_settles_is_logged_and_measured_anyway(night, env):
sleeps = []
r = boot_runner([6300, 6280, 6310], loads=[5.0])
assert nightly.measure_boot(night, r, night.cfg.clone / "unity/Builds/Web-gzip", sleep=sleeps.append) == 6300.0
assert sum(sleeps) == nightly.SETTLE_MAX_S
assert (f"settle: not settled after {nightly.SETTLE_MAX_S} s (1-minute load 5.00, limit 2.0); measuring anyway"
in boot_logs(night)[0])
def test_unreadable_machine_state_never_changes_the_verdict(night, env):
sleeps = []
r = boot_runner([4400, 4500, 4450], broken=True)
assert nightly.measure_boot(night, r, night.cfg.clone / "unity/Builds/Web-gzip", sleep=sleeps.append) == 4450.0
assert sleeps == [] # no reading to wait on, so no wait
first = boot_logs(night)[0]
assert first.startswith("state: load averages unavailable (")
assert "settle: 1-minute load unreadable, not waiting" in first
# #2921: one over-bound median gets one re-measure after the machine settles again; only a second one refuses.
BOOT_BASELINE = [4400.0, 4450.0, 4500.0, 4400.0, 4450.0] # bound 4500 + 100 = 4600 ms
def test_a_first_median_under_the_bound_takes_no_second_measurement(night, env):
r = boot_runner([4400, 4500, 4450])
st = ns.State(boot_baseline=list(BOOT_BASELINE))
assert nightly.boot_gate(night, st, r, night.cfg.clone / "unity/Builds/Web-gzip") == (4450.0, "checked")
assert len(r.calls) == 3 and not (night.run_dir / "boot-4.log").exists()
def test_an_over_bound_median_then_one_under_it_passes_and_the_log_records_both(night, env, capsys):
r = boot_runner([6300, 6313, 6320, 4440, 4450, 4460])
st = ns.State(boot_baseline=list(BOOT_BASELINE))
assert nightly.boot_gate(night, st, r, night.cfg.clone / "unity/Builds/Web-gzip") == (4450.0, "checked")
assert len(r.calls) == 6
out = capsys.readouterr().out
assert "6313 ms, over the 4600 ms bound" in out and "re-measure after settling: 4450 ms" in out
again = [(night.run_dir / f"boot-{i}.log").read_text() for i in (4, 5, 6)]
assert "settle: 1-minute load 0.80 under 2.0" in again[0] and "settle:" not in again[1]
assert boot_logs(night)[1].count("BOOT phase") == 1 # the first three logs are kept, not overwritten
def test_two_over_bound_medians_refuse_naming_both(night, env):
r = boot_runner([6300, 6313, 6320, 6280, 6290, 6270])
st = ns.State(boot_baseline=list(BOOT_BASELINE))
with pytest.raises(Refused) as e:
nightly.boot_gate(night, st, r, night.cfg.clone / "unity/Builds/Web-gzip")
assert e.value.gate == "boot" and len(r.calls) == 6
assert "6313 ms, over the 4600 ms bound" in e.value.detail and "6280 ms, over the 4600 ms bound" in e.value.detail
# --- Task 6: publish_night, the stage wiring, the clients ---------------------------------------------------------
BOOT_MS = 8200.0
SIZES = {"data": 1000, "wasm": 90, "framework": 10}
@pytest.fixture
def pub(night, env, tmp_path):
"""A night plus two zips, a git log answer and a fake demo check."""
clone = str(night.cfg.clone)
env.runner.add(["git", "-C", clone, "log", "--format=%s%x1f%aN"], out="Fix a thing\x1fBeri\nAdd a thing\x1fmoshewe\n")
zips = (tmp_path / "web.zip", tmp_path / "pages.zip")
for z in zips:
z.write_bytes(b"zip")
return zips
@pytest.fixture
def served(monkeypatch):
calls = []
monkeypatch.setattr(nightly, "demo_serves", lambda url, version, *, deadline: calls.append((url, version)))
return calls
def last_published():
return ns.Published("v0.3.0-nightly.20261027", OLD, "0.3.0-nightly.20261027", {}, None)
PREVIOUS = ("v0.3.0-nightly.20261027", OLD)
def publish(night, state, gh, zips, env, itch=None, save=lambda: None, previous=PREVIOUS):
nightly.publish_night(night, state, gh, itch, zips, SIZES, BOOT_MS, previous=previous, save=save,
runner=env.runner)
def test_release_targets_the_preflight_commit(night, env, pub, served):
clone = str(night.cfg.clone)
gh, st = FakeGH(), ns.State(last_published=last_published())
publish(night, st, gh, pub, env) # origin/main may move on after preflight: nothing may follow it
create = next(c for c in gh.calls if c[0] == "create_draft")
assert create[1:3] == (TAG, night.sha) and create[4] == list(pub)
assert ["git", "-C", clone, "log", "--format=%s%x1f%aN", f"{OLD}..{night.sha}"] in env.runner.calls
assert not any("ls-remote" in c and "refs/heads/main" in c for c in env.runner.calls)
notes = (night.run_dir / "release-notes.md").read_text()
assert "- Fix a thing (by Beri)\n- Add a thing (by moshewe)" in notes and night.sha[:12] in notes
assert gh.names() == ["ensure_tag_available", "create_draft", "verify_draft", "latest_tag", "publish", "dispatch_site"]
assert gh.latest == TAG and "restore_latest" not in gh.names()
assert (night.run_dir / "latest-before-publish.txt").read_text() == "v0.3.1\n"
def test_a_subject_with_a_unicode_line_break_stays_one_line_with_its_author(night, env, pub, served):
# str.splitlines() also breaks on U+0085 and U+2028, which would print the first half as "(by )" (#2654 review).
clone = str(night.cfg.clone)
env.runner.rules.insert(0, (("git", "-C", clone, "log", "--format=%s%x1f%aN"), 0, "Fix\x85a thing\x1fBeri\n", None))
publish(night, ns.State(last_published=last_published()), FakeGH(), pub, env)
assert "- Fix\x85a thing (by Beri)" in (night.run_dir / "release-notes.md").read_text()
def test_the_first_night_fetches_the_release_tag_before_resolving_it(night, env):
clone = str(night.cfg.clone)
env.runner.add(["git", "-C", clone, "fetch"])
env.runner.add(["git", "-C", clone, "rev-list", "-n", "1", "refs/tags/v0.3.1"], out=OLD + "\n")
gh = FakeGH()
assert nightly.previous_build(night, ns.State(), gh, env.runner) == ("v0.3.1", OLD)
fetch = ["git", "-C", clone, "fetch", "--no-tags", "origin", "refs/tags/v0.3.1:refs/tags/v0.3.1"]
assert env.runner.calls.index(fetch) < [c[3] for c in env.runner.calls].index("rev-list")
def test_a_failed_tag_fetch_on_the_first_night_refuses(night, env):
env.runner.add(["git", "-C", str(night.cfg.clone), "fetch"], code=128)
with pytest.raises(ns.Refused):
nightly.previous_build(night, ns.State(), FakeGH(), env.runner)
def test_later_nights_use_the_published_commit_and_fetch_nothing(night, env):
assert nightly.previous_build(night, ns.State(last_published=last_published()), FakeGH(), env.runner) == \
("v0.3.0-nightly.20261027", OLD)
assert not any("fetch" in c for c in env.runner.calls)
def test_the_notes_log_runs_from_the_previous_commit_or_tag(night, env, pub, served):
clone = str(night.cfg.clone)
publish(night, ns.State(), FakeGH(), pub, env, previous=("v0.3.1", None))
assert ["git", "-C", clone, "log", "--format=%s%x1f%aN", f"v0.3.1..{night.sha}"] in env.runner.calls
def test_a_failed_draft_check_deletes_the_draft_and_refuses(night, env, pub, served):
gh = FakeGH(fail={"verify_draft": ns.Refused("github-draft", "hash differs")})
st = ns.State(last_published=last_published())
with pytest.raises(ns.Refused) as e:
publish(night, st, gh, pub, env)
assert e.value.gate == "github-draft" and "hash differs" in e.value.detail
assert ("delete_draft", TAG, 101) in gh.calls and "publish" not in gh.names() and "dispatch_site" not in gh.names()
assert st.open_draft is None and st.last_published.sha == OLD and served == []
@pytest.mark.parametrize("open_draft", [None, TAG, "v0.3.0"])
def test_a_release_made_after_preflight_refuses_before_create_and_is_never_deleted(night, env, pub, served, open_draft):
gh = FakeGH("draft")
st = ns.State(last_published=last_published(), open_draft=open_draft)
with pytest.raises(ns.Refused) as e:
publish(night, st, gh, pub, env)
assert e.value.gate == "tag-exists"
assert gh.names() == ["ensure_tag_available"] and gh.release == "draft"
assert st.open_draft == open_draft and st.last_published.sha == OLD
def test_a_create_that_fails_after_leaving_a_draft_cleans_that_draft(night, env, pub, served):
gh = FakeGH(fail={"upload": ns.Refused("github-draft", "upload timed out")})
st = ns.State(last_published=last_published())
with pytest.raises(ns.Refused, match="upload timed out"):
publish(night, st, gh, pub, env)
assert [c for c in gh.calls if c[0] == "delete_draft"] == [("delete_draft", TAG, 101)]
assert gh.release is None and st.open_draft is None and st.last_published.sha == OLD
def test_upload_failure_has_a_persisted_owned_id_before_cleanup(night, env, pub, served):
# Mutation: save ownership only after upload, leaving a surviving draft unowned on disk.
gh = FakeGH(fail={"upload": ns.Refused("github-draft", "upload timed out")})
gh.delete_draft = lambda tag, release_id=None: (_ for _ in ()).throw(ns.Refused("github-delete", "offline"))
st = ns.State(last_published=last_published())
checkpoints = []
def save():
ns.save_state(env.state_path, st)
checkpoints.append(json.loads(env.state_path.read_text()))
with pytest.raises(ns.Refused, match="upload timed out"):
publish(night, st, gh, pub, env, save=save)
assert checkpoints[0].get("open_draft_id") == 101
assert checkpoints[0]["open_draft"] == TAG
assert gh.releases == [(TAG, 101, "draft")]
assert json.loads(env.state_path.read_text())["open_draft_id"] == 101
assert "verify_draft" not in gh.names() and "publish" not in gh.names()
def test_rollback_after_create_deletes_only_the_created_tag(night, env, pub, served):
gh = FakeGH(fail={"verify_draft": ns.Refused("github-draft", "hash differs")})
st = ns.State(open_draft="v0.3.0", last_published=last_published())
with pytest.raises(ns.Refused):
publish(night, st, gh, pub, env)
assert [c for c in gh.calls if c[0] == "delete_draft"] == [("delete_draft", TAG, 101)]
assert st.open_draft is None
def test_a_non_refusal_error_in_the_draft_check_still_deletes_the_draft(night, env, pub, served):
gh = FakeGH(fail={"verify_draft": OSError("disk")})
with pytest.raises(ns.Refused) as e:
publish(night, ns.State(last_published=last_published()), gh, pub, env)
assert e.value.gate == "github-draft" and "OSError" in e.value.detail and ("delete_draft", TAG, 101) in gh.calls
def test_a_failed_cleanup_keeps_the_original_refusal_and_the_open_draft(night, env, pub, served, capsys):
gh = FakeGH(fail={"verify_draft": ns.Refused("github-draft", "hash differs")})
gh.delete_draft = lambda tag, release_id=None: (_ for _ in ()).throw(ns.Refused("github-delete", "offline"))
st = ns.State(last_published=last_published())
with pytest.raises(ns.Refused) as e:
publish(night, st, gh, pub, env)
assert e.value.gate == "github-draft" and st.open_draft == TAG and "offline" in capsys.readouterr().err
def test_a_failed_publish_deletes_a_draft_that_is_still_one(night, env, pub, served):
gh = FakeGH(fail={"publish": ns.Refused("github-publish", "tag at the wrong commit")})
st = ns.State(last_published=last_published())
with pytest.raises(ns.Refused) as e:
publish(night, st, gh, pub, env)
assert e.value.gate == "github-publish" and ("delete_draft", TAG, 101) in gh.calls
assert st.last_published.sha == OLD and served == []
def test_a_failed_publish_check_on_a_public_release_is_never_deleted(night, env, pub, served):
class Public(FakeGH):
def publish(self, tag, sha):
self.release = "published"
self.latest = tag
raise ns.Refused("github-publish", f"{tag} points at the wrong commit")
gh = Public()
st = ns.State(last_published=last_published())
with pytest.raises(ns.Refused) as e:
publish(night, st, gh, pub, env)
assert e.value.gate == "github-publish" and "by hand" in e.value.detail
assert "delete_draft" not in gh.names() and st.open_draft == TAG
assert gh.latest == "v0.3.1" and ("restore_latest", "v0.3.1", TAG) in gh.calls
assert "restored previous Latest v0.3.1" in e.value.detail
assert "v0.3.1" in (night.run_dir / "latest-rollback.log").read_text()
def test_with_no_latest_at_all_the_recovery_reports_it_left_latest_alone(night, env, pub, served):
class NoLatest(FakeGH):
def publish(self, tag, sha): # the edit never reached GitHub, and the repository has no Latest
self.calls.append(("publish", tag, sha))
raise ns.Refused("github-publish", "gh release edit failed")
gh = NoLatest()
gh.latest = None
with pytest.raises(ns.Refused) as e:
publish(night, ns.State(last_published=last_published()), gh, pub, env)
assert ("restore_latest", None, TAG) in gh.calls and gh.latest is None
assert "there is no Latest now" in e.value.detail and "left alone" in e.value.detail
assert "restored" not in e.value.detail and "removed the failed release's Latest mark" not in e.value.detail
def test_a_newer_latest_published_meanwhile_is_never_overwritten_by_the_recovery(night, env, pub, served):
err = ns.Refused("site", "run failed")
gh = FakeGH(fail={"dispatch_site": [err, err]})
real_dispatch = gh.dispatch_site
def dispatch(deadline):
gh.latest = "v0.4.0" # the owner publishes a release while the site deploy runs
real_dispatch(deadline)
gh.dispatch_site = dispatch
with pytest.raises(ns.Refused) as e:
publish(night, ns.State(last_published=last_published()), gh, pub, env)
assert e.value.gate == "site" and gh.latest == "v0.4.0"
assert "Latest is now v0.4.0, not " + TAG + ": left alone" in e.value.detail
def test_a_site_failure_after_publish_retries_once_then_refuses_and_marks_site_pending(night, env, pub, served):
err = ns.Refused("site", "run failed")
gh = FakeGH(fail={"dispatch_site": [err, err]})
st = ns.State(last_published=last_published())
with pytest.raises(ns.Refused) as e:
publish(night, st, gh, pub, env)
assert e.value.gate == "site" and "public" in e.value.detail
assert "unchanged" not in e.value.detail
assert "unverified" in e.value.detail and "may have changed" in e.value.detail
assert gh.names().count("dispatch_site") == 2 and "delete_draft" not in gh.names()
assert st.last_published.tag == TAG and st.last_published.sha == night.sha # the release is public
assert st.site_pending == night.version and st.open_draft is None
assert gh.latest == "v0.3.1" and ("restore_latest", "v0.3.1", TAG) in gh.calls
assert "restored previous Latest v0.3.1" in e.value.detail
def test_a_site_refusal_does_not_enter_the_boot_baseline_through_run_night(env, pub, monkeypatch):
err = ns.Refused("site", "run failed")
gh = FakeGH(fail={"dispatch_site": [err, err]})
baseline = [8000.0, 8100.0]
state = ns.State(last_published=last_published(), boot_baseline=list(baseline))
monkeypatch.setattr(nightly, "run_gates", lambda night, runner: None)
monkeypatch.setattr(nightly, "run_editmode", lambda night, runner: None)
monkeypatch.setattr(nightly, "_build_both", lambda night, runner, free_gb: pub)
monkeypatch.setattr(nightly, "package_zip", lambda night, runner, build, pages: pub[1 if pages else 0])
monkeypatch.setattr(nightly, "run_web_checks", lambda night, runner, build: None)
monkeypatch.setattr(nightly, "previous_build", lambda night, state, client, runner: PREVIOUS)
monkeypatch.setattr(nightly, "check_sizes", lambda *args, **kwargs: SIZES)
monkeypatch.setattr(nightly, "measure_boot", lambda night, runner, build: BOOT_MS)
monkeypatch.setattr(nightly, "run_steam", lambda night, runner: None)
assert env.night(state, gh) == "REFUSED"
saved = ns.load_state(env.state_path)
assert saved.boot_baseline == baseline
assert "REFUSED" in env.log()
def test_a_site_refusal_records_the_restored_latest_in_the_nightly_log(env, pub, served, monkeypatch):
err = ns.Refused("site", "run failed")
gh = FakeGH(fail={"dispatch_site": [err, err]})
def stages(night, state, runner, client, itch, **kw):
night.run_dir.mkdir(parents=True, exist_ok=True)
publish(night, state, client, pub, env, save=kw["save"])
monkeypatch.setattr(nightly, "run_stages", stages)
assert env.night(ns.State(last_published=last_published()), gh) == "REFUSED"
assert "REFUSED" in env.log() and "restored previous Latest v0.3.1" in env.log()
def test_no_previous_latest_is_explicit_in_the_refusal_and_log(night, env, pub, served):
gh = FakeGH(fail={"publish": ns.Refused("github-publish", "wrong commit")})
gh.latest = None
with pytest.raises(ns.Refused) as e:
publish(night, ns.State(), gh, pub, env)
assert ("restore_latest", None, TAG) in gh.calls and gh.latest is None
assert "no previous Latest" in e.value.detail
assert "no previous Latest" in (night.run_dir / "latest-rollback.log").read_text()
def test_a_latest_recovery_failure_names_the_previous_latest(night, env, pub, served):
gh = FakeGH(fail={"publish": ns.Refused("github-publish", "wrong commit"),
"restore_latest": OSError("offline")})
with pytest.raises(ns.Refused) as e:
publish(night, ns.State(), gh, pub, env)
assert "wrong commit" in e.value.detail and "Latest recovery failed (previous Latest v0.3.1)" in e.value.detail
assert "offline" in (night.run_dir / "latest-rollback.log").read_text()
def test_an_interrupt_after_publish_restores_latest_and_records_the_result(night, env, pub, served):
gh = FakeGH(fail={"dispatch_site": KeyboardInterrupt()})
with pytest.raises(KeyboardInterrupt):
publish(night, ns.State(), gh, pub, env)
assert gh.latest == "v0.3.1" and "delete_draft" not in gh.names()
assert any("restored previous Latest v0.3.1" in note for note in night.notes)
def test_a_failed_latest_lookup_refuses_before_the_public_edit(night, env, pub, served):
gh = FakeGH(fail={"latest_tag": ns.Refused("github-latest", "offline")})
with pytest.raises(ns.Refused, match="offline"):
publish(night, ns.State(), gh, pub, env)
assert "publish" not in gh.names() and "restore_latest" not in gh.names()
assert ("delete_draft", TAG, 101) in gh.calls
def test_a_failed_save_after_publish_restores_latest(night, env, pub, served):
gh = FakeGH()
saves = []
def save():
saves.append(True)
if len(saves) == 2: # the save right after publish; _try_save swallows only OSError, so this one escapes
raise TypeError("Object of type Path is not JSON serializable")
with pytest.raises(ns.Refused, match="restored previous Latest v0.3.1"):
publish(night, ns.State(), gh, pub, env, save=save)
assert gh.latest == "v0.3.1" and "delete_draft" not in gh.names()
def test_a_disk_error_saving_state_after_publish_keeps_the_good_release_latest(night, env, pub, served, tmp_path,
monkeypatch):
monkeypatch.setattr(nightly, "notify", lambda *a: None)
blocked = tmp_path / "state.json"
gh, st = FakeGH(), ns.State(last_published=last_published())
saved_ids = []
def save():
if gh.release == "published" and not blocked.is_dir():
saved_ids.append(json.loads(blocked.read_text())["open_draft_id"])
blocked.unlink()
blocked.mkdir() # fail only after publication; the ownership checkpoint must have succeeded
return nightly._try_save(blocked, st)
publish(night, st, gh, pub, env, save=save)
assert saved_ids == [101] and blocked.is_dir()
assert gh.latest == TAG and "restore_latest" not in gh.names() and st.last_published.tag == TAG
@pytest.mark.parametrize("how", ["incomplete-read", "key-error"])
def test_an_unexpected_error_in_the_site_step_still_gets_the_second_attempt(night, env, pub, monkeypatch, how):
import http.client
import nightly_publish as gp
def broken(url, timeout):
raise http.client.IncompleteRead(b"x")
monkeypatch.setattr(nightly, "demo_serves", lambda url, version, *, deadline: gp.demo_serves(
url, version, deadline=deadline, fetch=broken, sleep=lambda s: None, now=iter(range(0, 10**9, 10**8)).__next__))
fail = {"dispatch_site": [KeyError("databaseId"), KeyError("databaseId")]} if how == "key-error" else None
gh, st = FakeGH(fail=fail), ns.State(last_published=last_published())
with pytest.raises(ns.Refused) as e:
publish(night, st, gh, pub, env)
assert e.value.gate == "site" and gh.names().count("dispatch_site") == 2
assert st.site_pending == night.version and st.last_published.tag == TAG
def test_site_pending_is_marked_before_the_site_step_and_saved_with_the_publish(night, env, pub, monkeypatch):
seen = []
monkeypatch.setattr(nightly, "demo_serves", lambda *a, **k: None)
gh, st = FakeGH(), ns.State(last_published=last_published())
gh.dispatch_site = lambda deadline: seen.append(st.site_pending)
publish(night, st, gh, pub, env)
assert seen == [night.version] and st.site_pending is None
class Crash(BaseException):
pass
def test_state_is_saved_right_after_create_draft_and_right_after_publish(night, env, pub, served, tmp_path):
path = tmp_path / "state.json"
saves = []
def save(crash_on):
def f():
ns.save_state(path, st)
saves.append((st.open_draft, st.last_published.tag))
if len(saves) == crash_on:
raise Crash()
return f
st = ns.State(last_published=last_published())
with pytest.raises(Crash):
publish(night, st, FakeGH(), pub, env, save=save(1)) # killed right after create_draft
assert json.loads(path.read_text()).get("open_draft_id") == 101
assert ns.load_state(path).open_draft == TAG and saves[0] == (TAG, last_published().tag)
saves.clear()
st = ns.State(last_published=last_published())
with pytest.raises(Crash):
publish(night, st, FakeGH(), pub, env, save=save(2)) # killed right after publish
disk = ns.load_state(path)
assert disk.last_published.tag == TAG and disk.open_draft is None and disk.last_published.sha == night.sha
def test_a_failing_checkpoint_save_does_not_stop_the_night(env, monkeypatch, capsys):
monkeypatch.setattr(nightly, "save_state", lambda p, st: (_ for _ in ()).throw(OSError("full")))
seen = {}
def stages(night, state, runner, gh, itch, *, no_publish, free_gb, save, no_steam=False):
save()
seen["ok"] = True
return True
monkeypatch.setattr(nightly, "run_stages", stages)
assert env.night() == "PUBLISHED" and seen and "could not save state" in capsys.readouterr().err
def test_a_failed_checkpoint_save_notifies_so_it_is_never_silent(env, monkeypatch):
monkeypatch.setattr(nightly, "save_state", lambda p, st: (_ for _ in ()).throw(OSError("full")))
monkeypatch.setattr(nightly, "run_stages", lambda night, state, runner, gh, itch, *, no_publish, free_gb, save, no_steam=False:
save() or True)
assert env.night() == "PUBLISHED"
assert any("not saved" in a[0].lower() and "full" in a[1] for a in env_notes)
def test_a_failing_demo_check_is_retried_once_and_a_second_success_clears_pending(night, env, pub, monkeypatch):
results = [ns.Refused("site", "old page"), None]
def demo(url, version, *, deadline):
r = results.pop(0)
if r:
raise r
monkeypatch.setattr(nightly, "demo_serves", demo)
gh, st = FakeGH(), ns.State(last_published=last_published(), site_pending="0.2.9")
publish(night, st, gh, pub, env)
assert gh.names().count("dispatch_site") == 2 and st.site_pending is None
def test_a_published_night_updates_state_and_boot_baseline(night, env, pub, served):
gh, st = FakeGH(), ns.State(last_published=last_published(), boot_baseline=[8000.0, 8100.0], open_draft="x")
publish(night, st, gh, pub, env)
assert st.last_published == ns.Published(TAG, night.sha, night.version, SIZES, BOOT_MS)
assert st.boot_baseline == [8000.0, 8100.0, BOOT_MS] and st.open_draft is None and st.site_pending is None
assert served == [(night.cfg.site_demo_url, night.version)]
full = ns.State(last_published=last_published(), boot_baseline=[1.0, 2.0, 3.0, 4.0, 5.0])
publish(night, full, FakeGH(), pub, env)
assert full.boot_baseline == [1.0, 2.0, 3.0, 4.0, 5.0]
def test_itch_is_skipped_with_a_logged_reason_when_there_is_no_client(night, env, pub, served, capsys):
publish(night, ns.State(last_published=last_published()), FakeGH(), pub, env)
assert NO_TEST_PAGE in capsys.readouterr().out
# --- Task 7: itch.io, behind itch_enabled ---------------------------------------------------------------------------------
PREV_TAG = "v0.3.0-nightly.20261027"
PREV_VERSION = "0.3.0-nightly.20261027"
TEST_TARGET = "eyalgolan/statecraft-israel-savetest:html5"
class FakeItch:
"""The itch client as the night uses it; every call lands in `log`, which tests share with FakeGH.calls."""
def __init__(self, log, *, fail=None):
self.log, self.fail = log, fail or {}
def _call(self, name, *args):
self.log.append((f"itch.{name}", *args))
err = self.fail.get(name)
if isinstance(err, list):
err = err.pop(0) if err else None
if err is not None:
raise err
def push(self, folder, version):
self._call("push", Path(folder).name, version)
def wait_live(self, version, deadline):
self._call("wait_live", version)
def matches(self, folder, dest):
self._call("matches", Path(folder).name)
def evidence_file(tmp_path, result):
"""A save test evidence file as savetest() writes it; `result` may also be any JSON value for a broken file."""
path = tmp_path / "savetest-evidence.json"
path.write_text(json.dumps({"result": result} if isinstance(result, str) else result))
return str(path)
def zip_of(path, name):
with zipfile.ZipFile(path, "w") as z:
z.writestr("index.html", name)
return path
@pytest.fixture
def itch_night(night, env, tmp_path, served):
"""An itch-enabled night with real zips for tonight and the previous build: a separate test page is configured
and the save test's PASS evidence is on record, so the push may go ahead (#2056)."""
night.cfg = dataclasses.replace(night.cfg, itch_enabled=True, savetest_itch_target=TEST_TARGET,
itch_evidence=evidence_file(tmp_path, "PASS"))
clone = str(night.cfg.clone)
env.runner.add(["git", "-C", clone, "log", "--format=%s%x1f%aN"], out="Fix a thing\x1fBeri\n")
zips = (zip_of(tmp_path / "web.zip", "tonight"), zip_of(tmp_path / "pages.zip", "pages"))
gh = FakeGH()
gh.baseline = zip_of(tmp_path / "previous-web.zip", "previous")
return night, zips, gh, FakeItch(gh.calls)
def run_itch(itch_night, env, itch="fake", st=None):
night, zips, gh, fake = itch_night
st = st or ns.State(last_published=last_published())
publish(night, st, gh, zips, env, itch=fake if itch == "fake" else itch)
return gh, st
def refused_itch(itch_night, env, itch="fake"):
st = ns.State(last_published=last_published())
with pytest.raises(ns.Refused) as e:
run_itch(itch_night, env, itch, st)
return e.value, itch_night[2], st
def test_itch_disabled_is_logged_and_never_calls_the_client(night, env, pub, served, capsys):
gh = FakeGH()
publish(night, ns.State(last_published=last_published()), gh, pub, env, itch=FakeItch(gh.calls))
assert NO_TEST_PAGE in capsys.readouterr().out
assert gh.names() == ["ensure_tag_available", "create_draft", "verify_draft", "latest_tag", "publish", "dispatch_site"]
def test_itch_enabled_without_a_client_refuses_before_any_store_change(itch_night, env):
err, gh, st = refused_itch(itch_night, env, itch=None)
assert err.gate == "itch" and "create_draft" not in gh.names() and st.open_draft is None
def test_the_itch_push_sits_between_verify_and_publish_and_the_rollback_is_ready_first(itch_night, env):
gh, st = run_itch(itch_night, env)
version = itch_night[0].version
assert gh.calls[3][:3] == ("download", PREV_TAG, "*-web.zip") # after the tag check, create_draft, verify_draft, before the push
assert [c[0] for c in gh.calls if c[0] not in ("release_state",)] == [
"ensure_tag_available", "create_draft", "verify_draft", "download", "itch.push", "itch.wait_live", "itch.matches", "latest_tag", "publish",
"dispatch_site"]
assert ("itch.push", "itch-push", version) in gh.calls and st.last_published.tag == TAG
night = itch_night[0]
assert (night.run_dir / "itch-push/index.html").read_text() == "tonight"
assert (night.run_dir / "itch-rollback/index.html").read_text() == "previous"
@pytest.mark.parametrize("how", ["download", "bad-zip"])
def test_an_unusable_rollback_target_refuses_before_any_push(itch_night, env, how):
night, zips, gh, fake = itch_night
if how == "download":
gh.fail["download"] = ns.Refused("github-download", "0 files matching")
else:
gh.baseline.write_bytes(b"not a zip")
err, gh, st = refused_itch(itch_night, env)
assert err.gate == "itch-rollback"
assert not [c for c in gh.calls if c[0].startswith("itch.")] and "publish" not in gh.names()
assert ("delete_draft", TAG, 101) in gh.calls and st.open_draft is None
@pytest.mark.parametrize("step", ["push", "wait_live", "matches"])
def test_an_itch_failure_rolls_back_and_deletes_the_draft(itch_night, env, step):
night, zips, gh, fake = itch_night
fake.fail[step] = [ns.Refused("itch", f"{step} failed")]
err, gh, st = refused_itch(itch_night, env)
assert err.gate == "itch" and f"{step} failed" in err.detail
itch_calls = [c for c in gh.calls if c[0].startswith("itch.")]
assert ("itch.push", "itch-rollback", PREV_VERSION) in itch_calls and ("itch.wait_live", PREV_VERSION) in itch_calls
names = [n for n in gh.names() if n != "release_state"]
assert names[-2:] == ["itch.wait_live", "delete_draft"]
assert "publish" not in names and "dispatch_site" not in names
assert st.open_draft is None and st.last_published.sha == OLD
def test_a_failed_rollback_is_named_in_the_refusal_and_notified(itch_night, env):
night, zips, gh, fake = itch_night
fake.fail["wait_live"] = [ns.Refused("itch", "never live"), None]
fake.fail["push"] = [None, ns.Refused("itch", "butler push exited 1")]
err, gh, st = refused_itch(itch_night, env)
assert err.gate == "itch" and "never live" in err.detail
assert "rollback" in err.detail and "butler push exited 1" in err.detail and "by hand" in err.detail
assert ("delete_draft", TAG, 101) in gh.calls # the draft is still cleaned up
assert any("itch" in a[0].lower() and "rollback" in a[1].lower() for a in env_notes)
def test_a_github_publish_failure_after_itch_rolls_itch_back(itch_night, env):
night, zips, gh, fake = itch_night
gh.fail["publish"] = ns.Refused("github-publish", "tag at the wrong commit")
err, gh, st = refused_itch(itch_night, env)
assert err.gate == "github-publish"
assert ("itch.push", "itch-rollback", PREV_VERSION) in gh.calls and ("itch.wait_live", PREV_VERSION) in gh.calls
assert ("delete_draft", TAG, 101) in gh.calls
def test_a_failed_rollback_after_a_publish_failure_is_named_and_notified(itch_night, env):
night, zips, gh, fake = itch_night
gh.fail["publish"] = ns.Refused("github-publish", "tag at the wrong commit")
fake.fail["push"] = [None, ns.Refused("itch", "butler push exited 1")]
err, gh, st = refused_itch(itch_night, env)
assert err.gate == "github-publish" and "tag at the wrong commit" in err.detail
assert "rollback" in err.detail and "butler push exited 1" in err.detail
assert any("rollback" in a[1].lower() for a in env_notes)
def test_an_interrupt_during_publish_rolls_itch_back_and_cleans_the_draft(itch_night, env):
night, zips, gh, fake = itch_night
gh.fail["publish"] = KeyboardInterrupt()
st = ns.State(last_published=last_published())
with pytest.raises(KeyboardInterrupt):
run_itch(itch_night, env, st=st)
assert ("itch.push", "itch-rollback", PREV_VERSION) in gh.calls and ("itch.wait_live", PREV_VERSION) in gh.calls
assert ("delete_draft", TAG, 101) in gh.calls and st.open_draft is None
def test_the_itch_skip_reason_is_noted_on_the_night(night, env, pub, served):
publish(night, ns.State(last_published=last_published()), FakeGH(), pub, env)
assert night.notes == [NO_TEST_PAGE]
def test_the_night_notes_reach_the_log_line(env, monkeypatch):
def stages(night, state, runner, gh, itch, *, no_publish, free_gb, save, no_steam=False):
night.notes.append("itch: skipped (save test not passed)")
return True
monkeypatch.setattr(nightly, "run_stages", stages)
assert env.night() == "PUBLISHED"
assert "PUBLISHED" in env.log() and "itch: skipped (save test not passed)" in env.log()
def test_a_site_failure_after_publish_does_not_roll_itch_back(itch_night, env):
night, zips, gh, fake = itch_night
err_site = ns.Refused("site", "run failed")
gh.fail["dispatch_site"] = [err_site, err_site]
err, gh, st = refused_itch(itch_night, env)
assert err.gate == "site"
assert [c[0] for c in gh.calls if c[0].startswith("itch.")] == ["itch.push", "itch.wait_live", "itch.matches"]
assert "delete_draft" not in gh.names()
# --- #2056: itch only with a separate test page and a recorded save test PASS -------------------------------------------
NO_TEST_PAGE = "itch: skipped (the job config has no savetest_itch_target, so no save test can run on a separate test page)"
@pytest.mark.parametrize("change, reason", [
({"savetest_itch_target": None}, NO_TEST_PAGE),
({"savetest_itch_target": ""}, NO_TEST_PAGE),
({"savetest_itch_target": "eyalgolan/statecraft-israel:savetest"}, "must not be the public itch project"),
({"savetest_itch_target": "EyalGolan/Statecraft-Israel:html5"}, "must not be the public itch project"),
({"itch_enabled": False}, "itch: skipped (save test not passed)"),
({"itch_evidence": None}, "itch_enabled is set but no save test evidence is recorded"),
({"itch_evidence": "/nonexistent/evidence.json"}, "is unreadable"),
("INCONCLUSIVE", "does not record a save test PASS"),
(["PASS"], "does not record a save test PASS"),
])
def test_itch_is_skipped_with_its_reason_unless_a_test_page_and_a_pass_are_on_record(itch_night, env, tmp_path, capsys,
change, reason):
night = itch_night[0]
if not isinstance(change, dict): # a broken or non-PASS evidence file
change = {"itch_evidence": evidence_file(tmp_path, change)}
night.cfg = dataclasses.replace(night.cfg, **change)
gh, st = run_itch(itch_night, env)
assert not [c for c in gh.calls if c[0].startswith("itch.")] and "download" not in gh.names()
assert len(night.notes) == 1 and night.notes[0].startswith("itch: skipped (") and reason in night.notes[0]
assert night.notes[0] in capsys.readouterr().out
assert st.last_published.tag == TAG # the GitHub release still goes out; only itch is held back
def test_the_job_config_of_2_november_skips_itch_and_names_the_missing_keys(tmp_path):
config = tmp_path / "config.json" # the live job config held only this key on 2 Nov 2026
config.write_text(json.dumps({"itch_page_url": "https://eyalgolan.itch.io/statecraft-israel"}))
assert nightly.itch_skip_reason(ns.load_config(config)) == NO_TEST_PAGE[len("itch: skipped ("):-1]
def test_a_pass_on_record_with_a_separate_test_page_lets_the_push_go_ahead(itch_night):
assert nightly.itch_skip_reason(itch_night[0].cfg) is None
# --- the stage wiring ---------------------------------------------------------------------------------------------------
@pytest.fixture
def stages(night, env, tmp_path, monkeypatch):
"""Every stage replaced by a recorder, so the order and the arguments are what is tested."""
order = []
source_gz, pages = tmp_path / "Web-gzip", tmp_path / "Web-pages"
source_gz.mkdir()
(source_gz / "index.html").write_text("first player")
gz = night.run_dir / "Web-gzip"
zips = {False: tmp_path / "web.zip", True: tmp_path / "pages.zip"}
prev = tmp_path / "prev.zip"
def rec(name, result=None):
def f(*a, **k):
order.append((name, a, k))
return result(a, k) if callable(result) else result
monkeypatch.setattr(nightly, name, f)
rec("run_gates")
rec("run_editmode")
rec("build_web", lambda a, k: pages if k["pages"] else source_gz)
rec("assert_clean_tree")
rec("package_zip", lambda a, k: zips[a[3]])
rec("run_web_checks")
rec("check_sizes", SIZES)
rec("measure_boot", BOOT_MS)
rec("publish_night")
gh = FakeGH()
gh.baseline = prev
return type("S", (), dict(order=order, gz=gz, source_gz=source_gz, pages=pages, zips=zips, prev=prev, gh=gh,
names=lambda self: [o[0] for o in order]))()
def test_the_stages_run_in_the_brief_order(night, env, stages, capsys):
st = ns.State(last_published=last_published())
assert nightly.run_stages(night, st, env.runner, stages.gh, None, no_publish=False, free_gb=lambda p: 100.0)
assert stages.names() == ["run_gates", "run_editmode", "build_web", "build_web", "assert_clean_tree",
"package_zip", "package_zip", "run_web_checks", "run_web_checks", "check_sizes",
"measure_boot", "publish_night"]
builds = [o for o in stages.order if o[0] == "build_web"]
assert [b[2]["pages"] for b in builds] == [False, True]
packages = [o for o in stages.order if o[0] == "package_zip"]
assert [p[1][2] for p in packages] == [stages.gz, stages.pages]
checks = [o for o in stages.order if o[0] == "run_web_checks"]
assert [c[1][2] for c in checks] == [stages.gz, stages.pages] # web checks on BOTH builds
boot = next(o for o in stages.order if o[0] == "measure_boot")
assert boot[1][2] == stages.gz
sizes = next(o for o in stages.order if o[0] == "check_sizes")
assert sizes[1][2:5] == (stages.gz, stages.prev, OLD) and sizes[2]["runner"] is env.runner
assert stages.gh.calls[-1][:3] == ("download", "v0.3.0-nightly.20261027", "*-web.zip")
pub_call = stages.order[-1]
assert pub_call[1][4] == (stages.zips[False], stages.zips[True]) and pub_call[1][5:7] == (SIZES, BOOT_MS)
assert pub_call[2]["previous"] == ("v0.3.0-nightly.20261027", OLD) and callable(pub_call[2]["save"])
assert stages.gh.names().count("previous_build_tag") == 1 # once a night
def test_no_publish_stops_before_any_store_call(night, env, stages, capsys):
st = ns.State(last_published=last_published())
assert nightly.run_stages(night, st, env.runner, stages.gh, None, no_publish=True,
free_gb=lambda p: 100.0) is False
assert "publish_night" not in stages.names() and f"NO-PUBLISH: all gates passed for {TAG}\n" in \
capsys.readouterr().out
assert stages.gh.names() == ["previous_build_tag", "download"] # reads only
def test_a_no_publish_night_touches_no_record_and_no_state(env, monkeypatch, capsys):
monkeypatch.setattr(nightly, "run_stages", lambda *a, **k: (print(f"NO-PUBLISH: all gates passed for {TAG}")
or False))
assert env.night(no_publish=True) == "NO-PUBLISH"
assert env.log() == "" and not env.state_path.exists() and not env.cfg.handoff.exists()
assert f"NO-PUBLISH: all gates passed for {TAG}" in capsys.readouterr().out and env_notes == []
def test_a_published_night_is_recorded_as_published(env, monkeypatch):
monkeypatch.setattr(nightly, "run_stages", lambda *a, **k: True)
assert env.night() == "PUBLISHED"
assert "PUBLISHED" in env.log() and f"tag={TAG}" in env.log()
def test_a_boot_slowdown_refuses_and_a_collecting_baseline_passes(night, env, stages):
st = ns.State(last_published=last_published(), boot_baseline=[8000.0, 8100.0, 8050.0, 8100.0, 8000.0])
nightly.run_stages(night, st, env.runner, stages.gh, None, no_publish=True, free_gb=lambda p: 100.0) # 8200 <= limit
# The next simulated night has its own evidence directory in production; discard only this test's completed copy.
shutil.rmtree(stages.gz)
st.boot_baseline = [1000.0, 1000.0, 1000.0, 1000.0, 1000.0]
with pytest.raises(ns.Refused) as e:
nightly.run_stages(night, st, env.runner, stages.gh, None, no_publish=True, free_gb=lambda p: 100.0)
assert e.value.gate == "boot" and "publish_night" not in stages.names()
def test_a_failed_build_still_checks_the_tree_before_the_refusal(night, env, stages, monkeypatch):
def boom(n, r, *, pages, free_gb):
if pages:
raise ns.Refused("build-web", "the Unity build exited 1")
return stages.source_gz
monkeypatch.setattr(nightly, "build_web", boom)
with pytest.raises(ns.Refused) as e:
nightly.run_stages(night, ns.State(last_published=last_published()), env.runner, stages.gh, None,
no_publish=False, free_gb=lambda p: 100.0)
assert e.value.gate == "build-web" and "assert_clean_tree" in stages.names()
assert "package_zip" not in stages.names() and "publish_night" not in stages.names()
def test_a_dirty_tree_after_a_failed_build_is_noted_not_substituted(night, env, stages, monkeypatch, capsys):
monkeypatch.setattr(nightly, "build_web", lambda *a, **k: (_ for _ in ()).throw(ns.Refused("build-web", "x")))
def dirty(n, r):
raise ns.Refused("dirty-tree", "settings still changed")
monkeypatch.setattr(nightly, "assert_clean_tree", dirty)
with pytest.raises(ns.Refused) as e:
nightly.run_stages(night, ns.State(last_published=last_published()), env.runner, stages.gh, None,
no_publish=False, free_gb=lambda p: 100.0)
assert e.value.gate == "build-web"
assert "settings still changed" in (night.run_dir / "dirty-tree.note").read_text()
assert "not clean" in capsys.readouterr().err
def test_a_dirty_tree_after_good_builds_refuses(night, env, stages, monkeypatch):
def dirty(n, r):
raise ns.Refused("dirty-tree", "changed")
monkeypatch.setattr(nightly, "assert_clean_tree", dirty)
with pytest.raises(ns.Refused) as e:
nightly.run_stages(night, ns.State(last_published=last_published()), env.runner, stages.gh, None,
no_publish=False, free_gb=lambda p: 100.0)
assert e.value.gate == "dirty-tree" and "package_zip" not in stages.names()
class LoggingWebRunner(WebRunner):
def run(self, cmd, **k):
if "-executeMethod" in cmd and "-logFile" in cmd:
Path(cmd[cmd.index("-logFile") + 1]).write_text(
"boring\nAssets/X.cs(3,4): error CS0103: The name 'y' does not exist\nmore\nBuildFailedException: nope\n")
return super().run(cmd, **k)
def test_a_failed_build_names_the_unity_errors_in_its_refusal(night, env):
r = LoggingWebRunner(night, build_code=1)
with pytest.raises(ns.Refused) as e:
nightly.build_web(night, r, pages=False, free_gb=lambda p: 100.0)
assert e.value.gate == "build-web-gz" and "error CS0103" in e.value.detail and "BuildFailedException" in e.value.detail
assert "boring" not in e.value.detail
def test_a_failed_build_without_a_unity_log_says_so(night, env):
r = WebRunner(night, build_code=1)
with pytest.raises(ns.Refused) as e:
nightly.build_web(night, r, pages=False, free_gb=lambda p: 100.0)
assert "no Unity log" in e.value.detail
def test_the_release_runbook_names_each_web_and_package_gate():
text = (Path(__file__).resolve().parents[2] / "docs/RELEASING.md").read_text()
gates = text.split("The gates, in order.", 1)[1].split("**Size budget.**", 1)[0]
for gate in ("build-web-gz", "build-web-pages", "package-gz", "package-pages"):
assert f"`{gate}`" in gates
assert "`build-web`" not in gates and "`package`" not in gates
# --- the clients ----------------------------------------------------------------------------------------------------------
def test_clients_are_a_github_for_the_configured_repo_and_no_itch(env, monkeypatch):
monkeypatch.setattr(nightly.shutil, "which", lambda name: "/usr/bin/gh")
gh, itch = nightly._clients(env.cfg)
assert isinstance(gh, nightly.GitHub) and gh.slug == env.cfg.repo_slug and gh.cwd == env.cfg.clone and itch is None
def test_an_itch_client_exists_only_when_itch_is_enabled(env, monkeypatch, tmp_path):
monkeypatch.setattr(nightly.shutil, "which", lambda name: "/usr/bin/gh")
butler = tmp_path / "butler"
butler.write_text("x")
cfg = dataclasses.replace(env.cfg, itch_enabled=True, butler=butler)
gh, itch = nightly._clients(cfg)
assert isinstance(itch, nightly.Itch) and itch.target == cfg.itch_target and itch.butler == butler
def test_enabled_itch_without_butler_is_a_recorded_refusal(env, monkeypatch, tmp_path):
monkeypatch.setattr(nightly.shutil, "which", lambda name: "/usr/bin/gh")
with pytest.raises(ns.Refused) as e:
nightly._clients(dataclasses.replace(env.cfg, itch_enabled=True, butler=tmp_path / "missing"))
assert e.value.gate == "itch-client"
def test_a_missing_gh_is_a_github_client_refusal(env, monkeypatch):
monkeypatch.setattr(nightly.shutil, "which", lambda name: None)
with pytest.raises(ns.Refused) as e:
nightly._clients(env.cfg)
assert e.value.gate == "github-client"
def test_an_unusable_client_is_a_recorded_github_client_refusal_not_internal(env):
err = ns.Refused("github-client", "gh is not on PATH")
out = nightly.run_night(env.cfg, env.state_path, env.job, env.runner, None, None, now=NOW, manual=False,
no_publish=False, client_error=err, free_gb=lambda p: 100.0)
assert out == "REFUSED" and "gate=github-client" in env.log() and "gh is not on PATH" in env.log()
assert env.runner.calls == [] and len(env_notes) == 1
def test_a_refused_night_records_the_real_failing_step_log(env, monkeypatch):
clone = str(env.cfg.clone)
env.runner.add(["uv", "run", f"{clone}/tools/build_sim_for_unity.py"], code=2, out="compiler exploded\n")
env.runner.add(["dotnet", "build-server", "shutdown"], out="servers stopped\n")
def stages(night, state, runner, gh, itch, *, no_publish, free_gb, save, no_steam=False):
nightly.run_gates(night, runner)
monkeypatch.setattr(nightly, "run_stages", stages)
assert env.night() == "REFUSED"
step_log = env.job / "runs/20261028-030000/build-sim.log"
line = env.log().strip().splitlines()[-1]
assert "gate=build-sim" in line and f"log={step_log}" in line
assert "compiler exploded" in step_log.read_text()
assert "NIGHTLY REFUSED gate=build-sim" in step_log.read_text()
assert "build_sim_for_unity exited 2" in step_log.read_text()
def test_a_capture_refusal_gets_a_cause_log(env):
prefix, _, out, effect = env.runner.rules[0]
env.runner.rules[0] = (prefix, 128, out, effect)
assert env.night() == "REFUSED"
evidence = env.job / "runs/20261028-030000/refused-command.log"
assert f"log={evidence}" in env.log() and evidence.is_file()
assert "git" in evidence.read_text() and "exited 128" in evidence.read_text()
# --- Task 8: the two-upload itch save test ----------------------------------------------------------------------------
ITCH_HOST = "https://html-classic.itch.zone"
SAVED = "PERSISTENCE saved 1948-05-16 turn 1 hash ab12\n"
class SaveItch:
"""The itch client of the save test: each push moves the live build id on by one."""
def __init__(self, calls, *, fail=None, same=False, ids=True, live_as=None):
self.calls, self.fail, self.pushes, self.build = calls, fail or {}, 0, 100
self.same, self.ids = same, ids # `same`: butler keeps showing upload A's build; `ids`: False shows none
self.live_as, self.live = live_as, None # `live_as`: the version butler shows live after wait_live
def push(self, folder, version):
self.calls.append(("itch.push", Path(folder).name, version))
if "push" in self.fail:
raise self.fail["push"]
self.pushes += 1
self.build += 1
def wait_live(self, version, deadline):
self.calls.append(("itch.wait_live", version))
if "wait_live" in self.fail:
raise self.fail["wait_live"]
self.live = self.live_as or version
def live_frame_ids(self, version):
self.calls.append(("itch.live_frame_ids", version))
if not self.ids or version != self.live: # as Itch.live_frame_ids: only the expected version's ids
return None
return UPLOAD_ID, 101 if self.same else self.build
class SaveRunner(FakeRunner):
"""Answers the web_check runs: the first-save run prints `saved`, a --expect run answers `loads` (one per call)."""
def __init__(self, *, saved=(0, "PASS: saw x\n" + SAVED), loads=((0, "PASS: saw GAME OK\n"),) * 2):
super().__init__()
self.saved, self.loads, self.runs = saved, list(loads), []
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)
Path(log).write_text(text)
return code
GAME_HTML = '<script>createUnityInstance(canvas, {productVersion: "0.3.2"})</script>' # the Statecraft template
class Page:
def __init__(self, text, *, url=None, status=200):
self.text, self.url, self.status = text, url, status
def geturl(self):
return self.url
def __enter__(self):
return self
def __exit__(self, *a):
return False
def read(self):
return self.text.encode()
UPLOAD_ID = 19840947
def frame_of(build):
return f"{ITCH_HOST}/html/{UPLOAD_ID}-{build}/index.html"
def http_error(url, code, retry_after=None):
import email.message
import urllib.error
headers = email.message.Message()
if retry_after is not None:
headers["Retry-After"] = retry_after
return urllib.error.HTTPError(url, code, "error", headers, None)
def frame_for(itch, fetched, *, missing=0, code=404, answer=None):
"""A fetch answering only the game frame of the itch client's live build (never an itch page): its first
`missing` answers are HTTP `code`, as while itch still unpacks an upload; `answer(url)` replaces the game page."""
def fetch(url, timeout=30):
fetched.append(url)
assert url == frame_of(101 if itch.same else itch.build)
if len(fetched) <= missing:
raise http_error(url, code)
return answer(url) if answer else Page(GAME_HTML, url=url)
return fetch
class Saved:
"""A save test: a config file, a published release and the fakes."""
def __init__(self, tmp_path, monkeypatch, *, release="published", target=TEST_TARGET, itch_kw=None, **runner_kw):
self.job = tmp_path / "job"
self.job.mkdir()
self.config = self.job / "config.json"
config = {"savetest_itch_target": target, "itch_page_url": "https://eyalgolan.itch.io/statecraft-israel"}
self.config.write_text(json.dumps({k: v for k, v in config.items() if v is not None}) + "\n")
self.cfg = ns.load_config(self.config)
self.cfg = dataclasses.replace(self.cfg, handoff=tmp_path / "HANDOFF.md")
self.gh = FakeGH(release=release)
self.gh.baseline = zip_of(tmp_path / "tonight-web.zip", "tonight")
self.itch = SaveItch(self.gh.calls, **(itch_kw or {}))
self.fetched = []
self.runner = SaveRunner(**runner_kw)
monkeypatch.setattr(nightly, "find_chrome", lambda: Path("/fake/chrome"))
def run(self, fetch=None, tag=TAG, sleep=lambda s: None):
return nightly.savetest(self.cfg, self.config, self.job, self.runner, self.gh, self.itch, tag=tag,
fetch=fetch or frame_for(self.itch, self.fetched), sleep=sleep)
def evidence(self):
return json.loads(next((self.job / "savetest").glob("*/evidence.json")).read_text())
def enabled(self):
return json.loads(self.config.read_text()).get("itch_enabled", False)
def log(self):
return (self.job / "LOG.md").read_text()
@pytest.fixture
def saved(tmp_path, monkeypatch, no_processes):
return lambda **kw: Saved(tmp_path, monkeypatch, **kw)
def test_savetest_passes_only_with_matching_tuple_new_url_same_origin(saved):
t = saved()
assert t.run() == "PASS"
version = TAG[1:]
assert [c for c in t.gh.calls if c[0].startswith("itch.")] == [
("itch.push", "folder", f"{version}-savetest-a"), ("itch.wait_live", f"{version}-savetest-a"),
("itch.live_frame_ids", f"{version}-savetest-a"),
("itch.push", "folder", f"{version}-savetest-b"), ("itch.wait_live", f"{version}-savetest-b"),
("itch.live_frame_ids", f"{version}-savetest-b")]
assert t.fetched == [frame_of(101), frame_of(102)] # #2056: only the build's own frame, never the itch page
first, b1, b2 = t.runner.runs
profile = first[first.index("--profile") + 1]
assert first[first.index("--url") + 1] == f"{ITCH_HOST}/html/19840947-101/index.html" and "--first-save" in first
for run in (b1, b2): # B twice, same frame URL, same kept profile, the full tuple
assert run[run.index("--url") + 1] == f"{ITCH_HOST}/html/19840947-102/index.html"
assert run[run.index("--profile") + 1] == profile
assert run[run.index("--expect") + 1] == "GAME OK 1948-05-16 turn 1 hash ab12"
assert run[:5] == ["uv", "run", str(nightly.TOOLS / "machine_lock.py"), "--shared", "--"]
ev = t.evidence()
assert ev["upload_a"] == {"upload_id": UPLOAD_ID, "build_id": 101, "frame_url": frame_of(101)}
assert ev["upload_b"] == {"upload_id": UPLOAD_ID, "build_id": 102, "frame_url": frame_of(102)} and ev["tuple"] == {"date": "1948-05-16", "turn": 1, "hash": "ab12"}
assert ev["chrome"] == "/fake/chrome" and len(ev["zip_sha256"]) == 64 and ev["result"] == "PASS"
assert t.enabled() and json.loads(t.config.read_text())["itch_evidence"].endswith("evidence.json")
assert "SAVETEST PASS" in t.log() and TAG in t.log()
def test_savetest_evidence_write_failure_is_recorded_once_as_inconclusive(saved, monkeypatch):
t = saved()
real_write = Path.write_text
def write(path, text, *args, **kwargs):
if path.name == "evidence.json":
raise OSError("evidence disk full")
return real_write(path, text, *args, **kwargs)
monkeypatch.setattr(Path, "write_text", write)
assert t.run() == "INCONCLUSIVE" and not t.enabled()
lines = [line for line in t.log().splitlines() if "SAVETEST" in line]
assert len(lines) == 1 and f"SAVETEST INCONCLUSIVE tag={TAG}" in lines[0]
assert "OSError: evidence disk full" in lines[0]
def test_savetest_enable_refusal_is_recorded_once_as_inconclusive(saved, monkeypatch):
t = saved()
monkeypatch.setattr(nightly, "enable_itch",
lambda *a: (_ for _ in ()).throw(ns.Refused("config", "changed during save test")))
assert t.run() == "INCONCLUSIVE" and not t.enabled()
lines = [line for line in t.log().splitlines() if "SAVETEST" in line]
assert len(lines) == 1 and f"SAVETEST INCONCLUSIVE tag={TAG} config: changed during save test" in lines[0]
assert t.evidence()["result"] == "INCONCLUSIVE"
def test_savetest_same_frame_url_is_inconclusive_and_keeps_itch_off(saved):
t = saved(itch_kw={"same": True})
assert t.run() == "INCONCLUSIVE"
assert not t.enabled() and len(t.runner.runs) == 1 # B is never loaded
assert "same frame URL" in t.evidence()["detail"] and "SAVETEST INCONCLUSIVE" in t.log()
def test_both_frames_are_on_the_one_frame_origin():
# IndexedDB is per origin: the frame URL is built from butler's ids on one fixed host, so A and B share it
a = urllib.parse.urlsplit(nightly.itch_build_frame_url(UPLOAD_ID, 101))
b = urllib.parse.urlsplit(nightly.itch_build_frame_url(UPLOAD_ID, 102))
assert (a.scheme, a.netloc) == (b.scheme, b.netloc) == ("https", "html-classic.itch.zone") and a.path != b.path
# --- review round on #2237 ------------------------------------------------------------------------------------------
def test_the_frame_ids_must_belong_to_the_version_this_run_pushed(saved):
t = saved(itch_kw={"live_as": "9.9.9-savetest-a"}) # another run's upload went live in between
assert t.run() == "INCONCLUSIVE" and t.runner.runs == [] and t.fetched == [] and not t.enabled()
assert f"{TAG[1:]}-savetest-a" in t.evidence()["detail"]
@pytest.mark.parametrize("answer", [
lambda url: Page("<html>Sign in to itch.io</html>", url=url), # 200, not the game
lambda url: Page(GAME_HTML, url="https://itch.io/login"), # redirected elsewhere
lambda url: Page(GAME_HTML, url=url, status=203), # not a plain 200
])
def test_only_the_game_page_itself_counts_as_a_served_frame(saved, answer):
t = saved()
sleeps = []
assert t.run(frame_for(t.itch, t.fetched, answer=answer), sleep=sleeps.append) == "INCONCLUSIVE"
assert t.runner.runs == [] and not t.enabled() and "not the game" in t.evidence()["detail"]
assert sum(sleeps) <= nightly.SAVETEST_FRAME_TRIES * nightly.SAVETEST_FRAME_SLEEP
@pytest.mark.parametrize("code", [401, 410, 500])
def test_any_other_http_answer_from_the_frame_ends_inconclusive_at_once(saved, code):
t = saved()
assert t.run(frame_for(t.itch, t.fetched, missing=10_000, code=code)) == "INCONCLUSIVE"
assert t.runner.runs == [] and len(t.fetched) == 1 and f"HTTP {code}" in t.evidence()["detail"]
def test_an_inconclusive_save_test_prints_its_recorded_line_and_evidence_path(saved, capsys):
# The v0.4.1 run (11 Nov 2026) printed only INCONCLUSIVE; the why was in LOG.md, HANDOFF.md and evidence.json alone.
t = saved()
assert t.run(frame_for(t.itch, t.fetched, missing=10_000, code=404)) == "INCONCLUSIVE"
recorded = next(line for line in t.log().splitlines() if "SAVETEST" in line).removeprefix("- ")
evidence = next((t.job / "savetest").glob("*/evidence.json"))
assert "still answered HTTP 404" in recorded
assert capsys.readouterr().out.splitlines() == [recorded, f"evidence: {evidence}"]
def test_a_save_test_prints_no_evidence_path_when_its_file_disagrees_with_the_result(saved, monkeypatch, capsys):
# A PASS evidence file is written, enabling itch fails and the INCONCLUSIVE rewrite fails: the file on disk still
# says PASS, so the command prints only the recorded line.
t = saved()
real_write, writes = Path.write_text, []
def write(path, text, *args, **kwargs):
if path.name == "evidence.json":
writes.append(path)
if len(writes) > 1:
raise OSError("evidence disk full")
return real_write(path, text, *args, **kwargs)
def enable_itch(*args):
raise OSError("config read-only")
monkeypatch.setattr(Path, "write_text", write)
monkeypatch.setattr(nightly, "enable_itch", enable_itch)
assert t.run() == "INCONCLUSIVE" and len(writes) == 2 and t.evidence()["result"] == "PASS"
recorded = next(line for line in t.log().splitlines() if "SAVETEST" in line).removeprefix("- ")
assert recorded == f"SAVETEST INCONCLUSIVE tag={TAG} OSError: config read-only"
assert capsys.readouterr().out.splitlines() == [recorded]
def test_a_b_frame_that_is_never_served_is_inconclusive_not_fail(saved):
t = saved()
def fetch(url, timeout=30):
if t.itch.pushes == 2:
raise http_error(url, 404)
return Page(GAME_HTML, url=url)
assert t.run(fetch) == "INCONCLUSIVE" and len(t.runner.runs) == 1 and not t.enabled()
def test_a_second_save_test_pushes_nothing_while_one_runs(saved):
import fcntl
t = saved()
with (t.job / "savetest.lock").open("a") as held:
fcntl.flock(held, fcntl.LOCK_EX | fcntl.LOCK_NB)
assert t.run() == "INCONCLUSIVE"
assert not any(c[0].startswith("itch.") or c[0] == "download" for c in t.gh.calls) and t.runner.runs == []
assert "another save test" in t.log() and not t.enabled()
assert t.run() == "PASS" # the lock is free again once the other run ends
@pytest.mark.parametrize("target", [" eyalgolan/statecraft-israel-savetest:html5", "eyalgolan/statecraft-israel/:html5",
"eyalgolan/statecraft-israel:", "eyalgolan/statecraft-israel-savetest:html5\n",
"eyalgolan/statecraft israel:html5"])
def test_a_malformed_save_test_target_is_refused_before_any_push(saved, target):
t = saved(target=target)
assert t.run() == "INCONCLUSIVE" and not t.enabled() and "test page" in t.log()
assert not any(c[0].startswith("itch.") or c[0] == "download" for c in t.gh.calls)
def test_the_project_of_the_public_page_url_is_refused_as_a_test_target(saved):
t = saved(target="eyalgolan/other-game:html5")
t.cfg = dataclasses.replace(t.cfg, itch_page_url="https://EyalGolan.itch.io/other-game/")
assert t.run() == "INCONCLUSIVE" and "must not be the public itch project" in t.log()
assert not any(c[0].startswith("itch.") for c in t.gh.calls)
def test_a_save_test_pass_enables_the_nightly_push(saved):
t = saved()
assert t.run() == "PASS"
assert nightly.itch_skip_reason(ns.load_config(t.config)) is None
def test_savetest_mismatch_fails_and_keeps_itch_off(saved):
t = saved(loads=((1, "TIMEOUT: never saw GAME OK\n"),))
assert t.run() == "FAIL" and not t.enabled() and "SAVETEST FAIL" in t.log()
assert len(t.runner.runs) == 2 # A, then the first load of B: no second load after a failure
def test_savetest_second_load_failing_is_a_fail(saved):
t = saved(loads=((0, "PASS: saw x\n"), (1, "TIMEOUT\n")))
assert t.run() == "FAIL" and not t.enabled()
def test_savetest_a_timed_out_load_is_inconclusive(saved):
t = saved(loads=((124, ""),))
assert t.run() == "INCONCLUSIVE" and not t.enabled()
@pytest.mark.parametrize("saved_run", [(1, "FAIL: x\n"), (0, "PASS: saw x\n"), (0, "no pass\n" + SAVED)])
def test_savetest_without_a_durable_first_save_is_inconclusive(saved, saved_run):
t = saved(saved=saved_run)
assert t.run() == "INCONCLUSIVE" and not t.enabled() and len(t.runner.runs) == 1
assert [c[0] for c in t.gh.calls].count("itch.push") == 1 # B is never pushed
@pytest.mark.parametrize("kw", [{"release": "draft"}, {"release": None}])
def test_savetest_needs_a_published_nightly(saved, kw):
t = saved(**kw)
assert t.run() == "INCONCLUSIVE" and not t.enabled()
assert not any(c[0].startswith("itch.") or c[0] == "download" for c in t.gh.calls) and t.runner.runs == []
assert "SAVETEST INCONCLUSIVE" in t.log()
def test_savetest_waits_while_itch_is_still_unpacking_the_upload(saved):
t = saved() # 28 Oct 2026: itch took about 17 minutes to unpack the web build after butler showed it live
sleeps = []
assert t.run(frame_for(t.itch, t.fetched, missing=30), sleep=sleeps.append) == "PASS" and t.enabled()
assert t.fetched[:31] == [frame_of(101)] * 31 and sleeps[:30] == [nightly.SAVETEST_FRAME_SLEEP] * 30
@pytest.mark.parametrize("code", [403, 404])
def test_a_frame_that_never_loads_ends_inconclusive_within_the_wait_budget(saved, code):
t = saved() # e.g. a frame itch would not serve signed out: nothing is played, itch stays off
sleeps = []
assert t.run(frame_for(t.itch, t.fetched, missing=10_000, code=code), sleep=sleeps.append) == "INCONCLUSIVE"
assert not t.enabled() and t.runner.runs == [] and [c[0] for c in t.gh.calls].count("itch.push") == 1
assert sum(sleeps) <= nightly.SAVETEST_FRAME_TRIES * nightly.SAVETEST_FRAME_SLEEP
assert f"HTTP {code}" in t.evidence()["detail"] and frame_of(101) in t.evidence()["detail"]
def test_savetest_without_live_frame_ids_is_inconclusive(saved):
t = saved(itch_kw={"ids": False})
assert t.run() == "INCONCLUSIVE" and t.runner.runs == [] and t.fetched == [] and not t.enabled()
assert "upload and build ids" in t.evidence()["detail"]
def test_savetest_needs_index_html_at_the_root_of_the_zip(saved, tmp_path):
t = saved() # the frame URL names <upload>-<build>/index.html, so the page must sit at the zip's root
with zipfile.ZipFile(t.gh.baseline, "w") as z:
z.writestr("web/index.html", "nested")
assert t.run() == "INCONCLUSIVE" and not t.enabled()
assert not any(c[0].startswith("itch.") for c in t.gh.calls) and "index.html" in t.evidence()["detail"]
@pytest.mark.parametrize("kw", [{"target": None}, {"target": "eyalgolan/statecraft-israel:html5"},
{"target": "eyalgolan/statecraft-israel:savetest"}, # another channel, same page
{"target": "EyalGolan/Statecraft-Israel:html5"},
{"target": "eyalgolan/statecraft-israel"}, # no channel: still the public project
{"target": ""}])
def test_savetest_runs_only_against_a_separate_test_page(saved, kw):
t = saved(**kw) # 28 Oct 2026: each upload hid the public game while itch unpacked it, for up to an hour
assert t.run() == "INCONCLUSIVE" and not t.enabled() and "test page" in t.log()
assert not any(c[0].startswith("itch.") or c[0] == "download" for c in t.gh.calls) and t.runner.runs == []
def test_savetest_records_its_target_and_no_page_in_the_evidence(saved):
t = saved()
assert t.run() == "PASS"
assert t.evidence()["target"] == TEST_TARGET and "page_url" not in t.evidence()
def test_the_savetest_page_url_key_is_gone_from_the_config():
# #2056 (owner, 2 Nov 2026: "Code change, page stays Restricted"): the save test never reads the test page,
# so the job config has no key for its URL; the old key is refused like any unknown one
assert "savetest_itch_page_url" not in {f.name for f in dataclasses.fields(ns.Config)}
assert nightly.SAVETEST_KEYS == ("savetest_itch_target",)
def test_a_config_still_holding_the_removed_page_url_key_is_refused_with_the_fix(tmp_path):
config = tmp_path / "config.json"
config.write_text(json.dumps({"savetest_itch_target": TEST_TARGET,
"savetest_itch_page_url": "https://eyalgolan.itch.io/statecraft-israel-savetest"}))
with pytest.raises(ns.Refused) as e:
ns.load_config(config)
assert e.value.gate == "config"
assert "remove savetest_itch_page_url from config.json; #2237 replaced it" in e.value.detail
def test_the_savetest_command_refuses_before_any_client_without_a_test_target(tmp_path, monkeypatch, capsys):
butler = tmp_path / "butler"
butler.write_text("")
monkeypatch.setattr(nightly.shutil, "which", lambda name: "/usr/bin/" + name)
built = []
monkeypatch.setattr(nightly, "Itch", lambda *a: built.append(a))
cfg = dataclasses.replace(ns.Config(), butler=butler, handoff=tmp_path / "HANDOFF.md")
assert nightly.run_savetest(cfg, tmp_path, TAG) == 1
assert built == [] and "savetest_itch_target" in capsys.readouterr().err
assert f"SAVETEST INCONCLUSIVE tag={TAG}" in (tmp_path / "LOG.md").read_text()
assert "savetest_itch_target" in (tmp_path / "LOG.md").read_text()
@pytest.mark.parametrize("missing,gate", [("gh", "github-client"), ("butler", "itch-client")])
def test_the_savetest_command_records_a_missing_client(tmp_path, monkeypatch, missing, gate):
job = tmp_path / "job"
job.mkdir()
butler = tmp_path / "butler"
if missing != "butler":
butler.write_text("")
handoff = tmp_path / "HANDOFF.md"
(job / "config.json").write_text(json.dumps({"butler": str(butler), "handoff": str(handoff),
"savetest_itch_target": TEST_TARGET}))
monkeypatch.setattr(nightly, "JOB", job)
monkeypatch.setattr(nightly.shutil, "which", lambda name: None if missing == "gh" else "/usr/bin/" + name)
assert nightly.main(["savetest", "--tag", TAG]) == 1
line = (job / "LOG.md").read_text()
assert f"SAVETEST INCONCLUSIVE tag={TAG} {gate}:" in line
assert f"SAVETEST INCONCLUSIVE tag={TAG} {gate}:" in handoff.read_text()
def test_the_savetest_command_builds_its_itch_client_on_the_test_target(tmp_path, monkeypatch):
butler = tmp_path / "butler"
butler.write_text("")
monkeypatch.setattr(nightly.shutil, "which", lambda name: "/usr/bin/" + name)
built = []
monkeypatch.setattr(nightly, "Itch", lambda runner, path, target: built.append(target) or "itch")
monkeypatch.setattr(nightly, "savetest", lambda cfg, config, job, runner, gh, itch, *, tag: "PASS")
cfg = dataclasses.replace(ns.Config(), butler=butler, handoff=tmp_path / "HANDOFF.md",
itch_page_url="https://eyalgolan.itch.io/statecraft-israel",
savetest_itch_target=TEST_TARGET)
assert nightly.run_savetest(cfg, tmp_path, TAG) == 0 and built == [TEST_TARGET]
def test_a_broken_savetest_lock_is_recorded_inconclusive(tmp_path, monkeypatch, no_processes, capsys):
butler = tmp_path / "butler"
butler.write_text("")
monkeypatch.setattr(nightly.shutil, "which", lambda name: "/usr/bin/" + name)
stages = []
monkeypatch.setattr(nightly, "_savetest", lambda *a, **k: stages.append((a, k)))
@contextmanager
def broken_lock(job):
raise ns.Refused("lock", f"cannot take {job / 'savetest.lock'}: denied")
yield True
monkeypatch.setattr(nightly, "savetest_lock", broken_lock)
cfg = dataclasses.replace(ns.Config(), butler=butler, handoff=tmp_path / "HANDOFF.md",
itch_page_url="https://eyalgolan.itch.io/statecraft-israel",
savetest_itch_target=TEST_TARGET)
assert nightly.run_savetest(cfg, tmp_path, TAG) == 1 and stages == []
assert "INCONCLUSIVE" in capsys.readouterr().out
log = (tmp_path / "LOG.md").read_text()
assert "SAVETEST INCONCLUSIVE" in log and "lock: cannot take" in log and "denied" in log
assert "SAVETEST INCONCLUSIVE" in cfg.handoff.read_text()
def too_many_requests(retry_after=None):
return http_error(frame_of(101), 429, retry_after)
@pytest.mark.parametrize("retry_after,pause", [("90", 90), (None, nightly.SAVETEST_RATE_LIMIT_SLEEP), ("soon",
nightly.SAVETEST_RATE_LIMIT_SLEEP), ("5", nightly.SAVETEST_FRAME_SLEEP)])
def test_savetest_backs_off_and_keeps_waiting_when_itch_rate_limits_the_frame(saved, retry_after, pause):
t = saved() # 28 Oct 2026: itch answered 429 Too Many Requests while the test waited for upload B's frame
framed, calls, sleeps = frame_for(t.itch, t.fetched), {"n": 0}, []
def fetch(url, timeout=30):
calls["n"] += 1
if t.itch.pushes == 2 and calls["n"] <= 6:
raise too_many_requests(retry_after)
return framed(url, timeout)
assert t.run(fetch, sleep=sleeps.append) == "PASS" and t.enabled()
assert pause in sleeps
def test_savetest_a_rate_limit_that_never_lifts_ends_inconclusive_within_the_wait_budget(saved):
t = saved()
sleeps = []
def fetch(url, timeout=30):
raise too_many_requests("99999")
assert t.run(fetch, sleep=sleeps.append) == "INCONCLUSIVE" and not t.enabled() and t.runner.runs == []
assert sum(sleeps) <= nightly.SAVETEST_FRAME_TRIES * nightly.SAVETEST_FRAME_SLEEP
assert sleeps and max(sleeps) == nightly.SAVETEST_RATE_LIMIT_MAX and "429" in t.log()
@pytest.mark.parametrize("step", ["push", "wait_live"])
def test_savetest_an_itch_failure_is_inconclusive_and_recorded(saved, step):
t = saved()
t.itch.fail[step] = ns.Refused("itch", f"{step} failed")
assert t.run() == "INCONCLUSIVE" and not t.enabled() and f"itch: {step} failed" in t.log()
def test_savetest_an_unreachable_frame_is_inconclusive(saved):
t = saved()
def fetch(url, timeout=30):
raise OSError("offline")
assert t.run(fetch) == "INCONCLUSIVE" and not t.enabled() and "offline" in t.log()
def test_savetest_without_chrome_pushes_nothing(saved, monkeypatch):
t = saved()
monkeypatch.setattr(nightly, "find_chrome", lambda: sys.exit("Chrome for Testing not found"))
assert t.run() == "INCONCLUSIVE" and not any(c[0].startswith("itch.") for c in t.gh.calls)
def test_the_savetest_command_takes_a_tag_and_exits_zero_only_on_a_pass(tmp_path, monkeypatch, no_processes):
monkeypatch.setattr(nightly, "JOB", tmp_path / "job")
got = []
for result, code in (("PASS", 0), ("FAIL", 1), ("INCONCLUSIVE", 1)):
monkeypatch.setattr(nightly, "run_savetest", lambda cfg, job, tag, r=result: got.append(tag) or (0 if r == "PASS" else 1))
assert nightly.main(["savetest", "--tag", TAG]) == code
assert got == [TAG] * 3
with pytest.raises(SystemExit):
nightly.main(["savetest"])
def test_the_restore_also_resets_the_prickly_pear_material(night):
r = FakeRunner()
r.add(("git", "checkout", "--"))
nightly.restore_settings(night, r)
assert r.calls == [["git", "checkout", "--", "unity/ProjectSettings", "unity/Assets/Settings",
"unity/Assets/Art/HexTiles/Props/arab_village_prickly_pear/prickly_pear-rock.mat"]]
assert (Path(__file__).resolve().parents[2] / r.calls[0][-1]).is_file() # the path is a real tracked file
def test_a_corrupt_config_on_the_savetest_path_is_recorded_not_an_attribute_error(tmp_path, monkeypatch):
job = tmp_path / "job"
job.mkdir()
(job / "config.json").write_text("{not json")
monkeypatch.setattr(nightly, "JOB", job)
monkeypatch.setattr(nightly, "Config", lambda: ns.Config(handoff=tmp_path / "HANDOFF.md"))
monkeypatch.setattr(nightly, "notify", lambda *a, **k: None)
assert nightly.main(["savetest", "--tag", "v0.3.1-nightly.20261028"]) == 1
line = (job / "LOG.md").read_text()
assert "gate=config" in line
recorded = Path(line.split("log=", 1)[1].split()[0])
assert recorded.is_file() and recorded.name == "refused-config.log" and "unreadable" in recorded.read_text()
assert f"log={recorded}" in (tmp_path / "HANDOFF.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 == []
@pytest.mark.parametrize("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)
@pytest.mark.parametrize("primary", [KeyboardInterrupt, SystemExit])
@pytest.mark.parametrize("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
@pytest.mark.parametrize("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
@pytest.mark.parametrize("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)
def test_gzip_player_survives_second_build_deleting_its_bee_artifacts(night, env, monkeypatch):
import shutil
gz = night.cfg.clone / "unity/Builds/Web-gzip"
pages = night.cfg.clone / "unity/Builds/Web-pages"
(gz / "Build").mkdir(parents=True)
(gz / "Build/player.data.gz").write_bytes(b"first-player-exact-bytes")
(gz / "index.html").write_text('dataUrl: "Build/player.data.gz"')
(gz / "StreamingAssets/content").mkdir(parents=True)
(gz / "StreamingAssets/content/policy.yaml").write_bytes(b"owner-records: unchanged")
checks = []
def build(n, r, *, pages: bool, free_gb):
if pages:
assert (gz / "Build/player.data.gz").read_bytes() == b"first-player-exact-bytes"
shutil.rmtree(gz / "Build") # Unity Bee retires the previous target's outputs.
return night.cfg.clone / "unity/Builds/Web-pages"
return gz
monkeypatch.setattr(nightly, "build_web", build)
monkeypatch.setattr(nightly, "assert_clean_tree", lambda n, r: checks.append("clean"))
saved, second = nightly._build_both(night, env.runner, lambda p: 100.0)
assert not (gz / "Build").exists(), "the test must actually retire the first output"
assert saved != gz and second == pages
assert (saved / "Build/player.data.gz").read_bytes() == b"first-player-exact-bytes"
assert (saved / "index.html").read_bytes() == (gz / "index.html").read_bytes()
assert (saved / "StreamingAssets/content/policy.yaml").read_bytes() == b"owner-records: unchanged"
assert checks == ["clean"]
def test_gzip_snapshot_collision_refuses_without_second_build_or_overwrite(night, env, monkeypatch):
source = night.cfg.clone / "unity/Builds/Web-gzip"
source.mkdir(parents=True)
(source / "index.html").write_text("new artifact")
existing = night.run_dir / "Web-gzip"
existing.mkdir()
(existing / "index.html").write_text("prior evidence")
builds, checks = [], []
def build(n, r, *, pages, free_gb):
builds.append(pages)
return source
monkeypatch.setattr(nightly, "build_web", build)
monkeypatch.setattr(nightly, "assert_clean_tree", lambda n, r: checks.append("clean"))
with pytest.raises(FileExistsError):
nightly._build_both(night, env.runner, lambda p: 100.0)
assert builds == [False] and checks == ["clean"]
assert (existing / "index.html").read_text() == "prior evidence"
def test_a_partial_gzip_copy_cannot_reach_any_consumer_or_publication(night, env, stages, monkeypatch):
def partial_copy(source, destination):
destination.mkdir()
(destination / "index.html").write_text("incomplete evidence")
raise OSError("simulated copy failure")
monkeypatch.setattr(nightly.shutil, "copytree", partial_copy)
with pytest.raises(OSError, match="simulated copy failure"):
nightly.run_stages(night, ns.State(last_published=last_published()), env.runner, stages.gh, None,
no_publish=False, free_gb=lambda p: 100.0)
assert stages.names() == ["run_gates", "run_editmode", "build_web", "assert_clean_tree"]
assert (stages.gz / "index.html").read_text() == "incomplete evidence"
@pytest.mark.parametrize("rollback", [False, True])
@pytest.mark.parametrize("record_owned_row", [False, True])
def test_same_tag_foreign_id_survives_cleanup_and_rollback(env, night, rollback, record_owned_row, capsys):
# Mutation: omit or pass the wrong saved ID to the fake's ownership check.
# The real-client DELETE-address test covers deleting by tag after a successful check.
gh = FakeGH()
# Two logical same-tag records also cover the issue's defensive fixture contract; no live API capability is assumed.
expected = ([(TAG, 101, "draft")] if record_owned_row else []) + [(TAG, 202, "draft"), ("v0.4.0", 303, "published")]
gh.releases = list(expected)
st = ns.State(open_draft=TAG)
st.open_draft_id = 101
refusal = ""
if rollback:
nightly._drop_draft(night, st, gh)
else:
try:
env.pre(st, gh)
except ns.Refused as e:
refusal = e.detail
assert gh.releases == expected
if rollback:
assert "check by hand" in capsys.readouterr().err
else:
assert "check by hand" in refusal
assert st.open_draft == TAG and st.open_draft_id == 101
def test_matching_persisted_id_cleans_our_stranded_draft_on_rerun(env):
# Mutation: refuse every stranded draft, or lose the ID while loading saved state.
gh = FakeGH()
gh.releases = [("v0.4.0", 202, "draft"), (TAG, 101, "draft")]
st = ns.State(open_draft=TAG, open_draft_id=101) # new-schema persistence contract
ns.save_state(env.state_path, st)
st = ns.load_state(env.state_path)
assert env.pre(st, gh).tag == TAG
assert gh.releases == [("v0.4.0", 202, "draft")]
assert st.open_draft is None and st.open_draft_id is None
def test_legacy_open_draft_without_id_refuses_and_survives(env):
# Mutation: treat a missing ID as permission to delete a same-tag draft.
env.state_path.write_text(json.dumps({"open_draft": TAG}))
st = ns.load_state(env.state_path)
gh = FakeGH("draft")
refusal = ""
try:
env.pre(st, gh)
except ns.Refused as e:
refusal = e.detail
assert gh.releases == [(TAG, 101, "draft")]
assert "check by hand" in refusal
assert st.open_draft == TAG and getattr(st, "open_draft_id", None) is None
def test_failed_recovery_is_persisted_then_retried_before_next_preflight(night, env, pub, served):
# Mutation: only report a recovery failure, or retry after preflight's no-change/site-pending path.
gh = FakeGH(fail={"dispatch_site": ns.Refused("site", "site unavailable"),
"restore_latest": ns.Refused("github-latest", "cannot verify")})
st = ns.State(last_published=last_published())
with pytest.raises(ns.Refused, match="check by hand"):
publish(night, st, gh, pub, env, save=lambda: ns.save_state(env.state_path, st))
pending = {"failed": TAG, "previous": "v0.3.1"}
assert json.loads(env.state_path.read_text()).get("latest_recovery_pending") == pending
gh.fail.clear()
gh.calls.clear()
assert env.night(gh=gh) == "SKIPPED"
assert gh.names() == ["restore_latest", "latest_tag", "dispatch_site"]
assert gh.latest == "v0.3.1"
assert ns.load_state(env.state_path).latest_recovery_pending is None
assert "restored previous Latest v0.3.1" in env.log()
assert any("restored previous Latest v0.3.1" in note[1] for note in env_notes)
gh.calls.clear()
assert env.night(gh=gh) == "SKIPPED"
assert "restore_latest" not in gh.names()
def test_unverified_restore_persists_even_if_latest_edit_reached_github(night, env, pub, served):
# Mutation: clear recovery on an edit that has not been verified.
gh = FakeGH(fail={"dispatch_site": ns.Refused("site", "site unavailable")})
st = ns.State(last_published=last_published())
def unverified(previous, failed):
gh.calls.append(("restore_latest", previous, failed))
gh.latest = previous # the edit reached GitHub, but verification failed
raise ns.Refused("github-latest", "cannot verify")
gh.restore_latest = unverified
with pytest.raises(ns.Refused, match="cannot verify"):
publish(night, st, gh, pub, env, save=lambda: ns.save_state(env.state_path, st))
assert gh.latest == "v0.3.1"
assert json.loads(env.state_path.read_text()).get("latest_recovery_pending") == {
"failed": TAG, "previous": "v0.3.1"}
@pytest.mark.parametrize("site_pending", [None, "0.3.2"])
def test_pending_recovery_precedes_unchanged_main_and_site_retry(env, monkeypatch, site_pending):
# Mutation: run real preflight's skip or site deploy before retrying pending recovery.
read_pending_with_old_state(monkeypatch)
raw = dataclasses.asdict(ns.State(last_published=ns.Published(TAG, SHA, "0.3.2", {}, None),
site_pending=site_pending))
raw["latest_recovery_pending"] = {"failed": TAG, "previous": "v0.3.1"}
env.state_path.write_text(json.dumps(raw))
gh = FakeGH()
gh.latest = TAG
observations = []
def dispatch(deadline):
gh.calls.append(("dispatch_site", deadline))
observations.append((gh.latest, json.loads(env.state_path.read_text()).get("latest_recovery_pending")))
gh.dispatch_site = dispatch
monkeypatch.setattr(nightly, "demo_serves", lambda *a, **k: None)
assert env.night(gh=gh) == "SKIPPED"
assert gh.names() == ["restore_latest"] + (["latest_tag", "dispatch_site"] if site_pending else [])
assert observations == ([("v0.3.1", None)] if site_pending else [])
assert json.loads(env.state_path.read_text()).get("latest_recovery_pending") is None
gh.calls.clear()
assert env.night(gh=gh) == "SKIPPED"
assert gh.calls == []
@pytest.mark.parametrize("current", ["v0.4.0", None, "v0.3.1"])
def test_pending_recovery_with_moved_latest_is_cleared_and_left_alone(env, monkeypatch, current):
# Mutation: disregard restore_latest's acted=False result or keep retrying an obsolete recovery.
gh = FakeGH()
gh.latest = current
read_pending_with_old_state(monkeypatch)
raw = dataclasses.asdict(ns.State(last_published=ns.Published(TAG, SHA, "0.3.2", {}, None)))
raw["latest_recovery_pending"] = {"failed": TAG, "previous": "v0.3.1"}
env.state_path.write_text(json.dumps(raw))
assert env.night(gh=gh) == "SKIPPED"
assert gh.calls == [("restore_latest", "v0.3.1", TAG)]
assert gh.latest == current
assert json.loads(env.state_path.read_text())["latest_recovery_pending"] is None
assert "left alone" in env.log()
assert any("left alone" in note[1] for note in env_notes)
gh.calls.clear()
assert env.night(gh=gh) == "SKIPPED"
assert "restore_latest" not in gh.names()
def test_pending_recovery_failure_stops_publication_and_keeps_record(env, monkeypatch, served):
# Mutation: clear pending on an unverified recovery or continue into publishing after it fails.
read_pending_with_old_state(monkeypatch)
pending = {"failed": TAG, "previous": None}
raw = dataclasses.asdict(ns.State(last_published=ns.Published(TAG, SHA, "0.3.2", {}, None),
site_pending="0.3.2"))
raw["latest_recovery_pending"] = pending
env.state_path.write_text(json.dumps(raw))
gh = FakeGH(fail={"restore_latest": OSError("offline")})
gh.latest = TAG
outcome = env.night(gh=gh)
assert "dispatch_site" not in gh.names() and "publish" not in gh.names()
assert json.loads(env.state_path.read_text())["latest_recovery_pending"] == pending
assert outcome == "REFUSED"
assert gh.calls == [("restore_latest", None, TAG)] and served == []
assert "check by hand" in env.log()
assert any("offline" in note[1] for note in env_notes)
def test_no_publish_leaves_pending_recovery_untouched(env, monkeypatch):
# Mutation: let a dry run edit Latest or clear its persisted recovery.
read_pending_with_old_state(monkeypatch)
raw = dataclasses.asdict(ns.State(last_published=ns.Published(TAG, SHA, "0.3.2", {}, None)))
raw["latest_recovery_pending"] = {"failed": TAG, "previous": None}
env.state_path.write_text(json.dumps(raw))
before = env.state_path.read_bytes()
gh = FakeGH()
assert env.night(gh=gh, no_publish=True) == "REFUSED"
assert gh.calls == []
assert env.state_path.read_bytes() == before
def test_publish_failure_cannot_clean_a_foreign_replacement_after_create(night, env, pub, served):
gh = FakeGH()
st = ns.State(last_published=last_published())
def replaced(tag, local, dest):
gh.releases[:] = [(TAG + "-replaced", 101, "draft"), (TAG, 202, "draft")]
raise ns.Refused("github-draft", "verification failed after replacement")
gh.verify_draft = replaced
with pytest.raises(ns.Refused, match="verification failed after replacement"):
publish(night, st, gh, pub, env, save=lambda: ns.save_state(env.state_path, st))
assert gh.releases == [(TAG + "-replaced", 101, "draft"), (TAG, 202, "draft")]
assert st.open_draft == TAG and getattr(st, "open_draft_id", None) == 101
assert "publish" not in gh.names() and served == []
def test_failed_ownership_checkpoint_prevents_upload(night, env, pub, served, monkeypatch):
gh = FakeGH()
st = ns.State(last_published=last_published())
ns.save_state(env.state_path, st)
before = env.state_path.read_bytes()
stages_seen = []
original = gh._maybe_fail
def stage(name):
stages_seen.append(name)
return original(name)
gh._maybe_fail = stage
def cannot_save(*a, **k):
raise OSError("checkpoint disk failure")
monkeypatch.setattr(nightly, "save_state", cannot_save)
err = None
try:
publish(night, st, gh, pub, env, save=lambda: nightly._try_save(env.state_path, st))
except ns.Refused as e:
err = e
assert "upload" not in stages_seen
assert err is not None and err.gate == "github-draft" and "persist" in err.detail
assert "verify_draft" not in gh.names() and "publish" not in gh.names() and served == []
assert env.state_path.read_bytes() == before
def test_failed_recovery_checkpoint_stops_site_after_best_effort_repair(env, monkeypatch, served):
st = ns.State(last_published=ns.Published(TAG, SHA, "0.3.2", {}, None), site_pending="0.3.2",
latest_recovery_pending=ns.LatestRecovery(TAG, None))
ns.save_state(env.state_path, st)
before = env.state_path.read_bytes()
def cannot_save(*a, **k):
raise OSError("checkpoint disk failure")
monkeypatch.setattr(nightly, "save_state", cannot_save)
gh = FakeGH()
gh.latest = TAG
outcome = env.night(gh=gh)
assert "dispatch_site" not in gh.names() and "publish" not in gh.names()
assert outcome == "REFUSED" and gh.calls == [("restore_latest", None, TAG)]
assert gh.latest is None and env.state_path.read_bytes() == before and served == []
assert "could not be saved" in env.log() and "check by hand" in env.log()
@pytest.mark.parametrize("failing_save", ["checkpoint", "result", "both"])
def test_raising_recovery_save_still_repairs_latest_and_returns_refusal(env, failing_save):
gh = FakeGH()
gh.latest = TAG
st = ns.State()
saves = []
def save():
stage = "checkpoint" if not saves else "result"
saves.append(stage)
if failing_save in (stage, "both"):
raise ValueError("cannot serialize recovery state")
err = None
recovered, detail = True, ""
try:
recovered, detail = nightly._recover_latest(st, gh, TAG, "v0.3.1", save)
except ValueError as e:
err = e
assert gh.calls == [("restore_latest", "v0.3.1", TAG)] and gh.latest == "v0.3.1"
assert err is None
assert saves == ["checkpoint", "result"] and not recovered
assert "could not be saved" in detail and "check by hand" in detail
@pytest.mark.parametrize("latest", ["v0.3.1", "v0.4.0"])
def test_pending_demo_verifies_current_latest_after_rollback(env, monkeypatch, latest):
gh = FakeGH(); gh.latest = latest
served = []
monkeypatch.setattr(nightly, "demo_serves", lambda url, version, *, deadline: served.append(version))
assert env.night(ns.State(last_published=ns.Published(TAG, SHA, "0.3.2", {}, None), site_pending="0.3.2"), gh) == "SKIPPED"
assert served == [latest[1:]]
assert gh.latest == latest and gh.names() == ["latest_tag", "dispatch_site"]
assert ns.load_state(env.state_path).site_pending is None
gh.calls.clear()
assert env.night(gh=gh) == "SKIPPED" and gh.calls == []
@pytest.mark.parametrize("missing", [True, False])
def test_pending_demo_without_verified_latest_preserves_hold_and_never_dispatches(env, monkeypatch, missing):
gh = FakeGH(fail={} if missing else {"latest_tag": OSError("offline")})
if missing: gh.latest = None
monkeypatch.setattr(nightly, "demo_serves", lambda *a, **k: pytest.fail("unverified Latest must not be served"))
assert env.night(ns.State(last_published=ns.Published(TAG, SHA, "0.3.2", {}, None), site_pending="0.3.2"), gh) == "SKIPPED"
assert gh.names() == ["latest_tag"]
assert ns.load_state(env.state_path).site_pending == "0.3.2"
# --- the Steam stage (plan 2026-11-01-steamworks-integration Task 7, #2155) --------------------------------------------
STEAM_IDS = {"app_id": 1000, "depots": {"windows": 1001, "mac": 1002, "linux": 1003}, "branches": ["beta", "nightly"]}
def steam_ready(env, ids=STEAM_IDS, *, build=0, stage=0):
"""steam/steam.json in the clone, and runner answers for the tag fetch and the two Steam commands."""
(env.cfg.clone / "steam").mkdir(exist_ok=True)
(env.cfg.clone / "steam/steam.json").write_text(json.dumps(ids))
clone = str(env.cfg.clone)
env.runner.add(["git", "-C", clone, "fetch", "--no-tags", "origin"], out="")
env.runner.add(["uv", "run", "tools/release_build.py"], code=build)
env.runner.add(["uv", "run", "tools/steam_upload.py"], code=stage)
def steam_calls(env):
return [c for c in env.runner.calls if c[:3] in (["uv", "run", "tools/release_build.py"],
["uv", "run", "tools/steam_upload.py"])
or c[:4] == ["git", "-C", str(env.cfg.clone), "fetch"]]
def staged(night, env, stages, st, **kw):
"""One run_stages call; a repeat in the same test first drops the previous call's copy of the first player."""
shutil.rmtree(stages.gz, ignore_errors=True)
return nightly.run_stages(night, st, env.runner, stages.gh, None, free_gb=lambda p: 100.0, **kw)
def published_marker(env, monkeypatch):
monkeypatch.setattr(nightly, "publish_night", lambda *a, **k: env.runner.calls.append(["PUBLISHED"]))
def test_the_steam_stage_runs_only_after_publish(night, env, stages, monkeypatch):
steam_ready(env)
published_marker(env, monkeypatch)
st = ns.State(last_published=last_published())
assert staged(night, env, stages, st, no_publish=False)
calls = env.runner.calls
first = next(i for i, c in enumerate(calls) if c in steam_calls(env))
assert calls.index(["PUBLISHED"]) < first
out = night.run_dir / "steam-release"
assert ["git", "-C", str(env.cfg.clone), "fetch", "--no-tags", "origin", f"refs/tags/{TAG}:refs/tags/{TAG}"] in calls
assert ["uv", "run", "tools/release_build.py", "--platform", "all", "--steam", "--tag", TAG,
"--nightly-version", night.version, "--out", str(out)] in calls
assert ["uv", "run", "tools/steam_upload.py", "stage", "--out", str(out), "--tag", TAG] in calls
assert not night.notes
def test_no_steam_stage_without_a_publish(night, env, stages, monkeypatch):
steam_ready(env)
st = ns.State(last_published=last_published())
staged(night, env, stages, st, no_publish=True)
assert steam_calls(env) == []
monkeypatch.setattr(nightly, "publish_night",
lambda *a, **k: (_ for _ in ()).throw(ns.Refused("github-publish", "no")))
with pytest.raises(ns.Refused):
staged(night, env, stages, st, no_publish=False)
assert steam_calls(env) == []
@pytest.mark.parametrize("failure", ["build", "stage", "fetch", "raises"])
def test_a_steam_failure_leaves_the_web_nightly_published(env, stages, monkeypatch, failure):
if failure == "fetch":
clone = str(env.cfg.clone)
env.runner.add(["git", "-C", clone, "fetch", "--no-tags", "origin"], code=128)
if failure == "raises":
env.runner.add(["uv", "run", "tools/release_build.py"],
effect=lambda cmd: (_ for _ in ()).throw(OSError("uv is missing")))
steam_ready(env, build=1 if failure == "build" else 0, stage=1 if failure == "stage" else 0)
published_marker(env, monkeypatch)
ns.save_state(env.state_path, ns.State(last_published=last_published()))
outcome = nightly.run_night(env.cfg, env.state_path, env.job, env.runner, stages.gh, None, now=NOW, manual=False,
no_publish=False, free_gb=lambda p: 100.0)
assert outcome == "PUBLISHED"
line = env.log().strip().splitlines()[-1]
assert "PUBLISHED" in line and "steam=failed steam_log=" in line
steam_log = Path(line.split("steam_log=", 1)[1].split()[0])
assert steam_log.is_file() and "NIGHTLY REFUSED" in steam_log.read_text()
assert not {"delete_draft", "restore_latest"} & set(stages.gh.names()), "the web nightly is never rolled back"
assert any("Steam" in note[0] for note in env_notes)
def test_the_steam_stage_is_skipped_while_ids_are_null(night, env, stages, monkeypatch, capsys):
published_marker(env, monkeypatch)
st = ns.State(last_published=last_published())
for ids in ({**STEAM_IDS, "app_id": None}, {**STEAM_IDS, "depots": {**STEAM_IDS["depots"], "mac": None}}):
steam_ready(env, ids)
assert staged(night, env, stages, st, no_publish=False)
assert steam_calls(env) == [] and not night.notes
assert "steam: skipped" in capsys.readouterr().out
# --no-steam skips it even with every ID known.
steam_ready(env)
assert staged(night, env, stages, st, no_publish=False, no_steam=True)
assert steam_calls(env) == []
def test_version_reaches_the_night_only_with_manual(env, monkeypatch, capsys):
seen = {}
loaded = []
monkeypatch.setattr(nightly, "load_config", lambda path: loaded.append(path) or env.cfg)
monkeypatch.setattr(nightly, "_clients", lambda cfg: (FakeGH(), None))
monkeypatch.setattr(nightly, "JOB", env.job)
monkeypatch.setattr(nightly, "run_night", lambda *a, **k: seen.update(k) or "PUBLISHED")
assert nightly.main(["run", "--manual", "--version", "0.4.0"]) == 0 and seen["version"] == "0.4.0"
assert nightly.main(["run"]) == 0 and seen["version"] is None # the launchd command line
seen.clear()
loaded.clear()
for argv in (["run", "--version", "0.4.0"], ["run", "--manual", "--version", "v0.4.0"],
["run", "--manual", "--version", "0.4"]):
with pytest.raises(SystemExit) as e:
nightly.main(argv)
assert e.value.code == 2
assert seen == {} and loaded == [] and not (env.job / "LOG.md").exists() # refused before any work or record
err = capsys.readouterr().err
assert "--version needs --manual" in err and "X.Y.Z" in err
def test_no_steam_reaches_the_stage_from_the_command_line(env, monkeypatch):
seen = {}
monkeypatch.setattr(nightly, "load_config", lambda path: env.cfg)
monkeypatch.setattr(nightly, "_clients", lambda cfg: (FakeGH(), None))
monkeypatch.setattr(nightly, "JOB", env.job)
monkeypatch.setattr(nightly, "run_night", lambda *a, **k: seen.update(k) or "PUBLISHED")
assert nightly.main(["run", "--no-steam"]) == 0 and seen["no_steam"] is True
assert nightly.main(["run"]) == 0 and seen["no_steam"] is False
class SteamEnvRunner(EnvRunner):
"""Also records stop_on_interrupt per command."""
def __init__(self):
super().__init__()
self.stops = []
def run(self, cmd, *, cwd, log, deadline, env=None, holder=None, stop_on_interrupt=False):
self.stops.append((list(cmd), stop_on_interrupt))
return super().run(cmd, cwd=cwd, log=log, deadline=deadline, env=env, holder=holder)
def test_the_steam_build_runs_like_the_nightlys_other_unity_steps(night, env):
# Review I2 (#2155): the MCP-free Unity env, the exclusive-window check, and children stopped on an interrupt.
env.runner = SteamEnvRunner()
env._rules()
steam_ready(env)
nightly.run_steam(night, env.runner)
build = next(e for e in env.runner.envs if e[0][:3] == ["uv", "run", "tools/release_build.py"])
assert build[1]["UNITY_MCP_SERVER_PATH"] == str(night.job / "no-mcp-server")
runs = [stop for cmd, stop in env.runner.stops if cmd[:2] == ["uv", "run"]]
assert runs == [True, True], runs # release_build.py and steam_upload.py, each stopped on an interrupt
assert not night.notes
env.marker.write_text("x")
nightly.run_steam(night, env.runner)
assert len(night.notes) == 1 and night.notes[0].startswith("steam=failed steam_log=")
assert len([e for e in env.runner.envs if e[0][:3] == ["uv", "run", "tools/release_build.py"]]) == 1
@pytest.mark.parametrize("text,fails", [('{"app_id": 1, "depots": [1, 2, 3], "branches": []}', True),
('[1]', True), ("not json", False)])
def test_a_malformed_steam_json_is_a_steam_failure_not_a_refused_night(night, env, text, fails):
# Review I3 (#2155): the web nightly is public by now, so even a broken steam.json only marks Steam.
(env.cfg.clone / "steam").mkdir(exist_ok=True)
(env.cfg.clone / "steam/steam.json").write_text(text)
nightly.run_steam(night, env.runner) # never raises
assert bool(night.notes) is fails # unreadable JSON is "not configured yet" (skipped); a wrong shape is a failure
if fails:
assert night.notes[0].startswith("steam=failed steam_log=")
assert not [c for c in env.runner.calls if c[:2] == ["uv", "run"]]
def test_steam_evidence_write_failure_stays_nonfatal(night, env, monkeypatch):
(env.cfg.clone / "steam").mkdir(exist_ok=True)
(env.cfg.clone / "steam/steam.json").write_text('[1]')
monkeypatch.setattr(nightly, "write_refusal_log", lambda *a, **k: (_ for _ in ()).throw(OSError("disk full")))
nightly.run_steam(night, env.runner)
assert len(night.notes) == 1 and night.notes[0].startswith("steam=failed detail=")
assert "could not write steam evidence: disk full" in night.notes[0]
def test_the_steam_content_is_removed_after_the_stage(night, env):
# Review (k2 H6): nothing prunes the run folders, and three players plus their zips each night would fill the disk
# the next web nightly's free-space gate reads. The record and the logs stay.
out = night.run_dir / "steam-release"
def built(cmd):
(out / "steam/linux").mkdir(parents=True)
(out / "steam/linux/Statecraft.x86_64").write_bytes(b"x" * 10)
(out / "steam-v0.3.2-linux.zip").write_bytes(b"z")
(out / "build-record.json").write_text("{}")
steam_ready(env)
env.runner.rules.insert(0, (("uv", "run", "tools/release_build.py"), 0, "", built))
nightly.run_steam(night, env.runner)
assert not (out / "steam").exists() and not list(out.glob("*.zip"))
assert (out / "build-record.json").is_file()
def test_a_run_lock_open_failure_in_main_is_a_recorded_refusal(tmp_path, monkeypatch, capsys):
"""#2644 review: a real run.lock open failure is recorded by nightly.main, not raised as a traceback."""
job = tmp_path / "job"
job.mkdir()
(job / "run.lock").mkdir()
monkeypatch.setattr(nightly, "JOB", job)
monkeypatch.setattr(nightly, "load_config", lambda p: ns.Config(handoff=tmp_path / "HANDOFF.md"))
monkeypatch.setattr(nightly, "notify", lambda *a, **k: None)
assert nightly.main(["run"]) == 1
assert "gate=lock" in (job / "LOG.md").read_text()
assert "REFUSED" in (tmp_path / "HANDOFF.md").read_text()
assert "cannot open" in capsys.readouterr().err
def test_a_run_lock_open_failure_in_a_no_publish_run_writes_no_record(tmp_path, monkeypatch, capsys):
"""#2670 review: a by-hand --no-publish run writes nothing to LOG.md or the handoff, a lock failure included."""
job = tmp_path / "job"
job.mkdir()
(job / "run.lock").mkdir()
monkeypatch.setattr(nightly, "JOB", job)
monkeypatch.setattr(nightly, "load_config", lambda p: ns.Config(handoff=tmp_path / "HANDOFF.md"))
sent = []
monkeypatch.setattr(nightly, "notify", lambda *a, **k: sent.append(a))
assert nightly.main(["run", "--no-publish"]) == 1
assert not (job / "LOG.md").exists() and not (tmp_path / "HANDOFF.md").exists() and not sent
assert "cannot open" in capsys.readouterr().err
def test_a_run_lock_release_failure_does_not_add_a_second_savetest_record(tmp_path, monkeypatch, capsys):
job = tmp_path / "job"
job.mkdir()
butler = tmp_path / "butler"
butler.write_text("")
cfg = dataclasses.replace(ns.Config(), butler=butler, handoff=tmp_path / "HANDOFF.md",
itch_page_url="https://eyalgolan.itch.io/statecraft-israel",
savetest_itch_target=TEST_TARGET)
monkeypatch.setattr(nightly, "JOB", job)
monkeypatch.setattr(nightly, "load_config", lambda p: cfg)
monkeypatch.setattr(nightly, "notify", lambda *a, **k: None)
monkeypatch.setattr(nightly.shutil, "which", lambda name: "/usr/bin/" + name)
monkeypatch.setattr(nightly, "_savetest", lambda *a, **k: ("PASS", "completed"))
unlocks = 0
def fail_outer_release(fh, operation):
nonlocal unlocks
if operation == fcntl.LOCK_UN:
unlocks += 1
if unlocks == 2:
raise PermissionError("denied")
monkeypatch.setattr(fcntl, "flock", fail_outer_release)
assert nightly.main(["savetest", "--tag", TAG]) == 0
log = (job / "LOG.md").read_text()
assert log.count("SAVETEST PASS") == 1 and "REFUSED" not in log and "gate=lock" not in log
assert (tmp_path / "HANDOFF.md").read_text().count("SAVETEST PASS") == 1
err = capsys.readouterr().err
assert "cannot release" in err and "existing record is unchanged" in err
def test_a_run_lock_release_failure_does_not_replace_run_nights_record(tmp_path, monkeypatch, capsys):
job = tmp_path / "job"
job.mkdir()
cfg = ns.Config(handoff=tmp_path / "HANDOFF.md")
monkeypatch.setattr(nightly, "JOB", job)
monkeypatch.setattr(nightly, "load_config", lambda p: cfg)
monkeypatch.setattr(nightly, "notify", lambda *a, **k: None)
monkeypatch.setattr(nightly, "_clients", lambda cfg: (_ for _ in ()).throw(ns.Refused("github-client", "offline")))
calls = 0
def fail_release(*args):
nonlocal calls
calls += 1
if calls == 2:
raise PermissionError("denied")
monkeypatch.setattr(fcntl, "flock", fail_release)
assert nightly.main(["run"]) == 1
log = (job / "LOG.md").read_text()
assert log.count("REFUSED") == 1 and "gate=github-client" in log and "gate=lock" not in log
err = capsys.readouterr().err
assert "cannot release" in err and "existing record is unchanged" in err
# --- #3009: a refusal recorded by main() marks the night as run, under run.lock ------------------------------------
class _FixedNow(datetime):
@classmethod
def now(cls, tz=None):
return NOW.astimezone(tz) if tz else NOW
def _main_job(tmp_path, monkeypatch, *, corrupt_config: bool):
job = tmp_path / "job"
job.mkdir()
ns.save_state(job / "state.json", ns.State(boot_baseline=[8000.0], last_run_day="2026-10-26",
site_pending="0.3.1"))
monkeypatch.setattr(nightly, "JOB", job)
monkeypatch.setattr(nightly, "datetime", _FixedNow)
monkeypatch.setattr(nightly, "notify", lambda *a, **k: None)
if corrupt_config:
(job / "config.json").write_text("{not json")
monkeypatch.setattr(nightly, "Config", lambda: ns.Config(handoff=tmp_path / "HANDOFF.md"))
else:
monkeypatch.setattr(nightly, "load_config", lambda p: ns.Config(handoff=tmp_path / "HANDOFF.md"))
return job
def _lock_fails_once(monkeypatch, then=None):
"""run_lock raises a lock-system Refused on its first use only; later uses get `then` (default: the real lock)."""
real = nightly.run_lock
calls = 0
def run_lock(job):
nonlocal calls
calls += 1
if calls == 1:
raise ns.Refused("lock", f"cannot open {job / 'run.lock'}: transient")
return then(job) if then else real(job)
monkeypatch.setattr(nightly, "run_lock", run_lock)
def _save_seeing_the_lock(job, seen):
real = ns.save_state
def save(path, state):
with (job / "run.lock").open("a") as fh: # a second open file: flock conflicts unless someone 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
def _assert_main_marked_the_night(job):
state = ns.load_state(job / "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, date(2026, 10, 29)) == [] # the next night records no MISSED line
@pytest.mark.parametrize("path", ["config", "lock"])
def test_a_refusal_recorded_by_main_marks_the_night_as_run_under_the_lock(tmp_path, monkeypatch, path):
job = _main_job(tmp_path, monkeypatch, corrupt_config=path == "config")
if path == "lock":
_lock_fails_once(monkeypatch)
seen: list[bool] = []
monkeypatch.setattr(nightly, "save_state", _save_seeing_the_lock(job, seen))
assert nightly.main(["run"]) == 1
assert f"gate={path}" in (job / "LOG.md").read_text()
_assert_main_marked_the_night(job)
assert seen == [True] # written while run.lock was held
def test_a_main_refusal_writes_no_state_when_another_run_holds_the_lock(tmp_path, monkeypatch):
job = _main_job(tmp_path, monkeypatch, corrupt_config=False)
@contextmanager
def held_elsewhere(job):
yield False
_lock_fails_once(monkeypatch, then=held_elsewhere)
before = (job / "state.json").read_text()
assert nightly.main(["run"]) == 1
assert "gate=lock" in (job / "LOG.md").read_text()
assert (job / "state.json").read_text() == before # the run holding the lock writes the day itself
def test_a_main_refusal_with_a_still_broken_lock_leaves_the_state_alone(tmp_path, monkeypatch, capsys):
job = _main_job(tmp_path, monkeypatch, corrupt_config=False)
(job / "run.lock").mkdir()
before = (job / "state.json").read_text()
assert nightly.main(["run"]) == 1
assert "gate=lock" in (job / "LOG.md").read_text()
assert (job / "state.json").read_text() == before # never written outside run.lock
assert "could not mark 2026-10-28 as run" in capsys.readouterr().err
def test_a_main_refusal_leaves_a_corrupt_state_file_alone(tmp_path, monkeypatch, capsys):
job = _main_job(tmp_path, monkeypatch, corrupt_config=True)
(job / "state.json").write_text("{not json")
assert nightly.main(["run"]) == 1
assert "gate=config" in (job / "LOG.md").read_text() # the refusal is still recorded
assert (job / "state.json").read_text() == "{not json" # the next night refuses it itself, as gate=state
assert "could not mark" in capsys.readouterr().err
@pytest.mark.parametrize("path", ["config", "lock"])
def test_a_no_publish_refusal_in_main_writes_no_state(tmp_path, monkeypatch, path):
job = _main_job(tmp_path, monkeypatch, corrupt_config=path == "config")
if path == "lock":
_lock_fails_once(monkeypatch)
before = (job / "state.json").read_text()
assert nightly.main(["run", "--no-publish"]) == 1
assert not (job / "LOG.md").exists() and (job / "state.json").read_text() == before
def test_a_savetest_refusal_in_main_does_not_mark_the_night(tmp_path, monkeypatch):
"""The save test is not the night's run (run_savetest never sets last_run_day), so its refusal leaves the day."""
job = _main_job(tmp_path, monkeypatch, corrupt_config=True)
before = (job / "state.json").read_text()
assert nightly.main(["savetest", "--tag", TAG]) == 1
assert "gate=config" in (job / "LOG.md").read_text()
assert (job / "state.json").read_text() == before