diff --git a/docs/README.md b/docs/README.md index 435291599c..1bc9ffcbbc 100644 --- a/docs/README.md +++ b/docs/README.md @@ -125,6 +125,7 @@ method, scope and caveats. No game data is included. | Document | What it covers | |---|---| +| [game_gate.md](game_gate.md) | The in-game gate for the D3D12 runtime: one command runs the game a set time in the world, stops it cleanly and writes `summary.json` (PASS/FAIL/ERROR, time to the world, warm cache, fps, crashes), the same on every machine. | | [measuring_fps.md](measuring_fps.md) | How to measure frame rates of the D3D12 runtime (`d3d12/`): look in the findings first, turn a switch inside one run with `LEONIDA_AB`, separate runs, which log number means what, what to write before reporting a cause. | | [d3d12/docs/findings.md](../d3d12/docs/findings.md) | What was measured of the D3D12 runtime's frame on several PCs: where a frame goes, switches by turns with their spread, what was not worth it, picture faults and what they were. | | [d3d12/docs/switches.md](../d3d12/docs/switches.md) | The `LEONIDA_*` variables the D3D12 runtime names, made from its sources (`tools/d3d12_switches.py`): how each is read, whether `LEONIDA_AB` can turn it, the sentence of the code's comment. | diff --git a/docs/game_gate.md b/docs/game_gate.md new file mode 100644 index 0000000000..4bb6c372da --- /dev/null +++ b/docs/game_gate.md @@ -0,0 +1,100 @@ +# The in-game gate + +One command runs the D3D12 runtime (`leonida.exe`) in the game for a set time in the world and says PASS, FAIL or ERROR. The same way on every machine. It is what a change to the render path needs before merge ("300 s in the world, no device loss"). It also gives the numbers an A/B compares: one `summary.json` per run, in one format. + +The script is `scripts/game-gate.ps1` (Windows, PowerShell 7). The parser is `tools/game_gate.py` (standard library only). The tests are in `tests/test_game_gate.py`. + +## Running it + +Build the runtime first (`d3d12\scripts\build-nvidia.ps1`). The gate refuses to start without `d3d12\target\diag\leonida.exe`, because the play script would build it inside the timed run. + +Make a data template once: +1. Play to the place the runs should start from. +2. Let the title save, and close the game cleanly. +3. Copy `\data\` (its `saves` and `storage`) into a folder outside the checkout. + +Each run gets a copy of it, so your own saves are never touched. A save is game data: never share or commit it. + +```powershell +pwsh -NoProfile -File scripts\game-gate.ps1 run -Game <game folder> -Data <data folder> -DataTemplate <template> ` + -Name base [-PlayArgs '<play-d3d12.ps1 switches>'] [-More 'LEONIDA_X=1;LEONIDA_KEYS=40:Enter,60:Enter'] [-WorldSeconds 300] +pwsh -NoProfile -File scripts\game-gate.ps1 start <same options> # detached: returns at once, prints the run folder +pwsh -NoProfile -File scripts\game-gate.ps1 stop -RunDir <run folder> +``` + +- **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). +- **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. + +The run folder (under `-RunRoot`, by default `<Data>\gate-runs`, refused inside a checkout) holds: + +| File | What | +| --- | --- | +| `run.json` | Name, start time, commit, exe hash, build features, card, driver, options | +| `launch.ps1` | How the game was started | +| `settings.txt` | The play script's `-DryRun` | +| `leonida-settings.txt` | The F1 menu file, when there was one (it changes every run, so the summary warns) | +| `launcher.txt` | The play script's output, with the precompile lines | +| `leonida.log` | The runtime's log, with `LEONIDA_LOG=info,leonida_gpu::frame=debug` (one line per present) | +| `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 | + +## summary.json (`leonida-gate-summary/1`) + +Times are seconds since the run started. The summary holds numbers, switch names and verdicts only. It never holds a path, a user or machine name, or text the title printed. A fault is told by the kind of module it was in, not by its name or address. + +| Field | Meaning | +| --- | --- | +| `run` | Name, start time, commit, `dirty` (a tracked file changed), `untracked` (how many files git does not track), exe hash (16 hex), build features, card, driver, play arguments, `world_seconds` | +| `settings` | The `LEONIDA_*` settings from the runtime's `settings` line, as it shows them (folders hidden). Empty, with a warning, from a runtime without that line | +| `precompile` | From the launcher: shaders in the cache and the seconds that took, pipelines known, made before, to make, made, their seconds and median ms | +| `times.world_at_s` | The world: the first of two frame lines in a row with 500 draws a frame or more. Cutscenes count: a save that opens on one is in the world. Like every time here, it counts from the gate's start, so the precompile is in it (its seconds are `precompile.shaders_s` and `precompile.made_s`) | +| `times.warm_at_s` | From then on, 60 s in the world with no pipeline being made and no wait for one that ran out. Draws dropped for a pipeline the host never has go on all run long and do not count | +| `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 | +| `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 | +| `verdict` | `result`, `reasons`, `warnings`, `min_world_s` | + +## The verdict + +**PASS** needs all of these: +- at least `-WorldSeconds` (300) in the world; +- no device loss and no panic; +- no fault before the stop request; +- no gap over 10 s with no frame presented once in the world, so a run frozen on a pipeline compile does not pass; +- the game alive at the stop request: a frame line less than 30 s old. + +**FAIL** comes with one or more reasons: +- `device_lost`: a host GPU failure, an out-of-memory command list that did not close, or exit 0x887A0005; +- `panic`; +- `fault_before_stop`; +- `exited_before_stop`; +- `present_gap`; +- `world_time_short`: the time limit came first; +- `not_alive_at_stop`; +- `world_not_reached`, when the game ended before reaching the world. + +**ERROR** means the gate could not judge the build: +- `not_started`; +- `relaunched`: the title restarted itself; +- `stopped_early`: a STOP file before the time; +- `world_not_reached`, when the game was still in the menus at the time limit. + +A crash after the stop request is a warning, except a device loss or a panic, which stay FAIL. A kill, a cache not saved and a late suspend are warnings too. + +## Not in this version + +- 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/scripts/game-gate.ps1 b/scripts/game-gate.ps1 new file mode 100644 index 0000000000..ad02a6c3b7 --- /dev/null +++ b/scripts/game-gate.ps1 @@ -0,0 +1,215 @@ +# The in-game gate for the D3D12 runtime (leonida.exe): one run, measured the same way on every machine. +# +# pwsh -NoProfile -File scripts\game-gate.ps1 run -Game <dir> -Data <dir> -DataTemplate <dir> -Name <label> [options] +# pwsh -NoProfile -File scripts\game-gate.ps1 start <same options> # the same, detached: returns at once, prints the run folder +# pwsh -NoProfile -File scripts\game-gate.ps1 stop -RunDir <run folder> # asks a run to stop (a STOP file) +# +# It starts the game through this checkout's scripts\play-d3d12.ps1, so a run is what players run, and writes one +# folder per run under -RunRoot (default: <Data>\gate-runs): run.json, launch.ps1, settings.txt (the play script's +# -DryRun), leonida-settings.txt (the F1 menu file, when there is one), launcher.txt (the precompile lines), +# leonida.log (the runtime's log), events.jsonl (what this script did and saw), data\ (a copy of -DataTemplate, so +# the tester's own saves are never touched) and summary.json (tools\game_gate.py, schema in docs\game_gate.md). +# +# It stops the game with WM_SYSCOMMAND/SC_CLOSE (the runtime's own end: the title suspended, the pipeline cache +# 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'. +param( + [Parameter(Mandatory, Position = 0)][ValidateSet('run', 'start', 'stop')][string]$Verb, + [string]$Game = '', + [string]$Data = '', + [string]$DataTemplate = '', + [string]$Name = '', + [string]$RunRoot = '', + [string]$RunDir = '', + [int]$WorldSeconds = 300, + [int]$MaxMinutes = 45, + [string]$More = '', + [string]$PlayArgs = '', + [string]$Python = '' +) +$ErrorActionPreference = 'Stop' +$repo = Split-Path -Parent $PSScriptRoot +$tool = Join-Path $repo 'tools\game_gate.py' +$play = Join-Path $repo 'scripts\play-d3d12.ps1' +$exe = Join-Path $repo 'd3d12\target\diag\leonida.exe' +$menuFile = Join-Path $repo 'd3d12\leonida-settings.txt' +if (-not $Python) { $Python = (Get-Command python -ErrorAction Stop).Source } + +if ($Verb -eq 'stop') { + if (-not $RunDir -or -not (Test-Path (Join-Path $RunDir 'run.json'))) { throw "not a run folder: '$RunDir'" } + Set-Content (Join-Path $RunDir 'STOP') 'stop' -NoNewline + "asked $RunDir to stop" + exit 0 +} + +foreach ($p in 'Game', 'Data', 'DataTemplate', 'Name') { + if (-not (Get-Variable $p -ValueOnly)) { throw "-$p is needed" } +} +$Game = (Resolve-Path $Game).Path +$Data = (Resolve-Path $Data).Path +$DataTemplate = (Resolve-Path $DataTemplate).Path +if (-not $RunRoot) { $RunRoot = Join-Path $Data 'gate-runs' } +New-Item -ItemType Directory -Force $RunRoot | Out-Null +$RunRoot = (Resolve-Path $RunRoot).Path +# A run writes gigabytes of logs and a copy of the saves: never into a checkout. +if (($RunRoot + '\').StartsWith($repo + '\', [StringComparison]::OrdinalIgnoreCase)) { throw "-RunRoot is inside the checkout: $RunRoot" } +if (-not (Test-Path $exe)) { throw "no ${exe}: build it first (d3d12\scripts\build-nvidia.ps1), the play script would build it inside the run" } +if (-not $RunDir) { $RunDir = Join-Path $RunRoot ('{0}-{1}' -f (Get-Date -Format 'yyyyMMdd-HHmmss'), ($Name -replace '[^\w.-]', '_')) } + +function Get-RunningGame { + Get-CimInstance Win32_Process -Filter "Name='leonida.exe' OR Name='leonida_sm.exe'" | + Where-Object { $_.CommandLine -match '\srun\s' } | Select-Object -First 1 +} + +if ($Verb -eq 'start') { + if (Get-RunningGame) { throw 'a leonida run is already running' } + $pwsh = (Get-Process -Id $PID).Path + $quote = { param($s) '"' + ($s -replace '"', '\"') + '"' } + $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 ' ' + # 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 @{ + CommandLine = $line; CurrentDirectory = $repo; ProcessStartupInformation = $startup } + if ($made.ReturnValue -ne 0) { throw "starting the run failed ($($made.ReturnValue))" } + $RunDir + exit 0 +} + +# ---- run: the supervisor, in the foreground. +if (Get-RunningGame) { throw 'a leonida run is already running' } +New-Item -ItemType Directory -Force $RunDir | Out-Null +# A detached run has no console: what this script says, and any error, goes to supervisor.log. +Start-Transcript -Path (Join-Path $RunDir 'supervisor.log') -Append | Out-Null +$events = Join-Path $RunDir 'events.jsonl' +function Add-Event([string]$event, [hashtable]$fields = @{}) { + $e = [ordered]@{ t = (Get-Date).ToUniversalTime().ToString('o'); event = $event } + foreach ($k in $fields.Keys) { $e[$k] = $fields[$k] } + Add-Content $events ($e | ConvertTo-Json -Compress) +} + +# The tester's saves, copied: the run plays from its own data folder (-More wins over the play script's own). +Copy-Item -Path (Join-Path $DataTemplate '*') -Destination (New-Item -ItemType Directory -Force (Join-Path $RunDir 'data')).FullName -Recurse +$hadMenuFile = Test-Path $menuFile +if ($hadMenuFile) { Copy-Item $menuFile (Join-Path $RunDir 'leonida-settings.txt') } + +$settings = [ordered]@{ + LEONIDA_DATA_DIR = (Join-Path $RunDir 'data') + LEONIDA_LOG = 'info,leonida_gpu::frame=debug' +} +foreach ($s in ($More -split ';' | Where-Object { $_ -match '=' })) { $k, $v = $s -split '=', 2; $settings[$k.Trim()] = $v.Trim() } +$moreText = ($settings.GetEnumerator() | ForEach-Object { " {0} = '{1}'" -f $_.Key, ($_.Value -replace "'", "''") }) -join "`n" +$launch = Join-Path $RunDir 'launch.ps1' +Set-Content $launch @" +# Written by scripts\game-gate.ps1: how this run started the game. +`$env:NO_COLOR = '1' +Set-Location '$repo' +`$settings = @{ +$moreText +} +& '$play' -Game '$Game' -Data '$Data' -More `$settings $PlayArgs @args +"@ + +$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]@{ + name = $Name + started_utc = (Get-Date).ToUniversalTime().ToString('o') + commit = (git -C $repo rev-parse --short HEAD) + dirty = [bool](git -C $repo status --porcelain --untracked-files=no) + untracked = @(git -C $repo status --porcelain --untracked-files=normal | Where-Object { $_.StartsWith('??') }).Count + exe_sha16 = (Get-FileHash $exe -Algorithm SHA256).Hash.Substring(0, 16).ToLower() + built_with = if (Test-Path $builtWith) { (Get-Content $builtWith -Raw).Trim() } else { $null } + gpu = $gpu.Name + driver = $gpu.DriverVersion + play_args = $PlayArgs + world_seconds = $WorldSeconds + max_minutes = $MaxMinutes + f1_settings_file = $hadMenuFile +} | ConvertTo-Json | Set-Content (Join-Path $RunDir 'run.json') + +& pwsh -NoProfile -ExecutionPolicy Bypass -File $launch -DryRun *> (Join-Path $RunDir 'settings.txt') +$launcher = Start-Process pwsh -ArgumentList @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', $launch) -WindowStyle Hidden -PassThru ` + -RedirectStandardOutput (Join-Path $RunDir 'launcher.txt') -RedirectStandardError (Join-Path $RunDir 'leonida.log') +Add-Event 'started' @{ launcher = $launcher.Id } + +if (-not ('GateWindow' -as [type])) { + Add-Type -TypeDefinition @' +using System; +using System.Runtime.InteropServices; +public static class GateWindow { + delegate bool EnumProc(IntPtr h, IntPtr l); + [StructLayout(LayoutKind.Sequential)] public struct RECT { public int L, T, R, B; } + [DllImport("user32.dll")] static extern bool EnumWindows(EnumProc cb, IntPtr l); + [DllImport("user32.dll")] static extern uint GetWindowThreadProcessId(IntPtr h, out uint pid); + [DllImport("user32.dll")] static extern bool IsWindowVisible(IntPtr h); + [DllImport("user32.dll")] static extern bool GetClientRect(IntPtr h, out RECT r); + [DllImport("user32.dll")] static extern bool PostMessage(IntPtr h, uint msg, IntPtr w, IntPtr l); + // WM_SYSCOMMAND/SC_CLOSE to the process's largest visible window: the runtime's end_title path. (A plain + // WM_CLOSE goes to the title's own window procedure, which does not end the run.) + public static bool Close(int pid) { + IntPtr best = IntPtr.Zero; long area = 0; + EnumWindows((h, l) => { + uint p; GetWindowThreadProcessId(h, out p); + RECT r; + if (p == (uint)pid && IsWindowVisible(h) && GetClientRect(h, out r)) { + long a = (long)(r.R - r.L) * (r.B - r.T); + if (a > area) { area = a; best = h; } + } + return true; + }, IntPtr.Zero); + return best != IntPtr.Zero && PostMessage(best, 0x0112, new IntPtr(0xF060), IntPtr.Zero); + } +} +'@ +} + +$began = Get-Date +$title = $null # the game process ($Game, the same name in any case, is its folder) +$stopReason = $null +try { +while ($true) { + Start-Sleep -Seconds 5 + if (-not $title) { + $found = Get-RunningGame + if ($found) { + $title = Get-Process -Id $found.ProcessId + $null = $title.Handle # held now, so that the exit code can be read after the process ends + Add-Event 'game' @{ pid = $found.ProcessId; image = $found.Name } + } + } + 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 (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 } + 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 } +} +if ($title) { Add-Event 'game_exited' @{ exit_code = $title.ExitCode } } +if (-not $launcher.WaitForExit(30000)) { Stop-Process -Id $launcher.Id -Force } +} catch { + Add-Event 'error' @{ message = $_.Exception.Message; line = $_.InvocationInfo.ScriptLineNumber } + Write-Host "gate error: $($_.Exception.Message) (line $($_.InvocationInfo.ScriptLineNumber))" +} finally { + & $Python -I $tool summary $RunDir + $code = $LASTEXITCODE + Stop-Transcript | Out-Null +} +exit $code diff --git a/tests/test_game_gate.py b/tests/test_game_gate.py new file mode 100644 index 0000000000..879419d5da --- /dev/null +++ b/tests/test_game_gate.py @@ -0,0 +1,305 @@ +"""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 datetime as dt +import json +import os +import re +import sys +import tempfile +import unittest + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, os.path.join(ROOT, "tools")) +import game_gate # noqa: E402 + +START = dt.datetime(2026, 11, 30, 18, 0, 0, tzinfo=dt.timezone.utc) + + +def stamp(seconds): + return (START + dt.timedelta(seconds=seconds)).strftime("%Y-%m-%dT%H:%M:%S.%f") + "Z" + + +def frame_line(t, fps, draws, making=0, dropped=0): + return (f"{stamp(t)} INFO leonida_gpu::host: {fps:.1f} fps, {1000.0 / fps:.1f} ms/frame (1.0 preparing: copies 0.1 ms " + f"0.1 MB, textures 0.1 ms 0.1 MB; 5.0 on the GPU; 0.0 copying back 0.0 MB), {draws} draws/frame, dropped " + f"{dropped} without a host pipeline ({making} being made) and 0 indirect, of both per frame: none") + + +class Fake: + """A run folder written line by line.""" + + def __init__(self, world_seconds=300): + self.dir = tempfile.mkdtemp(prefix="gate-test-") + self.log, self.launcher, self.events, self.crashes = [], [], [], [] + self.meta = {"name": "t", "started_utc": stamp(0), "commit": "abc1234", "dirty": False, "exe_sha16": "0" * 16, + "gpu": "Test GPU", "driver": "1.0", "play_args": "-SeriesS", "world_seconds": world_seconds} + + def event(self, t, name, **more): + self.events.append(dict(t=stamp(t), event=name, **more)) + + def frames(self, start, end, fps, draws, making=0, dropped=0, step=1.0, presents=True): + t = start + while t < end: + self.log.append(frame_line(t, fps, draws, making, dropped)) + t += step + if presents: + t, gap = start, 1.0 / fps + while t < end: + self.log.append(f"{stamp(t)} DEBUG leonida_gpu::frame: present token=1") + t += gap + + def 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 summarize(self): + self.log.sort(key=lambda l: l[:27]) + files = {"run.json": json.dumps(self.meta), "leonida.log": "\n".join(self.log) + "\n", + "launcher.txt": "\n".join(self.launcher) + "\n", + "events.jsonl": "".join(json.dumps(e) + "\n" for e in self.events)} + for name, text in files.items(): + with open(os.path.join(self.dir, name), "w", encoding="utf-8") as f: + f.write(text) + if self.crashes: + os.makedirs(os.path.join(self.dir, "data", "TITLE"), exist_ok=True) + with open(os.path.join(self.dir, "data", "TITLE", "crashes.log"), "w", encoding="utf-8") as f: + f.write("\n".join(self.crashes) + "\n") + return game_gate.summary(game_gate.Run(self.dir)) + + +def passing(world_seconds=300): + f = Fake(world_seconds) + f.event(1, "game", pid=1) + f.frames(10, 70, 60.0, 13) # menus: few draws + f.frames(70, 70 + 320, 50.0, 4000) # the world + f.clean_stop(70 + 320) + return f + + +class Verdicts(unittest.TestCase): + def test_a_clean_run_in_the_world_passes(self): + f = passing() + f.meta["untracked"] = 2 + s = f.summarize() + self.assertEqual((s["run"]["dirty"], s["run"]["untracked"]), (False, 2)) + self.assertEqual(s["verdict"]["result"], "PASS", s["verdict"]) + self.assertAlmostEqual(s["times"]["world_at_s"], 70.0, places=3) + self.assertGreaterEqual(s["times"]["world_s"], 300) + self.assertEqual(s["fps"]["source"], "presents") + self.assertAlmostEqual(s["fps"]["median"], 50.0, delta=0.5) + self.assertEqual(s["exit"], {"code_hex": "0x00000000", "kind": "clean"}) + self.assertEqual(s["stop"]["cache_saved"], True) + self.assertEqual(s["crash"]["kind"], "none") + + def test_a_lost_device_fails_by_its_exit_code_and_its_report(self): + f = Fake() + f.event(1, "game", pid=1) + f.frames(10, 200, 50.0, 4000) + f.log.append("host GPU failure: the card was removed") + f.crashes.append("Leonida: host GPU failure: the card was removed") + f.event(201, "game_exited", exit_code=0x887A0005) + s = f.summarize() + self.assertEqual(s["verdict"]["result"], "FAIL") + self.assertIn("device_lost", s["verdict"]["reasons"]) + self.assertEqual(s["exit"]["kind"], "device_lost") + self.assertEqual(s["crash"]["kind"], "device_lost") + + def test_an_out_of_memory_list_close_counts_as_a_lost_device(self): + f = passing() + f.log.append(f"{stamp(200)} ERROR leonida_gpu::host: a host command list did not close (0x8007000E): " + "a command recorded into it was invalid") + self.assertIn("device_lost", f.summarize()["verdict"]["reasons"]) + + def test_a_panic_fails_even_with_the_title_alive(self): + f = passing() + f.log.append(f"{stamp(150)} INFO leonida_gpu::host: before") + f.log.append("thread 'leonida-records' (4242) panicked at crates\\leonida-gpu\\src\\land.rs:1:1:") + s = f.summarize() + self.assertEqual(s["verdict"]["result"], "FAIL") + self.assertIn("panic", s["verdict"]["reasons"]) + + def test_menus_only_is_an_error_not_a_pass(self): + f = Fake() + f.event(1, "game", pid=1) + f.frames(10, 400, 60.0, 13) + f.event(400, "stop_requested", reason="timeout") + f.event(401, "game_exited", exit_code=0) + s = f.summarize() + self.assertEqual(s["verdict"]["result"], "ERROR") + self.assertIn("world_not_reached", s["verdict"]["reasons"]) + self.assertIsNone(s["times"]["world_at_s"]) + + def test_a_stop_file_before_the_world_time_is_an_error(self): + f = Fake() + f.event(1, "game", pid=1) + f.frames(70, 320, 50.0, 4000) + f.event(320, "stop_requested", reason="stop_file") + f.event(321, "game_exited", exit_code=0) + s = f.summarize() + self.assertEqual(s["verdict"]["result"], "ERROR") + self.assertIn("stopped_early", s["verdict"]["reasons"]) + + def test_too_little_world_time_at_the_time_limit_fails(self): + f = Fake() + f.event(1, "game", pid=1) + f.frames(70, 320, 50.0, 4000) + f.event(320, "stop_requested", reason="timeout") + f.event(321, "game_exited", exit_code=0) + s = f.summarize() + self.assertEqual(s["verdict"]["result"], "FAIL") + self.assertIn("world_time_short", s["verdict"]["reasons"]) + + def test_a_run_frozen_on_a_compile_fails_though_alive(self): + f = Fake() + f.event(1, "game", pid=1) + f.frames(70, 200, 50.0, 4000) + f.frames(200, 400, 0.5, 4000, making=1, presents=False) # frame lines go on, no frame is shown + f.clean_stop(400) + s = f.summarize() + self.assertEqual(s["verdict"]["result"], "FAIL") + self.assertIn("present_gap", s["verdict"]["reasons"]) + self.assertGreater(s["fps"]["longest_present_gap_s"], 150) + + def test_dying_before_the_stop_fails(self): + f = Fake() + f.event(1, "game", pid=1) + f.frames(70, 250, 50.0, 4000) + f.event(250, "game_exited", exit_code=1) + self.assertIn("exited_before_stop", f.summarize()["verdict"]["reasons"]) + + +class Measures(unittest.TestCase): + def test_the_cache_is_warm_after_a_quiet_minute(self): + f = Fake() + f.event(1, "game", pid=1) + f.frames(70, 130, 40.0, 4000, making=3) + # Draws dropped for pipelines the host never has go on all along: the cache is warm all the same. + f.frames(130, 420, 50.0, 4000, dropped=240) + f.clean_stop(420) + s = f.summarize() + self.assertAlmostEqual(s["times"]["warm_at_s"], 130.0, places=3) + self.assertEqual(s["pipelines"]["making_max"], 3) + + def test_percentiles_come_from_the_presents(self): + f = Fake() + f.event(1, "game", pid=1) + f.frames(70, 70 + 60, 50.0, 4000) + f.frames(130, 430, 25.0, 4000) + f.clean_stop(430) + s = f.summarize() + self.assertAlmostEqual(s["fps"]["median"], 25.0, delta=0.3) + self.assertAlmostEqual(s["fps"]["frame_p95_ms"], 40.0, delta=0.5) + self.assertAlmostEqual(s["fps"]["end_median"], 25.0, delta=0.3) + self.assertIsNone(s["fps"]["under_2_at_s"]) + + def test_a_dip_on_arrival_is_not_the_first_second_under_2(self): + # One frame a second just after the world (streaming in), then steady, then a dip later on: under_2_at_s + # counts from 60 s in the world, like the median, and finds the later dip. + f = Fake() + f.event(1, "game", pid=1) + f.frames(70, 75, 1.0, 4000) + f.frames(75, 300, 30.0, 4000) + f.frames(300, 305, 1.0, 4000) + f.frames(305, 420, 30.0, 4000) + f.clean_stop(420) + s = f.summarize() + self.assertAlmostEqual(s["times"]["world_at_s"], 70.0, places=3) + self.assertEqual(s["fps"]["under_2_at_s"], 300.0) + self.assertEqual(s["verdict"]["result"], "PASS", s["verdict"]) + + def test_without_present_lines_the_frame_lines_give_the_rate(self): + f = Fake() + f.event(1, "game", pid=1) + f.frames(70, 400, 30.0, 4000, presents=False) + f.clean_stop(400) + s = f.summarize() + self.assertEqual(s["fps"]["source"], "frame_lines") + self.assertAlmostEqual(s["fps"]["median"], 30.0, places=1) + self.assertIn("no_present_lines", s["verdict"]["warnings"]) + + def test_colored_lines_read_the_same(self): + f = passing() + f.log = [l.replace(" INFO ", " \x1b[32mINFO\x1b[0m ") for l in f.log] + self.assertEqual(f.summarize()["verdict"]["result"], "PASS") + + def test_a_write_at_zero_in_the_title_after_a_freeze_is_its_watchdog(self): + f = Fake() + f.event(1, "game", pid=1) + f.frames(70, 200, 50.0, 4000) + f.log.append(f"{stamp(230)} INFO leonida_hle::x: still here") + f.log.append("Leonida: unhandled exception 0xc0000005 at game_title.exe+0x1234 (write 0x0: no memory)") + f.event(231, "game_exited", exit_code=0xC0000005) + s = f.summarize() + self.assertEqual(s["crash"]["kind"], "fault") + self.assertEqual((s["crash"]["module"], s["crash"]["access"]), ("title", "write")) + self.assertTrue(s["crash"]["title_watchdog"]) + self.assertIn("fault_before_stop", s["verdict"]["reasons"]) + + def test_settings_and_precompile_lines_are_read(self): + f = passing() + f.log.append(f"{stamp(5)} INFO settings: 2 LEONIDA_ settings: LEONIDA_DATA_DIR=<hidden, 40 chars> " + "LEONIDA_RELAY=2") + f.launcher += ["25663 shaders in the cache, 3 do not translate, 118 s", + "88571 pipelines known, 85479 made before (abcd), 12 bad; 3092 to make, 12 processes", + "3092 made in 640 s (5 have no host pipeline, 0 ended their process); ms each: median 180.5, " + "p90 900.0, p99 2000.0, most 9000, sum 600 s"] + s = f.summarize() + self.assertEqual(s["settings"], {"LEONIDA_DATA_DIR": "<hidden, 40 chars>", "LEONIDA_RELAY": "2"}) + p = s["precompile"] + self.assertEqual((p["shaders"], p["untranslatable"], p["shaders_s"]), (25663, 3, 118)) + self.assertEqual((p["pipelines_known"], p["made_before"], p["to_make"], p["made"], p["made_s"]), + (88571, 85479, 3092, 3092, 640)) + self.assertNotIn("no_settings_line", s["verdict"]["warnings"]) + + def test_the_summary_holds_no_path(self): + f = passing() + f.log.append(f"{stamp(5)} INFO settings: 1 LEONIDA_ settings: LEONIDA_GAME_DIR=<hidden, 21 chars>") + f.log.append("Leonida: unhandled exception 0xc0000005 at C:\\Users\\someone\\x.dll+0x10 (read 0x8: x)") + text = json.dumps(f.summarize()) + self.assertNotIn("someone", text) + self.assertNotRegex(text, r"[A-Za-z]:\\\\") + + +class Command(unittest.TestCase): + def test_summary_writes_the_file_and_exits_by_verdict(self): + f = passing() + f.summarize() + self.assertEqual(game_gate.main(["game_gate.py", "summary", f.dir]), 0) + with open(os.path.join(f.dir, "summary.json"), encoding="utf-8") as h: + self.assertEqual(json.load(h)["schema"], game_gate.SCHEMA) + + def test_state_tells_the_supervisor_the_world_time(self): + f = passing() + f.summarize() + state = game_gate.state(game_gate.Run(f.dir)) + self.assertAlmostEqual(state["world_at_s"], 70.0, places=3) + self.assertGreaterEqual(state["world_s"], 300) + + +class Script(unittest.TestCase): + def test_no_variable_takes_a_parameters_name_in_another_case(self): + # PowerShell names ignore case: a `$game` process held in the `[string]$Game` parameter became its name, + # and the stop could not wait for it. + with open(os.path.join(ROOT, "scripts", "game-gate.ps1"), encoding="utf-8") as f: + text = f.read() + block = text[text.index("param("):text.index("\n)\n")] + params = re.findall(r"\$(\w+)", block) + self.assertIn("Game", params) + for name in params: + others = {m for m in re.findall(r"\$(\w+)\b", text) if m.lower() == name.lower() and m != name} + self.assertFalse(others, f"${name} is also written {sorted(others)}") + + +class Contract(unittest.TestCase): + def test_the_runtime_still_writes_what_the_parser_reads(self): + for words, path in game_gate.SOURCES.items(): + with open(os.path.join(ROOT, path), encoding="utf-8") as f: + # Rust strings continued over lines (a backslash at the end of a line) read as one. + text = re.sub(r"\\\r?\n\s*", "", f.read()) + self.assertIn(words, text, f"{path} no longer says {words!r}: update tools/game_gate.py") + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/game_gate.py b/tools/game_gate.py new file mode 100644 index 0000000000..d66ab92382 --- /dev/null +++ b/tools/game_gate.py @@ -0,0 +1,441 @@ +"""The in-game gate's parser: one run folder of scripts/game-gate.ps1 to its state and its summary.json. + + python -I tools/game_gate.py state <run dir> # JSON on stdout: what the supervisor stops on + python -I tools/game_gate.py summary <run dir> # writes <run dir>/summary.json; exit 0 PASS, 1 FAIL, 2 ERROR + +Standard library only. It reads run.json and events.jsonl (written by the gate script), launcher.txt (the play +script's output: the precompile lines), leonida.log (the runtime's log) and data/*/crashes.log. The summary holds +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 datetime as dt +import glob +import json +import os +import re +import statistics +import sys + +SCHEMA = "leonida-gate-summary/1" +# The runtime's first 3D frames draw hundreds of times a frame; its menus and loading screens a few dozen +# (capture.rs uses the same threshold). Two frame lines in a row, so a single busy menu frame does not count. +WORLD_DRAWS = 500 +WORLD_LINES = 2 +# Warm: this long in the world with no pipeline being made and no wait for one that ran out. (Draws dropped for +# a pipeline the host never has go on all run long, so they do not count.) +WARM_QUIET_S = 60.0 +# The frames counted for fps start this long after the world is reached, and the end median covers this long. +AFTER_WORLD_S = 60.0 +END_WINDOW_S = 60.0 +# A run that shows no new frame for longer than this, once in the world, is frozen, not slow. +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 +DEVICE_LOST = 0x887A0005 + +ANSI = re.compile(r"\x1b\[[0-9;]*m") +LINE = re.compile(r"^(\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?)Z\s+([A-Z]+)\s+([\w:]+): (.*)$") +FRAME = re.compile( + r"([\d.]+) fps, ([\d.]+) ms/frame \(.*?\), ([\d.]+) draws/frame, dropped ([\d.]+) without a host pipeline " + r"\((\d+) being made\)") +SHADERS = re.compile(r"^(\d+) shaders in the cache, (?:(\d+) do not translate, )?(\d+) s$") +KNOWN = re.compile(r"^(\d+) pipelines known, (\d+) made before \([^)]*\), (\d+) bad; (\d+) to make") +MADE = re.compile(r"^(\d+) made in (\d+) s .*ms each: median ([\d.]+)") +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 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. +SOURCES = { + "draws/frame, dropped": "d3d12/crates/leonida-gpu/src/host.rs", + "without a host pipeline ({making} being made)": "d3d12/crates/leonida-gpu/src/host.rs", + '"present"': "d3d12/crates/leonida-gpu/src/host.rs", + "a pipeline not made within its wait": "d3d12/crates/leonida-gpu/src/pipeline/make.rs", + ": suspending the title": "d3d12/crates/leonida-hle/src/modules/lifecycle.rs", + "; ending the title": "d3d12/crates/leonida-hle/src/modules/lifecycle.rs", + "title did not finish suspending in time": "d3d12/crates/leonida-hle/src/modules/lifecycle.rs", + '"relaunched"': "d3d12/crates/leonida-hle/src/modules/lifecycle.rs", + "host GPU failure: ": "d3d12/crates/leonida-gpu/src/host.rs", + "host command list did not close": "d3d12/crates/leonida-gpu/src/host.rs", + "Leonida: panic on thread": "d3d12/crates/leonida-loader/src/crash.rs", + "Leonida: {what} {:#010x} at {}{detail}": "d3d12/crates/leonida-loader/src/crash.rs", + "unhandled exception": "d3d12/crates/leonida-loader/src/crash.rs", + "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", +} + + +def when(text): + """Seconds since the epoch of an ISO 8601 UTC time ('...Z', any number of fraction digits).""" + m = re.match(r"(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)(?:\.(\d+))?", text) + if not m: + raise ValueError(f"not a time: {text!r}") + y, mo, d, h, mi, s, frac = m.groups() + base = dt.datetime(int(y), int(mo), int(d), int(h), int(mi), int(s), tzinfo=dt.timezone.utc).timestamp() + return base + (float("0." + frac) if frac else 0.0) + + +def read_lines(path): + if not os.path.exists(path): + return [] + with open(path, encoding="utf-8", errors="replace") as f: + return [ANSI.sub("", line.rstrip("\r\n")) for line in f] + + +def percentile(values, p): + """Nearest rank, as the runtime's frame-time statistics do.""" + ordered = sorted(values) + if not ordered: + return None + rank = max(1, -(-p * len(ordered) // 100)) + return ordered[min(rank, len(ordered)) - 1] + + +class Run: + """Everything one run folder says, in seconds since the run started.""" + + def __init__(self, folder): + self.folder = folder + with open(os.path.join(folder, "run.json"), encoding="utf-8-sig") as f: + self.meta = json.load(f) + self.start = when(self.meta["started_utc"]) + self.events = [] + for line in read_lines(os.path.join(folder, "events.jsonl")): + if line.strip(): + e = json.loads(line) + e["t_s"] = when(e["t"]) - self.start + self.events.append(e) + 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.settings = None # from the runtime's settings line + self.suspend = None + self.ended_at = None + self.relaunched = False + self.crashes = [] # dicts: kind, at_s, ... + self.last_at = None + self.read_log(read_lines(os.path.join(folder, "leonida.log"))) + for path in sorted(glob.glob(os.path.join(folder, "data", "*", "crashes.log"))): + self.read_crashes(read_lines(path)) + self.precompile = read_precompile(read_lines(os.path.join(folder, "launcher.txt"))) + + def read_log(self, lines): + for line in lines: + m = LINE.match(line) + if not m: + # Lines with no time (panics, the host GPU failure) belong to the last time seen. + self.read_crash_line(line, self.last_at) + continue + t = when(m.group(1)) - self.start + self.last_at = t + target, text = m.group(3), m.group(4) + if target == "leonida_gpu::frame" and text.startswith("present"): + self.presents.append(t) + continue + 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("a pipeline not made within its wait"): + self.missed.append(t) + elif target == "settings": + self.settings = parse_settings(text) + elif text.endswith("; ending the title"): + self.ended_at = t + self.suspend = "late" if text.startswith("title did not finish suspending in time") else "suspended" + elif text.startswith("relaunched"): + self.relaunched = True + self.read_crash_line(text, t) + + def read_crash_line(self, text, t): + if "host GPU failure" in text: + self.crashes.append({"kind": "device_lost", "at_s": t}) + elif "host command list did not close" in text and ("8007000E" in text.upper() or "E_OUTOFMEMORY" in text.upper()): + self.crashes.append({"kind": "device_lost", "at_s": t}) + elif PANIC.search(text): + self.crashes.append({"kind": "panic", "at_s": t}) + else: + m = FAULT.match(text) + if m: + access = ACCESS.search(m.group(3)) + module = m.group(2).split("+")[0] + self.crashes.append({ + "kind": "fault", + "at_s": t, + "code_hex": m.group(1).lower(), + "module": module_class(module), + "access": access.group(1) if access else None, + "null_address": bool(access) and int(access.group(2), 16) == 0, + }) + + def read_crashes(self, lines): + # crashes.log entries carry no time this parser trusts: they count from the end of the log. + for line in lines: + self.read_crash_line(line.strip(), self.last_at) + + def event(self, name): + return next((e for e in self.events if e.get("event") == name), None) + + def world_at(self): + run = 0 + for i, (t, _fps, draws, _dropped, _making) in enumerate(self.frames): + run = run + 1 if draws >= WORLD_DRAWS else 0 + if run == WORLD_LINES: + return self.frames[i - WORLD_LINES + 1][0] + return None + + def warm_at(self, world): + """The first time in the world from which WARM_QUIET_S passed with nothing being made or waited for in vain.""" + if world is None: + return None + quiet_from = None + for t, _fps, _draws, dropped, making in self.frames: + if t < world: + continue + busy = making > 0 or any(quiet_from is not None and quiet_from <= m <= t for m in self.missed) + if busy: + quiet_from = None + continue + if quiet_from is None: + quiet_from = t + elif t - quiet_from >= WARM_QUIET_S: + return quiet_from + return None + + def stop_at(self): + e = self.event("stop_requested") + return e["t_s"] if e else None + + +def parse_settings(text): + """{name: value} from the runtime's settings line (values it hid stay hidden).""" + if "LEONIDA_ settings:" not in text: + return {} + body = text.split("LEONIDA_ settings:", 1)[1] + out = {} + for m in re.finditer(r"(LEONIDA_[A-Z0-9_]+)=(<hidden, \d+ chars>|\S+)", body): + out[m.group(1)] = m.group(2) + return out + + +def module_class(module): + """Which kind of code a fault was in, not its name or address.""" + name = module.lower() + if name.startswith("leonida"): + return "runtime" + if name.startswith("game_") or name.endswith("master.exe"): + return "title" + if name.startswith("nv") or name.startswith("amd") or name.startswith("igd"): + return "driver" + if name.endswith(".dll"): + return "system" + return "unknown" + + +def read_precompile(lines): + out = {"shaders": None, "untranslatable": None, "shaders_s": None, "pipelines_known": None, "made_before": None, + "bad": None, "to_make": None, "made": None, "made_s": None, "made_median_ms": None} + for line in lines: + line = line.strip() + m = SHADERS.match(line) + if m: + out["shaders"], out["shaders_s"] = int(m.group(1)), int(m.group(3)) + out["untranslatable"] = int(m.group(2)) if m.group(2) else None + continue + m = KNOWN.match(line) + if m: + out["pipelines_known"], out["made_before"], out["bad"], out["to_make"] = map(int, m.groups()) + continue + m = MADE.match(line) + if m: + out["made"], out["made_s"], out["made_median_ms"] = int(m.group(1)), int(m.group(2)), float(m.group(3)) + return out + + +def state(run): + world = run.world_at() + last = run.last_at + return { + "world_at_s": world, + "world_s": (last - world) if world is not None and last is not None else 0.0, + "warm_at_s": run.warm_at(world), + "last_line_s": last, + "frame_lines": len(run.frames), + "relaunched": run.relaunched, + "device_lost": any(c["kind"] == "device_lost" for c in run.crashes), + } + + +def fps_block(run, world, end): + """Frame statistics over the world from AFTER_WORLD_S on, to `end`.""" + out = {"source": None, "basis": f"world+{AFTER_WORLD_S:.0f}s", "frames": 0, "median": None, "p5": None, + "frame_p95_ms": None, "end_median": None, "under_2_at_s": None, "longest_present_gap_s": None, + "longest_gap_at_s": None, "draws_median": None} + if world is None or end is None: + return out + begin = world + AFTER_WORLD_S + draws = [d for t, _f, d, _x, _m in run.frames if begin <= t < end] + out["draws_median"] = statistics.median(draws) if draws else None + shown = [t for t in run.presents if world <= t <= end] + if len(shown) >= 2: + out["source"] = "presents" + gaps = [(b - a, a) for a, b in zip(shown, shown[1:])] + tail = end - shown[-1] + gaps.append((tail, shown[-1])) + longest = max(gaps) + out["longest_present_gap_s"], out["longest_gap_at_s"] = round(longest[0], 3), round(longest[1], 3) + counted = [(b - a) * 1000.0 for a, b in zip(shown, shown[1:]) if a >= begin] + if counted: + out["frames"] = len(counted) + out["median"] = round(1000.0 / statistics.median(counted), 2) + out["p5"] = round(1000.0 / percentile(counted, 95), 2) + out["frame_p95_ms"] = round(percentile(counted, 95), 2) + tail_frames = [(b - a) * 1000.0 for a, b in zip(shown, shown[1:]) if a >= end - END_WINDOW_S] + if tail_frames: + out["end_median"] = round(1000.0 / statistics.median(tail_frames), 2) + per_second = {} + for t in shown: + per_second[int(t)] = per_second.get(int(t), 0) + 1 + # From 60 s in the world on, like the median: the arrival's streaming dip is not the run's rate. + second = int(begin) + while second + 1 <= end: + if per_second.get(second, 0) < 2: + out["under_2_at_s"] = float(second) + break + second += 1 + else: + rates = [f for t, f, _d, _x, _m in run.frames if begin <= t < end] + if rates: + out["source"] = "frame_lines" + out["frames"] = len(rates) + out["median"] = round(statistics.median(rates), 2) + out["p5"] = round(percentile(rates, 5), 2) + tail_rates = [f for t, f, _d, _x, _m in run.frames if end - END_WINDOW_S <= t < end] + out["end_median"] = round(statistics.median(tail_rates), 2) if tail_rates else None + return out + + +def summary(run): + world = run.world_at() + stop = run.stop_at() + end = stop if stop is not None else run.last_at + exited = run.event("game_exited") + killed = run.event("killed") is not None + min_world = float(run.meta.get("world_seconds", 300)) + reason = (run.event("stop_requested") or {}).get("reason") + world_s = (end - world) if world is not None and end is not None else 0.0 + fps = fps_block(run, world, end) + code = exited.get("exit_code") if exited else None + if code is not None and code & 0xFFFFFFFF == DEVICE_LOST: + run.crashes.append({"kind": "device_lost", "at_s": exited["t_s"]}) + before = [c for c in run.crashes if stop is None or c["at_s"] is None or c["at_s"] <= stop] + after = [c for c in run.crashes if c not in before] + for c in run.crashes: + frozen = [t for t, *_ in run.frames if c["at_s"] is not None and t <= c["at_s"]] + c["title_watchdog"] = (c["kind"] == "fault" and c.get("module") == "title" and c.get("access") == "write" + and c.get("null_address") and bool(frozen) and c["at_s"] - frozen[-1] >= 25.0) + kinds = [c["kind"] for c in run.crashes] + crash_kind = next((k for k in ("device_lost", "panic", "fault") if k in kinds), "none") + first = next((c for c in run.crashes if c["kind"] == crash_kind), None) + exited_before_stop = exited is not None and (stop is None or exited["t_s"] < stop) and not run.relaunched + last_frame = max((t for t, *_ in run.frames if stop is None or t <= stop), default=None) + alive = stop is not None and not exited_before_stop and last_frame is not None and stop - last_frame <= ALIVE_S + + fails, errors, warnings = [], [], [] + if "device_lost" in kinds: + fails.append("device_lost") + if "panic" in kinds: + fails.append("panic") + if any(c["kind"] == "fault" for c in before): + fails.append("fault_before_stop") + if exited_before_stop and not run.crashes: + 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 run.relaunched: + errors.append("relaunched") + if run.event("game") is None and not run.frames: + errors.append("not_started") + elif world is None: + (errors if not exited_before_stop else fails).append("world_not_reached") + elif world_s < min_world: + (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") + if any(c["kind"] == "fault" for c in after): + warnings.append("fault_after_stop") + if killed: + warnings.append("killed") + if stop is not None and run.ended_at is None: + warnings.append("cache_not_saved") + if run.suspend == "late": + warnings.append("suspend_late") + if fps["source"] == "frame_lines": + warnings.append("no_present_lines") + if run.settings is None: + warnings.append("no_settings_line") + if run.meta.get("f1_settings_file"): + warnings.append("f1_settings_file") + result = "FAIL" if fails else "ERROR" if errors else "PASS" + + return { + "schema": SCHEMA, + "run": {key: run.meta.get(key) for key in ("name", "started_utc", "commit", "dirty", "untracked", "exe_sha16", + "built_with", "gpu", "driver", "play_args", "world_seconds", + "max_minutes")}, + "settings": run.settings or {}, + "precompile": run.precompile, + "times": { + "world_at_s": round(world, 3) if world is not None else None, + "warm_at_s": round(run.warm_at(world), 3) if run.warm_at(world) is not None else None, + "stop_at_s": round(stop, 3) if stop is not None else None, + "world_s": round(world_s, 3), + "exit_at_s": round(exited["t_s"], 3) if exited else None, + }, + "fps": fps, + "pipelines": {"missed_waits": len(run.missed), "making_max": max((m for *_, m in run.frames), default=0)}, + "crash": { + "kind": crash_kind, + "at_s": round(first["at_s"], 3) if first and first["at_s"] is not None else None, + "code_hex": first.get("code_hex") if first else None, + "module": first.get("module") if first else None, + "access": first.get("access") if first else None, + "title_watchdog": bool(first and first.get("title_watchdog")), + "count": len(run.crashes), + }, + "exit": {"code_hex": f"0x{code & 0xFFFFFFFF:08X}" if code is not None else None, + "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}, + "relaunched": run.relaunched, + "verdict": {"result": result, "reasons": fails + errors, "warnings": warnings, "min_world_s": min_world}, + } + + +def main(argv): + if len(argv) != 3 or argv[1] not in ("state", "summary"): + print(__doc__.strip(), file=sys.stderr) + return 2 + run = Run(argv[2]) + if argv[1] == "state": + print(json.dumps(state(run))) + return 0 + out = summary(run) + 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") + v = out["verdict"] + print(f"{v['result']}: {out['times']['world_s']:.0f} s in the world" + + (f"; {', '.join(v['reasons'])}" if v["reasons"] else "") + + (f" (warnings: {', '.join(v['warnings'])})" if v["warnings"] else "")) + return {"PASS": 0, "FAIL": 1}.get(v["result"], 2) + + +if __name__ == "__main__": + try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode + sys.stdout.reconfigure(errors="replace") + except (AttributeError, ValueError, OSError): + pass + sys.exit(main(sys.argv))