"""tools/game_gate.py on synthetic run folders: every log line below is made up by the test, in the runtime's formats (no game data). The contract test checks that those formats are still in the runtime's source.""" import contextlib import csv import datetime as dt import io import json import os import re import shutil import subprocess import sys import tempfile import unittest ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, os.path.join(ROOT, "tools")) import game_gate # noqa: E402 START = dt.datetime(2026, 11, 30, 18, 0, 0, tzinfo=dt.timezone.utc) def stamp(seconds): return (START + dt.timedelta(seconds=seconds)).strftime("%Y-%m-%dT%H:%M:%S.%f") + "Z" def frame_line(t, fps, draws, making=0, dropped=0): return (f"{stamp(t)} INFO leonida_gpu::host: {fps:.1f} fps, {1000.0 / fps:.1f} ms/frame (1.0 preparing: copies 0.1 ms " f"0.1 MB, textures 0.1 ms 0.1 MB; 5.0 on the GPU; 0.0 copying back 0.0 MB), {draws} draws/frame, dropped " f"{dropped} without a host pipeline ({making} being made) and 0 indirect, of both per frame: none") class Fake: """A run folder written line by line.""" def __init__(self, world_seconds=300): self.dir = tempfile.mkdtemp(prefix="gate-test-") self.log, self.launcher, self.events, self.crashes = [], [], [], [] self.meta = {"name": "t", "started_utc": stamp(0), "commit": "abc1234", "dirty": False, "exe_sha16": "0" * 16, "gpu": "Test GPU", "driver": "1.0", "play_args": "-SeriesS", "world_seconds": world_seconds} def event(self, t, name, **more): self.events.append(dict(t=stamp(t), event=name, **more)) def frames(self, start, end, fps, draws, making=0, dropped=0, step=1.0, presents=True): t = start while t < end: self.log.append(frame_line(t, fps, draws, making, dropped)) t += step if presents: t, gap = start, 1.0 / fps while t < end: self.log.append(f"{stamp(t)} DEBUG leonida_gpu::frame: present token=1") t += gap def memory(self, t, private, used, budget=8000, left=3000, shared=500, waiting=0, reaper=0): """The runtime's video memory line, census line and memory line, as a diagnostics build writes them every 5 s.""" self.log.append(f"{stamp(t)} INFO leonida_gpu::census: memory, what waits to be let go: {waiting} objects let " f"go that wait for the submissions that may use them (LEONIDA_BURY_LAG), {reaper} retired " f"objects, landed host lists and lists' fronts handed to the thread that lets them go and not " f"let go yet (LEONIDA_REAPER=0: let go by the submitting thread); 0 let go by the thread done " f"with them instead, since the start, the reaper thread's line holding LEONIDA_REAPER_LIMIT=0 or " f"more (0: no bound)") self.log.append(f"{stamp(t)} INFO leonida_gpu::host: video memory as the system counts it, with the memory " f"line: the card's own: budget {budget} MB, in use {used} MB, 100 MB could still be reserved, " f"0 MB reserved; the PC's shared with the card: budget 16000 MB, in use {shared} MB, 0 MB could " f"still be reserved, 0 MB reserved (the layer reserves none)") self.log.append(f"{stamp(t)} INFO leonida_gpu::copystat: memory: {private} MB private ({private // 2} MB of it " f"in memory; the PC has 15000 MB free and {left} MB left to commit); host copies of title " f"memory: 1 alive 1 MB, of them 0 windows outside buffers 0 MB") def clean_stop(self, t, exit_code=0): self.event(t, "stop_requested", reason="target") self.log.append(f"{stamp(t + 0.1)} INFO leonida_hle::modules::lifecycle: window closed: suspending the title constrained=0 routines=1") self.log.append(f"{stamp(t + 0.3)} INFO leonida_hle::modules::lifecycle: title suspended; ending the title") self.event(t + 0.5, "game_exited", exit_code=exit_code) def state(self): """What the supervisor reads during the run (`game_gate.py state`).""" self.summarize() return game_gate.state(game_gate.Run(self.dir)) def summarize(self): self.log.sort(key=lambda l: l[:27]) files = {"run.json": json.dumps(self.meta), "leonida.log": "\n".join(self.log) + "\n", "launcher.txt": "\n".join(self.launcher) + "\n", "events.jsonl": "".join(json.dumps(e) + "\n" for e in self.events)} for name, text in files.items(): with open(os.path.join(self.dir, name), "w", encoding="utf-8") as f: f.write(text) if self.crashes: os.makedirs(os.path.join(self.dir, "data", "TITLE"), exist_ok=True) with open(os.path.join(self.dir, "data", "TITLE", "crashes.log"), "w", encoding="utf-8") as f: f.write("\n".join(self.crashes) + "\n") return game_gate.summary(game_gate.Run(self.dir)) def passing(world_seconds=300): f = Fake(world_seconds) f.event(1, "game", pid=1) f.frames(10, 70, 60.0, 13) # menus: few draws f.frames(70, 70 + 320, 50.0, 4000) # the world f.clean_stop(70 + 320) return f class Verdicts(unittest.TestCase): def test_a_clean_run_in_the_world_passes(self): f = passing() f.meta["untracked"] = 2 s = f.summarize() self.assertEqual((s["run"]["dirty"], s["run"]["untracked"]), (False, 2)) self.assertEqual(s["verdict"]["result"], "PASS", s["verdict"]) self.assertAlmostEqual(s["times"]["world_at_s"], 70.0, places=3) self.assertGreaterEqual(s["times"]["world_s"], 300) self.assertEqual(s["fps"]["source"], "presents") self.assertAlmostEqual(s["fps"]["median"], 50.0, delta=0.5) self.assertEqual(s["exit"], {"code_hex": "0x00000000", "kind": "clean"}) self.assertEqual(s["stop"]["cache_saved"], True) self.assertEqual(s["crash"]["kind"], "none") def test_a_lost_device_fails_by_its_exit_code_and_its_report(self): f = Fake() f.event(1, "game", pid=1) f.frames(10, 200, 50.0, 4000) f.log.append("host GPU failure: the card was removed") f.crashes.append("Leonida: host GPU failure: the card was removed") f.event(201, "game_exited", exit_code=0x887A0005) s = f.summarize() self.assertEqual(s["verdict"]["result"], "FAIL") self.assertIn("device_lost", s["verdict"]["reasons"]) self.assertEqual(s["exit"]["kind"], "device_lost") self.assertEqual(s["crash"]["kind"], "device_lost") def test_an_out_of_memory_list_close_counts_as_a_lost_device(self): f = passing() f.log.append(f"{stamp(200)} ERROR leonida_gpu::host: a host command list did not close (0x8007000E): " "a command recorded into it was invalid") self.assertIn("device_lost", f.summarize()["verdict"]["reasons"]) def test_a_panic_fails_even_with_the_title_alive(self): f = passing() f.log.append(f"{stamp(150)} INFO leonida_gpu::host: before") f.log.append("thread 'leonida-records' (4242) panicked at crates\\leonida-gpu\\src\\land.rs:1:1:") s = f.summarize() self.assertEqual(s["verdict"]["result"], "FAIL") self.assertIn("panic", s["verdict"]["reasons"]) def test_menus_only_is_an_error_not_a_pass(self): f = Fake() f.event(1, "game", pid=1) f.frames(10, 400, 60.0, 13) f.event(400, "stop_requested", reason="timeout") f.event(401, "game_exited", exit_code=0) s = f.summarize() self.assertEqual(s["verdict"]["result"], "ERROR") self.assertIn("world_not_reached", s["verdict"]["reasons"]) self.assertIsNone(s["times"]["world_at_s"]) def test_a_stop_file_before_the_world_time_is_an_error(self): f = Fake() f.event(1, "game", pid=1) f.frames(70, 320, 50.0, 4000) f.event(320, "stop_requested", reason="stop_file") f.event(321, "game_exited", exit_code=0) s = f.summarize() self.assertEqual(s["verdict"]["result"], "ERROR") self.assertIn("stopped_early", s["verdict"]["reasons"]) def test_too_little_world_time_at_the_time_limit_fails(self): f = Fake() f.event(1, "game", pid=1) f.frames(70, 320, 50.0, 4000) f.event(320, "stop_requested", reason="timeout") f.event(321, "game_exited", exit_code=0) s = f.summarize() self.assertEqual(s["verdict"]["result"], "FAIL") self.assertIn("world_time_short", s["verdict"]["reasons"]) def test_a_run_frozen_on_a_compile_fails_though_alive(self): f = Fake() f.event(1, "game", pid=1) f.frames(70, 200, 50.0, 4000) f.frames(200, 400, 0.5, 4000, making=1, presents=False) # frame lines go on, no frame is shown f.clean_stop(400) s = f.summarize() self.assertEqual(s["verdict"]["result"], "FAIL") self.assertIn("present_gap", s["verdict"]["reasons"]) self.assertGreater(s["fps"]["longest_present_gap_s"], 150) def test_dying_before_the_stop_fails(self): f = Fake() f.event(1, "game", pid=1) f.frames(70, 250, 50.0, 4000) f.event(250, "game_exited", exit_code=1) self.assertIn("exited_before_stop", f.summarize()["verdict"]["reasons"]) class Measures(unittest.TestCase): def test_the_cache_is_warm_after_a_quiet_minute(self): f = Fake() f.event(1, "game", pid=1) f.frames(70, 130, 40.0, 4000, making=3) # Draws dropped for pipelines the host never has go on all along: the cache is warm all the same. f.frames(130, 420, 50.0, 4000, dropped=240) f.clean_stop(420) s = f.summarize() self.assertAlmostEqual(s["times"]["warm_at_s"], 130.0, places=3) self.assertEqual(s["pipelines"]["making_max"], 3) def test_percentiles_come_from_the_presents(self): f = Fake() f.event(1, "game", pid=1) f.frames(70, 70 + 60, 50.0, 4000) f.frames(130, 430, 25.0, 4000) f.clean_stop(430) s = f.summarize() self.assertAlmostEqual(s["fps"]["median"], 25.0, delta=0.3) self.assertAlmostEqual(s["fps"]["frame_p95_ms"], 40.0, delta=0.5) self.assertAlmostEqual(s["fps"]["end_median"], 25.0, delta=0.3) self.assertIsNone(s["fps"]["under_2_at_s"]) def test_a_dip_on_arrival_is_not_the_first_second_under_2(self): # One frame a second just after the world (streaming in), then steady, then a dip later on: under_2_at_s # counts from 60 s in the world, like the median, and finds the later dip. f = Fake() f.event(1, "game", pid=1) f.frames(70, 75, 1.0, 4000) f.frames(75, 300, 30.0, 4000) f.frames(300, 305, 1.0, 4000) f.frames(305, 420, 30.0, 4000) f.clean_stop(420) s = f.summarize() self.assertAlmostEqual(s["times"]["world_at_s"], 70.0, places=3) self.assertEqual(s["fps"]["under_2_at_s"], 300.0) self.assertEqual(s["verdict"]["result"], "PASS", s["verdict"]) def test_memory_peaks_come_from_the_runtimes_memory_lines(self): f = passing() for i, t in enumerate(range(70, 390, 5)): # Private bytes grow, the PC's commit left shrinks, the card goes over its budget from 200 s on. f.memory(t, 20000 + 10 * i, 7000 if t < 200 else 9000, left=3000 - i, shared=500 + i) m = f.summarize()["memory"] self.assertEqual((m["source"], m["lines"]), ("memory lines", 64)) self.assertEqual((m["private_max_mb"], m["private_max_at_s"]), (20630, 385.0)) self.assertEqual(m["in_memory_max_mb"], 10315) self.assertEqual((m["pc_commit_left_min_mb"], m["pc_commit_left_min_at_s"]), (2937, 385.0)) self.assertEqual((m["vram_in_use_max_mb"], m["vram_max_at_s"], m["vram_budget_at_max_mb"]), (9000, 200.0, 8000)) self.assertEqual(m["vram_over_budget_s"], 185.0) self.assertEqual(m["shared_in_use_max_mb"], 563) def memory_run(self, limits, rows): """A run in the world with memory lines every 5 s from 70 s: rows of (private, video in use, PC left).""" f = Fake() f.meta["memory_stop"] = limits f.event(1, "game", pid=1) f.frames(10, 70, 60.0, 13) f.frames(70, 70 + 5 * len(rows), 30.0, 4000) for i, (private, used, left) in enumerate(rows): f.memory(70 + 5 * i, private, used, budget=8000, left=left) return f def test_the_memory_stop_asks_for_a_stop_past_each_limit(self): limits = {"private_max_mb": 30000, "commit_left_min_mb": 200, "over_budget_s": 60} calm = [(24000, 7000, 3000)] * 10 cases = { "private bytes 31000 MB, over 30000 MB": calm + [(31000, 7000, 3000)], "the PC had under 200 MB left to commit for 25 s": calm + [(24000, 7000, 150)] * 6, # Exactly 20 s under the floor (five lines 5 s apart) is enough: the floor's boundary, as 60 s is the # video memory's. "the PC had under 200 MB left to commit for 20 s": calm + [(24000, 7000, 150)] * 5, "video memory over its budget for 60 s": calm + [(24000, 9000, 3000)] * 13, } for why, rows in cases.items(): self.assertEqual(self.memory_run(limits, rows).state()["memory_stop"], why) # Under each limit, at the private limit itself, or not for long enough: no stop. for rows in (calm, calm + [(30000, 7000, 3000)], calm + [(24000, 7000, 150)] * 4, calm + [(24000, 9000, 3000)] * 12): self.assertIsNone(self.memory_run(limits, rows).state()["memory_stop"]) # 0 turns a limit off, and a run.json without limits (an older gate) never stops for memory. off = {"private_max_mb": 0, "commit_left_min_mb": 0, "over_budget_s": 0} self.assertIsNone(self.memory_run(off, cases["private bytes 31000 MB, over 30000 MB"]).state()["memory_stop"]) self.assertIsNone(self.memory_run(None, cases["private bytes 31000 MB, over 30000 MB"]).state()["memory_stop"]) # A negative limit is off too, not a stop at the first line (`-StopOverBudgetSeconds -1` stopped every run). for name in limits: self.assertIsNone(self.memory_run(dict(limits, **{name: -1}), calm).state()["memory_stop"], name) def test_a_run_stopped_for_memory_fails_with_its_reason(self): limits = {"private_max_mb": 30000, "commit_left_min_mb": 200, "over_budget_s": 60} f = self.memory_run(limits, [(24000, 7000, 3000)] * 10 + [(31000, 7000, 3000)]) f.event(121, "stop_requested", reason="memory", why="private bytes 31000 MB, over 30000 MB") f.log.append(f"{stamp(121.3)} INFO leonida_hle::modules::lifecycle: title suspended; ending the title") f.event(121.5, "game_exited", exit_code=0) s = f.summarize() self.assertEqual(s["verdict"]["result"], "FAIL") self.assertEqual(s["verdict"]["reasons"], ["memory_stop"]) self.assertEqual(s["stop"]["reason"], "memory") self.assertEqual(s["stop"]["memory_why"], "private bytes 31000 MB, over 30000 MB") self.assertEqual(s["memory"]["stop_limits"], limits) # Stopped before the world (seen in a real run with a low cap): the memory stop is the one reason. f = Fake() f.meta["memory_stop"] = limits f.event(1, "game", pid=1) f.frames(10, 80, 60.0, 13) f.memory(75, 31000, 4000) f.event(80, "stop_requested", reason="memory", why="private bytes 31000 MB, over 30000 MB") f.event(83, "game_exited", exit_code=0) self.assertEqual(f.summarize()["verdict"]["reasons"], ["memory_stop"]) def test_the_memory_series_and_a_pile_ups_slope(self): f = passing() for t in range(10, 390, 5): # From the world on (70 s) the private bytes grow 10 MB every 5 s and the reaper's queue grows. grown = max(0, t - 70) // 5 f.memory(t, 20000 + 10 * grown, 7000, waiting=3, reaper=100 * grown) s = f.summarize() m = s["memory"] self.assertEqual(m["private_mb_per_min_in_world"], 120.0) self.assertEqual((m["reaper_queue_max"], m["reaper_queue_max_at_s"]), (100 * 63, 385.0)) self.assertEqual(m["waiting_objects_max"], 3) self.assertEqual(m["series"], "memory.csv") # `summary` writes the series beside summary.json, one row per memory line, numbers only. with contextlib.redirect_stdout(io.StringIO()): game_gate.main(["game_gate.py", "summary", f.dir]) with open(os.path.join(f.dir, "memory.csv"), encoding="utf-8") as fh: rows = list(csv.DictReader(fh)) self.assertEqual(len(rows), 76) self.assertEqual(tuple(rows[0]), game_gate.SERIES_COLUMNS) self.assertEqual(rows[-1]["private_mb"], "20630") self.assertEqual(rows[-1]["reaper_queue"], "6300") self.assertEqual(rows[-1]["vram_in_use_mb"], "7000") # The same bytes on every machine: LF line ends, never CRLF. with open(os.path.join(f.dir, "memory.csv"), "rb") as fh: self.assertNotIn(b"\r", fh.read()) def summary_files(self, f): """`game_gate.py summary` on the folder: (exit code, summary.json, memory.csv rows or None, stderr).""" f.summarize() err = io.StringIO() with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(err): code = game_gate.main(["game_gate.py", "summary", f.dir]) with open(os.path.join(f.dir, "summary.json"), encoding="utf-8") as fh: s = json.load(fh) path = os.path.join(f.dir, "memory.csv") rows = None if os.path.isfile(path): with open(path, encoding="utf-8") as fh: rows = list(csv.DictReader(fh)) return code, s, rows, err.getvalue() def test_the_series_takes_the_lines_within_2_s_of_each_memory_line(self): f = passing() f.memory(100, 20000, 7000, waiting=3, reaper=40) # the three lines at once, as the runtime writes them f.memory(200, 21000, 7500, waiting=5, reaper=50) census, video, memory = f.log[-3:] # The video memory line 2 s before (taken), the census line 2.5 s after (too far: empty cells). f.log[-3:] = [census.replace(stamp(200), stamp(202.5)), video.replace(stamp(200), stamp(198)), memory] f.memory(300, 22000, 8000) f.log[-3:] = f.log[-1:] # a memory line alone _, _, rows, _ = self.summary_files(f) got = [(r["t_s"], r["vram_in_use_mb"], r["shared_in_use_mb"], r["waiting_objects"], r["reaper_queue"]) for r in rows] self.assertEqual(got, [("100.0", "7000", "500", "3", "40"), ("200.0", "7500", "500", "", ""), ("300.0", "", "", "", "")]) def test_the_slope_counts_the_world_up_to_the_stop(self): f = Fake() f.event(1, "game", pid=1) f.frames(10, 70, 60.0, 13) f.frames(70, 420, 50.0, 4000) for t in range(70, 420, 5): # 120 MB a minute in the world, then a jump while the title ends after the stop request (390 s). f.memory(t, 20000 + 2 * (t - 70) if t <= 390 else 40000, 7000) f.event(390, "stop_requested", reason="target") f.event(420, "game_exited", exit_code=0) self.assertEqual(f.summarize()["memory"]["private_mb_per_min_in_world"], 120.0) # Fewer than 3 memory lines in the world: no slope. f = passing() for t in (40, 50, 60, 100, 200): f.memory(t, 20000 + t, 7000) self.assertIsNone(f.summarize()["memory"]["private_mb_per_min_in_world"]) def test_a_series_it_cannot_write_still_leaves_the_summary(self): # memory.csv held by another program: the summary is written all the same, with no series named. f = passing() for t in range(70, 390, 5): f.memory(t, 20000, 7000) os.makedirs(os.path.join(f.dir, "memory.csv")) # opening it to write fails, as a locked file does code, s, _, err = self.summary_files(f) self.assertEqual(code, 0) self.assertEqual(s["verdict"]["result"], "PASS") self.assertIsNone(s["memory"]["series"]) self.assertEqual(s["memory"]["lines"], 64) self.assertIn("memory.csv not written or removed", err) def test_a_build_without_memory_lines_gives_no_memory_peaks(self): f = passing() m = f.summarize()["memory"] self.assertIsNone(m["source"]) self.assertEqual(m["lines"], 0) self.assertIsNone(m["private_max_mb"]) self.assertIsNone(m["vram_in_use_max_mb"]) self.assertIsNone(m["series"]) self.assertIsNone(m["reaper_queue_max"]) self.assertIsNone(m["private_mb_per_min_in_world"]) # And `summary` writes no series file: not even a header alone. with contextlib.redirect_stdout(io.StringIO()): game_gate.main(["game_gate.py", "summary", f.dir]) self.assertFalse(os.path.exists(os.path.join(f.dir, "memory.csv"))) def test_a_folder_summarized_again_without_memory_lines_keeps_no_old_series(self): # A memory.csv from an earlier summary, and a log that has no memory lines now: the old rows must not sit # beside `series: null`. f = passing() f.summarize() with open(os.path.join(f.dir, "memory.csv"), "w", encoding="utf-8", newline="\n") as fh: fh.write(",".join(game_gate.SERIES_COLUMNS) + "\n70.0,1000,500,15000,4000,8000,7000,500,0,0\n") with contextlib.redirect_stdout(io.StringIO()): game_gate.main(["game_gate.py", "summary", f.dir]) with open(os.path.join(f.dir, "summary.json"), encoding="utf-8") as fh: self.assertIsNone(json.load(fh)["memory"]["series"]) self.assertFalse(os.path.exists(os.path.join(f.dir, "memory.csv"))) def test_without_present_lines_the_frame_lines_give_the_rate(self): f = Fake() f.event(1, "game", pid=1) f.frames(70, 400, 30.0, 4000, presents=False) f.clean_stop(400) s = f.summarize() self.assertEqual(s["fps"]["source"], "frame_lines") self.assertAlmostEqual(s["fps"]["median"], 30.0, places=1) self.assertIn("no_present_lines", s["verdict"]["warnings"]) def test_colored_lines_read_the_same(self): f = passing() f.log = [l.replace(" INFO ", " \x1b[32mINFO\x1b[0m ") for l in f.log] self.assertEqual(f.summarize()["verdict"]["result"], "PASS") def test_a_write_at_zero_in_the_title_after_a_freeze_is_its_watchdog(self): f = Fake() f.event(1, "game", pid=1) f.frames(70, 200, 50.0, 4000) f.log.append(f"{stamp(230)} INFO leonida_hle::x: still here") f.log.append("Leonida: unhandled exception 0xc0000005 at game_title.exe+0x1234 (write 0x0: no memory)") f.event(231, "game_exited", exit_code=0xC0000005) s = f.summarize() self.assertEqual(s["crash"]["kind"], "fault") self.assertEqual((s["crash"]["module"], s["crash"]["access"]), ("title", "write")) self.assertTrue(s["crash"]["title_watchdog"]) self.assertIn("fault_before_stop", s["verdict"]["reasons"]) def test_settings_and_precompile_lines_are_read(self): f = passing() f.log.append(f"{stamp(5)} INFO settings: 2 LEONIDA_ settings: LEONIDA_DATA_DIR= " "LEONIDA_RELAY=2") f.launcher += ["25663 shaders in the cache, 3 do not translate, 118 s", "88571 pipelines known, 85479 made before (abcd), 12 bad; 3092 to make, 12 processes", "3092 made in 640 s (5 have no host pipeline, 0 ended their process); ms each: median 180.5, " "p90 900.0, p99 2000.0, most 9000, sum 600 s"] s = f.summarize() self.assertEqual(s["settings"], {"LEONIDA_DATA_DIR": "", "LEONIDA_RELAY": "2"}) p = s["precompile"] self.assertEqual((p["shaders"], p["untranslatable"], p["shaders_s"]), (25663, 3, 118)) self.assertEqual((p["pipelines_known"], p["made_before"], p["to_make"], p["made"], p["made_s"]), (88571, 85479, 3092, 3092, 640)) self.assertNotIn("no_settings_line", s["verdict"]["warnings"]) def test_the_summary_holds_no_path(self): f = passing() f.log.append(f"{stamp(5)} INFO settings: 1 LEONIDA_ settings: LEONIDA_GAME_DIR=") f.log.append("Leonida: unhandled exception 0xc0000005 at C:\\Users\\someone\\x.dll+0x10 (read 0x8: x)") text = json.dumps(f.summarize()) self.assertNotIn("someone", text) self.assertNotRegex(text, r"[A-Za-z]:\\\\") class Command(unittest.TestCase): def test_summary_writes_the_file_and_exits_by_verdict(self): f = passing() f.summarize() self.assertEqual(game_gate.main(["game_gate.py", "summary", f.dir]), 0) with open(os.path.join(f.dir, "summary.json"), encoding="utf-8") as h: self.assertEqual(json.load(h)["schema"], game_gate.SCHEMA) def test_state_tells_the_supervisor_the_world_time(self): f = passing() f.summarize() state = game_gate.state(game_gate.Run(f.dir)) self.assertAlmostEqual(state["world_at_s"], 70.0, places=3) self.assertGreaterEqual(state["world_s"], 300) class Script(unittest.TestCase): def test_it_needs_powershell_7(self): # Under Windows PowerShell 5.1 it failed in about 2 s without saying why: it now says so before running. with open(os.path.join(ROOT, "scripts", "game-gate.ps1"), encoding="utf-8") as f: self.assertEqual(f.readline().strip(), "#Requires -Version 7.0") def test_the_memory_stop_limits_reach_the_run_and_its_detached_start(self): with open(os.path.join(ROOT, "scripts", "game-gate.ps1"), encoding="utf-8") as f: text = f.read() for name in ("StopPrivateMB", "StopCommitLeftMB", "StopOverBudgetSeconds"): self.assertIn(f"[int]${name} = ", text) # `start` rebuilds the command line of the detached `run`: a limit left out would be lost there. self.assertIn(f"'-{name}'; ${name}", text) self.assertIn("memory_stop = [ordered]@{", text) # The private default follows the PC's memory too, not only its commit limit (a large page file). self.assertIn("TotalPhysicalMemory", text) self.assertIn("[math]::Min($commitLimitMB * 0.9, $physicalMB * 1.25)", text) # What one poll of the supervisor reads (`game_gate.py state`, a STOP file, the minutes since the start) and the # reason it stops the run for, with -WorldSeconds 300 and -MaxMinutes 45. POLLS = [ # The world time reached in the same poll as a memory limit: a measurement, not a memory stop. ({"relaunched": False, "world_s": 300.0, "memory_stop": "private bytes 31000 MB, over 30000 MB"}, False, 20, "target"), ({"relaunched": False, "world_s": 295.0, "memory_stop": "private bytes 31000 MB, over 30000 MB"}, False, 20, "memory"), ({"relaunched": True, "world_s": 300.0, "memory_stop": "private bytes 31000 MB, over 30000 MB"}, False, 20, "relaunched"), ({"relaunched": False, "world_s": 100.0, "memory_stop": "video memory over its budget for 60 s"}, True, 20, "memory"), ({"relaunched": False, "world_s": 100.0, "memory_stop": None}, True, 20, "stop_file"), # A memory limit at the time limit: the memory stop names the real reason. ({"relaunched": False, "world_s": 100.0, "memory_stop": "private bytes 31000 MB, over 30000 MB"}, False, 45, "memory"), ({"relaunched": False, "world_s": 0.0, "memory_stop": None}, False, 45, "timeout"), ({"relaunched": False, "world_s": 100.0, "memory_stop": None}, False, 20, "none"), ] def test_a_poll_stops_for_the_target_before_the_memory_stop(self): # The supervisor's own function is taken out of the script and put to PowerShell 7 with each poll above. with open(os.path.join(ROOT, "scripts", "game-gate.ps1"), encoding="utf-8") as f: text = f.read() self.assertIn("$stopReason = Get-StopReason -Poll $state ", text) self.assertIn("-TargetSeconds $WorldSeconds -LimitMinutes $MaxMinutes", text) self.assertEqual(text.count("$stopReason = "), 2) # set to $null before the loop, then only from the function # The memory stop's sentence goes into the stop_requested event (`stop.memory_why`). self.assertIn("if ($stopReason -eq 'memory') { $memoryWhy = $state.memory_stop }", text) pwsh = shutil.which("pwsh") if not pwsh: self.skipTest("no PowerShell 7 here") script = ("$ErrorActionPreference = 'Stop'; " "$language = 'System.Management.Automation.Language'; " "$ast = ($language + '.Parser' -as [type])::ParseFile($env:GATE_SCRIPT, [ref]$null, [ref]$null); " "$fn = $ast.Find({ $args[0].GetType().Name -eq 'FunctionDefinitionAst' -and " "$args[0].Name -eq 'Get-StopReason' }, $true); " "if (-not $fn) { throw 'the gate has no Get-StopReason' }; " ". ([scriptblock]::Create($fn.Extent.Text)); " "foreach ($p in ($env:GATE_POLLS | ConvertFrom-Json)) " "{ $r = Get-StopReason -Poll $p[0] -StopFile $p[1] -Minutes $p[2] -TargetSeconds 300 " "-LimitMinutes 45; if ($r) { $r } else { 'none' } }") env = dict(os.environ, GATE_SCRIPT=os.path.join(ROOT, "scripts", "game-gate.ps1"), GATE_POLLS=json.dumps([p[:3] for p in self.POLLS])) done = subprocess.run([pwsh, "-NoProfile", "-NonInteractive", "-Command", script], capture_output=True, text=True, timeout=120, env=env) self.assertEqual(done.returncode, 0, done.stderr) self.assertEqual(done.stdout.split(), [p[3] for p in self.POLLS]) def test_no_variable_takes_a_parameters_name_in_another_case(self): # PowerShell names ignore case: a `$game` process held in the `[string]$Game` parameter became its name, # and the stop could not wait for it. with open(os.path.join(ROOT, "scripts", "game-gate.ps1"), encoding="utf-8") as f: text = f.read() block = text[text.index("param("):text.index("\n)\n")] params = re.findall(r"\$(\w+)", block) self.assertIn("Game", params) for name in params: others = {m for m in re.findall(r"\$(\w+)\b", text) if m.lower() == name.lower() and m != name} self.assertFalse(others, f"${name} is also written {sorted(others)}") # -PlayArgs, and whether they switch DLSS off for scripts/play-d3d12.ps1 as PowerShell binds them. The gate refuses # a build made without DLSS once NVIDIA's SDK is there, unless the start says -NoDlss. NO_DLSS = { "": False, "-SeriesS -NoFrameGen": False, "-NoDlss": True, "-NoD": True, "-nodlss": True, "-SeriesS -NoDlss -NoFrameGen": True, "-NoDlss:$true": True, "-NoDlss: $true": True, "-SeriesS -NoDlss: $true -NoFrameGen": True, "-NoDlss:$false": False, "-NoDlss: $false": False, "-SeriesS -NoDlss: $false -NoFrameGen": False, "-Adapter 'Fixture -NoDlss Adapter'": False, "-Adapter 'Fixture -NoDlss Adapter' -NoDlss:$false": False, "-Adapter 'Fixture -NoDlss Adapter' -NoDlss": True, "-No": False, # several switches begin so: the play script refuses it as well "-NoDlssX": False, # no such switch "-NoDlss -Bogus": False, # does not bind at all: the start fails on it, and the gate says so "-SeriesS; $true": False, # what the text writes behind a `;` is not the answer } def test_the_dlss_preflight_asks_powershell_not_a_pattern(self): with open(os.path.join(ROOT, "scripts", "game-gate.ps1"), encoding="utf-8") as f: text = f.read() self.assertNotRegex(text, r"\$PlayArgs\s+-(not)?match") self.assertIn("$noDlss = Test-NoDlssBound $play $PlayArgs", text) def test_the_dlss_preflight_follows_the_switch_powershell_binds(self): # A pattern over the text took `-NoDlss: $true` (a space after the colon) for a start that wants DLSS, and a # quoted adapter name with -NoDlss in it for one that does not. The gate's own function is taken out of the # script and put to PowerShell 7 with each line of the table, against the real play script's parameters. pwsh = shutil.which("pwsh") if not pwsh: self.skipTest("no PowerShell 7 here") script = ("$ErrorActionPreference = 'Stop'; " "$language = 'System.Management.Automation.Language'; " "$ast = ($language + '.Parser' -as [type])::ParseFile($env:GATE_SCRIPT, [ref]$null, [ref]$null); " "$fn = $ast.Find({ $args[0].GetType().Name -eq 'FunctionDefinitionAst' -and " "$args[0].Name -eq 'Test-NoDlssBound' }, $true); " "if (-not $fn) { throw 'the gate has no Test-NoDlssBound' }; " ". ([scriptblock]::Create($fn.Extent.Text)); " "foreach ($line in ($env:GATE_PLAY_ARGS | ConvertFrom-Json)) " "{ [string]((Test-NoDlssBound $env:GATE_PLAY $line) -eq $true) }") forms = list(self.NO_DLSS) env = dict(os.environ, GATE_SCRIPT=os.path.join(ROOT, "scripts", "game-gate.ps1"), GATE_PLAY=os.path.join(ROOT, "scripts", "play-d3d12.ps1"), GATE_PLAY_ARGS=json.dumps(forms)) done = subprocess.run([pwsh, "-NoProfile", "-NonInteractive", "-Command", script], capture_output=True, text=True, timeout=120, env=env) self.assertEqual(done.returncode, 0, done.stderr) self.assertEqual(len(done.stdout.split()), len(forms), done.stdout) self.assertEqual(dict(zip(forms, done.stdout.split())), {form: str(said) for form, said in self.NO_DLSS.items()}) class Contract(unittest.TestCase): def test_the_runtime_still_writes_what_the_parser_reads(self): for words, path in game_gate.SOURCES.items(): with open(os.path.join(ROOT, path), encoding="utf-8") as f: # Rust strings continued over lines (a backslash at the end of a line) read as one. text = re.sub(r"\\\r?\n\s*", "", f.read()) self.assertIn(words, text, f"{path} no longer says {words!r}: update tools/game_gate.py") if __name__ == "__main__": unittest.main()