From 6dfe68db679ef1fa7a5862ce69cd44274734dec2 Mon Sep 17 00:00:00 2001 From: Hal <22532613+HalRiveria@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:07:04 -0500 Subject: [PATCH 1/2] Record each worker's non-terminating errors with its job An error a worker didn't catch was only printed as "Runspace error: ...", with no way to tell which job it came from, and a worker that wrote an error and then threw never had that error printed at all. Invoke-PkRunspaceJobs' result gains an Errors list, one @{ Job; Error } entry per non-terminating error, like Crashed. Errors are still printed. Both the main loop and the abort drain go through one new helper, which also runs for a worker that crashed, so its earlier errors are printed and recorded before the crash is reported. Co-Authored-By: Claude Opus 5.5 --- ParallelKit.Harness.ps1 | 47 +++++++++++++++++++++++++++++++-- ParallelKit.ps1 | 57 ++++++++++++++++++++++++++++------------- README.md | 4 +-- 3 files changed, 86 insertions(+), 22 deletions(-) diff --git a/ParallelKit.Harness.ps1 b/ParallelKit.Harness.ps1 index 9c2c7a2..1832331 100644 --- a/ParallelKit.Harness.ps1 +++ b/ParallelKit.Harness.ps1 @@ -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) + ")") @@ -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 @@ -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 "" @@ -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 diff --git a/ParallelKit.ps1 b/ParallelKit.ps1 index 7b6fb52..7735628 100644 --- a/ParallelKit.ps1 +++ b/ParallelKit.ps1 @@ -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, @@ -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() } @@ -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. @@ -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( @@ -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) { @@ -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() } diff --git a/README.md b/README.md index 3e4baeb..ca1cfda 100644 --- a/README.md +++ b/README.md @@ -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 = { @@ -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. ## The two rules for worker code From 087801734903a89a3a28b47d14e8ea71693fe113 Mon Sep 17 00:00:00 2001 From: Hal <22532613+HalRiveria@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:07:45 -0500 Subject: [PATCH 2/2] Say in the README that Errors keeps every entry until the call returns Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ca1cfda..33b2fa1 100644 --- a/README.md +++ b/README.md @@ -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`, `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. +- 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