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.

fix(unity,tools): golden run quits 1 on a boot error; web_check cleanup, scan tests, real build size

eyalgolan7ad9c0f54e1f
diff --git a/docs/determinism.md b/docs/determinism.md
index e6835af4b..155e22ed8 100644
--- a/docs/determinism.md
+++ b/docs/determinism.md
@@ -40,9 +40,12 @@ IL2CPP player in Chrome (M3 Task 22). Re-check with:
"$UNITY" -batchmode -quit -projectPath unity -buildTarget WebGL -executeMethod Statecraft.Game.EditorTools.Build.Web -compression disabled -logFile unity-build-web.log
uv run tools/web_check.py unity/Builds/Web-disabled --query golden --expect "GOLDEN OK 1950" --expect "GOLDEN OK 1952"
"$UNITY" -batchmode -quit -projectPath unity -buildTarget OSXUniversal -executeMethod Statecraft.Game.EditorTools.Build.Mac -logFile unity-build-mac.log
-"unity/Builds/Mac/Statecraft.app/Contents/MacOS/Statecraft Israel" -batchmode -nographics -golden -logFile unity-golden-mac.log; echo exit=$?
+"unity/Builds/Mac/Statecraft.app/Contents/MacOS/Statecraft Israel" -batchmode -nographics -golden -logFile "$PWD/unity-golden-mac.log"; echo exit=$?
```
+The player needs an absolute `-logFile` path: with a relative one it wrote no log file in the check run. The editor
+commands are fine with relative paths.
+
**Any change to a golden hash is a deliberate rules or content change.** Such a change could be to a rule, a system,
content in `content/`, or the hash format. When it happens, update every place above in the same commit, add a row to
the history below, and say in the commit message why the hash moved. If a hash changes and you did not mean to change
diff --git a/tools/README.md b/tools/README.md
index d526d5593..42564536b 100644
--- a/tools/README.md
+++ b/tools/README.md
@@ -12,7 +12,7 @@ Offline data tools (uv inline-script Python). Run from the repo root.
- `settlement_hexes.py` writes `content/map/settlement_hexes.yaml` (committed): the hex that owns each settlement, by the
`hexgrid.settlement_hex` rule. The sim reads it, so it needs no projection maths.
- `web_check.py` serves a WebGL build on http://localhost and opens it in headless Chrome for Testing (Playwright's
- cache); it passes when the console shows the expected lines (`GOLDEN OK ...`, `SMOKE OK ...`).
+ cache; macOS only, arm64 or x64); it passes when the console shows the expected lines (`GOLDEN OK ...`, `SMOKE OK ...`).
- `preview_map.py` renders the geography check image `tools/.cache/map-preview.png`.
## Running the tests
@@ -23,7 +23,7 @@ Run from the repo root; this installs every pinned dependency (rasterio included
uv run --with pytest==9.1.1 --with rasterio==1.5.2 --with numpy==2.5.3 --with pyyaml==6.0.3 --with pillow==12.3.0 --with requests==2.32.5 pytest tools/tests -q
```
-Expected: `99 passed`. Omitting a dependency (e.g. rasterio) silently drops tests or fails collection.
+Expected: `103 passed`. Omitting a dependency (e.g. rasterio) silently drops tests or fails collection.
## Required attribution (Copernicus DEM licence, modified data)
diff --git a/tools/tests/test_web_check.py b/tools/tests/test_web_check.py
index 00a58d3d9..d59c0a782 100644
--- a/tools/tests/test_web_check.py
+++ b/tools/tests/test_web_check.py
@@ -1,5 +1,7 @@
"""tools/web_check.py: the console-line parser and the static server's headers (no browser needed)."""
import gzip
+import http.client
+import re
import urllib.request
import web_check as wc
@@ -28,3 +30,47 @@ def test_precompressed_files_get_content_encoding_and_wasm_its_type(tmp_path):
assert urllib.request.urlopen(base + "/index.html").headers["Content-Encoding"] is None
finally:
server.shutdown()
+
+
+FAIL = re.compile(r"GOLDEN FAIL|BOOT FAIL")
+
+
+def line(text):
+ return f'[1010/025003.375619:INFO:CONSOLE:2] "{text}", source: http://localhost:1/index.html (2)'
+
+
+def test_scan_passes_when_every_expected_text_was_seen():
+ status, pending, texts = wc.scan([line("GOLDEN OK 1950 a"), line("GOLDEN OK 1952 b")], ["GOLDEN OK 1950", "GOLDEN OK 1952"], FAIL)
+ assert (status, pending) == ("pass", []) and texts == ["GOLDEN OK 1950 a", "GOLDEN OK 1952 b"]
+
+
+def test_scan_fails_on_a_failure_line_and_waits_for_missing_texts():
+ status, pending, texts = wc.scan([line("GOLDEN FAIL 1950 x expected y")], ["GOLDEN OK 1950"], FAIL)
+ assert status == "fail" and texts == ["GOLDEN FAIL 1950 x expected y"]
+ status, pending, _ = wc.scan([line("GOLDEN OK 1950 a")], ["GOLDEN OK 1950", "GOLDEN OK 1952"], FAIL)
+ assert (status, pending) == ("pending", ["GOLDEN OK 1952"])
+
+
+def test_scan_ignores_lines_that_are_not_console_messages():
+ status, pending, texts = wc.scan(["[0101/000000:ERROR:gpu] something", " at Foo.Bar()"], ["X"], FAIL)
+ assert (status, pending, texts) == ("pending", ["X"], [])
+
+
+def test_compressed_scripts_and_data_keep_their_types_and_traversal_is_404(tmp_path):
+ (tmp_path / "site").mkdir()
+ (tmp_path / "site" / "a.framework.js.gz").write_bytes(gzip.compress(b"x"))
+ (tmp_path / "site" / "a.data.br").write_bytes(b"\x00")
+ (tmp_path / "secret.txt").write_text("secret")
+ server = wc.serve(tmp_path / "site")
+ try:
+ base = f"http://localhost:{server.server_address[1]}"
+ assert urllib.request.urlopen(base + "/a.framework.js.gz").headers["Content-Type"] == "application/javascript"
+ assert urllib.request.urlopen(base + "/a.data.br").headers["Content-Type"] == "application/octet-stream"
+ conn = http.client.HTTPConnection("localhost", server.server_address[1])
+ for path in ("/../secret.txt", "/%2e%2e/secret.txt"):
+ conn.request("GET", path)
+ r = conn.getresponse(); r.read()
+ assert r.status == 404, path
+ finally:
+ server.shutdown()
+ server.server_close()
diff --git a/tools/web_check.py b/tools/web_check.py
index a1163ec9f..ac4c3bfa6 100644
--- a/tools/web_check.py
+++ b/tools/web_check.py
@@ -3,8 +3,9 @@
# dependencies = []
# ///
"""Serve a Unity WebGL build on http://localhost and open it in headless Chrome; pass when the console shows every
-expected line, fail on a failure line or a timeout. Uses the Playwright-cached chrome-headless-shell (no npm needed):
-console messages reach stderr with --enable-logging=stderr --v=1 as INFO:CONSOLE... "text", source: ...
+expected line, fail on a failure line or a timeout. Uses Chrome for Testing from the Playwright cache (macOS only, no npm needed) in --headless=new mode (the cached
+chrome-headless-shell has no WebGL for Unity): console messages reach stderr with --enable-logging=stderr --v=1 as
+INFO:CONSOLE... "text", source: ...
Usage (from the repo root):
uv run tools/web_check.py unity/Builds/Web-disabled --query "golden" --expect "GOLDEN OK 1950" --expect "GOLDEN OK 1952"
@@ -19,6 +20,9 @@ import os
import re
import subprocess
import sys
+import queue
+import shutil
+import tempfile
import threading
import time
from pathlib import Path
@@ -26,7 +30,7 @@ from pathlib import Path
# A console message's first line; Unity's Debug.Log adds a stack trace on later lines, so the closing quote and
# ", source:" may be far below. Only the first line is matched.
CONSOLE = re.compile(r'INFO:CONSOLE[^\]]*\] "(.*?)(?:", source: .*)?$')
-CHROME_GLOB = "ms-playwright/chromium-*/chrome-mac-arm64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing"
+CHROME_GLOB = "ms-playwright/chromium-*/chrome-mac*/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing"
class Handler(http.server.SimpleHTTPRequestHandler):
@@ -55,10 +59,16 @@ class Handler(http.server.SimpleHTTPRequestHandler):
def find_chrome() -> Path:
- found = sorted(Path.home().joinpath("Library", "Caches").glob(CHROME_GLOB))
+ """The newest Chrome for Testing in the Playwright cache (macOS, arm64 or x64), by numeric revision."""
+ found = list(Path.home().joinpath("Library", "Caches").glob(CHROME_GLOB))
if not found:
- sys.exit("Chrome for Testing not found under ~/Library/Caches/ms-playwright (npx playwright install chromium)")
- return found[-1]
+ sys.exit("Chrome for Testing not found under ~/Library/Caches/ms-playwright/chromium-<rev>/chrome-mac*"
+ " (macOS only; install with: npx playwright install chromium)")
+
+ def revision(path: Path) -> int:
+ m = re.search(r"chromium-(\d+)", str(path))
+ return int(m.group(1)) if m else -1
+ return max(found, key=revision)
def serve(root: Path) -> http.server.ThreadingHTTPServer:
@@ -67,6 +77,22 @@ def serve(root: Path) -> http.server.ThreadingHTTPServer:
return server
+def scan(lines, expect, fail):
+ """Reads stderr lines: returns (status, pending, texts). status is "fail" at the first failure message, "pass" when
+ every expected text has been seen, else "pending". texts are the console messages found (first lines only)."""
+ pending, texts = list(expect), []
+ for raw in lines:
+ m = CONSOLE.search(raw)
+ if not m:
+ continue
+ text = m.group(1)
+ texts.append(text)
+ if fail.search(text):
+ return "fail", pending, texts
+ pending = [p for p in pending if p not in text]
+ return ("pass" if not pending else "pending"), pending, texts
+
+
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("build", type=Path)
@@ -78,41 +104,57 @@ def main() -> int:
a = ap.parse_args()
if not (a.build / "index.html").exists():
sys.exit(f"{a.build}/index.html not found")
- server = serve(a.build)
- url = f"http://localhost:{server.server_address[1]}/index.html" + (f"?{a.query}" if a.query else "")
- flags = ["--headless=new", "--enable-logging=stderr", "--v=1", "--no-first-run", "--no-default-browser-check",
- "--autoplay-policy=no-user-gesture-required", "--window-size=1920,1080",
- "--disable-frame-rate-limit", "--disable-gpu-vsync",
- f"--user-data-dir={a.build.resolve()}/../.web-check-profile"]
- if a.swiftshader:
- flags += ["--use-angle=swiftshader", "--enable-unsafe-swiftshader"]
- proc = subprocess.Popen([str(find_chrome()), *flags, url], stderr=subprocess.PIPE, stdout=subprocess.DEVNULL, text=True, errors="replace")
- pending, fail, deadline = list(a.expect), re.compile(a.fail), time.time() + a.timeout
- lines: list[str] = []
- reader = threading.Thread(target=lambda: lines.extend(iter(proc.stderr.readline, "")), daemon=True)
- reader.start()
- seen = 0
+ server, proc, profile = None, None, tempfile.mkdtemp(prefix="web-check-")
try:
+ chrome = find_chrome()
+ server = serve(a.build)
+ url = f"http://localhost:{server.server_address[1]}/index.html" + (f"?{a.query}" if a.query else "")
+ flags = ["--headless=new", "--enable-logging=stderr", "--v=1", "--no-first-run", "--no-default-browser-check",
+ "--autoplay-policy=no-user-gesture-required", "--window-size=1920,1080",
+ "--disable-frame-rate-limit", "--disable-gpu-vsync", f"--user-data-dir={profile}"]
+ if a.swiftshader:
+ flags += ["--use-angle=swiftshader", "--enable-unsafe-swiftshader"]
+ proc = subprocess.Popen([str(chrome), *flags, url], stderr=subprocess.PIPE, stdout=subprocess.DEVNULL, text=True, errors="replace")
+ fail, pending, deadline = re.compile(a.fail), list(a.expect), time.time() + a.timeout
+ inbox: queue.Queue = queue.Queue()
+ threading.Thread(target=lambda: [inbox.put(l) for l in iter(proc.stderr.readline, "")], daemon=True).start()
+ idle = 0
while time.time() < deadline:
- while seen < len(lines):
- m = CONSOLE.search(lines[seen]); seen += 1
- if not m:
- continue
- text = m.group(1)
- print("console:", text)
- if fail.search(text):
- print(f"FAIL: {text}")
- return 1
- pending = [p for p in pending if p not in text]
- if not pending:
+ batch = []
+ while True: # lines are dropped once scanned: only the batch is held
+ try:
+ batch.append(inbox.get_nowait())
+ except queue.Empty:
+ break
+ status, pending, texts = scan(batch, pending, fail)
+ for t in texts:
+ print("console:", t)
+ if status == "fail":
+ print(f"FAIL: {texts[-1]}")
+ return 1
+ if status == "pass":
print("PASS: saw " + ", ".join(a.expect))
return 0
+ if proc.poll() is not None and not batch:
+ idle += 1 # two idle polls after exit: the reader thread has drained stderr
+ else:
+ idle = 0
+ if idle >= 2:
+ print(f"BROWSER EXITED code {proc.returncode}; never saw " + ", ".join(pending))
+ return 1
time.sleep(0.2)
print("TIMEOUT: never saw " + ", ".join(pending))
return 1
finally:
- proc.terminate()
- server.shutdown()
+ if proc is not None:
+ proc.terminate()
+ try:
+ proc.wait(5)
+ except subprocess.TimeoutExpired:
+ proc.kill(); proc.wait()
+ if server is not None:
+ server.shutdown(); server.server_close()
+ shutil.rmtree(profile, ignore_errors=True)
if __name__ == "__main__":
diff --git a/unity/Assets/Editor/Build.cs b/unity/Assets/Editor/Build.cs
index 66fbc12c1..6cab13d2c 100644
--- a/unity/Assets/Editor/Build.cs
+++ b/unity/Assets/Editor/Build.cs
@@ -1,5 +1,6 @@
#nullable enable
using System;
+using System.IO;
using System.Linq;
using UnityEditor;
using UnityEditor.Build;
@@ -59,6 +60,13 @@ namespace Statecraft.Game.EditorTools
/// <summary>Exits with code 1 after the caller's settings have been restored.</summary>
static void ExitIfFailed(bool ok) { if (!ok) EditorApplication.Exit(1); }
+ /// <summary>The real size of the build output (summary.totalSize also counts build intermediates).</summary>
+ static double OutputMegabytes(string path)
+ {
+ if (File.Exists(path)) return new FileInfo(path).Length / 1048576.0;
+ return Directory.Exists(path) ? new DirectoryInfo(path).EnumerateFiles("*", SearchOption.AllDirectories).Sum(f => f.Length) / 1048576.0 : 0;
+ }
+
static bool Run(BuildTarget target, string location)
{
var report = BuildPipeline.BuildPlayer(new BuildPlayerOptions
@@ -66,7 +74,7 @@ namespace Statecraft.Game.EditorTools
scenes = new[] { ProjectSetup.BootScene }, locationPathName = location, target = target, options = BuildOptions.None,
});
var s = report.summary;
- Debug.Log($"BUILD {s.result} {target} -> {location}: {s.totalSize / 1048576.0:0.0} MB, {s.totalErrors} errors, {s.totalTime.TotalSeconds:0}s");
+ Debug.Log($"BUILD {s.result} {target} -> {location}: {OutputMegabytes(location):0.0} MB on disk, {s.totalErrors} errors, {s.totalTime.TotalSeconds:0}s");
return s.result == BuildResult.Succeeded;
}
}
diff --git a/unity/Assets/Scripts/Boot/GameBoot.cs b/unity/Assets/Scripts/Boot/GameBoot.cs
index d9f62ea0b..88c216f03 100644
--- a/unity/Assets/Scripts/Boot/GameBoot.cs
+++ b/unity/Assets/Scripts/Boot/GameBoot.cs
@@ -41,6 +41,7 @@ namespace Statecraft.Game.Boot
Error = e.Message;
Debug.LogError("BOOT FAIL " + e.Message);
Debug.LogException(e);
+ if (GoldenCheck.QuitCodeOnError(GoldenCheck.Requested(), Application.platform == RuntimePlatform.WebGLPlayer) is int code) Application.Quit(code);
}
}
}
diff --git a/unity/Assets/Scripts/Boot/GoldenCheck.cs b/unity/Assets/Scripts/Boot/GoldenCheck.cs
index 9a71bce6b..84f21e9a9 100644
--- a/unity/Assets/Scripts/Boot/GoldenCheck.cs
+++ b/unity/Assets/Scripts/Boot/GoldenCheck.cs
@@ -16,6 +16,9 @@ namespace Statecraft.Game.Boot
? UrlFlags.Has(Application.absoluteURL, "golden")
: Environment.GetCommandLineArgs().Contains("-golden");
+ /// <summary>The exit code a boot error must quit with: 1 for a desktop -golden run (so it never hangs), else null.</summary>
+ public static int? QuitCodeOnError(bool requested, bool webgl) => requested && !webgl ? 1 : (int?)null;
+
public static (bool ok, List<string> lines) Run(Content c)
{
var lines = new List<string>();
diff --git a/unity/Assets/Scripts/Boot/UrlFlags.cs b/unity/Assets/Scripts/Boot/UrlFlags.cs
index 59bf1fa29..3a5451d25 100644
--- a/unity/Assets/Scripts/Boot/UrlFlags.cs
+++ b/unity/Assets/Scripts/Boot/UrlFlags.cs
@@ -14,7 +14,7 @@ namespace Statecraft.Game.Boot
public static int Int(string? url, string name)
{
var m = Regex.Match(url ?? "", @"[?&]" + Regex.Escape(name) + @"=(\d+)");
- return m.Success ? int.Parse(m.Groups[1].Value, CultureInfo.InvariantCulture) : 0;
+ return m.Success && int.TryParse(m.Groups[1].Value, NumberStyles.None, CultureInfo.InvariantCulture, out var v) ? v : 0;
}
}
}
diff --git a/unity/Assets/Tests/EditMode/GoldenCheckTests.cs b/unity/Assets/Tests/EditMode/GoldenCheckTests.cs
index b914fdbbd..66a7b11ff 100644
--- a/unity/Assets/Tests/EditMode/GoldenCheckTests.cs
+++ b/unity/Assets/Tests/EditMode/GoldenCheckTests.cs
@@ -27,4 +27,16 @@ public class GoldenCheckTests
Assert.AreEqual(5, UrlFlags.Int("http://x/index.html?golden&smoke=5", "smoke"));
Assert.AreEqual(0, UrlFlags.Int("http://x/smoke=5/index.html", "smoke"));
}
+
+ [Test]
+ public void AnOverflowingIntegerFlagReadsAsAbsent() =>
+ Assert.AreEqual(0, UrlFlags.Int("http://x/index.html?smoke=99999999999999999999", "smoke"));
+
+ [Test]
+ public void ABootErrorQuitsWithCode1OnlyForADesktopGoldenRun()
+ {
+ Assert.AreEqual(1, GoldenCheck.QuitCodeOnError(requested: true, webgl: false));
+ Assert.IsNull(GoldenCheck.QuitCodeOnError(requested: true, webgl: true));
+ Assert.IsNull(GoldenCheck.QuitCodeOnError(requested: false, webgl: false));
+ }
}