A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
ci: run the Linux player golden check under xvfb-run (refs #533, #54) (#581)
Eyal Golan1ec20903bd16
diff --git a/.github/workflows/player-golden.yml b/.github/workflows/player-golden.ymlindex 5169fa5a9..628c1ce30 100644--- a/.github/workflows/player-golden.yml+++ b/.github/workflows/player-golden.yml@@ -3,7 +3,8 @@ name: Player golden# The licence-free golden check of the released desktop players (plan# docs/superpowers/specs/2026-10-14-desktop-builds-and-release-pipeline.md, sections 2.2 and 6.3; decision O7 in# docs/oss/DECISIONS.md). The players are built on the owner's Mac and attached to a GitHub Release; this workflow only-# downloads them and runs `-batchmode -nographics -golden` on clean GitHub-hosted machines (docs/determinism.md). No+# downloads them and runs `-batchmode -nographics -golden` on clean GitHub-hosted machines (docs/determinism.md), the+# Linux player under `xvfb-run -a` because it needs a display even headless (issue #533). No# Unity install, no Unity licence and no secret: the only credential is the default token, read-only, which# `gh release download` uses.#@@ -126,6 +127,11 @@ jobs:TAG: ${{ needs.plan.outputs.tag }}ASSET: ${{ matrix.asset }}run: gh release download "$TAG" --repo "$GITHUB_REPOSITORY" --pattern "$ASSET" --dir "$RUNNER_TEMP/download"+ # The Linux player crashes with no display at all, -nographics or not (issue #533), so player_golden_check.py runs+ # it under xvfb-run (DISPLAY_WRAPPER). The image usually has xvfb already; this makes it explicit.+ - name: Install a virtual X display (Linux)+ if: matrix.platform == 'linux'+ run: sudo apt-get update -q && sudo apt-get install -y -q --no-install-recommends xvfb xauth- name: Run the player's golden checkenv:PLATFORM: ${{ matrix.platform }}diff --git a/docs/RELEASING.md b/docs/RELEASING.mdindex 87a2dc853..e2bc554e6 100644--- a/docs/RELEASING.md+++ b/docs/RELEASING.md@@ -87,7 +87,7 @@ GitHub Releases page (and, from M4, on itch.io). Steps 1–3 are a normal pull rPublishing starts the `Player golden` workflow (`.github/workflows/player-golden.yml`). It downloads each player,checks it against the SHA-256 GitHub records for the asset, and runs `-batchmode -nographics -golden` on GitHub's- Windows and Linux machines, and the Mac app twice: on Apple silicon (`macos-15`, its arm64 slice) and on Intel+ Windows and Linux machines (the Linux player under `xvfb-run -a`: with no display at all it crashes, issue #533), and the Mac app twice: on Apple silicon (`macos-15`, its arm64 slice) and on Intel(`macos-15-intel`, its x86_64 slice; issue #548 tracks its end in August 2027). It fails when only one or two of thethree archives are attached. A release with none (a web-only release, before desktop players ship) passes, but itsrun summary says UNCHECKED.diff --git a/scripts/oss/tests/test_github_config.py b/scripts/oss/tests/test_github_config.pyindex dab20d789..7107c5f58 100644--- a/scripts/oss/tests/test_github_config.py+++ b/scripts/oss/tests/test_github_config.py@@ -170,6 +170,12 @@ def test_player_golden_runs_only_the_repositorys_own_released_players():assert '--sha256 "$SHA256"' in run_step["run"] and run_step["env"]["SHA256"] == "${{ matrix.sha256 }}"assert '${ARCH:+--arch "$ARCH"}' in run_step["run"] and run_step["env"]["ARCH"] == "${{ matrix.arch }}"assert golden["name"] == "Player golden (${{ matrix.label }})" and golden["runs-on"] == "${{ matrix.runner }}"+ # #533 (P62): the Linux player needs an X display even with -nographics; player_golden_check.py runs it under+ # xvfb-run, so the Linux job installs xvfb before that step, and only the Linux job.+ names = [s.get("name", "") for s in golden["steps"]]+ xvfb = next(s for s in golden["steps"] if "xvfb" in s.get("run", ""))+ assert xvfb["if"] == "matrix.platform == 'linux'" and "apt-get install" in xvfb["run"]+ assert names.index(xvfb["name"]) < names.index(run_step["name"])downloads = [s["run"] for s in steps(wf) if "gh release download" in s.get("run", "")]assert downloads and all('--repo "$GITHUB_REPOSITORY"' in r for r in downloads)assert "curl" not in text and "wget" not in text and "download-artifact" not in textdiff --git a/tools/player_golden_check.py b/tools/player_golden_check.pyindex 681c168af..d877b359a 100644--- a/tools/player_golden_check.py+++ b/tools/player_golden_check.py@@ -18,7 +18,8 @@ manual run; on a release event it passes (a web-only release) but writes an "UNC`run` checks the archive's SHA-256 against that digest (so a re-uploaded asset fails until it is re-planned), unpacks itinto an empty folder, finds the player, checks the layout (the notices of REQUIRED_NOTICES at the top level beside theplayer or the .app), runs it with-`-batchmode -nographics -golden -logFile <absolute path>` (docs/determinism.md) and passes only when it exits 0 and its log+`-batchmode -nographics -golden -logFile <absolute path>` (docs/determinism.md), the Linux player under `xvfb-run -a`+(DISPLAY_WRAPPER: it crashes with no display at all), and passes only when it exits 0 and its logholds `GOLDEN OK 1950 <hash1950>` and `GOLDEN OK 1952 <hash1952>` from the golden manifest, and no FAIL line. On failureit prints the whole player log. With --arch (the Mac app, run once per slice) the runner's `uname -m` must be thatarchitecture and `lipo -archs` must list it. Exit 0 when the check passes, 1 when it fails, 2 on bad input.@@ -31,9 +32,12 @@ import hashlibimport jsonimport osimport re+import shutil+import signalimport subprocessimport sysimport tarfile+import timeimport zipfilefrom pathlib import Path@@ -67,6 +71,17 @@ REQUIRED_NOTICES = ["LICENSE", "LICENSES/CC-BY-4.0.txt", "LICENSES/CC-BY-SA-4.0."THIRD-PARTY-NOTICES.md"]NOTICE_TOPS = {n.split("/")[0] for n in REQUIRED_NOTICES}+# What the player is started behind, by platform. Linux: a virtual X display. Unity 6's Linux player picks its window+# backend (x11 or wayland) at start-up, and with neither DISPLAY nor WAYLAND_DISPLAY set it picks none ("Selected window+# backend: (null)") and segfaults in PlayerMain after loading the first scene, with -batchmode -nographics or without them+# (issue #533: the v0.1.0-rc.0 run on ubuntu-24.04, reproduced in an ubuntu:24.04 x86_64 container). Under xvfb-run it+# selects x11 and passes; -nographics still keeps the Null graphics device, so the runner needs no GPU.+# A test pins this command.+DISPLAY_WRAPPER = {"linux": ["xvfb-run", "-a"]}++# Seconds a timed-out run gets between SIGTERM and SIGKILL (stop_group).+TERM_GRACE = 5+GOLDENS = (("1950", "hash1950"), ("1952", "hash1952"))FAIL = re.compile(r"\b(GOLDEN FAIL|BOOT FAIL)\b")@@ -219,17 +234,62 @@ def check_arch(exe: Path, arch: str, machine: str, archs: str) -> list[str]:return problems-def run_player(exe: Path, log: Path, timeout: int) -> int | None:+def player_command(exe: Path, log: Path, platform: str) -> list[str]:+ """The golden run's command line: the player with -batchmode -nographics -golden and an absolute -logFile, behind+ the platform's DISPLAY_WRAPPER if it has one."""+ return [*DISPLAY_WRAPPER.get(platform, []), str(exe), "-batchmode", "-nographics", "-golden", "-logFile",+ str(log.resolve())]+++def run_player(exe: Path, log: Path, timeout: int, platform: str) -> int | None:"""Runs the golden check; the exit code, or None on timeout. subprocess waits for a Windows GUI-subsystem player- too, which a plain PowerShell call would not."""+ too, which a plain PowerShell call would not. On POSIX the run gets its own process group and a timeout stops the+ whole group: xvfb-run starts the player and Xvfb as its children, and killing only xvfb-run would leave them."""if os.name != "nt":exe.chmod(exe.stat().st_mode | 0o111)- cmd = [str(exe), "-batchmode", "-nographics", "-golden", "-logFile", str(log.resolve())]+ cmd = player_command(exe, log, platform)print("RUN", " ".join(cmd), flush=True)+ with subprocess.Popen(cmd, cwd=exe.parent, start_new_session=os.name != "nt") as proc:+ try:+ return proc.wait(timeout=timeout)+ except subprocess.TimeoutExpired:+ stop_group(proc, TERM_GRACE)+ return None+++def stop_group(proc: subprocess.Popen, grace: float) -> None:+ """Stops a timed-out run. POSIX: SIGTERM to its process group, so the player and Xvfb can shut down, then SIGKILL to+ whatever is left after `grace` seconds. The run may exit just as the timeout fires: signalling a group that is gone+ raises ProcessLookupError, which ends the stop. macOS can also answer PermissionError, for a gone group or for a+ group that still holds a zombie, so that answer never escapes but also never cuts the grace short or skips the+ SIGKILL."""+ if os.name == "nt":+ proc.kill()+ proc.wait()+ returntry:- return subprocess.run(cmd, cwd=exe.parent, timeout=timeout).returncode- except subprocess.TimeoutExpired:- return None+ os.killpg(proc.pid, signal.SIGTERM)+ except ProcessLookupError:+ proc.wait()+ return+ except PermissionError:+ pass # macOS: a zombie in the group answers EPERM, and the rest may still be running+ deadline = time.monotonic() + grace+ while time.monotonic() < deadline:+ proc.poll() # reaps the group leader, so a zombie leader does not keep the group "alive"+ try:+ os.killpg(proc.pid, 0)+ except ProcessLookupError:+ break+ except PermissionError:+ pass # the same macOS answer: not proof that the group is gone, so the grace runs on+ time.sleep(0.1)+ else:+ try:+ os.killpg(proc.pid, signal.SIGKILL)+ except (ProcessLookupError, PermissionError):+ pass+ proc.wait()def summary(tag: str, include: list[dict], ok: bool) -> str:@@ -285,13 +345,16 @@ def cmd_run(a) -> int:print(f"ARCH runner {machine}, player slices {archs.strip()}", flush=True)if problems := check_arch(exe, a.arch, machine, archs):raise ValueError("; ".join(problems))+ if (wrapper := DISPLAY_WRAPPER.get(a.platform)) and not shutil.which(wrapper[0]):+ raise ValueError(f"{wrapper[0]} is not installed: the {a.platform} player needs a virtual display "+ "(apt-get install xvfb; the workflow installs it)")except (OSError, ValueError, subprocess.CalledProcessError, tarfile.TarError, zipfile.BadZipFile) as e:print(f"::error::{a.platform}: {e}")print(f"PLAYER GOLDEN ERROR {a.platform}")return 2log = work / "player.log"try:- code = run_player(exe, log, a.timeout)+ code = run_player(exe, log, a.timeout, a.platform)except OSError as e: # the player could not be started at all (for example: Exec format error); it has no exit codecode, start_error = None, f"the player could not be started: {e}"else:diff --git a/tools/tests/test_player_golden_check.py b/tools/tests/test_player_golden_check.pyindex 45a43c84c..5df1c5022 100644--- a/tools/tests/test_player_golden_check.py+++ b/tools/tests/test_player_golden_check.py@@ -1,11 +1,13 @@import hashlibimport ioimport json+import osimport reimport shutilimport subprocessimport sysimport tarfile+import timeimport zipfilefrom pathlib import Path@@ -32,6 +34,33 @@ def add_notices_to_tar(t):t.addfile(info, io.BytesIO(data))+def fake_xvfb_run(tmp_path, monkeypatch):+ """A stand-in for xvfb-run on PATH: it records its arguments, then runs the command as its child, as xvfb-run does+ (so a timeout must stop a grandchild). The file it records to is returned."""+ calls = tmp_path / "xvfb-run-calls.txt"+ bin_dir = tmp_path / "fakebin"+ bin_dir.mkdir()+ fake = bin_dir / "xvfb-run"+ fake.write_text(f'#!/bin/sh\necho "$@" >> "{calls}"\n[ "$1" = -a ] || exit 99\nshift\n"$@"\n')+ fake.chmod(0o755)+ monkeypatch.setenv("PATH", f"{bin_dir}{os.pathsep}{os.environ['PATH']}")+ return calls+++def gone_soon(pid, seconds=3.0):+ """Whether pid is gone within `seconds`. A killed orphan lingers for some milliseconds until init (launchd on+ macOS) reaps it, so a check made at once can still find it."""+ deadline = time.monotonic() + seconds+ while time.monotonic() < deadline:+ try:+ os.kill(pid, 0)+ except ProcessLookupError:+ return True+ time.sleep(0.01)+ return False++def release(tag, *names, draft=False):return {"tagName": tag, "isDraft": draft, "assets": [{"name": n, "digest": digest(n)} for n in names]}@@ -227,8 +256,80 @@ def test_unpack_keeps_the_executable_bit_and_refuses_paths_that_leave_the_folderpg.unpack(tmp_path / "good.7z", tmp_path / "out4")+def test_the_linux_player_runs_under_a_virtual_x_display_and_the_others_run_bare(tmp_path):+ # #533 (P62): with no X or Wayland display, Unity 6's Linux player selects no window backend ("Selected window+ # backend: (null)") and segfaults in PlayerMain, -batchmode -nographics or not. xvfb-run gives it one; -nographics+ # still keeps the Null graphics device, so the runner needs no GPU.+ exe, log = tmp_path / "Statecraft.x86_64", tmp_path / "player.log"+ args = [str(exe), "-batchmode", "-nographics", "-golden", "-logFile", str(log.resolve())]+ assert pg.player_command(exe, log, "linux") == ["xvfb-run", "-a", *args]+ assert pg.player_command(exe, log, "windows") == args+ assert pg.player_command(exe, log, "macos") == args++[email protected](sys.platform == "win32", reason="the fake player is a shell script")+def test_a_linux_run_without_xvfb_run_is_refused_before_the_player_runs(tmp_path, capsys, monkeypatch):+ (tmp_path / "manifest.txt").write_text(MANIFEST)+ arc = fake_linux_player(tmp_path, b"#!/bin/sh\n")+ monkeypatch.setenv("PATH", str(tmp_path / "nothing-here"))+ code = pg.main(["run", "--platform", "linux", "--manifest", str(tmp_path / "manifest.txt"), "--archive", str(arc),+ "--sha256", pg.sha256(arc), "--work", str(tmp_path / "w")])+ out = capsys.readouterr().out+ assert code == 2 and "xvfb-run is not installed" in out and "RUN " not in out++[email protected](sys.platform == "win32", reason="the fake player and xvfb-run are shell scripts")+def test_a_timeout_also_stops_what_xvfb_run_started(tmp_path, fake_xvfb_run):+ # xvfb-run runs the player as its child; killing only xvfb-run would leave the player running.+ exe = tmp_path / "Statecraft.x86_64"+ pid_file = tmp_path / "player.pid"+ exe.write_text(f'#!/bin/sh\necho $$ > "{pid_file}"\nexec sleep 30\n')+ exe.chmod(0o755)+ assert pg.run_player(exe, tmp_path / "player.log", 2, "linux") is None+ assert gone_soon(int(pid_file.read_text()))++[email protected](sys.platform == "win32", reason="the fake player and xvfb-run are shell scripts")+def test_a_timeout_asks_the_player_to_stop_before_killing_it(tmp_path, fake_xvfb_run):+ # Review #581 nit 1: SIGTERM first, so the player (and Xvfb) can shut down cleanly; SIGKILL only after the grace.+ exe = tmp_path / "Statecraft.x86_64"+ termed = tmp_path / "termed"+ exe.write_text(f"#!/bin/sh\ntrap 'echo yes > \"{termed}\"; exit 0' TERM\nsleep 30 &\nwait\n")+ exe.chmod(0o755)+ assert pg.run_player(exe, tmp_path / "player.log", 1, "linux") is None+ assert termed.read_text().strip() == "yes"++[email protected](sys.platform == "win32", reason="the fake player and xvfb-run are shell scripts")+def test_a_player_that_ignores_sigterm_is_killed_after_the_grace(tmp_path, fake_xvfb_run, monkeypatch):+ monkeypatch.setattr(pg, "TERM_GRACE", 1)+ exe = tmp_path / "Statecraft.x86_64"+ pid_file = tmp_path / "player.pid"+ exe.write_text(f"#!/bin/sh\ntrap '' TERM\necho $$ > \"{pid_file}\"\nwhile :; do sleep 1; done\n")+ exe.chmod(0o755)+ assert pg.run_player(exe, tmp_path / "player.log", 1, "linux") is None+ assert gone_soon(int(pid_file.read_text()))++[email protected](sys.platform == "win32", reason="process groups are POSIX")[email protected]("error", [ProcessLookupError, PermissionError])+def test_stopping_a_run_that_already_exited_is_not_an_error(monkeypatch, error):+ # Review #581 nit 2: the player can exit just as the timeout fires. Signalling its gone group raises+ # ProcessLookupError, or PermissionError on macOS; neither may escape.+ proc = subprocess.Popen(["true"], start_new_session=True)+ proc.wait()+ pg.stop_group(proc, 1) # the real race: the group is gone++ def gone(pid, sig):+ raise error()++ monkeypatch.setattr(pg.os, "killpg", gone)+ pg.stop_group(proc, 1)++@pytest.mark.skipif(sys.platform == "win32", reason="the fake player is a shell script")-def test_run_passes_a_player_that_prints_the_goldens_and_prints_the_log_when_it_does_not(tmp_path, capsys):+def test_run_passes_a_player_that_prints_the_goldens_and_prints_the_log_when_it_does_not(tmp_path, capsys,+ fake_xvfb_run):(tmp_path / "manifest.txt").write_text(MANIFEST)def archive(name, script):@@ -254,7 +355,9 @@ def test_run_passes_a_player_that_prints_the_goldens_and_prints_the_log_when_it_assert "but GitHub's digest for the asset is" in out and not (tmp_path / "w0").exists()assert pg.main(args + ["--archive", str(ok), *sha(ok), "--work", str(tmp_path / "w1")]) == 0out = capsys.readouterr().out- assert "PLAYER GOLDEN OK linux" in out and "ARCHIVE ok.tar.gz sha256 " in out and "-batchmode -nographics -golden -logFile" in out+ assert "PLAYER GOLDEN OK linux" in out and "ARCHIVE ok.tar.gz sha256 " in out+ assert "RUN xvfb-run -a " in out and "-batchmode -nographics -golden -logFile" in out+ assert fake_xvfb_run.read_text().startswith("-a ") and "Statecraft.x86_64 -batchmode -nographics" in fake_xvfb_run.read_text()bad = archive("bad.tar.gz", "for a; do log=$a; done\necho 'GOLDEN FAIL 1950 x expected y' >> \"$log\"\nexit 1\n")assert pg.main(args + ["--archive", str(bad), *sha(bad), "--work", str(tmp_path / "w2")]) == 1@@ -316,7 +419,10 @@ def fake_linux_player(tmp_path, body: bytes, name="p.tar.gz"):@pytest.mark.skipif(sys.platform == "win32", reason="exec format errors are POSIX")-def test_a_player_that_cannot_start_fails_cleanly(tmp_path, capsys):+def test_a_player_that_cannot_start_fails_cleanly(tmp_path, capsys, monkeypatch):+ # The player started directly (as on Windows and macOS): under xvfb-run an unstartable Linux player is xvfb-run's+ # exit code 126 instead, which the exit-code rule already fails.+ monkeypatch.setattr(pg, "DISPLAY_WRAPPER", {})(tmp_path / "manifest.txt").write_text(MANIFEST)arc = fake_linux_player(tmp_path, b"\x00\x01 not an executable")code = pg.main(["run", "--platform", "linux", "--manifest", str(tmp_path / "manifest.txt"), "--archive", str(arc),