From f806537a8cfb568c8dcd9dcc806182f9ac0520a5 Mon Sep 17 00:00:00 2001 From: TheGeogeo <57634077+TheGeogeo@users.noreply.github.com> Date: Tue, 1 Dec 2026 01:32:36 +0100 Subject: [PATCH 1/3] gate: summary.json gets the run's memory peaks (D3D12-GATE-MEMORY-PEAKS) Testers could not use the gate daily without memory figures, and a memory pile-up took a 3090's Windows down twice. The parser now reads the runtime's memory line and video memory line (every 5 s in builds with diagnostics) and writes a memory block: the private bytes at their most and when, 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 then, the seconds over that budget, and the most shared memory in use. The video memory is what the system counts for the process, so it works on any card. The five runtime strings it reads join the contract test. --- docs/game_gate.md | 1 + tests/test_game_gate.py | 31 ++++++++++++++++++++++++++++++ tools/game_gate.py | 42 +++++++++++++++++++++++++++++++++++++++++ 3 files changed, 74 insertions(+) diff --git a/docs/game_gate.md b/docs/game_gate.md index 4bb6c372da..2a4f44c379 100644 --- a/docs/game_gate.md +++ b/docs/game_gate.md @@ -57,6 +57,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 | | `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 | diff --git a/tests/test_game_gate.py b/tests/test_game_gate.py index 879419d5da..9da60f265c 100644 --- a/tests/test_game_gate.py +++ b/tests/test_game_gate.py @@ -48,6 +48,16 @@ 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.""" + self.log.append(f"{stamp(t)} INFO leonida_gpu::host: video memory as the system counts it, with the memory " + f"line: the card's own: budget {budget} MB, in use {used} MB, 100 MB could still be reserved, " + f"0 MB reserved; the PC's shared with the card: budget 16000 MB, in use {shared} MB, 0 MB could " + f"still be reserved, 0 MB reserved (the layer reserves none)") + self.log.append(f"{stamp(t)} INFO leonida_gpu::copystat: memory: {private} MB private ({private // 2} MB of it " + f"in memory; the PC has 15000 MB free and {left} MB left to commit); host copies of title " + f"memory: 1 alive 1 MB, of them 0 windows outside buffers 0 MB") + def clean_stop(self, t, exit_code=0): self.event(t, "stop_requested", reason="target") self.log.append(f"{stamp(t + 0.1)} INFO leonida_hle::modules::lifecycle: window closed: suspending the title constrained=0 routines=1") @@ -209,6 +219,27 @@ def test_a_dip_on_arrival_is_not_the_first_second_under_2(self): self.assertEqual(s["fps"]["under_2_at_s"], 300.0) self.assertEqual(s["verdict"]["result"], "PASS", s["verdict"]) + def test_memory_peaks_come_from_the_runtimes_memory_lines(self): + f = passing() + for i, t in enumerate(range(70, 390, 5)): + # Private bytes grow, the PC's commit left shrinks, the card goes over its budget from 200 s on. + f.memory(t, 20000 + 10 * i, 7000 if t < 200 else 9000, left=3000 - i, shared=500 + i) + m = f.summarize()["memory"] + self.assertEqual((m["source"], m["lines"]), ("memory lines", 64)) + self.assertEqual((m["private_max_mb"], m["private_max_at_s"]), (20630, 385.0)) + self.assertEqual(m["in_memory_max_mb"], 10315) + self.assertEqual((m["pc_commit_left_min_mb"], m["pc_commit_left_min_at_s"]), (2937, 385.0)) + self.assertEqual((m["vram_in_use_max_mb"], m["vram_max_at_s"], m["vram_budget_at_max_mb"]), (9000, 200.0, 8000)) + self.assertEqual(m["vram_over_budget_s"], 185.0) + self.assertEqual(m["shared_in_use_max_mb"], 563) + + def 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"]) + def test_without_present_lines_the_frame_lines_give_the_rate(self): f = Fake() f.event(1, "game", pid=1) diff --git a/tools/game_gate.py b/tools/game_gate.py index d66ab92382..5a69e89952 100644 --- a/tools/game_gate.py +++ b/tools/game_gate.py @@ -44,6 +44,11 @@ PANIC = re.compile(r"(?:^thread '[^']*'(?: \(\d+\))? panicked at|^Leonida: panic on thread)") FAULT = re.compile(r"^Leonida: unhandled exception (0x[0-9a-fA-F]+) at (\S+)(.*)$") ACCESS = re.compile(r"\((read|write|execute)\w* (0x[0-9a-fA-F]+)") +# The memory line and the video memory line (diagnostics builds, every 5 s with the frame line). +MEMORY = re.compile(r"^memory: (\d+) MB private \((\d+) MB of it in memory; the PC has (\d+) MB free and (\d+) MB " + 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 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. @@ -64,6 +69,13 @@ "shaders in the cache, {} do not translate, {:.0} s": "d3d12/apps/leonida/src/translate.rs", "pipelines known, {} made before ({fingerprint}), {} bad; {} to make": "d3d12/apps/leonida/src/warm.rs", "made in {:.0} s (": "d3d12/apps/leonida/src/warm.rs", + "memory: {:.0} MB private ({:.0} MB of it in memory; the PC has {:.0} MB free and {:.0} MB": + "d3d12/crates/leonida-gpu/src/copystat.rs", + "left to commit); host copies": "d3d12/crates/leonida-gpu/src/copystat.rs", + "video memory as the system counts it, {}: the card's own: budget {} MB, in use {} MB": + "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", } @@ -110,6 +122,8 @@ def __init__(self, folder): self.frames = [] # (t, fps, draws, dropped, making) self.presents = [] # t of each present (diagnostics builds, frame debug lines) 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.settings = None # from the runtime's settings line self.suspend = None self.ended_at = None @@ -137,6 +151,10 @@ def read_log(self, lines): f = FRAME.search(text) if f: self.frames.append((t, float(f.group(1)), float(f.group(3)), float(f.group(4)), int(f.group(5)))) + elif text.startswith("memory: ") and MEMORY.match(text): + 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("a pipeline not made within its wait"): self.missed.append(t) elif target == "settings": @@ -316,6 +334,29 @@ 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).""" + 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} + 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) + out["in_memory_max_mb"] = max(m[2] for m in run.memory) + t, left = min(((m[0], m[4]) for m in run.memory), key=lambda x: x[1]) + out["pc_commit_left_min_mb"], out["pc_commit_left_min_at_s"] = left, round(t, 3) + if run.video: + t, budget, used = max(((v[0], v[1], v[2]) for v in run.video), key=lambda x: x[2]) + out["vram_in_use_max_mb"], out["vram_max_at_s"], out["vram_budget_at_max_mb"] = used, round(t, 3), budget + # Time over the card's budget: each line counts until the next one. + over = sum(b[0] - a[0] for a, b in zip(run.video, run.video[1:]) if a[2] > a[1]) + out["vram_over_budget_s"] = round(over, 1) + out["shared_in_use_max_mb"] = max(v[4] for v in run.video) + return out + + def summary(run): world = run.world_at() stop = run.stop_at() @@ -395,6 +436,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), "crash": { "kind": crash_kind, "at_s": round(first["at_s"], 3) if first and first["at_s"] is not None else None, From 0cd683949359e94bfe374013c20df95c579a9a74 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 2/3] 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 2a4f44c379..d345ba6643 100644 --- a/docs/game_gate.md +++ b/docs/game_gate.md @@ -26,6 +26,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. @@ -60,7 +66,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 @@ -79,6 +85,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 ad02a6c3b7..0ddc78b107 100644 --- a/scripts/game-gate.ps1 +++ b/scripts/game-gate.ps1 @@ -14,6 +14,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 = '', @@ -26,7 +30,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 @@ -69,7 +76,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 @{ @@ -113,6 +121,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 $builtWith = Join-Path $repo 'd3d12\target\diag\built-with.txt' [ordered]@{ @@ -129,6 +142,7 @@ $builtWith = Join-Path $repo 'd3d12\target\diag\built-with.txt' 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') @@ -170,6 +184,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 @@ -185,6 +200,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' } @@ -192,7 +208,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 @@ -200,7 +216,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 9da60f265c..1d2f94aa19 100644 --- a/tests/test_game_gate.py +++ b/tests/test_game_gate.py @@ -64,6 +64,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", @@ -233,6 +238,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"]) @@ -310,6 +366,16 @@ def test_state_tells_the_supervisor_the_world_time(self): class Script(unittest.TestCase): + 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 5a69e89952..7b1b909343 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 5323dfa697eee4ca643e57d777bc19ae8ce9d7ee 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 3/3] 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 d345ba6643..2cc22eecc7 100644 --- a/docs/game_gate.md +++ b/docs/game_gate.md @@ -27,7 +27,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 0ddc78b107..7b6ddad8c3 100644 --- a/scripts/game-gate.ps1 +++ b/scripts/game-gate.ps1 @@ -15,9 +15,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 = '', @@ -124,7 +125,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 $builtWith = Join-Path $repo 'd3d12\target\diag\built-with.txt' diff --git a/tests/test_game_gate.py b/tests/test_game_gate.py index 1d2f94aa19..d268e31afa 100644 --- a/tests/test_game_gate.py +++ b/tests/test_game_gate.py @@ -374,6 +374,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):