upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/tests/test_game_gate.py
diff options
context:
space:
mode:
authorMoonEyes <14891700+MoonEyes@users.noreply.github.com>2026-12-02 11:51:40 +0100
committerMoonEyes <14891700+MoonEyes@users.noreply.github.com>2026-12-02 11:51:40 +0100
commitfff970e616bf965729cd08a4e86bc6264494de73 (patch)
tree03cdc30677fbe1ddaaf33d160150c9afbcfe73c5 /tests/test_game_gate.py
parent7c245a359b8bdb6d9985c6d3ffd2bee0609de911 (diff)
parent895c472faa1c3d44a1358640f09c1f10e6a6a876 (diff)
Merge origin/main into carry/1346
Diffstat (limited to 'tests/test_game_gate.py')
-rw-r--r--tests/test_game_gate.py246
1 files changed, 243 insertions, 3 deletions
diff --git a/tests/test_game_gate.py b/tests/test_game_gate.py
index 9873a95bf..b842660f9 100644
--- a/tests/test_game_gate.py
+++ b/tests/test_game_gate.py
@@ -1,6 +1,9 @@
1"""tools/game_gate.py on synthetic run folders: every log line below is made up by the test, in the runtime's 1"""tools/game_gate.py on synthetic run folders: every log line below is made up by the test, in the runtime's
2formats (no game data). The contract test checks that those formats are still in the runtime's source.""" 2formats (no game data). The contract test checks that those formats are still in the runtime's source."""
3import contextlib
4import csv
3import datetime as dt 5import datetime as dt
6import io
4import json 7import json
5import os 8import os
6import re 9import re
@@ -50,8 +53,14 @@ class Fake:
50 self.log.append(f"{stamp(t)} DEBUG leonida_gpu::frame: present token=1") 53 self.log.append(f"{stamp(t)} DEBUG leonida_gpu::frame: present token=1")
51 t += gap 54 t += gap
52 55
53 def memory(self, t, private, used, budget=8000, left=3000, shared=500): 56 def memory(self, t, private, used, budget=8000, left=3000, shared=500, waiting=0, reaper=0):
54 """The runtime's video memory line and memory line, as a diagnostics build writes them every 5 s.""" 57 """The runtime's video memory line, census line and memory line, as a diagnostics build writes them every 5 s."""
58 self.log.append(f"{stamp(t)} INFO leonida_gpu::census: memory, what waits to be let go: {waiting} objects let "
59 f"go that wait for the submissions that may use them (LEONIDA_BURY_LAG), {reaper} retired "
60 f"objects, landed host lists and lists' fronts handed to the thread that lets them go and not "
61 f"let go yet (LEONIDA_REAPER=0: let go by the submitting thread); 0 let go by the thread done "
62 f"with them instead, since the start, the reaper thread's line holding LEONIDA_REAPER_LIMIT=0 or "
63 f"more (0: no bound)")
55 self.log.append(f"{stamp(t)} INFO leonida_gpu::host: video memory as the system counts it, with the memory " 64 self.log.append(f"{stamp(t)} INFO leonida_gpu::host: video memory as the system counts it, with the memory "
56 f"line: the card's own: budget {budget} MB, in use {used} MB, 100 MB could still be reserved, " 65 f"line: the card's own: budget {budget} MB, in use {used} MB, 100 MB could still be reserved, "
57 f"0 MB reserved; the PC's shared with the card: budget 16000 MB, in use {shared} MB, 0 MB could " 66 f"0 MB reserved; the PC's shared with the card: budget 16000 MB, in use {shared} MB, 0 MB could "
@@ -66,6 +75,11 @@ class Fake:
66 self.log.append(f"{stamp(t + 0.3)} INFO leonida_hle::modules::lifecycle: title suspended; ending the title") 75 self.log.append(f"{stamp(t + 0.3)} INFO leonida_hle::modules::lifecycle: title suspended; ending the title")
67 self.event(t + 0.5, "game_exited", exit_code=exit_code) 76 self.event(t + 0.5, "game_exited", exit_code=exit_code)
68 77
78 def state(self):
79 """What the supervisor reads during the run (`game_gate.py state`)."""
80 self.summarize()
81 return game_gate.state(game_gate.Run(self.dir))
82
69 def summarize(self): 83 def summarize(self):
70 self.log.sort(key=lambda l: l[:27]) 84 self.log.sort(key=lambda l: l[:27])
71 files = {"run.json": json.dumps(self.meta), "leonida.log": "\n".join(self.log) + "\n", 85 files = {"run.json": json.dumps(self.meta), "leonida.log": "\n".join(self.log) + "\n",
@@ -235,12 +249,177 @@ class Measures(unittest.TestCase):
235 self.assertEqual(m["vram_over_budget_s"], 185.0) 249 self.assertEqual(m["vram_over_budget_s"], 185.0)
236 self.assertEqual(m["shared_in_use_max_mb"], 563) 250 self.assertEqual(m["shared_in_use_max_mb"], 563)
237 251
252 def memory_run(self, limits, rows):
253 """A run in the world with memory lines every 5 s from 70 s: rows of (private, video in use, PC left)."""
254 f = Fake()
255 f.meta["memory_stop"] = limits
256 f.event(1, "game", pid=1)
257 f.frames(10, 70, 60.0, 13)
258 f.frames(70, 70 + 5 * len(rows), 30.0, 4000)
259 for i, (private, used, left) in enumerate(rows):
260 f.memory(70 + 5 * i, private, used, budget=8000, left=left)
261 return f
262
263 def test_the_memory_stop_asks_for_a_stop_past_each_limit(self):
264 limits = {"private_max_mb": 30000, "commit_left_min_mb": 200, "over_budget_s": 60}
265 calm = [(24000, 7000, 3000)] * 10
266 cases = {
267 "private bytes 31000 MB, over 30000 MB": calm + [(31000, 7000, 3000)],
268 "the PC had under 200 MB left to commit for 25 s": calm + [(24000, 7000, 150)] * 6,
269 # Exactly 20 s under the floor (five lines 5 s apart) is enough: the floor's boundary, as 60 s is the
270 # video memory's.
271 "the PC had under 200 MB left to commit for 20 s": calm + [(24000, 7000, 150)] * 5,
272 "video memory over its budget for 60 s": calm + [(24000, 9000, 3000)] * 13,
273 }
274 for why, rows in cases.items():
275 self.assertEqual(self.memory_run(limits, rows).state()["memory_stop"], why)
276 # Under each limit, at the private limit itself, or not for long enough: no stop.
277 for rows in (calm, calm + [(30000, 7000, 3000)], calm + [(24000, 7000, 150)] * 4,
278 calm + [(24000, 9000, 3000)] * 12):
279 self.assertIsNone(self.memory_run(limits, rows).state()["memory_stop"])
280 # 0 turns a limit off, and a run.json without limits (an older gate) never stops for memory.
281 off = {"private_max_mb": 0, "commit_left_min_mb": 0, "over_budget_s": 0}
282 self.assertIsNone(self.memory_run(off, cases["private bytes 31000 MB, over 30000 MB"]).state()["memory_stop"])
283 self.assertIsNone(self.memory_run(None, cases["private bytes 31000 MB, over 30000 MB"]).state()["memory_stop"])
284 # A negative limit is off too, not a stop at the first line (`-StopOverBudgetSeconds -1` stopped every run).
285 for name in limits:
286 self.assertIsNone(self.memory_run(dict(limits, **{name: -1}), calm).state()["memory_stop"], name)
287
288 def test_a_run_stopped_for_memory_fails_with_its_reason(self):
289 limits = {"private_max_mb": 30000, "commit_left_min_mb": 200, "over_budget_s": 60}
290 f = self.memory_run(limits, [(24000, 7000, 3000)] * 10 + [(31000, 7000, 3000)])
291 f.event(121, "stop_requested", reason="memory", why="private bytes 31000 MB, over 30000 MB")
292 f.log.append(f"{stamp(121.3)} INFO leonida_hle::modules::lifecycle: title suspended; ending the title")
293 f.event(121.5, "game_exited", exit_code=0)
294 s = f.summarize()
295 self.assertEqual(s["verdict"]["result"], "FAIL")
296 self.assertEqual(s["verdict"]["reasons"], ["memory_stop"])
297 self.assertEqual(s["stop"]["reason"], "memory")
298 self.assertEqual(s["stop"]["memory_why"], "private bytes 31000 MB, over 30000 MB")
299 self.assertEqual(s["memory"]["stop_limits"], limits)
300 # Stopped before the world (seen in a real run with a low cap): the memory stop is the one reason.
301 f = Fake()
302 f.meta["memory_stop"] = limits
303 f.event(1, "game", pid=1)
304 f.frames(10, 80, 60.0, 13)
305 f.memory(75, 31000, 4000)
306 f.event(80, "stop_requested", reason="memory", why="private bytes 31000 MB, over 30000 MB")
307 f.event(83, "game_exited", exit_code=0)
308 self.assertEqual(f.summarize()["verdict"]["reasons"], ["memory_stop"])
309
310 def test_the_memory_series_and_a_pile_ups_slope(self):
311 f = passing()
312 for t in range(10, 390, 5):
313 # From the world on (70 s) the private bytes grow 10 MB every 5 s and the reaper's queue grows.
314 grown = max(0, t - 70) // 5
315 f.memory(t, 20000 + 10 * grown, 7000, waiting=3, reaper=100 * grown)
316 s = f.summarize()
317 m = s["memory"]
318 self.assertEqual(m["private_mb_per_min_in_world"], 120.0)
319 self.assertEqual((m["reaper_queue_max"], m["reaper_queue_max_at_s"]), (100 * 63, 385.0))
320 self.assertEqual(m["waiting_objects_max"], 3)
321 self.assertEqual(m["series"], "memory.csv")
322 # `summary` writes the series beside summary.json, one row per memory line, numbers only.
323 with contextlib.redirect_stdout(io.StringIO()):
324 game_gate.main(["game_gate.py", "summary", f.dir])
325 with open(os.path.join(f.dir, "memory.csv"), encoding="utf-8") as fh:
326 rows = list(csv.DictReader(fh))
327 self.assertEqual(len(rows), 76)
328 self.assertEqual(tuple(rows[0]), game_gate.SERIES_COLUMNS)
329 self.assertEqual(rows[-1]["private_mb"], "20630")
330 self.assertEqual(rows[-1]["reaper_queue"], "6300")
331 self.assertEqual(rows[-1]["vram_in_use_mb"], "7000")
332 # The same bytes on every machine: LF line ends, never CRLF.
333 with open(os.path.join(f.dir, "memory.csv"), "rb") as fh:
334 self.assertNotIn(b"\r", fh.read())
335
336 def summary_files(self, f):
337 """`game_gate.py summary` on the folder: (exit code, summary.json, memory.csv rows or None, stderr)."""
338 f.summarize()
339 err = io.StringIO()
340 with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(err):
341 code = game_gate.main(["game_gate.py", "summary", f.dir])
342 with open(os.path.join(f.dir, "summary.json"), encoding="utf-8") as fh:
343 s = json.load(fh)
344 path = os.path.join(f.dir, "memory.csv")
345 rows = None
346 if os.path.isfile(path):
347 with open(path, encoding="utf-8") as fh:
348 rows = list(csv.DictReader(fh))
349 return code, s, rows, err.getvalue()
350
351 def test_the_series_takes_the_lines_within_2_s_of_each_memory_line(self):
352 f = passing()
353 f.memory(100, 20000, 7000, waiting=3, reaper=40) # the three lines at once, as the runtime writes them
354 f.memory(200, 21000, 7500, waiting=5, reaper=50)
355 census, video, memory = f.log[-3:]
356 # The video memory line 2 s before (taken), the census line 2.5 s after (too far: empty cells).
357 f.log[-3:] = [census.replace(stamp(200), stamp(202.5)), video.replace(stamp(200), stamp(198)), memory]
358 f.memory(300, 22000, 8000)
359 f.log[-3:] = f.log[-1:] # a memory line alone
360 _, _, rows, _ = self.summary_files(f)
361 got = [(r["t_s"], r["vram_in_use_mb"], r["shared_in_use_mb"], r["waiting_objects"], r["reaper_queue"])
362 for r in rows]
363 self.assertEqual(got, [("100.0", "7000", "500", "3", "40"), ("200.0", "7500", "500", "", ""),
364 ("300.0", "", "", "", "")])
365
366 def test_the_slope_counts_the_world_up_to_the_stop(self):
367 f = Fake()
368 f.event(1, "game", pid=1)
369 f.frames(10, 70, 60.0, 13)
370 f.frames(70, 420, 50.0, 4000)
371 for t in range(70, 420, 5):
372 # 120 MB a minute in the world, then a jump while the title ends after the stop request (390 s).
373 f.memory(t, 20000 + 2 * (t - 70) if t <= 390 else 40000, 7000)
374 f.event(390, "stop_requested", reason="target")
375 f.event(420, "game_exited", exit_code=0)
376 self.assertEqual(f.summarize()["memory"]["private_mb_per_min_in_world"], 120.0)
377 # Fewer than 3 memory lines in the world: no slope.
378 f = passing()
379 for t in (40, 50, 60, 100, 200):
380 f.memory(t, 20000 + t, 7000)
381 self.assertIsNone(f.summarize()["memory"]["private_mb_per_min_in_world"])
382
383 def test_a_series_it_cannot_write_still_leaves_the_summary(self):
384 # memory.csv held by another program: the summary is written all the same, with no series named.
385 f = passing()
386 for t in range(70, 390, 5):
387 f.memory(t, 20000, 7000)
388 os.makedirs(os.path.join(f.dir, "memory.csv")) # opening it to write fails, as a locked file does
389 code, s, _, err = self.summary_files(f)
390 self.assertEqual(code, 0)
391 self.assertEqual(s["verdict"]["result"], "PASS")
392 self.assertIsNone(s["memory"]["series"])
393 self.assertEqual(s["memory"]["lines"], 64)
394 self.assertIn("memory.csv not written or removed", err)
395
238 def test_a_build_without_memory_lines_gives_no_memory_peaks(self): 396 def test_a_build_without_memory_lines_gives_no_memory_peaks(self):
239 m = passing().summarize()["memory"] 397 f = passing()
398 m = f.summarize()["memory"]
240 self.assertIsNone(m["source"]) 399 self.assertIsNone(m["source"])
241 self.assertEqual(m["lines"], 0) 400 self.assertEqual(m["lines"], 0)
242 self.assertIsNone(m["private_max_mb"]) 401 self.assertIsNone(m["private_max_mb"])
243 self.assertIsNone(m["vram_in_use_max_mb"]) 402 self.assertIsNone(m["vram_in_use_max_mb"])
403 self.assertIsNone(m["series"])
404 self.assertIsNone(m["reaper_queue_max"])
405 self.assertIsNone(m["private_mb_per_min_in_world"])
406 # And `summary` writes no series file: not even a header alone.
407 with contextlib.redirect_stdout(io.StringIO()):
408 game_gate.main(["game_gate.py", "summary", f.dir])
409 self.assertFalse(os.path.exists(os.path.join(f.dir, "memory.csv")))
410
411 def test_a_folder_summarized_again_without_memory_lines_keeps_no_old_series(self):
412 # A memory.csv from an earlier summary, and a log that has no memory lines now: the old rows must not sit
413 # beside `series: null`.
414 f = passing()
415 f.summarize()
416 with open(os.path.join(f.dir, "memory.csv"), "w", encoding="utf-8", newline="\n") as fh:
417 fh.write(",".join(game_gate.SERIES_COLUMNS) + "\n70.0,1000,500,15000,4000,8000,7000,500,0,0\n")
418 with contextlib.redirect_stdout(io.StringIO()):
419 game_gate.main(["game_gate.py", "summary", f.dir])
420 with open(os.path.join(f.dir, "summary.json"), encoding="utf-8") as fh:
421 self.assertIsNone(json.load(fh)["memory"]["series"])
422 self.assertFalse(os.path.exists(os.path.join(f.dir, "memory.csv")))
244 423
245 def test_without_present_lines_the_frame_lines_give_the_rate(self): 424 def test_without_present_lines_the_frame_lines_give_the_rate(self):
246 f = Fake() 425 f = Fake()
@@ -317,6 +496,67 @@ class Script(unittest.TestCase):
317 with open(os.path.join(ROOT, "scripts", "game-gate.ps1"), encoding="utf-8") as f: 496 with open(os.path.join(ROOT, "scripts", "game-gate.ps1"), encoding="utf-8") as f:
318 self.assertEqual(f.readline().strip(), "#Requires -Version 7.0") 497 self.assertEqual(f.readline().strip(), "#Requires -Version 7.0")
319 498
499 def test_the_memory_stop_limits_reach_the_run_and_its_detached_start(self):
500 with open(os.path.join(ROOT, "scripts", "game-gate.ps1"), encoding="utf-8") as f:
501 text = f.read()
502 for name in ("StopPrivateMB", "StopCommitLeftMB", "StopOverBudgetSeconds"):
503 self.assertIn(f"[int]${name} = ", text)
504 # `start` rebuilds the command line of the detached `run`: a limit left out would be lost there.
505 self.assertIn(f"'-{name}'; ${name}", text)
506 self.assertIn("memory_stop = [ordered]@{", text)
507 # The private default follows the PC's memory too, not only its commit limit (a large page file).
508 self.assertIn("TotalPhysicalMemory", text)
509 self.assertIn("[math]::Min($commitLimitMB * 0.9, $physicalMB * 1.25)", text)
510
511 # What one poll of the supervisor reads (`game_gate.py state`, a STOP file, the minutes since the start) and the
512 # reason it stops the run for, with -WorldSeconds 300 and -MaxMinutes 45.
513 POLLS = [
514 # The world time reached in the same poll as a memory limit: a measurement, not a memory stop.
515 ({"relaunched": False, "world_s": 300.0, "memory_stop": "private bytes 31000 MB, over 30000 MB"}, False, 20,
516 "target"),
517 ({"relaunched": False, "world_s": 295.0, "memory_stop": "private bytes 31000 MB, over 30000 MB"}, False, 20,
518 "memory"),
519 ({"relaunched": True, "world_s": 300.0, "memory_stop": "private bytes 31000 MB, over 30000 MB"}, False, 20,
520 "relaunched"),
521 ({"relaunched": False, "world_s": 100.0, "memory_stop": "video memory over its budget for 60 s"}, True, 20,
522 "memory"),
523 ({"relaunched": False, "world_s": 100.0, "memory_stop": None}, True, 20, "stop_file"),
524 # A memory limit at the time limit: the memory stop names the real reason.
525 ({"relaunched": False, "world_s": 100.0, "memory_stop": "private bytes 31000 MB, over 30000 MB"}, False, 45,
526 "memory"),
527 ({"relaunched": False, "world_s": 0.0, "memory_stop": None}, False, 45, "timeout"),
528 ({"relaunched": False, "world_s": 100.0, "memory_stop": None}, False, 20, "none"),
529 ]
530
531 def test_a_poll_stops_for_the_target_before_the_memory_stop(self):
532 # The supervisor's own function is taken out of the script and put to PowerShell 7 with each poll above.
533 with open(os.path.join(ROOT, "scripts", "game-gate.ps1"), encoding="utf-8") as f:
534 text = f.read()
535 self.assertIn("$stopReason = Get-StopReason -Poll $state ", text)
536 self.assertIn("-TargetSeconds $WorldSeconds -LimitMinutes $MaxMinutes", text)
537 self.assertEqual(text.count("$stopReason = "), 2) # set to $null before the loop, then only from the function
538 # The memory stop's sentence goes into the stop_requested event (`stop.memory_why`).
539 self.assertIn("if ($stopReason -eq 'memory') { $memoryWhy = $state.memory_stop }", text)
540 pwsh = shutil.which("pwsh")
541 if not pwsh:
542 self.skipTest("no PowerShell 7 here")
543 script = ("$ErrorActionPreference = 'Stop'; "
544 "$language = 'System.Management.Automation.Language'; "
545 "$ast = ($language + '.Parser' -as [type])::ParseFile($env:GATE_SCRIPT, [ref]$null, [ref]$null); "
546 "$fn = $ast.Find({ $args[0].GetType().Name -eq 'FunctionDefinitionAst' -and "
547 "$args[0].Name -eq 'Get-StopReason' }, $true); "
548 "if (-not $fn) { throw 'the gate has no Get-StopReason' }; "
549 ". ([scriptblock]::Create($fn.Extent.Text)); "
550 "foreach ($p in ($env:GATE_POLLS | ConvertFrom-Json)) "
551 "{ $r = Get-StopReason -Poll $p[0] -StopFile $p[1] -Minutes $p[2] -TargetSeconds 300 "
552 "-LimitMinutes 45; if ($r) { $r } else { 'none' } }")
553 env = dict(os.environ, GATE_SCRIPT=os.path.join(ROOT, "scripts", "game-gate.ps1"),
554 GATE_POLLS=json.dumps([p[:3] for p in self.POLLS]))
555 done = subprocess.run([pwsh, "-NoProfile", "-NonInteractive", "-Command", script], capture_output=True,
556 text=True, timeout=120, env=env)
557 self.assertEqual(done.returncode, 0, done.stderr)
558 self.assertEqual(done.stdout.split(), [p[3] for p in self.POLLS])
559
320 def test_no_variable_takes_a_parameters_name_in_another_case(self): 560 def test_no_variable_takes_a_parameters_name_in_another_case(self):
321 # PowerShell names ignore case: a `$game` process held in the `[string]$Game` parameter became its name, 561 # PowerShell names ignore case: a `$game` process held in the `[string]$Game` parameter became its name,
322 # and the stop could not wait for it. 562 # and the stop could not wait for it.