From abfc2bde3ac3405c2a3a6b95d12eb4e290f4e597 Mon Sep 17 00:00:00 2001 From: gertvw23 Date: Sat, 28 Nov 2026 21:06:52 +0100 Subject: [PATCH] Rig launcher: live watch, processes left behind, tests - scripts\watch-rig.ps1: the live watch as a script of its own (-Watch opens it beside the game): fps, stalls, memory and GPU every minute; alerts at once on low commit, out-of-memory, log errors, stalls, GPU heat, and a hang (the game's log still for 60 s, or its window not responding for 15 s), as the start that froze on 2026-11-28 did. - Processes left behind: every victory.exe is listed as game, preload or warm worker; only those left behind (a game without a window, a preload or worker whose parent is gone) are offered to be ended, with what they started. Work whose parent still runs is listed and left alone. - An error in the watcher's runspace is now reported instead of lost. It found a bug in this change: the new -Watch switch and the watcher's $watch script block were one variable (names are not case-sensitive), so the runspace ran the word False. Renamed to $watchScript. - scripts\tests\play-rig.Tests.ps1: 13 Pester tests (3.4, Windows 10's own) against a stand-in victory.exe in a temporary VICTORY_HOME. Co-Authored-By: Claude Opus 5.5 --- docs/rig-launcher.md | 33 +++++ scripts/play-rig.ps1 | 61 +++++++- scripts/tests/play-rig.Tests.ps1 | 230 +++++++++++++++++++++++++++++++ scripts/watch-rig.ps1 | 186 +++++++++++++++++++++++++ 4 files changed, 503 insertions(+), 7 deletions(-) create mode 100644 scripts/tests/play-rig.Tests.ps1 create mode 100644 scripts/watch-rig.ps1 diff --git a/docs/rig-launcher.md b/docs/rig-launcher.md index 6c2a3ef5..29fbed91 100644 --- a/docs/rig-launcher.md +++ b/docs/rig-launcher.md @@ -93,6 +93,38 @@ against: they came from one crashed run. The summary's numbers come from the layer's own once-a-second frame-time lines. Seconds drawn faster than 125 frames a second (menus, loading screens) are left out; "under 10 fps" counts the stalls. +## Live watch (`scripts\watch-rig.ps1`, or `-Watch`) + +Read-only, at below-normal priority, every 5 s: the newest play log, Windows' commit, the game's +processes and `nvidia-smi`. Every minute (`-ReportEvery`) a line with rendered fps (median and slowest +5 %), seconds under 10 fps, commit free, the game's memory and CPU, GPU load, VRAM, temperature and power; +while the shader preload runs, its progress instead. At once (and not more than every minute or two): +commit under 5 GB, the layer's memory-pressure and out-of-memory lines, errors in the log, 15 s under +10 fps, the GPU at 84 C, and a hang: the game's log still for 60 s (not with `VICTORY_LOG=warn`) or +Windows finding its window not responding for 15 s. When the game has ended, one line for the whole run. + +## Processes left behind + +Before a start the launcher lists every `victory.exe` with what it is: the game (`play` / `run`), the +shader preload, or one of its pipeline workers (`warm`). It offers to end only those left behind: a game +without a window, or a preload or worker whose parent process is gone (a closed window or a killed +preload leaves those). A game with its window, or a preload or warm run whose parent still runs, is +listed but left alone: it may be someone's work in progress. + +## Tests + +```powershell +Invoke-Pester .\scripts\tests # Pester 3.4 (Windows 10's own) or later 3.x / 4.x; about 3 minutes +``` + +They run the launcher and the watcher as separate processes against a stand-in `victory.exe` compiled +for the purpose, in a temporary `VICTORY_HOME`: no game files, and nothing of a real setup is read or +changed. Covered: the log summary (crash, close, menus left out), `-Compare` (verdict, noise, too few +runs), `-Set` with commas, `-Check` starting nothing, processes left behind vs work in progress, the +preload's exit code (stopped early, done), the skip choice, the runs file's new columns with older rows +kept, and the watcher's end-of-run line. Not covered: the real game, the window changes and the +fast-core preference (see above for those). + ## Options | Option | What | @@ -105,5 +137,6 @@ than 125 frames a second (menus, loading screens) are left out; "under 10 fps" c | `-Preload auto` / `yes` / `no` | the shader preload. Auto asks yes / no this time / skip for this version (remembered). It counts as done only when victory.exe's preload process exits with 0; stopped early, the next start says how many pipelines are built and offers to go on | | `-Try cores` / `room`, `-Compare` | A/B tests and their comparison (above) | | `-NoFullscreen` | leave the window as the layer makes it | +| `-Watch` | a second window with `scripts\watch-rig.ps1` (below) | | `-Set VICTORY_X=1` | add or override any switch (`-Set "VICTORY_A=1,VICTORY_B=2"` from cmd) | | `-Yes` | take the default answer to every question | diff --git a/scripts/play-rig.ps1 b/scripts/play-rig.ps1 index 304541f1..4d2d2440 100644 --- a/scripts/play-rig.ps1 +++ b/scripts/play-rig.ps1 @@ -56,6 +56,8 @@ param( # Only the comparison of the runs in rig-runs.csv, by settings, and what they say about the memory needed. [switch]$Compare, [switch]$NoFullscreen, + # A second window with scripts\watch-rig.ps1: fps, memory and GPU every minute, alerts at once, until the game ends. + [switch]$Watch, # Add or override a switch: -Set VICTORY_X=1,VICTORY_Y=2 [string[]]$Set = @(), # Take the default answer to every question. @@ -287,6 +289,28 @@ function Get-Rig([string]$gameExe, [string]$victoryExe) { } } +# Every victory.exe, what it is (game: `play` / `run`; preload; warm: a pipeline worker or a warm run; other) +# and whether it was left behind: a game without a window, or a preload or warm process whose parent is gone. +function Get-VictoryProcesses { + $all = @(Get-CimInstance Win32_Process -Filter "Name='victory.exe'" -ErrorAction SilentlyContinue) + $alive = @{}; foreach ($p in Get-Process -ErrorAction SilentlyContinue) { $alive[[int]$p.Id] = $p } + foreach ($w in $all) { + $cmd = [string]$w.CommandLine + $kind = if ($cmd -match '\spreload(\s|$)') { 'preload' } elseif ($cmd -match '\swarm(\s|$)') { 'warm' } elseif ($cmd -match '\s(play|run)(\s|$)') { 'game' } else { 'other' } + $proc = $alive[[int]$w.ProcessId] + $window = $proc -and $proc.MainWindowHandle -ne [IntPtr]::Zero + # A parent id can be reused after the parent ended: it only counts if that process started before this one. + $parent = $alive[[int]$w.ParentProcessId] + $parentAlive = $false + if ($parent -and $proc) { try { $parentAlive = $parent.StartTime -le $proc.StartTime } catch { $parentAlive = $true } } + $leftBehind = switch ($kind) { 'game' { -not $window } { $_ -in 'preload', 'warm' } { -not $parentAlive } default { $false } } + $state = if ($kind -eq 'game') { if ($window) { 'with a window' } else { 'no window (left behind)' } } + elseif ($kind -in 'preload', 'warm') { if ($parentAlive) { 'its parent is still running' } else { 'its parent is gone (left behind)' } } + else { 'not started by the launcher' } + [pscustomobject]@{ Id = [int]$w.ProcessId; Kind = $kind; CommitGB = if ($proc) { $proc.PrivateMemorySize64 / 1GB } else { 0 }; State = $state; LeftBehind = [bool]$leftBehind } + } +} + function Show-Rig($rig) { Write-Host '' Write-Host 'This PC' -ForegroundColor Cyan @@ -315,18 +339,27 @@ function Test-Rig($rig, [string]$victoryExe) { Write-Host 'Checks' -ForegroundColor Cyan # A game process left behind (the F1 menu's SAVE AND RESTART can leave one without a window) holds its memory. - $left = @(Get-Process victory -ErrorAction SilentlyContinue) + # So can the shader preload's pipeline workers (`victory warm`) when their parent was closed or killed. Only + # those left behind are offered to be ended: a game with its window, or a preload or warm run whose parent + # is still there (started by hand, or by a build or test elsewhere), is someone's work in progress. + $left = @(Get-VictoryProcesses) if ($left.Count) { - foreach ($p in $left) { - Write-Line 'FIX' ("victory.exe already running: pid {0}, {1:N1} GB committed, {2}" -f $p.Id, ($p.PrivateMemorySize64 / 1GB), $(if ($p.MainWindowHandle -ne 0) { 'with a window' } else { 'no window (left behind)' })) + foreach ($v in $left) { + $tag = if ($v.LeftBehind) { 'FIX' } else { 'WARN' } + Write-Line $tag ("victory.exe already running: pid {0}, {1}, {2:N1} GB committed, {3}" -f $v.Id, $v.Kind, $v.CommitGB, $v.State) } - if (Read-YesNo ' End these victory.exe processes first? Their memory counts against this run.' $false) { - $left | ForEach-Object { Stop-Process -Id $_.Id -ErrorAction SilentlyContinue } + $stale = @($left | Where-Object LeftBehind) + if ($stale.Count -and (Read-YesNo (" End the {0} left behind (and anything they started)? Their memory counts against this run." -f $stale.Count) $false)) { + foreach ($v in $stale) { & taskkill.exe /PID $v.Id /T /F 2>&1 | Out-Null } Start-Sleep -Seconds 2 $os = Get-CimInstance Win32_OperatingSystem $rig.CommitFreeGB = [math]::Round($os.FreeVirtualMemory / 1MB, 1) Write-Line 'OK' ("ended; commit free now {0:N1} GB" -f $rig.CommitFreeGB) } + if (@($left | Where-Object { -not $_.LeftBehind }).Count) { + Write-Host ' The others look like work in progress (a running game, or a preload or warm run whose parent is' + Write-Host ' still there); close them yourself if they are yours and not needed.' + } } else { Write-Line 'OK' 'no victory.exe left running' } @@ -774,7 +807,9 @@ Save-State $state $sync = [hashtable]::Synchronized(@{ Stop = $false; Notes = [System.Collections.ArrayList]::Synchronized((New-Object System.Collections.ArrayList)) PreloadExit = $null; MinCommitMB = $null; PeakGameMB = 0 }) $pin = if ($Cores -eq 'pcores' -and $rig.Hybrid) { $rig.FastIds } else { $null } -$watch = { +# (Not $watch: names are not case-sensitive, and -Watch is the script's switch; assigned to it, this +# script block became the word False.) +$watchScript = { param($RunnerPath, $PinIds, $MakeBorderless, $Sync, $LogsDir, $SettleSeconds) $seen = @{} $tick = 0 @@ -837,7 +872,7 @@ $watch = { } } $ps = [powershell]::Create() -[void]$ps.AddScript($watch).AddArgument($runner).AddArgument($pin).AddArgument(-not $NoFullscreen).AddArgument($sync).AddArgument((Join-Path $vhome 'logs')).AddArgument(15) +[void]$ps.AddScript($watchScript).AddArgument($runner).AddArgument($pin).AddArgument(-not $NoFullscreen).AddArgument($sync).AddArgument((Join-Path $vhome 'logs')).AddArgument(15) $handle = $ps.BeginInvoke() # --------------------------------------------------------------------------------------------------------------- @@ -845,6 +880,13 @@ $handle = $ps.BeginInvoke() # --------------------------------------------------------------------------------------------------------------- $began = Get-Date $preloadOk = $false +if ($Watch) { + $watcher = Join-Path $PSScriptRoot 'watch-rig.ps1' + if (Test-Path -LiteralPath $watcher) { + Start-Process powershell -ArgumentList @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-NoExit', '-File', "`"$watcher`"") | Out-Null + Write-Host ' live watch: a second window (fps, memory and GPU every minute; it stays open after the game ends)' + } else { Write-Line 'WARN' "no $watcher" } +} Write-Host '' Write-Host 'Starting. F1 in the game: settings; F3: the stats panel.' -ForegroundColor Cyan & $runner @playArgs 2>&1 | ForEach-Object { @@ -857,6 +899,11 @@ $code = $LASTEXITCODE while (@(Get-Process victory -ErrorAction SilentlyContinue | Where-Object { try { $_.Path -eq $runner } catch { $false } }).Count) { Start-Sleep -Seconds 2 } $sync.Stop = $true [void]$ps.EndInvoke($handle) +# The watcher runs in a runspace of its own; an error there would otherwise go unseen. +if ($ps.Streams.Error.Count) { + $first = $ps.Streams.Error[0] + Write-Line 'WARN' ("the watcher stopped on an error ({0} in all): {1} (line {2})" -f $ps.Streams.Error.Count, $first.Exception.Message, $first.InvocationInfo.ScriptLineNumber) +} $ps.Dispose() foreach ($n in $sync.Notes) { Write-Host " $n" } diff --git a/scripts/tests/play-rig.Tests.ps1 b/scripts/tests/play-rig.Tests.ps1 new file mode 100644 index 00000000..4c37d5ba --- /dev/null +++ b/scripts/tests/play-rig.Tests.ps1 @@ -0,0 +1,230 @@ +# Tests for scripts\play-rig.ps1 and scripts\watch-rig.ps1, run as a user would run them (separate processes), +# in a folder of their own: VICTORY_HOME points there, so nothing of a real setup is read or changed. A stand-in +# victory.exe (compiled here) plays the game's part; no game files are used. +# +# Invoke-Pester .\scripts\tests (Pester 3.4, as Windows 10 ships it, or later 3.x/4.x) +# +# ASCII only. +$here = Split-Path -Parent $MyInvocation.MyCommand.Path +$scripts = Split-Path -Parent $here +$launcher = Join-Path $scripts 'play-rig.ps1' +$watcher = Join-Path $scripts 'watch-rig.ps1' + +$root = Join-Path ([IO.Path]::GetTempPath()) ('play-rig-tests-' + [guid]::NewGuid().ToString('N').Substring(0, 8)) +$home_ = Join-Path $root 'home' +$game = Join-Path $root 'game\game_scarlett_master.exe' +$fake = Join-Path $root 'bin\victory.exe' +New-Item -ItemType Directory -Force (Join-Path $home_ 'logs'), (Join-Path $home_ 'cache\pipelines'), (Join-Path $home_ 'data\7952987A'), (Split-Path $game), (Split-Path $fake) | Out-Null +Set-Content $game 'placeholder' -Encoding ASCII + +# The stand-in: `play ... [--preload]` runs a `preload` child (exit code FAKE_PRELOAD_EXIT, 3 warm-done lines), +# then writes a 90-window play log and stays FAKE_PLAY_SECONDS; `warm ...` just stays FAKE_PLAY_SECONDS. +Add-Type -OutputType ConsoleApplication -OutputAssembly $fake -TypeDefinition @' +using System; +using System.Diagnostics; +using System.IO; +using System.Threading; +public static class Program { + static int Seconds() { return int.Parse(Environment.GetEnvironmentVariable("FAKE_PLAY_SECONDS") ?? "2"); } + public static int Main(string[] args) { + string home = Environment.GetEnvironmentVariable("VICTORY_HOME"); + if (args.Length > 0 && args[0] == "warm") { Thread.Sleep(Seconds() * 1000); return 0; } + if (args.Length > 0 && args[0] == "preload") { + using (StreamWriter w = File.AppendText(Path.Combine(home, "cache", "pipelines", "warm-done.txt"))) + for (int i = 0; i < 3; i++) w.WriteLine("fp k" + Guid.NewGuid().ToString("N")); + // Long enough for the launcher's watcher, which needs a few seconds to start, to see it. + Thread.Sleep(8000); + return int.Parse(Environment.GetEnvironmentVariable("FAKE_PRELOAD_EXIT") ?? "0"); + } + Console.WriteLine("args: " + string.Join(" | ", args)); + if (Array.IndexOf(args, "--preload") >= 0) { + Process child = Process.Start(new ProcessStartInfo(Process.GetCurrentProcess().MainModule.FileName, "preload C:\\game") { UseShellExecute = false }); + child.WaitForExit(); + } + int pid = Process.GetCurrentProcess().Id; + string log = Path.Combine(home, "logs", "victory-nvidia-play-20261128-000000-" + pid + ".log"); + using (StreamWriter w = new StreamWriter(log)) { + w.WriteLine("# console=series-x build=release switches: VICTORY_MENU_CONSOLE=series-x VICTORY_MENU_RES=1440 VICTORY_MENU_DLSS=quality VICTORY_MENU_FRAMEGEN=2"); + DateTime t = new DateTime(2026, 11, 28, 12, 0, 0, DateTimeKind.Utc); + for (int i = 0; i < 90; i++) + w.WriteLine(t.AddSeconds(i).ToString("yyyy-MM-ddTHH:mm:ss.ffffffZ") + " INFO victory_gpu::frame_times: frame times: 30 frames, median 33.3 ms, p95 40.0, p99 45.0, longest 50.0"); + w.WriteLine(t.AddSeconds(91).ToString("yyyy-MM-ddTHH:mm:ss.ffffffZ") + " INFO victory_hle::modules::lifecycle: title suspended; ending the title"); + } + Thread.Sleep(Seconds() * 1000); + return 0; + } +} +'@ + +function Invoke-Launcher([string[]]$more) { + $env:VICTORY_HOME = $home_ + $all = @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', $launcher, '-Exe', $game, '-Victory', $fake, '-NoFullscreen', '-Yes') + $more + $out = & powershell @all 2>&1 | ForEach-Object { "$_" } + return ($out -join "`n") +} + +function New-Log([string]$name, [double[]]$ms, [string[]]$extra) { + $t = [datetime]'2026-11-28T12:00:00' + $lines = @('# console=series-x build=release switches: VICTORY_MENU_CONSOLE=series-x VICTORY_MENU_RES=1440 VICTORY_MENU_DLSS=quality VICTORY_MENU_FRAMEGEN=0') + for ($i = 0; $i -lt $ms.Count; $i++) { + $lines += ('{0:yyyy-MM-ddTHH:mm:ss}.000000Z INFO victory_gpu::frame_times: frame times: 30 frames, median {1} ms, p95 40.0, p99 45.0, longest 50.0' -f $t.AddSeconds($i), $ms[$i].ToString([Globalization.CultureInfo]::InvariantCulture)) + } + $lines += $extra + $path = Join-Path $home_ "logs\$name" + Set-Content $path $lines -Encoding ASCII + return $path +} + +function New-Runs([object[]]$rows) { + $file = Join-Path $home_ 'rig-runs.csv' + $rows | ForEach-Object { [pscustomobject]$_ } | Export-Csv $file -NoTypeInformation -Encoding UTF8 +} + +function Row([string]$variant, [double]$fps, [int]$seconds = 300) { + [ordered]@{ When = '2026-11-28 12:00'; Log = 'x.log'; Console = 'series-x'; Res = '1440'; Dlss = 'quality'; FrameGen = '2'; Cores = 'layer' + Workers = ''; Room = ''; GameSeconds = $seconds; FpsMedian = $fps; FpsLow = $fps - 3; Stalls = 2; MinCommitMB = ''; OutOfMemory = 0; Ended = 'closed' + Variant = $variant; CommitStartGB = 33; MinCommitFreeGB = 12; PeakGameGB = 20 } +} + +try { + Describe 'the scripts' { + It 'parse, and are ASCII only (Windows PowerShell 5.1 reads them as ANSI)' { + foreach ($f in $launcher, $watcher) { + $errors = $null + [void][Management.Automation.Language.Parser]::ParseFile($f, [ref]$null, [ref]$errors) + $errors.Count | Should Be 0 + ([regex]::Matches([IO.File]::ReadAllText($f), '[^\x00-\x7F]')).Count | Should Be 0 + } + } + } + + Describe '-Summary' { + It 'calls a run with out-of-memory errors and a crash record a crash' { + $log = New-Log 'victory-nvidia-play-20261128-120000-4196.log' @(33.3, 33.3, 400, 33.3) @('2026-11-28T12:00:05.0Z WARN victory_gpu::host: no shared buffer error=Not enough memory (0x8007000E) size=4194304') + Set-Content (Join-Path $home_ 'data\7952987A\crashes.log') @('unix time 1795886387, process 4196', 'VIctory: host GPU failure: out of memory') -Encoding ASCII + $out = Invoke-Launcher @('-Summary', '-Log', $log) + $out | Should Match 'it crashed' + $out | Should Match 'host GPU failure' + $out | Should Match '1 out-of-memory errors' + $out | Should Match '1 s under 10 fps' + } + It 'leaves menus out and calls a run with its closing line closed' { + $log = New-Log 'victory-nvidia-play-20261128-120000-77.log' @(2.0, 2.0, 33.3, 33.3, 33.3) @('2026-11-28T12:00:09.0Z INFO victory_hle::modules::lifecycle: title suspended; ending the title') + $out = Invoke-Launcher @('-Summary', '-Log', $log) + $out | Should Match 'it was closed' + $out | Should Match 'of it 3 s in the game' + $out | Should Match 'median 30\.0 fps' + } + } + + Describe '-Compare' { + It 'gives a verdict with three long runs a side, and ignores untagged and short runs' { + New-Runs @((Row 'cores=layer' 30), (Row 'cores=layer' 29.8), (Row 'cores=layer' 30.2), (Row 'cores=pcores' 33), (Row 'cores=pcores' 32.8), (Row 'cores=pcores' 33.1), (Row 'cores=pcores' 5 20), (Row '' 10)) + $out = Invoke-Launcher @('-Compare') + $out | Should Match 'cores=pcores vs cores=layer: \+10\.0 % median fps' + $out | Should Not Match 'not enough runs' + $out | Should Match 'took up to 21\.0 GB of commit' + } + It 'calls a difference under 3 % noise' { + New-Runs @((Row 'room=80' 30), (Row 'room=80' 30), (Row 'room=80' 30), (Row 'room=84' 30.5), (Row 'room=84' 30.5), (Row 'room=84' 30.5)) + (Invoke-Launcher @('-Compare')) | Should Match 'no clear winner' + } + It 'asks for more runs below three a side' { + New-Runs @((Row 'cores=layer' 30), (Row 'cores=pcores' 33)) + (Invoke-Launcher @('-Compare')) | Should Match 'not enough runs yet' + } + } + + Describe '-Check' { + It 'passes -Set values with commas whole, and splits only before another VICTORY_ name' { + $out = Invoke-Launcher @('-Check', '-Set', 'VICTORY_LEAVE_OUT=aa,bb,VICTORY_AMBIENT=0') + $out | Should Match '--set VICTORY_LEAVE_OUT=aa,bb --set VICTORY_AMBIENT=0' + } + It 'starts nothing' { + $before = @(Get-ChildItem (Join-Path $home_ 'logs') -Filter 'victory-nvidia-play-*.log').Count + [void](Invoke-Launcher @('-Check')) + @(Get-ChildItem (Join-Path $home_ 'logs') -Filter 'victory-nvidia-play-*.log').Count | Should Be $before + } + } + + Describe 'leftover victory.exe processes' { + It 'calls a warm worker whose parent is gone left behind, and one whose parent runs work in progress' { + $env:VICTORY_HOME = $home_; $env:FAKE_PLAY_SECONDS = '40' + # An orphan: started by a PowerShell that ends at once. + # (WaitForExit on the PowerShell alone: Start-Process -Wait in 5.1 also waits for what it started.) + $starter = Start-Process powershell -WindowStyle Hidden -PassThru -ArgumentList @('-NoProfile', '-Command', "Start-Process '$fake' -ArgumentList 'warm','--these','1' -WindowStyle Hidden") + $starter.WaitForExit() + # Not an orphan: started by this test, which is still running. + $mine = Start-Process $fake -ArgumentList 'warm', '--these', '2' -WindowStyle Hidden -PassThru + Start-Sleep -Seconds 2 + try { + $orphan = Get-CimInstance Win32_Process -Filter "Name='victory.exe'" | Where-Object { $_.CommandLine -match '--these 1' } | Select-Object -First 1 + $orphan | Should Not BeNullOrEmpty + $out = Invoke-Launcher @('-Check') + $out | Should Match ("pid {0}, warm, [\d.]+ GB committed, its parent is gone \(left behind\)" -f $orphan.ProcessId) + $out | Should Match ("pid {0}, warm, [\d.]+ GB committed, its parent is still running" -f $mine.Id) + # -Yes takes the default answer, no: nothing is ended. + (Get-Process -Id $orphan.ProcessId -ErrorAction SilentlyContinue) | Should Not BeNullOrEmpty + } finally { + Get-CimInstance Win32_Process -Filter "Name='victory.exe'" | Where-Object { $_.ExecutablePath -eq $fake } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue } + $env:FAKE_PLAY_SECONDS = $null + } + } + } + + Describe 'the shader preload' { + It 'counts a preload that exits with 1 as stopped early, and one that exits with 0 as done' { + $env:FAKE_PLAY_SECONDS = '8' + $env:FAKE_PRELOAD_EXIT = '1' + $out = Invoke-Launcher @('-Preload', 'yes') + $out | Should Match 'shader preload stopped early \(ended with code 1\): 3 pipelines built so far' + (Invoke-Launcher @('-Check')) | Should Match 'partly done \(3 pipelines built so far\)' + $env:FAKE_PRELOAD_EXIT = '0' + $out = Invoke-Launcher @('-Preload', 'auto') + $out | Should Match 'shader preload complete \(6 pipelines built in all\)' + (Invoke-Launcher @('-Check')) | Should Match 'shaders already preloaded' + $env:FAKE_PRELOAD_EXIT = $null + } + It 'does not ask again after skip for this version' { + $state = Join-Path $home_ 'rig-launcher.json' + $s = Get-Content $state -Raw | ConvertFrom-Json + $key = $s.preloaded + $s.PSObject.Properties.Remove('preloaded') + $s | Add-Member -NotePropertyName preloadSkip -NotePropertyValue $key -Force + $s | ConvertTo-Json | Set-Content $state + $out = Invoke-Launcher @('-Check') + $out | Should Match 'shader preload skipped for this victory.exe and driver' + $out | Should Not Match '--preload' + } + It 'records the run with its memory columns, keeping older rows' { + New-Runs @((Row '' 29)) + $env:FAKE_PLAY_SECONDS = '12' + [void](Invoke-Launcher @('-Preload', 'no', '-Try', 'cores')) + $rows = @(Import-Csv (Join-Path $home_ 'rig-runs.csv')) + $rows.Count | Should Be 2 + $rows[1].Variant | Should Match '^cores=(layer|pcores)$' + $rows[1].GameSeconds | Should Be '90' + $rows[1].CommitStartGB | Should Not BeNullOrEmpty + $rows[1].PeakGameGB | Should Not BeNullOrEmpty + $env:FAKE_PLAY_SECONDS = $null + } + } + + Describe 'watch-rig.ps1' { + It 'reports the end of a run from its log, bounded' { + Remove-Item (Join-Path $home_ 'logs\*') -Force + $env:VICTORY_HOME = $home_; $env:FAKE_PLAY_SECONDS = '6' + $play = Start-Process $fake -ArgumentList 'play', 'x' -WindowStyle Hidden -PassThru + $out = & powershell -NoProfile -ExecutionPolicy Bypass -File $watcher -ReportEvery 3 -MaxMinutes 2 2>&1 | ForEach-Object { "$_" } + $text = $out -join "`n" + $text | Should Match 'victory.exe started' + $text | Should Match 'GAME ENDED, closed normally' + $text | Should Match '90 s in game, rendered fps median 30\.0' + $env:FAKE_PLAY_SECONDS = $null + } + } +} finally { + Get-CimInstance Win32_Process -Filter "Name='victory.exe'" | Where-Object { $_.ExecutablePath -eq $fake } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue } + $env:VICTORY_HOME = $null + Remove-Item -Recurse -Force $root -ErrorAction SilentlyContinue +} diff --git a/scripts/watch-rig.ps1 b/scripts/watch-rig.ps1 new file mode 100644 index 00000000..1fadcd0b --- /dev/null +++ b/scripts/watch-rig.ps1 @@ -0,0 +1,186 @@ +# Live performance watch for a VIctory run, in a window of its own (play-rig.ps1 -Watch opens it), read-only: +# the newest play log in %LOCALAPPDATA%\victory\logs, Windows' commit, the game's processes, nvidia-smi. It waits +# for victory.exe, reports every -ReportEvery seconds (rendered fps, stalls, memory, GPU), alerts at once on low +# commit, out-of-memory, errors in the log, stalls and GPU heat, and ends with a line for the whole run. +# +# .\scripts\watch-rig.ps1 until the game ends +# .\scripts\watch-rig.ps1 -ReportEvery 30 +# .\scripts\watch-rig.ps1 -MaxMinutes 29 -StateFile x.json bounded; a later start with the same file carries on +# +# Nothing it does touches the game: it reads files and counters, at below-normal priority, every 5 s. +# Windows PowerShell 5.1 or PowerShell 7. ASCII only. +param([string]$StateFile = '', [int]$ReportEvery = 60, [int]$MaxMinutes = 0) +$ErrorActionPreference = 'SilentlyContinue' +try { (Get-Process -Id $PID).PriorityClass = 'BelowNormal' } catch { } +$vhome = if ($env:VICTORY_HOME) { $env:VICTORY_HOME } else { Join-Path $env:LOCALAPPDATA 'victory' } +$logsDir = Join-Path $vhome 'logs' +$cacheDir = if ($env:VICTORY_CACHE_DIR) { $env:VICTORY_CACHE_DIR } else { Join-Path $vhome 'cache' } +$inv = [Globalization.CultureInfo]::InvariantCulture +# Plain lines when the output is piped (a log, another program); coloured alerts in a console. +function Emit([string]$s) { + $line = '{0:HH:mm:ss} {1}' -f (Get-Date), $s + if ([Console]::IsOutputRedirected) { [Console]::Out.WriteLine($line); [Console]::Out.Flush() } + elseif ($s -like 'ALERT*') { Write-Host $line -ForegroundColor Yellow } + elseif ($s -like 'GAME ENDED*') { Write-Host $line -ForegroundColor Cyan } + else { Write-Host $line } +} + +$s = $null +if ($StateFile -and (Test-Path -LiteralPath $StateFile)) { try { $s = Get-Content -LiteralPath $StateFile -Raw | ConvertFrom-Json } catch { } } +$fresh = -not $s +if ($fresh) { + $s = [pscustomobject]@{ Since = (Get-Date).AddMinutes(-2).ToString('o'); Log = ''; Offset = 0; Fps = @(); Stalls = 0; MinCommitMB = 999999 + PeakVramMB = 0; PeakGameMB = 0; MaxTempC = 0; Errors = 0; Oom = 0; Pressure = 0; GameSeen = $false; Suspended = $false; Logs = 0; FgOn = '' } +} +$fps = New-Object System.Collections.Generic.List[double]; foreach ($v in @($s.Fps)) { if ($null -ne $v) { $fps.Add([double]$v) } } +$since = [datetime]::Parse($s.Since, $inv, [Globalization.DateTimeStyles]::RoundtripKind) +$lastAlert = @{} +function Alert([string]$kind, [string]$text, [int]$every = 120) { + $now = Get-Date + if (-not $lastAlert.ContainsKey($kind) -or ($now - $lastAlert[$kind]).TotalSeconds -ge $every) { $lastAlert[$kind] = $now; Emit "ALERT $text" } +} +function Save { + $s.Fps = @($fps | Select-Object -Last 20000) + if ($StateFile) { $s | ConvertTo-Json -Depth 3 -Compress | Set-Content -LiteralPath $StateFile -Encoding UTF8 } +} +function Pct($list, [double]$q) { $a = @($list | Sort-Object); if (-not $a.Count) { return $null }; $a[[math]::Min($a.Count - 1, [math]::Floor($q * $a.Count))] } +function CacheMB { [math]::Round(((Get-ChildItem $cacheDir -Recurse -File -ErrorAction SilentlyContinue | Measure-Object Length -Sum).Sum) / 1MB) } + +if ($fresh) { Emit 'watching: waiting for victory.exe (preload, then the game)' } else { Emit 'watch re-armed; carrying on' } +$deadline = if ($MaxMinutes -gt 0) { (Get-Date).AddMinutes($MaxMinutes) } else { [datetime]::MaxValue } +$lastReport = Get-Date +$win = New-Object System.Collections.Generic.List[double] # in-game fps windows since the last report +$gpuUtil = New-Object System.Collections.Generic.List[double] +$cpuPct = New-Object System.Collections.Generic.List[double] +$cmdOf = @{}; $prevCpu = $null; $prevAt = $null; $goneSince = $null; $wasPreloading = $false; $preloadAt = $null; $preloadCache = 0 +$lowRun = 0; $partial = ''; $logMovedAt = $null; $notResponding = 0 +$logical = [Environment]::ProcessorCount + +while ((Get-Date) -lt $deadline) { + # --- processes + $procs = @(Get-Process victory -ErrorAction SilentlyContinue) + foreach ($p in $procs) { if (-not $cmdOf.ContainsKey($p.Id)) { $cmdOf[$p.Id] = [string](Get-CimInstance Win32_Process -Filter "ProcessId=$($p.Id)").CommandLine } } + $preloading = @($procs | Where-Object { $cmdOf[$_.Id] -match '\spreload\s' }).Count -gt 0 + if ($procs.Count) { + if (-not $s.GameSeen) { $s.GameSeen = $true; Emit "victory.exe started (pid $(($procs | ForEach-Object Id) -join ', '))" } + $goneSince = $null + } elseif ($s.GameSeen) { + if (-not $goneSince) { $goneSince = Get-Date } + elseif (((Get-Date) - $goneSince).TotalSeconds -ge 40) { + # The end: one line with the whole run. + $crash = '' + if ($s.Log -match '-(\d+)\.log$') { + $procId = $Matches[1] + foreach ($f in Get-ChildItem (Join-Path $vhome 'data\*\crashes.log')) { + $t = Get-Content -LiteralPath $f.FullName + for ($i = 0; $i -lt $t.Count - 1; $i++) { if ($t[$i] -match "^unix time \d+, process $procId\s*$") { $crash = $t[$i + 1] } } + } + } + $how = if ($crash) { "CRASHED: $crash" } elseif ($s.Suspended) { 'closed normally' } else { 'ended without the normal closing line (crash or killed?)' } + $med = Pct $fps 0.5; $low = Pct $fps 0.05 + Emit ("GAME ENDED, {0}. Whole run: {1} s in game, rendered fps median {2} / slowest 5% {3}, {4} s under 10 fps; lowest commit free {5:N1} GB; peak game memory {6:N1} GB; peak VRAM {7:N1} GB; max GPU temp {8} C; {9} errors, {10} out-of-memory, {11} memory-pressure warnings; {12} run log(s)" -f ` + $how, $fps.Count, $(if ($null -ne $med) { '{0:N1}' -f $med } else { '-' }), $(if ($null -ne $low) { '{0:N1}' -f $low } else { '-' }), $s.Stalls, ($s.MinCommitMB / 1024), ($s.PeakGameMB / 1024), ($s.PeakVramMB / 1024), $s.MaxTempC, $s.Errors, $s.Oom, $s.Pressure, $s.Logs) + if ($StateFile) { Remove-Item -LiteralPath $StateFile -ErrorAction SilentlyContinue } + exit 0 + } + } + if ($preloading -and -not $wasPreloading) { $preloadAt = Get-Date; $preloadCache = CacheMB; Emit "shader preload running (cache $preloadCache MB)" } + if (-not $preloading -and $wasPreloading) { Emit ("shader preload finished after {0:N1} min (cache {1} MB); the game is starting" -f ((Get-Date) - $preloadAt).TotalMinutes, (CacheMB)) } + $wasPreloading = $preloading + + # --- the newest play log since the watch began + $newest = Get-ChildItem $logsDir -Filter 'victory-nvidia-play-*.log' | Where-Object { $_.LastWriteTime -ge $since } | Sort-Object LastWriteTime | Select-Object -Last 1 + if ($newest -and $newest.FullName -ne $s.Log) { + if ($s.Log) { Emit "new run log $($newest.Name): the game restarted (warm-up restart or F1 menu)" } + $s.Log = $newest.FullName; $s.Offset = 0; $s.Logs++; $partial = ''; $s.Suspended = $false + $head = Get-Content -LiteralPath $newest.FullName -TotalCount 1 + if ($head -match 'VICTORY_MENU_FRAMEGEN=(\d)') { $s.FgOn = $Matches[1] } + } + if ($s.Log -and (Test-Path -LiteralPath $s.Log)) { + try { + $fs = [IO.File]::Open($s.Log, 'Open', 'Read', 'ReadWrite') + if ($fs.Length -gt $s.Offset) { $logMovedAt = Get-Date } + if ($fs.Length -gt $s.Offset) { + [void]$fs.Seek([int64]$s.Offset, 'Begin') + $sr = New-Object IO.StreamReader($fs) + $text = $partial + $sr.ReadToEnd() + $s.Offset = $fs.Length + $cut = $text.LastIndexOf("`n") + if ($cut -ge 0) { $partial = $text.Substring($cut + 1); $text = $text.Substring(0, $cut) } else { $partial = $text; $text = '' } + foreach ($line in $text -split "`r?`n") { + if ($line -match 'frame times: (\d+) frames, median ([\d.]+) ms') { + $ms = [double]::Parse($Matches[2], $inv) + if ($ms -ge 8.0) { + $f = 1000.0 / $ms; $fps.Add($f); $win.Add($f) + if ($f -lt 10) { $s.Stalls++; $lowRun++ } else { $lowRun = 0 } + if ($lowRun -eq 15) { Alert 'stall' 'under 10 fps for 15 s in a row (pipelines being made or streaming)' 180 } + } + } + elseif ($line -match 'host memory pressure.*available_commit_mib=(\d+)') { $s.Pressure++; Alert 'pressure' "the layer reports memory pressure: $($Matches[1]) MB of commit left" } + elseif ($line -match '0x8007000E') { $s.Oom++; Alert 'oom' "out-of-memory errors in the log ($($s.Oom) so far)" 60 } + elseif ($line -match '^\S+\s+ERROR\s+(.*)$') { $s.Errors++; $m = $Matches[1]; Alert 'error' ('ERROR in log: ' + $m.Substring(0, [math]::Min(180, $m.Length))) 90 } + elseif ($line -match 'DLSS Frame Generation (switched|is on with)|more frames asked than this card') { $m = $line -replace '^\S+\s+\S+\s+', ''; Emit ('frame generation: ' + $m.Substring(0, [math]::Min(160, $m.Length))) } + elseif ($line -match 'title suspended; ending the title') { $s.Suspended = $true } + } + $sr.Dispose() + } + $fs.Dispose() + } catch { } + } + + # --- a hang: the game (not the preload) runs, but its log has not moved, or Windows finds its window not + # responding. A start froze like this on 2026-11-28 (log stopped 3 s in; Windows closed it 4 min later). + $games = @($procs | Where-Object { $cmdOf[$_.Id] -notmatch '\s(preload|warm)(\s|$)' }) + if ($games.Count -and -not $preloading) { + if (-not $logMovedAt) { $logMovedAt = Get-Date } + $quiet = ((Get-Date) - $logMovedAt).TotalSeconds + # (A log set to warnings only, VICTORY_LOG=warn, is quiet anyway: no alert then.) + if ($quiet -ge 60 -and "$env:VICTORY_LOG" -notmatch '^\s*(warn|error)') { Alert 'quiet' ("the game's log has not moved for {0:N0} s: it may be frozen (if the picture is stuck too, close it and start again)" -f $quiet) 120 } + $stuck = @($games | Where-Object { $_.MainWindowHandle -ne [IntPtr]::Zero -and -not $_.Responding }) + if ($stuck.Count) { $notResponding++ } else { $notResponding = 0 } + if ($notResponding -eq 3) { Alert 'hung' 'Windows reports the game window as not responding (15 s so far)' 120 } + } else { $logMovedAt = $null; $notResponding = 0 } + + # --- the PC + $os = Get-CimInstance Win32_OperatingSystem + $commitMB = [int]($os.FreeVirtualMemory / 1KB) + if ($s.GameSeen -and $commitMB -lt $s.MinCommitMB) { $s.MinCommitMB = $commitMB } + if ($s.GameSeen -and $commitMB -lt 5120) { Alert 'commit' ("only {0:N1} GB of commit left: close other programs now or the game may crash" -f ($commitMB / 1024)) 90 } + # The game's memory: not the preload or its pipeline workers. + $gameMB = [int](($games | Measure-Object PrivateMemorySize64 -Sum).Sum / 1MB) + if ($gameMB -gt $s.PeakGameMB) { $s.PeakGameMB = $gameMB } + $cpuNow = ($procs | ForEach-Object { $_.TotalProcessorTime.TotalSeconds } | Measure-Object -Sum).Sum + $at = Get-Date + if ($null -ne $prevCpu -and $procs.Count -and $cpuNow -ge $prevCpu) { $cpuPct.Add(100 * ($cpuNow - $prevCpu) / (($at - $prevAt).TotalSeconds * $logical)) } + $prevCpu = $cpuNow; $prevAt = $at + $smi = nvidia-smi --query-gpu=utilization.gpu,memory.used,memory.total,temperature.gpu,power.draw --format=csv,noheader,nounits 2>$null | Select-Object -First 1 + $vramMB = 0; $vramTotal = 0; $temp = 0; $watts = 0 + # (Recent drivers give the temperature with decimals: "3, 1114, 16376, 41.32, 36.40".) + if ($smi -match '^\s*([\d.]+),\s*([\d.]+),\s*([\d.]+),\s*([\d.]+),\s*([\d.]+)') { + $gpuUtil.Add([double]::Parse($Matches[1], $inv)); $vramMB = [int][double]::Parse($Matches[2], $inv); $vramTotal = [int][double]::Parse($Matches[3], $inv) + $temp = [int][math]::Round([double]::Parse($Matches[4], $inv)); $watts = [double]::Parse($Matches[5], $inv) + if ($s.GameSeen -and $vramMB -gt $s.PeakVramMB) { $s.PeakVramMB = $vramMB } + if ($temp -gt $s.MaxTempC) { $s.MaxTempC = $temp } + if ($temp -ge 84) { Alert 'temp' "GPU at $temp C" 300 } + } + + # --- the periodic report + if (((Get-Date) - $lastReport).TotalSeconds -ge $ReportEvery -and $procs.Count) { + $cpuAvg = if ($cpuPct.Count) { ($cpuPct | Measure-Object -Average).Average } else { 0 } + $gpuAvg = if ($gpuUtil.Count) { ($gpuUtil | Measure-Object -Average).Average } else { 0 } + $sys = "commit free {0:N1} GB | game {1:N1} GB RAM, CPU {2:N0}% of all threads | GPU {3:N0}% busy, VRAM {4:N1}/{5:N1} GB, {6} C, {7:N0} W" -f ($commitMB / 1024), ($gameMB / 1024), $cpuAvg, $gpuAvg, ($vramMB / 1024), ($vramTotal / 1024), $temp, $watts + if ($preloading) { + $c = CacheMB + Emit ("preloading shaders for {0:N0} min, cache {1} MB (+{2} MB) | {3}" -f ((Get-Date) - $preloadAt).TotalMinutes, $c, ($c - $preloadCache), $sys) + } elseif ($win.Count) { + $fg = if ($s.FgOn -and $s.FgOn -ne '0') { " (x$($s.FgOn) frame generation: about {0:N0} shown)" -f ((Pct $win 0.5) * [int]$s.FgOn) } else { '' } + Emit ("in game: rendered {0:N1} fps median, slowest 5% {1:N1}{2}; {3} s under 10 fps this stretch | {4}" -f (Pct $win 0.5), (Pct $win 0.05), $fg, @($win | Where-Object { $_ -lt 10 }).Count, $sys) + } else { + Emit "menus or loading (no in-game frames this stretch) | $sys" + } + $win.Clear(); $gpuUtil.Clear(); $cpuPct.Clear(); $lastReport = Get-Date + } + Save + Start-Sleep -Seconds 5 +} +Save