Skip to content

A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.

Nightly: a refused night's record names the failing step and its log (Fixes #2667) (#2684)

Eyal Golancc82a54aa38b
diff --git a/docs/RELEASING.md b/docs/RELEASING.md
index cbce6af95..4cf2b48e4 100644
--- a/docs/RELEASING.md
+++ b/docs/RELEASING.md
@@ -226,8 +226,9 @@ The gates, in order. The first one that fails ends the night as REFUSED, and not
same bar as a release.
3. The sim tests under `he_IL` and `en_US` (`sim-he_IL`, `sim-en_US`).
4. The Unity warm-up and the full EditMode run (`editmode`), with at least one test and no failure.
-5. The two WebGL builds, the gzip one and the Pages one (`build-web`), with the nightly version stamped in after the
- gates; the tree must be clean afterwards, and the stamp is never committed. Then both zips (`package`).
+5. The two WebGL builds, the gzip one (`build-web-gz`) and the Pages one (`build-web-pages`), with the nightly version
+ stamped in after the gates; the tree must be clean afterwards, and the stamp is never committed. Then the gzip
+ zip (`package-gz`) and the Pages zip (`package-pages`).
6. `web_check.py` on both builds (`web-check`).
7. Download size (`sizes`): compare the combined total of the data, wasm and framework files with this job's last
published night (`state.json`'s `last_published`), even if that release is now a draft. On a first night with no
diff --git a/tools/README.md b/tools/README.md
index 1a98faa71..0d922e009 100644
--- a/tools/README.md
+++ b/tools/README.md
@@ -220,7 +220,8 @@ and what is public are in `docs/RELEASING.md`, "Nightly builds". It runs on the
`Assets/Settings`, the prickly pear material) is gone before the next night. A missing clone is a REFUSED line in
`LOG.md` (`gate=clone`); the launcher never clones. While a run is in progress it exits 0 and touches nothing.
- The job folder holds `config.json` (optional; its keys are the fields of `Config` in `nightly_state.py`, and a wrong
- one refuses the night), `state.json`, `LOG.md`, `runs/` (one folder per night with every step's log), `run.lock`,
+ one refuses the night), `state.json`, `LOG.md`, `runs/` (one folder per night; a refused `LOG.md` line points
+ directly to its evidence file), `run.lock`,
`launchd.log` and `no-mcp-server`. A corrupt `config.json` or `state.json` refuses the night; it never counts as a
first night.
- itch.io pushes stay off (`itch_enabled` is false) until the save test passes: set `itch_page_url` in `config.json`
@@ -262,8 +263,9 @@ cd "$clone" && uv run tools/nightly.py run --manual --no-publish
It runs every gate and build, writes nothing to `LOG.md` or `state.json` and touches no store, and must end with
`NO-PUBLISH: all gates passed for v<version>`. A run that ends `REFUSED` prints no reason (a by-hand run writes no
-`LOG.md` line); the step that stopped it has its log in the newest folder under `$job/runs/` (a refusal before the first step, such as disk,
-licence or the clone, leaves none). Fix that step first
+`LOG.md` line). For a scheduled night, the refused line's `gate=` names the step or web/package variant and `log=`
+names the evidence file containing its cause; preflight and captured-command refusals receive a
+`refused-<gate>.log`. Fix that step first
(`gh` and `butler` must be logged in, and the Unity licence and `unity_slots.py` must be where `Config` says), then
run it again. Then:
diff --git a/tools/nightly.py b/tools/nightly.py
index 3470c7cd0..2883d9d51 100644
--- a/tools/nightly.py
+++ b/tools/nightly.py
@@ -34,7 +34,7 @@ from nightly_publish import (GitHub, Itch, demo_serves, itch_build_frame_url, re
unzip_to)
from nightly_state import (JOB, TZ, Config, LatestRecovery, Missed, Published, Refused, Runner, Skipped, State, Stop,
enable_itch, late_start, load_config, load_state, log_line, missed_days, night_of,
- notify, record, run_lock, save_state, savetest_lock, tag_for)
+ notify, record, run_lock, save_state, savetest_lock, tag_for, write_refusal_log)
from web_check import find_chrome
HOLDER_ENV = unity_postmerge.machine_lock.HOLDER_ENV
@@ -230,11 +230,18 @@ def _limit(night: Night, minutes: float) -> float:
def _step(night: Night, runner: Runner, name: str, cmd: list[str], minutes: float,
- env: dict[str, str] | None = None, *, stop_on_interrupt: bool = False) -> tuple[int, str]:
+ env: dict[str, str] | None = None, *, stop_on_interrupt: bool = False) -> tuple[int, str, Path]:
log = night.run_dir / f"{name}.log"
kwargs = {"stop_on_interrupt": True} if stop_on_interrupt else {}
- code = runner.run(cmd, cwd=night.cfg.clone, log=log, deadline=_limit(night, minutes), env=env, **kwargs)
- return code, log.read_text(encoding="utf-8", errors="replace") if log.is_file() else ""
+ try:
+ code = runner.run(cmd, cwd=night.cfg.clone, log=log, deadline=_limit(night, minutes), env=env, **kwargs)
+ except (OSError, subprocess.SubprocessError) as error:
+ raise Refused(name, f"{type(error).__name__}: {error}", log=log) from error
+ try:
+ text = log.read_text(encoding="utf-8", errors="replace") if log.is_file() else ""
+ except OSError as error:
+ raise Refused(name, f"could not read command log: {error}", log=log) from error
+ return code, text, log
def run_gates(night: Night, runner: Runner) -> None:
@@ -257,28 +264,28 @@ def run_gates(night: Night, runner: Runner) -> None:
pending = None
try:
clone = night.cfg.clone
- code, _ = step("build-sim", ["uv", "run", str(clone / "tools/build_sim_for_unity.py")], 15)
+ code, _, log = step("build-sim", ["uv", "run", str(clone / "tools/build_sim_for_unity.py")], 15)
if code != 0:
- raise Refused("build-sim", "timed out" if code == 124 else f"build_sim_for_unity exited {code}")
- code, text = step("check", ["bash", "scripts/check.sh", "origin/main"], 45)
+ raise Refused("build-sim", "timed out" if code == 124 else f"build_sim_for_unity exited {code}", log=log)
+ code, text, log = step("check", ["bash", "scripts/check.sh", "origin/main"], 45)
why = nightly_checks.check_sh_verdict(text, code)
if why:
- raise Refused("check", "timed out" if code == 124 else why)
- code, text = step("release-gate", ["bash", "scripts/oss/release_gate.sh"], 60)
+ raise Refused("check", "timed out" if code == 124 else why, log=log)
+ code, text, log = step("release-gate", ["bash", "scripts/oss/release_gate.sh"], 60)
why = nightly_checks.release_gate_verdict(text, code)
if why:
- raise Refused("release-gate", "timed out" if code == 124 else why)
+ raise Refused("release-gate", "timed out" if code == 124 else why, log=log)
for locale in ("he_IL", "en_US"):
lang = f"{locale}.UTF-8"
env = {**base_env, "LANG": lang, "LC_ALL": lang}
- code, text = step(f"sim-{locale}",
+ code, text, log = step(f"sim-{locale}",
["dotnet", "test", "sim/Statecraft.sln", "-c", "Release", "--nologo",
"-nodeReuse:false", "-p:UseSharedCompilation=false"], 30, env)
failed, total = nightly_checks.dotnet_totals(text)
if code == 124:
- raise Refused(f"sim-{locale}", "timed out")
+ raise Refused(f"sim-{locale}", "timed out", log=log)
if code != 0 or failed or total == 0:
- raise Refused(f"sim-{locale}", f"dotnet test exited {code}: {failed} failed of {total} tests")
+ raise Refused(f"sim-{locale}", f"dotnet test exited {code}: {failed} failed of {total} tests", log=log)
except BaseException as primary:
pending = primary
raise
@@ -297,7 +304,8 @@ def run_gates(night: Night, runner: Runner) -> None:
shutdown_failure = f"compiler server shutdown raised {type(error).__name__}: {error}"
if shutdown_failure is not None:
if pending is None:
- raise Refused("build-server-shutdown", shutdown_failure)
+ raise Refused("build-server-shutdown", shutdown_failure,
+ log=night.run_dir / "build-server-shutdown.log")
night.notes.append(shutdown_failure)
try:
(night.run_dir / "build-server-shutdown.note").write_text(shutdown_failure + "\n", encoding="utf-8")
@@ -333,11 +341,14 @@ RESTORE_ARGV = ["git", "checkout", "--", "unity/ProjectSettings", "unity/Assets/
def restore_settings(night: Night, runner: Runner) -> None:
"""Unity rewrites project settings while it runs; put them back so the tree stays clean."""
- code = runner.run(list(RESTORE_ARGV),
- cwd=night.cfg.clone, log=night.run_dir / "restore-settings.log",
- deadline=time.monotonic() + 120)
+ log = night.run_dir / "restore-settings.log"
+ try:
+ code = runner.run(list(RESTORE_ARGV), cwd=night.cfg.clone, log=log,
+ deadline=time.monotonic() + 120)
+ except (OSError, subprocess.SubprocessError) as error:
+ raise Refused("restore-settings", f"{type(error).__name__}: {error}", log=log) from error
if code != 0:
- raise Refused("restore-settings", f"git checkout of the Unity settings exited {code}")
+ raise Refused("restore-settings", f"git checkout of the Unity settings exited {code}", log=log)
def _note_restore(night: Night, err: Refused) -> None:
@@ -355,20 +366,28 @@ def run_editmode(night: Night, runner: Runner) -> None:
try:
warm = unity_argv(night, ["-buildTarget", "OSXUniversal", "-executeMethod", unity_postmerge.WARM_UP,
"-logFile", str(night.run_dir / "warmup.log")], webgl=False)
- warm_code = runner.run(warm, cwd=night.cfg.clone, log=night.run_dir / "warmup.out",
- deadline=_limit(night, 60), env=env, holder=night.run_dir / "lock-holder")
+ warm_out = night.run_dir / "warmup.out"
+ try:
+ warm_code = runner.run(warm, cwd=night.cfg.clone, log=warm_out,
+ deadline=_limit(night, 60), env=env, holder=night.run_dir / "lock-holder")
+ except (OSError, subprocess.SubprocessError) as error:
+ raise Refused("editmode", f"{type(error).__name__}: {error}", log=warm_out) from error
if warm_code == 124:
- raise Refused("editmode", "the Unity warm-up timed out")
+ raise Refused("editmode", "the Unity warm-up timed out", log=warm_out)
warm_log = night.run_dir / "warmup.log"
warm_text = warm_log.read_text(encoding="utf-8", errors="replace") if warm_log.is_file() else ""
if warm_code != 0 or WARM_UP_OK not in warm_text:
- raise Refused("editmode", f"the Unity warm-up failed or did not confirm (exit {warm_code})")
+ raise Refused("editmode", f"the Unity warm-up failed or did not confirm (exit {warm_code})", log=warm_out)
check_window(night)
argv = unity_argv(night, ["-buildTarget", "OSXUniversal", "-runTests", "-testPlatform", "EditMode",
"-testResults", str(xml), "-logFile", str(night.run_dir / "editmode.log")],
webgl=False)
- code = runner.run(argv, cwd=night.cfg.clone, log=night.run_dir / "editmode.out",
- deadline=_limit(night, 150), env=env, holder=night.run_dir / "lock-holder")
+ edit_out = night.run_dir / "editmode.out"
+ try:
+ code = runner.run(argv, cwd=night.cfg.clone, log=edit_out,
+ deadline=_limit(night, 150), env=env, holder=night.run_dir / "lock-holder")
+ except (OSError, subprocess.SubprocessError) as error:
+ raise Refused("editmode", f"{type(error).__name__}: {error}", log=edit_out) from error
except BaseException:
pending = True
raise
@@ -386,7 +405,7 @@ def run_editmode(night: Night, runner: Runner) -> None:
or f"exit {code}, {results.failed} failed of {results.total} tests")
if restore_error is not None:
_note_restore(night, restore_error)
- raise Refused("editmode", why)
+ raise Refused("editmode", why, log=night.run_dir / "editmode.out")
if restore_error is not None:
raise restore_error
@@ -429,9 +448,11 @@ def build_web(night: Night, runner: Runner, *, pages: bool, free_gb: Callable[[P
raise Refused("disk", f"{free:.1f} GB free, {night.cfg.min_free_gb} GB needed before a WebGL build")
check_window(night)
name = "Web-pages" if pages else "Web-gzip"
+ variant = "pages" if pages else "gz"
+ gate = f"build-web-{variant}"
build = clone / "unity/Builds" / name
shutil.rmtree(build, ignore_errors=True) # a page left by an earlier run must not pass the stamp check
- log = night.run_dir / f"unity-build-web-{'pages' if pages else 'gz'}.log"
+ log = night.run_dir / f"unity-build-web-{variant}.log"
args = [*BUILD_WEB, "-compression", "gzip"]
if pages:
args += ["-decompressionFallback", "-shareable", "-out", f"Builds/{name}"]
@@ -447,9 +468,12 @@ def build_web(night: Night, runner: Runner, *, pages: bool, free_gb: Callable[[P
stamp_bundle_version(clone / SETTINGS_ASSET, night.version)
except ValueError as e:
raise Refused("version-stamp", str(e)) from e
- code = runner.run(unity_argv(night, args, webgl=True), cwd=clone,
- log=night.run_dir / f"unity-build-web-{'pages' if pages else 'gz'}.out",
- deadline=_limit(night, 120), env=env, holder=night.run_dir / "lock-holder")
+ out_log = night.run_dir / f"unity-build-web-{variant}.out"
+ try:
+ code = runner.run(unity_argv(night, args, webgl=True), cwd=clone, log=out_log,
+ deadline=_limit(night, 120), env=env, holder=night.run_dir / "lock-holder")
+ except (OSError, subprocess.SubprocessError) as error:
+ raise Refused(gate, f"{type(error).__name__}: {error}", log=out_log) from error
except BaseException:
pending = True
raise
@@ -465,8 +489,8 @@ def build_web(night: Night, runner: Runner, *, pages: bool, free_gb: Callable[[P
if restore_error is not None:
_note_restore(night, restore_error)
if code == 124:
- raise Refused("build-web", "the Unity build timed out")
- raise Refused("build-web", f"the Unity build exited {code}{_build_failure_detail(log)}")
+ raise Refused(gate, "the Unity build timed out", log=log)
+ raise Refused(gate, f"the Unity build exited {code}{_build_failure_detail(log)}", log=log)
if restore_error is not None:
raise restore_error
index = build / "index.html"
@@ -478,13 +502,15 @@ def build_web(night: Night, runner: Runner, *, pages: bool, free_gb: Callable[[P
def package_zip(night: Night, runner: Runner, build: Path, pages: bool) -> Path:
+ variant = "pages" if pages else "gz"
+ gate = f"package-{variant}"
zip_path = night.run_dir / f"statecraft-israel-v{night.version}-web{'-pages' if pages else ''}.zip"
- code, text = _step(night, runner, f"package-{'pages' if pages else 'gz'}",
- ["bash", "scripts/oss/package_web.sh", str(build), str(zip_path)], 20)
+ code, text, log = _step(night, runner, gate,
+ ["bash", "scripts/oss/package_web.sh", str(build), str(zip_path)], 20)
if code != 0:
- raise Refused("package", "timed out" if code == 124 else f"package_web.sh exited {code}")
+ raise Refused(gate, "timed out" if code == 124 else f"package_web.sh exited {code}", log=log)
if "PACKAGED " not in text or "OK: notices inside" not in text:
- raise Refused("package", "package_web.sh did not confirm the zip and its notices")
+ raise Refused(gate, "package_web.sh did not confirm the zip and its notices", log=log)
return zip_path
@@ -506,11 +532,12 @@ def run_web_checks(night: Night, runner: Runner, build: Path) -> None:
for i, args in enumerate(passes, 1):
argv = ["uv", "run", str(clone / "tools/machine_lock.py"), "--shared", "--",
"uv", "run", str(clone / "tools/web_check.py"), *args]
- code, text = _step(night, runner, f"web-check-{build.name}-{i}", argv, 10)
+ name = f"web-check-{build.name}-{i}"
+ code, text, log = _step(night, runner, name, argv, 10)
if code == 124:
- raise Refused("web-check", f"{build.name} pass {i} timed out")
+ raise Refused("web-check", f"{build.name} pass {i} timed out", log=log)
if code != 0 or not re.search(r"^PASS:", text, re.M):
- raise Refused("web-check", f"{build.name} pass {i} exited {code} without a PASS line")
+ raise Refused("web-check", f"{build.name} pass {i} exited {code} without a PASS line", log=log)
def check_sizes(night: Night, gh: GitHub, build: Path, previous_zip: Path, prev_sha: str | None, *,
@@ -545,18 +572,21 @@ def measure_boot(night: Night, runner: Runner, build: Path) -> float:
"--", "uv", "run", str(clone / "tools/web_check.py"), str(build), "--query", "bootlog",
"--expect", "GAME OK", "--timeout", "300", "--stall", "90"]
log = night.run_dir / f"boot-{i}.log"
- code = runner.run(argv, cwd=night.cfg.main_repo, log=log, deadline=_limit(night, 60))
+ try:
+ code = runner.run(argv, cwd=night.cfg.main_repo, log=log, deadline=_limit(night, 60))
+ except (OSError, subprocess.SubprocessError) as error:
+ raise Refused("boot", f"{type(error).__name__}: {error}", log=log) from error
text = log.read_text(encoding="utf-8", errors="replace") if log.is_file() else ""
if code == 124:
- raise Refused("boot", f"boot run {i} timed out")
+ raise Refused("boot", f"boot run {i} timed out", log=log)
if code == 3:
- raise Refused("boot", f"boot run {i}: another Unity was still running after 45 minutes")
+ raise Refused("boot", f"boot run {i}: another Unity was still running after 45 minutes", log=log)
if code != 0:
- raise Refused("boot", f"boot run {i} exited {code}")
+ raise Refused("boot", f"boot run {i} exited {code}", log=log)
try:
runs.append(nightly_checks.boot_ms(text))
except ValueError as e:
- raise Refused("boot", f"boot run {i}: {e}") from e
+ raise Refused("boot", f"boot run {i}: {e}", log=log) from e
return float(statistics.median(runs))
@@ -800,7 +830,7 @@ def steam_ids_missing(clone: Path) -> str | None:
def run_steam(night: Night, runner: Runner) -> None:
"""After the web nightly is published: build the Steam players, stage them in a draft release and dispatch the
upload to the `nightly` branch. It never refuses, unpublishes or rolls back the web nightly: any failure only adds
- steam=failed to the night's line (the logs are in the run folder) and notifies."""
+ steam=failed and the exact evidence log to the night's line, and notifies."""
out = night.run_dir / "steam-release"
try:
if (why := steam_ids_missing(night.cfg.clone)) is not None:
@@ -809,22 +839,31 @@ def run_steam(night: Night, runner: Runner) -> None:
check_window(night)
# tonight's tag was made on GitHub by the publish; release_build.py checks it points at HEAD and never fetches
_git(runner, night.cfg.clone, "fetch", "--no-tags", "origin", f"refs/tags/{night.tag}:refs/tags/{night.tag}")
- code, _ = _step(night, runner, "steam-build",
- ["uv", "run", "tools/release_build.py", "--platform", "all", "--steam", "--tag", night.tag,
- "--nightly-version", night.version, "--out", str(out)], STEAM_BUILD_MINUTES,
- unity_env(night), stop_on_interrupt=True)
+ code, _, log = _step(night, runner, "steam-build",
+ ["uv", "run", "tools/release_build.py", "--platform", "all", "--steam", "--tag", night.tag,
+ "--nightly-version", night.version, "--out", str(out)], STEAM_BUILD_MINUTES,
+ unity_env(night), stop_on_interrupt=True)
if code != 0:
- raise Refused("steam", "release_build.py timed out" if code == 124 else f"release_build.py exited {code}")
- code, _ = _step(night, runner, "steam-stage",
- ["uv", "run", "tools/steam_upload.py", "stage", "--out", str(out), "--tag", night.tag],
- STEAM_STAGE_MINUTES, stop_on_interrupt=True)
+ raise Refused("steam-build", "release_build.py timed out" if code == 124 else f"release_build.py exited {code}",
+ log=log)
+ code, _, log = _step(night, runner, "steam-stage",
+ ["uv", "run", "tools/steam_upload.py", "stage", "--out", str(out), "--tag", night.tag],
+ STEAM_STAGE_MINUTES, stop_on_interrupt=True)
if code != 0:
- raise Refused("steam", "steam_upload.py timed out" if code == 124 else f"steam_upload.py exited {code}")
+ raise Refused("steam-stage", "steam_upload.py timed out" if code == 124 else f"steam_upload.py exited {code}",
+ log=log)
except Exception as e:
detail = _detail(e)
print(f"steam: failed: {detail}", file=sys.stderr)
- night.notes.append("steam=failed")
- notify("Nightly Steam stage failed", f"{night.tag} is published; Steam: {detail}; logs in {night.run_dir}"[:200])
+ source = e.log if isinstance(e, Stop) else None
+ try:
+ failure_log = write_refusal_log(night.run_dir, e.gate if isinstance(e, Stop) else "steam", detail, source)
+ night.notes.append(f"steam=failed steam_log={failure_log}")
+ where = str(failure_log)
+ except OSError as error:
+ night.notes.append(f"steam=failed detail={detail}; could not write steam evidence: {error}")
+ where = f"evidence unavailable ({error})"
+ notify("Nightly Steam stage failed", f"{night.tag} is published; Steam: {detail}; log: {where}"[:200])
finally:
# Nothing prunes the run folders, and three players and their zips a night would eat the free space the next
# web nightly's disk gate needs (review of #2155). The draft holds the zips; the record and the logs stay.
@@ -905,6 +944,8 @@ def run_night(cfg: Config, state_path: Path, job: Path, runner: Runner, gh: GitH
outcome, gate, detail = "REFUSED", "internal", ""
state: State | None = None
night: Night | None = None
+ evidence: Path | None = None
+ run_dir = job / "runs" / f"{now.astimezone(TZ):%Y%m%d-%H%M%S}"
recovery_note = ""
day = night_of(now)
try:
@@ -932,6 +973,7 @@ def run_night(cfg: Config, state_path: Path, job: Path, runner: Runner, gh: GitH
outcome, gate = ("PUBLISHED" if published else "NO-PUBLISH"), "-"
except Stop as e:
outcome, gate, detail = e.outcome, e.gate, e.detail
+ evidence = e.log
except STAGE_ERRORS as e:
stage = "preflight" if night is None else "run"
outcome, gate, detail = "REFUSED", stage, str(e)
@@ -946,8 +988,16 @@ def run_night(cfg: Config, state_path: Path, job: Path, runner: Runner, gh: GitH
detail = " ".join(filter(None, [detail, recovery_note]))
if night is not None and night.notes:
detail = " ".join(filter(None, [detail, *night.notes]))
+ if outcome == "REFUSED":
+ try:
+ evidence = write_refusal_log(run_dir, gate, detail, evidence)
+ except OSError as error:
+ evidence = None
+ detail = f"{detail}; could not write refusal log: {error}"
+ elif night is not None:
+ evidence = night.run_dir
line = log_line(now, outcome, tag=night.tag if night else None, sha=night.sha if night else None,
- gate=gate, log=night.run_dir if night else None)
+ gate=gate, log=evidence)
record(job / "LOG.md", cfg.handoff, f"{line} {detail}".rstrip() if detail else line)
if state is not None: # after the record, so a failed save never costs the night its line
state.last_run_day = day.isoformat()
@@ -1063,11 +1113,22 @@ def savetest(cfg: Config, config_path: Path, job: Path, runner: Runner, gh: GitH
detail = f"{e.gate}: {e.detail}"
except (OSError, SystemExit) as e: # find_chrome exits when there is no Chrome
detail = f"{type(e).__name__}: {e}"
- evidence.update(result=result, detail=detail)
- if work.is_dir():
- (work / "evidence.json").write_text(json.dumps(evidence, indent=2, sort_keys=True) + "\n", encoding="utf-8")
- if result == "PASS":
- enable_itch(config_path, work / "evidence.json")
+ try:
+ evidence.update(result=result, detail=detail)
+ if work.is_dir():
+ (work / "evidence.json").write_text(json.dumps(evidence, indent=2, sort_keys=True) + "\n", encoding="utf-8")
+ if result == "PASS":
+ enable_itch(config_path, work / "evidence.json")
+ except (Stop, OSError) as e: # #2684 review: a failure after the test still gets its one SAVETEST record
+ result = "INCONCLUSIVE"
+ detail = f"{e.gate}: {e.detail}" if isinstance(e, Stop) else f"{type(e).__name__}: {e}"
+ evidence.update(result=result, detail=detail)
+ if work.is_dir():
+ try:
+ (work / "evidence.json").write_text(json.dumps(evidence, indent=2, sort_keys=True) + "\n",
+ encoding="utf-8")
+ except OSError:
+ pass # LOG.md stays the record when the evidence file itself cannot be written
record(Path(job) / "LOG.md", cfg.handoff, f"SAVETEST {result} tag={tag} {detail}".rstrip())
return result
@@ -1210,6 +1271,8 @@ def run_savetest(cfg: Config, job: Path, tag: str) -> int:
runner = ProcRunner()
gh, itch = GitHub(runner, cfg.repo_slug, cfg.clone), Itch(runner, cfg.butler, cfg.savetest_itch_target)
except Refused as e:
+ record(Path(job) / "LOG.md", cfg.handoff,
+ f"SAVETEST INCONCLUSIVE tag={tag} {e.gate}: {e.detail}")
print(e, file=sys.stderr)
return 1
result = savetest(cfg, job / "config.json", job, runner, gh, itch, tag=tag)
@@ -1233,8 +1296,15 @@ def main(argv: list[str] | None = None) -> int:
cfg = load_config(job / "config.json")
except Refused as e: # a corrupt config is a recorded REFUSED night, not a first night on defaults
if not getattr(args, "no_publish", False): # the savetest command has no such flag
- line = log_line(now, "REFUSED", tag=None, sha=None, gate=e.gate, log=None)
- record(job / "LOG.md", Config().handoff, f"{line} {e.detail}")
+ detail = e.detail
+ try:
+ evidence = write_refusal_log(job / "runs" / f"{now.astimezone(TZ):%Y%m%d-%H%M%S}",
+ e.gate, detail, e.log)
+ except OSError as error:
+ evidence = None
+ detail = f"{detail}; could not write refusal log: {error}"
+ line = log_line(now, "REFUSED", tag=None, sha=None, gate=e.gate, log=evidence)
+ record(job / "LOG.md", Config().handoff, f"{line} {detail}")
notify("Nightly refused", str(e)[:200])
print(e, file=sys.stderr)
return 1
diff --git a/tools/nightly_launch.py b/tools/nightly_launch.py
index 9dc9b517c..c0e5bb689 100644
--- a/tools/nightly_launch.py
+++ b/tools/nightly_launch.py
@@ -21,7 +21,7 @@ from datetime import datetime
from pathlib import Path
from typing import Callable
-from nightly_state import TZ, Config, Refused, load_config, log_line, notify, record, run_lock
+from nightly_state import TZ, Config, Refused, load_config, log_line, notify, record, run_lock, write_refusal_log
# What `git clean -x` keeps in the clone: Unity's import cache and the Unity-MCP plugin's NuGet download. The same
# list as unity_postmerge.KEEP (a test keeps them equal; this file runs without the checkout, so it cannot import it).
@@ -56,11 +56,20 @@ def prepare_clone(cfg: Config, git: Callable[..., str] = _git,
except subprocess.CalledProcessError as e:
tail = (e.stderr or "").strip()[-300:]
raise Refused("clone", f"{' '.join(str(a) for a in e.cmd[:3])} failed: {tail}") from e
+ except OSError as e:
+ raise Refused("clone", f"could not prepare the clone: {type(e).__name__}: {e}") from e
def _refuse(cfg: Config, home: Path, e: Refused, now: datetime) -> None:
- line = log_line(now, "REFUSED", tag=None, sha=None, gate=e.gate, log=None)
- record(home / "LOG.md", cfg.handoff, f"{line} {e.detail}")
+ run_dir = home / "runs" / f"{now.astimezone(TZ):%Y%m%d-%H%M%S}"
+ detail = e.detail
+ try:
+ evidence = write_refusal_log(run_dir, e.gate, detail, e.log)
+ except OSError as error:
+ evidence = None
+ detail = f"{detail}; could not write refusal log: {error}"
+ line = log_line(now, "REFUSED", tag=None, sha=None, gate=e.gate, log=evidence)
+ record(home / "LOG.md", cfg.handoff, f"{line} {detail}")
notify("Nightly refused", str(e)[:200])
print(e, file=sys.stderr)
@@ -88,7 +97,12 @@ def main(argv: list[str] | None = None, *, git: Callable[..., str] = _git,
except Refused as e:
_refuse(cfg, a.home, e, now)
return 1
- return call([a.uv, "run", str(cfg.clone / "tools" / "nightly.py"), "run"])
+ try:
+ return call([a.uv, "run", str(cfg.clone / "tools" / "nightly.py"), "run"])
+ except OSError as e:
+ refusal = Refused("launch", f"could not start {a.uv}: {type(e).__name__}: {e}")
+ _refuse(cfg, a.home, refusal, now)
+ return 1
if __name__ == "__main__":
diff --git a/tools/nightly_state.py b/tools/nightly_state.py
index 35c5e31a6..0ae3bb222 100644
--- a/tools/nightly_state.py
+++ b/tools/nightly_state.py
@@ -30,20 +30,21 @@ SHA_SHOWN = 12
class Stop(Exception):
- """A night that ends without publishing. `outcome` is REFUSED, SKIPPED or MISSED."""
+ """A night that ends without publishing. A refusal may carry its exact evidence log."""
outcome = "REFUSED"
- def __init__(self, gate: str, detail: str):
+ def __init__(self, gate: str, detail: str, *, log: Path | None = None):
super().__init__(f"{gate}: {detail}")
self.gate = gate
self.detail = detail
+ self.log = Path(log) if log is not None else None
class Refused(Stop):
outcome = "REFUSED"
- def __init__(self, gate: str, detail: str):
- super().__init__(gate, detail)
+ def __init__(self, gate: str, detail: str, *, log: Path | None = None):
+ super().__init__(gate, detail, log=log)
class Skipped(Stop):
@@ -71,6 +72,16 @@ class Runner(Protocol):
def capture(self, cmd: list[str], *, cwd: Path, timeout: float = 300) -> str: ...
+def write_refusal_log(run_dir: Path, gate: str, detail: str, source: Path | None = None) -> Path:
+ """Append the terminal cause to a command log, or create a refusal evidence file in the timestamped run folder."""
+ safe_gate = re.sub(r"[^A-Za-z0-9_.-]+", "-", gate)
+ log = Path(source) if source is not None else Path(run_dir) / f"refused-{safe_gate}.log"
+ log.parent.mkdir(parents=True, exist_ok=True)
+ with log.open("a", encoding="utf-8") as out:
+ out.write(f"\nNIGHTLY REFUSED gate={gate}\n{detail}\n")
+ return log
+
+
# --- config -----------------------------------------------------------------------------------------------------
@dataclass(frozen=True)
diff --git a/tools/release_build.py b/tools/release_build.py
index 3e3bb619e..6b8dc5158 100644
--- a/tools/release_build.py
+++ b/tools/release_build.py
@@ -624,8 +624,11 @@ def main(argv: list[str] | None = None) -> int:
return 0
(out / "logs").mkdir(parents=True, exist_ok=True)
- if run(sim, cwd=REPO).returncode != 0:
- print("FAILED: tools/build_sim_for_unity.py", file=sys.stderr)
+ sim_log = out / "logs/build-sim.log"
+ with sim_log.open("w", encoding="utf-8") as log:
+ sim_result = run(sim, cwd=REPO, stdout=log, stderr=subprocess.STDOUT)
+ if sim_result.returncode != 0:
+ print(f"FAILED: tools/build_sim_for_unity.py; see {sim_log}", file=sys.stderr)
return 1
expected = expected_goldens()
artifacts, all_ok = [], True
diff --git a/tools/tests/test_nightly.py b/tools/tests/test_nightly.py
index 2ec74b582..4e31cf399 100644
--- a/tools/tests/test_nightly.py
+++ b/tools/tests/test_nightly.py
@@ -698,8 +698,10 @@ def test_settings_are_restored_when_the_runner_raises(night, env):
raise OSError("disk gone")
return real(cmd, **k)
r.run = boom
- with pytest.raises(OSError):
+ 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"
@@ -764,11 +766,13 @@ def test_a_pending_error_and_a_failed_restore_keep_the_original(night, env, how)
raise OSError("disk gone")
return real(cmd, **k)
r.run = boom
- expect, exc = None, OSError
+ 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()
@@ -887,11 +891,13 @@ def test_a_build_page_without_tonights_version_refuses(night, env):
nightly.build_web(night, r, pages=False, free_gb=lambda p: 100.0)
-def test_a_failed_build_refuses_and_restores(night, env):
[email protected]("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=True, free_gb=lambda p: 100.0)
- assert e.value.gate == "build-web" and r.restores == 1
+ 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):
@@ -917,7 +923,7 @@ 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" and "timed out" in e.value.detail
+ 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
@@ -930,7 +936,7 @@ def test_a_failed_restore_does_not_mask_the_build_error(night, env, capsys):
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"
+ assert e.value.gate == "build-web-gz"
assert (night.run_dir / "restore-settings.note").is_file()
@@ -942,11 +948,13 @@ def test_packaging_needs_the_notices_line(night, env):
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 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), build, False)
- assert e.value.gate == "package"
+ 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):
@@ -1899,7 +1907,7 @@ 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" and "error CS0103" in e.value.detail and "BuildFailedException" in e.value.detail
+ 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
@@ -1910,6 +1918,14 @@ def test_a_failed_build_without_a_unity_log_says_so(night, env):
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):
@@ -1949,6 +1965,33 @@ def test_an_unusable_client_is_a_recorded_github_client_refusal_not_internal(env
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"
@@ -2109,6 +2152,32 @@ def test_savetest_passes_only_with_matching_tuple_new_url_same_origin(saved):
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"
@@ -2298,6 +2367,26 @@ def test_the_savetest_command_refuses_before_any_client_without_a_test_target(tm
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()
+
+
[email protected]("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):
@@ -2391,7 +2480,11 @@ def test_a_corrupt_config_on_the_savetest_path_is_recorded_not_an_attribute_erro
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
- assert "gate=config" in (job / "LOG.md").read_text()
+ 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):
@@ -3095,7 +3188,9 @@ def test_a_steam_failure_leaves_the_web_nightly_published(env, stages, monkeypat
no_publish=False, free_gb=lambda p: 100.0)
assert outcome == "PUBLISHED"
line = env.log().strip().splitlines()[-1]
- assert "PUBLISHED" in line and line.endswith("steam=failed")
+ 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)
@@ -3149,21 +3244,32 @@ def test_the_steam_build_runs_like_the_nightlys_other_unity_steps(night, env):
assert not night.notes
env.marker.write_text("x")
nightly.run_steam(night, env.runner)
- assert night.notes == ["steam=failed"]
+ 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
[email protected]("text, notes", [('{"app_id": 1, "depots": [1, 2, 3], "branches": []}', ["steam=failed"]),
- ('[1]', ["steam=failed"]), ("not json", [])])
-def test_a_malformed_steam_json_is_a_steam_failure_not_a_refused_night(night, env, text, notes):
[email protected]("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 night.notes == notes # unreadable JSON is "not configured yet" (skipped); a wrong shape is a failure
+ 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.
diff --git a/tools/tests/test_nightly_launch.py b/tools/tests/test_nightly_launch.py
index a405fc8bc..ff92e3d9d 100644
--- a/tools/tests/test_nightly_launch.py
+++ b/tools/tests/test_nightly_launch.py
@@ -103,7 +103,9 @@ def test_a_missing_clone_is_refused_and_recorded_not_cloned(tmp_path, monkeypatc
assert code == 1 and rec.calls == [] and ran == []
log = (home / "LOG.md").read_text()
assert "REFUSED" in log and "gate=clone" in log and "2026-10-28 03:00" in log
- assert "gate=clone" in cfg.handoff.read_text()
+ evidence = home / "runs/20261028-030000/refused-clone.log"
+ assert f"log={evidence}" in log and evidence.is_file() and "not a git clone" in evidence.read_text()
+ assert "gate=clone" in cfg.handoff.read_text() and f"log={evidence}" in cfg.handoff.read_text()
assert not cfg.clone.exists()
@@ -115,7 +117,42 @@ def test_a_corrupt_config_is_refused_not_a_night_on_defaults(tmp_path, monkeypat
monkeypatch.setattr(nl, "Config", lambda: ns.Config(handoff=tmp_path / "HANDOFF.md"))
rec, ran = Recorder(), []
assert nl.main(["--uv", "/opt/uv", "--home", str(home)], git=rec.git, copy=rec.copy, call=ran.append, now=NOW) == 1
- assert rec.calls == [] and ran == [] and "gate=config" in (home / "LOG.md").read_text()
+ log = (home / "LOG.md").read_text()
+ evidence = home / "runs/20261028-030000/refused-config.log"
+ assert rec.calls == [] and ran == [] and "gate=config" in log
+ assert f"log={evidence}" in log and evidence.is_file() and "unreadable" in evidence.read_text()
+ assert f"log={evidence}" in (tmp_path / "HANDOFF.md").read_text()
+
+
[email protected]("failure,gate", [("git", "clone"), ("copy", "clone"), ("call", "launch")])
+def test_a_process_start_failure_is_refused_and_recorded(tmp_path, monkeypatch, failure, gate):
+ home = tmp_path / "job"
+ cfg = cfg_for(tmp_path, library=failure == "copy")
+ write_config(home, cfg)
+ monkeypatch.setattr(nl, "notify", lambda *a, **k: None)
+ rec = Recorder()
+
+ def git(cwd, *args):
+ if failure == "git":
+ raise OSError("git would not start")
+ return rec.git(cwd, *args)
+
+ def copy(cwd, src, dest):
+ if failure == "copy":
+ raise OSError("cp would not start")
+ rec.copy(cwd, src, dest)
+
+ def call(cmd):
+ if failure == "call":
+ raise OSError("uv would not start")
+ pytest.fail("the nightly process must not start after clone preparation fails")
+
+ assert nl.main(["--uv", "/opt/uv", "--home", str(home)], git=git, copy=copy, call=call, now=NOW) == 1
+ log = (home / "LOG.md").read_text()
+ evidence = home / f"runs/20261028-030000/refused-{gate}.log"
+ assert f"gate={gate}" in log and f"log={evidence}" in log
+ assert evidence.is_file() and "would not start" in evidence.read_text()
+ assert f"log={evidence}" in cfg.handoff.read_text()
def test_a_run_in_progress_exits_0_and_touches_nothing(tmp_path, capsys):
diff --git a/tools/tests/test_release_build.py b/tools/tests/test_release_build.py
index ad5f14319..90687a3b2 100644
--- a/tools/tests/test_release_build.py
+++ b/tools/tests/test_release_build.py
@@ -67,7 +67,8 @@ class Fake:
def __init__(self, dirty="", golden_ok=True, build_ok=True, branch="main", tags=("v0.1.0",), worktrees=None,
build_raises=None, dirty_after="", on_origin_main=True, fail_status=False,
- fail_status_after=False, fail_worktree_list=False, fail_checkout=False, lipo_code=0, lipo_out="x86_64 arm64\n"):
+ fail_status_after=False, fail_worktree_list=False, sim_ok=True, sim_output="", fail_checkout=False,
+ lipo_code=0, lipo_out="x86_64 arm64\n"):
self.calls: list[list[str]] = []
self.dirty, self.golden_ok, self.build_ok = dirty, golden_ok, build_ok
self.branch, self.tags, self.worktrees = branch, tags, worktrees
@@ -76,6 +77,7 @@ class Fake:
self.fail_status = fail_status
self.fail_status_after = fail_status_after
self.fail_worktree_list = fail_worktree_list
+ self.sim_ok, self.sim_output = sim_ok, sim_output
self.fail_checkout = fail_checkout
self.lipo_code = lipo_code
self.lipo_out = lipo_out
@@ -84,7 +86,11 @@ class Fake:
cmd = [str(c) for c in cmd]
self.calls.append(cmd)
out, code = "", 0
- if cmd[:2] == ["git", "status"]:
+ if Path(cmd[-1]).as_posix().endswith("tools/build_sim_for_unity.py"):
+ if "stdout" in kw:
+ kw["stdout"].write(self.sim_output)
+ code = 0 if self.sim_ok else 1
+ elif cmd[:2] == ["git", "status"]:
status_failed = self.fail_status_after if self.built else self.fail_status
if status_failed:
code = 1
@@ -530,6 +536,16 @@ def test_the_sim_dlls_are_built_before_unity(repo, editor, monkeypatch, tmp_path
assert sim < next(i for i, c in enumerate(fake.calls) if "-executeMethod" in c)
+def test_a_failed_sim_build_has_a_named_log(repo, editor, monkeypatch, tmp_path, capsys):
+ fake = Fake(sim_ok=False, sim_output="sim compiler failure\n")
+ out = tmp_path / "out"
+ assert run_main(["--platform", "mac", "--out", str(out)], repo, editor, fake, monkeypatch) == 1
+ sim_log = out / "logs/build-sim.log"
+ assert sim_log.read_text() == "sim compiler failure\n"
+ assert str(sim_log) in capsys.readouterr().err
+ assert unity_calls(fake) == []
+
+
def test_no_push_upload_commit_or_network(repo, editor, monkeypatch, tmp_path):
fake = Fake()
run_main(["--platform", "all", "--out", str(tmp_path / "out")], repo, editor, fake, monkeypatch)