Files
leleka/scripts/laptop/win/watchdog.ps1
T
Pavlo RatushnyiandClaude Sonnet 5.5 df08f9bf14 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 <noreply@anthropic.com>
2026-10-28 20:30:07 +01:00

758 lines
42 KiB
PowerShell

# 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 <exe> -ChildArguments "<one argument string>" -TimeoutSeconds <seconds> [-RunId <id>] [-Leaf <name>]
# -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 <json> | -ThresholdsDir <dir> (default docs\experiments of this tree; picks
# *-s3-7-laptop-thresholds*.json when present, else the S3.1 BOOTSTRAP instance), -ArtifactsRoot <dir> (default: artifacts\
# of the MAIN checkout, never inside .git\wt), -RunRoot <dir> (default <artifacts>\runs\<RunId>), -NvidiaSmi <path>,
# -TimeScale <x> (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\<leaf> (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])