From 3c8eea5fbf55ef7238ec1ef3885a3d0bb6beb1fe Mon Sep 17 00:00:00 2001 From: Hal <22532613+HalRiveria@users.noreply.github.com> Date: Tue, 1 Dec 2026 16:12:28 -0500 Subject: [PATCH 1/5] Invoke-PkProcessBatch no longer needs the kit's functions to be global Two of the batch's own closures called Complete-PkProcess and Write-PkMessage by name. A .GetNewClosure() block only sees global functions, so a batch failed with "'Complete-PkProcess' is not recognized" when the kit was loaded for one module only. They're captured up front now, like the private helpers. Co-Authored-By: Claude Opus 5.5 --- ParallelKit.Harness.ps1 | 37 ++++++++++++++++++++++++++++++++++--- ParallelKit.ps1 | 13 ++++++++----- 2 files changed, 42 insertions(+), 8 deletions(-) diff --git a/ParallelKit.Harness.ps1 b/ParallelKit.Harness.ps1 index c9f132e..b9eea4e 100644 --- a/ParallelKit.Harness.ps1 +++ b/ParallelKit.Harness.ps1 @@ -1032,8 +1032,9 @@ Test-Assert ($probeThreads -eq $probeWas) ("and leaves the thread pool's minimum # A script run the way a prompt runs it (& script, or .\script.ps1) holds # the kit's functions in its own scope, where a .GetNewClosure() block can't -# see them. The kit's public functions are imported globally, so the batch (whose callbacks are -# closures) and a caller's closure that calls a kit function both work. +# see them. The kit's public functions are imported globally, so a caller's +# closure that calls one works; the batch's own closures don't rely on that +# (section Z). # Needs a fresh process, started with -Command rather than -File. $promptScript = Join-Path $env:TEMP ("pk-prompt-" + [guid]::NewGuid().ToString("N") + ".ps1") [System.IO.File]::WriteAllText($promptScript, @" @@ -2308,6 +2309,36 @@ Remove-Item -LiteralPath $modDir -Recurse -Force -ErrorAction SilentlyContinue $modOut = ([string]$modRun.Stdout + [string]$modRun.Stderr).Trim() -replace '\s+', ' ' Test-Assert ($modOut -match 'module private=105') ("a module's private function can be shared with workers (" + $modOut + ")") Test-Assert ($modOut -match 'kit modules=1') "loading the kit a second time leaves one ParallelKit module, not two" + +# The batch's own callbacks are closures, which only see global functions. The +# batch must not count on its public functions being global: here the kit is +# loaded inside another module, for that module only. One command runs and one +# can't start, so both of the kit's own closures that call a public function do. +$scopeText = [System.IO.File]::ReadAllText($kitPath) +$scopeClose = '} | Import-Module -Global' +Test-Assert ([regex]::Matches($scopeText, [regex]::Escape($scopeClose)).Count -eq 1) "the kit's last line is still the import this test rewrites" +$scopeDir = Join-Path $env:TEMP ("pk-harness-scope-" + $PID) +$null = New-Item -ItemType Directory -Force -Path $scopeDir +$scopeModule = Join-Path $scopeDir 'PkHarnessScope.psm1' +[System.IO.File]::WriteAllText($scopeModule, $scopeText.Replace($scopeClose, '} | Import-Module') + @' + +function Invoke-ScopeBatch { + $codes = [System.Collections.Generic.List[object]]::new() + $batch = Invoke-PkProcessBatch -Commands @( + @{ FilePath = $env:ComSpec; Arguments = '/c exit 7' } + @{ FilePath = 'C:\pk-harness-no-such-program.exe'; Arguments = '' } + ) -OnComplete { param($c, $r) $codes.Add($r.ExitCode) }.GetNewClosure() + 'finished=' + ($codes -join ',') + ' results=' + $batch.Results.Count + ' starterrors=' + @($batch.Results | Where-Object { $_.StartError }).Count +} +Export-ModuleMember -Function Invoke-ScopeBatch +'@) +$scopeScript = Join-Path $scopeDir 'use.ps1' +[System.IO.File]::WriteAllText($scopeScript, "Import-Module '" + $scopeModule + "'`r`n'kit global=' + [bool](Get-ChildItem Function: | Where-Object { `$_.Name -eq 'Complete-PkProcess' })`r`ntry { Invoke-ScopeBatch } catch { 'error: ' + `$_ }`r`n") +$scopeRun = Invoke-PkProcessWithTimeout -FilePath $selfExe -Arguments (ConvertTo-PkArgumentString @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command', ("& '" + $scopeScript + "'"))) -TimeoutMs 60000 +Remove-Item -LiteralPath $scopeDir -Recurse -Force -ErrorAction SilentlyContinue +$scopeOut = ([string]$scopeRun.Stdout + [string]$scopeRun.Stderr).Trim() -replace '\s+', ' ' +Test-Assert ($scopeOut -match 'kit global=False' -and $scopeOut -match 'finished=7 results=2 starterrors=1') ("a batch runs when the kit's functions aren't global (" + $scopeOut + ")") +Test-Assert ($scopeOut -match "a command couldn't start") "and reports the command that couldn't start" Write-Host "" } @@ -3810,7 +3841,7 @@ function Get-HarnessUnguardedCallbacks { # this list. Invoke-PkRun's `& $ScriptBlock` is the run itself, not called # from a loop. Returns @{ Calls; Problems }. param([string]$Source) - $internal = @('$pkNewBatchResult', '$pkGetStartFailureCause', '$pkGetJobTimeLimit', '$pkGetJobMaxOutputChars', '$pkGetJobSwitch', '$pkStopExitedJobTree', '$pkReportStartFailure', '$pkStartProcessCore', '$pkWriteCallbackLoopWarning') + $internal = @('$pkNewBatchResult', '$pkGetStartFailureCause', '$pkGetJobTimeLimit', '$pkGetJobMaxOutputChars', '$pkGetJobSwitch', '$pkStopExitedJobTree', '$pkReportStartFailure', '$pkStartProcessCore', '$pkWriteCallbackLoopWarning', '$pkWriteMessage', '$pkCompleteProcess') $problems = [System.Collections.Generic.List[string]]::new() $tokens = $null; $errors = $null $ast = [System.Management.Automation.Language.Parser]::ParseInput($Source, [ref]$tokens, [ref]$errors) diff --git a/ParallelKit.ps1 b/ParallelKit.ps1 index 3c5f4d7..d3a1d09 100644 --- a/ParallelKit.ps1 +++ b/ParallelKit.ps1 @@ -3224,8 +3224,9 @@ function Invoke-PkProcessBatch { $pkResults = [System.Collections.Generic.List[object]]::new() $pkState = @{ Given = $false } - # The closures below can't see the module's private functions (a - # .GetNewClosure() block only sees global ones), so take these along. + # The closures below can't see the module's functions (a .GetNewClosure() + # block only sees global ones), so take these along: the public ones too, + # which aren't global when the kit is loaded for one module only. $pkNewBatchResult = ${function:New-PkBatchResult} $pkStartProcessCore = ${function:Start-PkProcessCore} $pkGetJobTimeLimit = ${function:Get-PkJobTimeLimit} @@ -3233,6 +3234,8 @@ function Invoke-PkProcessBatch { $pkGetJobSwitch = ${function:Get-PkJobSwitch} $pkGetStartFailureCause = ${function:Get-PkStartFailureCause} $pkWriteCallbackLoopWarning = ${function:Write-PkCallbackLoopWarning} + $pkWriteMessage = ${function:Write-PkMessage} + $pkCompleteProcess = ${function:Complete-PkProcess} # Invoke-PkCallback's -PkContext: callbacks that used continue/break are # warned about once each, under this prefix. $pkCallbackContext = @{ Prefix = 'Invoke-PkProcessBatch: '; Warned = @{} } @@ -3252,7 +3255,7 @@ function Invoke-PkProcessBatch { return } $pkStartFailures[$pkFailureKey] = @{ FilePath = $pkFilePath; Cause = $pkCause; More = 0 } - Write-PkMessage ("Invoke-PkProcessBatch: a command couldn't start: " + $pkError) -Level Error + & $pkWriteMessage ("Invoke-PkProcessBatch: a command couldn't start: " + $pkError) -Level Error }.GetNewClosure() $pkGroupProvider = { @@ -3302,7 +3305,7 @@ function Invoke-PkProcessBatch { $pkJobFinalize = { param($pkJob, $pkPendingQueue) - $pkR = & $pkNewBatchResult -Command $pkJob['Command'] -Completed (Complete-PkProcess -Job $pkJob) -TimedOut ([bool]$pkJob['TimedOut']) + $pkR = & $pkNewBatchResult -Command $pkJob['Command'] -Completed (& $pkCompleteProcess -Job $pkJob) -TimedOut ([bool]$pkJob['TimedOut']) $pkResults.Add($pkR) if ($null -ne $pkOnComplete) { # Invoke-PkCallback, inlined: this runs per command. @@ -4350,7 +4353,7 @@ function Test-PkWorkerSafetyCore { # ============================================================================== # Imported globally: a .GetNewClosure() block only sees global functions, -# so this lets the batch's callbacks, and yours, call them. The same list is +# so this lets a callback of yours call them. The same list is # $publicFunctions in ParallelKit.Harness.ps1; keep the two in step. Export-ModuleMember -Function @( 'Set-PkMessageHandler', 'Write-PkMessage', 'Initialize-ParallelKit', 'Register-PkCancellationSource', From 1ec5c06b7ce913df40c6ff05f7f9d6a3540068c1 Mon Sep 17 00:00:00 2001 From: Hal <22532613+HalRiveria@users.noreply.github.com> Date: Tue, 1 Dec 2026 16:24:37 -0500 Subject: [PATCH 2/5] Set-PkMessageHandler throws in worker code A worker given the function (-SharedFunctionNames takes it) could set a handler made in its own runspace, which the main thread then ran for every message. Running another runspace's scriptblock can hang or crash PowerShell. Co-Authored-By: Claude Opus 5.5 --- ParallelKit.Harness.ps1 | 12 ++++++++++++ ParallelKit.ps1 | 6 ++++++ README.md | 2 +- 3 files changed, 19 insertions(+), 1 deletion(-) diff --git a/ParallelKit.Harness.ps1 b/ParallelKit.Harness.ps1 index b9eea4e..86def59 100644 --- a/ParallelKit.Harness.ps1 +++ b/ParallelKit.Harness.ps1 @@ -801,6 +801,18 @@ Set-PkMessageHandler -Handler { param($Message, $Level) "noise"; 42 } $leaked = Write-PkMessage "hello" Test-Assert ($null -eq $leaked) "a message handler's output doesn't leak out of Write-PkMessage" Set-PkMessageHandler -Handler { param($Message, $Level) $messageSink.Add(@{ Message = $Message; Level = $Level }) }.GetNewClosure() + +# Set in a worker, the handler would be the worker's scriptblock, run by the main thread. +$handlerCrash = [System.Collections.Generic.List[string]]::new() +$handlerBefore = [PkState]::MessageHandler +$handlerRun = Invoke-PkRunspaceJobs -MaxParallel 1 -JobParams (New-JobList -Jobs @(@{ Reset = $false }, @{ Reset = $true })) -SharedFunctionNames Set-PkMessageHandler -JobCrashedHandler { param($e) $handlerCrash.Add([string]$e.Exception.InnerException.Message) }.GetNewClosure() -WorkerScript { + param($Reset) + if ($Reset) { Set-PkMessageHandler $null } else { Set-PkMessageHandler { param($Message, $Level) } } +} +$handlerKept = [object]::ReferenceEquals($handlerBefore, [PkState]::MessageHandler) +[PkState]::MessageHandler = $handlerBefore +Test-Assert ($handlerRun.CrashedCount -eq 2 -and @($handlerCrash | Where-Object { $_ -like '*Set-PkMessageHandler*main thread*' }).Count -eq 2) ("Set-PkMessageHandler throws in a worker, for a handler or `$null (" + ($handlerCrash -join '; ') + ")") +Test-Assert $handlerKept "and leaves the handler as it was" Write-Host "" } diff --git a/ParallelKit.ps1 b/ParallelKit.ps1 index d3a1d09..d618f85 100644 --- a/ParallelKit.ps1 +++ b/ParallelKit.ps1 @@ -1098,12 +1098,18 @@ function Set-PkMessageHandler { # always runs on the main thread, including for messages from worker code. If it # throws, the message is shown on the console instead and the run carries on. # Leave it early with return: continue and break end it too, but warn once. + # Throws in worker code; call it on the main thread. # .PARAMETER Handler # { param($Message, $Level) ... }, or $null to go back to the default (console). # .EXAMPLE # Set-PkMessageHandler { param($Message, $Level) Add-Content run.log "$Level $Message" } [CmdletBinding()] param([scriptblock]$Handler) + # A worker's scriptblock belongs to its runspace: the main thread running + # it can hang or crash. + if ($null -ne $global:PkWorkerQueue) { + throw "Set-PkMessageHandler: this is worker code, and the handler can only be set on the main thread, which runs it. Set it before starting the workers; Write-PkMessage in a worker already goes to it." + } [PkState]::MessageHandler = $Handler } diff --git a/README.md b/README.md index e7d2f61..23d0df5 100644 --- a/README.md +++ b/README.md @@ -578,7 +578,7 @@ Workers can't safely write to the console. `Write-PkMessage "text" -Level Info|W Set-PkMessageHandler { param($Message, $Level) Write-MyLog $Message $Level } ``` -The handler always runs on the main thread, so it can use anything. The kit's own notices (abort announcements, crashed workers, force-stops) go through the same handler. If your handler throws, the message is shown on the console instead and the run carries on. `Set-PkMessageHandler $null` restores the default. +The handler always runs on the main thread, so it can use anything. The kit's own notices (abort announcements, crashed workers, force-stops) go through the same handler. If your handler throws, the message is shown on the console instead and the run carries on. `Set-PkMessageHandler $null` restores the default. Call it on the main thread: in worker code it throws. ## Abort From 4a2e332ad35e8d3ad8f303b811ae281a48a759b3 Mon Sep 17 00:00:00 2001 From: Hal <22532613+HalRiveria@users.noreply.github.com> Date: Tue, 1 Dec 2026 16:37:08 -0500 Subject: [PATCH 3/5] Invoke-PkProcessWithTimeout starts nothing during an abort or cancel It only looked for an abort after its first 200 ms wait, so a program that finished sooner ran to the end and returned normally, and a slower one ran for about 200 ms before it was killed. It now throws before starting the program, unless -IgnoreAbort is given. Co-Authored-By: Claude Opus 5.5 --- ParallelKit.Harness.ps1 | 28 ++++++++++++++++++++++++++++ ParallelKit.ps1 | 10 +++++++--- README.md | 2 +- 3 files changed, 36 insertions(+), 4 deletions(-) diff --git a/ParallelKit.Harness.ps1 b/ParallelKit.Harness.ps1 index 86def59..f0ce80d 100644 --- a/ParallelKit.Harness.ps1 +++ b/ParallelKit.Harness.ps1 @@ -1477,6 +1477,34 @@ $cleanup = $null try { $cleanup = Invoke-PkProcessWithTimeout -FilePath $pingExe -Arguments '-n 3 127.0.0.1' -IgnoreAbort } catch { } Test-Assert ($null -ne $cleanup -and $cleanup.ExitCode -eq 0) "-IgnoreAbort lets a cleanup program run to the end during an abort" +# A program quick enough to finish before the abort was looked at used to run. +# Each writes a file, so a run leaves a trace. +$quickDir = Join-Path $env:TEMP ("pk-harness-quick-" + $PID) +$null = New-Item -ItemType Directory -Force -Path $quickDir +$quickError = $null +try { $null = Invoke-PkProcessWithTimeout -FilePath $cmdExe -Arguments ('/c echo ran> "' + $quickDir + '\abort.txt"') } catch { $quickError = [string]$_ } +Test-Assert ($quickError -like "*wasn't started because the run is being aborted*" -and -not (Test-Path -LiteralPath ($quickDir + '\abort.txt'))) ("during an abort, a quick program isn't started (" + $quickError + ")") +$quick = $null +try { $quick = Invoke-PkProcessWithTimeout -FilePath $cmdExe -Arguments ('/c echo ran> "' + $quickDir + '\ignore.txt"') -IgnoreAbort } catch { } +Test-Assert ($null -ne $quick -and (Test-Path -LiteralPath ($quickDir + '\ignore.txt'))) "-IgnoreAbort still runs it" +Reset-Harness +# The same in a worker, when its run is canceled rather than aborted. +$quickCts = [System.Threading.CancellationTokenSource]::new() +$quickCrash = [System.Collections.Generic.List[string]]::new() +$quickPolls = @{ Count = 0 } +$null = Invoke-PkRunspaceJobs -MaxParallel 1 -Cts $quickCts -DrainTimeoutSeconds 20 -JobParams (New-JobList -Jobs @(@{ Cmd = $cmdExe; Dir = $quickDir })) ` + -PollCallback { $quickPolls.Count++; if ($quickPolls.Count -eq 3) { $quickCts.Cancel() } }.GetNewClosure() ` + -JobCrashedHandler { param($e) $quickCrash.Add([string]$e.Exception.InnerException.Message) }.GetNewClosure() -WorkerScript { + param($Cmd, $Dir) + $waited = [System.Diagnostics.Stopwatch]::StartNew() + while (-not (Test-PkCancelRequested) -and $waited.Elapsed.TotalSeconds -lt 15) { [System.Threading.Thread]::Sleep(20) } + $null = Invoke-PkProcessWithTimeout -FilePath $Cmd -Arguments ('/c echo ran> "' + $Dir + '\ignored.txt"') -IgnoreAbort + $null = Invoke-PkProcessWithTimeout -FilePath $Cmd -Arguments ('/c echo ran> "' + $Dir + '\cancel.txt"') + } +Test-Assert ($quickCrash.Count -eq 1 -and $quickCrash[0] -like "*wasn't started because the run is being aborted*" -and -not (Test-Path -LiteralPath ($quickDir + '\cancel.txt')) -and (Test-Path -LiteralPath ($quickDir + '\ignored.txt'))) ("in a worker whose run is canceled, a quick program isn't started, except with -IgnoreAbort (" + ($quickCrash -join '; ') + ")") +$quickCts.Dispose() +Remove-Item -LiteralPath $quickDir -Recurse -Force -ErrorAction SilentlyContinue + # A job's own Group field is left alone. Reset-Harness $feed = @{ Given = $false } diff --git a/ParallelKit.ps1 b/ParallelKit.ps1 index d618f85..b1af98b 100644 --- a/ParallelKit.ps1 +++ b/ParallelKit.ps1 @@ -2244,7 +2244,8 @@ function Invoke-PkProcessWithTimeout { # .DESCRIPTION # Throws if the program had to be killed: because it ran past -TimeoutMs, or # because the run was aborted or canceled while it was going. Anything the - # program started is killed with it. + # program started is killed with it. During an abort or cancel it throws + # without starting the program. # .PARAMETER FilePath # The program to run. # .PARAMETER Arguments @@ -2270,8 +2271,8 @@ function Invoke-PkProcessWithTimeout { # nothing it left behind holds its output open. Only for a program Windows # gave a Job Object of its own, the normal case. # .PARAMETER IgnoreAbort - # Keep going during an abort, for a cleanup or restore step that has to run - # because of it. + # Start and keep going during an abort, for a cleanup or restore step that has + # to run because of it. # .OUTPUTS # Complete-PkProcess's object: ExitCode, Stdout, Stderr, StreamTimedOut, # StreamError, Duration (how long the program ran, from its start to its @@ -2298,6 +2299,9 @@ function Invoke-PkProcessWithTimeout { # Start-PkProcess, Invoke-PkProcessBatch and Invoke-PkProcessDispatch make the # same check: keep the four in step. if ($MaxOutputChars -lt 0) { throw ("Invoke-PkProcessWithTimeout: -MaxOutputChars must be 0 (no cap) or more (got " + $MaxOutputChars + "). It's how many characters of each output stream to keep.") } + # Here as well as in the loop, which only looks after its first wait: a + # quick program would have run to the end by then. + if (-not $IgnoreAbort -and ((Test-PkAbortSignal) -or (Test-PkCancelRequested))) { throw ("'" + $FilePath + "' wasn't started because the run is being aborted") } $job = Start-PkProcessCore -FilePath $FilePath -Arguments $Arguments -WorkingDirectory $WorkingDirectory -OutputEncoding $OutputEncoding -MaxOutputChars $MaxOutputChars -InheritStdin:$InheritStdin -CallerState $PSCmdlet.SessionState $job['KillTree'] = $KillTreeOnExit.IsPresent try { diff --git a/README.md b/README.md index 23d0df5..70dd329 100644 --- a/README.md +++ b/README.md @@ -561,7 +561,7 @@ For one program at a time, outside the engines. All of these are safe in worker | Function | Use | |---|---| -| `Invoke-PkProcessWithTimeout -FilePath -Arguments -TimeoutMs` | Run one program and wait, with a hard time limit (default 60s). Returns the [process result](#process-results) fields marked "all". If it overruns, or the run is aborted, the program is killed and this **throws**; add `-IgnoreAbort` for a cleanup step that must finish anyway. | +| `Invoke-PkProcessWithTimeout -FilePath -Arguments -TimeoutMs` | Run one program and wait, with a hard time limit (default 60s). Returns the [process result](#process-results) fields marked "all". If it overruns, or the run is aborted, the program is killed and this **throws**; called while an abort or cancel is already in force, it throws without starting the program. Add `-IgnoreAbort` for a cleanup step that must run anyway. | | `ConvertTo-PkArgumentString @(args)` | Join a list of arguments into one correctly quoted command line. `-Arguments` / `Arguments` also take the list directly, and then also quote it for `cmd.exe` when the program is a `.bat` or `.cmd`. | | `Start-PkProcess -FilePath -Arguments` | Start one hidden, with output captured in the background. Returns `@{ Proc; StdoutTask; StderrTask; Stopwatch }`; throws if it can't start. | | `Wait-PkProcess -Process -TimeoutMs` | Wait for exit with a timeout that can't overrun. Returns `$true` if it exited. | From fde58ffff2c1c38b7ec59b5476c44f4cdf48caa3 Mon Sep 17 00:00:00 2001 From: Hal <22532613+HalRiveria@users.noreply.github.com> Date: Tue, 1 Dec 2026 16:49:18 -0500 Subject: [PATCH 4/5] Worker-safety check: see a scriptblock through parentheses, casts and GetNewClosure DelegateCast missed a scriptblock passed to .NET as ({ 1 }), { 1 }.GetNewClosure(), [scriptblock]{ 1 } and the like, in the call or through a variable. Co-Authored-By: Claude Opus 5.5 --- ParallelKit.Harness.ps1 | 21 +++++++++++++++++++++ ParallelKit.ps1 | 28 ++++++++++++++++++++-------- README.md | 2 +- 3 files changed, 42 insertions(+), 9 deletions(-) diff --git a/ParallelKit.Harness.ps1 b/ParallelKit.Harness.ps1 index f0ce80d..34deb12 100644 --- a/ParallelKit.Harness.ps1 +++ b/ParallelKit.Harness.ps1 @@ -980,6 +980,27 @@ $f = Test-PkWorkerSafety -WorkerScript { param($Id) $h = { 1 }; $m = [System.Col Test-Assert ($f.Count -eq 0) ("storing a scriptblock in a collection (.Add/.Enqueue) is not flagged (got " + $f.Count + ")") $f = Test-PkWorkerSafety -WorkerScript { param($Id) $h = { 1 }; $d = [System.Collections.Concurrent.ConcurrentDictionary[string,object]]::new(); $null = $d.GetOrAdd('a', $h) } Test-Assert ($f.Count -eq 1 -and $f[0].Rule -eq 'DelegateCast') "a scriptblock variable passed as a GetOrAdd factory is still flagged" +# Parentheses, a [scriptblock] cast or .GetNewClosure() around the scriptblock +# don't hide it, in the call or where its variable was assigned. +$wrapMissed = [System.Collections.Generic.List[string]]::new() +$wrapped = @('({ 1 })', '(({ 1 }))', '{ 1 }.GetNewClosure()', '({ 1 }).GetNewClosure()', '({ 1 }.GetNewClosure())', '[scriptblock]{ 1 }', '([scriptblock]({ 1 })).GetNewClosure()', '[System.Management.Automation.ScriptBlock]{ 1 }') +foreach ($w in $wrapped) { + $f = Test-PkWorkerSafety -WorkerScript ([scriptblock]::Create('param($Id) $null = [System.Threading.Tasks.Task]::Run(' + $w + ')')) + if ($f.Count -ne 1 -or $f[0].Rule -ne 'DelegateCast' -or $f[0].Text -notlike '*passes a scriptblock to .Run()*') { $wrapMissed.Add('passed ' + $w) } + $f = Test-PkWorkerSafety -WorkerScript ([scriptblock]::Create('param($Id) $sb = ' + $w + '; $null = [System.Threading.Tasks.Task]::Run($sb)')) + if ($f.Count -ne 1 -or $f[0].Rule -ne 'DelegateCast' -or $f[0].Text -notlike '*$sb*') { $wrapMissed.Add('assigned ' + $w) } +} +foreach ($w in @('($sb)', '$sb.GetNewClosure()', '[scriptblock]$sb', '($sb.GetNewClosure())')) { + $f = Test-PkWorkerSafety -WorkerScript ([scriptblock]::Create('param($Id) $sb = { 1 }; $null = [System.Threading.Tasks.Task]::Run(' + $w + ')')) + if ($f.Count -ne 1 -or $f[0].Rule -ne 'DelegateCast' -or $f[0].Text -notlike '*$sb*') { $wrapMissed.Add('passed ' + $w) } +} +Test-Assert ($wrapMissed.Count -eq 0) ("a wrapped scriptblock passed to .NET is flagged, written in the call or through a variable (missed: " + ($wrapMissed -join ' | ') + ")") +$wrapWrong = [System.Collections.Generic.List[string]]::new() +foreach ($w in @('$n = (1); $null = [Math]::Abs(($n))', '$s = [string]({ 1 }.ToString()); $null = [Math]::Abs($s.Length)', '$sb = ({ 1 }); $null = @(1).ForEach(($sb))', '$sb = ({ 1 }); $l = [System.Collections.Generic.List[object]]::new(); $l.Add(($sb))', '$r = (& { 1 }); $null = [Math]::Abs($r)', '$sb = { 1 }; $n = $sb.ToString(); $null = [Math]::Abs($n.Length)', '$null = [System.Threading.Tasks.Task]::Run(({ 1 })) # pk:ignore')) { + $f = Test-PkWorkerSafety -WorkerScript ([scriptblock]::Create("param(`$Id) " + $w + "`n")) + if ($f.Count -ne 0) { $wrapWrong.Add($w + ' -> ' + $f[0].Text) } +} +Test-Assert ($wrapWrong.Count -eq 0) ("and other parenthesized or cast values aren't (" + ($wrapWrong -join ' | ') + ")") # MissingFunction through an alias, and for a module a worker can't load. Set-Alias -Name hdbl -Value Get-HarnessDouble -Scope Global diff --git a/ParallelKit.ps1 b/ParallelKit.ps1 index b1af98b..4357ef3 100644 --- a/ParallelKit.ps1 +++ b/ParallelKit.ps1 @@ -4168,6 +4168,20 @@ function Get-PkUndeclaredVariables { } } +function Get-PkUnwrappedExpression { + # What's left of an expression without the parentheses, [scriptblock] casts + # and .GetNewClosure() calls around it, for finding a scriptblock inside. + param($Ast) + while ($true) { + if ($Ast -is [System.Management.Automation.Language.ParenExpressionAst]) { $Ast = $Ast.Pipeline; continue } + if ($Ast -is [System.Management.Automation.Language.PipelineAst] -and $Ast.PipelineElements.Count -eq 1) { $Ast = $Ast.PipelineElements[0]; continue } + if ($Ast -is [System.Management.Automation.Language.CommandExpressionAst]) { $Ast = $Ast.Expression; continue } + if ($Ast -is [System.Management.Automation.Language.ConvertExpressionAst] -and $Ast.Type.TypeName.Name -match '^(System\.Management\.Automation\.)?scriptblock$') { $Ast = $Ast.Child; continue } + if ($Ast -is [System.Management.Automation.Language.InvokeMemberExpressionAst] -and [string]$Ast.Member.Extent.Text -eq 'GetNewClosure') { $Ast = $Ast.Expression; continue } + return $Ast + } +} + function Test-PkWorkerSafety { # .SYNOPSIS # Checks worker code against the worker rules without running it. @@ -4317,10 +4331,10 @@ function Test-PkWorkerSafetyCore { } # The implicit form: a scriptblock literal, or a variable assigned one - # ({ }.GetNewClosure() included) anywhere in this code, passed to a - # method or constructor: $dict.GetOrAdd($k, { }), - # [System.Lazy[object]]::new($factory). .NET gets a delegate all the - # same. Matched by variable name, not flow. .ForEach()/.Where() take + # anywhere in this code, passed to a method or constructor: + # $dict.GetOrAdd($k, { }), [System.Lazy[object]]::new($factory). .NET + # gets a delegate all the same. Either can be wrapped (see + # Get-PkUnwrappedExpression). Matched by variable name, not flow. .ForEach()/.Where() take # real scriptblocks. Storage methods ($list.Add($sb), # $queue.Enqueue($sb)) make no delegate and aren't flagged, so a # collection typed to hold delegates (List[Func[object]]) isn't caught. @@ -4330,10 +4344,7 @@ function Test-PkWorkerSafetyCore { $target = $assign.Left if ($target -is [System.Management.Automation.Language.ConvertExpressionAst]) { $target = $target.Child } if ($target -isnot [System.Management.Automation.Language.VariableExpressionAst]) { continue } - $rhs = $assign.Right - if ($rhs -is [System.Management.Automation.Language.PipelineAst] -and $rhs.PipelineElements.Count -eq 1) { $rhs = $rhs.PipelineElements[0] } - if ($rhs -is [System.Management.Automation.Language.CommandExpressionAst]) { $rhs = $rhs.Expression } - if ($rhs -is [System.Management.Automation.Language.InvokeMemberExpressionAst] -and [string]$rhs.Member.Extent.Text -eq 'GetNewClosure') { $rhs = $rhs.Expression } + $rhs = Get-PkUnwrappedExpression -Ast $assign.Right if ($rhs -is [System.Management.Automation.Language.ScriptBlockExpressionAst]) { $null = $scriptBlockVars.Add($target.VariablePath.UserPath) } } foreach ($call in $ast.FindAll({ param($node) $node -is [System.Management.Automation.Language.InvokeMemberExpressionAst] }, $true)) { @@ -4343,6 +4354,7 @@ function Test-PkWorkerSafetyCore { if ($memberName -in $storageMethods) { continue } $passed = $null foreach ($argument in $call.Arguments) { + $argument = Get-PkUnwrappedExpression -Ast $argument if ($argument -is [System.Management.Automation.Language.ScriptBlockExpressionAst]) { $passed = 'a scriptblock' } elseif ($argument -is [System.Management.Automation.Language.VariableExpressionAst] -and $scriptBlockVars.Contains($argument.VariablePath.UserPath)) { $passed = ("the scriptblock in `$" + $argument.VariablePath.UserPath) diff --git a/README.md b/README.md index 70dd329..ac20a16 100644 --- a/README.md +++ b/README.md @@ -428,7 +428,7 @@ Everything else is fine in a worker, cmdlets included. Callbacks that run on the
How the kit checks them -`Invoke-PkRunspaceJobs` checks both rules before it starts anything, and refuses to launch code that breaks them, naming the line or the job key. Pass `-CheckWorkerSafety:$false` to turn that off. The code check is also available on its own as `Test-PkWorkerSafety -WorkerScript $w -SharedFunctionNames $names`, which returns a list of findings (including functions the worker calls but you didn't share), for use in your own tests. For rule 2 it flags written casts, and scriptblocks passed into a .NET method or constructor, either written in the call or through a variable they were assigned to. `# pk:ignore` on a line accepts a finding. Storing a scriptblock in a collection (`$list.Add($sb)`, `$queue.Enqueue($sb)`) isn't flagged, since that makes no delegate. The check also refuses a worker that reads a variable it never declares or assigns anywhere (`UndeclaredVariable`), since it would read as empty: one of your script's, or one a `.GetNewClosure()` captured. Parameters, assignments, loop variables, `[ref]`, `-OutVariable` and its kind, `Set-Variable` with a literal name, and PowerShell's own variables all count as declared. `$global:` names and drive-qualified ones (`$env:`) aren't checked, and neither are shared functions, which may read their caller's variables. If something the worker runs sets the variable (a helper file it dot-sources, a module it imports), put `# pk:ignore` on the line that reads it. It can't see commands run through a variable (`& $cmd`), a collection typed to hold delegates (`List[Func[object]]`, whose `.Add` converts), or a scriptblock buried more than three levels deep in a job value. +`Invoke-PkRunspaceJobs` checks both rules before it starts anything, and refuses to launch code that breaks them, naming the line or the job key. Pass `-CheckWorkerSafety:$false` to turn that off. The code check is also available on its own as `Test-PkWorkerSafety -WorkerScript $w -SharedFunctionNames $names`, which returns a list of findings (including functions the worker calls but you didn't share), for use in your own tests. For rule 2 it flags written casts, and scriptblocks passed into a .NET method or constructor, either written in the call or through a variable they were assigned to, parentheses, a `[scriptblock]` cast or `.GetNewClosure()` around them included. `# pk:ignore` on a line accepts a finding. Storing a scriptblock in a collection (`$list.Add($sb)`, `$queue.Enqueue($sb)`) isn't flagged, since that makes no delegate. The check also refuses a worker that reads a variable it never declares or assigns anywhere (`UndeclaredVariable`), since it would read as empty: one of your script's, or one a `.GetNewClosure()` captured. Parameters, assignments, loop variables, `[ref]`, `-OutVariable` and its kind, `Set-Variable` with a literal name, and PowerShell's own variables all count as declared. `$global:` names and drive-qualified ones (`$env:`) aren't checked, and neither are shared functions, which may read their caller's variables. If something the worker runs sets the variable (a helper file it dot-sources, a module it imports), put `# pk:ignore` on the line that reads it. It can't see commands run through a variable (`& $cmd`), a collection typed to hold delegates (`List[Func[object]]`, whose `.Add` converts), or a scriptblock buried more than three levels deep in a job value.
From 4d66c25af49cca17b8bbc237af595e6cae3c2f20 Mon Sep 17 00:00:00 2001 From: Hal <22532613+HalRiveria@users.noreply.github.com> Date: Tue, 1 Dec 2026 17:03:16 -0500 Subject: [PATCH 5/5] Singular function names, and one name each for the engines' limits Invoke-PkRunspaceJobs is Invoke-PkRunspaceBatch, and 13 private functions lose their plural names. -MaxConcurrent and -AbortTimeoutSeconds are the only names on every engine: -MaxParallel and -DrainTimeoutSeconds are gone. Co-Authored-By: Claude Opus 5.5 --- ParallelKit.Harness.ps1 | 251 +++++++++++++++++--------------- ParallelKit.ps1 | 181 +++++++++++------------ README.md | 34 ++--- Testing/cmdlet-hang/inner.ps1 | 4 +- Testing/hosts/check-host.ps1 | 2 +- Testing/readme-examples/run.ps1 | 8 +- Testing/soak/run.ps1 | 4 +- 7 files changed, 245 insertions(+), 239 deletions(-) diff --git a/ParallelKit.Harness.ps1 b/ParallelKit.Harness.ps1 index 34deb12..6fea69c 100644 --- a/ParallelKit.Harness.ps1 +++ b/ParallelKit.Harness.ps1 @@ -107,7 +107,7 @@ $publicFunctions = @('Set-PkMessageHandler', 'Write-PkMessage', 'Initialize-Para 'Unregister-PkCancellationSource', 'Reset-PkAbortState', 'Request-PkAbort', 'Test-PkAbortSignal', 'Test-PkCancelRequested', 'Get-PkAbortTriggerLabel', 'Invoke-PkRun', 'ConvertTo-PkArgumentString', 'Start-PkProcess', 'Stop-PkProcessTree', 'Wait-PkProcess', 'Complete-PkProcess', 'Invoke-PkProcessWithTimeout', 'Invoke-PkProcessDispatch', 'Invoke-PkProcessBatch', - 'Invoke-PkRunspaceJobs', 'Test-PkWorkerSafety') + 'Invoke-PkRunspaceBatch', 'Test-PkWorkerSafety') # cmd exits at once, but the ping it starts with `start /b` keeps the output # pipe open about 3 s longer. $heldArgs = '/d /c echo before& start /b ping -n 4 127.0.0.1 >nul& echo after' @@ -256,12 +256,12 @@ $worker = { } $jobs = New-JobList -Jobs @(1..8 | ForEach-Object { @{ Id = $_; Track = $track; Gate = $gate } }) $results = [System.Collections.Generic.List[hashtable]]::new() -$out = Invoke-PkRunspaceJobs -WorkerScript $worker -JobParams $jobs -MaxParallel 3 -SharedFunctionNames @('Get-HarnessDouble') ` +$out = Invoke-PkRunspaceBatch -WorkerScript $worker -JobParams $jobs -MaxConcurrent 3 -SharedFunctionNames @('Get-HarnessDouble') ` -ResultHandler { param($r) $results.Add($r) }.GetNewClosure() -CheckWorkerSafety Test-Assert ($results.Count -eq 8) "all 8 jobs return a result" $sum = 0; foreach ($r in $results) { $sum += $r.Doubled } Test-Assert ($sum -eq 72) "the shared user function ran inside the workers (sum of doubles = 72)" -Test-Assert ($track.Max -le 3 -and $track.Max -ge 2) ("never more than MaxParallel workers at once (peak " + $track.Max + ")") +Test-Assert ($track.Max -le 3 -and $track.Max -ge 2) ("never more than MaxConcurrent workers at once (peak " + $track.Max + ")") Test-Assert (@($script:messages | Where-Object { $_.Message -like 'worker * done' }).Count -eq 8) "all 8 worker messages reach the main-thread handler" Test-Assert ($out.CrashedCount -eq 0 -and -not $out.Aborted -and $out.ForceStoppedCount -eq 0) "a clean run reports no crashes, no abort, nothing force-stopped" Test-Assert ([PkState]::SourceCount -eq 0) "the run's own cancellation source is unregistered afterwards" @@ -274,14 +274,14 @@ Reset-Harness $feed = @{ Next = 1 } $provider = { if ($feed.Next -gt 5) { return $null }; $j = @{ Id = $feed.Next }; $feed.Next++; return $j }.GetNewClosure() $results = [System.Collections.Generic.List[object]]::new() -$out = Invoke-PkRunspaceJobs -WorkerScript { param([int]$Id) return $Id } -NextJobProvider $provider -MaxParallel 2 ` +$out = Invoke-PkRunspaceBatch -WorkerScript { param([int]$Id) return $Id } -NextJobProvider $provider -MaxConcurrent 2 ` -ResultHandler { param($r) $results.Add($r) }.GetNewClosure() Test-Assert ($results.Count -eq 5) "-NextJobProvider feeds jobs until it returns null" $crashes = [System.Collections.Generic.List[object]]::new() $results = [System.Collections.Generic.List[object]]::new() $jobs = New-JobList -Jobs @(@{ Id = 1 }, @{ Id = 2 }, @{ Id = 3 }) -$out = Invoke-PkRunspaceJobs -WorkerScript { param([int]$Id) if ($Id -eq 2) { throw "boom" }; return $Id } -JobParams $jobs -MaxParallel 2 ` +$out = Invoke-PkRunspaceBatch -WorkerScript { param([int]$Id) if ($Id -eq 2) { throw "boom" }; return $Id } -JobParams $jobs -MaxConcurrent 2 ` -ResultHandler { param($r) $results.Add($r) }.GetNewClosure() -JobCrashedHandler { param($e) $crashes.Add($e) }.GetNewClosure() Test-Assert ($out.CrashedCount -eq 1 -and $crashes.Count -eq 1) "a worker that throws is counted and reported to -JobCrashedHandler" Test-Assert ($results.Count -eq 2) "the other workers still return their results" @@ -292,28 +292,28 @@ $crashedProp = $out.PSObject.Properties['Crashed'] # read safely: strict mode Test-Assert ($null -ne $crashedProp -and @($crashedProp.Value).Count -eq 1 -and $crashedProp.Value[0].Job['Id'] -eq 2 -and $crashedProp.Value[0].Error -is [System.Management.Automation.ErrorRecord]) "the return object lists the crashed job and its error" $crashWorker = { param([int]$Id) if ($Id -eq 2) { throw "boom" }; return $Id } $seenJobs = [System.Collections.Generic.List[object]]::new() -$null = Invoke-PkRunspaceJobs -WorkerScript $crashWorker -JobParams $jobs -MaxParallel 2 -JobCrashedHandler { param($e, $job) $seenJobs.Add($job) }.GetNewClosure() +$null = Invoke-PkRunspaceBatch -WorkerScript $crashWorker -JobParams $jobs -MaxConcurrent 2 -JobCrashedHandler { param($e, $job) $seenJobs.Add($job) }.GetNewClosure() Test-Assert ($seenJobs.Count -eq 1 -and $null -ne $seenJobs[0] -and $seenJobs[0]['Id'] -eq 2) "a -JobCrashedHandler with a second parameter gets the job that crashed" $seenArgs = @{ Count = -1; Id = $null } -$null = Invoke-PkRunspaceJobs -WorkerScript $crashWorker -JobParams $jobs -MaxParallel 2 -JobCrashedHandler { $seenArgs.Count = $args.Count; $seenArgs.Id = $args[1]['Id'] }.GetNewClosure() +$null = Invoke-PkRunspaceBatch -WorkerScript $crashWorker -JobParams $jobs -MaxConcurrent 2 -JobCrashedHandler { $seenArgs.Count = $args.Count; $seenArgs.Id = $args[1]['Id'] }.GetNewClosure() Test-Assert ($seenArgs.Count -eq 2 -and $seenArgs.Id -eq 2) ("a -JobCrashedHandler with no param() gets the error and the job in `$args (count " + $seenArgs.Count + ")") # One-parameter handlers that would throw on a second argument still work. $advanced = @{ Calls = 0 } -$null = Invoke-PkRunspaceJobs -WorkerScript $crashWorker -JobParams $jobs -MaxParallel 2 -JobCrashedHandler { [CmdletBinding()] param($e) $advanced.Calls++ }.GetNewClosure() +$null = Invoke-PkRunspaceBatch -WorkerScript $crashWorker -JobParams $jobs -MaxConcurrent 2 -JobCrashedHandler { [CmdletBinding()] param($e) $advanced.Calls++ }.GetNewClosure() Test-Assert ($advanced.Calls -eq 1) "a one-parameter [CmdletBinding()] -JobCrashedHandler is still called" function Receive-HarnessCrash($e, $job) { $script:harnessCrashId = $job['Id'] } $script:harnessCrashId = $null -$null = Invoke-PkRunspaceJobs -WorkerScript $crashWorker -JobParams $jobs -MaxParallel 2 -JobCrashedHandler ${function:Receive-HarnessCrash} +$null = Invoke-PkRunspaceBatch -WorkerScript $crashWorker -JobParams $jobs -MaxConcurrent 2 -JobCrashedHandler ${function:Receive-HarnessCrash} Test-Assert ($script:harnessCrashId -eq 2) "a function used as -JobCrashedHandler, with function f(`$e, `$job) parameters, gets the job" # A handler that throws is reported, not swallowed. Reset-Harness -$null = Invoke-PkRunspaceJobs -WorkerScript $crashWorker -JobParams $jobs -MaxParallel 2 -JobCrashedHandler { param($e) throw "handler bug" } +$null = Invoke-PkRunspaceBatch -WorkerScript $crashWorker -JobParams $jobs -MaxConcurrent 2 -JobCrashedHandler { param($e) throw "handler bug" } Test-Assert (@($script:messages | Where-Object { $_.Message -like '*-JobCrashedHandler threw*handler bug*' }).Count -eq 1) "a -JobCrashedHandler that throws is reported as a message" # Workers that throw while an abort waits for them count as crashes too. Reset-Harness $poll = @{ Count = 0 } $drainCrashes = [System.Collections.Generic.List[object]]::new() -$drainOut = Invoke-PkRunspaceJobs -MaxParallel 2 -JobParams (New-JobList -Jobs @(@{ Id = 1 }, @{ Id = 2 })) -WorkerScript { +$drainOut = Invoke-PkRunspaceBatch -MaxConcurrent 2 -JobParams (New-JobList -Jobs @(@{ Id = 1 }, @{ Id = 2 })) -WorkerScript { param([int]$Id) for ($i = 0; $i -lt 100; $i++) { if (Test-PkCancelRequested) { break }; [System.Threading.Thread]::Sleep(50) } [System.Threading.Thread]::Sleep(500) @@ -324,12 +324,12 @@ Test-Assert ($drainOut.Aborted -and $drainOut.CrashedCount -eq 2 -and $null -ne Reset-Harness $threw = $false -try { $null = Invoke-PkRunspaceJobs -WorkerScript { param($Id) } -JobParams (New-JobList -Jobs @(@{ Id = 1 })) -MaxParallel 1 -SharedFunctionNames @('No-SuchFunction') } catch { $threw = ($_.ToString() -like "*No-SuchFunction*") } +try { $null = Invoke-PkRunspaceBatch -WorkerScript { param($Id) } -JobParams (New-JobList -Jobs @(@{ Id = 1 })) -MaxConcurrent 1 -SharedFunctionNames @('No-SuchFunction') } catch { $threw = ($_.ToString() -like "*No-SuchFunction*") } Test-Assert $threw "an unknown -SharedFunctionNames entry fails up front with the name in the message" $threw = $false -try { $null = Invoke-PkRunspaceJobs -WorkerScript { param($Id) } -JobParams (New-JobList -Jobs @(@{ Id = 1; Extra = 2 })) -MaxParallel 1 } catch { $threw = ($_.ToString() -like "*Extra*") } +try { $null = Invoke-PkRunspaceBatch -WorkerScript { param($Id) } -JobParams (New-JobList -Jobs @(@{ Id = 1; Extra = 2 })) -MaxConcurrent 1 } catch { $threw = ($_.ToString() -like "*Extra*") } Test-Assert $threw "a job key the worker doesn't declare fails with a clear message" -$emptyOut = Invoke-PkRunspaceJobs -WorkerScript { param($Id) } -JobParams ([System.Collections.Generic.List[hashtable]]::new()) -MaxParallel 1 +$emptyOut = Invoke-PkRunspaceBatch -WorkerScript { param($Id) } -JobParams ([System.Collections.Generic.List[hashtable]]::new()) -MaxConcurrent 1 Test-Assert ($emptyOut.CrashedCount -eq 0 -and -not $emptyOut.Aborted) "an empty job list returns immediately" Write-Host "" } @@ -350,7 +350,7 @@ $jobs = New-JobList -Jobs @(1..6 | ForEach-Object { @{ Id = $_ } }) $results = [System.Collections.Generic.List[hashtable]]::new() $poll = @{ Count = 0 } $sw = [System.Diagnostics.Stopwatch]::StartNew() -$out = Invoke-PkRunspaceJobs -WorkerScript $worker -JobParams $jobs -MaxParallel 2 ` +$out = Invoke-PkRunspaceBatch -WorkerScript $worker -JobParams $jobs -MaxConcurrent 2 ` -ResultHandler { param($r) $results.Add($r) }.GetNewClosure() ` -PollCallback { $poll.Count++; if ($poll.Count -eq 5) { Request-PkAbort } }.GetNewClosure() $sw.Stop() @@ -366,8 +366,8 @@ Test-Assert (@($script:messages | Where-Object { $_.Message -like '*Abort reques Reset-Harness $poll = @{ Count = 0 } $sw = [System.Diagnostics.Stopwatch]::StartNew() -$out = Invoke-PkRunspaceJobs -WorkerScript { param([int]$Id) [System.Threading.Thread]::Sleep(6000); return $Id } ` - -JobParams (New-JobList -Jobs @(@{ Id = 1 }, @{ Id = 2 })) -MaxParallel 2 -DrainTimeoutSeconds 1 ` +$out = Invoke-PkRunspaceBatch -WorkerScript { param([int]$Id) [System.Threading.Thread]::Sleep(6000); return $Id } ` + -JobParams (New-JobList -Jobs @(@{ Id = 1 }, @{ Id = 2 })) -MaxConcurrent 2 -AbortTimeoutSeconds 1 ` -PollCallback { $poll.Count++; if ($poll.Count -eq 3) { Request-PkAbort } }.GetNewClosure() $sw.Stop() Test-Assert ($out.ForceStoppedCount -eq 2) "workers that ignore the cancel are force-stopped after the drain timeout" @@ -615,7 +615,7 @@ $engine = { $peak = @{ Max = 0 } $results = [System.Collections.Generic.List[hashtable]]::new() $jobs = New-JobList -Jobs @(@{ Name = 'A'; Budget = $budget; PingExe = $pingExe; Peak = $peak }, @{ Name = 'B'; Budget = $budget; PingExe = $pingExe; Peak = $peak }) -$out = Invoke-PkRunspaceJobs -WorkerScript $engine -JobParams $jobs -MaxParallel 2 -ResultHandler { param($r) $results.Add($r) }.GetNewClosure() -CheckWorkerSafety +$out = Invoke-PkRunspaceBatch -WorkerScript $engine -JobParams $jobs -MaxConcurrent 2 -ResultHandler { param($r) $results.Add($r) }.GetNewClosure() -CheckWorkerSafety Test-Assert ($out.CrashedCount -eq 0) "dispatchers run inside worker runspaces without crashing" $total = 0; foreach ($r in $results) { $total += $r.Done } Test-Assert ($total -eq 8) ("both engines finish all their processes (8 total, got " + $total + ")") @@ -638,7 +638,7 @@ $churn = { return $Id } $before = [PkState]::SourceCount -$churnOut = Invoke-PkRunspaceJobs -WorkerScript $churn -JobParams (New-JobList -Jobs @(1..6 | ForEach-Object { @{ Id = $_ } })) -MaxParallel 6 +$churnOut = Invoke-PkRunspaceBatch -WorkerScript $churn -JobParams (New-JobList -Jobs @(1..6 | ForEach-Object { @{ Id = $_ } })) -MaxConcurrent 6 Test-Assert ($churnOut.CrashedCount -eq 0 -and [PkState]::SourceCount -eq $before) "cancellation sources can be registered and unregistered from 6 workers at once" Write-Host "" } @@ -718,40 +718,40 @@ Test-Assert ($f.Count -eq 0) "'# pk:ignore' on the line accepts a finding" $f = Test-PkWorkerSafety -WorkerScript { param($Id) Write-PkMessage "x"; if (Test-PkCancelRequested) { return }; $null = Start-PkProcess -FilePath 'x' } Test-Assert ($f.Count -eq 0) "the kit's own worker functions never need listing" $threw = $false -try { $null = Invoke-PkRunspaceJobs -WorkerScript { param($Id) $null = [Func[int]]{ 1 } } -JobParams (New-JobList -Jobs @(@{ Id = 1 })) -MaxParallel 1 -CheckWorkerSafety } catch { $threw = ($_.ToString() -like '*Func*') } +try { $null = Invoke-PkRunspaceBatch -WorkerScript { param($Id) $null = [Func[int]]{ 1 } } -JobParams (New-JobList -Jobs @(@{ Id = 1 })) -MaxConcurrent 1 -CheckWorkerSafety } catch { $threw = ($_.ToString() -like '*Func*') } Test-Assert $threw "-CheckWorkerSafety refuses to launch unsafe worker code, naming the problem" $threw = $false -try { $null = Invoke-PkRunspaceJobs -WorkerScript { param($Id) $null = [Func[int]]{ 1 } } -JobParams (New-JobList -Jobs @(@{ Id = 1 })) -MaxParallel 1 } catch { $threw = ($_.ToString() -like '*Func*') } +try { $null = Invoke-PkRunspaceBatch -WorkerScript { param($Id) $null = [Func[int]]{ 1 } } -JobParams (New-JobList -Jobs @(@{ Id = 1 })) -MaxConcurrent 1 } catch { $threw = ($_.ToString() -like '*Func*') } Test-Assert $threw "the worker-safety check runs without being asked" $out = $null -try { $out = Invoke-PkRunspaceJobs -WorkerScript { param($Id) $null = [Func[int]]{ 1 } } -JobParams (New-JobList -Jobs @(@{ Id = 1 })) -MaxParallel 1 -CheckWorkerSafety:$false } catch { Write-Host " opt-out threw: $_" } +try { $out = Invoke-PkRunspaceBatch -WorkerScript { param($Id) $null = [Func[int]]{ 1 } } -JobParams (New-JobList -Jobs @(@{ Id = 1 })) -MaxConcurrent 1 -CheckWorkerSafety:$false } catch { Write-Host " opt-out threw: $_" } Test-Assert ($null -ne $out -and $out.CrashedCount -eq 0) "-CheckWorkerSafety:`$false turns the check off" $results = [System.Collections.Generic.List[object]]::new() -$out = Invoke-PkRunspaceJobs -WorkerScript { param($Id) return @(1, 2, 3) | Where-Object { $_ -gt 1 } | Measure-Object -Sum | ForEach-Object { $_.Sum + $Id } } ` - -JobParams (New-JobList -Jobs @(@{ Id = 10 }, @{ Id = 20 })) -MaxParallel 2 -ResultHandler { param($r) $results.Add($r) }.GetNewClosure() +$out = Invoke-PkRunspaceBatch -WorkerScript { param($Id) return @(1, 2, 3) | Where-Object { $_ -gt 1 } | Measure-Object -Sum | ForEach-Object { $_.Sum + $Id } } ` + -JobParams (New-JobList -Jobs @(@{ Id = 10 }, @{ Id = 20 })) -MaxConcurrent 2 -ResultHandler { param($r) $results.Add($r) }.GetNewClosure() Test-Assert ($out.CrashedCount -eq 0 -and (@($results | Sort-Object) -join ',') -eq '15,25') "workers can run cmdlets, including ones that take a scriptblock" $results = [System.Collections.Generic.List[object]]::new() -$out = Invoke-PkRunspaceJobs -WorkerScript { param($Path) return (Get-FileHash -LiteralPath $Path -Algorithm SHA256).Hash } ` - -JobParams (New-JobList -Jobs @(@{ Path = $cmdExe })) -MaxParallel 1 -ResultHandler { param($r) $results.Add($r) }.GetNewClosure() +$out = Invoke-PkRunspaceBatch -WorkerScript { param($Path) return (Get-FileHash -LiteralPath $Path -Algorithm SHA256).Hash } ` + -JobParams (New-JobList -Jobs @(@{ Path = $cmdExe })) -MaxConcurrent 1 -ResultHandler { param($r) $results.Add($r) }.GetNewClosure() Test-Assert ($out.CrashedCount -eq 0 -and $results.Count -eq 1 -and $results[0] -eq (Get-FileHash -LiteralPath $cmdExe -Algorithm SHA256).Hash) "a function from a module (Get-FileHash) needn't be shared, and autoloads in the worker" # A scriptblock passed as a job value runs against the main thread's session # state - refused at launch, with the pass-as-text workaround. $mainThreadBlock = { param($x) $x * 2 } $threw = $false -try { $null = Invoke-PkRunspaceJobs -WorkerScript { param($Fn) } -JobParams (New-JobList -Jobs @(@{ Fn = 'ok' }, @{ Fn = $mainThreadBlock })) -MaxParallel 1 } catch { $threw = ($_.ToString() -like "*job 1*'Fn'*Create*Nothing was started*") } +try { $null = Invoke-PkRunspaceBatch -WorkerScript { param($Fn) } -JobParams (New-JobList -Jobs @(@{ Fn = 'ok' }, @{ Fn = $mainThreadBlock })) -MaxConcurrent 1 } catch { $threw = ($_.ToString() -like "*job 1*'Fn'*Create*Nothing was started*") } Test-Assert $threw "a scriptblock job value is refused before any worker starts, naming the job and key" $threw = $false -try { $null = Invoke-PkRunspaceJobs -WorkerScript { param($Fns) } -JobParams (New-JobList -Jobs @(@{ Fns = @(1, $mainThreadBlock) })) -MaxParallel 1 } catch { $threw = ($_.ToString() -like "*'Fns'*") } +try { $null = Invoke-PkRunspaceBatch -WorkerScript { param($Fns) } -JobParams (New-JobList -Jobs @(@{ Fns = @(1, $mainThreadBlock) })) -MaxConcurrent 1 } catch { $threw = ($_.ToString() -like "*'Fns'*") } Test-Assert $threw "a scriptblock inside an array job value is refused too" $threw = $false $providerState = @{ Given = 0 } $provider = { if ($providerState.Given -ge 2) { return $null }; $providerState.Given++; if ($providerState.Given -eq 2) { return @{ Fn = $mainThreadBlock } }; return @{ Fn = 'ok' } }.GetNewClosure() -try { $null = Invoke-PkRunspaceJobs -WorkerScript { param($Fn) } -NextJobProvider $provider -MaxParallel 1 } catch { $threw = ($_.ToString() -like "*-NextJobProvider*'Fn'*") } +try { $null = Invoke-PkRunspaceBatch -WorkerScript { param($Fn) } -NextJobProvider $provider -MaxConcurrent 1 } catch { $threw = ($_.ToString() -like "*-NextJobProvider*'Fn'*") } Test-Assert $threw "a scriptblock job value from -NextJobProvider is refused" $results = [System.Collections.Generic.List[object]]::new() -$out = Invoke-PkRunspaceJobs -WorkerScript { param($FnText, $Id) $fn = [scriptblock]::Create($FnText); return (& $fn $Id) } ` - -JobParams (New-JobList -Jobs @(@{ FnText = $mainThreadBlock.ToString(); Id = 4 })) -MaxParallel 1 -ResultHandler { param($r) $results.Add($r) }.GetNewClosure() +$out = Invoke-PkRunspaceBatch -WorkerScript { param($FnText, $Id) $fn = [scriptblock]::Create($FnText); return (& $fn $Id) } ` + -JobParams (New-JobList -Jobs @(@{ FnText = $mainThreadBlock.ToString(); Id = 4 })) -MaxConcurrent 1 -ResultHandler { param($r) $results.Add($r) }.GetNewClosure() Test-Assert ($out.CrashedCount -eq 0 -and $results.Count -eq 1 -and $results[0] -eq 8) "the pass-as-text workaround runs" Write-Host "" } @@ -772,14 +772,14 @@ if (Test-HarnessSection 'M' "callbacks that output things") { Reset-Harness # Every callback below emits stray output. None of it may reach a return value. $poll = @{ Count = 0 } -$out = Invoke-PkRunspaceJobs -MaxParallel 2 -JobParams (New-JobList -Jobs @(1..4 | ForEach-Object { @{ Id = $_ } })) ` +$out = Invoke-PkRunspaceBatch -MaxConcurrent 2 -JobParams (New-JobList -Jobs @(1..4 | ForEach-Object { @{ Id = $_ } })) ` -WorkerScript { param([int]$Id) for ($i = 0; $i -lt 50; $i++) { if (Test-PkCancelRequested) { return $Id }; [System.Threading.Thread]::Sleep(100) }; return $Id } ` -ResultHandler { param($r) $true; 123 } ` -PollCallback { $poll.Count++; if ($poll.Count -eq 4) { Request-PkAbort }; "noise" }.GetNewClosure() Test-Assert ($out -is [System.Management.Automation.PSCustomObject] -and $out.Aborted) "runspace jobs: noisy -ResultHandler/-PollCallback don't corrupt the result, even through an abort drain" Reset-Harness -$crashOut = Invoke-PkRunspaceJobs -MaxParallel 1 -JobParams (New-JobList -Jobs @(@{ Id = 1 })) -WorkerScript { param($Id) throw "x" } -JobCrashedHandler { param($e) "noise"; 5 } +$crashOut = Invoke-PkRunspaceBatch -MaxConcurrent 1 -JobParams (New-JobList -Jobs @(@{ Id = 1 })) -WorkerScript { param($Id) throw "x" } -JobCrashedHandler { param($e) "noise"; 5 } Test-Assert ($crashOut -is [System.Management.Automation.PSCustomObject] -and $crashOut.CrashedCount -eq 1) "runspace jobs: a noisy -JobCrashedHandler doesn't corrupt the result" Reset-Harness @@ -805,7 +805,7 @@ Set-PkMessageHandler -Handler { param($Message, $Level) $messageSink.Add(@{ Mess # Set in a worker, the handler would be the worker's scriptblock, run by the main thread. $handlerCrash = [System.Collections.Generic.List[string]]::new() $handlerBefore = [PkState]::MessageHandler -$handlerRun = Invoke-PkRunspaceJobs -MaxParallel 1 -JobParams (New-JobList -Jobs @(@{ Reset = $false }, @{ Reset = $true })) -SharedFunctionNames Set-PkMessageHandler -JobCrashedHandler { param($e) $handlerCrash.Add([string]$e.Exception.InnerException.Message) }.GetNewClosure() -WorkerScript { +$handlerRun = Invoke-PkRunspaceBatch -MaxConcurrent 1 -JobParams (New-JobList -Jobs @(@{ Reset = $false }, @{ Reset = $true })) -SharedFunctionNames Set-PkMessageHandler -JobCrashedHandler { param($e) $handlerCrash.Add([string]$e.Exception.InnerException.Message) }.GetNewClosure() -WorkerScript { param($Reset) if ($Reset) { Set-PkMessageHandler $null } else { Set-PkMessageHandler { param($Message, $Level) } } } @@ -879,7 +879,7 @@ Reset-Harness $mine = [System.Threading.CancellationTokenSource]::new() $poll = @{ Count = 0 } $results = [System.Collections.Generic.List[object]]::new() -$out = Invoke-PkRunspaceJobs -MaxParallel 2 -Cts $mine -JobParams (New-JobList -Jobs @(1..6 | ForEach-Object { @{ Id = $_ } })) ` +$out = Invoke-PkRunspaceBatch -MaxConcurrent 2 -Cts $mine -JobParams (New-JobList -Jobs @(1..6 | ForEach-Object { @{ Id = $_ } })) ` -WorkerScript { param([int]$Id) for ($i = 0; $i -lt 50; $i++) { if (Test-PkCancelRequested) { return $Id }; [System.Threading.Thread]::Sleep(100) }; return $Id } ` -ResultHandler { param($r) $results.Add($r) }.GetNewClosure() ` -PollCallback { $poll.Count++; if ($poll.Count -eq 4) { Request-PkAbort } }.GetNewClosure() @@ -918,14 +918,14 @@ Reset-Harness Request-PkAbort $null = Test-PkAbortSignal $results = [System.Collections.Generic.List[object]]::new() -$out = Invoke-PkRunspaceJobs -MaxParallel 2 -JobParams (New-JobList -Jobs @(1..4 | ForEach-Object { @{ Id = $_ } })) ` +$out = Invoke-PkRunspaceBatch -MaxConcurrent 2 -JobParams (New-JobList -Jobs @(1..4 | ForEach-Object { @{ Id = $_ } })) ` -WorkerScript { param([int]$Id) if (Test-PkCancelRequested) { return }; return $Id } -ResultHandler { param($r) $results.Add($r) }.GetNewClosure() Test-Assert ($out.Aborted -eq $true -and $results.Count -eq 0) "a run started while an earlier abort is still in force reports Aborted instead of silently doing nothing" $batchAfter = Invoke-PkProcessBatch -Commands @(@{ FilePath = $cmdExe; Arguments = '/c exit 0' }) -MaxConcurrent 1 Test-Assert ($batchAfter.Aborted -eq $true) "the same goes for a process batch" Reset-PkAbortState $results = [System.Collections.Generic.List[object]]::new() -$out = Invoke-PkRunspaceJobs -MaxParallel 2 -JobParams (New-JobList -Jobs @(1..4 | ForEach-Object { @{ Id = $_ } })) ` +$out = Invoke-PkRunspaceBatch -MaxConcurrent 2 -JobParams (New-JobList -Jobs @(1..4 | ForEach-Object { @{ Id = $_ } })) ` -WorkerScript { param([int]$Id) if (Test-PkCancelRequested) { return }; return $Id } -ResultHandler { param($r) $results.Add($r) }.GetNewClosure() Test-Assert (-not $out.Aborted -and $results.Count -eq 4) "after Reset-PkAbortState the next run is normal again" @@ -1130,7 +1130,7 @@ Set-PkMessageHandler -Handler { param($Message, $Level) throw "log file locked" $results = [System.Collections.Generic.List[object]]::new() $threw = $false try { - $out = Invoke-PkRunspaceJobs -MaxParallel 2 -JobParams (New-JobList -Jobs @(@{ Id = 1 }, @{ Id = 2 }, @{ Id = 3 })) ` + $out = Invoke-PkRunspaceBatch -MaxConcurrent 2 -JobParams (New-JobList -Jobs @(@{ Id = 1 }, @{ Id = 2 }, @{ Id = 3 })) ` -WorkerScript { param([int]$Id) Write-PkMessage ("from " + $Id); if ($Id -eq 2) { throw "boom" }; return $Id } ` -ResultHandler { param($r) $results.Add($r) }.GetNewClosure() } catch { $threw = $true } @@ -1152,7 +1152,7 @@ Test-Assert (@($script:messages | Where-Object { $_.Level -eq 'Warn' -and $_.Mes Reset-Harness $feed = @{ Next = 1 } $results = [System.Collections.Generic.List[object]]::new() -$out = Invoke-PkRunspaceJobs -MaxParallel 2 -WorkerScript { param([int]$Id) return $Id } ` +$out = Invoke-PkRunspaceBatch -MaxConcurrent 2 -WorkerScript { param([int]$Id) return $Id } ` -NextJobProvider { if ($feed.Next -gt 3) { return $null }; "noise"; $j = @{ Id = $feed.Next }; $feed.Next++; return $j }.GetNewClosure() ` -ResultHandler { param($r) $results.Add($r) }.GetNewClosure() Test-Assert ($results.Count -eq 3 -and $out.CrashedCount -eq 0) "a job provider that lets stray output escape still feeds its jobs" @@ -1167,7 +1167,7 @@ $ran = @{ Count = 0 } $gate = [object]::new() $threw = $false try { - $null = Invoke-PkRunspaceJobs -MaxParallel 1 ` + $null = Invoke-PkRunspaceBatch -MaxConcurrent 1 ` -JobParams (New-JobList -Jobs @(@{ Id = 1; Ran = $ran; Gate = $gate }, @{ Id = 2; Ran = $ran; Gate = $gate }, @{ Id = 3; Ran = $ran; Gate = $gate; Typo = 1 })) ` -WorkerScript { param([int]$Id, $Ran, $Gate) [System.Threading.Monitor]::Enter($Gate); try { $Ran.Count++ } finally { [System.Threading.Monitor]::Exit($Gate) }; return $Id } } catch { $threw = ($_.ToString() -like "*job 2 supplies 'Typo'*Nothing was started*") } @@ -1182,7 +1182,7 @@ $results = [System.Collections.Generic.List[object]]::new() $loopGuard = @{ Calls = 0 } $threw = $null try { - $null = Invoke-PkRunspaceJobs -MaxParallel 2 -JobParams (New-JobList -Jobs @(@{ Id = 1 }, @{ Id = 2 })) -WorkerScript { param([int]$Id) $Id } -ResultHandler { + $null = Invoke-PkRunspaceBatch -MaxConcurrent 2 -JobParams (New-JobList -Jobs @(@{ Id = 1 }, @{ Id = 2 })) -WorkerScript { param([int]$Id) $Id } -ResultHandler { param($r) $loopGuard.Calls++ if ($loopGuard.Calls -gt 20) { throw 'still looping after 20 handler calls' } @@ -1198,7 +1198,7 @@ $loopGuard = @{ Calls = 0 } $poll = @{ Count = 0 } $threw = $null try { - $null = Invoke-PkRunspaceJobs -MaxParallel 2 -JobParams (New-JobList -Jobs @(@{ Id = 1 }, @{ Id = 2 }, @{ Id = 3 })) -WorkerScript { + $null = Invoke-PkRunspaceBatch -MaxConcurrent 2 -JobParams (New-JobList -Jobs @(@{ Id = 1 }, @{ Id = 2 }, @{ Id = 3 })) -WorkerScript { param([int]$Id) # Finish only after the abort, and late enough that the main loop has # already handed over to the drain. @@ -1220,7 +1220,7 @@ Test-Assert ($null -eq $threw -and $loopGuard.Calls -eq 2 -and $results.Count -e # A -JobCrashedHandler without a closure sees the caller's $results. Reset-Harness $results = [System.Collections.Generic.List[object]]::new() -$null = Invoke-PkRunspaceJobs -MaxParallel 1 -JobParams (New-JobList -Jobs @(@{ Id = 1 })) -WorkerScript { param([int]$Id) throw "x" } -JobCrashedHandler { param($e) $results.Add($e) } +$null = Invoke-PkRunspaceBatch -MaxConcurrent 1 -JobParams (New-JobList -Jobs @(@{ Id = 1 })) -WorkerScript { param([int]$Id) throw "x" } -JobCrashedHandler { param($e) $results.Add($e) } Test-Assert ($results.Count -eq 1) ("a -JobCrashedHandler without a closure reaches the caller's `$results (count=" + $results.Count + ")") Reset-Harness Write-Host "" @@ -1282,16 +1282,16 @@ Test-Assert (-not $threw -and $state.Finalized -eq 2 -and $d.GroupResults.Count Reset-Harness $results = [System.Collections.Generic.List[object]]::new() $oneJob = foreach ($n in @(7)) { @{ Id = $n } } -$out = Invoke-PkRunspaceJobs -MaxParallel 2 -JobParams $oneJob -WorkerScript { param([int]$Id) return $Id } -ResultHandler { param($r) $results.Add($r) }.GetNewClosure() +$out = Invoke-PkRunspaceBatch -MaxConcurrent 2 -JobParams $oneJob -WorkerScript { param([int]$Id) return $Id } -ResultHandler { param($r) $results.Add($r) }.GetNewClosure() Test-Assert ($results.Count -eq 1 -and $results[0] -eq 7) "-JobParams accepts a job list that collapsed to a single hashtable" $results = [System.Collections.Generic.List[object]]::new() -$out = Invoke-PkRunspaceJobs -MaxParallel 2 -JobParams @(@{ Id = 1 }, @{ Id = 2 }) -WorkerScript { param([int]$Id) return $Id } -ResultHandler { param($r) $results.Add($r) }.GetNewClosure() +$out = Invoke-PkRunspaceBatch -MaxConcurrent 2 -JobParams @(@{ Id = 1 }, @{ Id = 2 }) -WorkerScript { param([int]$Id) return $Id } -ResultHandler { param($r) $results.Add($r) }.GetNewClosure() Test-Assert ($results.Count -eq 2) "-JobParams accepts a plain array of hashtables" $threw = $false -try { $null = Invoke-PkRunspaceJobs -MaxParallel 1 -JobParams @(@{ Id = 1 }, 'oops') -WorkerScript { param($Id) } } catch { $threw = ($_.ToString() -like '*entry 1 is not a hashtable*') } +try { $null = Invoke-PkRunspaceBatch -MaxConcurrent 1 -JobParams @(@{ Id = 1 }, 'oops') -WorkerScript { param($Id) } } catch { $threw = ($_.ToString() -like '*entry 1 is not a hashtable*') } Test-Assert $threw "-JobParams with a non-hashtable entry fails with a message naming the entry" $threw = $false -try { $null = Invoke-PkRunspaceJobs -MaxParallel 1 -JobParams @(@{ Id = 1 }, $null) -WorkerScript { param($Id) } } catch { $threw = ($_.ToString() -like '*entry 1 is not a hashtable*') } +try { $null = Invoke-PkRunspaceBatch -MaxConcurrent 1 -JobParams @(@{ Id = 1 }, $null) -WorkerScript { param($Id) } } catch { $threw = ($_.ToString() -like '*entry 1 is not a hashtable*') } Test-Assert $threw "-JobParams with a `$null entry fails the same way" # So does a shared budget. @@ -1416,7 +1416,7 @@ Reset-Harness $poll = @{ Count = 0 } $workerErrors = [System.Collections.Generic.List[object]]::new() $sw = [System.Diagnostics.Stopwatch]::StartNew() -$out = Invoke-PkRunspaceJobs -MaxParallel 1 -JobParams @{ PingExe = $pingExe } -DrainTimeoutSeconds 20 ` +$out = Invoke-PkRunspaceBatch -MaxConcurrent 1 -JobParams @{ PingExe = $pingExe } -AbortTimeoutSeconds 20 ` -WorkerScript { param($PingExe) try { $null = Invoke-PkProcessWithTimeout -FilePath $PingExe -Arguments '-n 30 127.0.0.1' -TimeoutMs 25000; return 'finished' } catch { return [string]$_ } } ` -ResultHandler { param($r) $workerErrors.Add($r) }.GetNewClosure() ` -PollCallback { $poll.Count++; if ($poll.Count -eq 6) { Request-PkAbort } }.GetNewClosure() @@ -1450,7 +1450,7 @@ Test-Assert ([PkConsoleCtrl]::RunActive -eq $false) "the run still disarms at it # A worker that turns strict mode on can still use the kit's functions. Reset-Harness $results = [System.Collections.Generic.List[object]]::new() -$out = Invoke-PkRunspaceJobs -MaxParallel 1 -JobParams @{ CmdExe = $cmdExe } ` +$out = Invoke-PkRunspaceBatch -MaxConcurrent 1 -JobParams @{ CmdExe = $cmdExe } ` -WorkerScript { param($CmdExe) Set-StrictMode -Version Latest # pk:ignore @@ -1513,7 +1513,7 @@ Reset-Harness $quickCts = [System.Threading.CancellationTokenSource]::new() $quickCrash = [System.Collections.Generic.List[string]]::new() $quickPolls = @{ Count = 0 } -$null = Invoke-PkRunspaceJobs -MaxParallel 1 -Cts $quickCts -DrainTimeoutSeconds 20 -JobParams (New-JobList -Jobs @(@{ Cmd = $cmdExe; Dir = $quickDir })) ` +$null = Invoke-PkRunspaceBatch -MaxConcurrent 1 -Cts $quickCts -AbortTimeoutSeconds 20 -JobParams (New-JobList -Jobs @(@{ Cmd = $cmdExe; Dir = $quickDir })) ` -PollCallback { $quickPolls.Count++; if ($quickPolls.Count -eq 3) { $quickCts.Cancel() } }.GetNewClosure() ` -JobCrashedHandler { param($e) $quickCrash.Add([string]$e.Exception.InnerException.Message) }.GetNewClosure() -WorkerScript { param($Cmd, $Dir) @@ -1560,7 +1560,7 @@ $ownTokenEngine = { $results = [System.Collections.Generic.List[hashtable]]::new() $poll = @{ Count = 0 } $sw = [System.Diagnostics.Stopwatch]::StartNew() -$out = Invoke-PkRunspaceJobs -WorkerScript $ownTokenEngine -JobParams @{ PingExe = $pingExe } -MaxParallel 1 -DrainTimeoutSeconds 20 ` +$out = Invoke-PkRunspaceBatch -WorkerScript $ownTokenEngine -JobParams @{ PingExe = $pingExe } -MaxConcurrent 1 -AbortTimeoutSeconds 20 ` -ResultHandler { param($r) $results.Add($r) }.GetNewClosure() ` -PollCallback { $poll.Count++; if ($poll.Count -eq 15) { Request-PkAbort } }.GetNewClosure() $sw.Stop() @@ -1581,7 +1581,7 @@ $shapeOne = Invoke-PkProcessWithTimeout -FilePath $cmdExe -Arguments '/c exit 0' Test-Assert ((Get-HarnessShape $shapeOne) -eq 'ExitCode,Stdout,Stderr,StreamTimedOut,StreamError,Duration,StdoutDroppedChars,StderrDroppedChars') ("Invoke-PkProcessWithTimeout returns an object (" + (Get-HarnessShape $shapeOne) + ")") $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) } +$shapeJobs = Invoke-PkRunspaceBatch -MaxConcurrent 1 -JobParams @{ Id = 1 } -WorkerScript { param($Id) } 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] @@ -1782,7 +1782,7 @@ Reset-Harness $presser = Start-HarnessPresses $sw = [System.Diagnostics.Stopwatch]::StartNew() $rsOut = Invoke-PkRun { - Invoke-PkRunspaceJobs -MaxParallel 3 -JobParams (New-JobList -Jobs @(@{ Id = 1 }, @{ Id = 2 }, @{ Id = 3 })) -DrainTimeoutSeconds 25 ` + Invoke-PkRunspaceBatch -MaxConcurrent 3 -JobParams (New-JobList -Jobs @(@{ Id = 1 }, @{ Id = 2 }, @{ Id = 3 })) -AbortTimeoutSeconds 25 ` -WorkerScript { param([int]$Id) for ($i = 0; $i -lt 150; $i++) { [System.Threading.Thread]::Sleep(100) }; $Id } }.GetNewClosure() $sw.Stop() @@ -1795,7 +1795,7 @@ Reset-Harness $parked = @{ AfterDrain = $null } $poll = @{ Count = 0 } Invoke-PkRun { - $null = Invoke-PkRunspaceJobs -MaxParallel 2 -JobParams (New-JobList -Jobs @(@{ Id = 1 }, @{ Id = 2 })) ` + $null = Invoke-PkRunspaceBatch -MaxConcurrent 2 -JobParams (New-JobList -Jobs @(@{ Id = 1 }, @{ Id = 2 })) ` -WorkerScript { param([int]$Id) for ($i = 0; $i -lt 100; $i++) { if (Test-PkCancelRequested) { break }; [System.Threading.Thread]::Sleep(50) }; $Id } ` -PollCallback { $poll.Count++; if ($poll.Count -eq 3) { Request-PkAbort } }.GetNewClosure() $parked.AfterDrain = [PkConsoleCtrl]::DrainComplete.IsSet @@ -2219,7 +2219,7 @@ Push-Location -LiteralPath $workerDir $workerDir = (Get-Location).ProviderPath # the long form; %TEMP% can be an 8.3 path try { $seen = [System.Collections.Generic.List[object]]::new() - $null = Invoke-PkRunspaceJobs -MaxParallel 1 -JobParams (New-JobList -Jobs @(@{ Id = 1 }, @{ Id = 2 }, @{ Id = 3 })) ` + $null = Invoke-PkRunspaceBatch -MaxConcurrent 1 -JobParams (New-JobList -Jobs @(@{ Id = 1 }, @{ Id = 2 }, @{ Id = 3 })) ` -WorkerScript $cleanWorker -ResultHandler { param($r) $seen.Add($r) }.GetNewClosure() $badLocation = @($seen | Where-Object { $_.Location -ine $workerDir } | ForEach-Object { "job " + $_.Id + "=" + $_.Location }) Test-Assert ($seen.Count -eq 3 -and $badLocation.Count -eq 0) ("each worker job starts in the caller's location, even after an earlier job changed folder (wrong: " + ($badLocation -join ', ') + ")") @@ -2232,7 +2232,7 @@ try { Push-Location -LiteralPath 'PkHarnessJobs:\' try { $onDrive = [System.Collections.Generic.List[object]]::new() - $null = Invoke-PkRunspaceJobs -MaxParallel 1 -JobParams (New-JobList -Jobs @(@{ Id = 1 })) ` + $null = Invoke-PkRunspaceBatch -MaxConcurrent 1 -JobParams (New-JobList -Jobs @(@{ Id = 1 })) ` -WorkerScript $cleanWorker -ResultHandler { param($r) $onDrive.Add($r) }.GetNewClosure() } finally { Pop-Location } } finally { Remove-PSDrive -Name PkHarnessJobs -Scope Script } @@ -2312,7 +2312,7 @@ Test-Assert ($plainBatch.Results.Count -eq 2 -and $foreign -eq 0 -and $results.C Test-Assert ($sawTimeout.Value -eq 99) ("a plain -OnComplete reads the caller's `$TimeoutSeconds, not the batch's parameter (" + $sawTimeout.Value + ")") Remove-Variable -Name TimeoutSeconds $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 } +$plainJobs = Invoke-PkRunspaceBatch -MaxConcurrent 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 5) ("a plain -ResultHandler writes to the caller's `$outcome, not the kit's return value (caller's " + $outcome.Count + ")") @@ -2331,12 +2331,12 @@ $lookupScript = Join-Path $env:TEMP ("pk-lookup-" + [guid]::NewGuid().ToString(" function Get-LookupDouble { param(`$N) 2 * `$N } function Get-LookupState { `$script:lookupState } `$out = [System.Collections.Generic.List[object]]::new() -`$null = Invoke-PkRunspaceJobs -MaxParallel 1 -JobParams @(@{ N = 3 }) -SharedFunctionNames Get-LookupDouble -WorkerScript { param(`$N) Get-LookupDouble -N `$N } -ResultHandler { param(`$r) `$out.Add(`$r) }.GetNewClosure() +`$null = Invoke-PkRunspaceBatch -MaxConcurrent 1 -JobParams @(@{ N = 3 }) -SharedFunctionNames Get-LookupDouble -WorkerScript { param(`$N) Get-LookupDouble -N `$N } -ResultHandler { param(`$r) `$out.Add(`$r) }.GetNewClosure() Write-Output ('script fn=' + (`$out -join ',')) function Invoke-LookupOuter { function Get-LookupInner { param(`$N) 10 * `$N } `$inner = [System.Collections.Generic.List[object]]::new() - `$null = Invoke-PkRunspaceJobs -MaxParallel 1 -JobParams @(@{ N = 4 }) -SharedFunctionNames Get-LookupInner -WorkerScript { param(`$N) Get-LookupInner -N `$N } -ResultHandler { param(`$r) `$inner.Add(`$r) }.GetNewClosure() + `$null = Invoke-PkRunspaceBatch -MaxConcurrent 1 -JobParams @(@{ N = 4 }) -SharedFunctionNames Get-LookupInner -WorkerScript { param(`$N) Get-LookupInner -N `$N } -ResultHandler { param(`$r) `$inner.Add(`$r) }.GetNewClosure() Write-Output ('inner fn=' + (`$inner -join ',')) } Invoke-LookupOuter @@ -2358,7 +2358,7 @@ $modPath = Join-Path $modDir 'PkHarnessMod.psm1' function Get-ModPrivate { param($N) 100 + $N } function Invoke-ModWork { $out = [System.Collections.Generic.List[object]]::new() - $null = Invoke-PkRunspaceJobs -MaxParallel 1 -JobParams @(@{ N = 5 }) -SharedFunctionNames Get-ModPrivate -WorkerScript { param($N) Get-ModPrivate -N $N } -ResultHandler { param($r) $out.Add($r) }.GetNewClosure() + $null = Invoke-PkRunspaceBatch -MaxConcurrent 1 -JobParams @(@{ N = 5 }) -SharedFunctionNames Get-ModPrivate -WorkerScript { param($N) Get-ModPrivate -N $N } -ResultHandler { param($r) $out.Add($r) }.GetNewClosure() 'module private=' + ($out -join ',') } Export-ModuleMember -Function Invoke-ModWork @@ -2409,7 +2409,7 @@ if (Test-HarnessSection 'AA' "callbacks inside a worker, and drives made inside # their pk-prefixed names keep them out of a closure-less callback's way. Reset-Harness $workerOut = [System.Collections.Generic.List[object]]::new() -$null = Invoke-PkRunspaceJobs -MaxParallel 1 -JobParams (New-JobList -Jobs @(@{ CmdExe = $cmdExe })) -ResultHandler { param($r) $workerOut.Add($r) }.GetNewClosure() -WorkerScript { +$null = Invoke-PkRunspaceBatch -MaxConcurrent 1 -JobParams (New-JobList -Jobs @(@{ CmdExe = $cmdExe })) -ResultHandler { param($r) $workerOut.Add($r) }.GetNewClosure() -WorkerScript { param($CmdExe) # Every variable name visible from where this runs, up the scope chain. $probe = { @@ -2541,7 +2541,7 @@ Test-Assert ($fileNoDrive -eq 5) ("and so does a FilePath with no drive (" + $fi Reset-Harness $poll = @{ Count = 0 } $softOut = [System.Collections.Generic.List[object]]::new() -$softRun = Invoke-PkRunspaceJobs -MaxParallel 2 -JobParams (New-JobList -Jobs @(@{ Id = 1 }, @{ Id = 2 })) -WorkerScript { +$softRun = Invoke-PkRunspaceBatch -MaxConcurrent 2 -JobParams (New-JobList -Jobs @(@{ Id = 1 }, @{ Id = 2 })) -WorkerScript { param([int]$Id) for ($i = 0; $i -lt 100; $i++) { if (Test-PkCancelRequested) { break }; [System.Threading.Thread]::Sleep(50) } [System.Threading.Thread]::Sleep(500) @@ -2579,7 +2579,7 @@ Test-Assert ($bestPerProgram -lt 90) ("short programs aren't held back by the po $bestPerJob = [double]::MaxValue for ($try = 0; $try -lt 3 -and $bestPerJob -ge 70; $try++) { $sw = [System.Diagnostics.Stopwatch]::StartNew() - $null = Invoke-PkRunspaceJobs -MaxParallel 1 -JobParams (New-JobList -Jobs @(foreach ($i in 1..20) { @{ Id = $i } })) -WorkerScript { + $null = Invoke-PkRunspaceBatch -MaxConcurrent 1 -JobParams (New-JobList -Jobs @(foreach ($i in 1..20) { @{ Id = $i } })) -WorkerScript { param([int]$Id) $spin = [System.Diagnostics.Stopwatch]::StartNew() while ($spin.ElapsedMilliseconds -lt 20) { } @@ -2605,7 +2605,7 @@ $wideCommands = foreach ($i in 1..70) { @{ FilePath = $pingExe; Arguments = '-n $wide = Invoke-PkProcessBatch -Commands $wideCommands -MaxConcurrent 70 $wideOk = @($wide.Results | Where-Object { $_.ExitCode -eq 0 }).Count Test-Assert ($wideOk -eq 70) "70 programs at once all finish ($wideOk ok)" -$wideRun = Invoke-PkRunspaceJobs -MaxParallel 70 -JobParams (New-JobList -Jobs @(foreach ($i in 1..70) { @{ Id = $i } })) -WorkerScript { +$wideRun = Invoke-PkRunspaceBatch -MaxConcurrent 70 -JobParams (New-JobList -Jobs @(foreach ($i in 1..70) { @{ Id = $i } })) -WorkerScript { param([int]$Id) [System.Threading.Thread]::Sleep(500) return $Id @@ -2631,7 +2631,7 @@ $turnLog = [System.Collections.Concurrent.ConcurrentQueue[string]]::new() $turnJobs = New-JobList -Jobs @( @{ Tag = 'A'; DelayMs = 0; Budget = $turnBudget; Log = $turnLog; Exe = $cmdExe }, @{ Tag = 'B'; DelayMs = 300; Budget = $turnBudget; Log = $turnLog; Exe = $cmdExe }) -$null = Invoke-PkRunspaceJobs -MaxParallel 2 -JobParams $turnJobs -ResultHandler { param($r) } -WorkerScript { +$null = Invoke-PkRunspaceBatch -MaxConcurrent 2 -JobParams $turnJobs -ResultHandler { param($r) } -WorkerScript { param([string]$Tag, [int]$DelayMs, [System.Threading.SemaphoreSlim]$Budget, $Log, [string]$Exe) [System.Threading.Thread]::Sleep($DelayMs) $feed = @{ Given = $false } @@ -2647,7 +2647,7 @@ Test-Assert ($turnOrder.Length -eq 60 -and $turnFirstB -ge 0 -and $turnFirstB -l # The same loop inside a worker, where the wait helper is a plain copy. $workerWait = [System.Collections.Generic.List[object]]::new() -$null = Invoke-PkRunspaceJobs -MaxParallel 1 -JobParams (New-JobList -Jobs @(@{ CmdExe = $cmdExe })) -WorkerScript { +$null = Invoke-PkRunspaceBatch -MaxConcurrent 1 -JobParams (New-JobList -Jobs @(@{ CmdExe = $cmdExe })) -WorkerScript { param([string]$CmdExe) $inner = Invoke-PkProcessBatch -Commands @(@{ FilePath = $CmdExe; Arguments = '/d /c exit 0' }, @{ FilePath = $CmdExe; Arguments = '/d /c ping -n 2 127.0.0.1 >nul' }) -MaxConcurrent 2 return @($inner.Results | Where-Object { $_.ExitCode -eq 0 }).Count @@ -2774,7 +2774,7 @@ Reset-Harness # Inside a worker, where the helpers are plain copies and a plain callback sees # the kit's frames: it must read the worker's own $TimeoutSeconds. $limitWorker = [System.Collections.Generic.List[object]]::new() -$limitOut = Invoke-PkRunspaceJobs -MaxParallel 1 -JobParams (New-JobList -Jobs @(@{ PingExe = $pingExe })) -ResultHandler { param($r) $limitWorker.Add($r) }.GetNewClosure() -WorkerScript { +$limitOut = Invoke-PkRunspaceBatch -MaxConcurrent 1 -JobParams (New-JobList -Jobs @(@{ PingExe = $pingExe })) -ResultHandler { param($r) $limitWorker.Add($r) }.GetNewClosure() -WorkerScript { param([string]$PingExe) $TimeoutSeconds = 99 $seen = @{ Value = $null } @@ -2881,7 +2881,7 @@ Test-Assert ((Get-StartMessageCount "*ProcessDispatch: a job couldn't start:*Tim Reset-Harness $collapseWorker = [System.Collections.Generic.List[object]]::new() -$collapseOut = Invoke-PkRunspaceJobs -MaxParallel 1 -JobParams (New-JobList -Jobs @(@{ Missing = $missing })) -ResultHandler { param($r) $collapseWorker.Add($r) }.GetNewClosure() -WorkerScript { +$collapseOut = Invoke-PkRunspaceBatch -MaxConcurrent 1 -JobParams (New-JobList -Jobs @(@{ Missing = $missing })) -ResultHandler { param($r) $collapseWorker.Add($r) }.GetNewClosure() -WorkerScript { param([string]$Missing) $batch = Invoke-PkProcessBatch -Commands @(@{ FilePath = $Missing }, @{ FilePath = $Missing }, @{ FilePath = $Missing }) -MaxConcurrent 2 return @{ Failed = @($batch.Results | Where-Object { $_.StartError }).Count } @@ -3084,7 +3084,7 @@ if ($compiled) { # Inside a worker, where the kit's functions are plain copies. Reset-Harness $argWorker = [System.Collections.Generic.List[object]]::new() - $argOut = Invoke-PkRunspaceJobs -MaxParallel 1 -JobParams (New-JobList -Jobs @(@{ Exe = $argvExe })) -ResultHandler { param($r) $argWorker.Add($r) }.GetNewClosure() -WorkerScript { + $argOut = Invoke-PkRunspaceBatch -MaxConcurrent 1 -JobParams (New-JobList -Jobs @(@{ Exe = $argvExe })) -ResultHandler { param($r) $argWorker.Add($r) }.GetNewClosure() -WorkerScript { param([string]$Exe) $batch = Invoke-PkProcessBatch -Commands @(@{ FilePath = $Exe; Arguments = @('two words', 'x') }) -MaxConcurrent 1 return @{ Stdout = $batch.Results[0].Stdout; StartError = $batch.Results[0].StartError } @@ -3104,8 +3104,8 @@ if (Test-HarnessSection 'AF' "parameter handling: advanced functions, aliases, t $simpleFunctions = @($publicFunctions | Where-Object { -not (Get-Command $_).CmdletBinding }) Test-Assert ($simpleFunctions.Count -eq 0) ("every public function rejects unknown arguments (not: " + ($simpleFunctions -join ', ') + ")") $threw = $null -try { $null = Initialize-ParallelKit -MaxParallel 4 } catch { $threw = [string]$_ } -Test-Assert ($threw -like '*MaxParallel*') "Initialize-ParallelKit -MaxParallel (the engine's name) is an error, not ignored" +try { $null = Initialize-ParallelKit -AbortTimeoutSeconds 4 } catch { $threw = [string]$_ } +Test-Assert ($threw -like '*AbortTimeoutSeconds*') "Initialize-ParallelKit -AbortTimeoutSeconds (an engine's parameter) is an error, not ignored" $threw = $null try { $null = Test-PkAbortSignal 'extra' } catch { $threw = [string]$_ } Test-Assert ($null -ne $threw) "Test-PkAbortSignal refuses an argument it doesn't take" @@ -3121,34 +3121,47 @@ $threw = $null try { $null = Invoke-PkProcessBatch -Commands @(@{ FilePath = $cmdExe; Arguments = '/c exit 0' }) -MaxConcurrent 0 } catch { $threw = [string]$_ } Test-Assert ($threw -like 'Invoke-PkProcessBatch:*') ("the batch's own -MaxConcurrent error names the batch (" + $threw + ")") -# The concurrency and abort-wait names work on every engine. -Reset-Harness -$aliasBatchParams = @{ Commands = @(@{ FilePath = $cmdExe; Arguments = '/c exit 3' }); MaxParallel = 2; DrainTimeoutSeconds = 5 } -$aliasBatch = $null -try { $aliasBatch = Invoke-PkProcessBatch @aliasBatchParams } catch { Write-Host " batch alias threw: $_" } -Test-Assert ($null -ne $aliasBatch -and $aliasBatch.Results[0].ExitCode -eq 3) "the batch takes -MaxParallel and -DrainTimeoutSeconds" -$aliasRunParams = @{ WorkerScript = { param($Id) $Id * 2 }; JobParams = (New-JobList -Jobs @(@{ Id = 21 })); MaxConcurrent = 2; AbortTimeoutSeconds = 5 } -$aliasRunResults = [System.Collections.Generic.List[object]]::new() -try { $null = Invoke-PkRunspaceJobs @aliasRunParams -ResultHandler { param($r) $aliasRunResults.Add($r) }.GetNewClosure() } catch { Write-Host " runspace alias threw: $_" } -Test-Assert ($aliasRunResults.Count -eq 1 -and $aliasRunResults[0] -eq 42) "Invoke-PkRunspaceJobs takes -MaxConcurrent and -AbortTimeoutSeconds" -$aliasFeed = @{ Given = $false } -$aliasDispatch = $null +# The concurrency and abort-wait names are the same on every engine, and each +# has only the one name. +Reset-Harness +$oldNames = foreach ($engine in 'Invoke-PkProcessBatch', 'Invoke-PkProcessDispatch', 'Invoke-PkRunspaceBatch') { + $engineParams = (Get-Command $engine).Parameters + foreach ($name in 'MaxConcurrent', 'AbortTimeoutSeconds') { + if (-not $engineParams.ContainsKey($name)) { $engine + ' has no -' + $name } + elseif ($engineParams[$name].Aliases.Count -gt 0) { $engine + ' -' + $name + ' has aliases' } + } +} +Test-Assert (@($oldNames).Count -eq 0) ("every engine takes -MaxConcurrent and -AbortTimeoutSeconds, with no aliases (" + ($oldNames -join '; ') + ")") +$threw = $null +try { $null = Invoke-PkRunspaceBatch -MaxParallel 1 -JobParams @(@{ Id = 1 }) -WorkerScript { param($Id) $Id } } catch { $threw = [string]$_ } +Test-Assert ($threw -like "*parameter name 'MaxParallel'*") ("the old name -MaxParallel is an error (" + $threw + ")") +Test-Assert ($null -eq (Get-Command Invoke-PkRunspaceJobs -ErrorAction SilentlyContinue)) "Invoke-PkRunspaceJobs, the old name of Invoke-PkRunspaceBatch, is gone" +$sameNameBatchParams = @{ Commands = @(@{ FilePath = $cmdExe; Arguments = '/c exit 3' }); MaxConcurrent = 2; AbortTimeoutSeconds = 5 } +$sameNameBatch = $null +try { $sameNameBatch = Invoke-PkProcessBatch @sameNameBatchParams } catch { Write-Host " batch threw: $_" } +Test-Assert ($null -ne $sameNameBatch -and $sameNameBatch.Results[0].ExitCode -eq 3) "the batch takes -MaxConcurrent and -AbortTimeoutSeconds" +$sameNameRunParams = @{ WorkerScript = { param($Id) $Id * 2 }; JobParams = (New-JobList -Jobs @(@{ Id = 21 })); MaxConcurrent = 2; AbortTimeoutSeconds = 5 } +$sameNameRunResults = [System.Collections.Generic.List[object]]::new() +try { $null = Invoke-PkRunspaceBatch @sameNameRunParams -ResultHandler { param($r) $sameNameRunResults.Add($r) }.GetNewClosure() } catch { Write-Host " runspace batch threw: $_" } +Test-Assert ($sameNameRunResults.Count -eq 1 -and $sameNameRunResults[0] -eq 42) "Invoke-PkRunspaceBatch takes -MaxConcurrent and -AbortTimeoutSeconds" +$sameNameFeed = @{ Given = $false } +$sameNameDispatch = $null try { - $aliasDispatch = Invoke-PkProcessDispatch -MaxParallel 1 -DrainTimeoutSeconds 5 ` - -GroupProvider { if ($aliasFeed.Given) { return $null }; $aliasFeed.Given = $true; return 'g' }.GetNewClosure() ` + $sameNameDispatch = Invoke-PkProcessDispatch -MaxConcurrent 1 -AbortTimeoutSeconds 5 ` + -GroupProvider { if ($sameNameFeed.Given) { return $null }; $sameNameFeed.Given = $true; return 'g' }.GetNewClosure() ` -JobBuilder { param($g) return @(@{ FilePath = $cmdExe; Arguments = '/c exit 0' }) }.GetNewClosure() ` -JobFinalize { param($job, $q) $null = Complete-PkProcess -Job $job } -} catch { Write-Host " dispatcher alias threw: $_" } -Test-Assert ($null -ne $aliasDispatch -and $aliasDispatch.GroupResults.Count -eq 1) "the dispatcher takes -MaxParallel and -DrainTimeoutSeconds" +} catch { Write-Host " dispatcher threw: $_" } +Test-Assert ($null -ne $sameNameDispatch -and $sameNameDispatch.GroupResults.Count -eq 1) "the dispatcher takes -MaxConcurrent and -AbortTimeoutSeconds" # -CheckWorkerSafety: on unless turned off, however it's passed. $unsafeWorker = { param($Id) $null = [Func[int]]{ 1 } } $threw = $false -try { $null = Invoke-PkRunspaceJobs -WorkerScript $unsafeWorker -JobParams (New-JobList -Jobs @(@{ Id = 1 })) -MaxParallel 1 } catch { $threw = ($_.ToString() -like '*Func*') } +try { $null = Invoke-PkRunspaceBatch -WorkerScript $unsafeWorker -JobParams (New-JobList -Jobs @(@{ Id = 1 })) -MaxConcurrent 1 } catch { $threw = ($_.ToString() -like '*Func*') } Test-Assert $threw "the worker-safety check is on when -CheckWorkerSafety isn't given" $safetyOff = @{ CheckWorkerSafety = $false } $out = $null -try { $out = Invoke-PkRunspaceJobs -WorkerScript $unsafeWorker -JobParams (New-JobList -Jobs @(@{ Id = 1 })) -MaxParallel 1 @safetyOff } catch { Write-Host " splatted opt-out threw: $_" } +try { $out = Invoke-PkRunspaceBatch -WorkerScript $unsafeWorker -JobParams (New-JobList -Jobs @(@{ Id = 1 })) -MaxConcurrent 1 @safetyOff } catch { Write-Host " splatted opt-out threw: $_" } Test-Assert ($null -ne $out -and $out.CrashedCount -eq 0) "a splatted CheckWorkerSafety = `$false turns it off" Reset-Harness Write-Host "" @@ -3231,7 +3244,7 @@ $stopWatch = [System.Diagnostics.Stopwatch]::StartNew() $stopPoll = { if ($stopWatch.Elapsed.TotalSeconds -ge 1 -and (Get-LimitPingCount 46) -ge 2) { $stopCts.Cancel() } elseif ($stopWatch.Elapsed.TotalSeconds -ge 15) { $stopCts.Cancel() } }.GetNewClosure() $stopOut = $null try { - $stopOut = Invoke-PkRunspaceJobs -MaxParallel 1 -Cts $stopCts -DrainTimeoutSeconds 1 -AbortWaitMessage '' -PollCallback $stopPoll ` + $stopOut = Invoke-PkRunspaceBatch -MaxConcurrent 1 -Cts $stopCts -AbortTimeoutSeconds 1 -AbortWaitMessage '' -PollCallback $stopPoll ` -JobParams (New-JobList -Jobs @(@{ Ping = $pingExe })) ` -WorkerScript { param($Ping) $null = Invoke-PkProcessBatch -MaxConcurrent 2 -Commands @(@{ FilePath = $Ping; Arguments = '-n 46 127.0.0.1' }, @{ FilePath = $Ping; Arguments = '-n 46 127.0.0.1' }) } } catch { Write-Host " force-stopped worker run threw: $_" } @@ -3458,19 +3471,19 @@ $d = Invoke-KwDispatch -Extra @{ JobBuilder = { param($g) @{ FilePath = 'cmd.exe $kwOk = ($d.Done -eq 1 -and $d.Result.GroupResults.Count -eq 1); $kwDetail = "done " + $d.Done '@ '-ResultHandler' = @' -$o = Invoke-PkRunspaceJobs -MaxParallel 1 -JobParams @(@{ Id = 1 }) -WorkerScript { param($Id) 1; 2; 3 } -ResultHandler { param($r) $kwCount.N++; KEYWORD } +$o = Invoke-PkRunspaceBatch -MaxConcurrent 1 -JobParams @(@{ Id = 1 }) -WorkerScript { param($Id) 1; 2; 3 } -ResultHandler { param($r) $kwCount.N++; KEYWORD } $kwOk = ($kwCount.N -eq 3 -and -not $o.Aborted); $kwDetail = "results " + $kwCount.N '@ '-PollCallback' = @' -$o = Invoke-PkRunspaceJobs -MaxParallel 1 -JobParams @(@{ Id = 1 }, @{ Id = 2 }) -WorkerScript { param($Id) Start-Sleep -Milliseconds 300; $Id } -ResultHandler { param($r) $kwList.Add($r) } -PollCallback { $kwCount.N++; KEYWORD } +$o = Invoke-PkRunspaceBatch -MaxConcurrent 1 -JobParams @(@{ Id = 1 }, @{ Id = 2 }) -WorkerScript { param($Id) Start-Sleep -Milliseconds 300; $Id } -ResultHandler { param($r) $kwList.Add($r) } -PollCallback { $kwCount.N++; KEYWORD } $kwOk = ($kwList.Count -eq 2 -and $o.ForceStoppedCount -eq 0); $kwDetail = "results " + $kwList.Count '@ '-NextJobProvider' = @' -$o = Invoke-PkRunspaceJobs -MaxParallel 1 -NextJobProvider { $kwCount.N++; if ($kwCount.N -le 3) { return @{ Id = $kwCount.N } }; KEYWORD } -WorkerScript { param($Id) $Id } -ResultHandler { param($r) $kwList.Add($r) } +$o = Invoke-PkRunspaceBatch -MaxConcurrent 1 -NextJobProvider { $kwCount.N++; if ($kwCount.N -le 3) { return @{ Id = $kwCount.N } }; KEYWORD } -WorkerScript { param($Id) $Id } -ResultHandler { param($r) $kwList.Add($r) } $kwOk = ($kwList.Count -eq 3); $kwDetail = "results " + $kwList.Count '@ '-JobCrashedHandler' = @' -$o = Invoke-PkRunspaceJobs -MaxParallel 1 -JobParams @(@{ Id = 1 }, @{ Id = 2 }) -WorkerScript { param($Id) throw "boom" } -JobCrashedHandler { param($e) $kwCount.N++; KEYWORD } +$o = Invoke-PkRunspaceBatch -MaxConcurrent 1 -JobParams @(@{ Id = 1 }, @{ Id = 2 }) -WorkerScript { param($Id) throw "boom" } -JobCrashedHandler { param($e) $kwCount.N++; KEYWORD } $kwOk = ($kwCount.N -eq 2 -and $o.CrashedCount -eq 2); $kwDetail = "handler calls " + $kwCount.N + ", crashed " + $o.CrashedCount '@ 'message handler' = @' @@ -3510,7 +3523,7 @@ foreach ($kwName in $kwCases.Keys) { # The warning names the parameter and the engine it was given to. $kwEngine = 'ProcessDispatch' if ($kwName -like '*(batch)') { $kwEngine = 'Invoke-PkProcessBatch' } - elseif ($kwName -in '-ResultHandler', '-PollCallback', '-NextJobProvider', '-JobCrashedHandler') { $kwEngine = 'Invoke-PkRunspaceJobs' } + elseif ($kwName -in '-ResultHandler', '-PollCallback', '-NextJobProvider', '-JobCrashedHandler') { $kwEngine = 'Invoke-PkRunspaceBatch' } $kwExpected = $kwEngine + ': ' + ($kwName -split ' ')[0] + " used 'continue' or 'break'" $kwWarned = ($null -ne $kwOut -and $kwOut.Warned -eq 1 -and $kwOut.Text.StartsWith($kwExpected)) } @@ -3550,7 +3563,7 @@ if (Test-HarnessSection 'AI' "a worker's non-terminating errors are recorded wit 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 { +$errRun = Invoke-PkRunspaceBatch -MaxConcurrent 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 @@ -3567,7 +3580,7 @@ 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 { +$errRun = Invoke-PkRunspaceBatch -MaxConcurrent 1 -JobParams (New-JobList -Jobs @(@{ Id = 7 })) -WorkerScript { param([int]$Id) Write-Error "soft before the crash" throw "hard crash" @@ -3579,7 +3592,7 @@ $errPrinted = @($script:messages | Where-Object { $_.Message -like 'Runspace err 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) } +$errEmpty = Invoke-PkRunspaceBatch -MaxConcurrent 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 @@ -3658,7 +3671,7 @@ $threw = $null try { Write-PkMessage 'pk-level-bad' -Level Debug } catch { $threw = [string]$_ } Test-Assert ($threw -like '*Level*Debug*' -and (Get-StartMessageCount '*pk-level-bad*') -eq 0) ("an unknown -Level is an error (" + $threw + ")") Reset-Harness -$null = Invoke-PkRunspaceJobs -MaxParallel 1 -JobParams (New-JobList -Jobs @(@{ Id = 1 })) -WorkerScript { param($Id) Write-PkMessage 'pk-level-worker' -Level Warning } +$null = Invoke-PkRunspaceBatch -MaxConcurrent 1 -JobParams (New-JobList -Jobs @(@{ Id = 1 })) -WorkerScript { param($Id) Write-PkMessage 'pk-level-worker' -Level Warning } $apiLevels = (@($script:messages | Where-Object { $_.Message -eq 'pk-level-worker' } | ForEach-Object { $_.Level }) -join ',') Test-Assert ($apiLevels -ceq 'Warn') ("and the same from a worker (" + $apiLevels + ")") @@ -3870,7 +3883,7 @@ function Get-HarnessForceStopDrift { $steps = [System.Collections.Generic.List[string]]::new() $siblings = $loop.Parent.Statements $at = $siblings.IndexOf($loop) - if ($at -lt 1) { $problems.Add('nothing runs before the stop loop over ' + $list + ' (expected Stop-PkJobProcesses)'); continue } + if ($at -lt 1) { $problems.Add('nothing runs before the stop loop over ' + $list + ' (expected Stop-PkJobProcess)'); continue } $before = $siblings[$at - 1] $steps.Add((Get-HarnessCodeText -Text $before.Extent.Text).Replace($list, '$LIST')) $skipped = $false @@ -3902,7 +3915,7 @@ function Get-HarnessUnguardedCallbacks { # this list. Invoke-PkRun's `& $ScriptBlock` is the run itself, not called # from a loop. Returns @{ Calls; Problems }. param([string]$Source) - $internal = @('$pkNewBatchResult', '$pkGetStartFailureCause', '$pkGetJobTimeLimit', '$pkGetJobMaxOutputChars', '$pkGetJobSwitch', '$pkStopExitedJobTree', '$pkReportStartFailure', '$pkStartProcessCore', '$pkWriteCallbackLoopWarning', '$pkWriteMessage', '$pkCompleteProcess') + $internal = @('$pkNewBatchResult', '$pkGetStartFailureCause', '$pkGetJobTimeLimit', '$pkGetJobOutputLimit', '$pkGetJobSwitch', '$pkStopExitedJobTree', '$pkReportStartFailure', '$pkStartProcessCore', '$pkWriteCallbackLoopWarning', '$pkWriteMessage', '$pkCompleteProcess') $problems = [System.Collections.Generic.List[string]]::new() $tokens = $null; $errors = $null $ast = [System.Management.Automation.Language.Parser]::ParseInput($Source, [ref]$tokens, [ref]$errors) @@ -4065,7 +4078,7 @@ $growthCases = [ordered]@{ 'Start-PkProcess' = @{ Measured = 100; Run = { $s = Start-PkProcess -FilePath $cmdExe -Arguments '/d /c exit 0'; $null = Complete-PkProcess $s -Dispose } } 'Start-PkProcess, Process.Start fallback' = @{ Measured = 100; Fallback = $true; Run = { $s = Start-PkProcess -FilePath $cmdExe -Arguments '/d /c exit 0'; $null = Complete-PkProcess $s -Dispose } } 'Invoke-PkProcessBatch' = @{ Measured = 60; Run = { $null = Invoke-PkProcessBatch -MaxConcurrent 2 -Commands @(@{ FilePath = $cmdExe; Arguments = '/d /c exit 0' }, @{ FilePath = $cmdExe; Arguments = '/d /c exit 0' }) } } - 'Invoke-PkRunspaceJobs' = @{ Measured = 80; SkipHandles = $true; Run = { $null = Invoke-PkRunspaceJobs -WorkerScript { param([int]$Id) $Id } -JobParams @(@{ Id = 1 }, @{ Id = 2 }) -MaxParallel 2 } } + 'Invoke-PkRunspaceBatch' = @{ Measured = 80; SkipHandles = $true; Run = { $null = Invoke-PkRunspaceBatch -WorkerScript { param([int]$Id) $Id } -JobParams @(@{ Id = 1 }, @{ Id = 2 }) -MaxConcurrent 2 } } } foreach ($growthName in $growthCases.Keys) { $growthCase = $growthCases[$growthName] @@ -4287,7 +4300,7 @@ foreach ($rsName in 'ResultHandler', 'PollCallback', 'NextJobProvider') { Reset-Harness $seen = [System.Collections.Concurrent.ConcurrentDictionary[int, string]]::new() $st = @{ Calls = 0; Running = -1 } - $p = @{ WorkerScript = $rsWorker; MaxParallel = 3 } + $p = @{ WorkerScript = $rsWorker; MaxConcurrent = 3 } switch ($rsName) { 'ResultHandler' { # Job 1 returns at once, while jobs 2 and 3 run on. @@ -4304,7 +4317,7 @@ foreach ($rsName in 'ResultHandler', 'PollCallback', 'NextJobProvider') { } $rsError = $null $sw = [System.Diagnostics.Stopwatch]::StartNew() - try { $null = Invoke-PkRunspaceJobs @p } catch { $rsError = [string]$_ } + try { $null = Invoke-PkRunspaceBatch @p } catch { $rsError = [string]$_ } $sw.Stop() # The pool closes in the background once the stopped workers have ended. for ($t = 0; $t -lt 60 -and @(Get-Runspace).Count -gt $rsBaseline; $t++) { Start-Sleep -Milliseconds 50 } @@ -4371,7 +4384,7 @@ foreach ($njCase in 'two jobs', 'job then null') { $njProvider = { $nj.Calls++; if ($nj.Calls -gt 1) { return $null }; @{ Id = 1 }; return @{ Id = 2 } }.GetNewClosure() # A second call (only reached if the first didn't end the run) gives job 3, then the end. if ($njCase -eq 'job then null') { $njProvider = { $nj.Calls++; if ($nj.Calls -gt 2) { return $null }; if ($nj.Calls -eq 2) { return @{ Id = 3 } }; @{ Id = 1 }; return $null }.GetNewClosure() } - $null = Invoke-PkRunspaceJobs -WorkerScript { param([int]$Id) $Id } -NextJobProvider $njProvider -MaxParallel 1 -ResultHandler { param($r) $njRan.Add($r) }.GetNewClosure() + $null = Invoke-PkRunspaceBatch -WorkerScript { param([int]$Id) $Id } -NextJobProvider $njProvider -MaxConcurrent 1 -ResultHandler { param($r) $njRan.Add($r) }.GetNewClosure() $njWarned = @($script:messages | Where-Object { $_.Message -like '*-NextJobProvider*' -and $_.Level -eq 'Warn' }).Count $njExpected = '2' if ($njCase -eq 'job then null') { $njExpected = '' } @@ -4402,7 +4415,7 @@ $tlCases = [ordered]@{ 'Invoke-PkProcessDispatch -TimeoutSeconds Infinity' = @{ Expect = 'Invoke-PkProcessDispatch: -TimeoutSeconds'; Run = { $null = Invoke-PkProcessDispatch @tlDispatch -TimeoutSeconds ([double]::PositiveInfinity) } } 'Invoke-PkProcessBatch -AbortTimeoutSeconds -5' = @{ Expect = 'Invoke-PkProcessBatch: -AbortTimeoutSeconds'; Run = { $null = Invoke-PkProcessBatch -Commands @($tlJob) -AbortTimeoutSeconds -5 } } 'Invoke-PkProcessDispatch -AbortTimeoutSeconds -5' = @{ Expect = 'Invoke-PkProcessDispatch: -AbortTimeoutSeconds'; Run = { $null = Invoke-PkProcessDispatch @tlDispatch -AbortTimeoutSeconds -5 } } - 'Invoke-PkRunspaceJobs -DrainTimeoutSeconds -5' = @{ Expect = 'Invoke-PkRunspaceJobs: -DrainTimeoutSeconds'; Run = { $null = Invoke-PkRunspaceJobs -WorkerScript { param($Id) $Id } -JobParams @(@{ Id = 1 }) -MaxParallel 1 -DrainTimeoutSeconds -5 } } + 'Invoke-PkRunspaceBatch -AbortTimeoutSeconds -5' = @{ Expect = 'Invoke-PkRunspaceBatch: -AbortTimeoutSeconds'; Run = { $null = Invoke-PkRunspaceBatch -WorkerScript { param($Id) $Id } -JobParams @(@{ Id = 1 }) -MaxConcurrent 1 -AbortTimeoutSeconds -5 } } 'Invoke-PkProcessWithTimeout -StreamTimeoutMs -1' = @{ Expect = 'Invoke-PkProcessWithTimeout: -StreamTimeoutMs'; Run = { $null = Invoke-PkProcessWithTimeout -FilePath $cmdExe -Arguments '/d /c exit 0' -StreamTimeoutMs -1 } } 'Complete-PkProcess -StreamTimeoutMs -1' = @{ Expect = 'Complete-PkProcess: -StreamTimeoutMs'; Started = $true; Run = { param($s) $null = Complete-PkProcess $s -StreamTimeoutMs -1 } } 'Wait-PkProcess -TimeoutMs -1' = @{ Expect = 'Wait-PkProcess: -TimeoutMs'; Started = $true; Run = { param($s) $null = Wait-PkProcess -Process $s['Proc'] -TimeoutMs -1 } } @@ -4426,9 +4439,9 @@ try { $null = Wait-PkProcess -Process $s['Proc'] -TimeoutMs 5000 $null = Complete-PkProcess $s -StreamTimeoutMs 0 -Dispose $null = Invoke-PkProcessBatch -Commands @($tlJob) -AbortTimeoutSeconds 0 -TimeoutSeconds 0 - $null = Invoke-PkRunspaceJobs -WorkerScript { param($Id) $Id } -JobParams @(@{ Id = 1 }) -MaxParallel 1 -DrainTimeoutSeconds 0 + $null = Invoke-PkRunspaceBatch -WorkerScript { param($Id) $Id } -JobParams @(@{ Id = 1 }) -MaxConcurrent 1 -AbortTimeoutSeconds 0 } catch { $tlZero = $_.ToString() } -Test-Assert ($null -eq $tlZero) ("0 is still accepted for -TimeoutMs, -StreamTimeoutMs, -AbortTimeoutSeconds, -DrainTimeoutSeconds and -TimeoutSeconds (error: " + $tlZero + ")") +Test-Assert ($null -eq $tlZero) ("0 is still accepted for -TimeoutMs, -StreamTimeoutMs, -AbortTimeoutSeconds and -TimeoutSeconds (error: " + $tlZero + ")") Write-Host "" } @@ -4444,7 +4457,7 @@ $tkKit = Get-Module ParallelKit $tkIds = [int[]](1000000..1002999) $tkLimit = 32000 - (Join-Path $env:SystemRoot 'System32\taskkill.exe').Length $tkLists = $null -try { $tkLists = & $tkKit Split-PkTaskkillArguments -Ids $tkIds -MaxLength $tkLimit } catch { $tkLists = @() } # a list returned whole: assigned, not wrapped +try { $tkLists = & $tkKit Split-PkTaskkillArgumentList -Ids $tkIds -MaxLength $tkLimit } catch { $tkLists = @() } # a list returned whole: assigned, not wrapped $tkSeen = @{} $tkTooLong = 0 foreach ($line in $tkLists) { @@ -4930,26 +4943,26 @@ Reset-Harness $bcRan = [System.Collections.Generic.List[object]]::new() $bcError = $null try { - $null = Invoke-PkRunspaceJobs -MaxParallel 2 -JobParams @(@{ Name = 'a'; Id = 1 }, @{ Id = 2 }) -WorkerScript { param([Parameter(Mandatory)][string]$Name, $Id) $Id } -ResultHandler { param($r) $bcRan.Add($r) }.GetNewClosure() + $null = Invoke-PkRunspaceBatch -MaxConcurrent 2 -JobParams @(@{ Name = 'a'; Id = 1 }, @{ Id = 2 }) -WorkerScript { param([Parameter(Mandatory)][string]$Name, $Id) $Id } -ResultHandler { param($r) $bcRan.Add($r) }.GetNewClosure() } catch { $bcError = [string]$_ } Test-Assert ($bcError -match "job 1 doesn't supply 'Name'" -and $bcError -match 'Nothing was started' -and $bcRan.Count -eq 0) ("-JobParams: a job missing a mandatory parameter is refused before anything starts (" + $bcError + "; ran " + $bcRan.Count + ")") # The same for a -NextJobProvider job, as it arrives. $bcFeed = [System.Collections.Generic.Queue[hashtable]]::new(); $bcFeed.Enqueue(@{ Name = 'a' }); $bcFeed.Enqueue(@{ Other = 1 }) $bcError = $null try { - $null = Invoke-PkRunspaceJobs -MaxParallel 1 -NextJobProvider { if ($bcFeed.Count -gt 0) { return $bcFeed.Dequeue() }; return $null }.GetNewClosure() -WorkerScript { param([Parameter(Mandatory)][string]$Name, $Other) $Name } + $null = Invoke-PkRunspaceBatch -MaxConcurrent 1 -NextJobProvider { if ($bcFeed.Count -gt 0) { return $bcFeed.Dequeue() }; return $null }.GetNewClosure() -WorkerScript { param([Parameter(Mandatory)][string]$Name, $Other) $Name } } catch { $bcError = [string]$_ } Test-Assert ($bcError -match "doesn't supply 'Name'") ("-NextJobProvider: a job missing a mandatory parameter is refused as it arrives (" + $bcError + ")") # A case-sensitive hashtable's 'name' binds to $Name, so it isn't missing. $bcJob = [hashtable]::new(); $bcJob['name'] = 'a' $bcOut = $null; $bcError = $null -try { $bcOut = Invoke-PkRunspaceJobs -MaxParallel 1 -JobParams @(,$bcJob) -WorkerScript { param([Parameter(Mandatory)][string]$Name) $Name } } catch { $bcError = [string]$_ } +try { $bcOut = Invoke-PkRunspaceBatch -MaxConcurrent 1 -JobParams @(,$bcJob) -WorkerScript { param([Parameter(Mandatory)][string]$Name) $Name } } catch { $bcError = [string]$_ } Test-Assert ($null -eq $bcError -and $null -ne $bcOut -and $bcOut.Errors.Count -eq 0) ("a mandatory parameter supplied in another case, in a case-sensitive hashtable, isn't counted as missing (" + $bcError + ")") # Not refused: a mandatory CancelToken (the kit supplies it), Mandatory = # $false, and parameter sets (which parameters are needed depends on the set). -$bcOut = Invoke-PkRunspaceJobs -MaxParallel 2 -JobParams @(@{ Id = 1 }) -WorkerScript { param([Parameter(Mandatory)][System.Threading.CancellationToken]$CancelToken, [Parameter(Mandatory = $false)]$Opt, $Id) $Id } +$bcOut = Invoke-PkRunspaceBatch -MaxConcurrent 2 -JobParams @(@{ Id = 1 }) -WorkerScript { param([Parameter(Mandatory)][System.Threading.CancellationToken]$CancelToken, [Parameter(Mandatory = $false)]$Opt, $Id) $Id } Test-Assert ($bcOut.Errors.Count -eq 0) ("a mandatory CancelToken and Mandatory = `$false aren't counted as missing (" + $bcOut.Errors.Count + " errors)") -$bcOut = Invoke-PkRunspaceJobs -MaxParallel 2 -JobParams @(@{ A = 1 }) -WorkerScript { param([Parameter(Mandatory, ParameterSetName = 'A')]$A, [Parameter(Mandatory, ParameterSetName = 'B')]$B) $A } +$bcOut = Invoke-PkRunspaceBatch -MaxConcurrent 2 -JobParams @(@{ A = 1 }) -WorkerScript { param([Parameter(Mandatory, ParameterSetName = 'A')]$A, [Parameter(Mandatory, ParameterSetName = 'B')]$B) $A } Test-Assert ($bcOut.Errors.Count -eq 0) ("a worker with parameter sets isn't refused for the other set's mandatory parameter (" + $bcOut.Errors.Count + " errors)") # A code page read from a CSV or config file is a string. @@ -5039,7 +5052,7 @@ try { # Inside a worker the kit isn't a module: the default poll still carries # the limit it was given. $bdRes = [System.Collections.Generic.List[object]]::new() - $bdOut = Invoke-PkRunspaceJobs -MaxParallel 1 -JobParams @(@{ Cmd = $cmdExe }) -ResultHandler { param($r) $bdRes.Add($r) }.GetNewClosure() -WorkerScript { + $bdOut = Invoke-PkRunspaceBatch -MaxConcurrent 1 -JobParams @(@{ Cmd = $cmdExe }) -ResultHandler { param($r) $bdRes.Add($r) }.GetNewClosure() -WorkerScript { param($Cmd) $wsw = [System.Diagnostics.Stopwatch]::StartNew() $wb = Invoke-PkProcessBatch -StreamTimeoutMs 1000 -Commands @(@{ FilePath = $Cmd; Arguments = '/d /c echo held& start /b ping -n 9 -w 4321 127.0.0.1 >nul' }) @@ -5650,7 +5663,7 @@ try { # Inside a worker. Reset-Harness $bjWorker = [System.Collections.Generic.List[object]]::new() - $bjOut = Invoke-PkRunspaceJobs -MaxParallel 1 -JobParams @{ Cmd = $cmdExe; Line = $bjHeld } -ResultHandler { param($r) $bjWorker.Add($r) }.GetNewClosure() -WorkerScript { + $bjOut = Invoke-PkRunspaceBatch -MaxConcurrent 1 -JobParams @{ Cmd = $cmdExe; Line = $bjHeld } -ResultHandler { param($r) $bjWorker.Add($r) }.GetNewClosure() -WorkerScript { param([string]$Cmd, [string]$Line) $one = Invoke-PkProcessWithTimeout -FilePath $Cmd -Arguments $Line -KillTreeOnExit $batch = (Invoke-PkProcessBatch -Commands @(@{ FilePath = $Cmd; Arguments = $Line }) -KillTreeOnExit).Results[0] @@ -5694,7 +5707,7 @@ try { $bkFindings = foreach ($i in 1..3) { (Test-PkWorkerSafety -WorkerScript $bkOnWorker).Count } $bkFirst = @($bkLookups | Where-Object { $_ -like '*-ListAvailable*' }).Count Test-Assert (($bkFindings -join ',') -eq '0,0,0' -and $bkFirst -eq 1) ("three checks of a worker using one module look it up once (findings " + ($bkFindings -join ',') + ", lookups " + $bkFirst + ")") - $bkRun = foreach ($i in 1..2) { (Invoke-PkRunspaceJobs -MaxParallel 1 -JobParams @{ Id = 1 } -WorkerScript $bkOnWorker).CrashedCount } + $bkRun = foreach ($i in 1..2) { (Invoke-PkRunspaceBatch -MaxConcurrent 1 -JobParams @{ Id = 1 } -WorkerScript $bkOnWorker).CrashedCount } $bkSecond = @($bkLookups | Where-Object { $_ -like '*-ListAvailable*' }).Count Test-Assert (($bkRun -join ',') -eq '0,0' -and $bkSecond -eq 1) ("and so do the runs after them (crashes " + ($bkRun -join ',') + ", lookups " + $bkSecond + ")") @@ -5793,10 +5806,10 @@ $blClosureText = @($blFound | ForEach-Object { $_.Text }) -join '; ' Test-Assert ($blPlainText -like '*$blPrefix*job value*' -and $blPlainText -notlike '*GetNewClosure*') ("the message says to pass it as a job value (" + $blPlainText + ")") Test-Assert ($blClosureText -like '*$blPrefix*GetNewClosure() doesn''t carry*job value*') ("and for a closure, that .GetNewClosure() doesn't carry variables into a worker (" + $blClosureText + ")") $blResults = [System.Collections.Generic.List[object]]::new(); $blThrew = '' -try { $null = Invoke-PkRunspaceJobs -MaxParallel 1 -JobParams @{ Id = 1 } -WorkerScript $blPlain.GetNewClosure() -ResultHandler { param($r) $blResults.Add($r) }.GetNewClosure() } catch { $blThrew = [string]$_ } +try { $null = Invoke-PkRunspaceBatch -MaxConcurrent 1 -JobParams @{ Id = 1 } -WorkerScript $blPlain.GetNewClosure() -ResultHandler { param($r) $blResults.Add($r) }.GetNewClosure() } catch { $blThrew = [string]$_ } Test-Assert ($blThrew -like '*worker-safety rules*$blPrefix*' -and $blResults.Count -eq 0) ("a closure worker that would lose its variable is refused before anything runs (results " + ($blResults -join ',') + ", error: " + $blThrew + ")") $blResults.Clear() -$null = Invoke-PkRunspaceJobs -MaxParallel 1 -JobParams @{ Id = 1 } -WorkerScript $blPlain -CheckWorkerSafety:$false -ResultHandler { param($r) $blResults.Add($r) }.GetNewClosure() +$null = Invoke-PkRunspaceBatch -MaxConcurrent 1 -JobParams @{ Id = 1 } -WorkerScript $blPlain -CheckWorkerSafety:$false -ResultHandler { param($r) $blResults.Add($r) }.GetNewClosure() Test-Assert ($blResults.Count -eq 1 -and $blResults[0] -eq '[1]') ("with the check off it runs, and reads it as empty (" + ($blResults -join ',') + ")") Reset-Harness Write-Host "" diff --git a/ParallelKit.ps1 b/ParallelKit.ps1 index 4357ef3..69504c9 100644 --- a/ParallelKit.ps1 +++ b/ParallelKit.ps1 @@ -180,7 +180,7 @@ public static class PkState public static readonly System.Collections.Concurrent.ConcurrentDictionary ModuleFound = new System.Collections.Concurrent.ConcurrentDictionary(StringComparer.OrdinalIgnoreCase); - // Get-PkPredefinedVariables' answer for this session. + // Get-PkPredefinedVariable' answer for this session. public static HashSet PredefinedVariables = null; } '@ -Language CSharp @@ -1081,7 +1081,7 @@ if ((& { try { [PkState]::TypesVersion } catch { 0 } }) -ne 13) { throw "ParallelKit: this PowerShell session already loaded an older version of the kit, and its compiled parts can't be swapped out. Close this window and start a new one." } -# Set in a worker by Invoke-PkRunspaceJobs, null elsewhere: how kit +# Set in a worker by Invoke-PkRunspaceBatch, null elsewhere: how kit # functions tell where they run. Defined here for strict mode. if (-not (Test-Path -LiteralPath 'Variable:\global:PkWorkerQueue')) { $global:PkWorkerQueue = $null } if (-not (Test-Path -LiteralPath 'Variable:\global:PkCancelToken')) { $global:PkCancelToken = $null } @@ -1171,7 +1171,7 @@ function Write-PkMessage { Invoke-PkMessageHandler -Message $Message -Level $Level } -function Receive-PkWorkerMessages { +function Receive-PkWorkerMessage { # Main thread only: deliver everything workers have queued so far. param([System.Collections.Concurrent.ConcurrentQueue[object]]$Queue) if ($null -eq $Queue) { return } @@ -1280,7 +1280,7 @@ function Register-PkCancellationSource { # .DESCRIPTION # Every registered source is canceled the moment an abort is detected. If an # abort is still in force when you register (see Reset-PkAbortState), the source - # is canceled right away. A -Cts passed to Invoke-PkRunspaceJobs is + # is canceled right away. A -Cts passed to Invoke-PkRunspaceBatch is # registered for you. Remove it with Unregister-PkCancellationSource when done. # .PARAMETER Cts # The source to cancel on an abort. @@ -1578,7 +1578,7 @@ function ConvertTo-PkArgumentStringCore { return ($parts -join ' ') } -function Resolve-PkArguments { +function Resolve-PkArgumentList { # -Arguments as given -> the command line: a string as written, a list # quoted one argument per element (a [string] cast would join it with # spaces, or $OFS), a lone file or folder object as its full path. @@ -1733,7 +1733,7 @@ function Start-PkProcessCore { [System.Management.Automation.SessionState]$CallerState ) $encoding = Resolve-PkEncoding -Encoding $OutputEncoding - $commandLine = Resolve-PkArguments -Arguments $Arguments -FilePath $FilePath + $commandLine = Resolve-PkArgumentList -Arguments $Arguments -FilePath $FilePath # For a caller who never ran Initialize-ParallelKit. No-ops once done; # a failure warns once, as Initialize-ParallelKit would. if (-not [PkChildProcessJob]::IsInitialized) { $null = Initialize-PkChildProcessJob -Once } @@ -1883,7 +1883,7 @@ function Stop-PkProcessTreeCore { # many taskkill calls as the limit needs. if ($MaxArgumentLength -le 0) { $MaxArgumentLength = 32000 - $TaskkillPath.Length } $ids = [int[]]@(foreach ($p in $viaTaskkill) { $p.Id }) - foreach ($taskkillArgs in $(if ($ids.Count -gt 0) { Split-PkTaskkillArguments -Ids $ids -MaxLength $MaxArgumentLength })) { + foreach ($taskkillArgs in $(if ($ids.Count -gt 0) { Split-PkTaskkillArgumentList -Ids $ids -MaxLength $MaxArgumentLength })) { $psi = [System.Diagnostics.ProcessStartInfo]::new($TaskkillPath, $taskkillArgs) $psi.UseShellExecute = $false $psi.CreateNoWindow = $true @@ -1930,7 +1930,7 @@ function Stop-PkProcessTreeCore { return $killed } -function Split-PkTaskkillArguments { +function Split-PkTaskkillArgumentList { # taskkill argument lists ('/T /F /PID 1 /PID 2 ...') for these PIDs, as # few as fit, each at most MaxLength characters (a single PID that doesn't # fit still gets a list of its own). Returns a list of strings. @@ -1952,7 +1952,7 @@ function Split-PkTaskkillArguments { return ,$lists } -function Stop-PkJobProcesses { +function Stop-PkJobProcess { # The dispatcher's force-stop: every running job's tree in one # Stop-PkProcessTree call. A custom starter's .Proc may not be a Process; # those are skipped. Stop-PkProcessTree passes over a program that has @@ -1978,7 +1978,7 @@ function Get-PkJobTimeLimit { return $limit } -function Get-PkJobMaxOutputChars { +function Get-PkJobOutputLimit { # A job's output cap in characters: its own MaxOutputChars key if it has # one, else the default. 0 = no cap. Throws on a bad key, as # Get-PkJobTimeLimit does for TimeoutSeconds. @@ -2058,7 +2058,7 @@ function Wait-PkProcess { ) # -1 would wait until the program exits, forever if it never does. if ($TimeoutMs -lt 0) { throw ("Wait-PkProcess: -TimeoutMs must be 0 or more (got " + $TimeoutMs + "). It's how long to wait, in milliseconds; 0 just checks.") } - # Same handle wrapping as Wait-PkRunningJobs. + # Same handle wrapping as Wait-PkRunningJob. $waitHandle = [System.Threading.ManualResetEvent]::new($false) $origHandle = $waitHandle.SafeWaitHandle $waitHandle.SafeWaitHandle = [Microsoft.Win32.SafeHandles.SafeWaitHandle]::new($Process.Handle, $false) @@ -2070,7 +2070,7 @@ function Wait-PkProcess { } } -function Wait-PkRunningJobs { +function Wait-PkRunningJob { # The dispatch loop's pause: until a running program exits, the token is # canceled, or TimeoutMs passes. Exited programs aren't waited on: a # -JobPollCompleted can keep saying "not done" after the exit, and the @@ -2388,7 +2388,7 @@ function Invoke-PkProcessDispatch { # abort cut short, so check Test-PkCancelRequested before anything irreversible. # .PARAMETER MaxConcurrent # How many programs run at once: an int, or a SemaphoreSlim shared by several - # dispatchers that must stay under one combined limit. -MaxParallel also works. + # dispatchers that must stay under one combined limit. # .PARAMETER PollCallback # { param($runningJobs) } run on every loop pass, with the jobs currently running. # -AbortPollCallback (its name before 3.0) also works. @@ -2398,7 +2398,7 @@ function Invoke-PkProcessDispatch { # .PARAMETER AbortTimeoutSeconds # How long an abort waits for running jobs before force-stopping them # (default 60). A force-stopped program is killed along with anything it - # started. -DrainTimeoutSeconds also works. + # started. # .PARAMETER MaxQueueAhead # How many groups to pull ahead of the ones running (default 3). # .PARAMETER GroupReleaseCheck @@ -2444,12 +2444,10 @@ function Invoke-PkProcessDispatch { [scriptblock]$JobAbortCleanup = $null, [scriptblock]$GroupCompleteCallback = $null, [Parameter(Mandatory)] - [Alias('MaxParallel')] $MaxConcurrent, [Alias('AbortPollCallback')] [scriptblock]$PollCallback = $null, [System.Threading.CancellationToken]$CancelToken, - [Alias('DrainTimeoutSeconds')] [int]$AbortTimeoutSeconds = 60, [int]$MaxQueueAhead = 3, [scriptblock]$GroupReleaseCheck = $null, @@ -2463,7 +2461,7 @@ function Invoke-PkProcessDispatch { ) # pk-prefixed, parameters included: inside a worker runspace the kit isn't # a module, so a callback without .GetNewClosure() sees this frame's - # variables. Same in Add-PkDispatchGroupJobs, Invoke-PkProcessDispatchCore, Invoke-PkProcessBatch. + # variables. Same in Add-PkDispatchGroupJob, Invoke-PkProcessDispatchCore, Invoke-PkProcessBatch. $pkGroupProvider = $GroupProvider $pkJobBuilder = $JobBuilder $pkJobStarter = $JobStarter @@ -2516,7 +2514,7 @@ function Invoke-PkProcessDispatch { $pkCallerState = $PSCmdlet.SessionState $pkJobStarter = { param($pkJob) - $pkStarted = Start-PkProcessCore -CallerState $pkCallerState -FilePath $pkJob['FilePath'] -Arguments $pkJob['Arguments'] -WorkingDirectory ([string]$pkJob['WorkingDirectory']) -OutputEncoding $pkJob['OutputEncoding'] -MaxOutputChars (Get-PkJobMaxOutputChars -Job $pkJob -DefaultMaxOutputChars $pkMaxOutputChars) -InheritStdin:(Get-PkJobSwitch -Job $pkJob -Key 'InheritStdin' -Default $pkInheritStdin) + $pkStarted = Start-PkProcessCore -CallerState $pkCallerState -FilePath $pkJob['FilePath'] -Arguments $pkJob['Arguments'] -WorkingDirectory ([string]$pkJob['WorkingDirectory']) -OutputEncoding $pkJob['OutputEncoding'] -MaxOutputChars (Get-PkJobOutputLimit -Job $pkJob -DefaultMaxOutputChars $pkMaxOutputChars) -InheritStdin:(Get-PkJobSwitch -Job $pkJob -Key 'InheritStdin' -Default $pkInheritStdin) # Start-PkProcessCore's four keys (it builds them in two places); the # batch's starter copies them too: a new key goes in all four. $pkJob['Proc'] = $pkStarted.Proc; $pkJob['StdoutTask'] = $pkStarted.StdoutTask; $pkJob['StderrTask'] = $pkStarted.StderrTask @@ -2594,7 +2592,7 @@ function Invoke-PkProcessDispatch { } } -function Add-PkDispatchGroupJobs { +function Add-PkDispatchGroupJob { # Builds one group's jobs, tags them with the group and queues them; # returns how many. Its own function so the group's job list dies with # this call: in the dispatch loop's frame it kept every finished job's @@ -2657,7 +2655,7 @@ function Invoke-PkProcessDispatchCore { ) # pk-prefixed, parameters included: inside a worker runspace the kit isn't # a module, so a callback without .GetNewClosure() sees this frame's - # variables. Same in Add-PkDispatchGroupJobs, Invoke-PkProcessDispatch, Invoke-PkProcessBatch. + # variables. Same in Add-PkDispatchGroupJob, Invoke-PkProcessDispatch, Invoke-PkProcessBatch. $pkGroupProvider = $GroupProvider $pkJobBuilder = $JobBuilder $pkJobStarter = $JobStarter @@ -2739,7 +2737,7 @@ function Invoke-PkProcessDispatchCore { # A fresh key per group, not the group value: two groups that # compare equal (the same folder name) mustn't share a job count. $pkGroupKey = [object]::new() - $pkJobCount = Add-PkDispatchGroupJobs -JobBuilder $pkJobBuilder -GroupInfo $pkGroupInfo -GroupKey $pkGroupKey -Pending $pkPending -CallbackContext $pkCallbackContext + $pkJobCount = Add-PkDispatchGroupJob -JobBuilder $pkJobBuilder -GroupInfo $pkGroupInfo -GroupKey $pkGroupKey -Pending $pkPending -CallbackContext $pkCallbackContext $pkState = @{ GroupInfo = $pkGroupInfo; Outstanding = $pkJobCount; Completed = $false } $pkGroupStates[$pkGroupKey] = $pkState $pkActiveGroupCount++ @@ -2895,7 +2893,7 @@ function Invoke-PkProcessDispatchCore { $pkAnyFinished = ($pkStillRunning.Count -lt $pkRunning.Count) $pkRunning = $pkStillRunning - if ($pkIsSharedBudget -or -not $pkAnyFinished) { Wait-PkRunningJobs -Jobs $pkRunning -CancelToken $pkCancelToken -TimeoutMs 50 } + if ($pkIsSharedBudget -or -not $pkAnyFinished) { Wait-PkRunningJob -Jobs $pkRunning -CancelToken $pkCancelToken -TimeoutMs 50 } } if ($pkCancelToken.IsCancellationRequested -and $pkRunning.Count -gt 0) { @@ -3022,7 +3020,7 @@ function Invoke-PkProcessDispatchCore { if ($pkRunning.Count -gt 0) { $pkDispatchResult.ForceKilledCount = $pkRunning.Count Write-PkMessage ("ProcessDispatch: force-stopping " + $pkRunning.Count + " job(s)" + (Get-PkForceStopReason -TimeoutSeconds $pkAbortTimeoutSeconds) + ".") -Level Warn - Stop-PkJobProcesses -Jobs $pkRunning + Stop-PkJobProcess -Jobs $pkRunning foreach ($pkJob in $pkRunning) { try { if ($pkJob['Proc']) { $null = $pkJob['Proc'].WaitForExit(5000) } } catch { } # a custom starter's .Proc may not be a Process; the kill above already ran try { $null = Invoke-PkCallback -PkCallback $pkJobAbortCleanup -PkArgs @(,$pkJob) -PkName '-JobAbortCleanup' -PkContext $pkCallbackContext } catch { } # one job's failed cleanup mustn't skip the others' @@ -3043,7 +3041,7 @@ function Invoke-PkProcessDispatchCore { $pkTearDown = [System.Collections.Generic.List[hashtable]]::new() foreach ($pkJob in $pkRunning) { if (-not $pkJob['SlotReleased']) { $pkTearDown.Add($pkJob) } } if ($null -ne $pkStarting -and -not $pkTearDown.Contains($pkStarting)) { $pkTearDown.Add($pkStarting) } - Stop-PkJobProcesses -Jobs $pkTearDown + Stop-PkJobProcess -Jobs $pkTearDown foreach ($pkJob in $pkTearDown) { try { if ($pkJob['Proc']) { $null = $pkJob['Proc'].WaitForExit(5000) } } catch { } # a custom starter's .Proc may not be a Process; the kill above already ran if (-not [object]::ReferenceEquals($pkJob, $pkFinalizing)) { @@ -3140,13 +3138,12 @@ function Invoke-PkProcessBatch { # .PARAMETER Commands # The command hashtables. $null or empty returns no results. # .PARAMETER MaxConcurrent - # How many programs run at once (default 4). -MaxParallel also works. + # How many programs run at once (default 4). # .PARAMETER OnComplete # { param($command, $result) } run on the main thread as each program finishes. # Not called for one that couldn't start or was stopped by an abort. # .PARAMETER AbortTimeoutSeconds # How long an abort waits for running programs before killing them (default 60). - # -DrainTimeoutSeconds also works. # .PARAMETER TimeoutSeconds # Kill a program still running after this long (default 0, no limit). Its # result has TimedOut = $true. @@ -3184,10 +3181,8 @@ function Invoke-PkProcessBatch { [AllowNull()] [AllowEmptyCollection()] [hashtable[]]$Commands, - [Alias('MaxParallel')] [int]$MaxConcurrent = 4, [scriptblock]$OnComplete = $null, - [Alias('DrainTimeoutSeconds')] [int]$AbortTimeoutSeconds = 60, [double]$TimeoutSeconds = 0, $OutputEncoding = $null, @@ -3200,7 +3195,7 @@ function Invoke-PkProcessBatch { ) # pk-prefixed, parameters included: inside a worker runspace the kit isn't # a module, so a callback without .GetNewClosure() sees this frame's - # variables. Same in Add-PkDispatchGroupJobs, Invoke-PkProcessDispatch, Invoke-PkProcessDispatchCore. + # variables. Same in Add-PkDispatchGroupJob, Invoke-PkProcessDispatch, Invoke-PkProcessDispatchCore. $pkCommands = $Commands $pkMaxConcurrent = $MaxConcurrent $pkOnComplete = $OnComplete @@ -3240,7 +3235,7 @@ function Invoke-PkProcessBatch { $pkNewBatchResult = ${function:New-PkBatchResult} $pkStartProcessCore = ${function:Start-PkProcessCore} $pkGetJobTimeLimit = ${function:Get-PkJobTimeLimit} - $pkGetJobMaxOutputChars = ${function:Get-PkJobMaxOutputChars} + $pkGetJobOutputLimit = ${function:Get-PkJobOutputLimit} $pkGetJobSwitch = ${function:Get-PkJobSwitch} $pkGetStartFailureCause = ${function:Get-PkStartFailureCause} $pkWriteCallbackLoopWarning = ${function:Write-PkCallbackLoopWarning} @@ -3285,7 +3280,7 @@ function Invoke-PkProcessBatch { # starter below, so the command would get no result. try { $null = & $pkGetJobTimeLimit -Job $pkC - $pkCap = & $pkGetJobMaxOutputChars -Job $pkC -DefaultMaxOutputChars $pkMaxOutputChars + $pkCap = & $pkGetJobOutputLimit -Job $pkC -DefaultMaxOutputChars $pkMaxOutputChars $pkStdin = & $pkGetJobSwitch -Job $pkC -Key 'InheritStdin' -Default $pkInheritStdin $pkKillTree = & $pkGetJobSwitch -Job $pkC -Key 'KillTreeOnExit' -Default $pkKillTreeOnExit } catch { @@ -3356,12 +3351,12 @@ function Invoke-PkProcessBatch { # Runspace jobs - run PowerShell worker scripts in parallel # ============================================================================== -function Get-PkWorkerSafeFunctionNames { +function Get-PkWorkerSafeFunctionName { # Kit functions every worker runspace gets automatically. - return @('Write-PkMessage', 'Test-PkAbortSignal', 'Test-PkCancelRequested', 'Initialize-PkChildProcessJob', 'Stop-PkProcessTree', 'Stop-PkProcessTreeCore', 'Split-PkTaskkillArguments', 'Stop-PkJobProcesses', 'Get-PkProcessDuration', 'Resolve-PkEncoding', - 'Start-PkProcess', 'Wait-PkProcess', 'Wait-PkRunningJobs', 'Complete-PkProcess', 'Invoke-PkProcessWithTimeout', + return @('Write-PkMessage', 'Test-PkAbortSignal', 'Test-PkCancelRequested', 'Initialize-PkChildProcessJob', 'Stop-PkProcessTree', 'Stop-PkProcessTreeCore', 'Split-PkTaskkillArgumentList', 'Stop-PkJobProcess', 'Get-PkProcessDuration', 'Resolve-PkEncoding', + 'Start-PkProcess', 'Wait-PkProcess', 'Wait-PkRunningJob', 'Complete-PkProcess', 'Invoke-PkProcessWithTimeout', 'Invoke-PkProcessDispatch', 'Invoke-PkProcessDispatchCore', 'Invoke-PkProcessBatch', - 'Register-PkCancellationSource', 'Unregister-PkCancellationSource', 'New-PkBatchResult', 'Get-PkJobMaxOutputChars', 'Get-PkJobSwitch', 'Stop-PkExitedJobTree', 'ConvertTo-PkArgumentString', 'Get-PkForceStopReason', 'Resolve-PkFileSystemPath', 'Add-PkDispatchGroupJobs', 'Start-PkProcessCore', 'Get-PkJobTimeLimit', 'Stop-PkTimedOutJob', 'Get-PkStartFailureCause', 'Resolve-PkArguments', 'Invoke-PkCallback', 'Write-PkCallbackLoopWarning', 'ConvertTo-PkArgumentStringCore') + 'Register-PkCancellationSource', 'Unregister-PkCancellationSource', 'New-PkBatchResult', 'Get-PkJobOutputLimit', 'Get-PkJobSwitch', 'Stop-PkExitedJobTree', 'ConvertTo-PkArgumentString', 'Get-PkForceStopReason', 'Resolve-PkFileSystemPath', 'Add-PkDispatchGroupJob', 'Start-PkProcessCore', 'Get-PkJobTimeLimit', 'Stop-PkTimedOutJob', 'Get-PkStartFailureCause', 'Resolve-PkArgumentList', 'Invoke-PkCallback', 'Write-PkCallbackLoopWarning', 'ConvertTo-PkArgumentStringCore') } function Get-PkHandlerParamCount { @@ -3406,7 +3401,7 @@ function Add-PkCrashedJob { } } -function Add-PkJobErrors { +function Add-PkJobError { # A finished worker's non-terminating errors: print each and record it # with its job. Shared by the main loop and the abort drain. Called for a # crashed worker too: its error stream holds only the errors before the @@ -3423,7 +3418,7 @@ function Add-PkJobErrors { } } -function Receive-PkCompletedHandles { +function Receive-PkCompletedHandle { param( [System.Collections.Generic.List[hashtable]]$Handles, [scriptblock]$ResultHandler, @@ -3438,9 +3433,9 @@ function Receive-PkCompletedHandles { $pkCrash = $null try { try { $pkWorkerOutput = $h.PS.EndInvoke($h.Handle) } catch { $pkCrash = $_ } - # Same as Invoke-PkRunspaceJobs' main loop: its errors, then the + # Same as Invoke-PkRunspaceBatch' main loop: its errors, then the # crash, in the order they happened. - Add-PkJobErrors -PkOutcome $Outcome -PkJob $h['Job'] -PkErrors $h.PS.Streams.Error + Add-PkJobError -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" -PkCallbackContext $CallbackContext } @@ -3495,15 +3490,15 @@ function Invoke-PkGracefulDrain { if ($AbortWaitMessage -ne "") { Invoke-PkMessageHandler -Message $AbortWaitMessage -Level Warn } while ($localHandles.Count -gt 0 -and -not [PkConsoleCtrl]::IsCloseEvent -and -not [PkConsoleCtrl]::SkipDrain -and $abortDeadline.Elapsed.TotalSeconds -lt $TimeoutSeconds) { - $localHandles = Receive-PkCompletedHandles -Handles $localHandles -ResultHandler $ResultHandler -Outcome $Outcome -JobCrashedHandler $JobCrashedHandler -CallbackContext $CallbackContext - Receive-PkWorkerMessages -Queue $MessageQueue + $localHandles = Receive-PkCompletedHandle -Handles $localHandles -ResultHandler $ResultHandler -Outcome $Outcome -JobCrashedHandler $JobCrashedHandler -CallbackContext $CallbackContext + Receive-PkWorkerMessage -Queue $MessageQueue if ($localHandles.Count -gt 0) { [System.Threading.Thread]::Sleep(250) } } # One final pass before declaring anything force-stopped. if ($localHandles.Count -gt 0) { - $localHandles = Receive-PkCompletedHandles -Handles $localHandles -ResultHandler $ResultHandler -Outcome $Outcome -JobCrashedHandler $JobCrashedHandler -CallbackContext $CallbackContext - Receive-PkWorkerMessages -Queue $MessageQueue + $localHandles = Receive-PkCompletedHandle -Handles $localHandles -ResultHandler $ResultHandler -Outcome $Outcome -JobCrashedHandler $JobCrashedHandler -CallbackContext $CallbackContext + Receive-PkWorkerMessage -Queue $MessageQueue } if ($localHandles.Count -gt 0) { @@ -3516,12 +3511,12 @@ function Invoke-PkGracefulDrain { } } - Receive-PkWorkerMessages -Queue $MessageQueue + Receive-PkWorkerMessage -Queue $MessageQueue return @{ ForceStoppedCount = $forceStoppedCount } } -function Invoke-PkRunspaceJobs { +function Invoke-PkRunspaceBatch { # .SYNOPSIS # Runs a PowerShell scriptblock once per job, a limited number at a time, each in # its own runspace. @@ -3551,8 +3546,8 @@ function Invoke-PkRunspaceJobs { # it outputs is ignored, with a warning. # .PARAMETER SharedFunctionNames # Your functions the worker calls. - # .PARAMETER MaxParallel - # How many workers run at once. -MaxConcurrent also works. + # .PARAMETER MaxConcurrent + # How many workers run at once. # .PARAMETER Cts # Your own CancellationTokenSource for the run; an abort cancels it too. # So does any exit that leaves workers running (one of your callbacks @@ -3567,9 +3562,9 @@ function Invoke-PkRunspaceJobs { # of param() if you don't need it. The worker's own error is # $errorRecord.Exception.InnerException. If the handler throws, that's reported # as a message and the run carries on. - # .PARAMETER DrainTimeoutSeconds + # .PARAMETER AbortTimeoutSeconds # How long an abort waits for running workers before force-stopping them - # (default 60). -AbortTimeoutSeconds also works. + # (default 60). # .PARAMETER AbortWaitMessage # The message shown while an abort waits; '' for none. # .PARAMETER CheckWorkerSafety @@ -3581,7 +3576,7 @@ function Invoke-PkRunspaceJobs { # (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 } + # Invoke-PkRunspaceBatch -MaxConcurrent 4 -JobParams @(@{ Id = 1 }, @{ Id = 2 }) -WorkerScript { param($Id) $Id * 2 } -ResultHandler { param($r) Write-Host $r } param( [Parameter(Mandatory)] [scriptblock]$WorkerScript, @@ -3589,14 +3584,12 @@ function Invoke-PkRunspaceJobs { [scriptblock]$NextJobProvider = $null, [string[]]$SharedFunctionNames = @(), [Parameter(Mandatory)] - [Alias('MaxConcurrent')] - [int]$MaxParallel, + [int]$MaxConcurrent, [System.Threading.CancellationTokenSource]$Cts = $null, [scriptblock]$ResultHandler = $null, [scriptblock]$PollCallback = $null, [scriptblock]$JobCrashedHandler = $null, - [Alias('AbortTimeoutSeconds')] - [int]$DrainTimeoutSeconds = 60, + [int]$AbortTimeoutSeconds = 60, [string]$AbortWaitMessage, [switch]$CheckWorkerSafety ) @@ -3604,14 +3597,14 @@ function Invoke-PkRunspaceJobs { $checkSafety = (-not $PSBoundParameters.ContainsKey('CheckWorkerSafety')) -or $CheckWorkerSafety.IsPresent if ($null -eq $JobParams -and $null -eq $NextJobProvider) { - throw "Invoke-PkRunspaceJobs: must supply either -JobParams or -NextJobProvider." + throw "Invoke-PkRunspaceBatch: must supply either -JobParams or -NextJobProvider." } if ($null -ne $JobParams -and $null -ne $NextJobProvider) { - throw "Invoke-PkRunspaceJobs: supply only one of -JobParams or -NextJobProvider, not both." + throw "Invoke-PkRunspaceBatch: supply only one of -JobParams or -NextJobProvider, not both." } - if ($MaxParallel -lt 1) { throw "Invoke-PkRunspaceJobs: -MaxParallel must be at least 1." } - if ($DrainTimeoutSeconds -lt 0) { - throw ("Invoke-PkRunspaceJobs: -DrainTimeoutSeconds must be 0 or more (got " + $DrainTimeoutSeconds + "). It's how long an abort waits for running workers before force-stopping them; 0 doesn't wait.") + if ($MaxConcurrent -lt 1) { throw "Invoke-PkRunspaceBatch: -MaxConcurrent must be at least 1." } + if ($AbortTimeoutSeconds -lt 0) { + throw ("Invoke-PkRunspaceBatch: -AbortTimeoutSeconds must be 0 or more (got " + $AbortTimeoutSeconds + "). It's how long an abort waits for running workers before force-stopping them; 0 doesn't wait.") } # A List, an array or a single hashtable: a one-job list built with @@ -3623,7 +3616,7 @@ function Invoke-PkRunspaceJobs { } else { foreach ($jobEntry in $JobParams) { if ($jobEntry -isnot [hashtable]) { - throw ("Invoke-PkRunspaceJobs: -JobParams entry " + $normalizedJobs.Count + " is not a hashtable. Each job must be a hashtable of the worker's parameters.") + throw ("Invoke-PkRunspaceBatch: -JobParams entry " + $normalizedJobs.Count + " is not a hashtable. Each job must be a hashtable of the worker's parameters.") } $normalizedJobs.Add($jobEntry) } @@ -3638,7 +3631,7 @@ function Invoke-PkRunspaceJobs { $safetyFindings = Test-PkWorkerSafetyCore -WorkerScript $WorkerScript -SharedFunctionNames $SharedFunctionNames -SessionState $PSCmdlet.SessionState if ($safetyFindings.Count -gt 0) { $safetyLines = foreach ($f in $safetyFindings) { " " + $f.Text } - throw ("Invoke-PkRunspaceJobs: worker code breaks the worker-safety rules (see README.md):`r`n" + ($safetyLines -join "`r`n")) + throw ("Invoke-PkRunspaceBatch: worker code breaks the worker-safety rules (see README.md):`r`n" + ($safetyLines -join "`r`n")) } } @@ -3681,14 +3674,14 @@ function Invoke-PkRunspaceJobs { for ($jobIndex = 0; $jobIndex -lt $JobParams.Count; $jobIndex++) { foreach ($key in $JobParams[$jobIndex].Keys) { if (-not $declaredParams.Contains([string]$key)) { - throw ("Invoke-PkRunspaceJobs: job " + $jobIndex + " supplies '" + $key + "', but -WorkerScript's param() block doesn't declare it. Nothing was started.") + throw ("Invoke-PkRunspaceBatch: job " + $jobIndex + " supplies '" + $key + "', but -WorkerScript's param() block doesn't declare it. Nothing was started.") } } # -contains, not ContainsKey: case-insensitive like binding, even # for a case-sensitive [hashtable]::new() job. foreach ($mandatoryParam in $mandatoryParams) { if (@($JobParams[$jobIndex].Keys) -notcontains $mandatoryParam) { - throw ("Invoke-PkRunspaceJobs: job " + $jobIndex + " doesn't supply '" + $mandatoryParam + "', which -WorkerScript's param() block makes mandatory. Nothing was started.") + throw ("Invoke-PkRunspaceBatch: job " + $jobIndex + " doesn't supply '" + $mandatoryParam + "', which -WorkerScript's param() block makes mandatory. Nothing was started.") } } if ($checkSafety) { @@ -3707,7 +3700,7 @@ function Invoke-PkRunspaceJobs { $scanExhausted = $false # Invoke-PkCallback's -PkContext: callbacks that used continue/break are # warned about once each, under this prefix. - $pkCallbackContext = @{ Prefix = 'Invoke-PkRunspaceJobs: '; Warned = @{} } + $pkCallbackContext = @{ Prefix = 'Invoke-PkRunspaceBatch: '; Warned = @{} } try { if ($null -eq $Cts) { @@ -3724,19 +3717,19 @@ function Invoke-PkRunspaceJobs { $iss = [System.Management.Automation.Runspaces.InitialSessionState]::CreateDefault() $allShared = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase) - foreach ($n in (Get-PkWorkerSafeFunctionNames)) { $null = $allShared.Add($n) } + foreach ($n in (Get-PkWorkerSafeFunctionName)) { $null = $allShared.Add($n) } foreach ($n in $SharedFunctionNames) { $null = $allShared.Add($n) } # The kit's worker functions come from this module; yours from where # you called this (a script's own functions, functions inside a # function, a module's private ones). - $kitWorkerNames = [System.Collections.Generic.HashSet[string]]::new([string[]]@(Get-PkWorkerSafeFunctionNames), [System.StringComparer]::OrdinalIgnoreCase) + $kitWorkerNames = [System.Collections.Generic.HashSet[string]]::new([string[]]@(Get-PkWorkerSafeFunctionName), [System.StringComparer]::OrdinalIgnoreCase) $callerFns = Get-PkCallerFunction -SessionState $PSCmdlet.SessionState -Name @($allShared | Where-Object { -not $kitWorkerNames.Contains($_) }) foreach ($sharedFn in $allShared) { $fnInfo = $null if ($kitWorkerNames.Contains($sharedFn)) { $fnInfo = Get-Item -LiteralPath ("Function:\" + $sharedFn) -ErrorAction SilentlyContinue } else { $fnInfo = $callerFns[$sharedFn] } if ($null -eq $fnInfo) { - throw ("Invoke-PkRunspaceJobs: -SharedFunctionNames entry '" + $sharedFn + "' does not resolve to a defined function - check for a typo, or that the file defining it was dot-sourced before this call.") + throw ("Invoke-PkRunspaceBatch: -SharedFunctionNames entry '" + $sharedFn + "' does not resolve to a defined function - check for a typo, or that the file defining it was dot-sourced before this call.") } $iss.Commands.Add([System.Management.Automation.Runspaces.SessionStateFunctionEntry]::new($sharedFn, $fnInfo.Definition)) } @@ -3745,7 +3738,7 @@ function Invoke-PkRunspaceJobs { $iss.Variables.Add([System.Management.Automation.Runspaces.SessionStateVariableEntry]::new('PkWorkerQueue', $messageQueue, 'ParallelKit worker message queue')) $iss.Variables.Add([System.Management.Automation.Runspaces.SessionStateVariableEntry]::new('PkCancelToken', $Cts.Token, 'ParallelKit run cancellation token')) - $pool = [RunspaceFactory]::CreateRunspacePool(1, $MaxParallel, $iss, $Host) + $pool = [RunspaceFactory]::CreateRunspacePool(1, $MaxConcurrent, $iss, $Host) $pool.Open() # Each job starts in the caller's current location: the real folder, @@ -3763,7 +3756,7 @@ function Invoke-PkRunspaceJobs { while ((-not $scanExhausted -or $handles.Count -gt 0) -and -not $Cts.Token.IsCancellationRequested) { - while (-not $scanExhausted -and $handles.Count -lt $MaxParallel -and -not $Cts.Token.IsCancellationRequested) { + while (-not $scanExhausted -and $handles.Count -lt $MaxConcurrent -and -not $Cts.Token.IsCancellationRequested) { if ($null -ne $JobParams) { if ($fixedListIndex -lt $JobParams.Count) { $nextJob = $JobParams[$fixedListIndex] @@ -3791,19 +3784,19 @@ function Invoke-PkRunspaceJobs { if ($rawIndex -ne $jobIndex -and $null -ne $rawItems[$rawIndex]) { $strayCount++ } } if ($strayCount -gt 0) { - Invoke-PkMessageHandler -Level Warn -Message ("Invoke-PkRunspaceJobs: -NextJobProvider output " + $strayCount + " value(s) besides its job hashtable or `$null - ignored. Output only the next job, or `$null when there are no more (`$null = ... discards a value you don't want).") + Invoke-PkMessageHandler -Level Warn -Message ("Invoke-PkRunspaceBatch: -NextJobProvider output " + $strayCount + " value(s) besides its job hashtable or `$null - ignored. Output only the next job, or `$null when there are no more (`$null = ... discards a value you don't want).") } } if ($null -eq $nextJob) { $scanExhausted = $true; break } foreach ($key in $nextJob.Keys) { if (-not $declaredParams.Contains([string]$key)) { - throw ("Invoke-PkRunspaceJobs: a job supplies '" + $key + "', but -WorkerScript's param() block doesn't declare it.") + throw ("Invoke-PkRunspaceBatch: a job supplies '" + $key + "', but -WorkerScript's param() block doesn't declare it.") } } foreach ($mandatoryParam in $mandatoryParams) { if (@($nextJob.Keys) -notcontains $mandatoryParam) { # case-insensitive, as for -JobParams above - throw ("Invoke-PkRunspaceJobs: a job from -NextJobProvider doesn't supply '" + $mandatoryParam + "', which -WorkerScript's param() block makes mandatory.") + throw ("Invoke-PkRunspaceBatch: a job from -NextJobProvider doesn't supply '" + $mandatoryParam + "', which -WorkerScript's param() block makes mandatory.") } } if ($checkSafety -and $null -eq $JobParams) { @@ -3827,7 +3820,7 @@ function Invoke-PkRunspaceJobs { } $null = Test-PkAbortSignal - Receive-PkWorkerMessages -Queue $messageQueue + Receive-PkWorkerMessage -Queue $messageQueue if ($null -ne $PollCallback) { $null = Invoke-PkCallback -PkCallback $PollCallback -PkName '-PollCallback' -PkContext $pkCallbackContext } $stillPending = [System.Collections.Generic.List[hashtable]]::new() @@ -3837,9 +3830,9 @@ function Invoke-PkRunspaceJobs { $pkCrash = $null try { try { $pkWorkerOutput = $h.PS.EndInvoke($h.Handle) } catch { $pkCrash = $_ } - # Same as Receive-PkCompletedHandles: its errors, then + # Same as Receive-PkCompletedHandle: its errors, then # the crash, in the order they happened. - Add-PkJobErrors -PkOutcome $outcome -PkJob $h['Job'] -PkErrors $h.PS.Streams.Error + Add-PkJobError -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. @@ -3861,7 +3854,7 @@ function Invoke-PkRunspaceJobs { } } $handles = $stillPending - if ($handles.Count -gt 0 -and ($scanExhausted -or $handles.Count -ge $MaxParallel)) { + if ($handles.Count -gt 0 -and ($scanExhausted -or $handles.Count -ge $MaxConcurrent)) { # Until a worker finishes or the token is canceled. The 100 ms cap # keeps worker messages, -PollCallback and the abort flag moving. # WaitAny holds 63 handles at most on an STA thread, one of them the @@ -3877,14 +3870,14 @@ function Invoke-PkRunspaceJobs { } if ($Cts.Token.IsCancellationRequested) { - $drainArgs = @{ Handles = $handles; ResultHandler = $ResultHandler; MessageQueue = $messageQueue; TimeoutSeconds = $DrainTimeoutSeconds; Outcome = $outcome; JobCrashedHandler = $JobCrashedHandler; CallbackContext = $pkCallbackContext } + $drainArgs = @{ Handles = $handles; ResultHandler = $ResultHandler; MessageQueue = $messageQueue; TimeoutSeconds = $AbortTimeoutSeconds; Outcome = $outcome; JobCrashedHandler = $JobCrashedHandler; CallbackContext = $pkCallbackContext } if ($PSBoundParameters.ContainsKey('AbortWaitMessage')) { $drainArgs.AbortWaitMessage = $AbortWaitMessage } $drainResult = Invoke-PkGracefulDrain @drainArgs $outcome.ForceStoppedCount = $drainResult.ForceStoppedCount $outcome.Aborted = $true } - Receive-PkWorkerMessages -Queue $messageQueue + Receive-PkWorkerMessage -Queue $messageQueue if ($null -ne $PollCallback) { $null = Invoke-PkCallback -PkCallback $PollCallback -PkName '-PollCallback' -PkContext $pkCallbackContext } } finally { # Best-effort teardown; whatever exception is already in flight is the one to surface. @@ -3907,7 +3900,7 @@ function Invoke-PkRunspaceJobs { } else { try { $pool.Dispose() } catch { } } # teardown only; the exception in flight, if any, is the one to surface } - if ($null -ne $messageQueue) { try { Receive-PkWorkerMessages -Queue $messageQueue } catch { } } # last messages are best effort; the exception in flight, if any, is the one to surface + if ($null -ne $messageQueue) { try { Receive-PkWorkerMessage -Queue $messageQueue } catch { } } # last messages are best effort; the exception in flight, if any, is the one to surface if ($null -ne $ownCts) { Unregister-PkCancellationSource -Cts $ownCts $ownCts.Dispose() @@ -3978,7 +3971,7 @@ function Get-PkCommandKind { # autoload), or 'Other' (cmdlet, program, autoloadable module function, # or unknown). Uses the Alias: and Function: drives, not Get-Command, # which searches every module on $env:PSModulePath for a name that - # doesn't resolve, on every Invoke-PkRunspaceJobs call. + # doesn't resolve, on every Invoke-PkRunspaceBatch call. param([System.Management.Automation.FunctionInfo]$Fn) if ($null -eq $Fn) { return 'Other' } if ([string]::IsNullOrEmpty($Fn.ModuleName)) { return 'Function' } @@ -3989,7 +3982,7 @@ function Get-PkCommandKind { # cmdlet does - but only if the module can be found by name. One imported # by path from elsewhere can't. Remembered for the session: on 5.1 each # lookup searches all of PSModulePath (51 ms with 154 modules on it), for - # every Invoke-PkRunspaceJobs call. So a module installed mid-session is + # every Invoke-PkRunspaceBatch call. So a module installed mid-session is # missed until a new window, but one put on PSModulePath, as the finding # suggests, isn't: that's part of the key. $key = $env:PSModulePath + '|' + $Fn.ModuleName @@ -4055,13 +4048,13 @@ function Test-PkHoldsScriptBlock { } function Get-PkScriptBlockJobMessage { - # Shared by the fixed-list and -NextJobProvider checks in Invoke-PkRunspaceJobs. + # Shared by the fixed-list and -NextJobProvider checks in Invoke-PkRunspaceBatch. param([string]$Job, [string]$Key) - return ("Invoke-PkRunspaceJobs: " + $Job + " passes a scriptblock in '" + $Key + "'. A scriptblock made on the main thread and run in a worker can corrupt, crash or hang the run. " + + return ("Invoke-PkRunspaceBatch: " + $Job + " passes a scriptblock in '" + $Key + "'. A scriptblock made on the main thread and run in a worker can corrupt, crash or hang the run. " + "Pass its text instead (`$sb.ToString()) and rebuild it in the worker with [scriptblock]::Create(`$text), or pass -CheckWorkerSafety:`$false to skip this check.") } -function Get-PkPredefinedVariables { +function Get-PkPredefinedVariable { # The names a worker can read without declaring them: what a fresh # runspace has, what PowerShell makes on demand, and the kit's own worker # globals. Read once per session. @@ -4087,7 +4080,7 @@ function Get-PkPredefinedVariables { return ,$known } -function Get-PkCommandVariables { +function Get-PkCommandVariable { # The variables a command assigns by name, where the name is written out: # -OutVariable x and the like, Set-Variable x, Import-LocalizedData x. param([System.Management.Automation.Language.CommandAst]$Command) @@ -4128,7 +4121,7 @@ function Get-PkCommandVariables { } } -function Get-PkUndeclaredVariables { +function Get-PkUndeclaredVariable { # The variable reads in a worker's code whose variable it never declares # or assigns, anywhere in it (order is ignored), as VariableExpressionAsts. # Left out: $global: and drive-qualified ones. @@ -4145,7 +4138,7 @@ function Get-PkUndeclaredVariables { 'DataStatementAst' { if ($node.Variable) { $null = $declared.Add($node.Variable) } } 'UnaryExpressionAst' { if ([string]$node.TokenKind -match '^(Prefix|Postfix)?(PlusPlus|MinusMinus)$') { $targets.Push($node.Child) } } 'ConvertExpressionAst' { if ($node.Type.TypeName.FullName -eq 'ref') { $targets.Push($node.Child) } } - 'CommandAst' { foreach ($name in (Get-PkCommandVariables -Command $node)) { $null = $declared.Add($name) } } + 'CommandAst' { foreach ($name in (Get-PkCommandVariable -Command $node)) { $null = $declared.Add($name) } } } # An assignment's target, unwrapped: [int]$x, ($x) and $x, $y. Not # $x.Key or $x[0], which read $x. @@ -4159,7 +4152,7 @@ function Get-PkUndeclaredVariables { elseif ($target -is [System.Management.Automation.Language.ParenExpressionAst]) { $targets.Push($target.Pipeline) } } } - $predefined = Get-PkPredefinedVariables + $predefined = Get-PkPredefinedVariable foreach ($read in $reads) { $path = $read.VariablePath if ($path.IsDriveQualified -or $path.IsGlobal -or $path.UserPath -like 'variable:*') { continue } # PowerShell doesn't count Variable: as a drive there @@ -4186,7 +4179,7 @@ function Test-PkWorkerSafety { # .SYNOPSIS # Checks worker code against the worker rules without running it. # .DESCRIPTION - # Invoke-PkRunspaceJobs runs this check itself; call it directly from your own + # Invoke-PkRunspaceBatch runs this check itself; call it directly from your own # tests. Each finding has a Rule: # MissingFunction the worker calls a function of yours that isn't shared # ScriptVariable a shared function, or a nested block or function in the @@ -4208,7 +4201,7 @@ function Test-PkWorkerSafety { # and Text. # Scriptblocks handed to a worker as job values are refused separately, - # by Invoke-PkRunspaceJobs (see Get-PkScriptBlockJobKey). + # by Invoke-PkRunspaceBatch (see Get-PkScriptBlockJobKey). param( [Parameter(Mandatory)] [scriptblock]$WorkerScript, @@ -4220,7 +4213,7 @@ function Test-PkWorkerSafety { function Test-PkWorkerSafetyCore { # Test-PkWorkerSafety's body. -SessionState is the caller's, for finding - # their functions (Invoke-PkRunspaceJobs passes its own caller's). + # their functions (Invoke-PkRunspaceBatch passes its own caller's). param( [Parameter(Mandatory)][scriptblock]$WorkerScript, [string[]]$SharedFunctionNames = @(), @@ -4228,7 +4221,7 @@ function Test-PkWorkerSafetyCore { ) $findings = [System.Collections.Generic.List[object]]::new() - $kitNames = [System.Collections.Generic.HashSet[string]]::new([string[]]@(Get-PkWorkerSafeFunctionNames), [System.StringComparer]::OrdinalIgnoreCase) + $kitNames = [System.Collections.Generic.HashSet[string]]::new([string[]]@(Get-PkWorkerSafeFunctionName), [System.StringComparer]::OrdinalIgnoreCase) $listed = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase) foreach ($n in $kitNames) { $null = $listed.Add($n) } foreach ($n in $SharedFunctionNames) { $null = $listed.Add($n) } @@ -4314,7 +4307,7 @@ function Test-PkWorkerSafetyCore { $closureNote = "" if ($null -ne $WorkerScript.Module -and $WorkerScript.Module.Name -like '__DynamicModule_*') { $closureNote = ".GetNewClosure() doesn't carry variables into a worker: " } $seenNames = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase) - foreach ($ref in (Get-PkUndeclaredVariables -Ast $ast)) { + foreach ($ref in (Get-PkUndeclaredVariable -Ast $ast)) { if ($seenRefs.Contains($ref.Extent.StartOffset)) { continue } if ($ref.Extent.StartScriptPosition.Line -match '#\s*pk:ignore') { continue } if (-not $seenNames.Add($ref.VariablePath.UserPath)) { continue } @@ -4382,6 +4375,6 @@ Export-ModuleMember -Function @( 'Unregister-PkCancellationSource', 'Reset-PkAbortState', 'Request-PkAbort', 'Test-PkAbortSignal', 'Test-PkCancelRequested', 'Get-PkAbortTriggerLabel', 'Invoke-PkRun', 'ConvertTo-PkArgumentString', 'Start-PkProcess', 'Stop-PkProcessTree', 'Wait-PkProcess', 'Complete-PkProcess', 'Invoke-PkProcessWithTimeout', 'Invoke-PkProcessDispatch', 'Invoke-PkProcessBatch', - 'Invoke-PkRunspaceJobs', 'Test-PkWorkerSafety') + 'Invoke-PkRunspaceBatch', 'Test-PkWorkerSafety') } | Import-Module -Global diff --git a/README.md b/README.md index ac20a16..8fffb6e 100644 --- a/README.md +++ b/README.md @@ -51,7 +51,7 @@ foreach ($r in $batch.Results) { } ``` -That's all you need for this case. The worker rules, closures and callback details further down don't apply to it: they only matter for running PowerShell code in parallel (`Invoke-PkRunspaceJobs`) or for the group dispatcher. [Run a list of programs](#run-a-list-of-programs) covers the options, and [Process results](#process-results) what comes back. +That's all you need for this case. The worker rules, closures and callback details further down don't apply to it: they only matter for running PowerShell code in parallel (`Invoke-PkRunspaceBatch`) or for the group dispatcher. [Run a list of programs](#run-a-list-of-programs) covers the options, and [Process results](#process-results) what comes back. ## Who it's for @@ -77,7 +77,7 @@ For running PowerShell code in parallel, most of these are fine and some are sim - **`Start-Job`.** Built in, but each job is a whole new `powershell.exe` process, so every job costs noticeable startup time and memory, and what it returns comes back as serialized copies (properties only, no methods). 5.1's `Start-Job` has no throttle either, so you write the wait-for-a-free-slot loop yourself. Fine for a handful of long jobs, poor for thousands of short ones. - **ThreadJob (`Start-ThreadJob`).** Runs jobs as runspaces in the same process, with a `-ThrottleLimit`. On 5.1 it's the best fit for plain parallel scriptblocks, if you can install a module from the PowerShell Gallery (`Microsoft.PowerShell.ThreadJob`; it ships with PowerShell 7, not 5.1). - **PoshRSJob (`Start-RSJob`).** A community module from the Gallery, also runspace-based, with a `-Throttle` limit and a job-style interface. It hasn't had a release since 2018, it can report a job as Completed before its output is ready (run `Wait-RSJob` before `Receive-RSJob`), and it's hit harder than ThreadJob by the [scriptblock problem](#faq). Where both are an option, ThreadJob is the better pick. -- **A runspace pool by hand** (`[runspacefactory]::CreateRunspacePool`). That's what `Invoke-PkRunspaceJobs` is built on. It works, but you end up writing the polling loop, error collection, cancellation and cleanup yourself, which is most of what this file is. +- **A runspace pool by hand** (`[runspacefactory]::CreateRunspacePool`). That's what `Invoke-PkRunspaceBatch` is built on. It works, but you end up writing the polling loop, error collection, cancellation and cleanup yourself, which is most of what this file is. - **Workflows (`foreach -parallel`).** Still in 5.1, but they use a restricted version of the language, start slowly, and were dropped from PowerShell 6 and later. Not worth starting anything new on. - **`Start-Process` in a loop.** Starts programs without waiting, but can only send their output to files, and the throttling and waiting are up to you. Using `System.Diagnostics.Process` directly gets output into memory, but reading stdout and then stderr the simple way deadlocks once a program fills the pipe you aren't reading. The kit reads both in the background. - **`Invoke-Command -AsJob` against localhost.** Needs PowerShell remoting enabled (on by default only on Windows Server), and connecting to your own machine needs an elevated session, all for no gain on one machine. @@ -93,7 +93,7 @@ The kit's public functions, by what they're for. Everything else in the file is | **Engines** | | | `Invoke-PkProcessBatch` | Run a flat list of external programs, a set number at a time, and get one result per command. | | `Invoke-PkProcessDispatch` | Run programs that come in groups, with retries or follow-up jobs and a callback when each group is done. | -| `Invoke-PkRunspaceJobs` | Run a PowerShell worker script many times in parallel, in runspaces. | +| `Invoke-PkRunspaceBatch` | Run a PowerShell worker script many times in parallel, in runspaces. | | `Invoke-PkRun` | Wrap any of the above for graceful Ctrl+C: running work finishes before the rest is stopped. | | **One program** | | | `Invoke-PkProcessWithTimeout` | Run one program and wait for it, with a hard time limit. | @@ -165,7 +165,7 @@ Its public functions are imported globally, so they stay available for the rest ## How it fits together -Two engines do the work: the process side runs external programs, and `Invoke-PkRunspaceJobs` runs PowerShell code. `Invoke-PkRun` is an optional wrapper around either one that turns Ctrl+C into a graceful abort. +Two engines do the work: the process side runs external programs, and `Invoke-PkRunspaceBatch` runs PowerShell code. `Invoke-PkRun` is an optional wrapper around either one that turns Ctrl+C into a graceful abort. ```mermaid flowchart TB @@ -173,7 +173,7 @@ flowchart TB B["Invoke-PkProcessBatch"] --> D["Invoke-PkProcessDispatch"] D -->|"default starter"| S["Start-PkProcess"] W["Invoke-PkProcessWithTimeout"] --> S - R["Invoke-PkRunspaceJobs"] --> P["Runspace pool running your worker script"] + R["Invoke-PkRunspaceBatch"] --> P["Runspace pool running your worker script"] end S --> J["Each program inside the kit's Job Object, with a job of its own for killing its tree"] P -.->|"a worker can call the process functions too"| D @@ -243,7 +243,7 @@ Programs run in your current location (`Get-Location`) unless a command says oth
Defaults, time limits, output caps and input -`-OnComplete` runs as each command finishes, but only for commands that actually ran. Check `Results` for the ones that couldn't start or were aborted. A progress counter driven from `-OnComplete` won't reach the total if any did, so count from `$batch.Results` afterwards for the final numbers. Defaults: `-MaxConcurrent` 4, `-AbortTimeoutSeconds` 60 (how long Ctrl+C waits for running programs), `-TimeoutSeconds` 0 (no limit). The runspace engine's names, `-MaxParallel` and `-DrainTimeoutSeconds`, work here too, and on the dispatcher. +`-OnComplete` runs as each command finishes, but only for commands that actually ran. Check `Results` for the ones that couldn't start or were aborted. A progress counter driven from `-OnComplete` won't reach the total if any did, so count from `$batch.Results` afterwards for the final numbers. Defaults: `-MaxConcurrent` 4, `-AbortTimeoutSeconds` 60 (how long Ctrl+C waits for running programs), `-TimeoutSeconds` 0 (no limit). `-TimeoutSeconds 600` kills any program still running after 10 minutes. Its result has `TimedOut = $true`, still goes through `-OnComplete`, and the rest of the batch carries on. The default, 0, means no limit. Any programs it started are killed with it. It can be fractional. A command's own `TimeoutSeconds` key overrides this for that command; 0 opts it out of the limit. A bad value there gives that command a `StartError`. @@ -342,7 +342,7 @@ While a program's output is held open, its command keeps its slot, but the other ## Run PowerShell code in parallel -`Invoke-PkRunspaceJobs` runs a worker script once per job, a set number at a time, and hands what each one returns to your result handler on the main thread. +`Invoke-PkRunspaceBatch` runs a worker script once per job, a set number at a time, and hands what each one returns to your result handler on the main thread. ```powershell # Worker code can use cmdlets - see "The two rules" below for what it can't do. @@ -356,7 +356,7 @@ foreach ($f in Get-ChildItem -File) { $jobs.Add(@{ Path = $f.FullName }) } $shaByPath = @{} $jobsParams = @{ - MaxParallel = 4 + MaxConcurrent = 4 JobParams = $jobs SharedFunctionNames = @('Get-FileSha') WorkerScript = { @@ -367,7 +367,7 @@ $jobsParams = @{ } ResultHandler = { param($r) $shaByPath[$r.Path] = $r.Sha }.GetNewClosure() } -$out = Invoke-PkRun { Invoke-PkRunspaceJobs @jobsParams } +$out = Invoke-PkRun { Invoke-PkRunspaceBatch @jobsParams } ``` Each worker runs in its own runspace: a separate PowerShell session inside the same process, with its own variables and functions. That separation is what makes running them at the same time safe, and also why a worker can't see your script's variables or functions unless you hand them over. Read [the two rules for worker code](#the-two-rules-for-worker-code) before writing one. @@ -381,7 +381,7 @@ Each worker runs in its own runspace: a separate PowerShell session inside the s - A worker runspace starts empty. Name every one of your functions it calls in `-SharedFunctionNames`. The kit's own worker functions are always there, and cmdlets and functions from installed modules load on their own. A module you imported by path isn't installed, so list its functions too (or put it on `$env:PSModulePath`). The kit looks each module up once per session, so one it didn't find and you then install is only seen in a new window. - Your script's variables aren't in the worker either: pass what it needs as job values. `.GetNewClosure()` on the worker doesn't carry them over, since the worker is rebuilt from its text. A worker that reads a variable it never declares or assigns is refused; see [How the kit checks them](#the-two-rules-for-worker-code). - Each job starts in your current location (the real folder, if you're on a `New-PSDrive` drive), in a fresh scope. A folder change or a variable one job makes, preference variables like `$ErrorActionPreference` included, doesn't carry over to the next job. Relative paths in .NET calls such as `[System.IO.File]::ReadAllText('x.txt')` still go by the process's working directory, as they do outside workers, so give .NET full paths. -- `-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. +- `-MaxConcurrent` has no default; you choose it. `-AbortTimeoutSeconds` (how long Ctrl+C waits for running workers) defaults to 60.
@@ -416,7 +416,7 @@ Each worker runs in its own runspace: a separate PowerShell session inside the s ## The two rules for worker code -These only apply if you run PowerShell code in parallel with `Invoke-PkRunspaceJobs` (or call a dispatcher from inside one of its workers). Running external programs with `Invoke-PkProcessBatch` or `Invoke-PkProcessDispatch` on the main thread never touches them. +These only apply if you run PowerShell code in parallel with `Invoke-PkRunspaceBatch` (or call a dispatcher from inside one of its workers). Running external programs with `Invoke-PkProcessBatch` or `Invoke-PkProcessDispatch` on the main thread never touches them. Worker code is the worker script, every function in `-SharedFunctionNames`, and anything they call. Breaking these rules doesn't fail loudly. It hangs, crashes, or quietly reads nothing. @@ -428,7 +428,7 @@ Everything else is fine in a worker, cmdlets included. Callbacks that run on the
How the kit checks them -`Invoke-PkRunspaceJobs` checks both rules before it starts anything, and refuses to launch code that breaks them, naming the line or the job key. Pass `-CheckWorkerSafety:$false` to turn that off. The code check is also available on its own as `Test-PkWorkerSafety -WorkerScript $w -SharedFunctionNames $names`, which returns a list of findings (including functions the worker calls but you didn't share), for use in your own tests. For rule 2 it flags written casts, and scriptblocks passed into a .NET method or constructor, either written in the call or through a variable they were assigned to, parentheses, a `[scriptblock]` cast or `.GetNewClosure()` around them included. `# pk:ignore` on a line accepts a finding. Storing a scriptblock in a collection (`$list.Add($sb)`, `$queue.Enqueue($sb)`) isn't flagged, since that makes no delegate. The check also refuses a worker that reads a variable it never declares or assigns anywhere (`UndeclaredVariable`), since it would read as empty: one of your script's, or one a `.GetNewClosure()` captured. Parameters, assignments, loop variables, `[ref]`, `-OutVariable` and its kind, `Set-Variable` with a literal name, and PowerShell's own variables all count as declared. `$global:` names and drive-qualified ones (`$env:`) aren't checked, and neither are shared functions, which may read their caller's variables. If something the worker runs sets the variable (a helper file it dot-sources, a module it imports), put `# pk:ignore` on the line that reads it. It can't see commands run through a variable (`& $cmd`), a collection typed to hold delegates (`List[Func[object]]`, whose `.Add` converts), or a scriptblock buried more than three levels deep in a job value. +`Invoke-PkRunspaceBatch` checks both rules before it starts anything, and refuses to launch code that breaks them, naming the line or the job key. Pass `-CheckWorkerSafety:$false` to turn that off. The code check is also available on its own as `Test-PkWorkerSafety -WorkerScript $w -SharedFunctionNames $names`, which returns a list of findings (including functions the worker calls but you didn't share), for use in your own tests. For rule 2 it flags written casts, and scriptblocks passed into a .NET method or constructor, either written in the call or through a variable they were assigned to, parentheses, a `[scriptblock]` cast or `.GetNewClosure()` around them included. `# pk:ignore` on a line accepts a finding. Storing a scriptblock in a collection (`$list.Add($sb)`, `$queue.Enqueue($sb)`) isn't flagged, since that makes no delegate. The check also refuses a worker that reads a variable it never declares or assigns anywhere (`UndeclaredVariable`), since it would read as empty: one of your script's, or one a `.GetNewClosure()` captured. Parameters, assignments, loop variables, `[ref]`, `-OutVariable` and its kind, `Set-Variable` with a literal name, and PowerShell's own variables all count as declared. `$global:` names and drive-qualified ones (`$env:`) aren't checked, and neither are shared functions, which may read their caller's variables. If something the worker runs sets the variable (a helper file it dot-sources, a module it imports), put `# pk:ignore` on the line that reads it. It can't see commands run through a variable (`& $cmd`), a collection typed to hold delegates (`List[Func[object]]`, whose `.Add` converts), or a scriptblock buried more than three levels deep in a job value.
@@ -586,7 +586,7 @@ Inside `Invoke-PkRun { ... }`, Ctrl+C: 1. stops new jobs from starting, 2. cancels the run's token (`Test-PkCancelRequested` turns true in workers), -3. waits for in-flight work (`-AbortTimeoutSeconds`, default 60; every engine also takes it as `-DrainTimeoutSeconds`), +3. waits for in-flight work (`-AbortTimeoutSeconds`, default 60), 4. force-stops whatever is left. The batch marks each killed or never-started command's result `Aborted`; the group dispatcher calls `-JobAbortCleanup` for each such job. Press Ctrl+C again to skip step 3: whatever is still running is force-stopped right away, and your script carries on. A third press stops the script the way Ctrl+C normally does, and the kit's engines still kill the programs they started. Presses less than a second apart count as one, and Ctrl+Break works the same as Ctrl+C. @@ -604,14 +604,14 @@ Three things to know: `Invoke-PkRun` also turns off the console's QuickEdit mode for the length of the run (`-DisableQuickEdit $false` to opt out). With QuickEdit on in the classic console window, one stray click starts a text selection, and the script freezes at its next console write until the selection is cleared. That looks exactly like a hang. It's turned back on afterwards if it was on before. -Other pieces: `Request-PkAbort` triggers the same abort from code. `Test-PkAbortSignal` asks whether one is under way. `Register-PkCancellationSource` adds your own `CancellationTokenSource` to the set an abort cancels, and `Unregister-PkCancellationSource` takes it back out (a `-Cts` you pass to `Invoke-PkRunspaceJobs` is added automatically; a `-CancelToken` you pass to the dispatcher isn't canceled by an abort, but the dispatcher stops either way). `Get-PkAbortTriggerLabel` says which kind of abort it was. +Other pieces: `Request-PkAbort` triggers the same abort from code. `Test-PkAbortSignal` asks whether one is under way. `Register-PkCancellationSource` adds your own `CancellationTokenSource` to the set an abort cancels, and `Unregister-PkCancellationSource` takes it back out (a `-Cts` you pass to `Invoke-PkRunspaceBatch` is added automatically; a `-CancelToken` you pass to the dispatcher isn't canceled by an abort, but the dispatcher stops either way). `Get-PkAbortTriggerLabel` says which kind of abort it was. ## Choosing limits - **`-MaxConcurrent` for programs.** For programs that use one CPU core each, start at `[Environment]::ProcessorCount`. Many encoders (image, video, compression) already use several cores per file, so fewer copies at once is often as fast and uses less memory. Programs that mostly wait on disk or network can go higher. Try a few values on real work; the best number depends on the tool. -- **`-MaxParallel` for runspace jobs.** Same idea: the core count for CPU-heavy PowerShell work. Each runspace costs some memory and startup time, so very high values rarely help. +- **`-MaxConcurrent` for runspace jobs.** Same idea: the core count for CPU-heavy PowerShell work. Each runspace costs some memory and startup time, so very high values rarely help. - **Several dispatchers at once** (for example, one per runspace job) should share one `SemaphoreSlim` as `-MaxConcurrent`, so their combined total stays under the limit you picked. They take turns: each pauses up to 50 ms after a program finishes so the others can get the free slot, which costs very short programs some speed compared with a dispatcher of their own. ## Limits @@ -750,12 +750,12 @@ Additions, changes, fixes, and other things that have been evaluated and decline - **Output modes such as `-KeepOutput None|Stderr|All`.** `-MaxOutputChars` caps how much of each stream is kept, and setting `$result.Stdout = $null; $result.Stderr = $null` in `-OnComplete` frees a finished program's output as the batch goes. To throw a stream away completely, redirect it in the command itself (`cmd /c tool.exe 2>nul`). - **Writing output past the `-MaxOutputChars` cap to a file.** The kit can't know where you'd want those files or when they're safe to delete. If you need all of a program's output, redirect it in the command (`cmd /c tool.exe > out.txt 2>&1`) or use the program's own output option. - **More fields on results, such as `Index`, `Status`, `JobId` or batch totals.** Any key you put on a command comes back on its result's `Command`, so `Index = $n` lets you sort on it: `$batch.Results | Sort-Object { $_.Command.Index }`. A `Status` field would only repeat `ExitCode`, `StartError`, `TimedOut` and `Aborted`, and what counts as failure is up to you: some programs exit nonzero on success. -- **Renaming parameters or result fields.** A rename would break existing scripts. Where the engines' names differ, both work on every engine: `-MaxParallel` and `-MaxConcurrent`, `-DrainTimeoutSeconds` and `-AbortTimeoutSeconds`. Result fields have no aliases, since an alias would show up as a second column in `Format-Table`, `Export-Csv` and JSON. +- **Aliases for result fields.** An alias would show up as a second column in `Format-Table`, `Export-Csv` and JSON. - **Built-in structured logging (JSON Lines, lifecycle events).** `Set-PkMessageHandler` receives every message the kit writes, with its level, `-OnComplete` and `-ResultHandler` see each result, and `-JobFinalize` each finished job, so you can write whatever format you need from there. An event for every job, built in, would slow the engines on Windows PowerShell 5.1. - **Signing the release.** That needs a paid code-signing certificate. If your machines require signed scripts (`AllSigned`), sign the file with a certificate they trust, as [Setup](#setup) says. - **Separate checksums or build provenance.** The release asset is `ParallelKit.ps1` itself, attached straight from the tagged source with no build step, and GitHub shows a SHA-256 digest for it on the release page. Compare it with `Get-FileHash .\ParallelKit.ps1`. - **Avoiding the private part of .NET the kit uses.** To create a program inside the Job Object, the kit briefly makes its output pipes inheritable, and holds .NET's own process-start lock meanwhile so that no other program PowerShell or .NET starts at that moment picks them up. That lock isn't public. If a future .NET moves it, the kit doesn't fail: it starts programs the older way, warns once, and `Initialize-ParallelKit` reports `StartMode` `AddedToJob` (see [Process-tree cleanup limitations](#process-tree-cleanup-limitations)). Doing without the lock would mean always using that older way, or risking output held open by an unrelated program. -- **Fractional abort and drain timeouts.** `-AbortTimeoutSeconds` and `-DrainTimeoutSeconds` are whole seconds; 2.5 is rounded to a whole number. `-TimeoutSeconds`, the time limit on a program, does take fractions. +- **Fractional abort timeouts.** `-AbortTimeoutSeconds` is whole seconds; 2.5 is rounded to a whole number. `-TimeoutSeconds`, the time limit on a program, does take fractions. diff --git a/Testing/cmdlet-hang/inner.ps1 b/Testing/cmdlet-hang/inner.ps1 index 9dbb126..c6696c6 100644 --- a/Testing/cmdlet-hang/inner.ps1 +++ b/Testing/cmdlet-hang/inner.ps1 @@ -1,5 +1,5 @@ # One stress trial, run in a fresh powershell.exe by run.ps1. -# Runs -Rounds separate Invoke-PkRunspaceJobs calls (a new runspace pool, so +# Runs -Rounds separate Invoke-PkRunspaceBatch calls (a new runspace pool, so # fresh runspaces, each round). In each round all -Workers workers wait on a # gate, then are released at the same instant into the -Mode body - the # "first cmdlet call in two fresh runspaces at once" case this was written to @@ -120,7 +120,7 @@ try { } }.GetNewClosure() $crashes = [System.Collections.Generic.List[string]]::new() - $out = Invoke-PkRunspaceJobs -MaxParallel $Workers -JobParams $jobs -WorkerScript $worker ` + $out = Invoke-PkRunspaceBatch -MaxConcurrent $Workers -JobParams $jobs -WorkerScript $worker ` -PollCallback $poll -JobCrashedHandler { param($err) $crashes.Add([string]$err) }.GetNewClosure() if ($state.GateTimedOut) { Write-Progress2 "round $round gate-timeout" } foreach ($c in $crashes) { Write-Progress2 "round $round crash: $c" } diff --git a/Testing/hosts/check-host.ps1 b/Testing/hosts/check-host.ps1 index d8034cd..259e66a 100644 --- a/Testing/hosts/check-host.ps1 +++ b/Testing/hosts/check-host.ps1 @@ -35,7 +35,7 @@ try { Write-Log ("batch returned after " + [int]$sw.Elapsed.TotalSeconds + "s: aborted=" + $batch.Aborted + " results=" + $batch.Results.Count + " exit codes=" + (@($batch.Results | ForEach-Object { $_.ExitCode }) -join ',')) Reset-PkAbortState - $jobs = Invoke-PkRunspaceJobs -MaxParallel 2 -JobParams @(@{ Id = 1 }, @{ Id = 2 }) -WorkerScript { param($Id) Write-PkMessage ("worker " + $Id); $Id * 10 } -ResultHandler { param($r) Write-Log ("worker result: " + $r) } + $jobs = Invoke-PkRunspaceBatch -MaxConcurrent 2 -JobParams @(@{ Id = 1 }, @{ Id = 2 }) -WorkerScript { param($Id) Write-PkMessage ("worker " + $Id); $Id * 10 } -ResultHandler { param($r) Write-Log ("worker result: " + $r) } Write-Log ("runspace jobs: crashed=" + $jobs.CrashedCount + " aborted=" + $jobs.Aborted) Write-Log "done" } catch { diff --git a/Testing/readme-examples/run.ps1 b/Testing/readme-examples/run.ps1 index 47f12aa..58335cb 100644 --- a/Testing/readme-examples/run.ps1 +++ b/Testing/readme-examples/run.ps1 @@ -143,14 +143,14 @@ $tests.Add(@{ Name = 'Worker that returns its own error object'; Body = $pngs + . $Kit $global:results = [System.Collections.Generic.List[object]]::new() $jobsParams = @{ - MaxParallel = 2 + MaxConcurrent = 2 JobParams = @(@{ Path = (Join-Path $Data 'a.png') }, @{ Path = (Join-Path $Data 'missing.png') }) ResultHandler = { param($r) $global:results.Add($r) } '@ + (Get-Example 'Error = $_.Exception.Message') + @' } -$out = Invoke-PkRunspaceJobs @jobsParams +$out = Invoke-PkRunspaceBatch @jobsParams Test-Check ($global:results.Count -eq 2) "a result per job ($($global:results.Count) of 2)" $good = @($global:results | Where-Object { $_.Path -like '*a.png' })[0] $missing = @($global:results | Where-Object { $_.Path -like '*missing.png' })[0] @@ -166,7 +166,7 @@ function Write-MyLog($Message, $Level) { $global:log.Add("$Level|$Message") } '@ + (Get-Example 'Set-PkMessageHandler { param($Message, $Level)') + @' -$null = Invoke-PkRunspaceJobs -MaxParallel 2 -JobParams @(@{ N = 1 }) -WorkerScript { param($N) Write-PkMessage "from worker $N" -Level Warning } +$null = Invoke-PkRunspaceBatch -MaxConcurrent 2 -JobParams @(@{ N = 1 }) -WorkerScript { param($N) Write-PkMessage "from worker $N" -Level Warning } Write-PkMessage 'from the main thread' -Level Error Test-Check ($global:log -contains 'Warn|from worker 1') "a worker's -Level Warning arrives as Warn ($($global:log -join '; '))" Test-Check ($global:log -contains 'Error|from the main thread') 'a main-thread message arrives' @@ -240,7 +240,7 @@ $tests.Add(@{ Name = "Get-FileHash and a worker's `$ErrorActionPreference"; Body . $Kit $missingFile = Join-Path $Data 'missing.png' $global:results = [System.Collections.Generic.List[string]]::new() -$null = Invoke-PkRunspaceJobs -MaxParallel 1 -JobParams @(@{ Path = $missingFile; UseParam = $false }, @{ Path = $missingFile; UseParam = $true }) -ResultHandler { param($r) $global:results.Add($r) } -WorkerScript { +$null = Invoke-PkRunspaceBatch -MaxConcurrent 1 -JobParams @(@{ Path = $missingFile; UseParam = $false }, @{ Path = $missingFile; UseParam = $true }) -ResultHandler { param($r) $global:results.Add($r) } -WorkerScript { param($Path, $UseParam) $ErrorActionPreference = 'Stop' try { diff --git a/Testing/soak/run.ps1 b/Testing/soak/run.ps1 index 95c097f..1e713a8 100644 --- a/Testing/soak/run.ps1 +++ b/Testing/soak/run.ps1 @@ -4,7 +4,7 @@ # Each round runs 250 programs through Invoke-PkProcessBatch: quick ones, # ones that print more than a -MaxOutputChars cap, ones that leave a helper # holding their output past -StreamTimeoutMs, and ones killed at a time -# limit. Then 100 runspace jobs through Invoke-PkRunspaceJobs. Helpers left +# limit. Then 100 runspace jobs through Invoke-PkRunspaceBatch. Helpers left # holding output carry -w 4328 on their command line, and only those are # killed between rounds. # @@ -74,7 +74,7 @@ try { $timedOut = @($b.Results | Where-Object { $_.TimedOut }).Count if (-not $Compat) { $capped = @($b.Results | Where-Object { $_.StdoutDroppedChars -gt 0 }).Count } } - if (-not $NoRunspace) { $rsErrors = (Invoke-PkRunspaceJobs -MaxParallel 8 -JobParams $jobParams -WorkerScript { param($Id) $Id * 2 }).Errors.Count } + if (-not $NoRunspace) { $rsErrors = (Invoke-PkRunspaceBatch -MaxConcurrent 8 -JobParams $jobParams -WorkerScript { param($Id) $Id * 2 }).Errors.Count } Stop-SoakHelpers $c = Get-SoakCounts $row = [pscustomobject]@{ Round = $r; Seconds = [math]::Round($sw.Elapsed.TotalSeconds, 1); Handles = $c.Handles; Threads = $c.Threads; ManagedMB = $c.ManagedMB; PrivateMB = $c.PrivateMB; Bad = $bad; TimedOut = $timedOut; Capped = $capped; RunspaceErrors = $rsErrors }