Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 11 additions & 5 deletions .github/workflows/module.yml
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@ permissions:
env:
# As in tests.yml: the harness's console-event checks must run here.
PK_HARNESS_NO_SKIP: '1'
# As in tests.yml: a harness with no new assertion for this long is dumped
# and killed by its own watchdog.
PK_HARNESS_WATCHDOG_MINUTES: '2'
# Empty for a version's branch: the whole harness.
SECTIONS: ${{ github.event_name != 'push' && 'MODULE' || '' }}

Expand All @@ -36,13 +39,14 @@ jobs:
test:
name: Module
runs-on: windows-latest
timeout-minutes: 20
timeout-minutes: 25
steps:
- uses: actions/checkout@v7
with:
ref: ${{ inputs.tag || github.event.release.tag_name || '' }}

- name: Run the harness on the module
timeout-minutes: 16
shell: powershell
env:
PK_HARNESS_DUMP_DIR: ${{ runner.temp }}\pk-harness-dumps
Expand All @@ -52,9 +56,10 @@ jobs:
& powershell.exe @harness
exit $LASTEXITCODE

# As in tests.yml: the dumps of section AH cases that hung, if any.
# As in tests.yml: the dumps of section AH cases that hung, and of the
# harness itself if its watchdog found it hung, if any.
- name: Upload the dumps of cases that hung
if: failure()
if: failure() || cancelled()
uses: actions/upload-artifact@v7
with:
name: module-dumps-5.1
Expand All @@ -66,13 +71,14 @@ jobs:
test-pwsh:
name: Module (PowerShell 7)
runs-on: windows-latest
timeout-minutes: 20
timeout-minutes: 25
steps:
- uses: actions/checkout@v7
with:
ref: ${{ inputs.tag || github.event.release.tag_name || '' }}

- name: Run the harness on the module under pwsh
timeout-minutes: 16
shell: pwsh
env:
PK_HARNESS_DUMP_DIR: ${{ runner.temp }}\pk-harness-dumps
Expand All @@ -83,7 +89,7 @@ jobs:
exit $LASTEXITCODE

- name: Upload the dumps of cases that hung
if: failure()
if: failure() || cancelled()
uses: actions/upload-artifact@v7
with:
name: module-dumps-pwsh
Expand Down
25 changes: 18 additions & 7 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,18 +13,24 @@ permissions:
# Ctrl+C/window-close checks must run here: a skip counts as a failure.
env:
PK_HARNESS_NO_SKIP: '1'
# A harness with no new assertion for this many minutes is dumped and
# killed by its own watchdog (the longest quiet stretch is about 20 s), so
# a hang fails its step with a dump to upload, instead of running into the
# job's time limit with nothing.
PK_HARNESS_WATCHDOG_MINUTES: '2'

jobs:
harness:
name: Harness
runs-on: windows-latest
timeout-minutes: 15
timeout-minutes: 25
steps:
- uses: actions/checkout@v7

# Windows PowerShell 5.1 (shell: powershell), the version the kit targets.
# A fresh powershell.exe so the kit's compiled types load clean.
- name: Run ParallelKit.Harness.ps1
timeout-minutes: 14
shell: powershell
env:
PK_HARNESS_DUMP_DIR: ${{ runner.temp }}\pk-harness-dumps
Expand All @@ -34,6 +40,7 @@ jobs:

# The same in harness-pwsh below: keep the two in step.
- name: Run the loading sections on the module
timeout-minutes: 8
shell: powershell
env:
PK_HARNESS_DUMP_DIR: ${{ runner.temp }}\pk-harness-dumps
Expand All @@ -42,11 +49,13 @@ jobs:
exit $LASTEXITCODE

# A section AH case that ran past its time limit leaves a full dump of
# its process there, for a debugger. Nothing is uploaded if none did.
# The same in harness-pwsh below and both jobs of module.yml. The folder
# is set per step because a job's env can't use the runner context.
# its process there, for a debugger, and so does the harness itself
# when its watchdog finds it hung. Nothing is uploaded if none did.
# Cancelled too: a job that runs into its time limit is cancelled, not
# failed. The same in harness-pwsh below and both jobs of module.yml. The
# folder is set per step because a job's env can't use the runner context.
- name: Upload the dumps of cases that hung
if: failure()
if: failure() || cancelled()
uses: actions/upload-artifact@v7
with:
name: harness-dumps-5.1
Expand All @@ -59,11 +68,12 @@ jobs:
harness-pwsh:
name: Harness (PowerShell 7)
runs-on: windows-latest
timeout-minutes: 15
timeout-minutes: 25
steps:
- uses: actions/checkout@v7

