From aa75f13197627391579e7c282b353cfa85f466ff Mon Sep 17 00:00:00 2001 From: TheGeogeo <57634077+TheGeogeo@users.noreply.github.com> Date: Tue, 1 Dec 2026 01:39:51 +0100 Subject: [PATCH 1/7] gate: a memory stop ends a run before memory runs out (D3D12-GATE-MEMORY-STOP) A memory pile-up has taken a PC's whole Windows down, not only the device, and a fixed 80 GB cap never triggers on a PC with a 40 GB commit limit. The supervisor now asks `game_gate.py state` for a memory stop, read from the runtime's latest memory lines: the game's private bytes past -StopPrivateMB (default 90 % of this PC's commit limit), the PC under -StopCommitLeftMB left to commit for 20 s (default the larger of 128 MB and 0.25 % of the limit), or video memory over the system's budget for -StopOverBudgetSeconds (60). 0 turns one off. The run then stops the same clean way, with the reason `memory`; the limits go into run.json and the summary, the limit passed into `stop.memory_why`, and the verdict is FAIL `memory_stop`. `start` forwards the limits to the detached run. --- docs/game_gate.md | 9 +++++- scripts/game-gate.ps1 | 24 ++++++++++++--- tests/test_game_gate.py | 66 +++++++++++++++++++++++++++++++++++++++++ tools/game_gate.py | 45 +++++++++++++++++++++++++--- 4 files changed, 135 insertions(+), 9 deletions(-) diff --git a/docs/game_gate.md b/docs/game_gate.md index 4849a85f68..1178a5dc2b 100644 --- a/docs/game_gate.md +++ b/docs/game_gate.md @@ -28,6 +28,12 @@ pwsh -NoProfile -File scripts\game-gate.ps1 stop -RunDir - **Reaching the world.** The gate does not drive the menus. Pass key presses with `LEONIDA_KEYS`; they are timed from the start of the process, so allow for the precompile. - **The caches.** `-Data` keeps its caches (`cache-2`); only the saves are copied. The first start after a translator change translates every shader again: run once before measuring. - **Ending the run.** It stops when the time in the world reaches `-WorldSeconds`, when a `STOP` file appears in the run folder (`stop`), or after `-MaxMinutes` (45). +- **Memory stop.** It also stops the run, the same clean way and with the reason `memory`, before memory runs out. A memory pile-up has taken a PC's whole Windows down, not only the device. It reads the runtime's memory lines (every 5 s, builds with diagnostics) and stops when: + - the game's private bytes pass `-StopPrivateMB` (default: 90 % of this PC's commit limit); + - the PC has less than `-StopCommitLeftMB` left to commit for 20 s (default: the larger of 128 MB and 0.25 % of the limit; on a PC with no page file a normal run can leave a few hundred MB); + - video memory stays over the system's budget for `-StopOverBudgetSeconds` (60). + + 0 turns a limit off. The limits go into `run.json` (`memory_stop`) and the summary (`memory.stop_limits`). - **How it stops.** With `WM_SYSCOMMAND`/`SC_CLOSE`, the runtime's own end: the title is suspended and the pipeline cache saved. It kills the game only if it has not ended 60 s later. - **Exit code.** 0 PASS, 1 FAIL, 2 ERROR. `start` exits when the detached run is created. @@ -62,7 +68,7 @@ Times are seconds since the run started. The summary holds numbers, switch names | `memory` | Peaks over the whole run, from the runtime's memory line and video memory line (every 5 s; builds with diagnostics only, otherwise `source` is null): the process's private bytes and when (`private_max_mb`, `private_max_at_s`), the most of them in physical memory, the least the PC had left to commit and when, the card's video memory in use at its most and when, with the budget the system gave then (`vram_in_use_max_mb`, `vram_max_at_s`, `vram_budget_at_max_mb`), the seconds spent over that budget, and the most of the PC's memory shared with the card in use. The video memory is what the system counts for this process, less than a tool like `nvidia-smi` shows for the whole card | | `crash` | `kind` is `none`, `device_lost`, `panic` or `fault`. It also gives the time, the code, the module kind (`runtime`, `title`, `driver`, `system`, `unknown`) and the access (read/write). `title_watchdog` marks a write at address 0 in the title more than 25 s after the last frame line. `count` is the number of crashes | | `exit` | The game's exit code, and its kind: `clean`, `device_lost` (0x887A0005), `killed` or `other` | -| `stop` | Why it was stopped (`target`, `stop_file`, `timeout`, `relaunched`), whether it was killed, whether the cache was saved, whether the suspend was in time | +| `stop` | Why it was stopped (`target`, `stop_file`, `timeout`, `relaunched`, `memory` with the limit passed in `memory_why`), whether it was killed, whether the cache was saved, whether the suspend was in time | | `verdict` | `result`, `reasons`, `warnings`, `min_world_s` | ## The verdict @@ -81,6 +87,7 @@ Times are seconds since the run started. The summary holds numbers, switch names - `exited_before_stop`; - `present_gap`; - `world_time_short`: the time limit came first; +- `memory_stop`: the memory stop ended the run, which was on its way to running out; - `not_alive_at_stop`; - `world_not_reached`, when the game ended before reaching the world. diff --git a/scripts/game-gate.ps1 b/scripts/game-gate.ps1 index 6ab0c11a91..1192cd0960 100644 --- a/scripts/game-gate.ps1 +++ b/scripts/game-gate.ps1 @@ -15,6 +15,10 @@ # saved) when -WorldSeconds were spent in the world, when a STOP file appears in the run folder, or after # -MaxMinutes; it kills the game only if it has not ended 60 s later. Exit code: 0 PASS, 1 FAIL, 2 ERROR. # Options: -WorldSeconds (300), -MaxMinutes (45), -More 'LEONIDA_X=1;LEONIDA_Y=2', -PlayArgs '-SeriesS -NoFrameGen'. +# Memory stop (from the runtime's memory lines, every 5 s, builds with diagnostics): the run is stopped the same +# clean way, with the reason `memory`, when the game's private bytes pass -StopPrivateMB (90 % of this PC's commit +# limit), when the PC has less than -StopCommitLeftMB left to commit for 20 s (the larger of 128 MB and 0.25 % of +# the limit), or when video memory stays over the system's budget for -StopOverBudgetSeconds (60). 0 turns one off. param( [Parameter(Mandatory, Position = 0)][ValidateSet('run', 'start', 'stop')][string]$Verb, [string]$Game = '', @@ -27,7 +31,10 @@ param( [int]$MaxMinutes = 45, [string]$More = '', [string]$PlayArgs = '', - [string]$Python = '' + [string]$Python = '', + [int]$StopPrivateMB = -1, + [int]$StopCommitLeftMB = -1, + [int]$StopOverBudgetSeconds = 60 ) $ErrorActionPreference = 'Stop' $repo = Split-Path -Parent $PSScriptRoot @@ -96,7 +103,8 @@ if ($Verb -eq 'start') { $line = @(& $quote $pwsh; '-NoProfile'; '-ExecutionPolicy'; 'Bypass'; '-File'; & $quote $PSCommandPath; 'run' '-Game'; & $quote $Game; '-Data'; & $quote $Data; '-DataTemplate'; & $quote $DataTemplate; '-Name'; & $quote $Name '-RunRoot'; & $quote $RunRoot; '-RunDir'; & $quote $RunDir; '-WorldSeconds'; $WorldSeconds; '-MaxMinutes'; $MaxMinutes - '-More'; & $quote $More; '-PlayArgs'; & $quote $PlayArgs; '-Python'; & $quote $Python) -join ' ' + '-More'; & $quote $More; '-PlayArgs'; & $quote $PlayArgs; '-Python'; & $quote $Python + '-StopPrivateMB'; $StopPrivateMB; '-StopCommitLeftMB'; $StopCommitLeftMB; '-StopOverBudgetSeconds'; $StopOverBudgetSeconds) -join ' ' # Created by Windows, not as a child of this shell: an agent's or a console's end does not end the run. $startup = New-CimInstance -ClassName Win32_ProcessStartup -ClientOnly -Property @{ ShowWindow = [uint16]0 } $made = Invoke-CimMethod -ClassName Win32_Process -MethodName Create -Arguments @{ @@ -140,6 +148,11 @@ $moreText & '$play' -Game '$Game' -Data '$Data' -More `$settings $PlayArgs @args "@ +# The memory stop's limits, from this PC's commit limit unless given (0 turns one off). On a PC with no page file a +# normal run can leave a few hundred MB to commit: the floor is low and must hold for 20 s. +$commitLimitMB = [math]::Floor((Get-CimInstance Win32_OperatingSystem).TotalVirtualMemorySize / 1KB) +if ($StopPrivateMB -lt 0) { $StopPrivateMB = [int]($commitLimitMB * 0.9) } +if ($StopCommitLeftMB -lt 0) { $StopCommitLeftMB = [int][math]::Max(128, $commitLimitMB * 0.0025) } $gpu = Get-CimInstance Win32_VideoController | Sort-Object { [uint64]$_.AdapterRAM } -Descending | Select-Object -First 1 [ordered]@{ name = $Name @@ -155,6 +168,7 @@ $gpu = Get-CimInstance Win32_VideoController | Sort-Object { [uint64]$_.AdapterR world_seconds = $WorldSeconds max_minutes = $MaxMinutes f1_settings_file = $hadMenuFile + memory_stop = [ordered]@{ private_max_mb = $StopPrivateMB; commit_left_min_mb = $StopCommitLeftMB; over_budget_s = $StopOverBudgetSeconds } } | ConvertTo-Json | Set-Content (Join-Path $RunDir 'run.json') & pwsh -NoProfile -ExecutionPolicy Bypass -File $launch -DryRun *> (Join-Path $RunDir 'settings.txt') @@ -196,6 +210,7 @@ public static class GateWindow { $began = Get-Date $title = $null # the game process ($Game, the same name in any case, is its folder) $stopReason = $null +$memoryWhy = $null try { while ($true) { Start-Sleep -Seconds 5 @@ -211,6 +226,7 @@ while ($true) { if (-not $title -and $launcher.HasExited) { break } $state = & $Python -I $tool state $RunDir | ConvertFrom-Json if ($state.relaunched) { $stopReason = 'relaunched' } + elseif ($state.memory_stop) { $stopReason = 'memory'; $memoryWhy = $state.memory_stop } elseif (Test-Path (Join-Path $RunDir 'STOP')) { $stopReason = 'stop_file' } elseif ($state.world_s -ge $WorldSeconds) { $stopReason = 'target' } elseif (((Get-Date) - $began).TotalMinutes -ge $MaxMinutes) { $stopReason = 'timeout' } @@ -218,7 +234,7 @@ while ($true) { } if ($stopReason -and $title -and -not $title.HasExited) { - Add-Event 'stop_requested' @{ reason = $stopReason } + Add-Event 'stop_requested' @{ reason = $stopReason; why = $memoryWhy } if ([GateWindow]::Close($title.Id)) { Add-Event 'close_sent' } if (-not $title.WaitForExit(60000)) { Stop-Process -Id $title.Id -Force @@ -226,7 +242,7 @@ if ($stopReason -and $title -and -not $title.HasExited) { $title.WaitForExit() } } elseif ($stopReason) { - Add-Event 'stop_requested' @{ reason = $stopReason } + Add-Event 'stop_requested' @{ reason = $stopReason; why = $memoryWhy } } if ($title) { Add-Event 'game_exited' @{ exit_code = $title.ExitCode } } if (-not $launcher.WaitForExit(30000)) { Stop-Process -Id $launcher.Id -Force } diff --git a/tests/test_game_gate.py b/tests/test_game_gate.py index 9873a95bfe..c73c2485df 100644 --- a/tests/test_game_gate.py +++ b/tests/test_game_gate.py @@ -66,6 +66,11 @@ def clean_stop(self, t, exit_code=0): 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", @@ -235,6 +240,57 @@ def test_memory_peaks_come_from_the_runtimes_memory_lines(self): 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, + "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, or not for long enough: no stop. + for rows in (calm, 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"]) + + 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_a_build_without_memory_lines_gives_no_memory_peaks(self): m = passing().summarize()["memory"] self.assertIsNone(m["source"]) @@ -317,6 +373,16 @@ def test_it_needs_powershell_7(self): 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) + self.assertIn("$stopReason = 'memory'", text) + 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. diff --git a/tools/game_gate.py b/tools/game_gate.py index fee55866bd..0c9772c280 100644 --- a/tools/game_gate.py +++ b/tools/game_gate.py @@ -31,6 +31,8 @@ GAP_FAIL_S = 10.0 # The last frame line before the stop request is at most this old for the run to count as alive. ALIVE_S = 30.0 +# The memory stop: the PC under its commit floor this long (5 s memory lines). +COMMIT_LOW_S = 20.0 DEVICE_LOST = 0x887A0005 ANSI = re.compile(r"\x1b\[[0-9;]*m") @@ -271,6 +273,37 @@ def read_precompile(lines): return out +def since_end(rows, low): + """Seconds the last rows have all been `low`, from the first of them to the last row (0.0 if the last is not).""" + first = None + for row in reversed(rows): + if not low(row): + break + first = row[0] + return rows[-1][0] - first if first is not None else 0.0 + + +def memory_alarm(run): + """Why scripts/game-gate.ps1 must stop the run for memory now, or None, from the latest memory lines and the + limits it wrote in run.json (`memory_stop`; 0 turns one off).""" + limits = run.meta.get("memory_stop") or {} + private_max = limits.get("private_max_mb") or 0 + left_min = limits.get("commit_left_min_mb") or 0 + over_s = limits.get("over_budget_s") or 0 + if run.memory: + private = run.memory[-1][1] + if private_max and private > private_max: + return f"private bytes {private} MB, over {private_max} MB" + low = since_end(run.memory, lambda m: m[4] < left_min) if left_min else 0.0 + if low >= COMMIT_LOW_S: + return f"the PC had under {left_min} MB left to commit for {low:.0f} s" + if over_s and run.video: + over = since_end(run.video, lambda v: v[2] > v[1]) + if over >= over_s: + return f"video memory over its budget for {over:.0f} s" + return None + + def state(run): world = run.world_at() last = run.last_at @@ -282,6 +315,7 @@ def state(run): "frame_lines": len(run.frames), "relaunched": run.relaunched, "device_lost": any(c["kind"] == "device_lost" for c in run.crashes), + "memory_stop": memory_alarm(run), } @@ -394,13 +428,16 @@ def summary(run): fails.append("exited_before_stop") if fps["longest_present_gap_s"] is not None and fps["longest_present_gap_s"] > GAP_FAIL_S: fails.append("present_gap") + if reason == "memory": + # Stopped before memory ran out: the run was on its way to a crash, not short by choice. + fails.append("memory_stop") if run.relaunched: errors.append("relaunched") if run.event("game") is None and not run.frames: errors.append("not_started") - elif world is None: + elif world is None and reason != "memory": (errors if not exited_before_stop else fails).append("world_not_reached") - elif world_s < min_world: + elif world_s < min_world and reason != "memory": (errors if reason == "stop_file" else fails).append("stopped_early" if reason == "stop_file" else "world_time_short") if stop is not None and not alive and not fails and not errors: fails.append("not_alive_at_stop") @@ -436,7 +473,7 @@ def summary(run): }, "fps": fps, "pipelines": {"missed_waits": len(run.missed), "making_max": max((m for *_, m in run.frames), default=0)}, - "memory": memory_block(run), + "memory": dict(memory_block(run), stop_limits=run.meta.get("memory_stop")), "crash": { "kind": crash_kind, "at_s": round(first["at_s"], 3) if first and first["at_s"] is not None else None, @@ -450,7 +487,7 @@ def summary(run): "kind": ("device_lost" if code is not None and code & 0xFFFFFFFF == DEVICE_LOST else "killed" if killed else "clean" if code == 0 else "other" if code is not None else None)}, "stop": {"reason": reason, "killed": killed, "cache_saved": run.ended_at is not None if stop is not None else None, - "suspend": run.suspend}, + "suspend": run.suspend, "memory_why": (run.event("stop_requested") or {}).get("why")}, "relaunched": run.relaunched, "verdict": {"result": result, "reasons": fails + errors, "warnings": warnings, "min_world_s": min_world}, } From cb5bcfc2058e44cc4dea3197d6cf18d855f173ff Mon Sep 17 00:00:00 2001 From: TheGeogeo <57634077+TheGeogeo@users.noreply.github.com> Date: Tue, 1 Dec 2026 01:42:44 +0100 Subject: [PATCH 2/7] gate: the private-bytes stop also follows the PC's memory (review) With a large page file the commit limit is far above what a PC survives: two Windows crashes (0x10E) came at about 100 GB private on a PC with 64 GB of memory and a 175 GB limit, where 90 % of the limit is 158 GB. The default is now the lower of 90 % of the commit limit and 1.25 x the physical memory (80 GB there, 36 GB here); the video memory stop stays on by default. --- docs/game_gate.md | 2 +- scripts/game-gate.ps1 | 12 ++++++++---- tests/test_game_gate.py | 3 +++ 3 files changed, 12 insertions(+), 5 deletions(-) diff --git a/docs/game_gate.md b/docs/game_gate.md index 1178a5dc2b..2d5677e1e0 100644 --- a/docs/game_gate.md +++ b/docs/game_gate.md @@ -29,7 +29,7 @@ pwsh -NoProfile -File scripts\game-gate.ps1 stop -RunDir - **The caches.** `-Data` keeps its caches (`cache-2`); only the saves are copied. The first start after a translator change translates every shader again: run once before measuring. - **Ending the run.** It stops when the time in the world reaches `-WorldSeconds`, when a `STOP` file appears in the run folder (`stop`), or after `-MaxMinutes` (45). - **Memory stop.** It also stops the run, the same clean way and with the reason `memory`, before memory runs out. A memory pile-up has taken a PC's whole Windows down, not only the device. It reads the runtime's memory lines (every 5 s, builds with diagnostics) and stops when: - - the game's private bytes pass `-StopPrivateMB` (default: 90 % of this PC's commit limit); + - the game's private bytes pass `-StopPrivateMB` (default: the lower of 90 % of this PC's commit limit and 1.25 times its physical memory; with a large page file the limit is far above what a PC survives, and two Windows crashes came at about 100 GB private on a PC with 64 GB); - the PC has less than `-StopCommitLeftMB` left to commit for 20 s (default: the larger of 128 MB and 0.25 % of the limit; on a PC with no page file a normal run can leave a few hundred MB); - video memory stays over the system's budget for `-StopOverBudgetSeconds` (60). diff --git a/scripts/game-gate.ps1 b/scripts/game-gate.ps1 index 1192cd0960..b2a3c88c16 100644 --- a/scripts/game-gate.ps1 +++ b/scripts/game-gate.ps1 @@ -16,9 +16,10 @@ # -MaxMinutes; it kills the game only if it has not ended 60 s later. Exit code: 0 PASS, 1 FAIL, 2 ERROR. # Options: -WorldSeconds (300), -MaxMinutes (45), -More 'LEONIDA_X=1;LEONIDA_Y=2', -PlayArgs '-SeriesS -NoFrameGen'. # Memory stop (from the runtime's memory lines, every 5 s, builds with diagnostics): the run is stopped the same -# clean way, with the reason `memory`, when the game's private bytes pass -StopPrivateMB (90 % of this PC's commit -# limit), when the PC has less than -StopCommitLeftMB left to commit for 20 s (the larger of 128 MB and 0.25 % of -# the limit), or when video memory stays over the system's budget for -StopOverBudgetSeconds (60). 0 turns one off. +# clean way, with the reason `memory`, when the game's private bytes pass -StopPrivateMB (the lower of 90 % of this +# PC's commit limit and 1.25 x its memory), when the PC has less than -StopCommitLeftMB left to commit for 20 s +# (the larger of 128 MB and 0.25 % of the limit), or when video memory stays over the system's budget for +# -StopOverBudgetSeconds (60). 0 turns one off. param( [Parameter(Mandatory, Position = 0)][ValidateSet('run', 'start', 'stop')][string]$Verb, [string]$Game = '', @@ -151,7 +152,10 @@ $moreText # The memory stop's limits, from this PC's commit limit unless given (0 turns one off). On a PC with no page file a # normal run can leave a few hundred MB to commit: the floor is low and must hold for 20 s. $commitLimitMB = [math]::Floor((Get-CimInstance Win32_OperatingSystem).TotalVirtualMemorySize / 1KB) -if ($StopPrivateMB -lt 0) { $StopPrivateMB = [int]($commitLimitMB * 0.9) } +$physicalMB = [math]::Floor((Get-CimInstance Win32_ComputerSystem).TotalPhysicalMemory / 1MB) +# With a large page file the commit limit is far above what the PC survives: two Windows crashes (0x10E) came at +# about 100 GB private on a PC with 64 GB of memory and a 175 GB limit. So also no more than 1.25 x the memory. +if ($StopPrivateMB -lt 0) { $StopPrivateMB = [int][math]::Min($commitLimitMB * 0.9, $physicalMB * 1.25) } if ($StopCommitLeftMB -lt 0) { $StopCommitLeftMB = [int][math]::Max(128, $commitLimitMB * 0.0025) } $gpu = Get-CimInstance Win32_VideoController | Sort-Object { [uint64]$_.AdapterRAM } -Descending | Select-Object -First 1 [ordered]@{ diff --git a/tests/test_game_gate.py b/tests/test_game_gate.py index c73c2485df..8bba0d7562 100644 --- a/tests/test_game_gate.py +++ b/tests/test_game_gate.py @@ -381,6 +381,9 @@ def test_the_memory_stop_limits_reach_the_run_and_its_detached_start(self): # `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) self.assertIn("$stopReason = 'memory'", text) def test_no_variable_takes_a_parameters_name_in_another_case(self): From eac2b61d2f012c764c08eacda411ef76a5581d88 Mon Sep 17 00:00:00 2001 From: TheGeogeo <57634077+TheGeogeo@users.noreply.github.com> Date: Wed, 2 Dec 2026 02:52:41 +0100 Subject: [PATCH 3/7] gate: the world time comes before the memory stop, the commit floor tested at 20 s (review) A run that reached -WorldSeconds at the same poll as a memory limit was reported FAIL `memory_stop`. It is a measurement, and its memory peaks are in the summary all the same, so the supervisor now checks the target first. The poll's order is one function, Get-StopReason, which the test takes out of the script and puts to PowerShell 7 with synthetic polls. The commit floor's boundary is now tested at exactly 20 s, and the docs say what `stop.memory_why` holds: the gate's whole sentence. --- docs/game_gate.md | 4 ++-- scripts/game-gate.ps1 | 20 ++++++++++++------ tests/test_game_gate.py | 47 ++++++++++++++++++++++++++++++++++++++++- 3 files changed, 62 insertions(+), 9 deletions(-) diff --git a/docs/game_gate.md b/docs/game_gate.md index 2d5677e1e0..9f0722cfc4 100644 --- a/docs/game_gate.md +++ b/docs/game_gate.md @@ -33,7 +33,7 @@ pwsh -NoProfile -File scripts\game-gate.ps1 stop -RunDir - the PC has less than `-StopCommitLeftMB` left to commit for 20 s (default: the larger of 128 MB and 0.25 % of the limit; on a PC with no page file a normal run can leave a few hundred MB); - video memory stays over the system's budget for `-StopOverBudgetSeconds` (60). - 0 turns a limit off. The limits go into `run.json` (`memory_stop`) and the summary (`memory.stop_limits`). + 0 turns a limit off. The limits go into `run.json` (`memory_stop`) and the summary (`memory.stop_limits`). The gate checks every 5 s, and the world time comes first: a run that reaches `-WorldSeconds` at the same check as a limit stops with `target`. It is a measurement, and its memory peaks are in the summary all the same. - **How it stops.** With `WM_SYSCOMMAND`/`SC_CLOSE`, the runtime's own end: the title is suspended and the pipeline cache saved. It kills the game only if it has not ended 60 s later. - **Exit code.** 0 PASS, 1 FAIL, 2 ERROR. `start` exits when the detached run is created. @@ -68,7 +68,7 @@ Times are seconds since the run started. The summary holds numbers, switch names | `memory` | Peaks over the whole run, from the runtime's memory line and video memory line (every 5 s; builds with diagnostics only, otherwise `source` is null): the process's private bytes and when (`private_max_mb`, `private_max_at_s`), the most of them in physical memory, the least the PC had left to commit and when, the card's video memory in use at its most and when, with the budget the system gave then (`vram_in_use_max_mb`, `vram_max_at_s`, `vram_budget_at_max_mb`), the seconds spent over that budget, and the most of the PC's memory shared with the card in use. The video memory is what the system counts for this process, less than a tool like `nvidia-smi` shows for the whole card | | `crash` | `kind` is `none`, `device_lost`, `panic` or `fault`. It also gives the time, the code, the module kind (`runtime`, `title`, `driver`, `system`, `unknown`) and the access (read/write). `title_watchdog` marks a write at address 0 in the title more than 25 s after the last frame line. `count` is the number of crashes | | `exit` | The game's exit code, and its kind: `clean`, `device_lost` (0x887A0005), `killed` or `other` | -| `stop` | Why it was stopped (`target`, `stop_file`, `timeout`, `relaunched`, `memory` with the limit passed in `memory_why`), whether it was killed, whether the cache was saved, whether the suspend was in time | +| `stop` | Why it was stopped (`target`, `stop_file`, `timeout`, `relaunched` or `memory`), whether it was killed, whether the cache was saved, whether the suspend was in time. After a memory stop, `memory_why` is the gate's whole sentence for it, with its numbers: `private bytes 31000 MB, over 30000 MB`, `the PC had under 200 MB left to commit for 25 s` or `video memory over its budget for 60 s`, for example. It is null for the other reasons | | `verdict` | `result`, `reasons`, `warnings`, `min_world_s` | ## The verdict diff --git a/scripts/game-gate.ps1 b/scripts/game-gate.ps1 index b2a3c88c16..1a153a8ae5 100644 --- a/scripts/game-gate.ps1 +++ b/scripts/game-gate.ps1 @@ -19,7 +19,7 @@ # clean way, with the reason `memory`, when the game's private bytes pass -StopPrivateMB (the lower of 90 % of this # PC's commit limit and 1.25 x its memory), when the PC has less than -StopCommitLeftMB left to commit for 20 s # (the larger of 128 MB and 0.25 % of the limit), or when video memory stays over the system's budget for -# -StopOverBudgetSeconds (60). 0 turns one off. +# -StopOverBudgetSeconds (60). 0 turns one off. A run that reaches -WorldSeconds at the same poll stops with `target`. param( [Parameter(Mandatory, Position = 0)][ValidateSet('run', 'start', 'stop')][string]$Verb, [string]$Game = '', @@ -211,6 +211,16 @@ public static class GateWindow { '@ } +# Why this poll stops the run, or nothing. The target comes before the memory stop: a run that reached its world time +# in the same poll as a memory limit is a measurement, and its memory peaks are in the summary all the same. +function Get-StopReason($Poll, [bool]$StopFile, [double]$Minutes, [int]$TargetSeconds, [int]$LimitMinutes) { + if ($Poll.relaunched) { 'relaunched' } + elseif ($Poll.world_s -ge $TargetSeconds) { 'target' } + elseif ($Poll.memory_stop) { 'memory' } + elseif ($StopFile) { 'stop_file' } + elseif ($Minutes -ge $LimitMinutes) { 'timeout' } +} + $began = Get-Date $title = $null # the game process ($Game, the same name in any case, is its folder) $stopReason = $null @@ -229,11 +239,9 @@ while ($true) { if ($title -and $title.HasExited) { break } if (-not $title -and $launcher.HasExited) { break } $state = & $Python -I $tool state $RunDir | ConvertFrom-Json - if ($state.relaunched) { $stopReason = 'relaunched' } - elseif ($state.memory_stop) { $stopReason = 'memory'; $memoryWhy = $state.memory_stop } - elseif (Test-Path (Join-Path $RunDir 'STOP')) { $stopReason = 'stop_file' } - elseif ($state.world_s -ge $WorldSeconds) { $stopReason = 'target' } - elseif (((Get-Date) - $began).TotalMinutes -ge $MaxMinutes) { $stopReason = 'timeout' } + $stopReason = Get-StopReason -Poll $state -StopFile (Test-Path (Join-Path $RunDir 'STOP')) ` + -Minutes ((Get-Date) - $began).TotalMinutes -TargetSeconds $WorldSeconds -LimitMinutes $MaxMinutes + if ($stopReason -eq 'memory') { $memoryWhy = $state.memory_stop } if ($stopReason) { break } } diff --git a/tests/test_game_gate.py b/tests/test_game_gate.py index 8bba0d7562..bae6302bf1 100644 --- a/tests/test_game_gate.py +++ b/tests/test_game_gate.py @@ -257,6 +257,9 @@ def test_the_memory_stop_asks_for_a_stop_past_each_limit(self): 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(): @@ -384,7 +387,49 @@ def test_the_memory_stop_limits_reach_the_run_and_its_detached_start(self): # 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) - self.assertIn("$stopReason = 'memory'", 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"), + ({"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.assertEqual(text.count("$stopReason = "), 2) # set to $null before the loop, then only from the function + 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, From 01203fb3bf08de1b2bd019b00032514af1b07e66 Mon Sep 17 00:00:00 2001 From: TheGeogeo <57634077+TheGeogeo@users.noreply.github.com> Date: Wed, 2 Dec 2026 04:21:51 +0100 Subject: [PATCH 4/7] gate: a negative memory limit is off, and the poll's order tested in full (review) A negative -StopOverBudgetSeconds stopped every run at its first video memory line: 0 s over the budget passed a negative limit. Every limit is now off at 0 or less, with a test for each, and a line at exactly the private limit is tested not to stop. The poll test gets a memory limit at the time limit (memory wins), and the script text test checks the target and time limits the loop passes and that the memory stop's sentence reaches the stop event. The docs give the poll's whole order (a STOP file and the world time at the same check give `target`), say that `world_time_short` and `world_not_reached` are not added to `memory_stop`, and name `memory.stop_limits`. --- docs/game_gate.md | 8 ++++---- tests/test_game_gate.py | 14 ++++++++++++-- tools/game_gate.py | 8 ++++---- 3 files changed, 20 insertions(+), 10 deletions(-) diff --git a/docs/game_gate.md b/docs/game_gate.md index 9f0722cfc4..d0cf38cb0a 100644 --- a/docs/game_gate.md +++ b/docs/game_gate.md @@ -27,13 +27,13 @@ pwsh -NoProfile -File scripts\game-gate.ps1 stop -RunDir - **The play script's switches.** `-PlayArgs` passes them on as they are, for example `-SeriesS -NoFrameGen`. - **Reaching the world.** The gate does not drive the menus. Pass key presses with `LEONIDA_KEYS`; they are timed from the start of the process, so allow for the precompile. - **The caches.** `-Data` keeps its caches (`cache-2`); only the saves are copied. The first start after a translator change translates every shader again: run once before measuring. -- **Ending the run.** It stops when the time in the world reaches `-WorldSeconds`, when a `STOP` file appears in the run folder (`stop`), or after `-MaxMinutes` (45). +- **Ending the run.** It stops when the time in the world reaches `-WorldSeconds`, when a `STOP` file appears in the run folder (`stop`), or after `-MaxMinutes` (45). It checks every 5 s. When two reasons come at the same check, the first of these wins: the title relaunched, the world time (`target`), the memory stop (below), the `STOP` file, the time limit. So a `STOP` file and the world time at the same check give `target`. - **Memory stop.** It also stops the run, the same clean way and with the reason `memory`, before memory runs out. A memory pile-up has taken a PC's whole Windows down, not only the device. It reads the runtime's memory lines (every 5 s, builds with diagnostics) and stops when: - the game's private bytes pass `-StopPrivateMB` (default: the lower of 90 % of this PC's commit limit and 1.25 times its physical memory; with a large page file the limit is far above what a PC survives, and two Windows crashes came at about 100 GB private on a PC with 64 GB); - the PC has less than `-StopCommitLeftMB` left to commit for 20 s (default: the larger of 128 MB and 0.25 % of the limit; on a PC with no page file a normal run can leave a few hundred MB); - video memory stays over the system's budget for `-StopOverBudgetSeconds` (60). - 0 turns a limit off. The limits go into `run.json` (`memory_stop`) and the summary (`memory.stop_limits`). The gate checks every 5 s, and the world time comes first: a run that reaches `-WorldSeconds` at the same check as a limit stops with `target`. It is a measurement, and its memory peaks are in the summary all the same. + 0 turns a limit off. The limits go into `run.json` (`memory_stop`) and the summary (`memory.stop_limits`). A run that reaches `-WorldSeconds` at the same check as a limit stops with `target`: it is a measurement, and its memory peaks are in the summary all the same. - **How it stops.** With `WM_SYSCOMMAND`/`SC_CLOSE`, the runtime's own end: the title is suspended and the pipeline cache saved. It kills the game only if it has not ended 60 s later. - **Exit code.** 0 PASS, 1 FAIL, 2 ERROR. `start` exits when the detached run is created. @@ -65,7 +65,7 @@ Times are seconds since the run started. The summary holds numbers, switch names | `times.world_s` | Seconds from `world_at_s` to the stop request | | `fps` | From the presents, after the first 60 s in the world: frames, median, p5, frame p95 (ms), median of the last 60 s (`end_median`), the first second with fewer than 2 frames, from 60 s in the world on too (`under_2_at_s`), the longest gap with no frame presented from the world on (`longest_present_gap_s`, `longest_gap_at_s`; on purpose from the world on: a freeze on pipeline compiles comes right after arrival, and 10 s with no frame is what a player sees), draws a frame. Without the present lines (a build without diagnostics), the median and p5 come from the frame lines, with a warning | | `pipelines` | Waits that ran out (`missed_waits`), the most pipelines being made at once | -| `memory` | Peaks over the whole run, from the runtime's memory line and video memory line (every 5 s; builds with diagnostics only, otherwise `source` is null): the process's private bytes and when (`private_max_mb`, `private_max_at_s`), the most of them in physical memory, the least the PC had left to commit and when, the card's video memory in use at its most and when, with the budget the system gave then (`vram_in_use_max_mb`, `vram_max_at_s`, `vram_budget_at_max_mb`), the seconds spent over that budget, and the most of the PC's memory shared with the card in use. The video memory is what the system counts for this process, less than a tool like `nvidia-smi` shows for the whole card | +| `memory` | Peaks over the whole run, from the runtime's memory line and video memory line (every 5 s; builds with diagnostics only, otherwise `source` is null): the process's private bytes and when (`private_max_mb`, `private_max_at_s`), the most of them in physical memory, the least the PC had left to commit and when, the card's video memory in use at its most and when, with the budget the system gave then (`vram_in_use_max_mb`, `vram_max_at_s`, `vram_budget_at_max_mb`), the seconds spent over that budget, and the most of the PC's memory shared with the card in use. The video memory is what the system counts for this process, less than a tool like `nvidia-smi` shows for the whole card. `stop_limits` holds the memory stop's limits from `run.json` (null from a gate without the memory stop) | | `crash` | `kind` is `none`, `device_lost`, `panic` or `fault`. It also gives the time, the code, the module kind (`runtime`, `title`, `driver`, `system`, `unknown`) and the access (read/write). `title_watchdog` marks a write at address 0 in the title more than 25 s after the last frame line. `count` is the number of crashes | | `exit` | The game's exit code, and its kind: `clean`, `device_lost` (0x887A0005), `killed` or `other` | | `stop` | Why it was stopped (`target`, `stop_file`, `timeout`, `relaunched` or `memory`), whether it was killed, whether the cache was saved, whether the suspend was in time. After a memory stop, `memory_why` is the gate's whole sentence for it, with its numbers: `private bytes 31000 MB, over 30000 MB`, `the PC had under 200 MB left to commit for 25 s` or `video memory over its budget for 60 s`, for example. It is null for the other reasons | @@ -87,7 +87,7 @@ Times are seconds since the run started. The summary holds numbers, switch names - `exited_before_stop`; - `present_gap`; - `world_time_short`: the time limit came first; -- `memory_stop`: the memory stop ended the run, which was on its way to running out; +- `memory_stop`: the memory stop ended the run, which was on its way to running out. `world_time_short` and `world_not_reached` are not added to it: the stop is why the run was short; - `not_alive_at_stop`; - `world_not_reached`, when the game ended before reaching the world. diff --git a/tests/test_game_gate.py b/tests/test_game_gate.py index bae6302bf1..23cfbabea8 100644 --- a/tests/test_game_gate.py +++ b/tests/test_game_gate.py @@ -264,13 +264,17 @@ def test_the_memory_stop_asks_for_a_stop_past_each_limit(self): } for why, rows in cases.items(): self.assertEqual(self.memory_run(limits, rows).state()["memory_stop"], why) - # Under each limit, or not for long enough: no stop. - for rows in (calm, calm + [(24000, 7000, 150)] * 4, calm + [(24000, 9000, 3000)] * 12): + # 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} @@ -401,6 +405,9 @@ def test_the_memory_stop_limits_reach_the_run_and_its_detached_start(self): ({"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"), ] @@ -410,7 +417,10 @@ def test_a_poll_stops_for_the_target_before_the_memory_stop(self): 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") diff --git a/tools/game_gate.py b/tools/game_gate.py index 0c9772c280..c2748cde8f 100644 --- a/tools/game_gate.py +++ b/tools/game_gate.py @@ -285,19 +285,19 @@ def since_end(rows, low): def memory_alarm(run): """Why scripts/game-gate.ps1 must stop the run for memory now, or None, from the latest memory lines and the - limits it wrote in run.json (`memory_stop`; 0 turns one off).""" + limits it wrote in run.json (`memory_stop`; 0 or less turns one off).""" limits = run.meta.get("memory_stop") or {} private_max = limits.get("private_max_mb") or 0 left_min = limits.get("commit_left_min_mb") or 0 over_s = limits.get("over_budget_s") or 0 if run.memory: private = run.memory[-1][1] - if private_max and private > private_max: + if private_max > 0 and private > private_max: return f"private bytes {private} MB, over {private_max} MB" - low = since_end(run.memory, lambda m: m[4] < left_min) if left_min else 0.0 + low = since_end(run.memory, lambda m: m[4] < left_min) if left_min > 0 else 0.0 if low >= COMMIT_LOW_S: return f"the PC had under {left_min} MB left to commit for {low:.0f} s" - if over_s and run.video: + if over_s > 0 and run.video: over = since_end(run.video, lambda v: v[2] > v[1]) if over >= over_s: return f"video memory over its budget for {over:.0f} s" From 7150b7fe0c06488a99239cdfd65477f352c0c54f Mon Sep 17 00:00:00 2001 From: TheGeogeo <57634077+TheGeogeo@users.noreply.github.com> Date: Tue, 1 Dec 2026 01:45:30 +0100 Subject: [PATCH 5/7] gate: memory.csv and a pile-up's numbers beside the summary (D3D12-GATE-MEMORY-SERIES) Testers read a pile-up by its slope and by the reaper's queue, which the summary's peaks do not show. The parser now also reads the runtime's census line written with each memory line (objects let go that wait for their submissions, and the reaper thread's queue) and writes memory.csv beside summary.json: one row per memory line with the private bytes, the PC's memory free and left to commit, the card's video memory budget and in use, the shared memory in use and the two queues. The summary's memory block gets the reaper queue at its longest and when, the most objects waiting, and the least-squares slope of the private bytes in the world (MB a minute). The census strings join the contract test. --- docs/game_gate.md | 3 +- tests/test_game_gate.py | 37 +++++++++++++++++-- tools/game_gate.py | 80 ++++++++++++++++++++++++++++++++++++++--- 3 files changed, 113 insertions(+), 7 deletions(-) diff --git a/docs/game_gate.md b/docs/game_gate.md index d0cf38cb0a..049c52b693 100644 --- a/docs/game_gate.md +++ b/docs/game_gate.md @@ -50,6 +50,7 @@ The run folder (under `-RunRoot`, by default `\gate-runs`, refused inside | `events.jsonl` | What the gate did and saw: the game found, the stop asked for and why, a kill, the exit code | | `data\` | The run's copy of the template, and the runtime's `crashes.log` | | `summary.json` | The result, below | +| `memory.csv` | One row per runtime memory line (every 5 s, builds with diagnostics): time, private bytes, of them in physical memory, the PC's memory free and left to commit, the card's video memory budget and in use, the shared memory in use, the objects let go that wait for their submissions, and the reaper thread's queue. Only when the run has memory lines | ## summary.json (`leonida-gate-summary/1`) @@ -65,7 +66,7 @@ Times are seconds since the run started. The summary holds numbers, switch names | `times.world_s` | Seconds from `world_at_s` to the stop request | | `fps` | From the presents, after the first 60 s in the world: frames, median, p5, frame p95 (ms), median of the last 60 s (`end_median`), the first second with fewer than 2 frames, from 60 s in the world on too (`under_2_at_s`), the longest gap with no frame presented from the world on (`longest_present_gap_s`, `longest_gap_at_s`; on purpose from the world on: a freeze on pipeline compiles comes right after arrival, and 10 s with no frame is what a player sees), draws a frame. Without the present lines (a build without diagnostics), the median and p5 come from the frame lines, with a warning | | `pipelines` | Waits that ran out (`missed_waits`), the most pipelines being made at once | -| `memory` | Peaks over the whole run, from the runtime's memory line and video memory line (every 5 s; builds with diagnostics only, otherwise `source` is null): the process's private bytes and when (`private_max_mb`, `private_max_at_s`), the most of them in physical memory, the least the PC had left to commit and when, the card's video memory in use at its most and when, with the budget the system gave then (`vram_in_use_max_mb`, `vram_max_at_s`, `vram_budget_at_max_mb`), the seconds spent over that budget, and the most of the PC's memory shared with the card in use. The video memory is what the system counts for this process, less than a tool like `nvidia-smi` shows for the whole card. `stop_limits` holds the memory stop's limits from `run.json` (null from a gate without the memory stop) | +| `memory` | Peaks over the whole run, from the runtime's memory line and video memory line (every 5 s; builds with diagnostics only, otherwise `source` is null): the process's private bytes and when (`private_max_mb`, `private_max_at_s`), the most of them in physical memory, the least the PC had left to commit and when, the card's video memory in use at its most and when, with the budget the system gave then (`vram_in_use_max_mb`, `vram_max_at_s`, `vram_budget_at_max_mb`), the seconds spent over that budget, and the most of the PC's memory shared with the card in use. The video memory is what the system counts for this process, less than a tool like `nvidia-smi` shows for the whole card. `stop_limits` holds the memory stop's limits from `run.json` (null from a gate without the memory stop). Also the reaper thread's queue at its longest and when (`reaper_queue_max`), the most objects waiting for their submissions, and how fast the private bytes grew in the world in MB a minute (`private_mb_per_min_in_world`, a least-squares slope: on a short run it is the loading's climb, on a long one a pile-up's slope), and `series`: the name of `memory.csv` | | `crash` | `kind` is `none`, `device_lost`, `panic` or `fault`. It also gives the time, the code, the module kind (`runtime`, `title`, `driver`, `system`, `unknown`) and the access (read/write). `title_watchdog` marks a write at address 0 in the title more than 25 s after the last frame line. `count` is the number of crashes | | `exit` | The game's exit code, and its kind: `clean`, `device_lost` (0x887A0005), `killed` or `other` | | `stop` | Why it was stopped (`target`, `stop_file`, `timeout`, `relaunched` or `memory`), whether it was killed, whether the cache was saved, whether the suspend was in time. After a memory stop, `memory_why` is the gate's whole sentence for it, with its numbers: `private bytes 31000 MB, over 30000 MB`, `the PC had under 200 MB left to commit for 25 s` or `video memory over its budget for 60 s`, for example. It is null for the other reasons | diff --git a/tests/test_game_gate.py b/tests/test_game_gate.py index 23cfbabea8..58da38ea5e 100644 --- a/tests/test_game_gate.py +++ b/tests/test_game_gate.py @@ -1,6 +1,9 @@ """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 @@ -50,8 +53,12 @@ def frames(self, start, end, fps, draws, making=0, dropped=0, step=1.0, presents 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): - """The runtime's video memory line and memory line, as a diagnostics build writes them every 5 s.""" + 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)") 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 " @@ -298,12 +305,38 @@ def test_a_run_stopped_for_memory_fails_with_its_reason(self): 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 i, t in enumerate(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") + def test_a_build_without_memory_lines_gives_no_memory_peaks(self): m = passing().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"]) def test_without_present_lines_the_frame_lines_give_the_rate(self): f = Fake() diff --git a/tools/game_gate.py b/tools/game_gate.py index c2748cde8f..076c571754 100644 --- a/tools/game_gate.py +++ b/tools/game_gate.py @@ -8,6 +8,7 @@ numbers, switch names and verdicts only: no path, no user or machine name, nothing the title printed. Schema and rules: docs/game_gate.md. """ +import csv import datetime as dt import glob import json @@ -51,6 +52,14 @@ r"left to commit\)") VIDEO = re.compile(r"^video memory as the system counts it, [^:]*: the card's own: budget (\d+) MB, in use (\d+) MB, " r".*?; the PC's shared with the card: budget (\d+) MB, in use (\d+) MB") +# The census line with them: objects let go that wait for their submissions, and those handed to the reaper thread +# and not let go yet (the reaper's queue, the number a pile-up shows first). +WAITS = re.compile(r"^memory, what waits to be let go: (\d+) objects let go that wait for the submissions that may use " + r"them \(LEONIDA_BURY_LAG\), (\d+) retired objects, landed host lists and lists' fronts handed to the " + r"thread that lets them go") +SERIES = "memory.csv" +SERIES_COLUMNS = ("t_s", "private_mb", "in_memory_mb", "pc_free_mb", "pc_commit_left_mb", "vram_budget_mb", + "vram_in_use_mb", "shared_in_use_mb", "waiting_objects", "reaper_queue") # The runtime's own words this parser reads, and where they are written: tests/test_game_gate.py checks that # each is still there, so a reworded line fails the test, not the next gate. @@ -78,6 +87,11 @@ "d3d12/crates/leonida-gpu/src/host.rs", "the PC's shared with the card: budget {} MB, in use {} MB": "d3d12/crates/leonida-gpu/src/host.rs", 'h.log_video_memory("with the memory line")': "d3d12/crates/leonida-gpu/src/copystat.rs", + "memory, what waits to be let go: {waiting} objects let go that wait for the submissions that may use them " + "(LEONIDA_BURY_LAG)": "d3d12/crates/leonida-gpu/src/census.rs", + "{handed} retired objects, landed host lists and lists' fronts handed to the thread that lets them go": + "d3d12/crates/leonida-gpu/src/census.rs", + "crate::census::log();": "d3d12/crates/leonida-gpu/src/copystat.rs", } @@ -126,6 +140,7 @@ def __init__(self, folder): self.missed = [] # t of each pipeline not made within its wait self.memory = [] # (t, private MB, in memory MB, PC free MB, PC left to commit MB) self.video = [] # (t, card budget MB, card in use MB, shared budget MB, shared in use MB) + self.waits = [] # (t, objects waiting for their submissions, the reaper's queue) self.settings = None # from the runtime's settings line self.suspend = None self.ended_at = None @@ -157,6 +172,8 @@ def read_log(self, lines): self.memory.append((t,) + tuple(int(x) for x in MEMORY.match(text).groups())) elif text.startswith("video memory as the system counts it") and VIDEO.match(text): self.video.append((t,) + tuple(int(x) for x in VIDEO.match(text).groups())) + elif text.startswith("memory, what waits to be let go") and WAITS.match(text): + self.waits.append((t,) + tuple(int(x) for x in WAITS.match(text).groups())) elif text.startswith("a pipeline not made within its wait"): self.missed.append(t) elif target == "settings": @@ -368,12 +385,66 @@ def fps_block(run, world, end): return out -def memory_block(run): - """Peaks of the runtime's memory lines over the whole run (none from a build without diagnostics).""" +def slope_per_min(points): + """Least-squares slope of (t in s, value) points, per minute; None under 3 points or with no time spread.""" + if len(points) < 3: + return None + mt = sum(t for t, _ in points) / len(points) + mv = sum(v for _, v in points) / len(points) + spread = sum((t - mt) ** 2 for t, _ in points) + if spread == 0: + return None + return 60.0 * sum((t - mt) * (v - mv) for t, v in points) / spread + + +def near(rows, t, within=2.0): + """The row of `rows` (sorted by time) nearest to t, if within `within` seconds.""" + best = min(rows, key=lambda r: abs(r[0] - t), default=None) + return best if best is not None and abs(best[0] - t) <= within else None + + +def memory_rows(run): + """One row per memory line, with the video memory and census lines written with it (`memory.csv`).""" + rows = [] + for t, private, in_memory, free, left in run.memory: + v = near(run.video, t) + w = near(run.waits, t) + rows.append({"t_s": round(t, 3), "private_mb": private, "in_memory_mb": in_memory, "pc_free_mb": free, + "pc_commit_left_mb": left, "vram_budget_mb": v[1] if v else None, + "vram_in_use_mb": v[2] if v else None, "shared_in_use_mb": v[4] if v else None, + "waiting_objects": w[1] if w else None, "reaper_queue": w[2] if w else None}) + return rows + + +def write_series(run, folder): + """Writes memory.csv beside summary.json when the run has memory lines; returns its name or None.""" + rows = memory_rows(run) + if not rows: + return None + with open(os.path.join(folder, SERIES), "w", encoding="utf-8", newline="") as f: + out = csv.DictWriter(f, fieldnames=SERIES_COLUMNS, lineterminator="\n") + out.writeheader() + out.writerows(rows) + return SERIES + + +def memory_block(run, world=None): + """Peaks of the runtime's memory lines over the whole run (none from a build without diagnostics), the + reaper's queue at its longest, and how fast the private bytes grew in the world (a pile-up's slope).""" out = {"source": None, "lines": 0, "private_max_mb": None, "private_max_at_s": None, "in_memory_max_mb": None, "pc_commit_left_min_mb": None, "pc_commit_left_min_at_s": None, "vram_in_use_max_mb": None, "vram_max_at_s": None, "vram_budget_at_max_mb": None, "vram_over_budget_s": None, - "shared_in_use_max_mb": None} + "shared_in_use_max_mb": None, "reaper_queue_max": None, "reaper_queue_max_at_s": None, + "waiting_objects_max": None, "private_mb_per_min_in_world": None, "series": None} + if run.waits: + t, queue = max(((w[0], w[2]) for w in run.waits), key=lambda x: x[1]) + out["reaper_queue_max"], out["reaper_queue_max_at_s"] = queue, round(t, 3) + out["waiting_objects_max"] = max(w[1] for w in run.waits) + if run.memory and world is not None: + slope = slope_per_min([(m[0], m[1]) for m in run.memory if m[0] >= world]) + out["private_mb_per_min_in_world"] = round(slope, 1) if slope is not None else None + if run.memory: + out["series"] = SERIES if run.memory: out["source"], out["lines"] = "memory lines", len(run.memory) t, private = max(((t, p) for t, p, *_ in run.memory), key=lambda x: x[1]) @@ -473,7 +544,7 @@ def summary(run): }, "fps": fps, "pipelines": {"missed_waits": len(run.missed), "making_max": max((m for *_, m in run.frames), default=0)}, - "memory": dict(memory_block(run), stop_limits=run.meta.get("memory_stop")), + "memory": dict(memory_block(run, world), stop_limits=run.meta.get("memory_stop")), "crash": { "kind": crash_kind, "at_s": round(first["at_s"], 3) if first and first["at_s"] is not None else None, @@ -502,6 +573,7 @@ def main(argv): print(json.dumps(state(run))) return 0 out = summary(run) + write_series(run, argv[2]) with open(os.path.join(argv[2], "summary.json"), "w", encoding="utf-8", newline="\n") as f: json.dump(out, f, indent=2) f.write("\n") From bb6ff131273a9782c3ac7cb7c24bcfd5dd7a48d5 Mon Sep 17 00:00:00 2001 From: TheGeogeo <57634077+TheGeogeo@users.noreply.github.com> Date: Wed, 2 Dec 2026 02:55:26 +0100 Subject: [PATCH 6/7] gate: no stale memory.csv, and the docs say what the series holds (review) `write_series` returned before an older memory.csv was touched, so a folder summarized again from a log without memory lines kept old rows beside `series: null`: it now removes that file. Two tests go through `main()`: no memory lines writes no file, and an older file goes. The docs list the CSV header, how its video memory and census columns are picked (the nearest line within 2 s), `reaper_queue_max_at_s` and `waiting_objects_max`, and that the summary's video memory peak counts every video memory line, the swap chain's too, so it can come from a line with no row in the CSV. "Not in this version" no longer lists the time series and the VRAM and RAM peaks. The census line's fixture is the runtime's sentence as it is now, with the reaper's bound (LEONIDA_REAPER_LIMIT) at its end; the part the parser reads did not change. --- docs/game_gate.md | 6 ++---- tests/test_game_gate.py | 24 ++++++++++++++++++++++-- tools/game_gate.py | 8 ++++++-- 3 files changed, 30 insertions(+), 8 deletions(-) diff --git a/docs/game_gate.md b/docs/game_gate.md index 049c52b693..4eb842ec2f 100644 --- a/docs/game_gate.md +++ b/docs/game_gate.md @@ -50,7 +50,7 @@ The run folder (under `-RunRoot`, by default `\gate-runs`, refused inside | `events.jsonl` | What the gate did and saw: the game found, the stop asked for and why, a kill, the exit code | | `data\` | The run's copy of the template, and the runtime's `crashes.log` | | `summary.json` | The result, below | -| `memory.csv` | One row per runtime memory line (every 5 s, builds with diagnostics): time, private bytes, of them in physical memory, the PC's memory free and left to commit, the card's video memory budget and in use, the shared memory in use, the objects let go that wait for their submissions, and the reaper thread's queue. Only when the run has memory lines | +| `memory.csv` | One row per runtime memory line (every 5 s, builds with diagnostics): time, private bytes, of them in physical memory, the PC's memory free and left to commit, the card's video memory budget and in use, the shared memory in use, the objects let go that wait for their submissions, and the reaper thread's queue. Its header is `t_s,private_mb,in_memory_mb,pc_free_mb,pc_commit_left_mb,vram_budget_mb,vram_in_use_mb,shared_in_use_mb,waiting_objects,reaper_queue`. The video memory columns come from the video memory line nearest the memory line, and the last two from the census line nearest it, each within 2 s; a cell is empty when there is none. Only when the run has memory lines: a summary made again from a log without them removes an older `memory.csv` | ## summary.json (`leonida-gate-summary/1`) @@ -66,7 +66,7 @@ Times are seconds since the run started. The summary holds numbers, switch names | `times.world_s` | Seconds from `world_at_s` to the stop request | | `fps` | From the presents, after the first 60 s in the world: frames, median, p5, frame p95 (ms), median of the last 60 s (`end_median`), the first second with fewer than 2 frames, from 60 s in the world on too (`under_2_at_s`), the longest gap with no frame presented from the world on (`longest_present_gap_s`, `longest_gap_at_s`; on purpose from the world on: a freeze on pipeline compiles comes right after arrival, and 10 s with no frame is what a player sees), draws a frame. Without the present lines (a build without diagnostics), the median and p5 come from the frame lines, with a warning | | `pipelines` | Waits that ran out (`missed_waits`), the most pipelines being made at once | -| `memory` | Peaks over the whole run, from the runtime's memory line and video memory line (every 5 s; builds with diagnostics only, otherwise `source` is null): the process's private bytes and when (`private_max_mb`, `private_max_at_s`), the most of them in physical memory, the least the PC had left to commit and when, the card's video memory in use at its most and when, with the budget the system gave then (`vram_in_use_max_mb`, `vram_max_at_s`, `vram_budget_at_max_mb`), the seconds spent over that budget, and the most of the PC's memory shared with the card in use. The video memory is what the system counts for this process, less than a tool like `nvidia-smi` shows for the whole card. `stop_limits` holds the memory stop's limits from `run.json` (null from a gate without the memory stop). Also the reaper thread's queue at its longest and when (`reaper_queue_max`), the most objects waiting for their submissions, and how fast the private bytes grew in the world in MB a minute (`private_mb_per_min_in_world`, a least-squares slope: on a short run it is the loading's climb, on a long one a pile-up's slope), and `series`: the name of `memory.csv` | +| `memory` | Peaks over the whole run, from the runtime's memory line and video memory line (every 5 s; builds with diagnostics only, otherwise `source` is null): the process's private bytes and when (`private_max_mb`, `private_max_at_s`), the most of them in physical memory, the least the PC had left to commit and when, the card's video memory in use at its most and when, with the budget the system gave then (`vram_in_use_max_mb`, `vram_max_at_s`, `vram_budget_at_max_mb`), the seconds spent over that budget, and the most of the PC's memory shared with the card in use. The video memory is what the system counts for this process, less than a tool like `nvidia-smi` shows for the whole card. `stop_limits` holds the memory stop's limits from `run.json` (null from a gate without the memory stop). Also, from the runtime's census line, the reaper thread's queue at its longest and when (`reaper_queue_max`, `reaper_queue_max_at_s`) and the most objects let go that wait for their submissions (`waiting_objects_max`); how fast the private bytes grew in the world in MB a minute (`private_mb_per_min_in_world`, a least-squares slope: on a short run it is the loading's climb, on a long one a pile-up's slope); and `series`, the name of `memory.csv` (null without memory lines). The video memory peak and the time over the budget count every video memory line, the ones the runtime writes when it makes the swap chain too. `memory.csv` has only the one nearest each memory line, so the summary's peak can come from a line with no row there | | `crash` | `kind` is `none`, `device_lost`, `panic` or `fault`. It also gives the time, the code, the module kind (`runtime`, `title`, `driver`, `system`, `unknown`) and the access (read/write). `title_watchdog` marks a write at address 0 in the title more than 25 s after the last frame line. `count` is the number of crashes | | `exit` | The game's exit code, and its kind: `clean`, `device_lost` (0x887A0005), `killed` or `other` | | `stop` | Why it was stopped (`target`, `stop_file`, `timeout`, `relaunched` or `memory`), whether it was killed, whether the cache was saved, whether the suspend was in time. After a memory stop, `memory_why` is the gate's whole sentence for it, with its numbers: `private bytes 31000 MB, over 30000 MB`, `the PC had under 200 MB left to commit for 25 s` or `video memory over its budget for 60 s`, for example. It is null for the other reasons | @@ -104,8 +104,6 @@ A crash after the stop request is a warning, except a device loss or a panic, wh - A driver for the menus and a fixed route (a Lua mod). - An ABBA runner over several runs. -- A time series beside the summary (memory, census, reaping queue). - A "memory rising" warning. -- VRAM and RAM peaks. - The distance walked. - The Vulkan runtime (`gta6rt`). diff --git a/tests/test_game_gate.py b/tests/test_game_gate.py index 58da38ea5e..ddfd4fbe9a 100644 --- a/tests/test_game_gate.py +++ b/tests/test_game_gate.py @@ -58,7 +58,9 @@ def memory(self, t, private, used, budget=8000, left=3000, shared=500, waiting=0 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)") + 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 " @@ -329,7 +331,8 @@ def test_the_memory_series_and_a_pile_ups_slope(self): self.assertEqual(rows[-1]["vram_in_use_mb"], "7000") def test_a_build_without_memory_lines_gives_no_memory_peaks(self): - m = passing().summarize()["memory"] + f = passing() + m = f.summarize()["memory"] self.assertIsNone(m["source"]) self.assertEqual(m["lines"], 0) self.assertIsNone(m["private_max_mb"]) @@ -337,6 +340,23 @@ def test_a_build_without_memory_lines_gives_no_memory_peaks(self): 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() diff --git a/tools/game_gate.py b/tools/game_gate.py index 076c571754..d567c46fa6 100644 --- a/tools/game_gate.py +++ b/tools/game_gate.py @@ -417,11 +417,15 @@ def memory_rows(run): def write_series(run, folder): - """Writes memory.csv beside summary.json when the run has memory lines; returns its name or None.""" + """Writes memory.csv beside summary.json when the run has memory lines; returns its name or None. Without them + it removes a memory.csv already there (a folder summarized again), so no old rows sit beside `series: null`.""" + path = os.path.join(folder, SERIES) rows = memory_rows(run) if not rows: + if os.path.exists(path): + os.remove(path) return None - with open(os.path.join(folder, SERIES), "w", encoding="utf-8", newline="") as f: + with open(path, "w", encoding="utf-8", newline="") as f: out = csv.DictWriter(f, fieldnames=SERIES_COLUMNS, lineterminator="\n") out.writeheader() out.writerows(rows) From 0e5ebd0c697d62fcac20adeb60b38044ec8b96c1 Mon Sep 17 00:00:00 2001 From: TheGeogeo <57634077+TheGeogeo@users.noreply.github.com> Date: Wed, 2 Dec 2026 04:25:39 +0100 Subject: [PATCH 7/7] gate: the summary even when memory.csv cannot be written, the slope up to the stop (review) `summary` wrote memory.csv before summary.json, so a memory.csv open in another program left no summary and exit 1. A file it cannot write or remove is now said on stderr, `series` is null and summary.json is written. The private bytes' slope counted the memory lines written while the title ends after the stop request; it now covers the world up to the stop, as the frame rates do. New tests: the 2 s window and the empty cells of memory.csv, its LF line ends, the slope with lines after the stop and with fewer than 3 lines in the world, and a memory.csv that cannot be written. The census sentence's contract is one key over the whole part WAITS reads, the ", " between its two numbers too. The docs name every video memory line the peak counts (the swap chain made, its buffers made again, a budget change of 256 MB or more) and when the slope and `series` are null. --- docs/game_gate.md | 2 +- tests/test_game_gate.py | 65 ++++++++++++++++++++++++++++++++++++++++- tools/game_gate.py | 40 ++++++++++++++----------- 3 files changed, 88 insertions(+), 19 deletions(-) diff --git a/docs/game_gate.md b/docs/game_gate.md index 4eb842ec2f..ec6e3eece5 100644 --- a/docs/game_gate.md +++ b/docs/game_gate.md @@ -66,7 +66,7 @@ Times are seconds since the run started. The summary holds numbers, switch names | `times.world_s` | Seconds from `world_at_s` to the stop request | | `fps` | From the presents, after the first 60 s in the world: frames, median, p5, frame p95 (ms), median of the last 60 s (`end_median`), the first second with fewer than 2 frames, from 60 s in the world on too (`under_2_at_s`), the longest gap with no frame presented from the world on (`longest_present_gap_s`, `longest_gap_at_s`; on purpose from the world on: a freeze on pipeline compiles comes right after arrival, and 10 s with no frame is what a player sees), draws a frame. Without the present lines (a build without diagnostics), the median and p5 come from the frame lines, with a warning | | `pipelines` | Waits that ran out (`missed_waits`), the most pipelines being made at once | -| `memory` | Peaks over the whole run, from the runtime's memory line and video memory line (every 5 s; builds with diagnostics only, otherwise `source` is null): the process's private bytes and when (`private_max_mb`, `private_max_at_s`), the most of them in physical memory, the least the PC had left to commit and when, the card's video memory in use at its most and when, with the budget the system gave then (`vram_in_use_max_mb`, `vram_max_at_s`, `vram_budget_at_max_mb`), the seconds spent over that budget, and the most of the PC's memory shared with the card in use. The video memory is what the system counts for this process, less than a tool like `nvidia-smi` shows for the whole card. `stop_limits` holds the memory stop's limits from `run.json` (null from a gate without the memory stop). Also, from the runtime's census line, the reaper thread's queue at its longest and when (`reaper_queue_max`, `reaper_queue_max_at_s`) and the most objects let go that wait for their submissions (`waiting_objects_max`); how fast the private bytes grew in the world in MB a minute (`private_mb_per_min_in_world`, a least-squares slope: on a short run it is the loading's climb, on a long one a pile-up's slope); and `series`, the name of `memory.csv` (null without memory lines). The video memory peak and the time over the budget count every video memory line, the ones the runtime writes when it makes the swap chain too. `memory.csv` has only the one nearest each memory line, so the summary's peak can come from a line with no row there | +| `memory` | Peaks over the whole run, from the runtime's memory line and video memory line (every 5 s; builds with diagnostics only, otherwise `source` is null): the process's private bytes and when (`private_max_mb`, `private_max_at_s`), the most of them in physical memory, the least the PC had left to commit and when, the card's video memory in use at its most and when, with the budget the system gave then (`vram_in_use_max_mb`, `vram_max_at_s`, `vram_budget_at_max_mb`), the seconds spent over that budget, and the most of the PC's memory shared with the card in use. The video memory is what the system counts for this process, less than a tool like `nvidia-smi` shows for the whole card. `stop_limits` holds the memory stop's limits from `run.json` (null from a gate without the memory stop). Also, from the runtime's census line, the reaper thread's queue at its longest and when (`reaper_queue_max`, `reaper_queue_max_at_s`) and the most objects let go that wait for their submissions (`waiting_objects_max`); how fast the private bytes grew in the world in MB a minute (`private_mb_per_min_in_world`, a least-squares slope over the memory lines from `world_at_s` to the stop request: on a short run it is the loading's climb, on a long one a pile-up's slope; null with fewer than 3 lines there); and `series`, the name of `memory.csv` (null without memory lines, or when the file could not be written, for example open in another program: `game_gate.py` says so on stderr and writes `summary.json` all the same). The video memory peak and the time over the budget count every video memory line: the one written with each memory line, and the ones the runtime writes right before and after it makes the swap chain, right after the swap chain's buffers are made again for another size or format, and right after the system changes the card's budget by 256 MB or more. `memory.csv` has only the one nearest each memory line, so the summary's peak can come from a line with no row there | | `crash` | `kind` is `none`, `device_lost`, `panic` or `fault`. It also gives the time, the code, the module kind (`runtime`, `title`, `driver`, `system`, `unknown`) and the access (read/write). `title_watchdog` marks a write at address 0 in the title more than 25 s after the last frame line. `count` is the number of crashes | | `exit` | The game's exit code, and its kind: `clean`, `device_lost` (0x887A0005), `killed` or `other` | | `stop` | Why it was stopped (`target`, `stop_file`, `timeout`, `relaunched` or `memory`), whether it was killed, whether the cache was saved, whether the suspend was in time. After a memory stop, `memory_why` is the gate's whole sentence for it, with its numbers: `private bytes 31000 MB, over 30000 MB`, `the PC had under 200 MB left to commit for 25 s` or `video memory over its budget for 60 s`, for example. It is null for the other reasons | diff --git a/tests/test_game_gate.py b/tests/test_game_gate.py index ddfd4fbe9a..b842660f94 100644 --- a/tests/test_game_gate.py +++ b/tests/test_game_gate.py @@ -309,7 +309,7 @@ def test_a_run_stopped_for_memory_fails_with_its_reason(self): def test_the_memory_series_and_a_pile_ups_slope(self): f = passing() - for i, t in enumerate(range(10, 390, 5)): + 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) @@ -329,6 +329,69 @@ def test_the_memory_series_and_a_pile_ups_slope(self): 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() diff --git a/tools/game_gate.py b/tools/game_gate.py index d567c46fa6..b88ec95356 100644 --- a/tools/game_gate.py +++ b/tools/game_gate.py @@ -87,10 +87,10 @@ "d3d12/crates/leonida-gpu/src/host.rs", "the PC's shared with the card: budget {} MB, in use {} MB": "d3d12/crates/leonida-gpu/src/host.rs", 'h.log_video_memory("with the memory line")': "d3d12/crates/leonida-gpu/src/copystat.rs", + # One key over the whole part WAITS reads, the ", " between its two numbers too. "memory, what waits to be let go: {waiting} objects let go that wait for the submissions that may use them " - "(LEONIDA_BURY_LAG)": "d3d12/crates/leonida-gpu/src/census.rs", - "{handed} retired objects, landed host lists and lists' fronts handed to the thread that lets them go": - "d3d12/crates/leonida-gpu/src/census.rs", + "(LEONIDA_BURY_LAG), {handed} retired objects, landed host lists and lists' fronts handed to the thread that " + "lets them go": "d3d12/crates/leonida-gpu/src/census.rs", "crate::census::log();": "d3d12/crates/leonida-gpu/src/copystat.rs", } @@ -418,23 +418,29 @@ def memory_rows(run): def write_series(run, folder): """Writes memory.csv beside summary.json when the run has memory lines; returns its name or None. Without them - it removes a memory.csv already there (a folder summarized again), so no old rows sit beside `series: null`.""" + it removes a memory.csv already there (a folder summarized again), so no old rows sit beside `series: null`. + A file it cannot write or remove (open in another program) is said on stderr: the summary is written anyway.""" path = os.path.join(folder, SERIES) rows = memory_rows(run) - if not rows: - if os.path.exists(path): - os.remove(path) + try: + if not rows: + if os.path.exists(path): + os.remove(path) + return None + with open(path, "w", encoding="utf-8", newline="") as f: + out = csv.DictWriter(f, fieldnames=SERIES_COLUMNS, lineterminator="\n") + out.writeheader() + out.writerows(rows) + except OSError as e: + print(f"{SERIES} not written or removed: {e.__class__.__name__}: {e.strerror or e}", file=sys.stderr) return None - with open(path, "w", encoding="utf-8", newline="") as f: - out = csv.DictWriter(f, fieldnames=SERIES_COLUMNS, lineterminator="\n") - out.writeheader() - out.writerows(rows) return SERIES -def memory_block(run, world=None): +def memory_block(run, world=None, end=None): """Peaks of the runtime's memory lines over the whole run (none from a build without diagnostics), the - reaper's queue at its longest, and how fast the private bytes grew in the world (a pile-up's slope).""" + reaper's queue at its longest, and how fast the private bytes grew in the world up to `end` (a pile-up's + slope; the lines written while the title ends after the stop request do not count).""" out = {"source": None, "lines": 0, "private_max_mb": None, "private_max_at_s": None, "in_memory_max_mb": None, "pc_commit_left_min_mb": None, "pc_commit_left_min_at_s": None, "vram_in_use_max_mb": None, "vram_max_at_s": None, "vram_budget_at_max_mb": None, "vram_over_budget_s": None, @@ -445,11 +451,10 @@ def memory_block(run, world=None): out["reaper_queue_max"], out["reaper_queue_max_at_s"] = queue, round(t, 3) out["waiting_objects_max"] = max(w[1] for w in run.waits) if run.memory and world is not None: - slope = slope_per_min([(m[0], m[1]) for m in run.memory if m[0] >= world]) + slope = slope_per_min([(m[0], m[1]) for m in run.memory if world <= m[0] and (end is None or m[0] <= end)]) out["private_mb_per_min_in_world"] = round(slope, 1) if slope is not None else None if run.memory: out["series"] = SERIES - if run.memory: out["source"], out["lines"] = "memory lines", len(run.memory) t, private = max(((t, p) for t, p, *_ in run.memory), key=lambda x: x[1]) out["private_max_mb"], out["private_max_at_s"] = private, round(t, 3) @@ -548,7 +553,7 @@ def summary(run): }, "fps": fps, "pipelines": {"missed_waits": len(run.missed), "making_max": max((m for *_, m in run.frames), default=0)}, - "memory": dict(memory_block(run, world), stop_limits=run.meta.get("memory_stop")), + "memory": dict(memory_block(run, world, end), stop_limits=run.meta.get("memory_stop")), "crash": { "kind": crash_kind, "at_s": round(first["at_s"], 3) if first and first["at_s"] is not None else None, @@ -577,7 +582,8 @@ def main(argv): print(json.dumps(state(run))) return 0 out = summary(run) - write_series(run, argv[2]) + # `series` names the file only when it was written. + out["memory"]["series"] = write_series(run, argv[2]) with open(os.path.join(argv[2], "summary.json"), "w", encoding="utf-8", newline="\n") as f: json.dump(out, f, indent=2) f.write("\n")