Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
507 lines
31 KiB
PowerShell
507 lines
31 KiB
PowerShell
# test_guard.ps1 - dry tests of scripts/laptop/win/guard.ps1 (STRA-320). CPU only, no GPU, no model, no real state.ps1.
|
|
#
|
|
# powershell -NoProfile -ExecutionPolicy Bypass -File scripts/laptop/win/test_guard.ps1
|
|
#
|
|
# Exit 0 and the line 'ALL TESTS PASSED (<n> named cases, <m> 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: the "GPU child" is a ping loop of cmd.exe / ping.exe started by the test itself; the "watchdog" is a host
|
|
# powershell process the test starts and then kills; state.ps1 is replaced by a fake state script (-StateScript) that prints the JSON
|
|
# of state.ps1 from a mode file and logs its calls. Time: the cool-down is run on a VIRTUAL clock (600 s pass in milliseconds) or with
|
|
# -TimeScale; only the dead-man fallback is measured on the real clock (about 30 s). Every process that is killed was started by this
|
|
# script. Nothing outside the test directory is touched, nothing is deleted, no power / system setting is read or changed.
|
|
# Outputs go to artifacts\runs\guard-tests\<timestamp>\ of the main checkout (git-ignored).
|
|
[CmdletBinding()]
|
|
param([string]$TestRoot)
|
|
|
|
$ErrorActionPreference = 'Stop'
|
|
$tStart = [Diagnostics.Stopwatch]::StartNew()
|
|
$script:Here = Split-Path -Parent $MyInvocation.MyCommand.Path
|
|
$script:Guard = Join-Path $script:Here 'guard.ps1'
|
|
. $script:Guard -Library
|
|
|
|
if ([string]::IsNullOrWhiteSpace($TestRoot)) {
|
|
$TestRoot = Join-Path (Join-Path (Join-Path (Resolve-GuardMainCheckout) 'artifacts') 'runs') ('guard-tests\' + [DateTime]::Now.ToString('yyyyMMdd-HHmmss'))
|
|
}
|
|
[void](New-Item -ItemType Directory -Path $TestRoot -Force)
|
|
$script:TestRoot = $TestRoot
|
|
$script:TreeRoot = Resolve-GuardTreeRoot
|
|
$script:Results = New-Object System.Collections.ArrayList
|
|
$script:Asserts = 0
|
|
$script:Spawned = New-Object System.Collections.ArrayList
|
|
$script:Seq = 0
|
|
$PSEXE = (Get-Command powershell.exe -CommandType Application).Source
|
|
$CHILD_LONG = '/c ping -n 600 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
|
|
Write-Host ('--- ' + $Name)
|
|
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 + '"' }
|
|
|
|
# one command-line argument that itself contains double quotes
|
|
function QA { param([string]$S) return '"' + ($S -replace '"', '\"') + '"' }
|
|
|
|
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)
|
|
return $d
|
|
}
|
|
|
|
function Test-PidAlive {
|
|
param([int]$Id)
|
|
return ($null -ne (Get-Process -Id $Id -ErrorAction SilentlyContinue))
|
|
}
|
|
|
|
# The fake state.ps1: prints the JSON document of state.ps1 from mode.json, logs every call to calls.log.
|
|
# mode.json: boot_time_utc ('actual' = this machine's), kp41 (number of Kernel-Power 41 events), kp41_from_call (state calls from this
|
|
# number on report kp41 = 1), query_status, clean (post-abort), reasons.
|
|
function New-FakeState {
|
|
param([string]$Dir, [string]$Boot = 'actual', [int]$Kp41 = 0, [int]$Kp41FromCall = 0, [string]$QueryStatus = 'ok', [bool]$Clean = $true)
|
|
$fd = Join-Path $Dir 'fake'
|
|
[void](New-Item -ItemType Directory -Path $fd -Force)
|
|
$src = @'
|
|
param([switch]$PostAbort, [string]$ReferenceTime, [string]$OutFile)
|
|
$d = $PSScriptRoot
|
|
$m = [IO.File]::ReadAllText((Join-Path $d 'mode.json')) | ConvertFrom-Json
|
|
$kind = 'state'
|
|
if ($PostAbort) { $kind = 'postabort' }
|
|
Add-Content -LiteralPath (Join-Path $d 'calls.log') -Value ($kind + ' ref=' + $ReferenceTime)
|
|
$n = @(Get-Content -LiteralPath (Join-Path $d 'calls.log') | Where-Object { $_ -like 'state *' }).Count
|
|
$boot = [string]$m.boot_time_utc
|
|
if ($boot -eq 'actual') { $boot = (Get-CimInstance -ClassName Win32_OperatingSystem).LastBootUpTime.ToUniversalTime().ToString('o') }
|
|
$k = [int]$m.kp41
|
|
if ([int]$m.kp41_from_call -gt 0 -and $n -ge [int]$m.kp41_from_call) { $k = 1 }
|
|
$events = @()
|
|
for ($i = 0; $i -lt $k; $i++) { $events += [ordered]@{ id = 41; provider = 'Microsoft-Windows-Kernel-Power'; time_utc = '2026-10-28T12:00:00.0000000Z'; message_first_line = 'fake' } }
|
|
$doc = [ordered]@{ schema_version = 1; mode = $kind; boot_time_utc = $boot
|
|
crash_evidence = [ordered]@{ query_status = [string]$m.query_status; reference_time_utc = $ReferenceTime; kernel_power_41 = $events; bugcheck = @(); count = $k } }
|
|
$code = 0
|
|
if ($PostAbort) {
|
|
$doc['post_abort'] = [ordered]@{ clean = [bool]$m.clean; leftover_processes = @(); compute_apps = @(); reasons = @($m.reasons) }
|
|
if (-not [bool]$m.clean) { $code = 5 }
|
|
}
|
|
ConvertTo-Json -InputObject $doc -Depth 6
|
|
exit $code
|
|
'@
|
|
[IO.File]::WriteAllText((Join-Path $fd 'state.ps1'), $src, (New-Object Text.UTF8Encoding $false))
|
|
$mode = [ordered]@{ boot_time_utc = $Boot; kp41 = $Kp41; kp41_from_call = $Kp41FromCall; query_status = $QueryStatus; clean = $Clean; reasons = @('leftover_process:leleka-serve') }
|
|
[IO.File]::WriteAllText((Join-Path $fd 'mode.json'), ($mode | ConvertTo-Json), (New-Object Text.UTF8Encoding $false))
|
|
return (Join-Path $fd 'state.ps1')
|
|
}
|
|
|
|
function Get-FakeCalls {
|
|
param([string]$Dir, [string]$Kind)
|
|
$p = Join-Path $Dir 'fake\calls.log'
|
|
if (-not (Test-Path -LiteralPath $p)) { return 0 }
|
|
return @(Get-Content -LiteralPath $p | Where-Object { $_ -like ($Kind + ' *') }).Count
|
|
}
|
|
|
|
# Runs guard.ps1 as its own process (the way the runner does) and returns Exit / Out / Err / Summary.
|
|
function Invoke-GuardCli {
|
|
param([string]$Dir, [string]$ArgString, [string]$StateScript, [double]$TimeScale = 600, [int]$TimeoutS = 180)
|
|
$art = Join-Path $Dir 'artifacts'
|
|
$rr = Join-Path $Dir 'run'
|
|
$a = '-NoProfile -ExecutionPolicy Bypass -File ' + (Q $script:Guard) + ' -ArtifactsRoot ' + (Q $art) + ' -RunRoot ' + (Q $rr) + ' -StateScript ' + (Q $StateScript) +
|
|
' -TimeScale ' + $TimeScale + ' ' + $ArgString
|
|
$psi = New-Object System.Diagnostics.ProcessStartInfo
|
|
$psi.FileName = $PSEXE
|
|
$psi.Arguments = $a
|
|
$psi.UseShellExecute = $false
|
|
$psi.RedirectStandardOutput = $true
|
|
$psi.RedirectStandardError = $true
|
|
$psi.CreateNoWindow = $true
|
|
$p = [System.Diagnostics.Process]::Start($psi)
|
|
[void]$script:Spawned.Add($p)
|
|
$o = $p.StandardOutput.ReadToEndAsync()
|
|
$e = $p.StandardError.ReadToEndAsync()
|
|
$exit = -999
|
|
if ($p.WaitForExit($TimeoutS * 1000)) { $p.WaitForExit(); $exit = $p.ExitCode } else { [void](Stop-GuardPidTree -RootPid $p.Id) }
|
|
[void]$o.Wait(5000)
|
|
$out = ''
|
|
if ($o.IsCompleted) { $out = $o.Result }
|
|
$err = ''
|
|
if ($e.Wait(1000)) { $err = $e.Result }
|
|
$sum = $null
|
|
$sf = Join-Path $rr 'guard_summary.json'
|
|
if (Test-Path -LiteralPath $sf) { $sum = [IO.File]::ReadAllText($sf) | ConvertFrom-Json }
|
|
return @{ Exit = $exit; Out = $out; Err = $err; Summary = $sum; Art = $art; RunRoot = $rr; Lock = (Join-Path $art 'locks\LAPTOP_GPU.lock'); Stop = (Join-Path $art 'runs\STOP') }
|
|
}
|
|
|
|
function Write-LockFile {
|
|
param([string]$Art, [string]$RunId, [string]$Boot = 'actual')
|
|
$ld = Join-Path $Art 'locks'
|
|
[void](New-Item -ItemType Directory -Path $ld -Force)
|
|
if ($Boot -eq 'actual') { $Boot = Get-GuardBootTimeUtc }
|
|
$c = [ordered]@{ leaf = 'STRA-316'; run_id = $RunId; pid = 4242; utc = [DateTime]::UtcNow.ToString('o'); boot_time = $Boot; created_by = 'runner' }
|
|
[IO.File]::WriteAllText((Join-Path $ld 'LAPTOP_GPU.lock'), ($c | ConvertTo-Json), (New-Object Text.UTF8Encoding $false))
|
|
return (Join-Path $ld 'LAPTOP_GPU.lock')
|
|
}
|
|
|
|
# Starts a "watchdog" host process (it dot-sources guard.ps1 -Library and owns the contained child), waits until it reports the child's
|
|
# process tree, kills the host (a process this script started), and measures how long the whole tree takes to die.
|
|
function Measure-WatchdogKilled {
|
|
param([string]$Dir, [bool]$Fallback)
|
|
$hostPs1 = Join-Path $Dir 'host.ps1'
|
|
$ready = Join-Path $Dir 'ready.txt'
|
|
$hb = Join-Path $Dir 'heartbeat'
|
|
$ff = ''
|
|
if ($Fallback) { $ff = ' -ForceFallback' }
|
|
$body = @(
|
|
('. ' + (Q $script:Guard) + ' -Library'),
|
|
('$c = Start-Contained -FilePath ''cmd.exe'' -Arguments ''' + $CHILD_LONG + ''' -StdoutPath '''' -StderrPath '''' -HeartbeatFile ' + (Q $hb) + ' -DeadmanSeconds 30' + $ff),
|
|
'$tree = @()',
|
|
'$until = [DateTime]::UtcNow.AddSeconds(40)',
|
|
'while ([DateTime]::UtcNow -lt $until) {',
|
|
(' Send-GuardHeartbeat ' + (Q $hb)),
|
|
' $tree = @(Get-GuardPidTree -RootPid $c.Pid)',
|
|
' if ($tree.Count -ge 3 -or ($c.Mode -eq ''job'' -and $tree.Count -ge 2)) { break }',
|
|
' Start-Sleep -Milliseconds 500',
|
|
'}',
|
|
('[IO.File]::WriteAllText(' + (Q $ready) + ', (@($c.Mode) + $tree) -join '' '')'),
|
|
'while ($true) {',
|
|
(' Send-GuardHeartbeat ' + (Q $hb)),
|
|
' Start-Sleep -Milliseconds 1000',
|
|
'}') -join "`r`n"
|
|
[IO.File]::WriteAllText($hostPs1, $body, (New-Object Text.UTF8Encoding $false))
|
|
$hostProc = Start-Process -FilePath $PSEXE -ArgumentList ('-NoProfile -ExecutionPolicy Bypass -File ' + (Q $hostPs1)) -PassThru -WindowStyle Hidden
|
|
[void]$script:Spawned.Add($hostProc)
|
|
$until = [DateTime]::UtcNow.AddSeconds(90)
|
|
while (-not (Test-Path -LiteralPath $ready) -and [DateTime]::UtcNow -lt $until) { Start-Sleep -Milliseconds 300 }
|
|
Check (Test-Path -LiteralPath $ready) 'the host reported the child tree'
|
|
$parts = @(([IO.File]::ReadAllText($ready)).Trim().Split(' '))
|
|
$mode = $parts[0]
|
|
$pids = @($parts[1..($parts.Count - 1)] | ForEach-Object { [int]$_ })
|
|
$alive = @($pids | Where-Object { Test-PidAlive $_ })
|
|
Check ($alive.Count -eq $pids.Count -and $pids.Count -ge 2) ('child tree alive before the kill: ' + ($pids -join ','))
|
|
$sw = [Diagnostics.Stopwatch]::StartNew()
|
|
Stop-Process -Id $hostProc.Id -Force # the watchdog dies (a process this script started)
|
|
$limit = 90
|
|
while ($sw.Elapsed.TotalSeconds -lt $limit) {
|
|
if (@($pids | Where-Object { Test-PidAlive $_ }).Count -eq 0) { break }
|
|
Start-Sleep -Milliseconds 100
|
|
}
|
|
$n = [math]::Round($sw.Elapsed.TotalSeconds, 1)
|
|
$left = @($pids | Where-Object { Test-PidAlive $_ })
|
|
foreach ($id in $left) { try { Stop-Process -Id $id -Force } catch { } } # tidy up our own test processes if the assertion below fails
|
|
return @{ Mode = $mode; Seconds = $n; Left = $left; Pids = $pids }
|
|
}
|
|
|
|
# ===================================================================== Job Object route
|
|
Case 'job_object_available' {
|
|
Check (Initialize-GuardNative) ('Add-Type of the kernel32 wrapper: ' + $script:NativeWhy)
|
|
$d = New-TestDir 'job'
|
|
$c = Start-Contained -FilePath 'cmd.exe' -Arguments '/c exit 3' -StdoutPath (Join-Path $d 'o.txt') -StderrPath (Join-Path $d 'e.txt') -HeartbeatFile (Join-Path $d 'hb')
|
|
try {
|
|
Check ($c.Mode -eq 'job') ('the Job Object route works in this Windows PowerShell: ' + $c.Why)
|
|
$until = [DateTime]::UtcNow.AddSeconds(20)
|
|
while ((Test-ContainedAlive $c) -and [DateTime]::UtcNow -lt $until) { Start-Sleep -Milliseconds 100 }
|
|
Check ((Get-ContainedExitCode $c) -eq 3) 'exit code of the contained child is read back (3)'
|
|
} finally { [void](Stop-Contained $c); Close-Contained $c }
|
|
Write-Host ('job object: available, PowerShell ' + $PSVersionTable.PSVersion)
|
|
}
|
|
|
|
Case 'watchdog killed' {
|
|
$d = New-TestDir 'killed-job'
|
|
$r = Measure-WatchdogKilled -Dir $d -Fallback $false
|
|
Check ($r.Mode -eq 'job') ('containment mode is job, got ' + $r.Mode)
|
|
Check ($r.Left.Count -eq 0) ('the whole child tree is dead (cmd.exe and its ping.exe grandchild): left ' + ($r.Left -join ','))
|
|
Write-Host ('child dead after ' + $r.Seconds + ' s')
|
|
Check ($r.Seconds -le 35) ('child dead within 35 s, got ' + $r.Seconds)
|
|
}
|
|
|
|
Case 'watchdog killed (dead-man fallback)' {
|
|
$d = New-TestDir 'killed-deadman'
|
|
$r = Measure-WatchdogKilled -Dir $d -Fallback $true
|
|
Check ($r.Mode -eq 'deadman') ('containment mode is deadman, got ' + $r.Mode)
|
|
Check ($r.Left.Count -eq 0) ('the wrapper, the child and the grandchild are dead: left ' + ($r.Left -join ','))
|
|
Write-Host ('child dead after ' + $r.Seconds + ' s (fallback dead-man, heartbeat older than 30 s)')
|
|
Check ($r.Seconds -le 35) ('fallback: child dead within 35 s, got ' + $r.Seconds)
|
|
Check ($r.Seconds -ge 25) ('fallback: not killed while the heartbeat was fresh (' + $r.Seconds + ' s)')
|
|
}
|
|
|
|
# ===================================================================== kill only what we created
|
|
foreach ($variant in @('job', 'fallback')) {
|
|
Case ('same image name (' + $variant + ')') {
|
|
$d = New-TestDir ('same-image-' + $variant)
|
|
$other = Start-Process -FilePath 'ping.exe' -ArgumentList '-n 600 127.0.0.1' -PassThru -WindowStyle Hidden # unrelated, same image as the child
|
|
[void]$script:Spawned.Add($other)
|
|
$st = New-FakeState $d
|
|
$extra = ''
|
|
if ($variant -eq 'fallback') { $extra = ' -NoJobObject' }
|
|
$r = Invoke-GuardCli -Dir $d -StateScript $st -ArgString ('-ChildCommand ping.exe -ChildArguments ' + (Q '-n 600 127.0.0.1') + ' -TimeoutSeconds 1200' + $extra)
|
|
Check ($r.Exit -eq 6) ('timeout is an abort, exit 6, got ' + $r.Exit + ' / ' + $r.Out + $r.Err)
|
|
Check ($r.Summary.containment -eq $(if ($variant -eq 'job') { 'job' } else { 'deadman' })) ('containment ' + $r.Summary.containment)
|
|
Check (-not (Test-PidAlive ([int]$r.Summary.child_pid))) ('the created child (pid ' + $r.Summary.child_pid + ') is dead')
|
|
$alive = Test-PidAlive $other.Id
|
|
Write-Host ('unrelated process alive: ' + $alive)
|
|
Check $alive 'the unrelated ping.exe is alive after the abort (killed by created PID / job only)'
|
|
try { Stop-Process -Id $other.Id -Force } catch { }
|
|
}
|
|
}
|
|
|
|
# ===================================================================== STOP file
|
|
Case 'stop file' {
|
|
# (a) a STOP file refuses the start: exit 5, file still there, no lock taken, no child started
|
|
$d = New-TestDir 'stop-present'
|
|
$st = New-FakeState $d
|
|
$stopPath = Join-Path $d 'artifacts\runs\STOP'
|
|
[void](New-Item -ItemType Directory -Path (Split-Path -Parent $stopPath) -Force)
|
|
[IO.File]::WriteAllText($stopPath, 'owner has not inspected' + "`r`n")
|
|
$before = (Get-FileHash -LiteralPath $stopPath -Algorithm SHA256).Hash
|
|
$r = Invoke-GuardCli -Dir $d -StateScript $st -ArgString ('-ChildCommand cmd.exe -ChildArguments ' + (Q '/c exit 0'))
|
|
Check ($r.Exit -eq 5) ('guard exits 5 while the STOP file exists, got ' + $r.Exit + ' / ' + $r.Out + $r.Err)
|
|
Write-Host ('guard exit code: ' + $r.Exit)
|
|
$still = Test-Path -LiteralPath $stopPath
|
|
Write-Host ('stop file still present: ' + $still)
|
|
Check $still 'the STOP file is still present afterwards'
|
|
Check ((Get-FileHash -LiteralPath $stopPath -Algorithm SHA256).Hash -eq $before) 'the STOP file is unchanged'
|
|
Check (-not (Test-Path -LiteralPath $r.Lock)) 'no lock was taken'
|
|
Check ((Get-FakeCalls $d 'state') -eq 0) 'state.ps1 was not called'
|
|
|
|
# (b) a simulated STALL (the watchdog writes STALL in the run root) creates the STOP file; the next start is refused
|
|
$d2 = New-TestDir 'stop-stall'
|
|
$st2 = New-FakeState $d2
|
|
$rr = Join-Path $d2 'run'
|
|
[void](New-Item -ItemType Directory -Path $rr -Force)
|
|
$stallCmd = '/c echo stall>' + (Q (Join-Path $rr 'STALL')) + ' & ping -n 600 127.0.0.1 >nul'
|
|
$r2 = Invoke-GuardCli -Dir $d2 -StateScript $st2 -ArgString ('-ChildCommand cmd.exe -ChildArguments ' + (QA $stallCmd))
|
|
Check ($r2.Exit -eq 7) ('STALL exits 7, got ' + $r2.Exit + ' / ' + $r2.Out + $r2.Err)
|
|
Check (Test-Path -LiteralPath $r2.Stop) 'the STOP file is created on a STALL'
|
|
$stop = [IO.File]::ReadAllText($r2.Stop) | ConvertFrom-Json
|
|
Check ($stop.kind -eq 'STALL' -and $stop.run_id -eq $r2.Summary.run_id) ('STOP file records the kind and run id: ' + $stop.kind + ' ' + $stop.run_id)
|
|
Check ($r2.Out -match 'stop file: created') 'guard printed the stop file line'
|
|
Write-Host 'stop file: created (STALL)'
|
|
Check (-not (Test-PidAlive ([int]$r2.Summary.child_pid))) 'the child was killed on the STALL'
|
|
$r3 = Invoke-GuardCli -Dir $d2 -StateScript $st2 -ArgString ('-ChildCommand cmd.exe -ChildArguments ' + (Q '/c exit 0'))
|
|
Check ($r3.Exit -eq 5) ('after the STALL a new start is refused with exit 5, got ' + $r3.Exit)
|
|
Check (Test-Path -LiteralPath $r2.Stop) 'the STOP file was not removed by the refused start'
|
|
}
|
|
|
|
# ===================================================================== lock (SC13)
|
|
Case 'lock' {
|
|
$d = New-TestDir 'lock-lib'
|
|
$ld = Join-Path $d 'artifacts\locks'
|
|
# (a) standalone start with no lock creates it; a second exclusive creation fails
|
|
$l1 = Enter-GuardLock -LockDir $ld -RunId 'run-a' -Leaf 'x' -RunIdGiven $false
|
|
Check ($l1.Mode -eq 'created' -and (Test-Path -LiteralPath $l1.Path)) 'lock created when none exists'
|
|
$held = $false
|
|
try { $fs2 = [IO.FileStream]::new($l1.Path, [IO.FileMode]::CreateNew, [IO.FileAccess]::Write, [IO.FileShare]::None); $fs2.Dispose() } catch [IO.IOException] { $held = $true }
|
|
Check $held 'a second exclusive creation fails'
|
|
Write-Host 'second lock: refused'
|
|
$l1b = Enter-GuardLock -LockDir $ld -RunId 'run-a' -Leaf 'x' -RunIdGiven $false
|
|
Check ($l1b.Mode -eq 'refused' -and $l1b.Kind -eq 'held') 'a lock held open by its owner is refused (held)'
|
|
Remove-GuardLock $l1
|
|
Check (-not (Test-Path -LiteralPath $l1.Path)) 'release removes the lock'
|
|
|
|
# (b) -RunId equal to the recorded run id: verified, no second lock
|
|
$p = Write-LockFile -Art (Join-Path $d 'artifacts') -RunId 'run-b'
|
|
$l2 = Enter-GuardLock -LockDir $ld -RunId 'run-b' -Leaf 'x' -RunIdGiven $true
|
|
Check ($l2.Mode -eq 'verified') ('verified, got ' + $l2.Mode + ' ' + $l2.Reason)
|
|
Write-Host ('lock verified: ' + $l2.Holder.run_id)
|
|
$n = @(Get-ChildItem -LiteralPath $ld -Filter '*.lock' -File).Count
|
|
Write-Host ('lock files: ' + $n)
|
|
Check ($n -eq 1) 'exactly one lock file'
|
|
$hash = (Get-FileHash -LiteralPath $p -Algorithm SHA256).Hash
|
|
|
|
# (c) another run id refuses; (d) no run id refuses; the file is untouched
|
|
$l3 = Enter-GuardLock -LockDir $ld -RunId 'run-other' -Leaf 'x' -RunIdGiven $true
|
|
Check ($l3.Mode -eq 'refused' -and $l3.Kind -eq 'mismatch') 'run id mismatch refused'
|
|
Write-Host 'lock run id mismatch: refused'
|
|
$l4 = Enter-GuardLock -LockDir $ld -RunId 'run-zzz' -Leaf 'x' -RunIdGiven $false
|
|
Check ($l4.Mode -eq 'refused' -and $l4.Kind -eq 'held') 'held lock and no -RunId refused'
|
|
Write-Host 'lock held: refused'
|
|
Check ((Get-FileHash -LiteralPath $p -Algorithm SHA256).Hash -eq $hash) 'the foreign lock was never changed or stolen'
|
|
|
|
# the same four paths through the CLI
|
|
$dc = New-TestDir 'lock-cli'
|
|
$st = New-FakeState $dc
|
|
$art = Join-Path $dc 'artifacts'
|
|
$rr = Join-Path $dc 'run'
|
|
[void](New-Item -ItemType Directory -Path $rr -Force)
|
|
$lockPath = Join-Path $art 'locks\LAPTOP_GPU.lock'
|
|
$probe = '/c if exist ' + (Q $lockPath) + ' echo present>' + (Q (Join-Path $rr 'during.txt'))
|
|
$rA = Invoke-GuardCli -Dir $dc -StateScript $st -ArgString ('-ChildCommand cmd.exe -ChildArguments ' + (QA $probe))
|
|
Check ($rA.Exit -eq 0) ('standalone start exits 0, got ' + $rA.Exit + ' / ' + $rA.Out + $rA.Err)
|
|
Check ($rA.Summary.lock_mode -eq 'created') ('standalone start created the lock: ' + $rA.Summary.lock_mode)
|
|
Check (Test-Path -LiteralPath (Join-Path $rr 'during.txt')) 'the lock existed while the child ran'
|
|
Check (-not (Test-Path -LiteralPath $lockPath)) 'the lock is released at the end'
|
|
|
|
$dv = New-TestDir 'lock-cli-verified'
|
|
$stv = New-FakeState $dv
|
|
$lpv = Write-LockFile -Art (Join-Path $dv 'artifacts') -RunId 'run-v'
|
|
$rrv = Join-Path $dv 'run'
|
|
[void](New-Item -ItemType Directory -Path $rrv -Force)
|
|
$cnt = '/c dir /b ' + (Q (Join-Path $dv 'artifacts\locks')) + ' >' + (Q (Join-Path $rrv 'locks_during.txt'))
|
|
$rV = Invoke-GuardCli -Dir $dv -StateScript $stv -ArgString ('-RunId run-v -ChildCommand cmd.exe -ChildArguments ' + (QA $cnt))
|
|
Check ($rV.Exit -eq 0) ('start with a matching lock exits 0, got ' + $rV.Exit + ' / ' + $rV.Out + $rV.Err)
|
|
Check ($rV.Summary.lock_mode -eq 'verified') ('lock verified, not created: ' + $rV.Summary.lock_mode)
|
|
$during = @(Get-Content -LiteralPath (Join-Path $rrv 'locks_during.txt') | Where-Object { $_ -like '*.lock' })
|
|
Check ($during.Count -eq 1) ('one lock file while the child ran: ' + ($during -join ','))
|
|
Check (-not (Test-Path -LiteralPath $lpv)) 'the verified lock is released after the run'
|
|
|
|
$dm = New-TestDir 'lock-cli-mismatch'
|
|
$stm = New-FakeState $dm
|
|
$lpm = Write-LockFile -Art (Join-Path $dm 'artifacts') -RunId 'run-m'
|
|
$hm = (Get-FileHash -LiteralPath $lpm -Algorithm SHA256).Hash
|
|
$rM = Invoke-GuardCli -Dir $dm -StateScript $stm -ArgString ('-RunId run-other -ChildCommand cmd.exe -ChildArguments ' + (Q '/c exit 0'))
|
|
Check ($rM.Exit -eq 3) ('run id mismatch exits 3, got ' + $rM.Exit)
|
|
Check ($rM.Out -match 'LOCK REFUSED \(mismatch\)') 'mismatch reported'
|
|
$rH = Invoke-GuardCli -Dir $dm -StateScript $stm -ArgString ('-ChildCommand cmd.exe -ChildArguments ' + (Q '/c exit 0'))
|
|
Check ($rH.Exit -eq 3) ('held lock without -RunId exits 3, got ' + $rH.Exit)
|
|
Check ($rH.Out -match 'LOCK REFUSED \(held\)') 'held reported'
|
|
Check ((Get-FileHash -LiteralPath $lpm -Algorithm SHA256).Hash -eq $hm) 'the foreign lock file is untouched by both refusals'
|
|
Check ((Get-FakeCalls $dm 'state') -eq 0) 'no child, no state call after a lock refusal'
|
|
}
|
|
|
|
# ===================================================================== crash evidence, post abort, cool-down
|
|
Case 'crash evidence' {
|
|
# boot time differs from the lock's
|
|
$d1 = New-TestDir 'crash-boot'
|
|
$st1 = New-FakeState $d1
|
|
[void](Write-LockFile -Art (Join-Path $d1 'artifacts') -RunId 'run-c' -Boot '2020-01-01T00:00:00.0000000Z')
|
|
$r1 = Invoke-GuardCli -Dir $d1 -StateScript $st1 -ArgString ('-RunId run-c -ChildCommand cmd.exe -ChildArguments ' + (Q '/c exit 0'))
|
|
Check ($r1.Exit -eq 9) ('boot time differs: exit 9, got ' + $r1.Exit + ' / ' + $r1.Out + $r1.Err)
|
|
Check ((Test-Path -LiteralPath $r1.Stop) -and $r1.Out -match 'stop file: created') 'STOP file created on a boot time that differs from the lock''s'
|
|
Write-Host 'stop file: created'
|
|
Check ($null -eq $r1.Summary.child_pid) 'the child was not started'
|
|
Check (([string]($r1.Summary.crash_evidence -join ' ')) -match 'differs from the lock') ('reason names the boot time: ' + ($r1.Summary.crash_evidence -join ' '))
|
|
|
|
# Kernel-Power 41 event
|
|
$d2 = New-TestDir 'crash-kp41'
|
|
$st2 = New-FakeState $d2 -Kp41 1
|
|
$r2 = Invoke-GuardCli -Dir $d2 -StateScript $st2 -ArgString ('-ChildCommand cmd.exe -ChildArguments ' + (Q '/c exit 0'))
|
|
Check ($r2.Exit -eq 9) ('Kernel-Power 41: exit 9, got ' + $r2.Exit + ' / ' + $r2.Out + $r2.Err)
|
|
Check (Test-Path -LiteralPath $r2.Stop) 'STOP file created on a Kernel-Power 41 event'
|
|
Write-Host 'stop file: created'
|
|
Check (([string]($r2.Summary.crash_evidence -join ' ')) -match 'Kernel-Power 41') 'reason names Kernel-Power 41'
|
|
|
|
# evidence that cannot be read fails closed
|
|
$d3 = New-TestDir 'crash-unreadable'
|
|
$st3 = New-FakeState $d3 -QueryStatus 'unreadable'
|
|
$r3 = Invoke-GuardCli -Dir $d3 -StateScript $st3 -ArgString ('-ChildCommand cmd.exe -ChildArguments ' + (Q '/c exit 0'))
|
|
Check ($r3.Exit -eq 9 -and (Test-Path -LiteralPath $r3.Stop)) ('unreadable evidence fails closed: exit ' + $r3.Exit)
|
|
|
|
# a crash that shows only AFTER the run (the second state call reports a Kernel-Power 41)
|
|
$d4 = New-TestDir 'crash-after'
|
|
$st4 = New-FakeState $d4 -Kp41FromCall 2
|
|
$r4 = Invoke-GuardCli -Dir $d4 -StateScript $st4 -ArgString ('-ChildCommand cmd.exe -ChildArguments ' + (Q '/c exit 0'))
|
|
Check ($r4.Exit -eq 9) ('evidence after the run: exit 9, got ' + $r4.Exit + ' / ' + $r4.Out + $r4.Err)
|
|
Check ((Test-Path -LiteralPath $r4.Stop) -and $null -ne $r4.Summary.child_pid) 'the child ran and the STOP file was created after it'
|
|
|
|
# clean state: no STOP file, exit 0
|
|
$d5 = New-TestDir 'crash-none'
|
|
$st5 = New-FakeState $d5
|
|
$r5 = Invoke-GuardCli -Dir $d5 -StateScript $st5 -ArgString ('-ChildCommand cmd.exe -ChildArguments ' + (Q '/c exit 0'))
|
|
Check ($r5.Exit -eq 0 -and -not (Test-Path -LiteralPath $r5.Stop)) ('no evidence: exit 0 and no STOP file, got ' + $r5.Exit + ' / ' + $r5.Out + $r5.Err)
|
|
}
|
|
|
|
Case 'post abort' {
|
|
# a timeout abort: state.ps1 -PostAbort is called exactly once
|
|
$d = New-TestDir 'postabort'
|
|
$st = New-FakeState $d
|
|
$r = Invoke-GuardCli -Dir $d -StateScript $st -ArgString ('-ChildCommand cmd.exe -ChildArguments ' + (Q $CHILD_LONG) + ' -TimeoutSeconds 1200')
|
|
Check ($r.Exit -eq 6) ('timeout abort exit 6, got ' + $r.Exit + ' / ' + $r.Out + $r.Err)
|
|
$calls = Get-FakeCalls $d 'postabort'
|
|
Write-Host ('post abort calls: ' + $calls)
|
|
Check ($calls -eq 1) 'state.ps1 -PostAbort called once'
|
|
Check ($r.Summary.post_abort_calls -eq 1 -and $r.Summary.post_abort_clean -eq $true) 'summary: one post-abort call, clean'
|
|
Check (Test-Path -LiteralPath (Join-Path $d 'artifacts\locks\last_gpu_run.json')) 'the cool-down stamp for watchdog.ps1 was written'
|
|
$stamp = [IO.File]::ReadAllText((Join-Path $d 'artifacts\locks\last_gpu_run.json')) | ConvertFrom-Json
|
|
Check ($stamp.aborted -eq $true) 'the stamp records an abort (600 s rule of watchdog.ps1)'
|
|
Check ($r.Summary.lock_released -eq $true -and -not (Test-Path -LiteralPath $r.Lock)) 'lock released after the cool-down'
|
|
|
|
# a normal end is not an abort: no post-abort call
|
|
$dn = New-TestDir 'postabort-none'
|
|
$stn = New-FakeState $dn
|
|
$rn = Invoke-GuardCli -Dir $dn -StateScript $stn -ArgString ('-ChildCommand cmd.exe -ChildArguments ' + (Q '/c exit 0'))
|
|
Check ($rn.Exit -eq 0 -and (Get-FakeCalls $dn 'postabort') -eq 0) 'a normal end makes no post-abort call'
|
|
$dn1 = New-TestDir 'child-fail'
|
|
$rf = Invoke-GuardCli -Dir $dn1 -StateScript (New-FakeState $dn1) -ArgString ('-ChildCommand cmd.exe -ChildArguments ' + (Q '/c exit 3'))
|
|
Check ($rf.Exit -eq 1 -and $rf.Summary.child_exit_code -eq 3) 'a failing child exits 1 and its code is recorded'
|
|
|
|
# the watchdog's own abort codes (5 / 6) are aborts too
|
|
$dw = New-TestDir 'child-abort-code'
|
|
$rw = Invoke-GuardCli -Dir $dw -StateScript (New-FakeState $dw) -ArgString ('-ChildCommand cmd.exe -ChildArguments ' + (Q '/c exit 5'))
|
|
Check ($rw.Exit -eq 6 -and (Get-FakeCalls $dw 'postabort') -eq 1) ('child exit 5 = watchdog abort: exit 6 and one post-abort call, got ' + $rw.Exit)
|
|
|
|
# not clean: STOP file, lock KEPT
|
|
$dd = New-TestDir 'postabort-dirty'
|
|
$std = New-FakeState $dd -Clean $false
|
|
$rd = Invoke-GuardCli -Dir $dd -StateScript $std -ArgString ('-ChildCommand cmd.exe -ChildArguments ' + (Q $CHILD_LONG) + ' -TimeoutSeconds 1200')
|
|
Check ($rd.Exit -eq 10) ('post-abort not clean: exit 10, got ' + $rd.Exit + ' / ' + $rd.Out + $rd.Err)
|
|
Check ((Test-Path -LiteralPath $rd.Stop) -and (Test-Path -LiteralPath $rd.Lock)) 'not clean: STOP file written and the lock is kept'
|
|
}
|
|
|
|
Case 'cool-down' {
|
|
$d = New-TestDir 'cooldown'
|
|
$st = New-FakeState $d
|
|
$ld = Join-Path $d 'artifacts\locks'
|
|
$lock = Enter-GuardLock -LockDir $ld -RunId 'run-cd' -Leaf 'x' -RunIdGiven $true
|
|
Check ($lock.Mode -eq 'created') 'lock created for the cool-down case'
|
|
$clock = New-GuardClock -Virtual
|
|
$script:tickLockGone = @()
|
|
$script:tickMax = 0.0
|
|
$tick = {
|
|
param($el)
|
|
if ($el -gt $script:tickMax) { $script:tickMax = $el }
|
|
if (-not (Test-Path -LiteralPath $lock.Path)) { $script:tickLockGone += $el }
|
|
}
|
|
$script:PostAbortCalls = 0
|
|
$fin = Complete-GuardAbort -Lock $lock -Clock $clock -StateScript $st -LockDir $ld -StopFile (Join-Path $d 'artifacts\runs\STOP') -RunId 'run-cd' -Reason 'ABORTED' -OnTick $tick -ReferenceTime ([DateTime]::UtcNow.AddMinutes(-1).ToString('o'))
|
|
Check ($fin.Clean -and $fin.Released) 'abort completed clean and released'
|
|
Check ($script:tickLockGone.Count -eq 0) ('the lock was never released before 600 s (it was gone at: ' + ($script:tickLockGone -join ',') + ')')
|
|
Check ($script:tickMax -eq 600) ('cool-down ran to 600 s on the fake clock, last tick ' + $script:tickMax)
|
|
Write-Host ('lock released at: ' + [int]$fin.ReleasedAt)
|
|
Check ([int]$fin.ReleasedAt -eq 600) 'released at 600 s'
|
|
Check (-not (Test-Path -LiteralPath $lock.Path)) 'the lock is gone after the cool-down'
|
|
Check ($script:PostAbortCalls -eq 1 -and (Get-FakeCalls $d 'postabort') -eq 1) 'one post-abort call in the cool-down path'
|
|
Check ((Get-GuardNow $clock) -eq 600) 'virtual clock advanced exactly 600 s'
|
|
}
|
|
|
|
# ===================================================================== forbidden calls (AC6)
|
|
Case 'no_forbidden_calls' {
|
|
Push-Location $script:TreeRoot
|
|
try {
|
|
$out = & powershell -NoProfile -Command "Select-String -Path scripts/laptop/win/guard.ps1 -Pattern 'powercfg|Set-ExecutionPolicy|bash|taskkill /im|Stop-Process -Name'"
|
|
Check ($null -eq $out -or @($out).Count -eq 0) ('no match for powercfg|Set-ExecutionPolicy|bash|taskkill /im|Stop-Process -Name: ' + ($out -join ' | '))
|
|
$kills = @(Select-String -Path 'scripts/laptop/win/guard.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 Stop-Process form is -Id <created pid>'
|
|
$extra = @(Select-String -Path 'scripts/laptop/win/guard.ps1' -Pattern 'nvidia-smi\s+-(pl|lgc|rgc|lmc|rmc|pm|r)\b|New-ItemProperty|Set-ItemProperty|reg\.exe|Set-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 ' | '))
|
|
} finally { Pop-Location }
|
|
}
|
|
|
|
# ===================================================================== summary
|
|
foreach ($sp in @($script:Spawned)) {
|
|
try { if (-not $sp.HasExited) { [void](Stop-GuardPidTree -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
|