- name: Run ParallelKit.Harness.ps1 under pwsh
timeout-minutes: 14
shell: pwsh
env:
PK_HARNESS_DUMP_DIR: ${{ runner.temp }}\pk-harness-dumps
Expand All @@ -72,6 +82,7 @@ jobs:
exit $LASTEXITCODE

- name: Run the loading sections on the module under pwsh
timeout-minutes: 8
shell: pwsh
env:
PK_HARNESS_DUMP_DIR: ${{ runner.temp }}\pk-harness-dumps
Expand All @@ -80,7 +91,7 @@ jobs:
exit $LASTEXITCODE

- name: Upload the dumps of cases that hung
if: failure()
if: failure() || cancelled()
uses: actions/upload-artifact@v7
with:
name: harness-dumps-pwsh
Expand Down
111 changes: 86 additions & 25 deletions ParallelKit.Harness.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,8 @@ $script:noSkip = ($env:PK_HARNESS_NO_SKIP -eq '1')

function Test-Assert {
param([bool]$Condition, [string]$Message)
# For the watchdog (below): this run is still making progress.
if ($script:beatPath) { [System.IO.File]::WriteAllText($script:beatPath, $Message) }
if ($Condition) {
$script:passCount++
Write-Host (" [PASS] " + $Message) -ForegroundColor Green
Expand All @@ -76,6 +78,7 @@ function Test-Assert {

function Test-Skip {
param([string]$Message)
if ($script:beatPath) { [System.IO.File]::WriteAllText($script:beatPath, $Message) }
if ($script:noSkip) {
$script:failCount++
Write-Host (" [FAIL] " + $Message + " (skipping isn't allowed: PK_HARNESS_NO_SKIP=1)") -ForegroundColor Red
Expand Down Expand Up @@ -129,6 +132,82 @@ $cmdExe = Join-Path $env:SystemRoot "System32\cmd.exe"
$selfExe = [System.Diagnostics.Process]::GetCurrentProcess().MainModule.FileName
$pingExe = Join-Path $env:SystemRoot "System32\ping.exe"

function Write-HarnessDump {
# A full-memory minidump of a process that hung, for a debugger: WinDbg
# with SOS for powershell.exe, dotnet-dump for pwsh. Returns '' or why it
# wasn't written.
param([System.Diagnostics.Process]$Process, [string]$Path)
try {
if (-not ('PkHarnessDump' -as [type])) {
Add-Type -TypeDefinition 'using System; using System.Runtime.InteropServices; public static class PkHarnessDump { [DllImport("dbghelp.dll", SetLastError = true)] public static extern bool MiniDumpWriteDump(IntPtr hProcess, uint processId, IntPtr hFile, uint dumpType, IntPtr exceptionParam, IntPtr userStreamParam, IntPtr callbackParam); }'
}
$null = [System.IO.Directory]::CreateDirectory([System.IO.Path]::GetDirectoryName($Path))
$fs = [System.IO.FileStream]::new($Path, [System.IO.FileMode]::Create, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None)
try {
# Full memory, handles, unloaded modules, memory and thread info.
$ok = [PkHarnessDump]::MiniDumpWriteDump($Process.Handle, [uint32]$Process.Id, $fs.SafeFileHandle.DangerousGetHandle(), [uint32]0x1826, [IntPtr]::Zero, [IntPtr]::Zero, [IntPtr]::Zero)
$code = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
} finally { $fs.Dispose() }
if (-not $ok) { [System.IO.File]::Delete($Path); return ("MiniDumpWriteDump failed: 0x" + $code.ToString('X8')) }
return ''
} catch { return ("no dump: " + $_.Exception.Message) }
}

# Where a dump goes: a case in AH that hangs, or the harness itself (below).
# CI uploads this folder when the harness fails.
$harnessDumpDir = if ($env:PK_HARNESS_DUMP_DIR) { $env:PK_HARNESS_DUMP_DIR } else { Join-Path $env:TEMP 'pk-harness-dumps' }

# A hang in the harness's own process would only end at CI's time limit,
# with nothing to show for it: the cases in AH have a time limit and a dump
# of their own, the rest doesn't. With PK_HARNESS_WATCHDOG_MINUTES set (CI
# sets it), a watchdog process waits on this one, and when no assertion has
# come for that long it dumps it into the dump folder, lists the programs it
# had running, and kills it and its tree by PID. The longest gap between
# assertions on CI is about 20 s. The watchdog shares this console, so what
# it says is in the log.
$script:beatPath = $null
$watchdogMinutes = 0.0
if ($env:PK_HARNESS_WATCHDOG_MINUTES) {
if (-not [double]::TryParse($env:PK_HARNESS_WATCHDOG_MINUTES, [System.Globalization.NumberStyles]::Float, [System.Globalization.CultureInfo]::InvariantCulture, [ref]$watchdogMinutes) -or $watchdogMinutes -le 0) {
Write-Host ("PK_HARNESS_WATCHDOG_MINUTES must be a number of minutes above 0, such as 2 or 0.5 (got '" + $env:PK_HARNESS_WATCHDOG_MINUTES + "'). Leave it unset for no watchdog.") -ForegroundColor Red
exit 1
}
$script:beatPath = Join-Path $env:TEMP ('pk-harness-beat-' + $PID + '.txt')
[System.IO.File]::WriteAllText($script:beatPath, '(none yet: the harness had just started)')
$watchdogBody = @'
$harness = [System.Diagnostics.Process]::GetProcessById(PK_PID)
$beat = 'PK_BEAT'
$limit = [TimeSpan]::FromMinutes(PK_MINUTES)
function Write-WatchdogLine([string]$Text) { [Console]::Out.WriteLine(' ' + $Text); [Console]::Out.Flush() }
while (-not $harness.WaitForExit(5000)) {
# Gone once the harness is done; it may still be exiting.
if (-not [System.IO.File]::Exists($beat)) { continue }
if (([DateTime]::UtcNow - [System.IO.File]::GetLastWriteTimeUtc($beat)) -lt $limit) { continue }
$dump = Join-Path 'PK_DUMPDIR' ('harness-' + $harness.Id + '.dmp')
Write-WatchdogLine ('[FAIL] watchdog: no assertion for PK_MINUTES minute(s), so the harness is taken to have hung. The last one: ' + [System.IO.File]::ReadAllText($beat))
Write-WatchdogLine ('watchdog: dumping the harness (PID ' + $harness.Id + ') to ' + $dump)
$dumpError = Write-HarnessDump -Process $harness -Path $dump
if ($dumpError) { Write-WatchdogLine ('watchdog: ' + $dumpError) }
try {
foreach ($c in @(Get-CimInstance Win32_Process -Filter ('ParentProcessId = ' + $harness.Id) -OperationTimeoutSec 30 -ErrorAction Stop)) {
if ($c.ProcessId -ne $PID) { Write-WatchdogLine ('watchdog: it had running ' + $c.Name + ' (PID ' + $c.ProcessId + '): ' + $c.CommandLine) }
}
} catch { Write-WatchdogLine ("watchdog: its programs couldn't be listed: " + $_.Exception.Message) }
Write-WatchdogLine 'watchdog: killing the harness and its tree'
$null = & taskkill.exe /PID $harness.Id /T /F 2>&1
if ([System.IO.File]::Exists($beat)) { [System.IO.File]::Delete($beat) }
exit 1
}
if ([System.IO.File]::Exists($beat)) { [System.IO.File]::Delete($beat) }
'@
$watchdogBody = $watchdogBody.Replace('PK_PID', [string]$PID).Replace('PK_BEAT', $script:beatPath.Replace("'", "''")).Replace('PK_MINUTES', $watchdogMinutes.ToString([System.Globalization.CultureInfo]::InvariantCulture)).Replace('PK_DUMPDIR', $harnessDumpDir.Replace("'", "''"))
$watchdogScript = "function Write-HarnessDump {" + ${function:Write-HarnessDump}.ToString() + "}`n" + $watchdogBody
# The same console, no window: what it says lands in this run's output.
$watchdogInfo = [System.Diagnostics.ProcessStartInfo]::new($selfExe, ('-NoProfile -ExecutionPolicy Bypass -EncodedCommand ' + [Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($watchdogScript))))
$watchdogInfo.UseShellExecute = $false
$null = [System.Diagnostics.Process]::Start($watchdogInfo)
}

# A user function the workers share.
function Get-HarnessDouble {
param([int]$Value)
Expand Down Expand Up @@ -3575,7 +3654,7 @@ function Invoke-HarnessCaseProcess {
# with errors stopping it, and a hung case must not outlive it.
try {
try {
$r.Children = @(Get-CimInstance Win32_Process -Filter ("ParentProcessId = " + $p.Id) | ForEach-Object { @{ Name = [string]$_.Name; Pid = [int]$_.ProcessId } })
$r.Children = @(Get-CimInstance Win32_Process -Filter ("ParentProcessId = " + $p.Id) -OperationTimeoutSec 30 | ForEach-Object { @{ Name = [string]$_.Name; Pid = [int]$_.ProcessId } })
} catch { $r.Children = @(@{ Name = ("(not listed: " + $_.Exception.Message + ")"); Pid = 0 }) }
if ($DumpPath) { $r.DumpError = Write-HarnessDump -Process $p -Path $DumpPath; if (-not $r.DumpError) { $r.Dump = $DumpPath } }
} finally {
Expand All @@ -3589,29 +3668,8 @@ function Invoke-HarnessCaseProcess {
$p.Dispose()
return $r
}
function Write-HarnessDump {
# A full-memory minidump of a process that hung, for a debugger: WinDbg
# with SOS for powershell.exe, dotnet-dump for pwsh. Returns '' or why it
# wasn't written.
param([System.Diagnostics.Process]$Process, [string]$Path)
try {
if (-not ('PkHarnessDump' -as [type])) {
Add-Type -TypeDefinition 'using System; using System.Runtime.InteropServices; public static class PkHarnessDump { [DllImport("dbghelp.dll", SetLastError = true)] public static extern bool MiniDumpWriteDump(IntPtr hProcess, uint processId, IntPtr hFile, uint dumpType, IntPtr exceptionParam, IntPtr userStreamParam, IntPtr callbackParam); }'
}
$null = [System.IO.Directory]::CreateDirectory([System.IO.Path]::GetDirectoryName($Path))
$fs = [System.IO.FileStream]::new($Path, [System.IO.FileMode]::Create, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None)
try {
# Full memory, handles, unloaded modules, memory and thread info.
$ok = [PkHarnessDump]::MiniDumpWriteDump($Process.Handle, [uint32]$Process.Id, $fs.SafeFileHandle.DangerousGetHandle(), [uint32]0x1826, [IntPtr]::Zero, [IntPtr]::Zero, [IntPtr]::Zero)
$code = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
} finally { $fs.Dispose() }
if (-not $ok) { [System.IO.File]::Delete($Path); return ("MiniDumpWriteDump failed: 0x" + $code.ToString('X8')) }
return ''
} catch { return ("no dump: " + $_.Exception.Message) }
}
# Where a case that hangs leaves its dump. CI uploads this folder when the
# harness fails.
$kwDumpDir = if ($env:PK_HARNESS_DUMP_DIR) { $env:PK_HARNESS_DUMP_DIR } else { Join-Path $env:TEMP 'pk-harness-dumps' }
# Where a case that hangs leaves its dump.
$kwDumpDir = $harnessDumpDir
$kwWork = Join-Path $env:TEMP ("pk-harness-ah-" + $PID)
$null = [System.IO.Directory]::CreateDirectory($kwWork)

Expand All @@ -3624,7 +3682,7 @@ $kwHang = Invoke-HarnessCaseProcess -FilePath $selfExe -Arguments ('-NoProfile -
$kwHangSecs = [math]::Round($kwSw.Elapsed.TotalSeconds, 1)
$kwHangPing = @($kwHang.Children | Where-Object { $_.Name -eq 'PING.EXE' })
$kwHangLeft = @($kwHangPing | Where-Object { $null -ne (Get-Process -Id $_.Pid -ErrorAction SilentlyContinue) })
Test-Assert ($kwHang.TimedOut -and $kwHang.Gone -and $kwSw.Elapsed.TotalSeconds -lt 20 -and $kwHang.Stdout -like 'started *') ("a case that can't be stopped is cut off at its time limit, with its output so far (" + $kwHangSecs + " s, gone: " + $kwHang.Gone + ", output: " + $kwHang.Stdout.Trim() + ")")
Test-Assert ($kwHang.TimedOut -and $kwHang.Gone -and $kwSw.Elapsed.TotalSeconds -lt 20 -and $kwHang.Stdout -like 'started *') ("a case that can't be stopped is cut off at its time limit, with its output so far (" + $kwHangSecs + " s, gone: " + $kwHang.Gone + ", output: " + $kwHang.Stdout.Trim() + $(if (-not $kwHang.TimedOut) { "; it ended by itself, exit code 0x" + ([int]$kwHang.ExitCode).ToString('X8') + ", stderr: " + $kwHang.Stderr.Trim() }) + ")")
Test-Assert ($kwHangPing.Count -eq 1 -and $kwHangLeft.Count -eq 0) ("its child processes are listed, and killed with it (ping listed " + $kwHangPing.Count + "x, left running " + $kwHangLeft.Count + ")")
# The dump, on ping.exe as the program that runs too long: a full dump of a
# PowerShell is hundreds of MB, one of ping a few.
Expand Down Expand Up @@ -6613,6 +6671,9 @@ if ($null -ne $moduleDir) {
Remove-Item -LiteralPath $moduleDir -Recurse -Force -ErrorAction SilentlyContinue
}

# Tells the watchdog the run is over.
if ($script:beatPath) { Remove-Item -LiteralPath $script:beatPath -ErrorAction SilentlyContinue }

Write-Host "==============================================="
$skipText = ""
if ($script:skipCount -gt 0) { $skipText = ", " + $script:skipCount + " skipped" }
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -697,7 +697,7 @@ powershell -NoProfile -File .\ParallelKit.Harness.ps1
<details>
<summary>What it prints, and the stress tests in Testing/</summary>

It takes about seven minutes. It prints a `[PASS]`/`[FAIL]` line per check and exits 0 only if everything passed. A few checks send real Ctrl+C, Ctrl+Break and window-close events to child PowerShell processes in hidden consoles of their own, never to yours. Where a machine can't deliver those, they print `[SKIP]` with the reason instead; set `PK_HARNESS_NO_SKIP=1` to count skips as failures. The checks in section AH each run in a PowerShell process of their own with a 30-second limit; one that runs past it fails, and leaves a full dump of its process in `%TEMP%\pk-harness-dumps` (or `PK_HARNESS_DUMP_DIR`) for a debugger. A dump is a few hundred MB, and nothing deletes it for you. A few `message handler failed` lines in the output are expected: some checks break the message handler on purpose to test the fallback. `-Section AO,BB` runs only those sections (and A, the setup), for working on one area; it isn't a full pass, and its last line says so. `-AsModule` builds [the module](#as-a-module) and tests that instead of dot-sourcing the file; `-AsModule -Section MODULE` runs the sections where that can make a difference, in about a minute and a half.
It takes about seven minutes. It prints a `[PASS]`/`[FAIL]` line per check and exits 0 only if everything passed. A few checks send real Ctrl+C, Ctrl+Break and window-close events to child PowerShell processes in hidden consoles of their own, never to yours. Where a machine can't deliver those, they print `[SKIP]` with the reason instead; set `PK_HARNESS_NO_SKIP=1` to count skips as failures. The checks in section AH each run in a PowerShell process of their own with a 30-second limit; one that runs past it fails, and leaves a full dump of its process in `%TEMP%\pk-harness-dumps` (or `PK_HARNESS_DUMP_DIR`) for a debugger. Set `PK_HARNESS_WATCHDOG_MINUTES` (GitHub's runs use 2) to have the harness itself dumped there and stopped, with its last check named, when no check has finished for that many minutes. A dump is a few hundred MB, and nothing deletes it for you. A few `message handler failed` lines in the output are expected: some checks break the message handler on purpose to test the fallback. `-Section AO,BB` runs only those sections (and A, the setup), for working on one area; it isn't a full pass, and its last line says so. `-AsModule` builds [the module](#as-a-module) and tests that instead of dot-sourcing the file; `-AsModule -Section MODULE` runs the sections where that can make a difference, in about a minute and a half.

GitHub runs the same harness on Windows PowerShell 5.1 and on PowerShell 7 for every pull request and every change to `main`, and then those sections on the module. It also runs the soak test below on both before each release ([runs](https://github.com/HalRiveria/PowerShell-ParallelKit/actions/workflows/soak.yml)), and the whole harness on the module, which it then checks with PSScriptAnalyzer and packs ([runs](https://github.com/HalRiveria/PowerShell-ParallelKit/actions/workflows/module.yml)). The other scripts in `Testing/` are run by hand.

Expand Down