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
23 changes: 23 additions & 0 deletions .github/workflows/module.yml
Original file line number Diff line number Diff line change
Expand Up @@ -44,12 +44,24 @@ jobs:

- name: Run the harness on the module
shell: powershell
env:
PK_HARNESS_DUMP_DIR: ${{ runner.temp }}\pk-harness-dumps
run: |
$harness = @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', '.\ParallelKit.Harness.ps1', '-AsModule')
if ($env:SECTIONS) { $harness += @('-Section', $env:SECTIONS) }
& powershell.exe @harness
exit $LASTEXITCODE

# As in tests.yml: the dumps of section AH cases that hung, if any.
- name: Upload the dumps of cases that hung
if: failure()
uses: actions/upload-artifact@v7
with:
name: module-dumps-5.1
path: ${{ runner.temp }}\pk-harness-dumps
if-no-files-found: ignore
retention-days: 7

# PowerShell 7. Keep in step with test.
test-pwsh:
name: Module (PowerShell 7)
Expand All @@ -62,12 +74,23 @@ jobs:

- name: Run the harness on the module under pwsh
shell: pwsh
env:
PK_HARNESS_DUMP_DIR: ${{ runner.temp }}\pk-harness-dumps
run: |
$harness = @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', '.\ParallelKit.Harness.ps1', '-AsModule')
if ($env:SECTIONS) { $harness += @('-Section', $env:SECTIONS) }
& pwsh @harness
exit $LASTEXITCODE

- name: Upload the dumps of cases that hung
if: failure()
uses: actions/upload-artifact@v7
with:
name: module-dumps-pwsh
path: ${{ runner.temp }}\pk-harness-dumps
if-no-files-found: ignore
retention-days: 7

package:
name: Module package
needs: [test, test-pwsh]
Expand Down
30 changes: 30 additions & 0 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -26,17 +26,34 @@ jobs:
# A fresh powershell.exe so the kit's compiled types load clean.
- name: Run ParallelKit.Harness.ps1
shell: powershell
env:
PK_HARNESS_DUMP_DIR: ${{ runner.temp }}\pk-harness-dumps
run: |
& powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\ParallelKit.Harness.ps1
exit $LASTEXITCODE

# The same in harness-pwsh below: keep the two in step.
- name: Run the loading sections on the module
shell: powershell
env:
PK_HARNESS_DUMP_DIR: ${{ runner.temp }}\pk-harness-dumps
run: |
& powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\ParallelKit.Harness.ps1 -AsModule -Section MODULE
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.
- name: Upload the dumps of cases that hung
if: failure()
uses: actions/upload-artifact@v7
with:
name: harness-dumps-5.1
path: ${{ runner.temp }}\pk-harness-dumps
if-no-files-found: ignore
retention-days: 7

# PowerShell 7 on Windows is supported alongside 5.1, so this is a required
# check too.
harness-pwsh:
Expand All @@ -48,16 +65,29 @@ jobs:

- name: Run ParallelKit.Harness.ps1 under pwsh
shell: pwsh
env:
PK_HARNESS_DUMP_DIR: ${{ runner.temp }}\pk-harness-dumps
run: |
& pwsh -NoProfile -ExecutionPolicy Bypass -File .\ParallelKit.Harness.ps1
exit $LASTEXITCODE

- name: Run the loading sections on the module under pwsh
shell: pwsh
env:
PK_HARNESS_DUMP_DIR: ${{ runner.temp }}\pk-harness-dumps
run: |
& pwsh -NoProfile -ExecutionPolicy Bypass -File .\ParallelKit.Harness.ps1 -AsModule -Section MODULE
exit $LASTEXITCODE

- name: Upload the dumps of cases that hung
if: failure()
uses: actions/upload-artifact@v7
with:
name: harness-dumps-pwsh
path: ${{ runner.temp }}\pk-harness-dumps
if-no-files-found: ignore
retention-days: 7

