Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion docs/game_gate.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,12 @@ pwsh -NoProfile -File scripts\game-gate.ps1 stop -RunDir <run folder>
- **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: 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`).
- **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.

Expand Down Expand Up @@ -57,9 +63,10 @@ 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 |
| `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
Expand All @@ -78,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.

Expand Down
28 changes: 24 additions & 4 deletions scripts/game-gate.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,11 @@
# 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 (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 = '',
Expand All @@ -26,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
Expand Down Expand Up @@ -69,7 +77,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 @{
Expand Down Expand Up @@ -113,6 +122,14 @@ $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)
$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'
[ordered]@{
Expand All @@ -129,6 +146,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')
Expand Down Expand Up @@ -170,6 +188,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
Expand All @@ -185,22 +204,23 @@ 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' }
if ($stopReason) { break }
}

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
Add-Event 'killed'
$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 }
Expand Down
100 changes: 100 additions & 0 deletions tests/test_game_gate.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,12 +48,27 @@ 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")
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",
Expand Down Expand Up @@ -209,6 +224,78 @@ 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 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"])
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)
Expand Down Expand Up @@ -279,6 +366,19 @@ 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)
# 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):
# PowerShell names ignore case: a `$game` process held in the `[string]$Game` parameter became its name,
# and the stop could not wait for it.
Expand Down
Loading
Loading