A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
fix(visual): exact 1920x1080 viewport over CDP, res= and stall enforcement, kept-awake windows, two boot spans with the ruling-3 budget
eyalgolanbc7f11f26e82
diff --git a/docs/dev-setup.md b/docs/dev-setup.mdindex 0a4e0d881..d606fdd6f 100644--- a/docs/dev-setup.md+++ b/docs/dev-setup.md@@ -27,9 +27,11 @@profile per feature) and `?shot` (screenshots at the promo poses as `SHOT` console lines). Desktop players take `-golden`,`-smoke N`, `-profile`, `-camlog`, `-bootlog`, `-navlog`, `-vprofile` and `-shot`. The console also shows `GAME OK <date> turn <n> hash <h>` at start and `TURN <n> <date> hash <h>` per turn.- Visual checks (docs/visual-v1.md): measure only under the machine lock, which also waits for any open Unity editor:- `uv run tools/machine_lock.py --exclusive --wait-unity -- uv run tools/web_check.py <build> --query vprofile --expect "PROFILE visual done" --timeout 1800`- (headless), `... -- uv run tools/headed.py profile --build <build> --dpr 1` (headed; `--dpr 2` is the fill-rate stress- proxy) and `... -- uv run tools/headed.py boot --build <build> --runs 3 --baseline <ms>` (the boot budget); wrap Unity+ `uv run tools/machine_lock.py --exclusive --wait-unity -- uv run tools/web_check.py <build> --query vprofile --expect "PROFILE visual done" --timeout 1800 --stall 120`+ (headless), `... -- uv run tools/headed.py profile --build <build> --dpr 1` (headed; `--dpr 2` is the+ fill-rate stress proxy) and `... -- uv run tools/headed.py boot --build <build> --runs 3 --baseline <ms>+ --baseline-first-frame <ms>` (the boot budget: two spans, default allowance max(300 ms, 50%)); all of them fix the+ viewport to 1920x1080 over CDP and fail on another `res=`; wrap Unitybatch commands in `uv run tools/machine_lock.py --shared -- ...`; `tools/art_checkpoint.sh [--no-build] <name>` for theowner's side-by-side images.- A player build rewrites some URP asset and player-setting fields as build-time caches; drop them afterwards withdiff --git a/docs/visual-v1.md b/docs/visual-v1.mdindex 258acb74c..4083cb15c 100644--- a/docs/visual-v1.md+++ b/docs/visual-v1.md@@ -8,12 +8,21 @@ Plan: `docs/superpowers/plans/2026-10-11-statecraft-visual-v1.md`. Promo targets- Frame time: `?vprofile` (WebGL) or `-vprofile` (desktop player, quits when done), always under`uv run tools/machine_lock.py --exclusive --wait-unity -- ...` (no other Unity job on the machine). Per pose, everyconfiguration (`all`, each toggle off alone as `-<name>`, `none`) runs 3 times in interleaved orders, 300 frames after- 60 warm-up frames; Chrome runs with `--disable-frame-rate-limit --disable-gpu-vsync --force-device-scale-factor=1` (headless through- `web_check.py`, headed through `headed.py profile`), so times are not capped at the display rate and headed and headless- runs draw the same pixels. Every line states `res=` and- the render `scale=`. Read the `PROFILE summary` lines: a feature costs `median(all) - median(-name)`.-- Boot: `uv run tools/headed.py boot --runs 3 [--baseline MS]` (three cold loads in a headed window; the map-build span is- heightmap decoded to map built; `--cpu 4` adds CPU throttling as a cheap low-end proxy).+ 60 warm-up frames (and, before the first pose, one discarded warm-up pass of every configuration); Chrome runs with+ `--disable-frame-rate-limit --disable-gpu-vsync` and the anti-throttling flags (`--disable-backgrounding-occluded-windows+ --disable-renderer-backgrounding --disable-background-timer-throttling`), headless through `web_check.py` (add+ `--stall 120`), headed through `headed.py profile`. Both fix the page's viewport to exactly 1920x1080 CSS pixels at the+ DPR over CDP (`Emulation.setDeviceMetricsOverride`, before the page loads), so headed and headless runs draw the same+ pixels even when the laptop screen clamps the headed window (its final composite is then scaled; the backbuffer is not).+ Every line states `res=` and the render `scale=`, and both tools FAIL on a `res=` other than 1920x1080 times the DPR+ (and on a stall: no console line for 120 s). Read the `PROFILE summary` lines: a feature costs+ `median(all) - median(-name)`. The WebGL frame clock is quantised to about 1 ms: averages are fine, but every p95 is a+ whole millisecond, so a p95 budget is only good to about 1 ms.+- Boot: `uv run tools/headed.py boot --runs 3 [--baseline MS] [--baseline-first-frame MS] [--cpu R]` (three cold loads in+ a kept-awake headed window with a 1920x1080 viewport). Two spans, each the median of the runs: `map_build_ms`+ (heightmap decoded to map built) and `first_frame_ms` (navigation start to the second animation frame after `GAME OK`:+ download, scene load and texture uploads, map build and the first draw with its shader compiles). `--cpu 4` adds CPU+ throttling as a cheap low-end proxy; every line states `cpu=`.- Headed frame time: `uv run tools/headed.py profile --dpr 1` (`--dpr 2` is the fill-rate stress proxy). `--wait-unity`also waits for an interactive Unity editor that has any worktree open (it holds `unity/Temp/UnityLockfile`): close it,or the profile waits.@@ -28,7 +37,8 @@ Measured on the development Mac (Apple silicon, integrated GPU), 1920x1080 at DPwhen it exceeds the budget plus the larger of the two spreads;- headed numbers are recorded, plus a DPR-2 headed run in Task 10 as a fill-rate stress proxy for weaker GPUs; the 30 fpsfloor for an integrated-GPU laptop (research notes 2.3) is 33 ms p95;-- boot: the map-build span grows by at most 1,000 ms over the Task 1 baseline (median of 3).+- boot: each span (`map_build_ms` and `first_frame_ms`, median of 3, at `--cpu 1` and at `--cpu 4`) grows by at most+ max(300 ms, 50% of its Task 1 baseline): the tool's default when `--budget` is not given (controller ruling 3).## Baseline (Task 1, before any visual change)| Run | Lines |diff --git a/tools/README.md b/tools/README.mdindex 85f2541ac..697ce3cc6 100644--- a/tools/README.md+++ b/tools/README.md@@ -34,7 +34,7 @@ Run from the repo root; this installs every pinned dependency (rasterio includeduv 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: `129 passed, 1 skipped` (the skipped one is the headed browser check; add `--headed` and `--with websockets==15.0.1` to run it). Omitting a dependency (e.g. rasterio) silently drops tests or fails collection.+Expected: `142 passed, 1 skipped` (the skipped one is the headed browser check; add `--headed` and `--with websockets==15.0.1` to run it). Omitting a dependency (e.g. rasterio) silently drops tests or fails collection.## Required attribution (Copernicus DEM licence, modified data)diff --git a/tools/headed.py b/tools/headed.pyindex 73480ce45..12c6465ab 100644--- a/tools/headed.py+++ b/tools/headed.py@@ -15,7 +15,7 @@ serves a WebGL build with web_check's handler, and drives it over one browser-leRun from the repo root, e.g.:uv run tools/headed.py boot --build unity/Builds/Web-disabled --cpu 8uv run tools/headed.py navpairs --build unity/Builds/Web-disabled --cpu 20- uv run tools/headed.py boot --build unity/Builds/Web-disabled --runs 3 --baseline 5400+ uv run tools/headed.py boot --build unity/Builds/Web-disabled --runs 3 --baseline 450 --baseline-first-frame 9000Coordinates are CSS pixels for a 1568x752 window (the playtest window). Used for playtest 2 (P2-1, P2-4) and the finalreview evidence; the EditMode tests are the regression guard, this is the in-browser check."""@@ -52,11 +52,15 @@ def burst_events(points):BOOT_PHASE = re.compile(r"BOOT phase=(.+?) at=(\d+) ms dt=(\d+) ms")-def browser_flags(profile: str, width: int, height: int, dpr: float | None = None, uncapped: bool = False) -> list[str]:+def browser_flags(profile: str, width: int, height: int, dpr: float | None = None, uncapped: bool = False,+ keep_awake: bool = False) -> list[str]:"""Chrome flags for a headed run. dpr forces the device pixel ratio (1: the same pixels as a headless run; 2: the- visual v1 fill-rate stress proxy); uncapped lifts the display's frame-rate cap for frame-time profiles."""+ visual v1 fill-rate stress proxy); uncapped lifts the display's frame-rate cap for frame-time profiles; keep_awake+ stops Chrome throttling the window when it is in the background or covered (profiles and boot timings)."""flags = ["--use-angle=metal", "--remote-debugging-port=0", f"--user-data-dir={profile}", "--no-first-run","--no-default-browser-check", f"--window-size={width},{height}"]+ if keep_awake:+ flags += web_check.KEEP_AWAKEif dpr is not None:flags.append(f"--force-device-scale-factor={dpr:g}")if uncapped:@@ -81,16 +85,38 @@ def map_build_ms(phases) -> int:return first["map built"][0] - first["heightmap decoded"][0] + first["heightmap decoded"][1]-def over_budget(spans, baseline, budget) -> tuple[float, bool]:- """(median span, whether it exceeds baseline + budget); never over without a baseline."""+def allowed_growth(baseline, budget=None) -> float:+ """The boot budget's allowed growth over the baseline: budget when given, else max(300 ms, 50% of the baseline)."""+ return budget if budget is not None else max(300.0, 0.5 * baseline)+++def over_budget(spans, baseline, budget=None) -> tuple[float, bool]:+ """(median span, whether it exceeds baseline + allowed_growth); never over without a baseline."""median = statistics.median(spans)- return median, baseline is not None and median > baseline + budget+ return median, baseline is not None and median > baseline + allowed_growth(baseline, budget)+++# Installed before the page's own scripts: on the player's "GAME OK" line it waits two animation frames (the frame that+# draws the new map, shader compiles included, and the next) and records the time since navigation start.+FIRST_FRAME_SCRIPT = """(() => {+ const log = console.log;+ console.log = function (...args) {+ if (window.__scFirstFrame === undefined && typeof args[0] === "string" && args[0].startsWith("GAME OK")) {+ window.__scFirstFrame = null;+ requestAnimationFrame(() => requestAnimationFrame(() => { window.__scFirstFrame = performance.now(); }));+ }+ return log.apply(this, args);+ };+})();"""class Browser:- def __init__(self, build: Path, port=8766, width=WINDOW[0], height=WINDOW[1], dpr=None, uncapped=False):+ def __init__(self, build: Path, port=8766, width=WINDOW[0], height=WINDOW[1], dpr=None, uncapped=False,+ viewport=None, keep_awake=False):+ """viewport (w, h) fixes the page's CSS viewport over CDP before it loads (deviceScaleFactor = dpr or 1), so the+ player renders exactly that size even when the screen clamps the window (review ruling 1)."""self.build, self.port, self.size = Path(build), port, (width, height)- self.dpr, self.uncapped = dpr, uncapped+ self.dpr, self.uncapped, self.viewport, self.keep_awake = dpr, uncapped, viewport, keep_awakeself.profile = tempfile.mkdtemp(prefix="statecraft-headed-")self.next_id, self.pending, self.console = 0, {}, []@@ -100,7 +126,7 @@ class Browser:threading.Thread(target=self.server.serve_forever, daemon=True).start()self.base = f"http://localhost:{self.port}/"w, h = self.size- flags = browser_flags(self.profile, w, h, self.dpr, self.uncapped)+ flags = browser_flags(self.profile, w, h, self.dpr, self.uncapped, self.keep_awake)self.proc = subprocess.Popen([str(web_check.find_chrome()), *flags], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)port_file = Path(self.profile) / "DevToolsActivePort"for _ in range(200):@@ -148,25 +174,37 @@ class Browser:raise RuntimeError(f"{method}: {r['error']}")return r.get("result", {})- async def open(self, query="", cpu=1.0):+ async def open(self, query="", cpu=1.0, init_script=None):target = (await self.send("Target.createTarget", {"url": "about:blank"}))["targetId"]sid = (await self.send("Target.attachToTarget", {"targetId": target, "flatten": True}))["sessionId"]for m in ("Runtime.enable", "Page.enable"):await self.send(m, session=sid)if cpu != 1:await self.send("Emulation.setCPUThrottlingRate", {"rate": cpu}, session=sid)+ if self.viewport is not None:+ await self.send("Emulation.setDeviceMetricsOverride", web_check.viewport_override(*self.viewport, self.dpr or 1), session=sid)+ if init_script is not None:+ await self.send("Page.addScriptToEvaluateOnNewDocument", {"source": init_script}, session=sid)await self.send("Page.navigate", {"url": self.base + "index.html" + (f"?{query}" if query else "")}, session=sid)return siddef lines(self, sid):return [t for s, t, _ in self.console if s == sid]- async def wait_for(self, sid, pattern, timeout=300, after=0):+ async def wait_for(self, sid, pattern, timeout=300, after=0, stall=None):+ """The first console line matching pattern; TimeoutError after timeout seconds, or (stall) after stall seconds+ without any new console line, so a throttled or hung page fails loudly instead of waiting out the timeout."""rx, end = re.compile(pattern), time.time() + timeout+ seen, last = len(self.lines(sid)), time.time()while time.time() < end:- for t in self.lines(sid)[after:]:+ lines = self.lines(sid)+ for t in lines[after:]:if rx.search(t):return t+ if len(lines) != seen:+ seen, last = len(lines), time.time()+ elif stall is not None and time.time() - last > stall:+ raise TimeoutError(f"STALLED: no console line for {stall:.0f} s waiting for /{pattern}/; last lines: {lines[-8:]}")await asyncio.sleep(0.1)raise TimeoutError(f"never saw /{pattern}/; last lines: {self.lines(sid)[-8:]}")@@ -184,37 +222,61 @@ class Browser:async def boot(args):- """?bootlog timings, args.runs times (each in a fresh profile: a cold load), then the median map-build span; 1 when it- exceeds --baseline + --budget."""- spans = []+ """?bootlog timings, args.runs times (each in a fresh profile: a cold load) in a kept-awake window with a 1920x1080+ viewport, then two medians: the map-build span (heightmap decoded to map built) and the first frame (navigation+ start to the second animation frame after GAME OK: download, scene load, map build and the first draw with its+ shader compiles). 1 when either exceeds its baseline + the allowed growth (--budget, default max(300 ms, 50%))."""+ builds, firsts = [], []for run in range(args.runs):- async with Browser(args.build) as b:- sid = await b.open("bootlog", args.cpu)- await b.wait_for(sid, r"^GAME OK")+ async with Browser(args.build, width=web_check.VIEWPORT[0], height=web_check.VIEWPORT[1],+ viewport=web_check.VIEWPORT, keep_awake=True) as b:+ sid = await b.open("bootlog", args.cpu, init_script=FIRST_FRAME_SCRIPT)+ await b.wait_for(sid, r"^GAME OK", stall=args.stall)origin = (await b.send("Runtime.evaluate", {"expression": "performance.timeOrigin", "returnByValue": True}, session=sid))["result"]["value"]+ first = None+ for _ in range(300):+ first = (await b.send("Runtime.evaluate", {"expression": "window.__scFirstFrame", "returnByValue": True}, session=sid))["result"].get("value")+ if first:+ break+ await asyncio.sleep(0.1)+ if not first:+ raise RuntimeError("no first frame after GAME OK (the console hook did not fire)")print(f"CPU {args.cpu}x, run {run + 1} of {args.runs}")for s, text, ts in b.console:if s == sid and (text.startswith("BOOT") or text.startswith("GAME OK")):print(f"{ts - origin:8.0f} ms {text[:140]}")span = map_build_ms(boot_phases(b.lines(sid)))- print(f"BOOT map build {span} ms")- spans.append(span)- median, over = over_budget(spans, args.baseline, args.budget)- print(f"BOOT map_build_ms median={median:.0f} runs={len(spans)}")- if over:- print(f"OVER BUDGET: {median:.0f} ms > baseline {args.baseline:.0f} + {args.budget:.0f} ms")- return 1 if over else 0+ print(f"BOOT map build {span} ms, first frame {first:.0f} ms")+ builds.append(span)+ firsts.append(round(first))+ code = 0+ for name, spans, baseline in (("map_build_ms", builds, args.baseline), ("first_frame_ms", firsts, args.baseline_first_frame)):+ median, over = over_budget(spans, baseline, args.budget)+ print(f"BOOT {name} median={median:.0f} runs={len(spans)} cpu={args.cpu:g}")+ if over:+ print(f"OVER BUDGET: {name} {median:.0f} ms > baseline {baseline:.0f} + {allowed_growth(baseline, args.budget):.0f} ms")+ code = 1+ return codeasync def profile(args):- """?vprofile (visual v1) in a headed 1920x1080 window at --dpr, frame rate uncapped; prints the PROFILE lines."""- async with Browser(args.build, width=1920, height=1080, dpr=args.dpr, uncapped=True) as b:+ """?vprofile (visual v1) in a headed, kept-awake window with a 1920x1080 viewport at --dpr, frame rate uncapped;+ prints the PROFILE lines. 1 when a line is missing, a run is at another res= (ruling 1), or the page stalls."""+ async with Browser(args.build, width=1920, height=1080, dpr=args.dpr, uncapped=True,+ viewport=web_check.VIEWPORT, keep_awake=True) as b:sid = await b.open("vprofile", args.cpu)- await b.wait_for(sid, r"^PROFILE visual done", timeout=args.timeout)- for line in b.lines(sid):+ try:+ await b.wait_for(sid, r"^PROFILE visual done", timeout=args.timeout, stall=args.stall)+ except TimeoutError as e:+ print(f"FAIL: {e}")+ lines = b.lines(sid)+ for line in lines:if line.startswith("PROFILE"):print(line)- return 0+ errors = web_check.profile_errors(lines, web_check.expected_res(*web_check.VIEWPORT, args.dpr))+ for e in errors:+ print(f"FAIL: {e}")+ return 1 if errors else 0async def navpairs(args):@@ -261,7 +323,9 @@ def main(argv=None):p.add_argument("--out", default="headed", help="screenshot path prefix (loadshot)")p.add_argument("--runs", type=int, default=1, help="boot: cold loads to take the median of")p.add_argument("--baseline", type=float, help="boot: exit 1 when the median map-build span exceeds this + --budget (ms)")- p.add_argument("--budget", type=float, default=1000, help="boot: allowed growth over --baseline (ms)")+ p.add_argument("--baseline-first-frame", type=float, help="boot: the same for the first-frame span (ms)")+ p.add_argument("--budget", type=float, help="boot: allowed growth over each baseline (ms; default max(300, 50%%))")+ p.add_argument("--stall", type=float, default=120, help="boot, profile: fail after this many seconds with no console line")p.add_argument("--dpr", type=float, default=1.0, help="profile: device pixel ratio (2 = the fill-rate stress proxy)")p.add_argument("--timeout", type=float, default=1800, help="profile: seconds to wait for PROFILE visual done")args = p.parse_args(argv)diff --git a/tools/tests/test_headed.py b/tools/tests/test_headed.pyindex d2c1b5a6a..550a889ca 100644--- a/tools/tests/test_headed.py+++ b/tools/tests/test_headed.py@@ -50,3 +50,48 @@ def test_profile_windows_are_uncapped_at_the_requested_dpr():for flag in ("--force-device-scale-factor=2", "--disable-frame-rate-limit", "--disable-gpu-vsync", "--window-size=1920,1080"):assert flag in profassert prof[-1] == "about:blank"+++def test_the_default_boot_budget_is_300_ms_or_half_the_baseline():+ """Ruling 3: baseline + max(300 ms, 50%) unless --budget is given."""+ assert headed.over_budget([740], 450, None) == (740, False) # 450 + 300+ assert headed.over_budget([760], 450, None) == (760, True)+ assert headed.over_budget([1490], 1000, None) == (1490, False) # 1000 + 500+ assert headed.over_budget([1510], 1000, None) == (1510, True)+++def test_measurement_windows_are_kept_awake_and_navpairs_keeps_its_flags():+ awake = headed.browser_flags("/tmp/p", 1920, 1080, keep_awake=True)+ for flag in ("--disable-backgrounding-occluded-windows", "--disable-renderer-backgrounding",+ "--disable-background-timer-throttling"):+ assert flag in awake+ assert flag not in headed.browser_flags("/tmp/p", 1568, 752)+ assert awake[-1] == "about:blank"+++def test_the_viewport_is_set_before_the_page_loads(tmp_path):+ """Ruling 1: Emulation.setDeviceMetricsOverride (1920x1080 at the DPR, not mobile) precedes Page.navigate."""+ b = headed.Browser(tmp_path, viewport=(1920, 1080), dpr=2)+ sent = []++ async def send(method, params=None, session=None, timeout=60):+ sent.append((method, params))+ return {"targetId": "t", "sessionId": "s"}+ b.send, b.base = send, "http://localhost/"+ asyncio.run(b.open("vprofile", init_script="window.x = 1"))+ methods = [m for m, _ in sent]+ assert methods.index("Emulation.setDeviceMetricsOverride") < methods.index("Page.navigate")+ assert methods.index("Page.addScriptToEvaluateOnNewDocument") < methods.index("Page.navigate")+ assert dict(sent)["Emulation.setDeviceMetricsOverride"] == {"width": 1920, "height": 1080, "deviceScaleFactor": 2, "mobile": False}+ plain = headed.Browser(tmp_path)+ plain_sent = []++ async def send2(method, params=None, session=None, timeout=60):+ plain_sent.append(method)+ return {"targetId": "t", "sessionId": "s"}+ plain.send, plain.base = send2, "http://localhost/"+ asyncio.run(plain.open("navlog"))+ assert "Emulation.setDeviceMetricsOverride" not in plain_sent # navpairs and loadshot keep the window's size+ import shutil+ for browser in (b, plain):+ shutil.rmtree(browser.profile, ignore_errors=True)diff --git a/tools/tests/test_web_check_shots.py b/tools/tests/test_web_check_shots.pyindex 7f46f9ba8..2ec13baa1 100644--- a/tools/tests/test_web_check_shots.py+++ b/tools/tests/test_web_check_shots.py@@ -61,3 +61,66 @@ def test_headless_chrome_runs_uncapped_at_dpr_1():"--user-data-dir=/tmp/p", "--force-device-scale-factor=1"):assert flag in flagsassert "--use-angle=swiftshader" in wc.chrome_flags("/tmp/p", swiftshader=True)+++def png_of_size(w: int, h: int) -> bytes:+ import io+ from PIL import Image+ buf = io.BytesIO()+ Image.new("RGB", (w, h), (10, 20, 30)).save(buf, "PNG")+ return buf.getvalue()+++def test_a_shot_of_the_wrong_size_fails(tmp_path):+ """Ruling 1: screenshots are 1920x1080; the 1920x937 headless viewport must fail, not pass silently."""+ c = wc.ShotCollector(tmp_path, size=(1920, 1080))+ with pytest.raises(ValueError, match="1920x937.*1920x1080"):+ for line in shot_lines("gameplay03", png_of_size(1920, 937), chunk=4000):+ c.feed(line)+ ok = wc.ShotCollector(tmp_path, size=(64, 36))+ assert all(ok.feed(line) for line in shot_lines("diorama02", png_of_size(64, 36), chunk=4000))++[email protected]("bad", ["SHOT gameplay03 0/3 AAAA", "SHOT gameplay03 4/3 AAAA", "SHOT gameplay03 1/2 AAAA"])+def test_a_part_that_does_not_fit_its_begin_line_is_a_value_error(tmp_path, bad):+ """Review M1: out-of-range or mismatched part numbers fail as FAIL (ValueError), never as a KeyError traceback."""+ c = wc.ShotCollector(tmp_path)+ c.feed("SHOT gameplay03 begin 3 " + "0" * 64)+ with pytest.raises(ValueError, match="does not fit"):+ c.feed(bad)+++def test_the_viewport_is_fixed_over_cdp_at_the_dpr():+ assert wc.viewport_override(1920, 1080, 2) == {"width": 1920, "height": 1080, "deviceScaleFactor": 2, "mobile": False}+ assert wc.expected_res(1920, 1080, 1) == "1920x1080" and wc.expected_res(1920, 1080, 2) == "3840x2160"+++def test_a_profile_line_at_another_resolution_is_an_error():+ good = "PROFILE visual=all pose=gameplay03 res=1920x1080 scale=0.80 rep=0 frames=300 avg_ms=1.73 p95_ms=2.00"+ assert wc.res_error(good, "1920x1080") is None+ assert wc.res_error("GAME OK 1948-05-15 turn 0 hash 00", "1920x1080") is None+ assert "1920x937" in wc.res_error(good.replace("1920x1080", "1920x937"), "1920x1080")+++def test_profile_errors_need_run_lines_the_right_size_and_the_done_line():+ run = "PROFILE visual=all pose=gameplay03 res=1920x1080 scale=0.80 rep=0 frames=300 avg_ms=1.73 p95_ms=2.00"+ assert wc.profile_errors([run, "PROFILE visual done"], "1920x1080") == []+ assert wc.profile_errors(["GAME OK"], "1920x1080") # no PROFILE lines at all+ assert wc.profile_errors([run], "1920x1080") # never finished+ assert wc.profile_errors([run.replace("1920x1080", "1728x860"), "PROFILE visual done"], "1920x1080")+++def test_measurement_windows_are_kept_awake():+ flags = wc.chrome_flags("/tmp/p", swiftshader=False)+ for flag in ("--disable-backgrounding-occluded-windows", "--disable-renderer-backgrounding",+ "--disable-background-timer-throttling", "--remote-debugging-port=0"):+ assert flag in flags+ assert "--force-device-scale-factor=2" in wc.chrome_flags("/tmp/p", swiftshader=False, dpr=2)+++def test_a_silent_browser_stalls_out_before_the_timeout(capsys):+ import queue+ clock = iter(range(0, 10000, 10))+ code = wc.watch(queue.Queue(), lambda: None, lambda: None, ["PROFILE visual done"], wc.re.compile("FAIL"), 3600,+ now=lambda: next(clock), sleep=lambda s: None, stall=120)+ assert code == 1 and "STALLED" in capsys.readouterr().outdiff --git a/tools/web_check.py b/tools/web_check.pyindex 8eba52afc..42a602346 100644--- a/tools/web_check.py+++ b/tools/web_check.py@@ -1,6 +1,6 @@# /// script# requires-python = ">=3.11"-# dependencies = []+# dependencies = ["websockets==15.0.1"]# ///"""Serve a Unity WebGL build on http://localhost and open it in Chrome; pass when the console shows every expected line,fail on a failure line or a timeout. Uses Chrome for Testing from the Playwright cache (macOS only, no npm needed) in@@ -10,16 +10,21 @@ fail on a failure line or a timeout. Uses Chrome for Testing from the PlaywrightUsage (from the repo root):uv run tools/web_check.py unity/Builds/Web-disabled --query "golden" --expect "GOLDEN OK 1950 71e9904d0ee48083db9bbba281f3f046136482ba83ee056e48d57b62e76a5b07" --expect "GOLDEN OK 1952 73590e324f19e9959a455a4da79e93d7089dfcf283c13aac02af6b0a624b9767"Options: --query Q (page URL query, without '?'), --expect TEXT (repeatable), --fail REGEX (default: GOLDEN FAIL|SMOKE FAIL|BOOT FAIL),---timeout SECONDS (default 300), --swiftshader (software WebGL when there is no GPU), --shots DIR (reassemble the player's-"SHOT" console lines, from ?shot, into DIR/<pose>.png; a "SHOT done" with an unfinished shot fails the run). Chrome runs at-device pixel ratio 1. Headed runs (a visible window, another DPR) go through tools/headed.py.+--timeout SECONDS (default 300), --stall SECONDS (fail when no console message arrives for that long; 0 = off),+--swiftshader (software WebGL when there is no GPU), --dpr N (default 1), --shots DIR (reassemble the player's+"SHOT" console lines, from ?shot, into DIR/<pose>.png; a "SHOT done" with an unfinished shot fails the run).+The page is opened over the DevTools protocol with its viewport fixed to 1920x1080 at the DPR before it loads+(Emulation.setDeviceMetricsOverride: --window-size alone gives a 1920x937 viewport in --headless=new), and the run+fails on any "res=" line, or any screenshot, of another size. Headed runs go through tools/headed.py.Pre-compressed builds: *.br and *.gz files are served with Content-Encoding, *.wasm(.br/.gz) as application/wasm.Brotli needs a secure context; http://localhost is one."""import argparse+import asyncioimport base64import functoolsimport hashlibimport http.server+import jsonimport osimport reimport subprocess@@ -37,6 +42,38 @@ CONSOLE = re.compile(r'INFO:CONSOLE[^\]]*\] "(.*?)(?:", source: .*)?$')CHROME_GLOB = "ms-playwright/chromium-*/chrome-mac*/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing"SHOT_BEGIN = re.compile(r"^SHOT (\S+) begin (\d+) ([0-9a-f]{64})$")SHOT_PART = re.compile(r"^SHOT (\S+) (\d+)/(\d+) (\S+)$")+VIEWPORT = (1920, 1080)+# A background or occluded window is throttled (no frames, slow timers): measurement windows stay awake (review ruling 2).+KEEP_AWAKE = ["--disable-backgrounding-occluded-windows", "--disable-renderer-backgrounding",+ "--disable-background-timer-throttling"]+RES = re.compile(r"\bres=(\d+x\d+)\b")+++def viewport_override(width: int, height: int, dpr: float) -> dict:+ """Emulation.setDeviceMetricsOverride parameters: exactly width x height CSS pixels at dpr, desktop (review ruling 1)."""+ return {"width": width, "height": height, "deviceScaleFactor": dpr, "mobile": False}+++def expected_res(width: int, height: int, dpr: float) -> str:+ """The player's Screen size for a width x height viewport at dpr (Unity renders at the browser's DPR)."""+ return f"{round(width * dpr)}x{round(height * dpr)}"+++def res_error(text: str, expected: str) -> str | None:+ """An error when a console line states a res= other than expected; None otherwise."""+ m = RES.search(text)+ return None if m is None or m.group(1) == expected else f"res={m.group(1)}, expected res={expected}: {text}"+++def profile_errors(lines, expected: str) -> list[str]:+ """What is wrong with a ?vprofile run's console lines: no PROFILE run lines, a run at another size, no done line."""+ runs = [l for l in lines if l.startswith("PROFILE visual=")]+ errors = [e for e in (res_error(l, expected) for l in runs) if e]+ if not runs:+ errors.append("no PROFILE visual= lines")+ if "PROFILE visual done" not in lines:+ errors.append("no 'PROFILE visual done' line")+ return errorsclass Handler(http.server.SimpleHTTPRequestHandler):@@ -69,8 +106,8 @@ class ShotCollector:"SHOT <pose> <i>/<n> <base64>" (any order). A finished shot is checked against its SHA-256 and written to<out_dir>/<pose>.png (out_dir None: checked, not written)."""- def __init__(self, out_dir: Path | None):- self.out_dir = out_dir+ def __init__(self, out_dir: Path | None, size: tuple[int, int] | None = None):+ self.out_dir, self.size = out_dir, sizeself.expect: dict[str, tuple[int, str]] = {}self.parts: dict[str, dict[int, str]] = {}self.written: list[Path] = []@@ -83,6 +120,8 @@ class ShotCollector:raise ValueError(f"SHOT done with unfinished shots ({unfinished})")m = SHOT_BEGIN.match(text)if m:+ if int(m.group(2)) < 1:+ raise ValueError(f"SHOT {m.group(1)}: a begin line with no parts")self.expect[m.group(1)] = (int(m.group(2)), m.group(3))self.parts[m.group(1)] = {}return True@@ -92,6 +131,9 @@ class ShotCollector:name, i = m.group(1), int(m.group(2))if name not in self.expect:raise ValueError(f"SHOT {name}: part {i}/{m.group(3)} before its begin line")+ n = self.expect[name][0]+ if int(m.group(3)) != n or not 1 <= i <= n:+ raise ValueError(f"SHOT {name}: part {i}/{m.group(3)} does not fit its begin line ({n} parts)")self.parts[name][i] = m.group(4)if len(self.parts[name]) == self.expect[name][0]:self._finish(name)@@ -106,6 +148,10 @@ class ShotCollector:png = b""if hashlib.sha256(png).hexdigest() != digest:raise ValueError(f"SHOT {name}: SHA-256 mismatch (a console line was cut or lost)")+ if self.size is not None:+ w, h = int.from_bytes(png[16:20], "big"), int.from_bytes(png[20:24], "big")+ if (w, h) != self.size:+ raise ValueError(f"SHOT {name}: {w}x{h}, expected {self.size[0]}x{self.size[1]}")if self.out_dir is not None:self.out_dir.mkdir(parents=True, exist_ok=True)path = self.out_dir / f"{name}.png"@@ -127,16 +173,77 @@ def find_chrome() -> Path:return max(found, key=revision)-def chrome_flags(profile: str, swiftshader: bool) -> list[str]:- """Headless Chrome at device pixel ratio 1, frame rate uncapped (so frame times are not the display's)."""+def chrome_flags(profile: str, swiftshader: bool, dpr: float = 1.0) -> list[str]:+ """Headless Chrome at the device pixel ratio (1 unless asked), frame rate uncapped (so frame times are not the+ display's), never throttled, with a DevTools port for the viewport override."""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", "--force-device-scale-factor=1",- "--disable-frame-rate-limit", "--disable-gpu-vsync", f"--user-data-dir={profile}"]+ "--autoplay-policy=no-user-gesture-required", "--window-size=1920,1080", f"--force-device-scale-factor={dpr:g}",+ "--disable-frame-rate-limit", "--disable-gpu-vsync", *KEEP_AWAKE, "--remote-debugging-port=0",+ f"--user-data-dir={profile}"]if swiftshader:flags += ["--use-angle=swiftshader", "--enable-unsafe-swiftshader"]return flags+class Page:+ """Opens url in a new tab of the Chrome using `profile`, over the DevTools protocol, with the viewport fixed before+ the first load; the connection (and with it the override) is held on a background thread until close()."""++ def __init__(self, profile: str, url: str, width: int, height: int, dpr: float):+ self.profile, self.url, self.metrics = profile, url, viewport_override(width, height, dpr)+ self.ready, self.stop = threading.Event(), threading.Event()+ self.error: BaseException | None = None+ self.thread = threading.Thread(target=lambda: asyncio.run(self._run()), daemon=True)++ def open(self, timeout: float = 60) -> None:+ self.thread.start()+ if not self.ready.wait(timeout):+ raise ValueError(f"could not open the page over the DevTools protocol within {timeout:.0f} s")+ if self.error is not None:+ raise ValueError(f"could not open the page over the DevTools protocol: {self.error}")++ def close(self) -> None:+ self.stop.set()+ self.thread.join(5)++ async def _run(self) -> None:+ try:+ import websockets # lazy: the unit tests do not install it+ port_file = Path(self.profile) / "DevToolsActivePort"+ for _ in range(600):+ if port_file.exists() and len(port_file.read_text().split()) >= 2:+ break+ await asyncio.sleep(0.1)+ port, path = port_file.read_text().split()[:2]+ async with websockets.connect(f"ws://127.0.0.1:{port}{path}", max_size=None) as ws:+ ids = iter(range(1, 1 << 30))++ async def call(method: str, params: dict | None = None, session: str | None = None) -> dict:+ n = next(ids)+ await ws.send(json.dumps({"id": n, "method": method, "params": params or {},+ **({"sessionId": session} if session else {})}))+ while True:+ r = json.loads(await ws.recv())+ if r.get("id") == n:+ if "error" in r:+ raise RuntimeError(f"{method}: {r['error']}")+ return r.get("result", {})+ target = (await call("Target.createTarget", {"url": "about:blank"}))["targetId"]+ sid = (await call("Target.attachToTarget", {"targetId": target, "flatten": True}))["sessionId"]+ await call("Emulation.setDeviceMetricsOverride", self.metrics, sid)+ await call("Page.navigate", {"url": self.url}, sid)+ self.ready.set()+ while not self.stop.is_set():+ try:+ await asyncio.wait_for(ws.recv(), 0.5)+ except asyncio.TimeoutError:+ pass+ except Exception as e: # reported by open(); after it, the browser closing ends the thread+ if not self.ready.is_set():+ self.error = e+ self.ready.set()++def serve(root: Path) -> http.server.ThreadingHTTPServer:server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), functools.partial(Handler, directory=str(root)))threading.Thread(target=server.serve_forever, daemon=True).start()@@ -168,15 +275,19 @@ def drain(inbox: queue.Queue) -> list:return batch-def watch(inbox, poll, join_reader, expect, fail, timeout, now=time.time, sleep=time.sleep, on_text=None) -> int:- """The check loop: 0 on PASS, 1 on a failure line, on BROWSER EXITED or on TIMEOUT. poll() is the browser's- returncode (None while running); join_reader() waits briefly for the stderr reader thread to hit EOF, so output- written just before the exit is still scanned. on_text(text) -> True consumes a message (it is not printed)."""+def watch(inbox, poll, join_reader, expect, fail, timeout, now=time.time, sleep=time.sleep, on_text=None, stall=0) -> int:+ """The check loop: 0 on PASS, 1 on a failure line, on BROWSER EXITED, on TIMEOUT, or (stall > 0) when no console+ message arrives for stall seconds (STALLED). poll() is the browser's returncode (None while running); join_reader()+ waits briefly for the stderr reader thread to hit EOF, so output written just before the exit is still scanned.+ on_text(text) -> True consumes a message (it is not printed)."""pending, deadline = list(expect), now() + timeout+ last = now()def look():- nonlocal pending+ nonlocal pending, laststatus, pending, texts = scan(drain(inbox), pending, fail)+ if texts:+ last = now()for t in texts:if on_text is not None and on_text(t):continue@@ -201,6 +312,9 @@ def watch(inbox, poll, join_reader, expect, fail, timeout, now=time.time, sleep=return resultprint(f"BROWSER EXITED code {code}; never saw " + ", ".join(pending))return 1+ if stall and now() - last > stall:+ print(f"STALLED: no console message for {stall:.0f} s; never saw " + ", ".join(pending))+ return 1sleep(0.2)print("TIMEOUT: never saw " + ", ".join(pending))return 1@@ -215,26 +329,42 @@ def main() -> int:ap.add_argument("--timeout", type=float, default=300)ap.add_argument("--swiftshader", action="store_true")ap.add_argument("--shots", type=Path)+ ap.add_argument("--dpr", type=float, default=1.0)+ ap.add_argument("--stall", type=float, default=0)a = ap.parse_args()if not (a.build / "index.html").exists():sys.exit(f"{a.build}/index.html not found")- server, proc, profile = None, None, tempfile.mkdtemp(prefix="web-check-")- shots = ShotCollector(a.shots)+ server, proc, page, profile = None, None, None, tempfile.mkdtemp(prefix="web-check-")+ w, h = VIEWPORT+ res = expected_res(w, h, a.dpr)+ shots = ShotCollector(a.shots, size=(round(w * a.dpr), round(h * a.dpr)))++ def on_text(text: str) -> bool:+ err = res_error(text, res)+ if err:+ raise ValueError(err)+ return shots.feed(text)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 "")- proc = subprocess.Popen([str(chrome), *chrome_flags(profile, a.swiftshader), url],+ proc = subprocess.Popen([str(chrome), *chrome_flags(profile, a.swiftshader, a.dpr), "about:blank"],stderr=subprocess.PIPE, stdout=subprocess.DEVNULL, text=True, errors="replace")inbox: queue.Queue = queue.Queue()reader = threading.Thread(target=lambda: [inbox.put(l) for l in iter(proc.stderr.readline, "")], daemon=True)reader.start()try:- return watch(inbox, proc.poll, lambda: reader.join(2), list(a.expect), re.compile(a.fail), a.timeout, on_text=shots.feed)+ page = Page(profile, url, w, h, a.dpr)+ page.open()+ print(f"viewport {w}x{h} at DPR {a.dpr:g} (expect res={res})")+ return watch(inbox, proc.poll, lambda: reader.join(2), list(a.expect), re.compile(a.fail), a.timeout,+ on_text=on_text, stall=a.stall)except ValueError as e:print(f"FAIL: {e}")return 1finally:+ if page is not None:+ page.close()if proc is not None:proc.terminate()try: