From df08f9bf14abadbafc4876984063162fc3afb589 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Wed, 28 Oct 2026 20:30:07 +0100 Subject: [PATCH] feat(laptop): native-Windows read-only GPU watchdog with dry tests (STRA-291) Port of the safeguards of scripts/laptop/monitor.sh and lap_run.sh to PowerShell 5.1: preflight refusal (exit 4), 1 Hz sampling with a 5 s nvidia-smi call timeout, stall check off the sampler thread, kills only the PID tree it spawned, fail-closed on enforced.power.limit N/A/absent, caller-set timeout, 120 s / 600 s cool-down, exclusive machine lock (CreateNew + FileShare.None) with runner-lock verification, sample series file with sha256 and thresholds_source, injectable clock / -TimeScale. test_watchdog.ps1: 32 named cases against a fake nvidia-smi shim, CPU only. Co-Authored-By: Claude Sonnet 5.5 --- scripts/laptop/win/test_watchdog.ps1 | 687 ++++++++++++++++++++++++ scripts/laptop/win/watchdog.ps1 | 757 +++++++++++++++++++++++++++ 2 files changed, 1444 insertions(+) create mode 100644 scripts/laptop/win/test_watchdog.ps1 create mode 100644 scripts/laptop/win/watchdog.ps1 diff --git a/scripts/laptop/win/test_watchdog.ps1 b/scripts/laptop/win/test_watchdog.ps1 new file mode 100644 index 00000000..e5f99bbb --- /dev/null +++ b/scripts/laptop/win/test_watchdog.ps1 @@ -0,0 +1,687 @@ +# test_watchdog.ps1 - dry tests of scripts/laptop/win/watchdog.ps1 (STRA-291). CPU only, no GPU, no real nvidia-smi. +# +# powershell -NoProfile -ExecutionPolicy Bypass -File scripts/laptop/win/test_watchdog.ps1 +# +# Exit 0 and the line 'ALL TESTS PASSED ( named cases, assertions)' when every case passes, else exit 1. +# A plain assertion script (Pester availability is not assumed). Each `Case` is one named case. +# +# How the dry run works: a fake nvidia-smi (shim.cmd) prints recorded CSV lines from files in a per-test directory: the n-th call +# prints r.csv when that file exists, otherwise default.csv; hang-from.txt makes calls from that number on never return; +# error.flag makes it exit 2. The shim is handed to the watchdog with -NvidiaSmi; the child workload is a ping loop of cmd.exe. +# Time: the clock is injectable. Pure-logic cases run on a VIRTUAL clock (1800 s, 120 s, 600 s and 10 s pass in milliseconds); +# script-level cases use -TimeScale (clock seconds run N times faster than real seconds). Nothing here runs for 30 minutes. +# Outputs go to artifacts\runs\watchdog-tests\\ of the main checkout (git-ignored). Nothing outside it is touched, nothing +# is deleted, no power / system setting is read or changed. +[CmdletBinding()] +param([string]$TestRoot) + +$ErrorActionPreference = 'Stop' +$script:Here = Split-Path -Parent $MyInvocation.MyCommand.Path +$script:Watchdog = Join-Path $script:Here 'watchdog.ps1' +. $script:Watchdog -Library + +if ([string]::IsNullOrWhiteSpace($TestRoot)) { + $TestRoot = Join-Path (Join-Path (Join-Path (Resolve-MainCheckout) 'artifacts') 'runs') ('watchdog-tests\' + [DateTime]::Now.ToString('yyyyMMdd-HHmmss')) +} +[void](New-Item -ItemType Directory -Path $TestRoot -Force) +$script:TestRoot = $TestRoot +$script:TreeRoot = Resolve-TreeRoot +$script:Inv = [Globalization.CultureInfo]::InvariantCulture +$script:Results = New-Object System.Collections.ArrayList +$script:Asserts = 0 +$script:Spawned = New-Object System.Collections.ArrayList +$script:Seq = 0 + +# recorded nvidia-smi CSV lines: memory.used, clocks.sm, clocks.mem, power.draw, pstate, throttle reasons, enforced.power.limit, temp, util +$L = @{ + Idle = '1200, 210, 405, 12.00, P8, 0x0000000000000001, 139.00, 45, 0' + Load = '9000, 1710, 6001, 95.00, P0, 0x0000000000000000, 139.00, 72, 93' + Oem4 = '9000, 450, 810, 30.00, P5, 0x0000000000000004, 139.00, 70, 93' + Oem20 = '9000, 450, 810, 30.00, P5, 0x0000000000000020, 139.00, 70, 93' + Hot = '9000, 1710, 6001, 95.00, P0, 0x0000000000000000, 139.00, 91, 93' + LowLim = '9000, 1710, 6001, 95.00, P0, 0x0000000000000000, 51.00, 72, 93' + NaLim = '9000, 1710, 6001, 95.00, P0, 0x0000000000000000, [N/A], 72, 93' + EmptyLim = '9000, 1710, 6001, 95.00, P0, 0x0000000000000000, , 72, 93' + Absent = '9000, 1710, 6001, 95.00, P0, 0x0000000000000000, 72, 93' + P5Idle = '1200, 210, 405, 12.00, P5, 0x0000000000000001, 139.00, 45, 0' + Cap4Idle = '1200, 210, 405, 12.00, P8, 0x0000000000000005, 139.00, 45, 0' + Cap20Idle = '1200, 210, 405, 12.00, P8, 0x0000000000000021, 139.00, 45, 0' + Below99 = '1200, 210, 405, 12.00, P8, 0x0000000000000001, 99.00, 45, 0' + At100 = '1200, 210, 405, 12.00, P8, 0x0000000000000001, 100.00, 45, 0' +} +$CHILD_LONG = '/c ping -n 120 127.0.0.1 >nul' +$CHILD_SHORT = '/c ping -n 4 127.0.0.1 >nul' + +function Check { + param([bool]$Cond, [string]$Msg) + $script:Asserts++ + if (-not $Cond) { throw ('assertion failed: ' + $Msg) } +} + +function Case { + param([string]$Name, [scriptblock]$Body) + $sw = [Diagnostics.Stopwatch]::StartNew() + $before = $script:Asserts + try { + & $Body + [void]$script:Results.Add(@{ Name = $Name; Ok = $true; Msg = '' }) + Write-Host ('PASS ' + $Name + ' (' + ($script:Asserts - $before) + ' assertions, ' + [math]::Round($sw.Elapsed.TotalSeconds, 1) + ' s)') + } catch { + [void]$script:Results.Add(@{ Name = $Name; Ok = $false; Msg = $_.Exception.Message }) + Write-Host ('FAIL ' + $Name + ': ' + $_.Exception.Message) + } +} + +function Q { param([string]$S) return '"' + $S + '"' } + +function New-TestDir { + param([string]$Name) + $script:Seq++ + $d = Join-Path $script:TestRoot ($script:Seq.ToString('00') + '-' + $Name) + [void](New-Item -ItemType Directory -Path $d -Force) + [void](New-Item -ItemType Directory -Path (Join-Path $d 'shim') -Force) + return $d +} + +# Writes the shim and the recorded lines. r1 is the preflight call; default.csv serves every later call. +function New-Shim { + param([string]$Dir, [string]$First = $L.Idle, [string]$Default = $L.Load) + $sd = Join-Path $Dir 'shim' + $cmd = @( + '@echo off', + 'setlocal EnableDelayedExpansion', + 'set n=0', + 'if exist "%SHIM_DIR%\calls.txt" set /p n=<"%SHIM_DIR%\calls.txt"', + 'set /a n+=1', + '>"%SHIM_DIR%\calls.txt" echo !n!', + 'if exist "%SHIM_DIR%\hang-from.txt" (', + ' set /p h=<"%SHIM_DIR%\hang-from.txt"', + ' if !n! GEQ !h! ping -n 300 127.0.0.1 >nul', + ')', + 'if exist "%SHIM_DIR%\error.flag" (', + ' echo query failed 1>&2', + ' exit /b 2', + ')', + 'if exist "%SHIM_DIR%\r!n!.csv" (', + ' type "%SHIM_DIR%\r!n!.csv"', + ' exit /b 0', + ')', + 'type "%SHIM_DIR%\default.csv"', + 'exit /b 0') -join "`r`n" + [IO.File]::WriteAllText((Join-Path $sd 'shim.cmd'), $cmd + "`r`n", [Text.Encoding]::ASCII) + [IO.File]::WriteAllText((Join-Path $sd 'r1.csv'), $First + "`r`n", [Text.Encoding]::ASCII) + [IO.File]::WriteAllText((Join-Path $sd 'default.csv'), $Default + "`r`n", [Text.Encoding]::ASCII) + $env:SHIM_DIR = $sd + return (Join-Path $sd 'shim.cmd') +} + +function Set-ShimFile { + param([string]$Dir, [string]$Name, [string]$Text) + [IO.File]::WriteAllText((Join-Path (Join-Path $Dir 'shim') $Name), $Text + "`r`n", [Text.Encoding]::ASCII) +} + +function Start-WD { + param([string]$Dir, [string]$RunId, [string]$Extra) + $art = Join-Path $Dir 'artifacts' + $args1 = '-NoProfile -ExecutionPolicy Bypass -File ' + (Q $script:Watchdog) + ' -RunId ' + $RunId + ' -NvidiaSmi ' + (Q (Join-Path $Dir 'shim\shim.cmd')) + ' -ArtifactsRoot ' + (Q $art) + ' ' + $Extra + $psi = New-Object System.Diagnostics.ProcessStartInfo + $psi.FileName = 'powershell.exe' + $psi.Arguments = $args1 + $psi.UseShellExecute = $false + $psi.RedirectStandardOutput = $true + $psi.RedirectStandardError = $true + $psi.CreateNoWindow = $true + $psi.EnvironmentVariables['SHIM_DIR'] = (Join-Path $Dir 'shim') + $p = [System.Diagnostics.Process]::Start($psi) + [void]$script:Spawned.Add($p) + return @{ Proc = $p; Out = $p.StandardOutput.ReadToEndAsync(); Err = $p.StandardError.ReadToEndAsync(); Art = $art; RunId = $RunId; Sw = [Diagnostics.Stopwatch]::StartNew() } +} + +function Wait-WD { + param($H, [int]$TimeoutMs = 120000) + if (-not $H.Proc.WaitForExit($TimeoutMs)) { + [void](Stop-PidTree -RootPid $H.Proc.Id) + throw ('watchdog run ' + $H.RunId + ' did not finish in ' + $TimeoutMs + ' ms') + } + $H.Proc.WaitForExit() + $summary = $null + $sp = Join-Path (Join-Path (Join-Path $H.Art 'runs') $H.RunId) 'watchdog_summary.json' + if (Test-Path -LiteralPath $sp) { $summary = [IO.File]::ReadAllText($sp) | ConvertFrom-Json } + return @{ Exit = $H.Proc.ExitCode; Out = $H.Out.Result; Err = $H.Err.Result; Summary = $summary; Art = $H.Art; RunId = $H.RunId; Secs = $H.Sw.Elapsed.TotalSeconds + RunRoot = (Join-Path (Join-Path $H.Art 'runs') $H.RunId) } +} + +function Invoke-WD { + param([string]$Dir, [string]$RunId, [string]$Extra, [int]$TimeoutMs = 120000) + return Wait-WD (Start-WD -Dir $Dir -RunId $RunId -Extra $Extra) $TimeoutMs +} + +function Test-Alive { param([int]$ProcId) return ($null -ne (Get-Process -Id $ProcId -ErrorAction SilentlyContinue)) } + +function Test-AllDead { + param($Pids) + foreach ($id in @($Pids)) { if (Test-Alive ([int]$id)) { return $false } } + return $true +} + +function New-S37File { + param([string]$Path, [scriptblock]$Mutate) + $boot = [IO.File]::ReadAllText((Join-Path $script:TreeRoot 'docs\experiments\2026-10-28-s3-1-laptop-thresholds.bootstrap.json')) | ConvertFrom-Json + $boot.thresholds_source = 'S3.7' + $boot.run.PSObject.Properties.Remove('cap_minutes') + if ($null -ne $Mutate) { & $Mutate $boot } + [IO.File]::WriteAllText($Path, ($boot | ConvertTo-Json -Depth 10), (New-Object Text.UTF8Encoding $false)) +} + +function New-GoodSample { + param([string]$Line, [double]$T) + $s = ConvertTo-GpuSample $Line + $s.T = $T + return $s +} + +$bootstrapPath = Join-Path $script:TreeRoot 'docs\experiments\2026-10-28-s3-1-laptop-thresholds.bootstrap.json' +$thBoot = Read-Thresholds -Path $bootstrapPath +$tStart = [Diagnostics.Stopwatch]::StartNew() +Write-Host ('test root: ' + $TestRoot) + +# ===================================================================== preflight (AC1) +Case 'preflight_refuse_below_threshold' { + $d = New-TestDir 'pre-below' + [void](New-Shim $d -First $L.Below99) + $r = Invoke-WD $d 'pre-below' '-PreflightOnly' + Check ($r.Exit -eq 4) ('exit 4 expected, got ' + $r.Exit + ' / ' + $r.Out) + Check ($r.Out -match 'REFUSED.*below the 100 W threshold') ('reason names the threshold: ' + $r.Out) + Check ($null -ne $r.Summary -and $r.Summary.outcome -eq 'REFUSED' -and $null -eq $r.Summary.child_pid) 'summary says REFUSED and no child was started' +} + +Case 'preflight_limit_boundary_100' { + $d = New-TestDir 'pre-100' + $shim = New-Shim $d -First $L.At100 + $clk = New-Clock + $pf = Invoke-Preflight -Th $thBoot -Exe $shim -Clock $clk + Check $pf.Ok ('exactly 100 W is accepted like lap_run.sh (l+0 >= 100): ' + ($pf.Reasons -join ';')) + Set-ShimFile $d 'calls.txt' '0' + Set-ShimFile $d 'r1.csv' $L.Below99 + $pf2 = Invoke-Preflight -Th $thBoot -Exe $shim -Clock $clk + Check (-not $pf2.Ok) '99 W is refused' +} + +Case 'preflight_refuse_sw_power_cap' { + $d = New-TestDir 'pre-cap' + [void](New-Shim $d -First $L.Cap4Idle) + $r = Invoke-WD $d 'pre-cap' '-PreflightOnly' + Check ($r.Exit -eq 4) ('exit 4 expected, got ' + $r.Exit) + Check ($r.Out -match 'SW power cap active at idle') ('reason: ' + $r.Out) +} + +Case 'preflight_refuse_sw_thermal_slowdown' { + $d = New-TestDir 'pre-thermal' + [void](New-Shim $d -First $L.Cap20Idle) + $r = Invoke-WD $d 'pre-thermal' '-PreflightOnly' + Check ($r.Exit -eq 4) ('exit 4 expected, got ' + $r.Exit) + Check ($r.Out -match 'SW thermal slowdown active at idle') ('reason: ' + $r.Out) +} + +Case 'preflight_refuse_p5' { + $d = New-TestDir 'pre-p5' + [void](New-Shim $d -First $L.P5Idle) + $r = Invoke-WD $d 'pre-p5' '-PreflightOnly' + Check ($r.Exit -eq 4) ('exit 4 expected, got ' + $r.Exit) + Check ($r.Out -match 'performance state P5') ('reason: ' + $r.Out) +} + +# ===================================================================== kills under load (AC1), script level, real child +function Test-KillRun { + param([string]$Name, [string]$Violation, [string]$ExpectReason) + $d = New-TestDir $Name + [void](New-Shim $d -First $L.Idle -Default $Violation) + Set-ShimFile $d 'r2.csv' $L.Load + Set-ShimFile $d 'r3.csv' $L.Load + $r = Invoke-WD $d $Name ('-ChildCommand cmd.exe -ChildArguments ' + (Q $CHILD_LONG) + ' -TimeoutSeconds 60') + Check ($r.Exit -eq 5) ('exit 5 (killed by a sample rule) expected, got ' + $r.Exit + ' / ' + $r.Out + $r.Err) + Check ($r.Summary.outcome -eq 'ABORTED') ('outcome ' + $r.Summary.outcome) + Check ($r.Summary.reason -match $ExpectReason) ('reason "' + $r.Summary.reason + '" should match ' + $ExpectReason) + Check (@($r.Summary.killed_pids).Count -ge 2) 'the child (cmd.exe) and its ping were killed' + Check (Test-AllDead $r.Summary.killed_pids) 'every killed pid is gone' + Check (-not (Test-Alive ([int]$r.Summary.child_pid))) 'the child is gone' + Check (Test-Path -LiteralPath (Join-Path $r.RunRoot 'abort.txt')) 'abort.txt written' + $stamp = [IO.File]::ReadAllText((Join-Path $r.Art 'locks\last_gpu_run.json')) | ConvertFrom-Json + Check ($stamp.aborted -eq $true) 'the cool-down stamp records an abort (600 s)' + Check (-not (Test-Path -LiteralPath (Join-Path $r.Art 'locks\LAPTOP_GPU.lock'))) 'the lock the watchdog created is released after an abort' +} + +Case 'kill_p5_throttle_0x4' { Test-KillRun 'kill-0x4' $L.Oem4 'P5, memory 810 MHz.*0x4.*OEM profile' } +Case 'kill_p5_throttle_0x20' { Test-KillRun 'kill-0x20' $L.Oem20 'P5, memory 810 MHz.*0x20.*OEM profile' } +Case 'kill_over_temperature' { Test-KillRun 'kill-hot' $L.Hot 'temperature 91 C above 90 C' } +Case 'kill_limit_below_threshold' { Test-KillRun 'kill-lowlim' $L.LowLim 'power limit 51 W below the 100 W floor' } + +# ===================================================================== pure rules on the virtual clock +Case 'p5_idle_reason_not_oem' { + # monitor.sh: a plain P5 with reason 0x1 while the model loads, a P5 at 2000 MHz, or a low memory clock outside P5 are not aborted + $v1 = Get-Violations (ConvertTo-GpuSample '9000, 450, 810, 30.00, P5, 0x0000000000000001, 139.00, 70, 93') $thBoot + $v2 = Get-Violations (ConvertTo-GpuSample '9000, 450, 2000, 30.00, P5, 0x0000000000000004, 139.00, 70, 93') $thBoot + $v3 = Get-Violations (ConvertTo-GpuSample '9000, 450, 810, 30.00, P0, 0x0000000000000004, 139.00, 70, 93') $thBoot + $v4 = Get-Violations (ConvertTo-GpuSample '9000, 450, 1999, 30.00, P5, 0x0000000000000024, 139.00, 70, 93') $thBoot + Check ($v1.Count -eq 0) 'P5 + reason 0x1 is not the OEM profile' + Check ($v2.Count -eq 0) 'memory clock 2000 MHz is not below 2000' + Check ($v3.Count -eq 0) 'P0 is not the OEM profile' + Check ($v4.Contains('oem')) 'P5, 1999 MHz, 0x24 is' + $v5 = Get-Violations (ConvertTo-GpuSample '9000, 450, 6001, 30.00, P0, 0x0, 100.00, 90, 93') $thBoot + Check ($v5.Count -eq 0) 'exactly 100 W and exactly 90 C are not violations (monitor.sh: < 100, -gt 90)' +} + +Case 'confirm_samples_two' { + $th2 = $thBoot.Clone() + $th2.ConfirmSamples = 2 + $st = New-WatchState -Th $th2 -StartAt 0.0 -TimeoutS 1800 + $bad = New-GoodSample $L.Hot 1.0 + $ok = New-GoodSample $L.Load 2.0 + Check ($null -eq (Step-Watch -State $st -Now 1.0 -Samples @($bad) -ChildAlive $true)) 'one hot sample does not abort with confirm_samples 2' + Check ($null -eq (Step-Watch -State $st -Now 2.0 -Samples @($ok) -ChildAlive $true)) 'a good sample resets the count' + Check ($null -eq (Step-Watch -State $st -Now 3.0 -Samples @((New-GoodSample $L.Hot 3.0)) -ChildAlive $true)) 'hot again: first' + $v = Step-Watch -State $st -Now 4.0 -Samples @((New-GoodSample $L.Hot 4.0)) -ChildAlive $true + Check ($null -ne $v -and $v.Kind -eq 'ABORT') 'two consecutive hot samples abort' + $st1 = New-WatchState -Th $thBoot -StartAt 0.0 -TimeoutS 1800 + $v1 = Step-Watch -State $st1 -Now 1.0 -Samples @($bad) -ChildAlive $true + Check ($null -ne $v1 -and $v1.Kind -eq 'ABORT') 'default confirm_samples 1 is the immediate monitor.sh trigger' +} + +Case 'stall_gap_10s' { + $st = New-WatchState -Th $thBoot -StartAt 0.0 -TimeoutS 1800 + Check ($null -eq (Step-Watch -State $st -Now 10.0 -Samples @() -ChildAlive $true)) 'a gap of exactly 10 s is not a stall (monitor.sh: -gt 10)' + $v = Step-Watch -State $st -Now 10.01 -Samples @() -ChildAlive $true + Check ($null -ne $v -and $v.Kind -eq 'STALL') 'a gap above 10 s is a STALL' + $st2 = New-WatchState -Th $thBoot -StartAt 0.0 -TimeoutS 1800 + $v2 = Step-Watch -State $st2 -Now 10.6 -Samples @((New-GoodSample $L.Load 10.5)) -ChildAlive $true + Check ($null -ne $v2 -and $v2.Kind -eq 'STALL') 'a late sample that proves the gap (10.5 s after the previous) is a STALL too' + # whole supervisor loop on the virtual clock: samples at 1..5 s, then silence + $clk = New-Clock -Virtual + $script:nextAt = 1.0 + $script:killed = 0 + $child = @{ IsAlive = { $true }; Kill = { $script:killed++; return @(4242) } } + $source = @{ Drain = { $out = @(); while ($clk.T -ge $script:nextAt -and $script:nextAt -le 5.0) { $out += New-GoodSample $L.Load $script:nextAt; $script:nextAt += 1.0 }; $out } } + $v3 = Invoke-Supervise -Clock $clk -Th $thBoot -Child $child -Source $source -TimeoutS 1800 -Tick 0.25 + Check ($v3.Kind -eq 'STALL') ('virtual loop ends in STALL, got ' + $v3.Kind) + Check ($v3.At -gt 15.0 -and $v3.At -le 15.5) ('detected just after last good + 10 s: ' + $v3.At) + Check ($script:killed -eq 1) 'the child is killed once' + # missing samples (timeouts) every second never refresh the clock: STALL after 10 s as well + $clk2 = New-Clock -Virtual + $script:nextAt = 1.0 + $source2 = @{ Drain = { $out = @(); while ($clk2.T -ge $script:nextAt) { $out += @{ Ok = $false; Why = 'timeout after 5 s'; T = $script:nextAt }; $script:nextAt += 1.0 }; $out } } + $v4 = Invoke-Supervise -Clock $clk2 -Th $thBoot -Child $child -Source $source2 -TimeoutS 1800 -Tick 0.25 + Check ($v4.Kind -eq 'STALL' -and $v4.Missing -ge 10) ('missing samples alone end in STALL: ' + $v4.Kind + ' missing ' + $v4.Missing) +} + +Case 'timeout_1800s_injected_clock' { + $clk = New-Clock -Virtual + $script:nextAt = 1.0 + $script:killed = 0 + $child = @{ IsAlive = { $true }; Kill = { $script:killed++; return @(4242) } } + $source = @{ Drain = { $out = @(); while ($clk.T -ge $script:nextAt) { $out += New-GoodSample $L.Load $script:nextAt; $script:nextAt += 1.0 }; $out } } + $sw = [Diagnostics.Stopwatch]::StartNew() + $v = Invoke-Supervise -Clock $clk -Th $thBoot -Child $child -Source $source -TimeoutS 1800 -Tick 1.0 + Check ($v.Kind -eq 'TIMEOUT') ('timeout verdict, got ' + $v.Kind + ' ' + $v.Reason) + Check ($v.At -ge 1800.0 -and $v.At -lt 1801.5) ('fired at the 1,800th clock second, not before: ' + $v.At) + Check ($script:killed -eq 1) 'the child is killed once' + Check ($sw.Elapsed.TotalSeconds -lt 60) ('1,800 clock seconds took ' + [math]::Round($sw.Elapsed.TotalSeconds, 1) + ' real seconds') + $st = New-WatchState -Th $thBoot -StartAt 0.0 -TimeoutS 1800 + $g = New-GoodSample $L.Load 1799.0 + $st.LastGoodAt = 1799.0 + Check ($null -eq (Step-Watch -State $st -Now 1799.99 -Samples @($g) -ChildAlive $true)) '1799.99 s: still running' + $st.LastGoodAt = 1800.0 + $v2 = Step-Watch -State $st -Now 1800.0 -Samples @() -ChildAlive $true + Check ($null -ne $v2 -and $v2.Kind -eq 'TIMEOUT') '1800.0 s: timeout' +} + +Case 'timeout_script_level_time_scale' { + $d = New-TestDir 'timeout-scaled' + [void](New-Shim $d -First $L.Idle -Default $L.Load) + $r = Invoke-WD $d 'timeout-scaled' ('-ChildCommand cmd.exe -ChildArguments ' + (Q $CHILD_LONG) + ' -TimeoutSeconds 12 -TimeScale 4') + Check ($r.Exit -eq 6) ('exit 6 (timeout) expected, got ' + $r.Exit + ' / ' + $r.Out + $r.Err) + Check ($r.Summary.outcome -eq 'TIMEOUT') 'outcome TIMEOUT' + Check ($r.Summary.detected_at_s -ge 12 -and $r.Summary.detected_at_s -lt 14) ('detected at ' + $r.Summary.detected_at_s + ' clock seconds') + Check (Test-AllDead $r.Summary.killed_pids) 'the child tree is gone' +} + +Case 'bootstrap_cap_refuses_long_timeout' { + $d = New-TestDir 'cap' + [void](New-Shim $d) + $r = Invoke-WD $d 'cap' ('-ChildCommand cmd.exe -ChildArguments ' + (Q $CHILD_SHORT) + ' -TimeoutSeconds 1800') + Check ($r.Exit -eq 2) ('exit 2 expected, got ' + $r.Exit) + Check ($r.Out -match 'cap a run at 15 minutes') ('message: ' + $r.Out) +} + +# ===================================================================== cool-down (AC1), injected clock +Case 'cooldown_120s_injected_clock' { + $stamp = [pscustomobject]@{ end_epoch = 1000.0; aborted = $false } + Check ((Get-CooldownRemaining -Stamp $stamp -WallNow 1000.0 -Th $thBoot) -eq 120.0) 'right after a run: 120 s' + Check ((Get-CooldownRemaining -Stamp $stamp -WallNow 1100.0 -Th $thBoot) -eq 20.0) '100 s later: 20 s' + Check ((Get-CooldownRemaining -Stamp $stamp -WallNow 1120.0 -Th $thBoot) -eq 0.0) '120 s later: none' + Check ((Get-CooldownRemaining -Stamp $null -WallNow 1000.0 -Th $thBoot) -eq 0.0) 'no previous run: none' + $clk = New-Clock -Virtual + $rem = Get-CooldownRemaining -Stamp $stamp -WallNow (1000.0 + $clk.T) -Th $thBoot + Invoke-ClockSleep $clk $rem + Check ($clk.T -eq 120.0) 'the wait advances the injected clock by 120 s without sleeping' + # script level: a normal-end stamp aged 90 s: 30 clock seconds remain = 1.5 real seconds at -TimeScale 20 (an abort stamp of the + # same age would leave 510 s, so 30 s proves the 120 s rule is the one applied) + $d = New-TestDir 'cooldown-120' + [void](New-Shim $d) + [void](New-Item -ItemType Directory -Path (Join-Path $d 'artifacts\locks') -Force) + $now = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() / 1000.0 - 90.0 + [IO.File]::WriteAllText((Join-Path $d 'artifacts\locks\last_gpu_run.json'), ('{"end_epoch": ' + $now.ToString('0.###', $script:Inv) + ', "aborted": false, "run_id": "prev"}')) + $r = Invoke-WD $d 'cooldown-120' '-PreflightOnly -TimeScale 20' + Check ($r.Exit -eq 0) ('preflight ok after the wait, exit ' + $r.Exit + ' / ' + $r.Out) + Check ($r.Out -match 'cool-down (2[6-9]|30) s') ('cool-down line: ' + $r.Out) + Check ($r.Secs -lt 20) ('30 clock seconds took ' + [math]::Round($r.Secs, 1) + ' real seconds') +} + +Case 'cooldown_600s_injected_clock' { + $stamp = [pscustomobject]@{ end_epoch = 1000.0; aborted = $true } + Check ((Get-CooldownRemaining -Stamp $stamp -WallNow 1000.0 -Th $thBoot) -eq 600.0) 'right after an abort: 600 s' + Check ((Get-CooldownRemaining -Stamp $stamp -WallNow 1599.0 -Th $thBoot) -eq 1.0) '599 s later: 1 s' + Check ((Get-CooldownRemaining -Stamp $stamp -WallNow 1600.0 -Th $thBoot) -eq 0.0) '600 s later: none' + $d = New-TestDir 'cooldown-600' + [void](New-Shim $d) + [void](New-Item -ItemType Directory -Path (Join-Path $d 'artifacts\locks') -Force) + # an abort stamp aged 570 s: 30 clock seconds remain (a normal-end stamp of that age would leave none) + $now = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() / 1000.0 - 570.0 + [IO.File]::WriteAllText((Join-Path $d 'artifacts\locks\last_gpu_run.json'), ('{"end_epoch": ' + $now.ToString('0.###', $script:Inv) + ', "aborted": true, "run_id": "prev"}')) + $r = Invoke-WD $d 'cooldown-600' '-PreflightOnly -TimeScale 20' + Check ($r.Exit -eq 0) ('preflight ok after the wait, exit ' + $r.Exit + ' / ' + $r.Out) + Check ($r.Out -match 'cool-down (2[6-9]|30) s') ('cool-down line: ' + $r.Out) + $d2 = New-TestDir 'cooldown-600-garbled' + [void](New-Shim $d2) + [void](New-Item -ItemType Directory -Path (Join-Path $d2 'artifacts\locks') -Force) + [IO.File]::WriteAllText((Join-Path $d2 'artifacts\locks\last_gpu_run.json'), 'not json') + $r2 = Invoke-WD $d2 'cooldown-600-garbled' '-PreflightOnly -TimeScale 600' + Check ($r2.Out -match 'cool-down (5[5-9][0-9]|600) s') ('an unreadable stamp is treated as an abort that just ended (fail closed): ' + $r2.Out) +} + +# ===================================================================== fail closed (AC2) +Case 'fail_closed_na' { + foreach ($variant in @(@('na', $L.NaLim), @('empty', $L.EmptyLim))) { + $d = New-TestDir ('fc-' + $variant[0]) + [void](New-Shim $d -First $variant[1]) + $r = Invoke-WD $d ('fc-pre-' + $variant[0]) '-PreflightOnly' + Check ($r.Exit -eq 4) ('preflight with enforced.power.limit ' + $variant[0] + ' refuses with exit 4, got ' + $r.Exit) + Check ($r.Out -match 'unreadable: enforced.power.limit') ('reason: ' + $r.Out) + # a run in progress: idle is fine, then the limit turns unreadable + $d2 = New-TestDir ('fc-run-' + $variant[0]) + [void](New-Shim $d2 -First $L.Idle -Default $variant[1]) + $r2 = Invoke-WD $d2 ('fc-run-' + $variant[0]) ('-ChildCommand cmd.exe -ChildArguments ' + (Q $CHILD_LONG) + ' -TimeoutSeconds 60') + Check ($r2.Exit -eq 5) ('a run with an unreadable limit is killed (exit 5), got ' + $r2.Exit + ' / ' + $r2.Out) + Check ($r2.Summary.reason -match 'unreadable: enforced.power.limit') ('abort reason: ' + $r2.Summary.reason) + Check (Test-AllDead $r2.Summary.killed_pids) 'the child is gone' + } +} + +Case 'fail_closed_absent' { + # power.limit populated (the old field) but enforced.power.limit absent: the line has one field too few + $d = New-TestDir 'fa-pre' + [void](New-Shim $d -First $L.Absent) + $r = Invoke-WD $d 'fa-pre' '-PreflightOnly' + Check ($r.Exit -eq 4) ('preflight refuses with exit 4, got ' + $r.Exit) + Check ($r.Out -match 'malformed nvidia-smi line') ('reason: ' + $r.Out) + $d2 = New-TestDir 'fa-run' + [void](New-Shim $d2 -First $L.Idle -Default $L.Absent) + $r2 = Invoke-WD $d2 'fa-run' ('-ChildCommand cmd.exe -ChildArguments ' + (Q $CHILD_LONG) + ' -TimeoutSeconds 60') + Check ($r2.Exit -eq 5) ('a run with the limit absent is killed (exit 5), got ' + $r2.Exit + ' / ' + $r2.Out) + Check ($r2.Summary.reason -match 'malformed nvidia-smi line') ('abort reason: ' + $r2.Summary.reason) + Check (Test-AllDead $r2.Summary.killed_pids) 'the child is gone' +} + +# ===================================================================== 5 s call timeout, stall off the sampler thread (AC3) +Case 'call_timeout_missing_sample' { + $d = New-TestDir 'call-timeout' + [void](New-Shim $d -First $L.Idle -Default $L.Load) + Set-ShimFile $d 'hang-from.txt' '2' + # -TimeScale 5: the 5 s call timeout is 1 real second, the 10 s gap 2 real seconds + $r = Invoke-WD $d 'call-timeout' ('-ChildCommand cmd.exe -ChildArguments ' + (Q $CHILD_LONG) + ' -TimeoutSeconds 60 -TimeScale 5') + Check ($r.Exit -eq 7) ('exit 7 (STALL) expected, got ' + $r.Exit + ' / ' + $r.Out + $r.Err) + Check ($r.Summary.outcome -eq 'STALL') 'outcome STALL' + Check (Test-Path -LiteralPath (Join-Path $r.RunRoot 'STALL')) 'the STALL file is written' + $rows = @(Get-Content -LiteralPath (Join-Path $r.RunRoot 'samples.tsv') | Where-Object { $_ -match '^run\t' }) + $missing = @($rows | Where-Object { ($_ -split "`t")[3] -eq '0' -and ($_ -split "`t")[4] -match '^timeout after 5 s' }) + Check ($missing.Count -ge 1) ('a hung call is recorded as a missing sample after 5 s (' + $missing.Count + ' rows)') + $firstMissing = [double](($missing[0] -split "`t")[1]) + $sinceStart = $firstMissing - $r.Summary.last_good_at_s # last_good_at_s is the supervision start when no good sample ever came + Check ($sinceStart -ge 4.9 -and $sinceStart -lt 10.0) ('the first missing sample arrives 5 clock seconds after its call started (the sampler runspace start-up adds a little): ' + $sinceStart) + $gap = $r.Summary.detected_at_s - $r.Summary.last_good_at_s + Check ($gap -gt 10.0 -and $gap -lt 12.0) ('the stall is declared at 10 s without a good sample, not when the sampler returns (it is still blocked in its next call): ' + $gap) + Check ($r.Summary.samples_missing -ge 1) 'samples_missing recorded' + Check (Test-AllDead $r.Summary.killed_pids) 'the child is gone' + Check (Test-Path -LiteralPath (Join-Path $r.Art 'locks\LAPTOP_GPU.lock')) 'after a STALL the lock the watchdog created is kept (all GPU work stops)' +} + +Case 'nvidia_smi_error_is_missing_sample' { + $d = New-TestDir 'smi-error' + $shim = New-Shim $d + Set-ShimFile $d 'error.flag' 'x' + $clk = New-Clock + $q = Invoke-NvidiaQuery -Exe $shim -TimeoutS 5 -Clock $clk + Check (-not $q.Ok -and $q.Why -match 'exit code 2') ('a failing query is a missing sample: ' + $q.Why) + $pf = Invoke-Preflight -Th $thBoot -Exe $shim -Clock $clk + Check (-not $pf.Ok -and ($pf.Reasons -join ';') -match 'no reading') 'and the preflight fails closed on it' +} + +# ===================================================================== own PID tree only; lock (AC4) +Case 'same_image_name_survives' { + $other = Start-Process -FilePath 'ping.exe' -ArgumentList '-n 120 127.0.0.1' -WindowStyle Hidden -PassThru + [void]$script:Spawned.Add($other) + try { + $d = New-TestDir 'same-image' + [void](New-Shim $d -First $L.Idle -Default $L.Oem4) + Set-ShimFile $d 'r2.csv' $L.Load + $r = Invoke-WD $d 'same-image' ('-ChildCommand cmd.exe -ChildArguments ' + (Q $CHILD_LONG) + ' -TimeoutSeconds 60') + Check ($r.Exit -eq 5) ('the child was killed, exit ' + $r.Exit) + Check ($r.Summary.killed_pids.Count -ge 2) 'the child ping.exe and its cmd.exe were killed' + Check (-not (@($r.Summary.killed_pids) -contains $other.Id)) 'the unrelated ping.exe is not in the killed list' + Check (-not $other.HasExited) 'an unrelated ping.exe (same image name as the child of the child) is still alive' + } finally { + if (-not $other.HasExited) { Stop-Process -Id $other.Id -Force } + } +} + +Case 'lock_exclusive_user_dir' { + # in-process: the lock file is created exclusively in the lock directory with leaf, run id, PID, UTC and boot time + $d = New-TestDir 'lock-excl' + $ld = Join-Path $d 'artifacts\locks' + $a = Enter-Lock -LockDir $ld -RunId 'run-a' -Leaf 'STRA-291' + Check ($a.Mode -eq 'created') 'standalone with no lock: created' + Check ((Split-Path -Leaf $a.Path) -eq 'LAPTOP_GPU.lock' -and (Split-Path -Parent $a.Path) -eq $ld) 'in artifacts\locks' + $second = $null + try { $second = [IO.File]::Open($a.Path, [IO.FileMode]::CreateNew, [IO.FileAccess]::Write, [IO.FileShare]::None) } catch [IO.IOException] { $second = $null } + Check ($null -eq $second) 'a second exclusive creation fails' + $b = Enter-Lock -LockDir $ld -RunId 'run-b' -Leaf 'STRA-291' + Check ($b.Mode -eq 'refused') ('a second job is refused while the file is held: ' + $b.Reason) + $a.Stream.Dispose() + $j = [IO.File]::ReadAllText($a.Path) | ConvertFrom-Json + Check ($j.leaf -eq 'STRA-291' -and $j.run_id -eq 'run-a' -and $j.pid -eq $PID -and $j.utc -and $j.boot_time -eq (Get-BootTimeUtc)) 'contents: leaf, run id, PID, UTC, boot time' + $c = Enter-Lock -LockDir $ld -RunId 'run-c' -Leaf 'x' + Check ($c.Mode -eq 'refused' -and $c.Reason -match 'never stolen') 'a lock left behind (even by a dead process) is never stolen' + # script level: a watchdog holds the lock for the whole run; the file cannot be opened or created by anyone else + $d2 = New-TestDir 'lock-excl-live' + [void](New-Shim $d2 -First $L.Idle -Default $L.Load) + $h = Start-WD -Dir $d2 -RunId 'lock-live' -Extra ('-Leaf STRA-291 -ChildCommand cmd.exe -ChildArguments ' + (Q $CHILD_LONG) + ' -TimeoutSeconds 60') + $lp = Join-Path $d2 'artifacts\locks\LAPTOP_GPU.lock' + $deadline = [DateTime]::UtcNow.AddSeconds(30) + while (-not (Test-Path -LiteralPath $lp) -and [DateTime]::UtcNow -lt $deadline) { Start-Sleep -Milliseconds 100 } + Check (Test-Path -LiteralPath $lp) 'the standalone watchdog created the lock file' + $third = $null + try { $third = [IO.File]::Open($lp, [IO.FileMode]::CreateNew, [IO.FileAccess]::Write, [IO.FileShare]::None) } catch [IO.IOException] { $third = $null } + Check ($null -eq $third) 'while it runs a second exclusive creation fails' + # lock refusal on a second job (AC1), while the first is running + $rb = Invoke-WD $d2 'lock-second' '-PreflightOnly' + Check ($rb.Exit -eq 3) ('the second job is refused with exit 3, got ' + $rb.Exit + ' / ' + $rb.Out) + Check ($rb.Out -match 'LOCK REFUSED') ('message: ' + $rb.Out) + Check (Test-Path -LiteralPath $lp) 'the first lock is untouched' + Set-ShimFile $d2 'default.csv' $L.Oem4 # end the first run quickly + $ra = Wait-WD $h + Check ($ra.Exit -eq 5) ('the first run ended by the injected violation, exit ' + $ra.Exit) + Check (-not (Test-Path -LiteralPath $lp)) 'and released its lock' +} + +Case 'lock_refusal_second_job' { + $d = New-TestDir 'lock-second' + $ld = Join-Path $d 'artifacts\locks' + [void](New-Item -ItemType Directory -Path $ld -Force) + $holder = $L.Idle # any text: the first job is simulated by a held lock of another run + $a = Enter-Lock -LockDir $ld -RunId 'first-job' -Leaf 'STRA-254' + [void](New-Shim $d) + $r = Invoke-WD $d 'second-job' ('-ChildCommand cmd.exe -ChildArguments ' + (Q $CHILD_SHORT) + ' -TimeoutSeconds 60') + $a.Stream.Dispose() + Check ($r.Exit -eq 3) ('exit 3 expected, got ' + $r.Exit + ' / ' + $r.Out) + Check ($null -eq $r.Summary) 'no run root, no child, no nvidia-smi call for a refused job' + Check (-not (Test-Path -LiteralPath (Join-Path $d 'shim\calls.txt'))) 'the GPU was not even queried' +} + +Case 'lock_existing_matching' { + $d = New-TestDir 'lock-match' + $ld = Join-Path $d 'artifacts\locks' + [void](New-Item -ItemType Directory -Path $ld -Force) + $lp = Join-Path $ld 'LAPTOP_GPU.lock' + $runner = [ordered]@{ leaf = 'STRA-316'; run_id = 'R-match'; pid = 4321; utc = [DateTime]::UtcNow.ToString('o'); boot_time = (Get-BootTimeUtc) } + [IO.File]::WriteAllText($lp, ($runner | ConvertTo-Json), (New-Object Text.UTF8Encoding $false)) + $before = (Get-FileHash -LiteralPath $lp -Algorithm SHA256).Hash + [void](New-Shim $d -First $L.Idle -Default $L.Load) + $r = Invoke-WD $d 'R-match' ('-ChildCommand cmd.exe -ChildArguments ' + (Q $CHILD_SHORT) + ' -TimeoutSeconds 60') + Check ($r.Exit -eq 0) ('the run proceeds, exit ' + $r.Exit + ' / ' + $r.Out) + Check ($r.Summary.lock_mode -eq 'verified') ('lock verified, not created: ' + $r.Summary.lock_mode) + Check ((Get-FileHash -LiteralPath $lp -Algorithm SHA256).Hash -eq $before) 'the runner lock file is unchanged and still there' + $locks = @(Get-ChildItem -LiteralPath $ld -Filter '*.lock' -File) + Check ($locks.Count -eq 1) 'no second lock file was created' +} + +Case 'lock_existing_other_run_refused' { + $d = New-TestDir 'lock-other' + $ld = Join-Path $d 'artifacts\locks' + [void](New-Item -ItemType Directory -Path $ld -Force) + $lp = Join-Path $ld 'LAPTOP_GPU.lock' + $runner = [ordered]@{ leaf = 'STRA-316'; run_id = 'R-other'; pid = 4321; utc = [DateTime]::UtcNow.ToString('o'); boot_time = (Get-BootTimeUtc) } + [IO.File]::WriteAllText($lp, ($runner | ConvertTo-Json), (New-Object Text.UTF8Encoding $false)) + $before = (Get-FileHash -LiteralPath $lp -Algorithm SHA256).Hash + [void](New-Shim $d) + $r = Invoke-WD $d 'R-mine' ('-ChildCommand cmd.exe -ChildArguments ' + (Q $CHILD_SHORT) + ' -TimeoutSeconds 60') + Check ($r.Exit -eq 3) ('exit 3 expected, got ' + $r.Exit + ' / ' + $r.Out) + Check ($r.Out -match 'held by run R-other') ('message names the holder: ' + $r.Out) + Check ((Get-FileHash -LiteralPath $lp -Algorithm SHA256).Hash -eq $before) 'the file is untouched' + # a lock from another boot is not trusted even when the run id matches + $old = [ordered]@{ leaf = 'STRA-316'; run_id = 'R-mine'; pid = 4321; utc = '2026-01-01T00:00:00Z'; boot_time = '2026-01-01T00:00:00.0000000Z' } + [IO.File]::WriteAllText($lp, ($old | ConvertTo-Json), (New-Object Text.UTF8Encoding $false)) + $r2 = Invoke-WD $d 'R-mine' ('-ChildCommand cmd.exe -ChildArguments ' + (Q $CHILD_SHORT) + ' -TimeoutSeconds 60') + Check ($r2.Exit -eq 3 -and $r2.Out -match 'another boot') ('a lock from another boot is refused: ' + $r2.Out) +} + +# ===================================================================== evidence for the S0.1 record (AC6) +Case 'sample_series_sha256' { + $d = New-TestDir 'series' + [void](New-Shim $d -First $L.Idle -Default $L.Load) + $r = Invoke-WD $d 'series' ('-ChildCommand cmd.exe -ChildArguments ' + (Q $CHILD_SHORT) + ' -TimeoutSeconds 60') + Check ($r.Exit -eq 0) ('completed run, exit ' + $r.Exit + ' / ' + $r.Out + $r.Err) + $sf = Join-Path $r.RunRoot 'samples.tsv' + Check (Test-Path -LiteralPath $sf) 'the sample series file exists in the run root' + $h = (Get-FileHash -LiteralPath $sf -Algorithm SHA256).Hash.ToLowerInvariant() + Check ($r.Summary.sample_series_sha256 -eq $h) 'summary carries the sha256 of the series file' + Check ($r.Out -match ('SAMPLE_SERIES_SHA256=' + $h)) 'and so does the output line' + $text = [IO.File]::ReadAllText($sf) + Check (-not $text.Contains("`r")) 'LF line endings (stable hash across tools)' + Check ($text -match '(?m)^# thresholds_source=BOOTSTRAP$' -and $text -match '(?m)^# thresholds_sha256=[0-9a-f]{64}$') 'the series records thresholds_source and the thresholds sha256' + $rows = @($text -split "`n" | Where-Object { $_ -match '^(pre|run)\t' }) + Check ($rows.Count -ge 3) ('1 Hz rows recorded (' + $rows.Count + ')') + Check ($rows[0] -match '^pre\t' -and $rows[1] -match '^run\t') 'preflight row first, then the run rows' + Check ($r.Summary.outcome -eq 'COMPLETED' -and $r.Summary.child_exit_code -eq 0) 'child exit code recorded' + Check (-not (Test-Path -LiteralPath (Join-Path $r.Art 'locks\LAPTOP_GPU.lock'))) 'lock released' + $stamp = [IO.File]::ReadAllText((Join-Path $r.Art 'locks\last_gpu_run.json')) | ConvertFrom-Json + Check ($stamp.aborted -eq $false) 'a normal end stamps the 120 s cool-down, not the 600 s one' +} + +Case 'thresholds_source_bootstrap' { + $d = New-TestDir 'th-boot' + [void](New-Shim $d -First $L.Idle -Default $L.Load) + $r = Invoke-WD $d 'th-boot' ('-ChildCommand cmd.exe -ChildArguments ' + (Q $CHILD_SHORT) + ' -TimeoutSeconds 60') + Check ($r.Exit -eq 0) ('starts with only the BOOTSTRAP file present, exit ' + $r.Exit + ' / ' + $r.Out) + Check ($r.Summary.thresholds_source -eq 'BOOTSTRAP') 'summary: thresholds_source BOOTSTRAP' + Check ($r.Summary.thresholds_sha256 -eq (Get-FileHash -LiteralPath $bootstrapPath -Algorithm SHA256).Hash.ToLowerInvariant()) 'summary: sha256 of the bootstrap file' + Check ((Get-Content -LiteralPath (Join-Path $r.RunRoot 'samples.tsv') -TotalCount 5) -contains '# thresholds_source=BOOTSTRAP') 'series header: thresholds_source=BOOTSTRAP' + Check ($r.Summary.power_limit_source -eq 'enforced.power.limit') 'power_limit_source enforced.power.limit' + $d2 = New-TestDir 'th-boot-floor' + [void](New-Shim $d2 -First $L.Below99) + $r2 = Invoke-WD $d2 'th-boot-floor' '-PreflightOnly' + Check ($r2.Exit -eq 4) 'the BOOTSTRAP floor (100 W) is applied' +} + +Case 'thresholds_source_s37' { + $d = New-TestDir 'th-s37' + $td = Join-Path $d 'thresholds' + [void](New-Item -ItemType Directory -Path $td -Force) + Copy-Item -LiteralPath $bootstrapPath -Destination (Join-Path $td '2026-10-28-s3-1-laptop-thresholds.bootstrap.json') + $s37 = Join-Path $td '2026-10-29-s3-7-laptop-thresholds.json' + New-S37File $s37 { param($t) $t.under_load.temperature_ceiling_c = 85; $t.idle_preflight.limit_min_w = 130; $t.under_load.power_limit_floor_w = 125 } + $py = Get-Command py -ErrorAction SilentlyContinue + if ($null -ne $py) { + $chk = & py -3 (Join-Path $script:TreeRoot 'docs\experiments\2026-10-28-s3-1-check_bootstrap.py') --validate $s37 + Check ($LASTEXITCODE -eq 0) ('the S3.7 fixture validates against the STRA-256 schema: ' + ($chk -join ' ')) + } + # 87 C passes the bootstrap ceiling (90) and breaks the S3.7 one (85): proof that the S3.7 file is the one applied + [void](New-Shim $d -First $L.Idle -Default '9000, 1710, 6001, 95.00, P0, 0x0000000000000000, 139.00, 87, 93') + $r = Invoke-WD $d 'th-s37' ('-ThresholdsDir ' + (Q $td) + ' -ChildCommand cmd.exe -ChildArguments ' + (Q $CHILD_LONG) + ' -TimeoutSeconds 1800') + Check ($r.Exit -eq 5) ('killed by the S3.7 ceiling, exit ' + $r.Exit + ' / ' + $r.Out + $r.Err) + Check ($r.Summary.thresholds_source -eq 'S3.7') ('summary: thresholds_source S3.7, got ' + $r.Summary.thresholds_source) + Check ($r.Summary.thresholds_sha256 -eq (Get-FileHash -LiteralPath $s37 -Algorithm SHA256).Hash.ToLowerInvariant()) 'summary: sha256 of the S3.7 file' + Check ($r.Summary.reason -match 'temperature 87 C above 85 C') ('stricter S3.7 ceiling applied: ' + $r.Summary.reason) + Check ((Get-Content -LiteralPath (Join-Path $r.RunRoot 'samples.tsv') -TotalCount 5) -contains '# thresholds_source=S3.7') 'series header: thresholds_source=S3.7' + Check ($r.Out -notmatch 'cap a run at') 'no 15 minute cap with the S3.7 file: a 1,800 s timeout is accepted' + $d2 = New-TestDir 'th-s37-idle' + [void](New-Shim $d2 -First $L.At100) + $r2 = Invoke-WD $d2 'th-s37-idle' ('-ThresholdsFile ' + (Q $s37) + ' -PreflightOnly') + Check ($r2.Exit -eq 4 -and $r2.Out -match 'below the 130 W threshold') ('the S3.7 preflight limit (130 W) is applied: ' + $r2.Out) +} + +Case 'thresholds_looser_refused' { + $d = New-TestDir 'th-loose' + $td = Join-Path $d 'thresholds' + [void](New-Item -ItemType Directory -Path $td -Force) + New-S37File (Join-Path $td '2026-10-29-s3-7-laptop-thresholds.json') { param($t) $t.under_load.temperature_ceiling_c = 95 } + [void](New-Shim $d) + $r = Invoke-WD $d 'th-loose' ('-ThresholdsDir ' + (Q $td) + ' -PreflightOnly') + Check ($r.Exit -eq 2) ('a file looser than monitor.sh is refused with exit 2, got ' + $r.Exit) + Check ($r.Out -match 'temperature_ceiling_c') ('message: ' + $r.Out) + Check (-not (Test-Path -LiteralPath (Join-Path $d 'shim\calls.txt'))) 'nvidia-smi was not called' +} + +Case 'child_exit_code_nonzero' { + $d = New-TestDir 'child-rc' + [void](New-Shim $d) + $r = Invoke-WD $d 'child-rc' ('-ChildCommand cmd.exe -ChildArguments ' + (Q '/c exit 3') + ' -TimeoutSeconds 60') + Check ($r.Exit -eq 1) ('watchdog exit 1 when the child fails, got ' + $r.Exit + ' / ' + $r.Out) + Check ($r.Summary.child_exit_code -eq 3 -and $r.Summary.outcome -eq 'CHILD_FAILED') 'child exit code 3 recorded' +} + +# ===================================================================== read-only guarantee (AC5) +Case 'no_forbidden_calls_ac5' { + Push-Location $script:TreeRoot + try { + $out = & powershell -NoProfile -Command "Select-String -Path scripts/laptop/win/watchdog.ps1 -Pattern 'powercfg|Set-ExecutionPolicy|Set-ItemProperty|taskkill /im|Stop-Process -Name|(^|[^a-z])bash ' | Where-Object Line -NotMatch '^\s*#'" + Check ($null -eq $out -or @($out).Count -eq 0) ('no forbidden call on a non-comment line: ' + ($out -join ' | ')) + $extra = @(Select-String -Path 'scripts/laptop/win/watchdog.ps1' -Pattern 'nvidia-smi\s+-(pl|lgc|rgc|lmc|rmc|pm|r)\b|--power-limit|--lock-gpu|--persistence|New-ItemProperty|Remove-ItemProperty|reg\s+add|reg\.exe|Set-Service|Stop-Service|Restart-Computer|Stop-Computer|shutdown|Start-Process.*-Verb' | Where-Object { $_.Line -notmatch '^\s*#' }) + Check ($extra.Count -eq 0) ('no setting-changing call: ' + (($extra | ForEach-Object { $_.Line.Trim() }) -join ' | ')) + $kills = @(Select-String -Path 'scripts/laptop/win/watchdog.ps1' -Pattern 'Stop-Process' | Where-Object { $_.Line -notmatch '^\s*#' }) + Check (($kills.Count -ge 1) -and (@($kills | Where-Object { $_.Line -notmatch 'Stop-Process -Id ' }).Count -eq 0)) 'the only kill is Stop-Process -Id ' + } finally { Pop-Location } +} + +# ===================================================================== summary +# leftovers: only processes this script itself started and still holds a handle to (a finished one has HasExited true) +foreach ($sp in @($script:Spawned)) { + try { if (-not $sp.HasExited) { [void](Stop-PidTree -RootPid $sp.Id) } } catch { } +} +$failed = @($script:Results | Where-Object { -not $_.Ok }) +Write-Host '' +Write-Host ('cases: ' + $script:Results.Count + ', assertions: ' + $script:Asserts + ', failed: ' + $failed.Count + ', time: ' + [math]::Round($tStart.Elapsed.TotalSeconds, 1) + ' s') +if ($failed.Count -gt 0) { + foreach ($f in $failed) { Write-Host (' FAILED ' + $f.Name + ': ' + $f.Msg) } + exit 1 +} +Write-Host ('ALL TESTS PASSED (' + $script:Results.Count + ' named cases, ' + $script:Asserts + ' assertions)') +exit 0 diff --git a/scripts/laptop/win/watchdog.ps1 b/scripts/laptop/win/watchdog.ps1 new file mode 100644 index 00000000..595b274c --- /dev/null +++ b/scripts/laptop/win/watchdog.ps1 @@ -0,0 +1,757 @@ +# watchdog.ps1 - native-Windows GPU watchdog for the RTX 3080 laptop (STRA-291, S3.8 of STRA-245). +# +# A READ-ONLY port of the safeguards of scripts/laptop/monitor.sh and scripts/laptop/lap_run.sh to Windows PowerShell 5.1 +# (WSL is off for the runs; nothing here starts the WSL launcher). The only external program it runs besides the child job +# is nvidia-smi, always as a query. It never changes a power, display, lock, sleep, execution-policy or registry setting and +# never kills anything but the process tree of the child it spawned itself (and its own nvidia-smi calls). +# +# USAGE NOTE FOR THE OWNER (the file header is the usage note of the definition of done) +# powershell -NoProfile -ExecutionPolicy Bypass -File scripts\laptop\win\watchdog.ps1 ` +# -ChildCommand -ChildArguments "" -TimeoutSeconds [-RunId ] [-Leaf ] +# -TimeoutSeconds is REQUIRED and is the caller's: lap_run.sh's 900 s default would kill a ~1,300 s arm, a 256k arm needs +# at least 1800. Under the BOOTSTRAP thresholds a run is capped at 15 minutes, so such a run is refused (exit 2) until the +# S3.7 thresholds file exists (use per-process -ExecutionPolicy Bypass as above; never Set-ExecutionPolicy). +# Other parameters: -ThresholdsFile | -ThresholdsDir (default docs\experiments of this tree; picks +# *-s3-7-laptop-thresholds*.json when present, else the S3.1 BOOTSTRAP instance), -ArtifactsRoot (default: artifacts\ +# of the MAIN checkout, never inside .git\wt), -RunRoot (default \runs\), -NvidiaSmi , +# -TimeScale (clock speed-up for tests: every second below is a CLOCK second, real time = clock time / x; default 1), +# -PreflightOnly (idle checks only, no child), -Library (dot-source: define the functions, run nothing; used by the tests). +# Laptop precondition at real use (owner actions, never agent actions): OEM Turbo scheme, enforced power limit above 100 W, +# charger connected, screen unlocked, recorded confirmation of the BSOD 0x19C history (docs/experiments/2026-10-28-s3-1-*). +# +# WHAT IT DOES (thresholds come from the thresholds file: S3.7 when present, else the BOOTSTRAP instance) +# 1. Machine lock (SC13, one GPU job at a time): artifacts\locks\LAPTOP_GPU.lock, created EXCLUSIVELY (CreateNew + FileShare.None) +# with leaf, run id, PID, UTC and boot time, only when no lock exists. If the runner (STRA-316) created the lock and its run +# id equals -RunId the lock is verified and no second one is made. Any other lock refuses the run (exit 3), is never +# removed and never stolen. +# 2. Cool-down: 120 s after the previous run, 600 s after an abort (stamp artifacts\locks\last_gpu_run.json). +# 3. PREFLIGHT at idle (nvidia-smi query): refuses (exit 4) when the enforced power limit is below the threshold, SW power cap +# (0x4) or SW thermal slowdown (0x20) is active, the GPU is in P5, or any of those readings is N/A, empty, malformed or +# missing (fail closed). The limit is read from enforced.power.limit; power.limit is N/A on this GPU (commit 96484f0). +# 4. Run: the child is started and nvidia-smi sampled every 1 clock second. Each call has a 5 s timeout; a timeout or a failed +# call is a MISSING sample. The supervisor (main thread) judges; the sampler runs in its own runspace, so a hung nvidia-smi +# cannot hide a stall. The child's process tree is killed (exit 5/6/7) on: P5 with memory clock below 2000 MHz and throttle +# reasons 0x4/0x20; enforced limit below the floor; temperature above 90 C; an unreadable required field; a gap of more +# than 10 s between good samples (STALL: a STALL file is written and the lock it created is kept, all GPU work stops); +# the caller's timeout. confirm_samples (default 1 = monitor.sh's immediate trigger) consecutive samples are needed for the +# four sample rules. +# 5. Output in the run root: samples.tsv (the 1 Hz series; its first lines record thresholds_source and the thresholds +# sha256), watchdog_summary.json (carries sample_series_sha256 for the S0.1 record), abort.txt, STALL, child.stdout.txt. +# +# EXIT CODES: 0 child finished with 0; 1 child finished non-zero; 2 usage / thresholds invalid / run root already used; +# 3 lock refused; 4 preflight refused; 5 killed by a sample rule; 6 killed on the timeout; 7 killed on a STALL; 8 internal error. +# +# NOT DONE HERE: containment (the child dying with the watchdog), the STOP file and the post-abort verification are STRA-320 and +# STRA-319; the child's grandchildren are killed only while their parent is alive when the tree is enumerated. +[CmdletBinding()] +param( + [string]$ChildCommand, + [string]$ChildArguments = '', + [string]$RunId, + [string]$Leaf = 'standalone', + [double]$TimeoutSeconds = 0, + [string]$ThresholdsFile, + [string]$ThresholdsDir, + [string]$ArtifactsRoot, + [string]$RunRoot, + [string]$NvidiaSmi = 'nvidia-smi', + [double]$TimeScale = 1.0, + [switch]$PreflightOnly, + [switch]$Library +) + +$script:WatchdogDir = $PSScriptRoot +$script:Inv = [Globalization.CultureInfo]::InvariantCulture +$script:GpuFields = @('memory.used', 'clocks.sm', 'clocks.mem', 'power.draw', 'pstate', 'clocks_throttle_reasons.active', + 'enforced.power.limit', 'temperature.gpu', 'utilization.gpu') +$script:TickS = 0.25 +$script:LockName = 'LAPTOP_GPU.lock' +$script:StampName = 'last_gpu_run.json' + +# ------------------------------------------------------------------------------------------------ clock (injectable) +# A clock is a hashtable. Real: stopwatch * Scale. Virtual: T is advanced by Invoke-ClockSleep only (unit tests). +function New-Clock { + param([double]$Scale = 1.0, [switch]$Virtual) + $c = [hashtable]::Synchronized(@{}) + $c.Virtual = [bool]$Virtual + $c.Scale = $Scale + $c.T = 0.0 + $c.Sw = [Diagnostics.Stopwatch]::StartNew() + $c.Epoch0 = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() / 1000.0 + return $c +} + +function Get-ClockNow { + param($Clock) + if ($Clock.Virtual) { return [double]$Clock.T } + return $Clock.Sw.Elapsed.TotalSeconds * $Clock.Scale +} + +function Invoke-ClockSleep { + param($Clock, [double]$Seconds) + if ($Seconds -le 0) { return } + if ($Clock.Virtual) { $Clock.T = $Clock.T + $Seconds; return } + Start-Sleep -Milliseconds ([int][math]::Max(1, [math]::Ceiling($Seconds / $Clock.Scale * 1000))) +} + +function Get-ClockWallEpoch { + param($Clock) + return $Clock.Epoch0 + (Get-ClockNow $Clock) +} + +# ------------------------------------------------------------------------------------------------ process tree (own PIDs only) +function Get-PidTree { + param([int]$RootPid) + $all = @(Get-CimInstance -ClassName Win32_Process -Property ProcessId, ParentProcessId, CreationDate -ErrorAction Stop) + $byPid = @{} + $byParent = @{} + foreach ($p in $all) { + $byPid[[int]$p.ProcessId] = $p + $k = [int]$p.ParentProcessId + if (-not $byParent.ContainsKey($k)) { $byParent[$k] = New-Object System.Collections.ArrayList } + [void]$byParent[$k].Add($p) + } + if (-not $byPid.ContainsKey($RootPid)) { return @() } + $out = New-Object System.Collections.ArrayList + $seen = @{} + $queue = New-Object System.Collections.Queue + $queue.Enqueue($byPid[$RootPid]) + while ($queue.Count -gt 0) { + $n = $queue.Dequeue() + $id = [int]$n.ProcessId + if ($seen.ContainsKey($id)) { continue } + $seen[$id] = $true + [void]$out.Add($id) + if ($byParent.ContainsKey($id)) { + foreach ($c in $byParent[$id]) { + # a child must have been created after its parent: guards against a reused parent PID + if ($null -ne $c.CreationDate -and $null -ne $n.CreationDate -and $c.CreationDate -ge $n.CreationDate) { $queue.Enqueue($c) } + } + } + } + return @($out) +} + +# Kills the tree rooted at a PID this script spawned. Never by image name. Returns the PIDs it stopped. +function Stop-PidTree { + param([int]$RootPid) + $killed = New-Object System.Collections.ArrayList + for ($pass = 0; $pass -lt 3; $pass++) { + $tree = @() + try { $tree = @(Get-PidTree -RootPid $RootPid) } catch { $tree = @() } + if ($tree.Count -eq 0) { break } + [array]::Reverse($tree) # descendants first + foreach ($id in $tree) { + try { Stop-Process -Id $id -Force -ErrorAction Stop; [void]$killed.Add($id) } catch { } + } + Start-Sleep -Milliseconds 100 + } + return @($killed) +} + +# ------------------------------------------------------------------------------------------------ nvidia-smi (read-only query) +# Returns @{ Ok; Text; Why }. A call that does not finish within TimeoutS CLOCK seconds is killed (its own tree) and is a MISSING sample. +function Invoke-NvidiaQuery { + param([string]$Exe, [double]$TimeoutS, $Clock, $PidSlot = $null) + $psi = New-Object System.Diagnostics.ProcessStartInfo + $psi.FileName = $Exe + $psi.Arguments = '--query-gpu=' + ($script:GpuFields -join ',') + ' --format=csv,noheader,nounits' + $psi.UseShellExecute = $false + $psi.RedirectStandardOutput = $true + $psi.RedirectStandardError = $true + $psi.CreateNoWindow = $true + try { $p = [System.Diagnostics.Process]::Start($psi) } catch { return @{ Ok = $false; Text = ''; Why = ('cannot start ' + $Exe + ': ' + $_.Exception.Message) } } + if ($null -ne $PidSlot) { $PidSlot.Pid = $p.Id } + try { + $o = $p.StandardOutput.ReadToEndAsync() + $e = $p.StandardError.ReadToEndAsync() + $ms = [int][math]::Ceiling($TimeoutS / $Clock.Scale * 1000) + if (-not $p.WaitForExit($ms)) { + [void](Stop-PidTree -RootPid $p.Id) + return @{ Ok = $false; Text = ''; Why = ('timeout after ' + $TimeoutS + ' s') } + } + $p.WaitForExit() + [void]$o.Wait(2000) + $text = '' + if ($o.IsCompleted) { $text = $o.Result } + if ($p.ExitCode -ne 0) { + $err = '' + if ($e.Wait(500)) { $err = $e.Result.Trim() } + return @{ Ok = $false; Text = ''; Why = ('exit code ' + $p.ExitCode + ' ' + $err) } + } + return @{ Ok = $true; Text = $text; Why = '' } + } finally { + if ($null -ne $PidSlot) { $PidSlot.Pid = 0 } + $p.Dispose() + } +} + +function ConvertTo-Num { + param([string]$Text) + $v = 0.0 + if ([double]::TryParse($Text.Trim(), [Globalization.NumberStyles]::Float, [Globalization.CultureInfo]::InvariantCulture, [ref]$v)) { + if (-not [double]::IsNaN($v) -and -not [double]::IsInfinity($v)) { return $v } + } + return $null +} + +# One CSV line in the order of $GpuFields. An N/A, empty or non-numeric field becomes $null; a line with the wrong number of fields +# (for example a driver that does not know enforced.power.limit) makes every field $null (Malformed). +function ConvertTo-GpuSample { + param([string]$Text) + $s = @{ Ok = $true; Malformed = $false; Vram = $null; SmClk = $null; MemClk = $null; Power = $null; Pstate = $null + Throttle = $null; Limit = $null; Temp = $null; Util = $null; T = 0.0; Why = '' } + $line = $null + foreach ($l in ($Text -split "`r?`n")) { if ($l.Trim().Length -gt 0) { $line = $l; break } } + if ($null -eq $line) { $s.Malformed = $true; return $s } + $f = @($line.Split(',') | ForEach-Object { $_.Trim() }) + if ($f.Count -ne $script:GpuFields.Count) { $s.Malformed = $true; return $s } + $s.Vram = ConvertTo-Num $f[0] + $s.SmClk = ConvertTo-Num $f[1] + $s.MemClk = ConvertTo-Num $f[2] + $s.Power = ConvertTo-Num $f[3] + if ($f[4] -match '^P\d{1,2}$') { $s.Pstate = $f[4] } + if ($f[5] -match '^0[xX][0-9a-fA-F]{1,16}$') { $s.Throttle = [Convert]::ToInt64($f[5].Substring(2), 16) } + $s.Limit = ConvertTo-Num $f[6] + $s.Temp = ConvertTo-Num $f[7] + $s.Util = ConvertTo-Num $f[8] + return $s +} + +function Get-Unreadable { + param($S, [string[]]$Required) + $m = @() + foreach ($r in $Required) { if ($null -eq $S[$r]) { $m += $r } } + return $m +} + +$script:FieldLabel = @{ Limit = 'enforced.power.limit'; Temp = 'temperature.gpu'; Pstate = 'pstate'; MemClk = 'clocks.mem'; Throttle = 'clocks_throttle_reasons.active' } + +# ------------------------------------------------------------------------------------------------ thresholds +function Get-FileSha256 { + param([string]$Path) + $sha = [System.Security.Cryptography.SHA256]::Create() + try { return ([BitConverter]::ToString($sha.ComputeHash([IO.File]::ReadAllBytes($Path))) -replace '-', '').ToLowerInvariant() } finally { $sha.Dispose() } +} + +# Reads a thresholds file (STRA-256 schema). A file looser than the floors of monitor.sh / lap_run.sh is refused (throws). +function Read-Thresholds { + param([string]$Path) + $text = [IO.File]::ReadAllText($Path, [Text.Encoding]::UTF8).TrimStart([char]0xFEFF) + $j = $text | ConvertFrom-Json + $bad = New-Object System.Collections.ArrayList + function Need([bool]$ok, [string]$msg) { if (-not $ok) { [void]$bad.Add($msg) } } + function Num($v) { if ($null -eq $v) { return $null }; return ConvertTo-Num ([Convert]::ToString($v, [Globalization.CultureInfo]::InvariantCulture)) } + Need ($j.schema_version -eq 1) 'schema_version must be 1' + Need (@('BOOTSTRAP', 'S3.7') -contains $j.thresholds_source) 'thresholds_source must be BOOTSTRAP or S3.7' + Need ($j.power_limit_source -eq 'enforced.power.limit') 'power_limit_source must be enforced.power.limit' + Need (($j.unreadable.preflight -eq 'REFUSE') -and ($j.unreadable.run -eq 'ABORT')) 'unreadable must be REFUSE / ABORT (fail closed)' + $interval = Num $j.sampling.interval_s + $callTo = Num $j.sampling.nvidia_smi_timeout_s + $confirm = Num $j.sampling.confirm_samples + Need (($null -ne $interval) -and ($interval -eq 1)) 'sampling.interval_s must be 1' + Need (($null -ne $callTo) -and ($callTo -ge 1) -and ($callTo -le 5)) 'sampling.nvidia_smi_timeout_s must be 1..5' + Need (($null -ne $confirm) -and ($confirm -ge 1)) 'sampling.confirm_samples must be >= 1' + Need (($j.sampling.timeout_counts_as_missing_sample -eq $true) -and ($j.sampling.stall_check_off_sampler_thread -eq $true)) 'sampling must count a timeout as a missing sample and check the stall off the sampler thread' + $limMin = Num $j.idle_preflight.limit_min_w + Need (($null -ne $limMin) -and ($limMin -ge 100)) 'idle_preflight.limit_min_w must be >= 100' + Need (($j.idle_preflight.sw_power_cap_active_refuses -eq $true) -and ($j.idle_preflight.sw_thermal_slowdown_active_refuses -eq $true) -and ($j.idle_preflight.p5_refuses -eq $true)) 'idle_preflight refusals must be true' + $floor = Num $j.under_load.power_limit_floor_w + $tmax = Num $j.under_load.temperature_ceiling_c + $stall = Num $j.under_load.stall_gap_s + Need (($null -ne $floor) -and ($floor -ge 100)) 'under_load.power_limit_floor_w must be >= 100' + Need (($null -ne $tmax) -and ($tmax -gt 0) -and ($tmax -le 90)) 'under_load.temperature_ceiling_c must be in (0, 90]' + Need (($null -ne $stall) -and ($stall -gt 0) -and ($stall -le 10)) 'under_load.stall_gap_s must be in (0, 10]' + $oem = $j.under_load.oem_profile + $memBelow = Num $oem.memory_clock_mhz_below + $bits = @($oem.throttle_reason_bits | ForEach-Object { [int64]$_ }) + Need (($oem.pstate -eq 'P5') -and ($null -ne $memBelow) -and ($memBelow -ge 2000) -and ($bits -contains 4) -and ($bits -contains 32)) 'under_load.oem_profile must be P5, memory clock >= 2000, bits 4 and 32' + Need ($j.run.timeout_source -eq 'caller_parameter') 'run.timeout_source must be caller_parameter' + $cdArm = Num $j.cooldown.between_arms_s + $cdAbort = Num $j.cooldown.after_abort_s + Need (($null -ne $cdArm) -and ($cdArm -ge 120)) 'cooldown.between_arms_s must be >= 120' + Need (($null -ne $cdAbort) -and ($cdAbort -ge 600)) 'cooldown.after_abort_s must be >= 600' + $cap = Num $j.run.cap_minutes + if ($j.thresholds_source -eq 'BOOTSTRAP') { Need (($null -ne $cap) -and ($cap -ge 1) -and ($cap -le 15)) 'BOOTSTRAP needs run.cap_minutes <= 15' } + if ($bad.Count -gt 0) { throw ('thresholds file ' + $Path + ' refused: ' + ($bad -join '; ')) } + $mask = [int64]0 + foreach ($b in $bits) { $mask = $mask -bor $b } + return @{ + Source = [string]$j.thresholds_source; Sha256 = (Get-FileSha256 $Path); Path = $Path; PowerLimitSource = [string]$j.power_limit_source + IntervalS = [double]$interval; CallTimeoutS = [double]$callTo; ConfirmSamples = [int]$confirm + LimitMinW = [double]$limMin; FloorW = [double]$floor; TempMaxC = [double]$tmax; StallGapS = [double]$stall + OemPstate = [string]$oem.pstate; OemMemBelow = [double]$memBelow; OemMask = $mask + CooldownArmS = [double]$cdArm; CooldownAbortS = [double]$cdAbort + CapMinutes = $(if ($null -ne $cap) { [double]$cap } else { $null }) + } +} + +function Find-ThresholdsFile { + param([string]$Dir) + $s37 = @(Get-ChildItem -LiteralPath $Dir -Filter '*-s3-7-laptop-thresholds*.json' -File -ErrorAction SilentlyContinue | Sort-Object Name) + if ($s37.Count -gt 0) { return $s37[$s37.Count - 1].FullName } + $boot = @(Get-ChildItem -LiteralPath $Dir -Filter '*laptop-thresholds.bootstrap.json' -File -ErrorAction SilentlyContinue | Sort-Object Name) + if ($boot.Count -gt 0) { return $boot[$boot.Count - 1].FullName } + return $null +} + +# ------------------------------------------------------------------------------------------------ preflight (idle) +function Invoke-Preflight { + param($Th, [string]$Exe, $Clock) + $q = Invoke-NvidiaQuery -Exe $Exe -TimeoutS $Th.CallTimeoutS -Clock $Clock + $res = @{ Ok = $false; Reasons = @(); Sample = $null; Query = $q } + if (-not $q.Ok) { $res.Reasons = @('no reading from nvidia-smi (' + $q.Why + '): unreadable, fail closed'); return $res } + $s = ConvertTo-GpuSample $q.Text + $res.Sample = $s + $r = New-Object System.Collections.ArrayList + $miss = @(Get-Unreadable $s @('Limit', 'Pstate', 'Throttle')) + if ($s.Malformed) { [void]$r.Add('malformed nvidia-smi line (' + $q.Text.Trim() + '): unreadable, fail closed') } + elseif ($miss.Count -gt 0) { [void]$r.Add('unreadable: ' + (($miss | ForEach-Object { $script:FieldLabel[$_] }) -join ', ') + ' (N/A, empty or not numeric): fail closed') } + if ($null -ne $s.Limit -and $s.Limit -lt $Th.LimitMinW) { [void]$r.Add('enforced power limit ' + $s.Limit + ' W is below the ' + $Th.LimitMinW + ' W threshold') } + if ($null -ne $s.Throttle) { + if (($s.Throttle -band 4) -ne 0) { [void]$r.Add('SW power cap active at idle (throttle reasons 0x' + $s.Throttle.ToString('x') + ')') } + if (($s.Throttle -band 32) -ne 0) { [void]$r.Add('SW thermal slowdown active at idle (throttle reasons 0x' + $s.Throttle.ToString('x') + ')') } + } + if ($s.Pstate -eq 'P5') { [void]$r.Add('performance state P5 at idle') } + $res.Reasons = @($r) + $res.Ok = ($r.Count -eq 0) + return $res +} + +# ------------------------------------------------------------------------------------------------ run rules (pure) +# Conditions of one good sample: key -> reason. Keys: unreadable, limit, temp, oem. +function Get-Violations { + param($S, $Th) + $v = [ordered]@{} + $miss = @(Get-Unreadable $S @('Limit', 'Temp', 'Pstate', 'MemClk', 'Throttle')) + if ($S.Malformed) { $v['unreadable'] = 'malformed nvidia-smi line: unreadable, fail closed' } + elseif ($miss.Count -gt 0) { $v['unreadable'] = 'unreadable: ' + (($miss | ForEach-Object { $script:FieldLabel[$_] }) -join ', ') + ' (fail closed)' } + if ($null -ne $S.Limit -and $S.Limit -lt $Th.FloorW) { $v['limit'] = 'power limit ' + $S.Limit + ' W below the ' + $Th.FloorW + ' W floor' } + if ($null -ne $S.Temp -and $S.Temp -gt $Th.TempMaxC) { $v['temp'] = 'temperature ' + $S.Temp + ' C above ' + $Th.TempMaxC + ' C' } + if ($S.Pstate -eq $Th.OemPstate -and $null -ne $S.MemClk -and $S.MemClk -lt $Th.OemMemBelow -and $null -ne $S.Throttle -and (($S.Throttle -band $Th.OemMask) -ne 0)) { + $v['oem'] = $Th.OemPstate + ', memory ' + $S.MemClk + ' MHz, SW power cap / thermal slowdown active (reasons 0x' + $S.Throttle.ToString('x') + '): the OEM profile' + } + return $v +} + +function New-WatchState { + param($Th, [double]$StartAt, [double]$TimeoutS) + return @{ Th = $Th; StartAt = $StartAt; LastGoodAt = $StartAt; TimeoutS = $TimeoutS; Counters = @{}; Missing = 0; Good = 0; Verdict = $null } +} + +# One supervisor step. Samples are the ones that arrived since the last step (oldest first). Returns $null to keep going, else +# @{ Kind = ABORT | STALL | EXIT | TIMEOUT; Reason }. The gap rule is evaluated here, on the supervisor's own clock reading, so it does not +# depend on the sampler making progress (a hung nvidia-smi call cannot hide a stall). +function Step-Watch { + param($State, [double]$Now, $Samples, [bool]$ChildAlive) + $th = $State.Th + foreach ($s in @($Samples)) { + if ($null -eq $s) { continue } + if (-not $s.Ok) { $State.Missing++; continue } + if (($s.T - $State.LastGoodAt) -gt $th.StallGapS) { + return @{ Kind = 'STALL'; Reason = ('STALL: ' + [math]::Round($s.T - $State.LastGoodAt, 2) + ' s between samples (more than ' + $th.StallGapS + ' s)') } + } + $State.LastGoodAt = $s.T + $State.Good++ + $v = Get-Violations $s $th + foreach ($key in @('unreadable', 'limit', 'temp', 'oem')) { + if ($v.Contains($key)) { $State.Counters[$key] = 1 + [int]$State.Counters[$key] } else { $State.Counters[$key] = 0 } + } + foreach ($key in @('unreadable', 'limit', 'temp', 'oem')) { + if ([int]$State.Counters[$key] -ge $th.ConfirmSamples) { return @{ Kind = 'ABORT'; Reason = $v[$key] } } + } + } + if (($Now - $State.LastGoodAt) -gt $th.StallGapS) { + return @{ Kind = 'STALL'; Reason = ('STALL: no good sample for ' + [math]::Round($Now - $State.LastGoodAt, 2) + ' s (more than ' + $th.StallGapS + ' s); ' + $State.Missing + ' missing samples') } + } + if (-not $ChildAlive) { return @{ Kind = 'EXIT'; Reason = 'the child exited' } } + if (($Now - $State.StartAt) -ge $State.TimeoutS) { return @{ Kind = 'TIMEOUT'; Reason = ('run timeout of ' + $State.TimeoutS + ' s reached') } } + return $null +} + +# Supervisor loop. $Child = @{ IsAlive = {..}; Kill = {..} }, $Source = @{ Drain = {..} } (returns the samples that arrived), +# $OnSample is called for every drained sample (the series writer). +function Invoke-Supervise { + param($Clock, $Th, $Child, $Source, [double]$TimeoutS, [scriptblock]$OnSample, [double]$Tick = 0.25) + $state = New-WatchState -Th $Th -StartAt (Get-ClockNow $Clock) -TimeoutS $TimeoutS + $verdict = $null + while ($true) { + $now = Get-ClockNow $Clock + $samples = @(& $Source.Drain) + if ($null -ne $OnSample) { foreach ($s in $samples) { & $OnSample $s } } + $alive = [bool](& $Child.IsAlive) + $verdict = Step-Watch -State $state -Now $now -Samples $samples -ChildAlive $alive + if ($null -ne $verdict) { break } + Invoke-ClockSleep $Clock $Tick + } + $verdict.At = Get-ClockNow $Clock + $verdict.LastGoodAt = $state.LastGoodAt + $verdict.Missing = $state.Missing + $verdict.Good = $state.Good + $verdict.Killed = @() + if ($verdict.Kind -ne 'EXIT') { $verdict.Killed = @(& $Child.Kill) } + return $verdict +} + +# ------------------------------------------------------------------------------------------------ cool-down +function Get-CooldownRemaining { + param($Stamp, [double]$WallNow, $Th) + if ($null -eq $Stamp) { return 0.0 } + $need = $Th.CooldownArmS + if ($Stamp.aborted -eq $true) { $need = $Th.CooldownAbortS } + return [math]::Max(0.0, $need - ($WallNow - [double]$Stamp.end_epoch)) +} + +function Read-Stamp { + param([string]$LockDir) + $p = Join-Path $LockDir $script:StampName + if (-not (Test-Path -LiteralPath $p)) { return $null } + try { + $j = [IO.File]::ReadAllText($p) | ConvertFrom-Json + if ($null -eq $j.end_epoch) { throw 'no end_epoch' } + return $j + } catch { + # an unreadable stamp is treated as an abort that ended now (fail closed) + return [pscustomobject]@{ end_epoch = ([DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() / 1000.0); aborted = $true; run_id = 'unreadable-stamp' } + } +} + +function Write-Stamp { + param([string]$LockDir, [double]$EndEpoch, [bool]$Aborted, [string]$RunId, [string]$Reason) + $p = Join-Path $LockDir $script:StampName + $obj = [ordered]@{ end_epoch = $EndEpoch; aborted = $Aborted; run_id = $RunId; reason = $Reason } + $tmp = $p + '.tmp' + [IO.File]::WriteAllText($tmp, ($obj | ConvertTo-Json), (New-Object Text.UTF8Encoding $false)) + Move-Item -LiteralPath $tmp -Destination $p -Force +} + +# ------------------------------------------------------------------------------------------------ machine lock (SC13) +function Get-BootTimeUtc { + return (Get-CimInstance -ClassName Win32_OperatingSystem -Property LastBootUpTime).LastBootUpTime.ToUniversalTime().ToString('o') +} + +# Returns @{ Mode = created | verified | refused; Stream; Path; Reason; Holder } +function Enter-Lock { + param([string]$LockDir, [string]$RunId, [string]$Leaf) + if (-not (Test-Path -LiteralPath $LockDir)) { [void](New-Item -ItemType Directory -Path $LockDir -Force) } + $di = Get-Item -LiteralPath $LockDir -Force + if (($di.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0) { return @{ Mode = 'refused'; Reason = ('lock directory ' + $LockDir + ' is a reparse point'); Stream = $null; Path = $null; Holder = $null } } + $path = Join-Path $LockDir $script:LockName + $boot = Get-BootTimeUtc + $content = [ordered]@{ leaf = $Leaf; run_id = $RunId; pid = $PID; utc = [DateTime]::UtcNow.ToString('o'); boot_time = $boot; created_by = 'watchdog.ps1' } + $bytes = (New-Object Text.UTF8Encoding $false).GetBytes(($content | ConvertTo-Json)) + try { + $fs = [IO.FileStream]::new($path, [IO.FileMode]::CreateNew, [IO.FileAccess]::Write, [IO.FileShare]::None) + $fs.Write($bytes, 0, $bytes.Length) + $fs.Flush() + return @{ Mode = 'created'; Stream = $fs; Path = $path; Reason = ''; Holder = $content } + } catch [IO.IOException] { + if (-not (Test-Path -LiteralPath $path)) { throw } + } + $holder = $null + try { + $rf = [IO.FileStream]::new($path, [IO.FileMode]::Open, [IO.FileAccess]::Read, ([IO.FileShare]::ReadWrite -bor [IO.FileShare]::Delete)) + try { $sr = New-Object IO.StreamReader($rf); $holder = $sr.ReadToEnd() | ConvertFrom-Json } finally { $rf.Dispose() } + } catch { + return @{ Mode = 'refused'; Reason = ('a lock file exists at ' + $path + ' and cannot be read or parsed (' + $_.Exception.Message + '); never stolen, needs inspection'); Stream = $null; Path = $path; Holder = $null } + } + if ($null -ne $holder -and $holder.run_id -eq $RunId -and -not [string]::IsNullOrEmpty([string]$holder.run_id)) { + if ($holder.boot_time -and $holder.boot_time -ne $boot) { + return @{ Mode = 'refused'; Reason = ('the lock of run ' + $RunId + ' dates from another boot (' + $holder.boot_time + '); needs inspection, not stolen'); Stream = $null; Path = $path; Holder = $holder } + } + return @{ Mode = 'verified'; Stream = $null; Path = $path; Reason = ''; Holder = $holder } + } + $who = 'unknown' + if ($null -ne $holder) { $who = 'run ' + $holder.run_id + ' leaf ' + $holder.leaf + ' pid ' + $holder.pid + ' since ' + $holder.utc } + return @{ Mode = 'refused'; Reason = ('the machine lock is held by ' + $who + ' (not run ' + $RunId + '); never stolen'); Stream = $null; Path = $path; Holder = $holder } +} + +# ------------------------------------------------------------------------------------------------ paths and series +function Resolve-TreeRoot { + $d = $script:WatchdogDir + while ($d) { + if (Test-Path -LiteralPath (Join-Path $d '.git')) { return $d } + $parent = Split-Path -Parent $d + if ($parent -eq $d) { break } + $d = $parent + } + return (Resolve-Path (Join-Path $script:WatchdogDir '..\..\..')).Path +} + +# artifacts\ lives in the MAIN checkout, never inside .git\wt\ (worktree cleanup deletes ignored files) +function Resolve-MainCheckout { + $d = $script:WatchdogDir + $marker = [IO.Path]::DirectorySeparatorChar + '.git' + [IO.Path]::DirectorySeparatorChar + 'wt' + [IO.Path]::DirectorySeparatorChar + $i = $d.IndexOf($marker, [StringComparison]::OrdinalIgnoreCase) + if ($i -ge 0) { return $d.Substring(0, $i) } + return Resolve-TreeRoot +} + +function Format-N { + param($V, [string]$Fmt = '0.###') + if ($null -eq $V) { return 'NA' } + return ([double]$V).ToString($Fmt, $script:Inv) +} + +function Format-SeriesRow { + param($S, [string]$Phase, [double]$T, [double]$WallEpoch) + $thr = 'NA' + if ($null -ne $S.Throttle) { $thr = '0x' + $S.Throttle.ToString('x') } + $ps = 'NA' + if ($null -ne $S.Pstate) { $ps = $S.Pstate } + $ok = 0 + $why = '' + if ($S.Ok) { $ok = 1; if ($S.Malformed) { $why = 'malformed' } } else { $why = ([string]$S.Why) -replace '[\t\r\n]', ' ' } + return (@($Phase, (Format-N $T), (Format-N $WallEpoch '0.###'), $ok, $why, $ps, (Format-N $S.SmClk), (Format-N $S.MemClk), (Format-N $S.Power), $thr, + (Format-N $S.Limit), (Format-N $S.Temp), (Format-N $S.Util), (Format-N $S.Vram)) -join "`t") +} + +function Write-Log { + param([string]$Msg) + Write-Host ('WATCHDOG ' + $Msg) +} + +function Write-TextFile { + param([string]$Path, [string]$Text) + [IO.File]::WriteAllText($Path, $Text, (New-Object Text.UTF8Encoding $false)) +} + +# ------------------------------------------------------------------------------------------------ sampler (own runspace) +$script:SamplerLoop = { + param($Shared) + try { + $clock = $Shared.Clock + while (-not $Shared.Stop) { + $t0 = Get-ClockNow $clock + $q = Invoke-NvidiaQuery -Exe $Shared.Exe -TimeoutS $Shared.CallTimeoutS -Clock $clock -PidSlot $Shared.PidSlot + if ($q.Ok) { $s = ConvertTo-GpuSample $q.Text } else { $s = @{ Ok = $false; Why = $q.Why } } + $s.T = Get-ClockNow $clock + $Shared.Queue.Enqueue($s) + while (-not $Shared.Stop -and ((Get-ClockNow $clock) -lt ($t0 + $Shared.IntervalS))) { + Start-Sleep -Milliseconds ([int][math]::Max(1, [math]::Min(50, ($t0 + $Shared.IntervalS - (Get-ClockNow $clock)) / $clock.Scale * 1000))) + } + } + } catch { + $Shared.Queue.Enqueue(@{ Ok = $false; Why = ('sampler failed: ' + $_.Exception.Message); T = (Get-ClockNow $Shared.Clock) }) + } +} + +function Start-Sampler { + param($Shared) + $iss = [System.Management.Automation.Runspaces.InitialSessionState]::CreateDefault2() + foreach ($fn in 'Get-ClockNow', 'Invoke-ClockSleep', 'Get-PidTree', 'Stop-PidTree', 'Invoke-NvidiaQuery', 'ConvertTo-Num', 'ConvertTo-GpuSample') { + $def = (Get-Item -LiteralPath ('function:' + $fn)).ScriptBlock.ToString() + $iss.Commands.Add((New-Object System.Management.Automation.Runspaces.SessionStateFunctionEntry($fn, $def))) + } + $iss.Variables.Add((New-Object System.Management.Automation.Runspaces.SessionStateVariableEntry('GpuFields', $script:GpuFields, 'gpu fields'))) + $rs = [System.Management.Automation.Runspaces.RunspaceFactory]::CreateRunspace($iss) + $rs.Open() + $ps = [PowerShell]::Create() + $ps.Runspace = $rs + [void]$ps.AddScript($script:SamplerLoop.ToString()).AddArgument($Shared) + $async = $ps.BeginInvoke() + return @{ Ps = $ps; Rs = $rs; Async = $async } +} + +function Stop-Sampler { + param($Handle, $Shared) + $Shared.Stop = $true + $slot = [int]$Shared.PidSlot.Pid + if ($slot -ne 0) { [void](Stop-PidTree -RootPid $slot) } + [void]$Handle.Async.AsyncWaitHandle.WaitOne(8000) + try { $Handle.Ps.Dispose() } catch { } + try { $Handle.Rs.Dispose() } catch { } +} + +# ------------------------------------------------------------------------------------------------ main +function Invoke-Main { + $summary = [ordered]@{ run_id = $null; leaf = $Leaf; outcome = 'NOT_STARTED'; watchdog_exit_code = $null; reason = ''; child_pid = $null; child_exit_code = $null + thresholds_source = $null; thresholds_sha256 = $null; thresholds_file = $null; power_limit_source = $null; lock_mode = $null + timeout_seconds = $TimeoutSeconds; time_scale = $TimeScale; started_utc = [DateTime]::UtcNow.ToString('o'); ended_utc = $null + samples_good = 0; samples_missing = 0; detected_at_s = $null; last_good_at_s = $null; killed_pids = @() + sample_series_file = $null; sample_series_sha256 = $null; run_root = $null } + if (-not $PreflightOnly) { + if ([string]::IsNullOrWhiteSpace($ChildCommand)) { Write-Log 'ERROR -ChildCommand is required (or -PreflightOnly)'; return 2 } + if ($TimeoutSeconds -le 0) { Write-Log 'ERROR -TimeoutSeconds is required and must be positive (the caller owns the timeout; lap_run.sh 900 s would kill a 256k arm)'; return 2 } + } + if ($TimeScale -le 0) { Write-Log 'ERROR -TimeScale must be positive'; return 2 } + if ([string]::IsNullOrWhiteSpace($RunId)) { $RunId = 'wd-' + [DateTime]::UtcNow.ToString('yyyyMMddTHHmmssfff') + '-' + $PID } + $summary.run_id = $RunId + + # thresholds + try { + $tf = $ThresholdsFile + if ([string]::IsNullOrWhiteSpace($tf)) { + $td = $ThresholdsDir + if ([string]::IsNullOrWhiteSpace($td)) { $td = Join-Path (Resolve-TreeRoot) 'docs\experiments' } + $tf = Find-ThresholdsFile -Dir $td + if ($null -eq $tf) { throw ('no thresholds file in ' + $td + ' (S3.7 file or the S3.1 BOOTSTRAP instance)') } + } + $th = Read-Thresholds -Path $tf + } catch { + Write-Log ('ERROR ' + $_.Exception.Message) + return 2 + } + $summary.thresholds_source = $th.Source; $summary.thresholds_sha256 = $th.Sha256; $summary.thresholds_file = $th.Path; $summary.power_limit_source = $th.PowerLimitSource + Write-Log ('thresholds_source=' + $th.Source + ' sha256=' + $th.Sha256 + ' file=' + $th.Path) + if (-not $PreflightOnly -and $null -ne $th.CapMinutes -and $TimeoutSeconds -gt ($th.CapMinutes * 60)) { + Write-Log ('ERROR the ' + $th.Source + ' thresholds cap a run at ' + $th.CapMinutes + ' minutes; -TimeoutSeconds ' + $TimeoutSeconds + ' is longer. Use the S3.7 thresholds file for a longer run.') + return 2 + } + + $artifacts = $ArtifactsRoot + if ([string]::IsNullOrWhiteSpace($artifacts)) { $artifacts = Join-Path (Resolve-MainCheckout) 'artifacts' } + $lockDir = Join-Path $artifacts 'locks' + $runRoot = $RunRoot + if ([string]::IsNullOrWhiteSpace($runRoot)) { $runRoot = Join-Path (Join-Path $artifacts 'runs') $RunId } + $summary.run_root = $runRoot + + # lock + try { $lock = Enter-Lock -LockDir $lockDir -RunId $RunId -Leaf $Leaf } catch { Write-Log ('ERROR lock: ' + $_.Exception.Message); return 8 } + $summary.lock_mode = $lock.Mode + if ($lock.Mode -eq 'refused') { Write-Log ('LOCK REFUSED: ' + $lock.Reason); return 3 } + Write-Log ('lock ' + $lock.Mode + ': ' + $lock.Path) + $code = 8 + $keepLock = $false + $series = $null + $started = $false + $wasAborted = $false + $sampler = $null + $shared = $null + try { + [void](New-Item -ItemType Directory -Path $runRoot -Force) + $seriesPath = Join-Path $runRoot 'samples.tsv' + if (Test-Path -LiteralPath $seriesPath) { Write-Log ('ERROR ' + $seriesPath + ' already exists; a run root is never reused (pick a new -RunId)'); $code = 2; return $code } + $summaryPath = Join-Path $runRoot 'watchdog_summary.json' + $summary.sample_series_file = $seriesPath + $series = New-Object IO.StreamWriter($seriesPath, $false, (New-Object Text.UTF8Encoding $false)) + $series.NewLine = "`n" + $series.AutoFlush = $true + $series.WriteLine('# watchdog_sample_series v1') + $series.WriteLine('# run_id=' + $RunId) + $series.WriteLine('# leaf=' + $Leaf) + $series.WriteLine('# thresholds_source=' + $th.Source) + $series.WriteLine('# thresholds_sha256=' + $th.Sha256) + $series.WriteLine('# power_limit_source=' + $th.PowerLimitSource) + $series.WriteLine('# time_scale=' + (Format-N $TimeScale)) + $series.WriteLine('# columns: t_s is CLOCK seconds since the watchdog started, utc is the clock epoch in seconds') + $series.WriteLine((@('phase', 't_s', 'utc', 'ok', 'why', 'pstate', 'sm_mhz', 'mem_mhz', 'power_w', 'throttle', 'limit_w', 'temp_c', 'util', 'vram_mib') -join "`t")) + + # the clock starts here (after the lock, so the start-up cost is not multiplied by -TimeScale) + $clock = New-Clock -Scale $TimeScale + + # cool-down after the previous run (stamp), kept while holding the lock like lap_run.sh + $stamp = Read-Stamp -LockDir $lockDir + $remain = Get-CooldownRemaining -Stamp $stamp -WallNow (Get-ClockWallEpoch $clock) -Th $th + if ($remain -gt 0) { + Write-Log ('cool-down ' + [math]::Ceiling($remain) + ' s') + Invoke-ClockSleep $clock $remain + } + + # preflight + $pre = Invoke-Preflight -Th $th -Exe $NvidiaSmi -Clock $clock + $preS = $pre.Sample + if ($null -eq $preS) { $preS = @{ Ok = $false; Why = $pre.Query.Why } } + $series.WriteLine((Format-SeriesRow $preS 'pre' (Get-ClockNow $clock) (Get-ClockWallEpoch $clock))) + if (-not $pre.Ok) { + Write-Log ('REFUSED: ' + ($pre.Reasons -join '; ')) + $summary.outcome = 'REFUSED'; $summary.reason = ($pre.Reasons -join '; ') + $code = 4 + return $code + } + Write-Log ('preflight ok: limit ' + $preS.Limit + ' W, ' + $preS.Pstate + ', throttle 0x' + $preS.Throttle.ToString('x')) + if ($PreflightOnly) { $summary.outcome = 'PREFLIGHT_OK'; $code = 0; return $code } + + # start the child (the process this script spawns is the only one it ever kills, with its descendants) + $exe = $ChildCommand + $cmd = Get-Command -Name $ChildCommand -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1 + if ($null -ne $cmd) { $exe = $cmd.Source } + $sp = @{ FilePath = $exe; PassThru = $true; NoNewWindow = $true; RedirectStandardOutput = (Join-Path $runRoot 'child.stdout.txt'); RedirectStandardError = (Join-Path $runRoot 'child.stderr.txt') } + if (-not [string]::IsNullOrWhiteSpace($ChildArguments)) { $sp.ArgumentList = $ChildArguments } + try { $proc = Start-Process @sp } catch { Write-Log ('ERROR cannot start the child: ' + $_.Exception.Message); $summary.outcome = 'CHILD_NOT_STARTED'; $summary.reason = $_.Exception.Message; $code = 8; return $code } + $null = $proc.Handle + $started = $true + $summary.child_pid = $proc.Id + Write-Log ('child started: pid ' + $proc.Id + ' ' + $exe + ' ' + $ChildArguments) + + $shared = [hashtable]::Synchronized(@{}) + $shared.Queue = New-Object 'System.Collections.Concurrent.ConcurrentQueue[object]' + $shared.Stop = $false + $shared.Clock = $clock + $shared.Exe = $NvidiaSmi + $shared.CallTimeoutS = $th.CallTimeoutS + $shared.IntervalS = $th.IntervalS + $shared.PidSlot = [hashtable]::Synchronized(@{ Pid = 0 }) + $sampler = Start-Sampler -Shared $shared + + $q = $shared.Queue + $source = @{ Drain = { $list = New-Object System.Collections.ArrayList; $item = $null; while ($q.TryDequeue([ref]$item)) { [void]$list.Add($item) }; $list.ToArray() } } + $p = $proc + $child = @{ + IsAlive = { -not $p.HasExited } + Kill = { if ($p.HasExited) { return @() }; return @(Stop-PidTree -RootPid $p.Id) } + } + $sw = $series + $cl = $clock + $onSample = { param($s) $sw.WriteLine((Format-SeriesRow $s 'run' $s.T ($cl.Epoch0 + $s.T))) } + $verdict = Invoke-Supervise -Clock $clock -Th $th -Child $child -Source $source -TimeoutS $TimeoutSeconds -OnSample $onSample -Tick $script:TickS + + Stop-Sampler -Handle $sampler -Shared $shared + $sampler = $null + foreach ($s in @(& $source.Drain)) { & $onSample $s } # rows that arrived while stopping + + $summary.reason = $verdict.Reason + $summary.detected_at_s = [math]::Round($verdict.At, 3) + $summary.last_good_at_s = [math]::Round($verdict.LastGoodAt, 3) + $summary.samples_good = $verdict.Good + $summary.samples_missing = $verdict.Missing + $summary.killed_pids = @($verdict.Killed) + switch ($verdict.Kind) { + 'EXIT' { + $proc.WaitForExit() + $summary.child_exit_code = $proc.ExitCode + if ($proc.ExitCode -eq 0) { $summary.outcome = 'COMPLETED'; $code = 0 } else { $summary.outcome = 'CHILD_FAILED'; $code = 1 } + } + 'ABORT' { $summary.outcome = 'ABORTED'; $code = 5; $wasAborted = $true; Write-TextFile (Join-Path $runRoot 'abort.txt') ($verdict.Reason + "`n") } + 'TIMEOUT' { $summary.outcome = 'TIMEOUT'; $code = 6; $wasAborted = $true; Write-TextFile (Join-Path $runRoot 'abort.txt') ($verdict.Reason + "`n") } + 'STALL' { + $summary.outcome = 'STALL'; $code = 7; $wasAborted = $true; $keepLock = $true + Write-TextFile (Join-Path $runRoot 'abort.txt') ($verdict.Reason + "`n") + Write-TextFile (Join-Path $runRoot 'STALL') ($verdict.Reason + "`nAll laptop GPU work must stop until the owner has inspected the machine.`n") + } + } + Write-Log ($summary.outcome + ': ' + $verdict.Reason + ' (killed pids: ' + (@($verdict.Killed) -join ',') + ')') + return $code + } catch { + Write-Log ('ERROR internal: ' + $_.Exception.Message) + $summary.outcome = 'ERROR'; $summary.reason = $_.Exception.Message + if ($started -and $null -ne $proc -and -not $proc.HasExited) { [void](Stop-PidTree -RootPid $proc.Id) } + $code = 8 + return $code + } finally { + if ($null -ne $sampler) { Stop-Sampler -Handle $sampler -Shared $shared } + if ($null -ne $series) { + $series.Dispose() + $summary.sample_series_sha256 = Get-FileSha256 $seriesPath + Write-Log ('SAMPLE_SERIES_SHA256=' + $summary.sample_series_sha256 + ' ' + $seriesPath) + } + $summary.watchdog_exit_code = $code + $summary.ended_utc = [DateTime]::UtcNow.ToString('o') + if ($started -and $lock.Mode -ne 'refused') { + try { Write-Stamp -LockDir $lockDir -EndEpoch (Get-ClockWallEpoch $clock) -Aborted $wasAborted -RunId $RunId -Reason $summary.outcome } catch { Write-Log ('WARNING cannot write the cool-down stamp: ' + $_.Exception.Message) } + } + if ($null -ne $series -or (Test-Path -LiteralPath $runRoot)) { + try { Write-TextFile (Join-Path $runRoot 'watchdog_summary.json') ($summary | ConvertTo-Json -Depth 4) } catch { Write-Log ('WARNING cannot write the summary: ' + $_.Exception.Message) } + } + if ($lock.Mode -eq 'created') { + $lock.Stream.Dispose() + if ($keepLock) { Write-Log ('STALL: the lock ' + $lock.Path + ' is kept; remove it only after the owner has inspected the machine') } + else { Remove-Item -LiteralPath $lock.Path -Force -ErrorAction SilentlyContinue } + } + } +} + +if ($Library) { return } + +$exitCode = @(Invoke-Main) +exit ([int]$exitCode[$exitCode.Count - 1])