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.

tools: record the machine's state with each boot and let it settle before boot 1 (Fixes #2914) (#2919)

Beri8e2088d052c5
diff --git a/docs/RELEASING.md b/docs/RELEASING.md
index 0840684fe..628ed0bb4 100644
--- a/docs/RELEASING.md
+++ b/docs/RELEASING.md
@@ -235,7 +235,11 @@ The gates, in order. The first one that fails ends the night as REFUSED, and not
saved publication, use the newest non-draft release carrying a `*-web.zip`. The total may grow at most 2%, plus
the size budget below.
8. Headless boot time (`boot`): the median of three boots. The first 5 published nights set the baseline; after
- that a boot slower than the slowest baseline night plus the spread of the baseline is refused.
+ that a boot slower than the slowest baseline night plus the spread of the baseline is refused. Before the first
+ boot the machine settles: the job waits until the 1-minute load average is under 2.0, at most 5 minutes, and
+ measures anyway if it never gets there. Each `boot-N.log` starts with the machine's load averages,
+ `vm.swapusage`, `memory_pressure`'s free percentage and `pmset -g therm`, and `boot-1.log` also says how long
+ the wait took.
A nightly never moves a golden: golden moves arrive through reviewed pull requests, and the nightly only needs the
golden tests of the full run to pass.
diff --git a/tools/nightly.py b/tools/nightly.py
index c380d8e0e..f0c7c10a4 100644
--- a/tools/nightly.py
+++ b/tools/nightly.py
@@ -567,16 +567,70 @@ def check_sizes(night: Night, gh: GitHub, build: Path, previous_zip: Path, prev_
return new
-def measure_boot(night: Night, runner: Runner, build: Path) -> float:
- """The median of three headless boots, each alone on the machine (no other Unity, no other check)."""
+# The boots follow two WebGL builds, 14 browser runs and a ~466 MB download. On 7 November 2026 they ran 2 s slower
+# than an A/B run of the same build seven minutes later (#2914), so the first boot waits for the machine to settle.
+# The bound is untouched: an unsettled machine is logged and measured anyway.
+SETTLE_LOAD = 2.0 # the 1-minute load average boot 1 waits to see under; tune it from the logged state lines
+SETTLE_MAX_S = 300 # the longest the wait may take
+SETTLE_POLL_S = 15
+
+
+def _read_state(runner: Runner, cmd: list[str], cwd: Path) -> str:
+ """One read-only macOS state command's output on one line. A failed read is written down, never a refusal."""
+ try:
+ text = runner.capture(cmd, cwd=cwd, timeout=30)
+ except (Refused, *STAGE_ERRORS) as error:
+ text = f"unavailable ({getattr(error, 'detail', error)})"
+ return "; ".join(line.strip() for line in text.splitlines() if line.strip())
+
+
+def _load_1min(loadavg: str) -> float | None:
+ """`sysctl -n vm.loadavg` prints `{ 1.52 1.40 1.31 }`; None when the read failed."""
+ m = re.match(r"\{\s*([\d.]+)", loadavg)
+ return float(m.group(1)) if m else None
+
+
+def machine_state(runner: Runner, cwd: Path) -> list[str]:
+ """The lines at the top of each boot-N.log, so a slow boot can be explained from its own log (#2914)."""
+ load = _read_state(runner, ["sysctl", "-n", "vm.loadavg"], cwd)
+ memory = _read_state(runner, ["memory_pressure"], cwd)
+ free = re.search(r"System-wide memory free percentage: \S+", memory) # the rest is page counts
+ return [f"state: load averages {load.strip('{} ')}",
+ f"state: vm.swapusage {_read_state(runner, ['sysctl', '-n', 'vm.swapusage'], cwd)}",
+ f"state: memory_pressure {free.group(0) if free else memory}",
+ f"state: pmset -g therm {_read_state(runner, ['pmset', '-g', 'therm'], cwd)}"]
+
+
+def settle(runner: Runner, cwd: Path, sleep: Callable[[float], None]) -> str:
+ """Wait until the 1-minute load average is under SETTLE_LOAD, at most SETTLE_MAX_S; the line saying how it went."""
+ waited = 0
+ while True:
+ load = _load_1min(_read_state(runner, ["sysctl", "-n", "vm.loadavg"], cwd))
+ if load is None: # nothing to wait on, and an unreadable load must not cost every night the full wait
+ return "settle: 1-minute load unreadable, not waiting"
+ if load < SETTLE_LOAD:
+ return f"settle: 1-minute load {load:.2f} under {SETTLE_LOAD} after {waited} s"
+ if waited >= SETTLE_MAX_S:
+ return (f"settle: not settled after {waited} s (1-minute load {load:.2f}, limit {SETTLE_LOAD}); "
+ "measuring anyway")
+ sleep(SETTLE_POLL_S)
+ waited += SETTLE_POLL_S
+
+
+def measure_boot(night: Night, runner: Runner, build: Path, *, sleep: Callable[[float], None] = time.sleep) -> float:
+ """The median of three headless boots, each alone on the machine (no other Unity, no other check), the first
+ after the machine settles. Each boot-N.log starts with the machine's state, read just before that boot."""
clone = night.cfg.clone
runs: list[int] = []
+ settled = settle(runner, night.cfg.main_repo, sleep)
for i in (1, 2, 3):
argv = ["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"]
log = night.run_dir / f"boot-{i}.log"
try:
+ header = machine_state(runner, night.cfg.main_repo) + ([settled] if i == 1 else [])
+ log.write_text("\n".join(header) + "\n", encoding="utf-8") # the runner appends the boot after it
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
diff --git a/tools/tests/test_nightly.py b/tools/tests/test_nightly.py
index 6b6bf15b0..ffb05c523 100644
--- a/tools/tests/test_nightly.py
+++ b/tools/tests/test_nightly.py
@@ -1004,7 +1004,8 @@ class CheckRunner(EnvRunner):
if marker in cmd:
code, text = answer(len(self.calls)) if callable(answer) else answer
Path(log).parent.mkdir(parents=True, exist_ok=True)
- Path(log).write_text(text)
+ with open(log, "a") as out: # appends, as ProcRunner does: measure_boot writes the machine state first
+ out.write(text)
return code
@@ -1124,17 +1125,46 @@ 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"
-def test_boot_takes_the_exclusive_lock_from_the_main_checkout_three_times(night, env):
- times = iter([8100, 8300, 8200])
-
- class BootRunner(CheckRunner):
- def run(self, cmd, **k):
+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, **k)
+ return super().run(cmd, **kw)
- r = BootRunner()
+ 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) == 8200.0
+ 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",
@@ -1145,13 +1175,68 @@ def test_boot_takes_the_exclusive_lock_from_the_main_checkout_three_times(night,
@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 = CheckRunner(answers={"--exclusive": answer})
+ r = MachineRunner(answers={"--exclusive": answer})
with pytest.raises(Refused) as e:
- nightly.measure_boot(night, r, night.cfg.clone / "unity/Builds/Web-gzip")
+ 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
+
+
# --- Task 6: publish_night, the stage wiring, the clients ---------------------------------------------------------
BOOT_MS = 8200.0