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
47 changes: 45 additions & 2 deletions ParallelKit.Harness.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -1341,7 +1341,7 @@ Test-Assert ((Get-HarnessShape $shapeOne) -eq 'ExitCode,Stdout,Stderr,StreamTime
$shapeDispatch = Invoke-PkProcessDispatch -MaxConcurrent 1 -GroupProvider { return $null } -JobBuilder { param($g) } -JobFinalize { param($j, $p) }
Test-Assert ((Get-HarnessShape $shapeDispatch) -eq 'GroupResults,Aborted,ForceKilledCount,JobStarterFailedCount') ("the dispatcher returns an object (" + (Get-HarnessShape $shapeDispatch) + ")")
$shapeJobs = Invoke-PkRunspaceJobs -MaxParallel 1 -JobParams @{ Id = 1 } -WorkerScript { param($Id) }
Test-Assert ((Get-HarnessShape $shapeJobs) -eq 'ForceStoppedCount,CrashedCount,Aborted,Crashed') ("runspace jobs return an object (" + (Get-HarnessShape $shapeJobs) + ")")
Test-Assert ((Get-HarnessShape $shapeJobs) -eq 'ForceStoppedCount,CrashedCount,Aborted,Crashed,Errors') ("runspace jobs return an object (" + (Get-HarnessShape $shapeJobs) + ")")
$shapeFindings = Test-PkWorkerSafety -WorkerScript { param($Id) $null = [Func[int]]{ 1 } }
$shapeFinding = $shapeFindings[0]
Test-Assert ((Get-HarnessShape $shapeFinding) -eq 'Rule,Where,Line,Text') ("worker-safety findings are objects (" + (Get-HarnessShape $shapeFinding) + ")")
Expand Down Expand Up @@ -2052,7 +2052,7 @@ $outcome = @{}
$plainJobs = Invoke-PkRunspaceJobs -MaxParallel 1 -JobParams (New-JobList -Jobs @(@{ Id = 1 })) -WorkerScript { param([int]$Id) @{ Id = ("job" + $Id) } } -ResultHandler { param($r) $outcome[$r.Id] = 1 }
$privateCall = @(Test-PkWorkerSafety -WorkerScript { param($N) Invoke-PkMessageHandler -Message 'x' -Level Info })
Test-Assert ($privateCall.Count -eq 1 -and $privateCall[0].Rule -eq 'MissingFunction') ("worker code calling one of the kit's private helpers is still flagged (" + (@($privateCall | ForEach-Object { $_.Rule }) -join ',') + ")")
Test-Assert ($outcome.Count -eq 1 -and @($plainJobs.PSObject.Properties).Count -eq 4) ("a plain -ResultHandler writes to the caller's `$outcome, not the kit's return value (caller's " + $outcome.Count + ")")
Test-Assert ($outcome.Count -eq 1 -and @($plainJobs.PSObject.Properties).Count -eq 5) ("a plain -ResultHandler writes to the caller's `$outcome, not the kit's return value (caller's " + $outcome.Count + ")")
$ScriptBlock = 'mine'
$fromRun = Invoke-PkRun { $ScriptBlock }
Remove-Variable -Name ScriptBlock
Expand Down Expand Up @@ -2256,6 +2256,10 @@ $softRun = Invoke-PkRunspaceJobs -MaxParallel 2 -JobParams (New-JobList -Jobs @(
} -PollCallback { $poll.Count++; if ($poll.Count -eq 3) { Request-PkAbort } }.GetNewClosure() -ResultHandler { param($r) $softOut.Add($r) }.GetNewClosure()
$softMessages = @($script:messages | Where-Object { $_.Level -eq 'Error' -and $_.Message -like 'Runspace error: soft drain*' }).Count
Test-Assert ($softRun.Aborted -and $softRun.CrashedCount -eq 0 -and $softOut.Count -eq 2 -and $softMessages -eq 2) ("a non-terminating error during an abort's drain is reported (messages " + $softMessages + ", results " + $softOut.Count + ")")
$softErrorsProp = $softRun.PSObject.Properties['Errors'] # read safely: strict mode throws on a missing property
$softErrorIds = @()
if ($null -ne $softErrorsProp) { $softErrorIds = @($softErrorsProp.Value | ForEach-Object { $_.Job['Id'] } | Sort-Object) }
Test-Assert (($softErrorIds -join ',') -eq '1,2') ("and lands in Errors with its job (" + ($softErrorIds -join ',') + ")")
Reset-Harness
Write-Host ""

Expand Down Expand Up @@ -3103,6 +3107,45 @@ Test-Assert ($kwLabeled -eq 'unset' -and $kwLeft -eq 0) ("a labeled break out of
Reset-Harness
Write-Host ""

Write-Host "=== AI: a worker's non-terminating errors are recorded with their job ===" -ForegroundColor Cyan

Reset-Harness
$errOut = [System.Collections.Generic.List[object]]::new()
$errRun = Invoke-PkRunspaceJobs -MaxParallel 2 -JobParams (New-JobList -Jobs @(@{ Id = 1 }, @{ Id = 2 }, @{ Id = 3 })) -WorkerScript {
param([int]$Id)
if ($Id -eq 2) { Write-Error "soft two"; Write-Error "soft two again" }
return $Id
} -ResultHandler { param($r) $errOut.Add($r) }.GetNewClosure()
$errProp = $errRun.PSObject.Properties['Errors'] # read safely: strict mode throws on a missing property
$errList = @()
if ($null -ne $errProp) { $errList = @($errProp.Value) }
$errOk = ($errList.Count -eq 2)
foreach ($e in $errList) { if ($e.Job['Id'] -ne 2 -or $e.Error -isnot [System.Management.Automation.ErrorRecord] -or ([string]$e.Error) -notlike 'soft two*') { $errOk = $false } }
Test-Assert ($errOk -and $errRun.CrashedCount -eq 0 -and $errOut.Count -eq 3) ("a worker's non-terminating errors land in Errors, each with its job and ErrorRecord (" + $errList.Count + " entries)")
$errPrinted = @($script:messages | Where-Object { $_.Level -eq 'Error' -and $_.Message -like 'Runspace error: soft two*' }).Count
Test-Assert ($errPrinted -eq 2) ("and are still printed (" + $errPrinted + ")")

# A worker that writes an error and then throws: the error it wrote is
# printed and recorded too, and the throw is a crash, not an Errors entry.
Reset-Harness
$errRun = Invoke-PkRunspaceJobs -MaxParallel 1 -JobParams (New-JobList -Jobs @(@{ Id = 7 })) -WorkerScript {
param([int]$Id)
Write-Error "soft before the crash"
throw "hard crash"
}
$errProp = $errRun.PSObject.Properties['Errors']
$errList = @()
if ($null -ne $errProp) { $errList = @($errProp.Value) }
$errPrinted = @($script:messages | Where-Object { $_.Message -like 'Runspace error: soft before the crash*' }).Count
Test-Assert ($errRun.CrashedCount -eq 1 -and $errList.Count -eq 1 -and $errList[0].Job['Id'] -eq 7 -and ([string]$errList[0].Error) -like 'soft before the crash*' -and $errPrinted -eq 1) ("a crashed worker's earlier non-terminating error is printed and recorded (" + $errList.Count + " entries, printed " + $errPrinted + ")")

# An empty job list returns the same shape.
$errEmpty = Invoke-PkRunspaceJobs -MaxParallel 1 -JobParams @() -WorkerScript { param($Id) }
$errProp = $errEmpty.PSObject.Properties['Errors']
Test-Assert ($null -ne $errProp -and @($errProp.Value).Count -eq 0) "an empty run has an empty Errors list"
Reset-Harness
Write-Host ""

Set-PkMessageHandler -Handler $null
Reset-PkAbortState

Expand Down
57 changes: 39 additions & 18 deletions ParallelKit.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -2158,6 +2158,23 @@ function Add-PkCrashedJob {
}
}

function Add-PkJobErrors {
# A finished worker's non-terminating errors: print each, as always, and
# record it with its job on the run's outcome. Shared by the main loop and
# the abort drain. Called for a worker that crashed too: its error stream
# holds only the errors from before the one that stopped it.
param(
[Parameter(Mandatory)][System.Collections.Specialized.OrderedDictionary]$PkOutcome,
[hashtable]$PkJob,
$PkErrors
)
if ($null -eq $PkErrors) { return }
foreach ($pkError in $PkErrors) {
$PkOutcome.Errors.Add([pscustomobject][ordered]@{ Job = $PkJob; Error = $pkError })
Invoke-PkMessageHandler -Message ("Runspace error: " + $pkError.ToString()) -Level Error
}
}

function Receive-PkCompletedHandles {
param(
[System.Collections.Generic.List[hashtable]]$Handles,
Expand All @@ -2174,14 +2191,15 @@ function Receive-PkCompletedHandles {
# locals, and $results.Add($r) there grew the collection this loop
# walks, so it never ended. Same in Invoke-PkRunspaceJobs.
$pkWorkerOutput = $null
$pkCrash = $null
try {
$pkWorkerOutput = $h.PS.EndInvoke($h.Handle)
# Same report as Invoke-PkRunspaceJobs' main loop.
if ($h.PS.HadErrors) {
foreach ($e in $h.PS.Streams.Error) { Invoke-PkMessageHandler -Message ("Runspace error: " + $e.ToString()) -Level Error }
try { $pkWorkerOutput = $h.PS.EndInvoke($h.Handle) } catch { $pkCrash = $_ }
# Same report as Invoke-PkRunspaceJobs' main loop: the errors
# it wrote, then the crash, in the order they happened.
Add-PkJobErrors -PkOutcome $Outcome -PkJob $h['Job'] -PkErrors $h.PS.Streams.Error
if ($null -ne $pkCrash) {
Add-PkCrashedJob -PkOutcome $Outcome -PkJob $h['Job'] -PkError $pkCrash -PkHandler $JobCrashedHandler -PkWhen " during abort drain" -PkCallbackWarned $CallbackWarned
}
} catch {
Add-PkCrashedJob -PkOutcome $Outcome -PkJob $h['Job'] -PkError $_ -PkHandler $JobCrashedHandler -PkWhen " during abort drain" -PkCallbackWarned $CallbackWarned
} finally {
$h.PS.Dispose()
}
Expand Down Expand Up @@ -2265,7 +2283,8 @@ function Invoke-PkRunspaceJobs {
# Each job starts in your current location, in a fresh scope: a folder change
# or a variable from an earlier job doesn't carry over.
# Only an error that stops the worker (throw, -ErrorAction Stop) counts as a
# crash; a non-terminating one is printed and the job's output still counts.
# crash; a non-terminating one is printed, recorded in Errors, and the job's
# output still counts.
# The worker code is checked against the worker rules (see the README)
# before anything starts, and each job's values before that job starts;
# code or values that break them are refused.
Expand Down Expand Up @@ -2303,8 +2322,9 @@ function Invoke-PkRunspaceJobs {
# Check the worker code and job values before starting. On unless you pass
# -CheckWorkerSafety:$false, whatever Get-Help says the default is.
# .OUTPUTS
# An object with ForceStoppedCount, CrashedCount, Aborted and Crashed (one
# @{ Job; Error } entry per worker that threw).
# An object with ForceStoppedCount, CrashedCount, Aborted, Crashed (one
# @{ Job; Error } entry per worker that threw) and Errors (one @{ Job; Error }
# entry per non-terminating error a worker wrote).
# .EXAMPLE
# Invoke-PkRunspaceJobs -MaxParallel 4 -JobParams @(@{ Id = 1 }, @{ Id = 2 }) -WorkerScript { param($Id) $Id * 2 } -ResultHandler { param($r) Write-Host $r }
param(
Expand Down Expand Up @@ -2356,7 +2376,7 @@ function Invoke-PkRunspaceJobs {
$JobParams = $normalizedJobs
}

$outcome = [ordered]@{ ForceStoppedCount = 0; CrashedCount = 0; Aborted = $false; Crashed = [System.Collections.Generic.List[object]]::new() }
$outcome = [ordered]@{ ForceStoppedCount = 0; CrashedCount = 0; Aborted = $false; Crashed = [System.Collections.Generic.List[object]]::new(); Errors = [System.Collections.Generic.List[object]]::new() }
if ($null -ne $JobParams -and $JobParams.Count -eq 0) { return [pscustomobject]$outcome }

if ($checkSafety) {
Expand Down Expand Up @@ -2520,16 +2540,17 @@ function Invoke-PkRunspaceJobs {
# $results.Add($r) there grew the collection this loop
# walks, so it never ended. Same in Receive-PkCompletedHandles.
$pkWorkerOutput = $null
$pkCrash = $null
try {
$pkWorkerOutput = $h.PS.EndInvoke($h.Handle)
# Same report as Receive-PkCompletedHandles.
if ($h.PS.HadErrors) {
foreach ($e in $h.PS.Streams.Error) { Invoke-PkMessageHandler -Message ("Runspace error: " + $e.ToString()) -Level Error }
try { $pkWorkerOutput = $h.PS.EndInvoke($h.Handle) } catch { $pkCrash = $_ }
# Same report as Receive-PkCompletedHandles: the errors
# it wrote, then the crash, in the order they happened.
Add-PkJobErrors -PkOutcome $outcome -PkJob $h['Job'] -PkErrors $h.PS.Streams.Error
if ($null -ne $pkCrash) {
# The worker itself threw - there is no result, so
# -ResultHandler is never called for this job.
Add-PkCrashedJob -PkOutcome $outcome -PkJob $h['Job'] -PkError $pkCrash -PkHandler $JobCrashedHandler -PkCallbackWarned $pkCallbackWarned
}
} catch {
# The worker itself threw - there is no result, so
# -ResultHandler is never called for this job.
Add-PkCrashedJob -PkOutcome $outcome -PkJob $h['Job'] -PkError $_ -PkHandler $JobCrashedHandler -PkCallbackWarned $pkCallbackWarned
} finally {
$h.PS.Dispose()
}
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,7 @@ Each worker runs in its own runspace: a separate PowerShell session inside the s
- `-NextJobProvider { ... }` can replace `-JobParams` to produce jobs lazily: it's called on the main thread for the next job hashtable, and returns `$null` when there are no more.
- `-PollCallback { ... }` runs on the main thread on every loop pass, for progress display and the like. That's at least every 0.1 s, and can be many times more often when jobs finish quickly, so keep it cheap.
- `-JobCrashedHandler { param($err, $job) ... }` is told when a worker throws, including while an abort waits for running workers, with the job hashtable that crashed. Leave `$job` out of `param()` if you don't need it. `$err.Exception.InnerException` is the worker's own error. That job's result handler isn't called, and anything the worker output before throwing is lost. If the handler itself throws, that's reported as a message and the run carries on.
- Only an error that stops the worker counts as a crash: `throw`, a cmdlet with `-ErrorAction Stop`, or any error once the worker sets `$ErrorActionPreference = 'Stop'`. A non-terminating error (a locked file in `Get-FileHash`, a `Write-Error`), or an exception from a .NET method such as `[System.IO.File]::ReadAllText(...)`, only ends that one statement. It's printed as `Runspace error: ...`, and whatever the worker returned still goes to `-ResultHandler` as if it had worked. Workers start with PowerShell's default preferences and no strict mode, whatever your script uses. To catch every failure and know which input it came from, have the worker return its own error object:
- Only an error that stops the worker counts as a crash: `throw`, a cmdlet with `-ErrorAction Stop`, or any error once the worker sets `$ErrorActionPreference = 'Stop'`. A non-terminating error (a locked file in `Get-FileHash`, a `Write-Error`), or an exception from a .NET method such as `[System.IO.File]::ReadAllText(...)`, only ends that one statement. It's printed as `Runspace error: ...` and recorded in the result's `Errors` list with its job, and whatever the worker returned still goes to `-ResultHandler` as if it had worked. Workers start with PowerShell's default preferences and no strict mode, whatever your script uses. To catch every failure and know which input it came from, have the worker return its own error object:

```powershell
WorkerScript = {
Expand All @@ -198,7 +198,7 @@ Each worker runs in its own runspace: a separate PowerShell session inside the s
- Don't call `exit` in a worker. It ends that job quietly (not as a crash) and sets your whole script's exit code.
- `-MaxParallel` has no default; you choose it. `-DrainTimeoutSeconds` (how long Ctrl+C waits for running workers) defaults to 60. The process engines' names, `-MaxConcurrent` and `-AbortTimeoutSeconds`, work here too.
- If `-ResultHandler`, `-PollCallback` or `-NextJobProvider` throws, the run stops: workers still going are told to stop and the exception comes out of the call.
- Returns an object with `ForceStoppedCount`, `CrashedCount`, `Aborted` and `Crashed`, which lists the `Job` and `Error` of each worker that threw.
- Returns an object with `ForceStoppedCount`, `CrashedCount`, `Aborted`, `Crashed`, which lists the `Job` and `Error` of each worker that threw, and `Errors`, which lists the `Job` and `Error` of each non-terminating error a worker wrote (including any a worker wrote before it threw). A worker that was force-stopped is in neither list. Every entry is kept until the call returns, so a worker that can write thousands of errors (walking a tree full of folders it can't read, say) should handle them itself, e.g. with `-ErrorAction SilentlyContinue -ErrorVariable`.

## The two rules for worker code

Expand Down
Loading