# The C# in Source/: ParallelKit.ps1 carries the same code, and it compiles
# with no warnings as C# 5 with the .NET Framework's compiler (Add-Type's on
# Windows PowerShell 5.1), and with the .NET SDK for the .NET pwsh runs on,
Expand Down
135 changes: 113 additions & 22 deletions ParallelKit.Harness.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -3434,10 +3434,94 @@ Write-Host ""
if (Test-HarnessSection 'AH' "'continue' or 'break' in a callback stays in the callback") {

# PowerShell sends continue/break to the nearest loop on the call stack, which
# for a callback is one of the kit's own. Each case runs in its own
# [PowerShell] so one that hangs fails after a timeout instead of hanging the
# suite. In each, KEYWORD becomes the keyword; the case sets $kwOk and
# $kwDetail. The kit must finish the run correctly and warn once.
# for a callback is one of the kit's own. Each case runs in a PowerShell
# process of its own, so one that hangs fails after a time limit and names the
# case, instead of hanging the suite: a [PowerShell] in this process couldn't
# promise that, since its Stop() waits for the case and can block for good. In
# each, KEYWORD becomes the keyword; the case sets $kwOk and $kwDetail. The kit
# must finish the run correctly and warn once.
function Invoke-HarnessCaseProcess {
# Runs a program, for the cases a fresh PowerShell of the harness's own
# version, and waits up to $TimeoutMs. Not through the kit, which is what's
# under test. On a timeout it first records what the process was doing (its
# child processes, and a dump when $DumpPath is given), then kills it and
# its tree by PID.
param([string]$FilePath, [string]$Arguments, [int]$TimeoutMs, [string]$DumpPath = '')
$psi = [System.Diagnostics.ProcessStartInfo]::new($FilePath, $Arguments)
$psi.UseShellExecute = $false
$psi.CreateNoWindow = $true
$psi.RedirectStandardOutput = $true
$psi.RedirectStandardError = $true
$p = [System.Diagnostics.Process]::Start($psi)
$outTask = $p.StandardOutput.ReadToEndAsync()
$errTask = $p.StandardError.ReadToEndAsync()
$r = @{ TimedOut = $false; ExitCode = $null; Stdout = ''; Stderr = ''; Pid = $p.Id; Children = @(); Dump = ''; DumpError = ''; Gone = $true }
if ($p.WaitForExit($TimeoutMs)) {
$p.WaitForExit()
$r.ExitCode = $p.ExitCode
} else {
$r.TimedOut = $true
# The kill happens whatever the notes before it do: the harness runs
# 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 } })
} 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 {
$null = & taskkill.exe /PID $p.Id /T /F 2>&1
$r.Gone = $p.WaitForExit(10000)
}
}
# The pipes close once the process and anything that inherited them are gone.
if ($outTask.Wait(5000)) { $r.Stdout = $outTask.Result }
if ($errTask.Wait(5000)) { $r.Stderr = $errTask.Result }
$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' }
$kwWork = Join-Path $env:TEMP ("pk-harness-ah-" + $PID)
$null = [System.IO.Directory]::CreateDirectory($kwWork)

# The time limit itself, on a case that can't be stopped from inside: a .NET
# wait with no timeout, with a ping.exe of its own running.
$kwHangScript = Join-Path $kwWork 'hang.ps1'
[System.IO.File]::WriteAllText($kwHangScript, "`$i = [System.Diagnostics.ProcessStartInfo]::new('" + $pingExe + "', '-n 30 127.0.0.1')`r`n`$i.UseShellExecute = `$false; `$i.CreateNoWindow = `$true; `$i.RedirectStandardOutput = `$true`r`n`$c = [System.Diagnostics.Process]::Start(`$i)`r`n'started ' + `$c.Id`r`n`$null = [System.Threading.ManualResetEvent]::new(`$false).WaitOne()`r`n")
$kwSw = [System.Diagnostics.Stopwatch]::StartNew()
$kwHang = Invoke-HarnessCaseProcess -FilePath $selfExe -Arguments ('-NoProfile -ExecutionPolicy Bypass -File "' + $kwHangScript + '"') -TimeoutMs 3000
$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 ($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.
$kwDumpFile = Join-Path $kwWork 'check.dmp'
$kwDumped = Invoke-HarnessCaseProcess -FilePath $pingExe -Arguments '-n 30 127.0.0.1' -TimeoutMs 1000 -DumpPath $kwDumpFile
$kwDumpSize = if (Test-Path -LiteralPath $kwDumpFile) { (Get-Item -LiteralPath $kwDumpFile).Length } else { 0 }
Test-Assert ($kwDumped.TimedOut -and $kwDumped.Gone -and $kwDumped.Dump -eq $kwDumpFile -and $kwDumpSize -gt 100KB) ("a program over its time limit is dumped before it's killed (" + [math]::Round($kwDumpSize / 1MB, 1) + " MB, gone: " + $kwDumped.Gone + $(if ($kwDumped.DumpError) { ", " + $kwDumped.DumpError } else { '' }) + ")")
$kwPrelude = @'
$kwMessages = [System.Collections.Generic.List[string]]::new()
Set-PkMessageHandler { param($Message, $Level) $kwMessages.Add($Message) }.GetNewClosure()
Expand Down Expand Up @@ -3537,27 +3621,22 @@ $kwOk = ($b.Results.Count -eq 4 -and $kwList.Count -ge 2); $kwDetail = "results
}
$kwEpilogue = @'
$kwWarnings = @($kwMessages | Where-Object { $_ -like "*'continue' or 'break'*" })
[pscustomobject]@{ Ok = [bool]$kwOk; Detail = [string]$kwDetail; Warned = $kwWarnings.Count; Text = ($kwWarnings -join ' | ') }
[System.IO.File]::WriteAllText('RESULT', ([pscustomobject]@{ Ok = [bool]$kwOk; Detail = [string]$kwDetail; Warned = $kwWarnings.Count; Text = ($kwWarnings -join ' | ') } | ConvertTo-Json -Compress))
'@
$kwSavedHandler = [PkState]::MessageHandler
$kwScriptPath = Join-Path $kwWork 'case.ps1'
$kwResultPath = Join-Path $kwWork 'result.json'
$kwLimitSecs = 30
foreach ($kwName in $kwCases.Keys) {
foreach ($kwKeyword in 'continue', 'break') {
$kwScript = ". '" + $kitPath + "'`r`n" + $kwPrelude + "`r`n" + $kwCases[$kwName].Replace('KEYWORD', $kwKeyword) + "`r`n" + $kwEpilogue
$ps = [PowerShell]::Create()
$null = $ps.AddScript($kwScript)
$async = $ps.BeginInvoke()
$kwFinished = $async.AsyncWaitHandle.WaitOne(20000)
$kwScript = ". '" + $kitPath + "'`r`n" + $kwPrelude + "`r`n" + $kwCases[$kwName].Replace('KEYWORD', $kwKeyword) + "`r`n" + $kwEpilogue.Replace('RESULT', $kwResultPath.Replace("'", "''"))
[System.IO.File]::WriteAllText($kwScriptPath, $kwScript)
[System.IO.File]::Delete($kwResultPath)
$kwDump = Join-Path $kwDumpDir ("ah-" + ($kwName -replace '[^A-Za-z0-9]+', '-').Trim('-') + "-" + $kwKeyword + "-" + $PID + ".dmp")
$kwRun = Invoke-HarnessCaseProcess -FilePath $selfExe -Arguments ('-NoProfile -ExecutionPolicy Bypass -File "' + $kwScriptPath + '"') -TimeoutMs ($kwLimitSecs * 1000) -DumpPath $kwDump
$kwFinished = -not $kwRun.TimedOut
$kwOut = $null
$kwError = ''
if ($kwFinished) {
try { $kwOut = @($ps.EndInvoke($async)) | Select-Object -Last 1 } catch { $kwError = [string]$_ }
} else {
$ps.Stop()
}
$kwConsole = (@($ps.Streams.Information) | ForEach-Object { [string]$_ }) -join ' '
$ps.Dispose()
# The case set its own handler in this process's shared state: put the harness's back.
[PkState]::MessageHandler = $kwSavedHandler
if ($kwFinished -and (Test-Path -LiteralPath $kwResultPath)) { $kwOut = [System.IO.File]::ReadAllText($kwResultPath) | ConvertFrom-Json }
$kwConsole = $kwRun.Stdout
if ($kwName -eq 'message handler') {
# Its warning can't go through the handler that broke, so it goes
# to the console, once however many messages the handler got.
Expand All @@ -3570,10 +3649,22 @@ foreach ($kwName in $kwCases.Keys) {
$kwExpected = $kwEngine + ': ' + ($kwName -split ' ')[0] + " used 'continue' or 'break'"
$kwWarned = ($null -ne $kwOut -and $kwOut.Warned -eq 1 -and $kwOut.Text.StartsWith($kwExpected))
}
$kwDetailText = if ($null -ne $kwOut) { $kwOut.Detail + ", warnings " + $kwOut.Warned + ": " + $kwOut.Text } elseif ($kwFinished) { "error: " + $kwError } else { "still running after 20 s" }
if ($null -ne $kwOut) { $kwDetailText = $kwOut.Detail + ", warnings " + $kwOut.Warned + ": " + $kwOut.Text }
elseif ($kwFinished) { $kwDetailText = "no result, exit " + $kwRun.ExitCode + ": " + ($kwRun.Stderr.Trim() -replace '\s+', ' ') }
else {
# What it was doing when it was stopped: the programs it had
# running (not its console's conhost), and where its dump is.
$kwKids = @($kwRun.Children | Where-Object { $_.Name -ne 'conhost.exe' } | ForEach-Object { $_.Name + " " + $_.Pid }) -join ', '
if (-not $kwKids) { $kwKids = 'none' }
$kwDumpText = if ($kwRun.Dump) { "dump " + $kwRun.Dump } else { $kwRun.DumpError }
$kwDetailText = "still running after " + $kwLimitSecs + " s, killed (gone: " + $kwRun.Gone + "); its programs: " + $kwKids + "; " + $kwDumpText
}
Test-Assert ($kwFinished -and $null -ne $kwOut -and $kwOut.Ok -and $kwWarned) ("'" + $kwKeyword + "' in " + $kwName + " ends only the callback, with one warning (" + $kwDetailText + ")")
}
}
# A file there can still be held for a moment (a virus scan of the dump, say):
# a temp folder left behind isn't worth stopping the harness for.
try { Remove-Item -LiteralPath $kwWork -Recurse -Force } catch { Write-Host (" (left " + $kwWork + ": " + $_.Exception.Message + ")") }

# The wrap hands back what a callback returned as it was: a one-element
# array returned whole (`,@(...)`) is still that array.
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -694,7 +694,7 @@ powershell -NoProfile -File .\ParallelKit.Harness.ps1
<details>
<summary>What it prints, and the stress tests in Testing/</summary>

It takes about five and a half 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. 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 five and a half 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.

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