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 01/10] 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 02/10] 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 03/10] 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 04/10] 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 05/10] 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 } From 99112bd97bb38124b52d5a7ddcd824355f2a69fc Mon Sep 17 00:00:00 2001 From: Hal <22532613+HalRiveria@users.noreply.github.com> Date: Tue, 1 Dec 2026 17:19:38 -0500 Subject: [PATCH 06/10] Remove names and code nothing uses, and review the kit's comments Initialize-ParallelKit loses -MaxConcurrentProcesses and ThreadPool, and the dispatcher its -AbortPollCallback alias. Code nothing reaches goes too. The stale-types message says "a different version". Two functions declare their output type. The comments are shorter and checked against the code. Co-Authored-By: Claude Opus 5.5 --- ParallelKit.Harness.ps1 | 43 ++++---- ParallelKit.ps1 | 195 ++++++++++++++++------------------- README.md | 3 +- Testing/hosts/check-host.ps1 | 2 +- 4 files changed, 112 insertions(+), 131 deletions(-) diff --git a/ParallelKit.Harness.ps1 b/ParallelKit.Harness.ps1 index 6fea69c..5b125a8 100644 --- a/ParallelKit.Harness.ps1 +++ b/ParallelKit.Harness.ps1 @@ -226,13 +226,12 @@ function Protect-HarnessPingChild { # ============================================================================== if (Test-HarnessSection 'A' "setup") { -$init = Initialize-ParallelKit -MaxConcurrentProcesses 8 +$init = Initialize-ParallelKit Test-Assert ($init.AbortHandler -eq $true) "abort handler registers" Test-Assert ($init.ChildProcessJob -eq $true) "child-process job object initializes" # For PkHarnessJobProbe, in several sections. Here because A always runs, and # the handle exists only once the Job Object has been set up. $jobHandle = [PkChildProcessJob].GetField('_job', [System.Reflection.BindingFlags]'NonPublic,Static').GetValue($null) -Test-Assert ($init.ThreadPool -eq $true) "ThreadPool is still `$true, for scripts that check it" $w = 0; $io = 0 [System.Threading.ThreadPool]::GetMinThreads([ref]$w, [ref]$io) Test-Assert ($w -eq $poolMinBefore -and $io -eq $poolIoBefore) ("Initialize-ParallelKit leaves the thread pool's minimum alone (" + $w + "/" + $io + ", was " + $poolMinBefore + "/" + $poolIoBefore + ")") @@ -400,7 +399,8 @@ try { $null = Start-PkProcess -FilePath 'C:\no\such\program.exe' } catch { $thre Test-Assert $threw "a program that can't be started throws a clear error (not a silent null)" $j = Start-PkProcess -FilePath $cmdExe -Arguments '/c exit 0' $null = Wait-PkProcess -Process $j.Proc -TimeoutMs 5000 -Test-Assert ([PkChildProcessJob]::Assign($j.Proc) -or $j.Proc.HasExited) "started processes are tied to the job object" +$assignWhy = $null +Test-Assert ([PkChildProcessJob]::Assign($j.Proc, [ref]$assignWhy) -or $j.Proc.HasExited) "started processes are tied to the job object" $j.Proc.Dispose() # ConvertTo-PkArgumentString: exact output for the tricky cases, then a @@ -1470,7 +1470,7 @@ try { . '$kitPath'; Write-Output 'LOADED' } catch { Write-Output ('REFUSED: ' + "@) $stale = Invoke-PkProcessWithTimeout -FilePath $selfExe -Arguments ('-NoProfile -ExecutionPolicy Bypass -File "' + $staleScript + '"') -TimeoutMs 60000 [System.IO.File]::Delete($staleScript) -Test-Assert ($stale.Stdout -like '*REFUSED:*older version of the kit*start a new one*') "loading the kit over an older copy's types is refused with a clear message" +Test-Assert ($stale.Stdout -like '*REFUSED:*a different version of the kit*start a new one*') ("loading the kit over another version's types is refused with a clear message (" + ([string]$stale.Stdout).Trim() + ")") # Invoke-PkRun keeps the PC from idle-sleeping only while it runs. Checked # on this thread: SetThreadExecutionState returns the thread's previous @@ -1586,7 +1586,7 @@ Test-Assert ((Get-HarnessShape $shapeJobs) -eq 'ForceStoppedCount,CrashedCount,A $shapeFindings = Test-PkWorkerSafety -WorkerScript { param($Id) $null = [Func[int]]{ 1 } } $shapeFinding = $shapeFindings[0] Test-Assert ((Get-HarnessShape $shapeFinding) -eq 'Rule,Where,Line,Text') ("worker-safety findings are objects (" + (Get-HarnessShape $shapeFinding) + ")") -Test-Assert ((Get-HarnessShape (Initialize-ParallelKit)) -eq 'AbortHandler,ChildProcessJob,ThreadPool,Version,StartMode') "Initialize-ParallelKit returns an object" +Test-Assert ((Get-HarnessShape (Initialize-ParallelKit)) -eq 'AbortHandler,ChildProcessJob,Version,StartMode') "Initialize-ParallelKit returns an object" $fields = @('Command', 'ExitCode', 'Stdout', 'Stderr', 'StreamTimedOut', 'StreamError', 'StartError', 'Aborted', 'TimedOut', 'Duration') $batch = Invoke-PkProcessBatch -MaxConcurrent 1 -Commands @( @@ -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 -AbortTimeoutSeconds 4 } catch { $threw = [string]$_ } -Test-Assert ($threw -like '*AbortTimeoutSeconds*') "Initialize-ParallelKit -AbortTimeoutSeconds (an engine's parameter) is an error, not ignored" +try { $null = Initialize-ParallelKit -MaxConcurrent 4 } catch { $threw = [string]$_ } +Test-Assert ($threw -like '*MaxConcurrent*') "Initialize-ParallelKit -MaxConcurrent (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" @@ -3675,21 +3675,24 @@ $null = Invoke-PkRunspaceBatch -MaxConcurrent 1 -JobParams (New-JobList -Jobs @( $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 + ")") -# The dispatcher's -PollCallback, and its alias -AbortPollCallback. +# The dispatcher's -PollCallback, and the names 4.0 removed. Reset-Harness -foreach ($apiName in 'PollCallback', 'AbortPollCallback') { - $apiFeed = @{ Given = $false; Polls = 0 } - $apiParams = @{ - MaxConcurrent = 1 - GroupProvider = { if ($apiFeed.Given) { return $null }; $apiFeed.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 } - } - $apiParams[$apiName] = { param($running) $apiFeed.Polls++ }.GetNewClosure() - $apiRun = Invoke-PkProcessDispatch @apiParams - Test-Assert ($apiFeed.Polls -gt 0 -and $apiRun.GroupResults.Count -eq 1) ("the dispatcher takes -" + $apiName + " (" + $apiFeed.Polls + " passes)") +$apiFeed = @{ Given = $false; Polls = 0 } +$apiParams = @{ + MaxConcurrent = 1 + GroupProvider = { if ($apiFeed.Given) { return $null }; $apiFeed.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 } + PollCallback = { param($running) $apiFeed.Polls++ }.GetNewClosure() } -Test-Assert ((Get-Command Invoke-PkProcessDispatch).Parameters['PollCallback'].Aliases -contains 'AbortPollCallback') "-AbortPollCallback is an alias of -PollCallback" +$apiRun = Invoke-PkProcessDispatch @apiParams +Test-Assert ($apiFeed.Polls -gt 0 -and $apiRun.GroupResults.Count -eq 1) ("the dispatcher takes -PollCallback (" + $apiFeed.Polls + " passes)") +$threw = $null +try { $null = Invoke-PkProcessDispatch -AbortPollCallback { } -MaxConcurrent 1 -GroupProvider { } -JobBuilder { } -JobFinalize { } } catch { $threw = [string]$_ } +Test-Assert ($threw -like "*parameter name 'AbortPollCallback'*") ("its old name -AbortPollCallback is an error (" + $threw + ")") +$threw = $null +try { $null = Initialize-ParallelKit -MaxConcurrentProcesses 8 } catch { $threw = [string]$_ } +Test-Assert ($threw -like "*parameter name 'MaxConcurrentProcesses'*") ("Initialize-ParallelKit -MaxConcurrentProcesses is an error (" + $threw + ")") Reset-Harness Write-Host "" } diff --git a/ParallelKit.ps1 b/ParallelKit.ps1 index 69504c9..62f1ac5 100644 --- a/ParallelKit.ps1 +++ b/ParallelKit.ps1 @@ -153,8 +153,8 @@ public static class PkSleepBlock public static bool Unblock() { return SetThreadExecutionState(0x80000000u) != 0; } } -// Main-thread bookkeeping. Static on purpose - see the note at the top of -// ParallelKit.ps1. +// Main-thread bookkeeping. Static on purpose: see the note at the top of this +// file. public static class PkState { public static bool AbortLatched = false; @@ -163,7 +163,7 @@ public static class PkState // Bump this, and the check after the type definitions, whenever any C# // in this file changes: a session keeps the types it compiled first. - public const int TypesVersion = 13; + public const int TypesVersion = 14; // Locked: Register-/Unregister-PkCancellationSource are callable from // worker runspaces, and List is not safe for concurrent writers. @@ -180,7 +180,7 @@ public static class PkState public static readonly System.Collections.Concurrent.ConcurrentDictionary ModuleFound = new System.Collections.Concurrent.ConcurrentDictionary(StringComparer.OrdinalIgnoreCase); - // Get-PkPredefinedVariable' answer for this session. + // Get-PkPredefinedVariable's answer for this session. public static HashSet PredefinedVariables = null; } '@ -Language CSharp @@ -254,24 +254,24 @@ public sealed class PkStartedProcess } // Reads one of a program's output streams to its end, in chunks, so what has -// arrived can be taken at any time (Snapshot): a program the program started +// arrived can be taken at any time (Snapshot): something the program started // can hold the stream open long after it exits. The first snapshot taken -// before the end is the stream's text from then on: the read carries on to -// the end, so the program holding the stream never blocks on a full pipe, -// but drops what it reads, which nobody can get any more. The task's result -// is that snapshot, or the whole text if none was taken. The reader is -// closed at the end of the stream. The reader's decoder carries a -// character split across two reads over to the next, and a snapshot leaves -// out a surrogate pair's first half whose second half hasn't arrived, so a -// snapshot never ends in half a character. Each read runs on a thread of its own -// (LongRunning), not a thread-pool thread: a read blocks until every holder -// of the stream's write end has let go (at the latest when PowerShell exits: -// they're in the Job Object), and leftover programs holding their output -// would otherwise use up the pool, so a new program's reads would wait for -// the pool to grow and hit their stream timeout. With a cap (maxChars), only -// the first half and the last half of a longer stream are kept, never split -// inside a surrogate pair; DroppedChars counts the rest. The read still goes -// to the end, so the program never blocks on a full pipe. +// before the end is the stream's text from then on, and the task's result; +// without one, the result is the whole text. The read goes on to the end +// either way, dropping what it no longer needs, so nothing that writes to the +// stream blocks on a full pipe. The reader is closed there. +// +// No text ends in half a character: the decoder carries one split across two +// reads over to the next, and a snapshot leaves out a surrogate pair's first +// half whose second hasn't arrived. With a cap (maxChars), only the first half +// and the last half of a longer stream are kept, never split inside a pair, +// and DroppedChars counts the rest. +// +// Each read has a thread of its own (LongRunning), not a pool thread: it +// blocks until every holder of the stream's write end has let go (at the +// latest when PowerShell exits: they're in the Job Object). Leftover programs +// holding their output would otherwise use up the pool, and a new program's +// reads would wait for it to grow and hit their stream timeout. public sealed class PkStreamReadTask : Task { private sealed class Buffer @@ -397,8 +397,6 @@ public sealed class PkStreamReadTask : Task private readonly Buffer _buffer; private PkStreamReadTask(Buffer buffer) : base(new Func(buffer.Pump), TaskCreationOptions.LongRunning) { _buffer = buffer; } - public static PkStreamReadTask Run(TextReader reader) { return Run(reader, 0); } - // maxChars: 0 for no cap. public static PkStreamReadTask Run(TextReader reader, int maxChars) { @@ -481,7 +479,7 @@ public static class PkChildProcessJob // A program's tree job, closed by ReleaseTree or, failing that, when its // Process object is collected. Without KILL_ON_JOB_CLOSE: closing it - // leaves whatever is still running in the kit's job, as before. + // leaves whatever is still running in the kit's job. private sealed class TreeJob : SafeHandleZeroOrMinusOneIsInvalid { public TreeJob(IntPtr h) : base(true) { SetHandle(h); } @@ -498,7 +496,7 @@ public static class PkChildProcessJob private static void AddTree(Process process, IntPtr treeJob) { try { _treeJobs.Add(process, new TreeJob(treeJob)); } - catch (ArgumentException) { CloseHandle(treeJob); } // already has one (can't happen: each start is a new Process) + catch (ArgumentException) { CloseHandle(treeJob); } // already has one: a second Assign of the same Process } // Kills every process in the program's tree job. False if it has none, @@ -580,16 +578,10 @@ public static class PkChildProcessJob // Never throws: a failed assignment only loses the force-kill cleanup // for that one process. Once it's in the kit's job, it also gets a tree - // job (Windows nests it); without one, a kill uses taskkill. - public static bool Assign(System.Diagnostics.Process process) - { - string reason; - return Assign(process, out reason); - } - - // The same, saying why it failed ("Win32 error 5", or what was thrown); - // null when it worked. Per call: LastError is shared, and another - // thread's start can change it before the caller reads it. + // job (Windows nests it); without one, a kill uses taskkill. reason says + // why it failed ("Win32 error 5", or what was thrown), null when it + // worked. Per call: LastError is shared, and another thread's start can + // change it before the caller reads it. public static bool Assign(System.Diagnostics.Process process, out string reason) { reason = null; @@ -926,8 +918,8 @@ public static class PkChildProcessJob try { // Setup: a failure here falls back to Process.Start and Assign - // (3.1's way) instead of failing the start. Only CreateProcess - // itself, below, reports that the program couldn't start. + // instead of failing the start. Only CreateProcess itself, + // below, reports that the program couldn't start. try { CreateOutputPipe(out outRead, out outWrite); @@ -1074,11 +1066,11 @@ public static class PkChildProcessJob '@ -Language CSharp } -# A session that loaded an older copy keeps its compiled types. Say so, -# rather than fail later with a missing-method error. Keep this number in +# A session that loaded another version keeps that one's compiled types. Say +# so, rather than fail later with a missing-method error. Keep this number in # sync with [PkState]::TypesVersion. -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." +if ((& { try { [PkState]::TypesVersion } catch { 0 } }) -ne 14) { + throw "ParallelKit: this PowerShell session already loaded a different 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-PkRunspaceBatch, null elsewhere: how kit @@ -1174,7 +1166,6 @@ function Write-PkMessage { 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 } $item = $null while ($Queue.TryDequeue([ref]$item)) { Invoke-PkMessageHandler -Message $item.Message -Level $item.Level @@ -1209,14 +1200,10 @@ function Write-PkCallbackLoopWarning { # once per -PkName in a run. -PkContext is the run's @{ Prefix; Warned }: # Prefix names the engine, Warned the names already warned about. param([string]$PkName, [hashtable]$PkContext) - $pkFullName = $PkName - if ($null -ne $PkContext) { - $pkWarned = $PkContext['Warned'] - if ($pkWarned.ContainsKey($PkName)) { return } - $pkWarned[$PkName] = $true - $pkFullName = [string]$PkContext['Prefix'] + $PkName - } - Write-PkMessage ($pkFullName + " used 'continue' or 'break' outside a loop of its own. PowerShell sends those to the nearest loop, which here is one of the kit's, so the kit stopped the callback there instead. Use 'return' to leave a callback early.") -Level Warn + $pkWarned = $PkContext['Warned'] + if ($pkWarned.ContainsKey($PkName)) { return } + $pkWarned[$PkName] = $true + Write-PkMessage ([string]$PkContext['Prefix'] + $PkName + " used 'continue' or 'break' outside a loop of its own. PowerShell sends those to the nearest loop, which here is one of the kit's, so the kit stopped the callback there instead. Use 'return' to leave a callback early.") -Level Warn } # ============================================================================== @@ -1249,29 +1236,21 @@ function Initialize-ParallelKit { # .DESCRIPTION # The engines set up what they need on first use anyway. Safe to call more than # once. A failed Ctrl+C handler or child-process cleanup also prints a warning. - # .PARAMETER MaxConcurrentProcesses - # Not used since 3.4, which leaves the thread pool's settings alone; kept so - # existing calls still work. # .OUTPUTS # An object with AbortHandler and ChildProcessJob, each $true if that part - # worked; ThreadPool, always $true since 3.4 (kept for scripts that check - # it); Version, the kit's version; and StartMode, how the kit starts + # worked; Version, the kit's version; and StartMode, how the kit starts # programs here: CreatedInJob (inside the Job Object, so anything they start # is in it too), AddedToJob (started, then added to it just after), or NoJob # (no cleanup if PowerShell is killed). A program whose start can't be set up # in the job falls back to AddedToJob, with a warning. [CmdletBinding()] - param([int]$MaxConcurrentProcesses = 0) + param() $handlerOk = Register-PkAbortHandler $jobOk = Initialize-PkChildProcessJob - # The kit used to raise the thread pool's minimum here, for output reads on - # pool threads. Those have threads of their own now (PkStreamReadTask), and - # the minimum is a setting the caller's own code shares. - $poolOk = $true # The header's Version line: the version PR changes both, and the harness # checks they match. $version = [version]'3.5' - return [pscustomobject][ordered]@{ AbortHandler = $handlerOk; ChildProcessJob = $jobOk; ThreadPool = $poolOk; Version = $version; StartMode = [PkChildProcessJob]::StartMode } + return [pscustomobject][ordered]@{ AbortHandler = $handlerOk; ChildProcessJob = $jobOk; Version = $version; StartMode = [PkChildProcessJob]::StartMode } } function Register-PkCancellationSource { @@ -1380,6 +1359,7 @@ function Test-PkCancelRequested { # .OUTPUTS # [bool] [CmdletBinding()] + [OutputType([bool])] param() if ($null -ne $global:PkCancelToken -and $global:PkCancelToken.IsCancellationRequested) { return $true } return [PkConsoleCtrl]::AbortRequested @@ -1392,6 +1372,7 @@ function Get-PkAbortTriggerLabel { # .OUTPUTS # [string] [CmdletBinding()] + [OutputType([string])] param() if ([PkState]::CloseAbort) { return "window close (X button)" } $pressedKey = [PkConsoleCtrl]::PressedKey @@ -1469,7 +1450,7 @@ function Invoke-PkRun { } # ============================================================================== -# External processes (all raw .NET - safe inside workers) +# External processes (safe inside workers) # ============================================================================== function ConvertTo-PkArgumentString { @@ -1517,10 +1498,11 @@ function ConvertTo-PkArgumentString { function ConvertTo-PkArgumentStringCore { # ConvertTo-PkArgumentString's body. -ForBatchFile: for cmd.exe or a .bat # or .cmd, whose command line cmd.exe reads first, a quote is written "" - # instead of \". cmd.exe counts every quote, \" included, so with \" an argument like - # a" & del ... & " runs a second command. "" keeps the count even, and the - # C runtime still reads it as one quote in a program the batch file passes - # %* to. A line break would end cmd.exe's command line, so it's refused. + # instead of \". cmd.exe counts every quote, \" included, so with \" an + # argument like a" & del ... & " runs a second command. "" keeps the count + # even, and the C runtime (not the old msvcrt.dll) still reads it as one + # quote in a program the batch file passes %* to. A line break would end + # cmd.exe's command line, so it's refused. param( [AllowNull()] [AllowEmptyCollection()] @@ -2166,21 +2148,21 @@ function Complete-PkProcess { [int]$StreamTimeoutMs = 15000, [switch]$Dispose ) - # A negative wait isn't a limit: -1 waited until the output closed, however - # long a leftover child held it. Invoke-PkProcessWithTimeout checks it too, - # before starting its program. + # -1 would wait until the output closes, however long a leftover child + # holds it. Invoke-PkProcessWithTimeout checks it too, before starting its + # program. if ($StreamTimeoutMs -lt 0) { throw ("Complete-PkProcess: -StreamTimeoutMs must be 0 or more (got " + $StreamTimeoutMs + "). It's how long to wait for the output after the program exits, in milliseconds; 0 doesn't wait.") } $result = [ordered]@{ ExitCode = $null; Stdout = $null; Stderr = $null; StreamTimedOut = $false; StreamError = $null; Duration = $null StdoutDroppedChars = [long]0; StderrDroppedChars = [long]0 } + # -KillTreeOnExit, set by Invoke-PkProcessWithTimeout and the dispatcher, + # whose default poll has done this already. Before the output wait, since + # that's what the leftovers hold up. + if ($Job['KillTree']) { Stop-PkExitedJobTree -Job $Job } # A custom starter's job may have no read tasks, and a read can fail. # Neither throws: this runs inside JobFinalize, where a throw stops the # whole dispatcher. - # KillTree: -KillTreeOnExit, set by Invoke-PkProcessWithTimeout and the - # dispatcher. The dispatcher's default poll has done this already. Before - # the output wait, since it's what the leftovers hold up. - if ($Job['KillTree']) { Stop-PkExitedJobTree -Job $Job } $tasks = [System.Collections.Generic.List[System.Threading.Tasks.Task]]::new() if ($null -ne $Job['StdoutTask']) { $tasks.Add($Job['StdoutTask']) } if ($null -ne $Job['StderrTask']) { $tasks.Add($Job['StderrTask']) } @@ -2213,12 +2195,10 @@ function Complete-PkProcess { if ($task.IsFaulted) { $result.StreamError = [string]$task.Exception.GetBaseException().Message; break } } } - # The output's end (both streams closed, or the timeout) is separate from - # the program's end (the exit code, below): a program it started can hold - # a stream open after it exits. A stream still open at the timeout gives - # the text that arrived before it, each stream on its own; its read - # carries on in the background until that program lets go, dropping - # what arrives after (Snapshot keeps the text it returns). + # A stream still open at the timeout (a program the job's own started can + # hold it open) gives the text that arrived before it, each stream on its + # own; its read carries on in the background, dropping what arrives after + # (Snapshot keeps the text it returns). $ranToCompletion = [System.Threading.Tasks.TaskStatus]::RanToCompletion foreach ($stream in 'Stdout', 'Stderr') { $task = $Job[$stream + 'Task'] @@ -2232,7 +2212,7 @@ function Complete-PkProcess { # The program's end, not the output's: before Dispose, which loses it. $result.Duration = Get-PkProcessDuration -Process $Job['Proc'] # The program has exited: its tree job's handle can go. Anything it left - # running stays in the kit's job, as before. + # running stays in the kit's job. if ($Job['Proc'] -is [System.Diagnostics.Process]) { [PkChildProcessJob]::ReleaseTree($Job['Proc']) } if ($Dispose) { $Job['Proc'].Dispose() } return [pscustomobject]$result @@ -2353,13 +2333,13 @@ function Invoke-PkProcessDispatch { # The dispatcher keeps its own state on each job hashtable. Don't use these keys # for anything else: GroupKey, SlotReleased, Proc, StdoutTask, StderrTask, # Stopwatch, TimeLimit, TimedOut, KillTree, StartFailureReported, OutputWait, - # OutputWaitOver, OutputWaitMs. It also sets Group to - # the job's group, unless the job already has a Group of its own. The default - # starter reads FilePath, Arguments (a string as written, or a list quoted one - # argument per element), WorkingDirectory, OutputEncoding, MaxOutputChars and - # InheritStdin from the job. A job's TimeoutSeconds key overrides - # -TimeoutSeconds, and its MaxOutputChars, InheritStdin and KillTreeOnExit keys - # the parameters of the same names. + # OutputWaitOver, OutputWaitMs. It also sets Group to the job's group, unless + # the job already has a Group of its own. The default starter reads FilePath, + # Arguments (a string as written, or a list quoted one argument per element), + # WorkingDirectory, OutputEncoding, MaxOutputChars and InheritStdin from the + # job. A job's TimeoutSeconds key overrides -TimeoutSeconds, and its + # MaxOutputChars, InheritStdin and KillTreeOnExit keys the parameters of the + # same names. # .PARAMETER GroupProvider # { } returning the next group, or $null when there are no more, and # outputting nothing else. Return a list as one group with a comma: @@ -2374,8 +2354,8 @@ function Invoke-PkProcessDispatch { # { param($job) } returning $true once the job is finished. Only its last # output value counts. Default: once the program has exited and its output # has been read, or -StreamTimeoutMs after the exit if a program it started - # holds the output open (the job keeps its slot meanwhile), so Complete-PkProcess in - # -JobFinalize doesn't wait and the other jobs carry on. + # holds the output open (the job keeps its slot meanwhile), so + # Complete-PkProcess in -JobFinalize doesn't wait and the other jobs carry on. # .PARAMETER JobFinalize # { param($job, $pendingQueue) } called once per finished job; collect its # result with Complete-PkProcess. Enqueue new job hashtables onto $pendingQueue @@ -2391,7 +2371,6 @@ function Invoke-PkProcessDispatch { # 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. # .PARAMETER CancelToken # Stops the dispatcher when canceled. An abort stops it either way, without # canceling this token. @@ -2445,7 +2424,6 @@ function Invoke-PkProcessDispatch { [scriptblock]$GroupCompleteCallback = $null, [Parameter(Mandatory)] $MaxConcurrent, - [Alias('AbortPollCallback')] [scriptblock]$PollCallback = $null, [System.Threading.CancellationToken]$CancelToken, [int]$AbortTimeoutSeconds = 60, @@ -2494,9 +2472,9 @@ function Invoke-PkProcessDispatch { # Invoke-PkProcessBatch makes the same -MaxConcurrent, -TimeoutSeconds, # -AbortTimeoutSeconds, -StreamTimeoutMs and -MaxOutputChars checks, so its # errors name the batch: keep the two in step. Start-PkProcess and - # Invoke-PkProcessWithTimeout check -MaxOutputChars the same way. NaN and +Infinity pass a `-lt 0` test and - # acted as no limit. A job's own TimeoutSeconds key follows the same rule - # (Get-PkJobTimeLimit). + # Invoke-PkProcessWithTimeout check -MaxOutputChars the same way. NaN and + # +Infinity pass a `-lt 0` test and would mean no limit. A job's own + # TimeoutSeconds key follows the same rule (Get-PkJobTimeLimit). if ([double]::IsNaN($pkTimeoutSeconds) -or [double]::IsInfinity($pkTimeoutSeconds) -or $pkTimeoutSeconds -lt 0) { throw ("Invoke-PkProcessDispatch: -TimeoutSeconds must be a number of seconds, 0 (no limit) or more (got " + $pkTimeoutSeconds + ").") } @@ -2538,8 +2516,7 @@ function Invoke-PkProcessDispatch { # KillTree (-KillTreeOnExit) kills what the program left running first, # so nothing is left to hold the output. # A closure, so it carries this call's $pkStreamTimeoutMs itself - # rather than finding it by dynamic scope (measured: no slower per - # job than the plain block on 5.1 or 7). + # rather than finding it by dynamic scope. $pkJobPollCompleted = { param($pkJob) if (-not $pkJob['Proc'].HasExited) { return $false } @@ -2551,8 +2528,8 @@ function Invoke-PkProcessDispatch { return ($pkJob['OutputWait'].ElapsedMilliseconds -ge $pkJob['OutputWaitMs']) }.GetNewClosure() } - if ($null -eq $pkJobAbortCleanup) { $pkJobAbortCleanup = { param($pkJob) } } - if ($null -eq $pkGroupCompleteCallback) { $pkGroupCompleteCallback = { param($pkGroup) } } + if ($null -eq $pkJobAbortCleanup) { $pkJobAbortCleanup = { } } + if ($null -eq $pkGroupCompleteCallback) { $pkGroupCompleteCallback = { } } # Token: the caller's; else (in a worker) the run's own; else a fresh one # registered so an abort cancels it. @@ -3270,7 +3247,6 @@ function Invoke-PkProcessBatch { }.GetNewClosure() $pkJobBuilder = { - param($pkGroup) $pkJobs = [System.Collections.Generic.List[hashtable]]::new() foreach ($pkC in $pkCommands) { if ($null -eq $pkC) { continue } @@ -3309,7 +3285,7 @@ function Invoke-PkProcessBatch { }.GetNewClosure() $pkJobFinalize = { - param($pkJob, $pkPendingQueue) + param($pkJob) $pkR = & $pkNewBatchResult -Command $pkJob['Command'] -Completed (& $pkCompleteProcess -Job $pkJob) -TimedOut ([bool]$pkJob['TimedOut']) $pkResults.Add($pkR) if ($null -ne $pkOnComplete) { @@ -3318,7 +3294,6 @@ function Invoke-PkProcessBatch { $null = do { & $pkOnComplete $pkJob['Command'] $pkR; $pkCbDone = $true } while ($false) if (-not $pkCbDone) { & $pkWriteCallbackLoopWarning -PkName '-OnComplete' -PkContext $pkCallbackContext } } - return @{ Success = ($pkR.ExitCode -eq 0) } }.GetNewClosure() $pkJobAbortCleanup = { @@ -3419,6 +3394,9 @@ function Add-PkJobError { } function Receive-PkCompletedHandle { + # The abort drain's collection pass: each finished worker's errors, crash + # and results, as Invoke-PkRunspaceBatch's main loop does it. Returns the + # workers still running. param( [System.Collections.Generic.List[hashtable]]$Handles, [scriptblock]$ResultHandler, @@ -3442,7 +3420,7 @@ function Receive-PkCompletedHandle { } finally { $h.PS.Dispose() } - if ($null -ne $ResultHandler -and $null -ne $pkWorkerOutput) { + if ($null -ne $pkWorkerOutput) { foreach ($r in $pkWorkerOutput) { # Invoke-PkCallback, inlined: this runs per result. $pkCbDone = $false @@ -3635,7 +3613,7 @@ function Invoke-PkRunspaceBatch { } } - if ($null -eq $ResultHandler) { $ResultHandler = { param($r) } } + if ($null -eq $ResultHandler) { $ResultHandler = { } } # Passing a parameter the worker doesn't declare fails the whole invoke # with an unhelpful binding error. @@ -3658,7 +3636,7 @@ function Invoke-PkRunspaceBatch { if ($namedArg.ArgumentName -ne 'Mandatory') { continue } $mandatoryValue = $true if (-not $namedArg.ExpressionOmitted) { - try { $mandatoryValue = [bool]$namedArg.Argument.SafeGetValue() } catch { $mandatoryValue = $false } # not a constant: left to binding, as before + try { $mandatoryValue = [bool]$namedArg.Argument.SafeGetValue() } catch { $mandatoryValue = $false } # not a constant: left to binding } if ($mandatoryValue) { $isMandatory = $true } } @@ -4327,10 +4305,11 @@ function Test-PkWorkerSafetyCore { # 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. + # 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. $storageMethods = @('Add', 'AddRange', 'Insert', 'Enqueue', 'Push', 'TryAdd', 'Contains', 'Remove', 'IndexOf', 'set_Item') $scriptBlockVars = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase) foreach ($assign in $ast.FindAll({ param($node) $node -is [System.Management.Automation.Language.AssignmentStatementAst] }, $true)) { diff --git a/README.md b/README.md index 8fffb6e..0886df9 100644 --- a/README.md +++ b/README.md @@ -144,7 +144,6 @@ If your machines only run signed scripts (the `AllSigned` execution policy), the - `AbortHandler`: `$true` if the Ctrl+C handler was registered. A failure also prints a warning. - `ChildProcessJob`: `$true` if the Job Object for child-process cleanup was set up. A failure also prints a warning, and is the same case as `StartMode` `NoJob`. -- `ThreadPool`: always `$true`, kept for scripts that check it. - `Version`: the kit's version. - `StartMode`: how the kit starts programs here. `CreatedInJob` (inside the Job Object, the normal case), `AddedToJob` (started, then added to it just after) or `NoJob` (no cleanup if PowerShell is killed). It's the default for the session, not a promise for every program: one whose start can't be set up inside the Job Object falls back to `AddedToJob`, with a warning. See [Process-tree cleanup limitations](#process-tree-cleanup-limitations). @@ -538,7 +537,7 @@ All of these callbacks run on whichever thread called the dispatcher: the main t - Supply `-JobStarter { param($job) ... }` to start jobs yourself. It must set `$job.Proc` and should return the job. A starter that is just `Start-PkProcess ...` works too: its result is folded into your job. Throw to report a job that couldn't start. - `-JobPollCompleted { param($job) }` replaces the default "has the process exited" check. Use it for a custom starter whose job isn't a plain process. Only its last output value counts, so a stray value written before the answer doesn't mark the job done. -- `-PollCallback { param($runningJobs) }` runs on every loop pass, with the jobs currently running (`-AbortPollCallback`, its name before 3.0, also works). That's about every 50 ms, and can be many times more often when programs finish quickly, so keep it cheap. +- `-PollCallback { param($runningJobs) }` runs on every loop pass, with the jobs currently running. That's about every 50 ms, and can be many times more often when programs finish quickly, so keep it cheap. - `-MaxConcurrent` can be a `SemaphoreSlim` shared by several dispatchers that must stay under one combined limit. It works inside workers, so two runspace jobs can each run a dispatcher against one shared budget. - `-CancelToken` stops the dispatcher when canceled. An abort stops it either way, without canceling your token. - Whatever your callbacks output is thrown away, apart from the return values listed here. Where a callback returns something, output only that: `-JobPollCompleted` and `-GroupReleaseCheck` go by their last value and `-JobBuilder` ignores anything that isn't a job hashtable, but a stray value from `-GroupProvider` becomes part of the group. diff --git a/Testing/hosts/check-host.ps1 b/Testing/hosts/check-host.ps1 index 259e66a..7e400ce 100644 --- a/Testing/hosts/check-host.ps1 +++ b/Testing/hosts/check-host.ps1 @@ -22,7 +22,7 @@ try { Write-Log "kit loaded" $init = Initialize-ParallelKit - Write-Log ("Initialize-ParallelKit: AbortHandler=" + $init.AbortHandler + " ChildProcessJob=" + $init.ChildProcessJob + " ThreadPool=" + $init.ThreadPool) + Write-Log ("Initialize-ParallelKit: AbortHandler=" + $init.AbortHandler + " ChildProcessJob=" + $init.ChildProcessJob) $ping = Join-Path $env:SystemRoot 'System32\ping.exe' $seconds = 30 From 5a227f6d79bed843876ffd317dc44586c51984dc Mon Sep 17 00:00:00 2001 From: Hal <22532613+HalRiveria@users.noreply.github.com> Date: Tue, 1 Dec 2026 17:37:57 -0500 Subject: [PATCH 07/10] Build the kit as a PowerShell module, and test it that way Build/New-ParallelKitModule.ps1 makes ParallelKit.psm1 and its manifest from ParallelKit.ps1. The harness can run on that module (-AsModule), and CI runs the sections where loading can matter on it. The README covers the module. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/tests.yml | 13 ++ Build/New-ParallelKitModule.ps1 | 170 ++++++++++++++++++++++++ ParallelKit.Harness.ps1 | 226 +++++++++++++++++++++++++++++--- ParallelKit.ps1 | 30 +++-- README.md | 61 ++++++++- 5 files changed, 460 insertions(+), 40 deletions(-) create mode 100644 Build/New-ParallelKitModule.ps1 diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 73560f8..3d0510c 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -30,6 +30,13 @@ jobs: & powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\ParallelKit.Harness.ps1 exit $LASTEXITCODE + # The same in harness-pwsh below: keep the two in step. + - name: Run the loading sections on the module + shell: powershell + run: | + & powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\ParallelKit.Harness.ps1 -AsModule -Section MODULE + exit $LASTEXITCODE + # PowerShell 7 on Windows is supported alongside 5.1, so this is a required # check too. harness-pwsh: @@ -44,3 +51,9 @@ jobs: run: | & pwsh -NoProfile -ExecutionPolicy Bypass -File .\ParallelKit.Harness.ps1 exit $LASTEXITCODE + + - name: Run the loading sections on the module under pwsh + shell: pwsh + run: | + & pwsh -NoProfile -ExecutionPolicy Bypass -File .\ParallelKit.Harness.ps1 -AsModule -Section MODULE + exit $LASTEXITCODE diff --git a/Build/New-ParallelKitModule.ps1 b/Build/New-ParallelKitModule.ps1 new file mode 100644 index 0000000..a8ab87d --- /dev/null +++ b/Build/New-ParallelKitModule.ps1 @@ -0,0 +1,170 @@ +# Builds the PowerShell module from ParallelKit.ps1: ParallelKit.psm1 and its +# manifest, ParallelKit.psd1. +# +# .\Build\New-ParallelKitModule.ps1 -OutputDirectory C:\Modules\ParallelKit +# +# The folder has to be called ParallelKit, or be a version folder inside one +# (ParallelKit\4.0), for Import-Module to find it by name. +# +# The .psm1 is the .ps1 without the wrapper that loads it as an in-memory +# module: the Get-Module | Remove-Module line, and the New-Module wrapper's first +# and last lines. Everything is checked before anything is written, so a .ps1 +# that doesn't look as expected stops this script and leaves the output folder +# alone. The same .ps1 always gives the same bytes, on 5.1 and 7, with LF or CRLF +# line endings. Exit code 0 = written, 1 = refused. +param( + # Default: the ParallelKit.ps1 one folder up. + [string]$SourcePath = '', + [Parameter(Mandatory)] + [string]$OutputDirectory +) + +$ErrorActionPreference = 'Stop' +Set-StrictMode -Version Latest + +# The module's identity on the PowerShell Gallery: never changes. +$moduleGuid = '1a05c60a-cafb-4e52-98e8-dd52affd2d61' +$removeLine = 'Get-Module -Name ParallelKit | Remove-Module' +$openLine = 'New-Module -Name ParallelKit -ErrorAction Stop -ScriptBlock {' +$closeLine = '} | Import-Module -Global' + +function Stop-PkBuild { + param([string]$Why) + throw ("New-ParallelKitModule: '" + $SourcePath + "' doesn't look as expected, so nothing was written: " + $Why) +} + +function Get-PkBuildLineIndex { + # Where the one line reading exactly $Text is; stops the build unless there's exactly one. + param([string[]]$Lines, [string]$Text) + $found = @(for ($i = 0; $i -lt $Lines.Count; $i++) { if ($Lines[$i] -ceq $Text) { $i } }) + if ($found.Count -ne 1) { Stop-PkBuild ("expected exactly one line reading '" + $Text + "', found " + $found.Count + ". If the kit's loading changed, update this script to match.") } + return $found[0] +} + +function Get-PkBuildAst { + param([string]$Text, [string]$What) + $tokens = $null; $parseErrors = $null + $ast = [System.Management.Automation.Language.Parser]::ParseInput($Text, [ref]$tokens, [ref]$parseErrors) + if (@($parseErrors).Count -gt 0) { Stop-PkBuild ($What + " has a syntax error at line " + $parseErrors[0].Extent.StartLineNumber + ": " + $parseErrors[0].Message) } + return $ast +} + +function Get-PkBuildCommandCall { + param($Ast, [string[]]$Name) + return ,@($Ast.FindAll({ param($n) $n -is [System.Management.Automation.Language.CommandAst] }, $true) | Where-Object { $Name -contains $_.GetCommandName() }) +} + +function Get-PkBuildFunctionName { + # The names of the functions defined directly in a list of statements. + param($Statements) + return @($Statements | Where-Object { $_ -is [System.Management.Automation.Language.FunctionDefinitionAst] } | ForEach-Object { $_.Name }) +} + +try { + # Not a parameter default: there, with -File on 5.1, $PSScriptRoot is empty. + if ($SourcePath -eq '') { $SourcePath = Join-Path (Split-Path -Parent $PSScriptRoot) 'ParallelKit.ps1' } + if (-not (Test-Path -LiteralPath $SourcePath -PathType Leaf)) { throw ("New-ParallelKitModule: there's no file at '" + $SourcePath + "'. Pass -SourcePath the path of ParallelKit.ps1.") } + $SourcePath = (Get-Item -LiteralPath $SourcePath).FullName + $OutputDirectory = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($OutputDirectory) + + # The .ps1 is ASCII, which 5.1 and 7 read alike without a BOM. + $bytes = [System.IO.File]::ReadAllBytes($SourcePath) + for ($i = 0; $i -lt $bytes.Length; $i++) { + if ($bytes[$i] -gt 127) { Stop-PkBuild ("byte " + $i + " isn't ASCII. 5.1 and 7 would read the file differently.") } + } + $source = [System.Text.Encoding]::ASCII.GetString($bytes).Replace("`r`n", "`n") + if ($source.Contains("`r")) { Stop-PkBuild "it has a carriage return on its own, not part of a CRLF." } + $lines = $source.TrimEnd("`n").Split("`n") + $sourceAst = Get-PkBuildAst -Text $source -What 'the file' + + # The three lines, in their places. + $removeAt = Get-PkBuildLineIndex -Lines $lines -Text $removeLine + $openAt = Get-PkBuildLineIndex -Lines $lines -Text $openLine + $closeAt = Get-PkBuildLineIndex -Lines $lines -Text $closeLine + if ($openAt -ne $removeAt + 1) { Stop-PkBuild ("the New-Module line (" + ($openAt + 1) + ") isn't right after the Remove-Module line (" + ($removeAt + 1) + ").") } + if ($closeAt -ne $lines.Count - 1) { Stop-PkBuild ("there's more after the closing '" + $closeLine + "' (line " + ($closeAt + 1) + "), which would end up in the module's own scope.") } + + # At the top level: the language mode check, then those two statements. + $top = @($sourceAst.EndBlock.Statements) + if ($null -ne $sourceAst.ParamBlock -or $null -ne $sourceAst.BeginBlock -or $null -ne $sourceAst.ProcessBlock -or $top.Count -ne 3) { Stop-PkBuild ("expected three top-level statements (the language mode check, Remove-Module, New-Module), found " + $top.Count + ".") } + if ($top[0] -isnot [System.Management.Automation.Language.IfStatementAst] -or $top[0].Extent.Text -notlike '*LanguageMode*') { Stop-PkBuild "the first statement isn't the language mode check." } + if ($top[1].Extent.StartLineNumber -ne $removeAt + 1 -or $top[2].Extent.StartLineNumber -ne $openAt + 1 -or $top[2].Extent.EndLineNumber -ne $closeAt + 1) { Stop-PkBuild "the wrapper's lines don't start and end the statements they should." } + $wrapped = @($top[2].PipelineElements[0].CommandElements)[-1] + if ($wrapped -isnot [System.Management.Automation.Language.ScriptBlockExpressionAst]) { Stop-PkBuild "New-Module's last argument isn't a scriptblock." } + + # The module: every line but those three. + $kept = @(for ($i = 0; $i -lt $lines.Count; $i++) { if ($i -ne $removeAt -and $i -ne $openAt -and $i -ne $closeAt) { $lines[$i] } }) + $module = (($kept -join "`n").TrimEnd("`n")) + "`n" + $moduleAst = Get-PkBuildAst -Text $module -What 'the module made from it' + $left = Get-PkBuildCommandCall -Ast $moduleAst -Name @('New-Module', 'Import-Module', 'Remove-Module') + if ($left.Count -gt 0) { Stop-PkBuild ("the module would still call " + $left[0].GetCommandName() + " (line " + $left[0].Extent.StartLineNumber + " of the module: '" + $left[0].Extent.Text + "').") } + + # The same functions, now at the top level. + $moduleFns = Get-PkBuildFunctionName -Statements $moduleAst.EndBlock.Statements + $sourceFns = Get-PkBuildFunctionName -Statements $wrapped.ScriptBlock.EndBlock.Statements + if (@($moduleFns).Count -eq 0 -or ($moduleFns -join ',') -cne ($sourceFns -join ',')) { Stop-PkBuild ("the module has " + @($moduleFns).Count + " top-level functions and the kit " + @($sourceFns).Count + "; they should be the same list.") } + $doubled = @($moduleFns | Group-Object | Where-Object { $_.Count -gt 1 } | ForEach-Object { $_.Name }) + if ($doubled.Count -gt 0) { Stop-PkBuild ("a function is defined twice: " + ($doubled -join ', ') + ".") } + + # The public list: plain names, each one a function. + $exports = Get-PkBuildCommandCall -Ast $moduleAst -Name @('Export-ModuleMember') + if ($exports.Count -ne 1) { Stop-PkBuild ("expected one Export-ModuleMember, found " + $exports.Count + ".") } + if (@($moduleAst.EndBlock.Statements)[-1].Extent.StartOffset -ne $exports[0].Extent.StartOffset) { Stop-PkBuild "Export-ModuleMember isn't the module's last statement." } + $elements = @($exports[0].CommandElements) + if ($elements.Count -ne 3 -or $elements[1] -isnot [System.Management.Automation.Language.CommandParameterAst] -or $elements[1].ParameterName -ne 'Function') { Stop-PkBuild "Export-ModuleMember isn't of the form 'Export-ModuleMember -Function @(...)'." } + $public = @($elements[2].FindAll({ param($n) $n -is [System.Management.Automation.Language.ExpressionAst] -and $n -isnot [System.Management.Automation.Language.ArrayExpressionAst] -and $n -isnot [System.Management.Automation.Language.ArrayLiteralAst] }, $true) | ForEach-Object { + if ($_ -isnot [System.Management.Automation.Language.StringConstantExpressionAst]) { Stop-PkBuild ("Export-ModuleMember's list has something that isn't a plain name: " + $_.Extent.Text) } + $_.Value + }) + if ($public.Count -eq 0) { Stop-PkBuild "Export-ModuleMember's list is empty." } + foreach ($name in $public) { + if ($moduleFns -cnotcontains $name) { Stop-PkBuild ("Export-ModuleMember lists '" + $name + "', which isn't a function in the kit.") } + } + if (@($public | Select-Object -Unique).Count -ne $public.Count) { Stop-PkBuild "Export-ModuleMember's list names a function twice." } + + # The version: the header and Initialize-ParallelKit agree. + $header = [regex]::Matches($source, '(?m)^# Version (\d+\.\d+(?:\.\d+)?)\b') + $inCode = [regex]::Matches($source, "(?m)^ \`$version = \[version\]'(\d+\.\d+(?:\.\d+)?)'`$") + if ($header.Count -ne 1 -or $inCode.Count -ne 1) { Stop-PkBuild ("expected one '# Version X.Y' line and one `$version = [version]'X.Y' line, found " + $header.Count + " and " + $inCode.Count + ".") } + $version = $header[0].Groups[1].Value + if ($version -cne $inCode[0].Groups[1].Value) { Stop-PkBuild ("the header says version " + $version + " and Initialize-ParallelKit " + $inCode[0].Groups[1].Value + ".") } + + # Written out rather than made by New-ModuleManifest, which puts the date + # and the user's name in the file. + $fnLines = (@($public | ForEach-Object { " '" + $_ + "'" }) -join ",`n") + $manifest = @' +@{ + RootModule = 'ParallelKit.psm1' + ModuleVersion = '__VERSION__' + GUID = '__MODULEGUID__' + Author = 'HalRiveria' + Copyright = '(c) 2026 HalRiveria. MIT License.' + Description = 'Parallel runspace jobs, bounded external-process dispatch, and graceful Ctrl+C/window-close handling for Windows PowerShell 5.1 and PowerShell 7, with a Job Object so child processes die with the script. Windows only.' + PowerShellVersion = '5.1' + CompatiblePSEditions = @('Desktop', 'Core') + FunctionsToExport = @( +__FUNCTIONS__ + ) + CmdletsToExport = @() + VariablesToExport = @() + AliasesToExport = @() + PrivateData = @{ + PSData = @{ + Tags = @('Windows', 'Parallel', 'Runspace', 'Process', 'Concurrency', 'PSEdition_Desktop', 'PSEdition_Core') + LicenseUri = 'https://github.com/HalRiveria/PowerShell-ParallelKit/blob/main/LICENSE' + ProjectUri = 'https://github.com/HalRiveria/PowerShell-ParallelKit' + } + } +} +'@ + $manifest = $manifest.Replace("`r`n", "`n").Replace('__VERSION__', $version).Replace('__MODULEGUID__', $moduleGuid).Replace('__FUNCTIONS__', $fnLines) + "`n" + $null = Get-PkBuildAst -Text $manifest -What 'the manifest made from it' + + $null = New-Item -ItemType Directory -Force -Path $OutputDirectory + [System.IO.File]::WriteAllBytes((Join-Path $OutputDirectory 'ParallelKit.psm1'), [System.Text.Encoding]::ASCII.GetBytes($module.Replace("`n", "`r`n"))) + [System.IO.File]::WriteAllBytes((Join-Path $OutputDirectory 'ParallelKit.psd1'), [System.Text.Encoding]::ASCII.GetBytes($manifest.Replace("`n", "`r`n"))) + Write-Output ("Wrote ParallelKit " + $version + " (" + @($moduleFns).Count + " functions, " + $public.Count + " public) to " + $OutputDirectory) +} catch { + [Console]::Error.WriteLine($_.Exception.Message) + exit 1 +} diff --git a/ParallelKit.Harness.ps1 b/ParallelKit.Harness.ps1 index 5b125a8..87123d4 100644 --- a/ParallelKit.Harness.ps1 +++ b/ParallelKit.Harness.ps1 @@ -1,13 +1,16 @@ -# Test harness for ParallelKit.ps1. Real runspaces and real child processes +# Test harness for ParallelKit. Real runspaces and real child processes # (cmd.exe / ping.exe), nothing mocked. # # powershell -NoProfile -File .\ParallelKit.Harness.ps1 # powershell -NoProfile -File .\ParallelKit.Harness.ps1 -Section AO,BB +# powershell -NoProfile -File .\ParallelKit.Harness.ps1 -AsModule -Section MODULE # # Exit code 0 = all passed, 1 = any failed. -Section runs only those sections, # plus A (the setup), for working on one area. That isn't a full pass, and the -# last line says so. -param([string[]]$Section = @()) +# last line says so. -AsModule builds the module (Build/New-ParallelKitModule.ps1) +# and tests that, imported by name, instead of dot-sourcing ParallelKit.ps1. +# -Section MODULE is the sections where how the kit is loaded can matter. +param([string[]]$Section = @(), [switch]$AsModule) $ErrorActionPreference = "Stop" # The whole suite runs under strict mode: a host project may well use it, @@ -16,7 +19,29 @@ Set-StrictMode -Version Latest # The thread pool's minimum before the kit loads: the kit leaves it alone. $poolMinBefore = 0; $poolIoBefore = 0 [System.Threading.ThreadPool]::GetMinThreads([ref]$poolMinBefore, [ref]$poolIoBefore) -. (Join-Path $PSScriptRoot "ParallelKit.ps1") +# What to load, here and in the child scripts, which dot-source $kitPath: the +# .ps1, or a one-line script that imports the module made from it. $kitSource is +# the file whose code runs, for the checks that read it; $kitPs1 is always the +# .ps1, for the checks on that file itself. +$kitPs1 = Join-Path $PSScriptRoot "ParallelKit.ps1" +$kitPath = $kitPs1 +$kitSource = $kitPs1 +$moduleDir = $null +if ($AsModule) { + $moduleVersion = [regex]::Match([System.IO.File]::ReadAllText($kitPs1), '(?m)^# Version (\d+\.\d+(?:\.\d+)?)\b').Groups[1].Value + $moduleDir = Join-Path $env:TEMP ("pk-harness-module-" + $PID) + $moduleBuilt = Join-Path $moduleDir ('mods\ParallelKit\' + $moduleVersion) + $global:LASTEXITCODE = 0 + $null = & (Join-Path $PSScriptRoot 'Build\New-ParallelKitModule.ps1') -SourcePath $kitPs1 -OutputDirectory $moduleBuilt + if ($LASTEXITCODE -ne 0) { Write-Host "The module couldn't be built (see above), so there's nothing to test." -ForegroundColor Red; exit 1 } + $kitSource = Join-Path $moduleBuilt 'ParallelKit.psm1' + $kitPath = Join-Path $moduleDir 'load.ps1' + # This version: another may be installed. + [System.IO.File]::WriteAllText($kitPath, 'Import-Module ParallelKit -RequiredVersion ' + $moduleVersion + "`r`n") + $env:PSModulePath = (Join-Path $moduleDir 'mods') + ';' + $env:PSModulePath + $env:PSModuleAnalysisCachePath = Join-Path $moduleDir 'ModuleAnalysisCache' +} +. $kitPath $script:passCount = 0 $script:failCount = 0 @@ -51,6 +76,8 @@ function Test-Skip { # -File passes AO,BB as one string. $script:onlySections = @($Section | ForEach-Object { $_ -split '[,\s]+' } | Where-Object { $_ } | ForEach-Object { $_.ToUpperInvariant() }) $allSections = @([regex]::Matches([System.IO.File]::ReadAllText($PSCommandPath), "(?m)^if \(Test-HarnessSection '([A-Z]+)'") | ForEach-Object { $_.Groups[1].Value }) +$moduleSections = @('B', 'F', 'I', 'K', 'P', 'S', 'V', 'Z', 'AA', 'AF', 'AG', 'AH', 'AQ', 'AW', 'AZ', 'BC', 'BG', 'BI', 'BK', 'BL', 'BM') +$script:onlySections = @($script:onlySections | ForEach-Object { if ($_ -eq 'MODULE') { $moduleSections } else { $_ } } | Select-Object -Unique) $badSections = @($script:onlySections | Where-Object { $allSections -notcontains $_ }) if ($badSections.Count -gt 0) { Write-Host ("No such section: " + ($badSections -join ', ') + ". -Section takes names from: " + ($allSections -join ', ') + ".") -ForegroundColor Red @@ -100,9 +127,8 @@ function Get-HarnessDouble { # it; anything a second section needs goes here, so -Section can run either on # its own (section BH checks that). $cscExe = Join-Path $env:SystemRoot 'Microsoft.NET\Framework64\v4.0.30319\csc.exe' -$kitPath = Join-Path $PSScriptRoot "ParallelKit.ps1" # The same list is the Export-ModuleMember list at the end of ParallelKit.ps1; -# keep the two in step. +# keep the two in step. The module's manifest is made from that one. $publicFunctions = @('Set-PkMessageHandler', 'Write-PkMessage', 'Initialize-ParallelKit', 'Register-PkCancellationSource', 'Unregister-PkCancellationSource', 'Reset-PkAbortState', 'Request-PkAbort', 'Test-PkAbortSignal', 'Test-PkCancelRequested', 'Get-PkAbortTriggerLabel', 'Invoke-PkRun', 'ConvertTo-PkArgumentString', 'Start-PkProcess', 'Stop-PkProcessTree', @@ -1065,9 +1091,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 a caller's -# closure that calls one works; the batch's own closures don't rely on that -# (section Z). +# see them. Dot-sourced or imported here, the kit's public functions are +# global, 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, @" @@ -1087,7 +1113,7 @@ Test-Assert ($prompt.Stdout -match 'closure=ok') "and so does a .GetNewClosure() # one before) are left alone, and loading raises no errors. $embedScript = Join-Path $env:TEMP ("pk-embed-" + [guid]::NewGuid().ToString("N") + ".ps1") [System.IO.File]::WriteAllText($embedScript, "Set-StrictMode -Version Latest`r`n`$ErrorActionPreference = 'Stop'`r`nfunction Get-HarnessBefore { 1 }`r`n`$fnAst = 'mine'`r`n" + - [System.IO.File]::ReadAllText($kitPath) + + [System.IO.File]::ReadAllText($kitPs1) + "`r`nfunction Get-HarnessAfter { 2 }`r`nWrite-Output ('kitGlobal=' + [bool](Get-ChildItem Function: | Where-Object { `$_.Name -eq 'Start-PkProcess' }))`r`nWrite-Output ('caller var=' + `$fnAst)`r`n") $embed = Invoke-PkProcessWithTimeout -FilePath $selfExe -Arguments (ConvertTo-PkArgumentString @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command', ("& '" + $embedScript + "'; 'before global=' + [bool](Get-Command Get-HarnessBefore -ErrorAction SilentlyContinue); 'after global=' + [bool](Get-Command Get-HarnessAfter -ErrorAction SilentlyContinue); 'kit global=' + [bool](Get-Command Start-PkProcess -ErrorAction SilentlyContinue)"))) -TimeoutMs 60000 [System.IO.File]::Delete($embedScript) @@ -2364,7 +2390,7 @@ function Invoke-ModWork { Export-ModuleMember -Function Invoke-ModWork '@) $modScript = Join-Path $modDir 'use.ps1' -[System.IO.File]::WriteAllText($modScript, ". '" + $kitPath + "'`r`nImport-Module '" + $modPath + "'`r`nInvoke-ModWork`r`n. '" + $kitPath + "'`r`n'kit modules=' + @(Get-Module -Name ParallelKit).Count`r`n") +[System.IO.File]::WriteAllText($modScript, ". '" + $kitPs1 + "'`r`nImport-Module '" + $modPath + "'`r`nInvoke-ModWork`r`n. '" + $kitPs1 + "'`r`n'kit modules=' + @(Get-Module -Name ParallelKit).Count`r`n") $modRun = Invoke-PkProcessWithTimeout -FilePath $selfExe -Arguments (ConvertTo-PkArgumentString @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command', ("& '" + $modScript + "'"))) -TimeoutMs 60000 Remove-Item -LiteralPath $modDir -Recurse -Force -ErrorAction SilentlyContinue $modOut = ([string]$modRun.Stdout + [string]$modRun.Stderr).Trim() -replace '\s+', ' ' @@ -2375,13 +2401,18 @@ Test-Assert ($modOut -match 'kit modules=1') "loading the kit a second time leav # 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" +if ($AsModule) { + $scopeText = "Import-Module '" + (Join-Path $moduleBuilt 'ParallelKit.psd1') + "'" +} else { + $scopeText = [System.IO.File]::ReadAllText($kitPs1) + $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" + $scopeText = $scopeText.Replace($scopeClose, '} | Import-Module') +} $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') + @' +[System.IO.File]::WriteAllText($scopeModule, $scopeText + @' function Invoke-ScopeBatch { $codes = [System.Collections.Generic.List[object]]::new() @@ -3805,9 +3836,9 @@ if (Test-HarnessSection 'AN' "static checks on the kit's own code") { # Rules that are easy to break in one place without any other test noticing: # the dispatcher's copied blocks drifting apart, a user callback called # without the continue/break guard, an empty catch with no reason. Each check -# reads ParallelKit.ps1, then an edited copy that breaks the rule once, so a +# reads the kit's source, then an edited copy that breaks the rule once, so a # check that has stopped seeing anything fails too. -$anSource = [System.IO.File]::ReadAllText((Join-Path $PSScriptRoot "ParallelKit.ps1")) +$anSource = [System.IO.File]::ReadAllText($kitSource) function Get-HarnessCodeText { # Code as one line of tokens: comments, line breaks and spacing don't count. @@ -4125,7 +4156,7 @@ Start-Sleep -Seconds 60 '@) try { foreach ($killFallback in 0, 1) { - $killArgs = '-NoProfile -ExecutionPolicy Bypass -File "' + $killScript + '" -Kit "' + (Join-Path $PSScriptRoot 'ParallelKit.ps1') + '" -Fallback ' + $killFallback + $killArgs = '-NoProfile -ExecutionPolicy Bypass -File "' + $killScript + '" -Kit "' + $kitPath + '" -Fallback ' + $killFallback $psi = [System.Diagnostics.ProcessStartInfo]::new($selfExe, $killArgs) $psi.UseShellExecute = $false; $psi.RedirectStandardOutput = $true; $psi.CreateNoWindow = $true $killHost = [System.Diagnostics.Process]::Start($psi) @@ -4591,7 +4622,7 @@ foreach ($l in $rdLeft) { Stop-Process -Id $l.ProcessId -Force -ErrorAction Sile Test-Assert ($rdError -like '*could not start*' -and $rdLeft.Count -eq 0) ("a program whose output readers fail to build is ended and the start reported as failed (" + $rdLeft.Count + " left running, error: " + $rdError + ")") # Initialize-ParallelKit reports the kit's version and how it starts programs. -$ipHeader = [regex]::Match([System.IO.File]::ReadAllText((Join-Path $PSScriptRoot 'ParallelKit.ps1')), '(?m)^# Version (\d+\.\d+(?:\.\d+)?)\b').Groups[1].Value +$ipHeader = [regex]::Match([System.IO.File]::ReadAllText($kitSource), '(?m)^# Version (\d+\.\d+(?:\.\d+)?)\b').Groups[1].Value $ipError = $null; $ip = $null; $ipAdded = $null try { $ip = Initialize-ParallelKit @@ -4785,7 +4816,7 @@ try { } '@) try { - $azRun = Invoke-PkProcessWithTimeout -FilePath $selfExe -Arguments ('-NoProfile -ExecutionPolicy Bypass -File "' + $azScript + '" -Kit "' + (Join-Path $PSScriptRoot 'ParallelKit.ps1') + '"') -TimeoutMs 120000 + $azRun = Invoke-PkProcessWithTimeout -FilePath $selfExe -Arguments ('-NoProfile -ExecutionPolicy Bypass -File "' + $azScript + '" -Kit "' + $kitPath + '"') -TimeoutMs 120000 $azLines = @(([string]$azRun.Stdout) -split "`r?`n") $azResult = @($azLines | Where-Object { $_ -like 'RESULT|*' }) $azDrain = @($azLines | Where-Object { $_ -like 'DRAINED|*' }) @@ -5401,7 +5432,7 @@ function Get-HarnessSectionLeaks([string]$Source) { foreach ($m in [regex]::Matches($statement.Extent.Text, '\bclass (Pk\w+)')) { $null = $defines[$id].Add('[' + $m.Groups[1].Value + ']') } } # The kit's own types, which a test's stand-in script may define too. - foreach ($m in [regex]::Matches([System.IO.File]::ReadAllText($kitPath), '\bclass (Pk\w+)')) { $null = $defines['A'].Add('[' + $m.Groups[1].Value + ']') } + foreach ($m in [regex]::Matches([System.IO.File]::ReadAllText($kitSource), '\bclass (Pk\w+)')) { $null = $defines['A'].Add('[' + $m.Groups[1].Value + ']') } $elsewhere = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase) foreach ($id in $defines.Keys) { $elsewhere.UnionWith($defines[$id]) } foreach ($id in $uses.Keys) { @@ -5818,12 +5849,165 @@ Reset-Harness Write-Host "" } +# ============================================================================== +if (Test-HarnessSection 'BM' "the module made from the kit") { +# Build/New-ParallelKitModule.ps1 and what it makes, whichever way the harness +# itself loaded the kit. -AsModule runs the other sections on that module. +$bmGenerator = Join-Path $PSScriptRoot 'Build\New-ParallelKitModule.ps1' +$bmDir = Join-Path $env:TEMP ("pk-harness-bm-" + $PID) +$null = New-Item -ItemType Directory -Force -Path $bmDir +$bmText = [System.IO.File]::ReadAllText($kitPs1) +$bmVersion = [regex]::Match($bmText, '(?m)^# Version (\d+\.\d+(?:\.\d+)?)\b').Groups[1].Value + +function Get-BmBuildCommand([string]$Source, [string]$Out) { + return @{ FilePath = $selfExe; Arguments = @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', $bmGenerator, '-SourcePath', $Source, '-OutputDirectory', $Out); Out = $Out } +} +function New-BmFile([string]$Name, [string]$Text) { + $path = Join-Path $bmDir $Name + [System.IO.File]::WriteAllText($path, $Text, [System.Text.UTF8Encoding]::new($false)) + return $path +} +$oldModulePath = $env:PSModulePath +$oldCachePath = $env:PSModuleAnalysisCachePath +try { + +# The same bytes every time, with LF or CRLF, and only the wrapper gone. +$bmMods = Join-Path $bmDir 'mods' +$bmBuilt = Join-Path $bmMods ('ParallelKit\' + $bmVersion) +$bmLf = New-BmFile 'lf.ps1' $bmText.Replace("`r`n", "`n") +$bmCrlf = New-BmFile 'crlf.ps1' $bmText.Replace("`r`n", "`n").Replace("`n", "`r`n") +$bmBuilds = Invoke-PkProcessBatch -MaxConcurrent 4 -Commands @((Get-BmBuildCommand $kitPs1 $bmBuilt), (Get-BmBuildCommand $kitPs1 (Join-Path $bmDir 'again')), (Get-BmBuildCommand $bmLf (Join-Path $bmDir 'lf')), (Get-BmBuildCommand $bmCrlf (Join-Path $bmDir 'crlf'))) +$bmErrors = @($bmBuilds.Results | ForEach-Object { [string]$_.Stderr } | Where-Object { $_ }) -join '; ' +$bmHashes = @($bmBuilds.Results | ForEach-Object { if ($_.ExitCode -eq 0) { (Get-FileHash -LiteralPath (Join-Path $_.Command['Out'] 'ParallelKit.psm1')).Hash + (Get-FileHash -LiteralPath (Join-Path $_.Command['Out'] 'ParallelKit.psd1')).Hash } else { 'exit ' + $_.ExitCode } }) +Test-Assert ($bmHashes.Count -eq 4 -and @($bmHashes | Select-Object -Unique).Count -eq 1 -and $bmHashes[0] -notlike 'exit*') ("the module is the same every time it's built, from LF or CRLF (" + $bmErrors + ")") +$bmLeft = [System.IO.File]::ReadAllText((Join-Path $bmBuilt 'ParallelKit.psm1')).Replace("`r`n", "`n").TrimEnd("`n") +$bmWant = $bmText.Replace("`r`n", "`n").Replace("Get-Module -Name ParallelKit | Remove-Module`nNew-Module -Name ParallelKit -ErrorAction Stop -ScriptBlock {`n", '').Replace("`n} | Import-Module -Global", '').TrimEnd("`n") +Test-Assert ($bmLeft -ceq $bmWant) "it's the .ps1 without the in-memory wrapper, and nothing else changed" + +# A .ps1 that doesn't look as expected is refused, with the output left alone. +$bmN = "`n" +if ($bmText.Contains("`r`n")) { $bmN = "`r`n" } +$bmRemove = 'Get-Module -Name ParallelKit | Remove-Module' +$bmOpen = 'New-Module -Name ParallelKit -ErrorAction Stop -ScriptBlock {' +$bmClose = '} | Import-Module -Global' +$bmCases = [ordered]@{ + 'the Remove-Module line gone' = $bmText.Replace($bmRemove + $bmN, '') + 'the New-Module line reworded' = $bmText.Replace($bmOpen, 'New-Module -Name ParallelKit -ScriptBlock {') + 'the closing line reworded' = $bmText.Replace($bmClose, '} | Import-Module') + 'code after the wrapper' = $bmText + $bmN + 'Write-Output 1' + $bmN + 'code before the wrapper' = $bmText.Replace($bmRemove, '$x = 1' + $bmN + $bmRemove) + 'a line inside the wrapper lines' = $bmText.Replace($bmRemove, $bmRemove + $bmN + '$x = 1') + 'the language mode check gone' = [regex]::Replace($bmText, '(?s)if \(\$ExecutionContext\.SessionState\.LanguageMode.*?\n\}\r?\n', '') + 'a syntax error' = $bmText.Replace('function Set-PkMessageHandler {', 'function Set-PkMessageHandler { (') + 'an empty file' = '' + 'a character that isn''t ASCII' = $bmText.Replace('# ParallelKit - parallel', ('# ParallelKit ' + [char]0x2014 + ' parallel')) + 'versions that differ' = $bmText.Replace("`$version = [version]'" + $bmVersion + "'", "`$version = [version]'99.9'") + 'no version line' = $bmText.Replace('# Version ' + $bmVersion, '# V ' + $bmVersion) + 'an export that isn''t there' = $bmText.Replace("'Set-PkMessageHandler', 'Write-PkMessage',", "'Set-PkMessageHandler', 'Write-PkMessageX',") + 'an export listed twice' = $bmText.Replace("'Set-PkMessageHandler', 'Write-PkMessage',", "'Set-PkMessageHandler', 'Set-PkMessageHandler',") + 'an export that isn''t a name' = $bmText.Replace("'Set-PkMessageHandler', 'Write-PkMessage',", "`$x, 'Write-PkMessage',") + 'no Export-ModuleMember' = [regex]::Replace($bmText, '(?s)Export-ModuleMember -Function @\(.*?\)\r?\n', '') + 'an Import-Module left inside' = $bmText.Replace('function Set-PkMessageHandler {', 'function Get-PkX { Import-Module Foo }' + $bmN + 'function Set-PkMessageHandler {') + 'a function defined twice' = $bmText.Replace('function Set-PkMessageHandler {', 'function Write-PkMessage { }' + $bmN + 'function Set-PkMessageHandler {') +} +$bmUnchanged = @($bmCases.Keys | Where-Object { $bmCases[$_] -ceq $bmText }) +Test-Assert ($bmUnchanged.Count -eq 0) ("every edit below changes the kit's text (not: " + ($bmUnchanged -join ', ') + ")") +$bmCommands = @(foreach ($name in $bmCases.Keys) { + $out = Join-Path $bmDir ('case-' + [guid]::NewGuid().ToString('N')) + $null = New-Item -ItemType Directory -Path $out + [System.IO.File]::WriteAllText((Join-Path $out 'ParallelKit.psm1'), 'earlier') + $command = Get-BmBuildCommand (New-BmFile ([System.IO.Path]::GetFileName($out) + '.ps1') $bmCases[$name]) $out + $command['Case'] = $name + $command +}) +$bmMissed = [System.Collections.Generic.List[string]]::new() +foreach ($r in (Invoke-PkProcessBatch -MaxConcurrent 4 -Commands $bmCommands).Results) { + $kept = [System.IO.File]::ReadAllText((Join-Path $r.Command['Out'] 'ParallelKit.psm1')) -eq 'earlier' -and -not (Test-Path -LiteralPath (Join-Path $r.Command['Out'] 'ParallelKit.psd1')) + if ($r.ExitCode -ne 1 -or -not $kept -or [string]$r.Stderr -notlike '*nothing was written*') { $bmMissed.Add($r.Command['Case'] + ' (exit ' + $r.ExitCode + ', output kept ' + $kept + ': ' + ([string]$r.Stderr).Trim() + ')') } +} +Test-Assert ($bmMissed.Count -eq 0) ("a .ps1 that doesn't look as expected is refused with a message, writing nothing (" + $bmCases.Count + " cases; not: " + ($bmMissed -join '; ') + ")") + +# The manifest. +$bmManifest = Test-ModuleManifest -Path (Join-Path $bmBuilt 'ParallelKit.psd1') +$bmExported = @($bmManifest.ExportedFunctions.Keys) +$bmDiffer = @($publicFunctions | Where-Object { $bmExported -notcontains $_ }) + @($bmExported | Where-Object { $publicFunctions -notcontains $_ }) +Test-Assert ($bmManifest.Version -eq [version]$bmVersion -and $bmDiffer.Count -eq 0 -and $bmManifest.PowerShellVersion -eq [version]'5.1') ("its manifest is valid, with the kit's version and public functions (" + $bmManifest.Version + "; differ: " + ($bmDiffer -join ', ') + ")") +Test-Assert (@('PSEdition_Desktop', 'PSEdition_Core', 'Windows' | Where-Object { $bmManifest.Tags -notcontains $_ }).Count -eq 0 -and $bmManifest.Author -eq 'HalRiveria' -and $bmManifest.Guid -eq [guid]'1a05c60a-cafb-4e52-98e8-dd52affd2d61') ("and its identity: GUID, author and tags (" + ($bmManifest.Tags -join ', ') + ")") + +# Loaded in fresh processes, by name and by path: what a caller does with it. +# -OnComplete and -ResultHandler are closures that call the kit's functions. +$env:PSModulePath = $bmMods + ';' + $oldModulePath +$env:PSModuleAnalysisCachePath = Join-Path $bmDir 'ModuleAnalysisCache' +$bmUse = @' +try { + $tag = 'ok' + $b = Invoke-PkProcessBatch -Commands @(@{ FilePath = $env:ComSpec; Arguments = '/c exit 7' }) -OnComplete { param($c, $r) Write-PkMessage ('closure ' + $tag) }.GetNewClosure() + $got = [System.Collections.Generic.List[object]]::new() + $null = Invoke-PkRunspaceBatch -MaxConcurrent 1 -JobParams @(@{ N = 3 }) -WorkerScript { param($N) (Invoke-PkProcessWithTimeout -FilePath $env:ComSpec -Arguments ('/c exit ' + $N) -TimeoutMs 20000).ExitCode } -ResultHandler { param($r) $null = Test-PkCancelRequested; $got.Add($r) }.GetNewClosure() + 'batch=' + $b.Results[0].ExitCode + ' worker=' + ($got -join ',') + ' version=' + (Initialize-ParallelKit).Version +} catch { 'threw ' + $_ } +'@ +$bmByPath = "Import-Module '" + (Join-Path $bmBuilt 'ParallelKit.psd1') + "'" +$bmConsumer = Join-Path $bmDir 'PkBmConsumer' +$null = New-Item -ItemType Directory -Force -Path $bmConsumer +[System.IO.File]::WriteAllText((Join-Path $bmConsumer 'PkBmConsumer.psm1'), "function Invoke-BmConsumer {`r`n" + $bmUse + "`r`n}`r`n") +[System.IO.File]::WriteAllText((Join-Path $bmConsumer 'PkBmConsumer.psd1'), "@{ RootModule = 'PkBmConsumer.psm1'; ModuleVersion = '1.0'; GUID = '" + [guid]::NewGuid() + "'; FunctionsToExport = @('Invoke-BmConsumer'); RequiredModules = @('ParallelKit') }") +$bmScripts = [ordered]@{ + 'imported by name' = 'Import-Module ParallelKit' + "`r`n" + $bmUse + 'imported by path' = $bmByPath + "`r`n" + $bmUse + 'not imported (auto-loaded)' = $bmUse + 'required by another module' = "Import-Module '" + (Join-Path $bmConsumer 'PkBmConsumer.psd1') + "'`r`nInvoke-BmConsumer" + 'imported, then -Force' = "Import-Module ParallelKit`r`nImport-Module ParallelKit -Force`r`n" + $bmUse + 'imported, removed, imported' = "Import-Module ParallelKit`r`nRemove-Module ParallelKit`r`nImport-Module ParallelKit`r`n" + $bmUse + 'imported, then dot-sourced' = "Import-Module ParallelKit`r`n. '" + $kitPs1 + "'`r`n" + $bmUse + 'dot-sourced, then imported' = ". '" + $kitPs1 + "'`r`nImport-Module ParallelKit`r`n" + $bmUse +} +$bmCommands = @(foreach ($name in $bmScripts.Keys) { + $script = New-BmFile ('use-' + [guid]::NewGuid().ToString('N') + '.ps1') $bmScripts[$name] + @{ FilePath = $selfExe; Arguments = @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', $script); Case = $name + ', -File' } + @{ FilePath = $selfExe; Arguments = @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command', ("& '" + $script + "'")); Case = $name + ', &' } +}) +$bmMissed.Clear() +foreach ($r in (Invoke-PkProcessBatch -MaxConcurrent 4 -TimeoutSeconds 120 -Commands $bmCommands).Results) { + $said = ([string]$r.Stdout + [string]$r.Stderr).Trim() -replace '\s+', ' ' + if ($said -notlike ('*closure ok*batch=7 worker=3 version=' + $bmVersion + '*')) { $bmMissed.Add($r.Command['Case'] + ': ' + $said) } +} +Test-Assert ($bmMissed.Count -eq 0) ("the module works however it's loaded, closures and workers included (" + $bmCommands.Count + " ways; not: " + ($bmMissed -join '; ') + ")") + +# Only the public functions come out, with their help. +$bmShow = New-BmFile 'show.ps1' @' +Import-Module ParallelKit +$m = Get-Module ParallelKit +'functions=' + $m.ExportedFunctions.Count + ' others=' + ($m.ExportedVariables.Count + $m.ExportedAliases.Count + $m.ExportedCmdlets.Count) + ' private=' + [bool](Get-Command Start-PkProcessCore -ErrorAction SilentlyContinue) + ' help=' + (Get-Help Invoke-PkRun).Synopsis +'@ +$bmShown = ([string](Invoke-PkProcessWithTimeout -FilePath $selfExe -Arguments @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', $bmShow) -TimeoutMs 60000).Stdout).Trim() -replace '\s+', ' ' +Test-Assert ($bmShown -like ('functions=' + $publicFunctions.Count + ' others=0 private=False help=Runs a block with graceful*')) ("and only its public functions come out (" + $bmShown + ")") + +# A copy with other compiled types is refused, and the one loaded stays. Only +# try/catch or $ErrorActionPreference stops the script there. +$bmOther = Join-Path $bmDir 'other' +$bmOtherText = [regex]::Replace([regex]::Replace($bmText, 'TypesVersion = \d+;', 'TypesVersion = 999;'), 'catch \{ 0 \} \}\) -ne \d+\)', 'catch { 0 } }) -ne 999)') +$bmOtherBuild = Invoke-PkProcessBatch -Commands @(Get-BmBuildCommand (New-BmFile 'other.ps1' $bmOtherText) $bmOther) +$bmStale = New-BmFile 'stale.ps1' ($bmByPath + "`r`ntry { Import-Module '" + (Join-Path $bmOther 'ParallelKit.psd1') + "'; 'loaded' } catch { 'refused ' + `$_ }`r`n" + $bmUse) +$bmStaleOut = ([string](Invoke-PkProcessWithTimeout -FilePath $selfExe -Arguments @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', $bmStale) -TimeoutMs 60000).Stdout).Trim() -replace '\s+', ' ' +Test-Assert ($bmOtherBuild.Results[0].ExitCode -eq 0 -and $bmStaleOut -like '*refused*a different version of the kit*batch=7 worker=3*') ("importing a copy with other compiled types is refused, and the one already loaded still works (" + $bmStaleOut + ")") + +} finally { + $env:PSModulePath = $oldModulePath + $env:PSModuleAnalysisCachePath = $oldCachePath + Remove-Item -LiteralPath $bmDir -Recurse -Force -ErrorAction SilentlyContinue +} +Write-Host "" +} + Set-PkMessageHandler -Handler $null Reset-PkAbortState +if ($null -ne $moduleDir) { Remove-Item -LiteralPath $moduleDir -Recurse -Force -ErrorAction SilentlyContinue } Write-Host "===============================================" $skipText = "" if ($script:skipCount -gt 0) { $skipText = ", " + $script:skipCount + " skipped" } +if ($AsModule) { $skipText += ", as the module" } if ($script:failCount -eq 0 -and $script:onlySections.Count -gt 0) { # Not "ALL PASSED": a filtered run mustn't read as a full one. Write-Host ("SECTIONS PASSED, NOT A FULL RUN (" + ((@('A') + $script:onlySections | Select-Object -Unique) -join ', ') + ": " + $script:passCount + " assertions" + $skipText + ")") -ForegroundColor Yellow diff --git a/ParallelKit.ps1 b/ParallelKit.ps1 index 62f1ac5..99c9662 100644 --- a/ParallelKit.ps1 +++ b/ParallelKit.ps1 @@ -3,11 +3,13 @@ # PowerShell 7. # # Version 3.5 - https://github.com/HalRiveria/PowerShell-ParallelKit -# (Initialize-ParallelKit reports the version too: change both together.) +# (Initialize-ParallelKit reports the version too: change both together. The +# module's manifest takes it from here.) # Copyright (c) 2026 HalRiveria. MIT License: keep this notice with any copy; # the full text is in LICENSE in the repository. # -# Use: . "\ParallelKit.ps1" (dot-source it; it loads itself as an in-memory module) +# Use: . "\ParallelKit.ps1" (the .ps1: dot-source it; it loads as an in-memory module) +# or: Import-Module ParallelKit (the module made from it) # Read README.md first: its two worker-code rules are what keep this from # hanging or crashing. # @@ -23,15 +25,17 @@ if ($ExecutionContext.SessionState.LanguageMode -ne 'FullLanguage') { "Ask whoever manages the machine to allow this script, or run it where that policy doesn't apply.") } -# Loads as an in-memory module, so a callback you pass in sees your -# variables, never the kit's, and the private helpers stay out of your -# session. A copy loaded earlier is removed first. -ErrorAction Stop makes a -# throw in here (the stale-types check) stop the script that loads the kit. +# The kit runs as a module, so a callback you pass in sees your variables, +# never the kit's, and the private helpers stay out of your session. The .ps1 +# makes itself one in memory: it removes a copy loaded earlier, and its +# New-Module's -ErrorAction Stop makes a throw in here (the stale-types check) +# stop the script that loads the kit. Build/New-ParallelKitModule.ps1 leaves +# that wrapper out of the module it makes. Get-Module -Name ParallelKit | Remove-Module New-Module -Name ParallelKit -ErrorAction Stop -ScriptBlock { # ============================================================================== -# Native types (guarded so the file can be dot-sourced more than once) +# Native types (guarded so the kit can be loaded more than once) # ============================================================================== if (-not ([System.Management.Automation.PSTypeName]'PkConsoleCtrl').Type) { @@ -3953,8 +3957,9 @@ function Get-PkCommandKind { param([System.Management.Automation.FunctionInfo]$Fn) if ($null -eq $Fn) { return 'Other' } if ([string]::IsNullOrEmpty($Fn.ModuleName)) { return 'Function' } - # The kit's own: a worker gets only the worker-safe ones, so the rest are - # treated like your own functions. + # The kit's own: a worker is given only the worker-safe ones, so the rest + # are treated like your own functions. (With the kit's module installed a + # worker could auto-load them, but they aren't made for workers.) if ($Fn.ModuleName -eq 'ParallelKit') { return 'Function' } # A module function (Get-FileHash, say) autoloads in a worker like a # cmdlet does - but only if the module can be found by name. One imported @@ -4346,9 +4351,10 @@ function Test-PkWorkerSafetyCore { # Public functions (the ones README.md documents) # ============================================================================== -# Imported globally: a .GetNewClosure() block only sees global functions, -# so this lets a callback of yours call them. The same list is -# $publicFunctions in ParallelKit.Harness.ps1; keep the two in step. +# Dot-sourcing imports these globally: a .GetNewClosure() block only sees global +# functions, so a callback of yours can call them. The same list is +# $publicFunctions in ParallelKit.Harness.ps1; keep the two in step. The module's +# manifest is made from this one. Export-ModuleMember -Function @( 'Set-PkMessageHandler', 'Write-PkMessage', 'Initialize-ParallelKit', 'Register-PkCancellationSource', 'Unregister-PkCancellationSource', 'Reset-PkAbortState', 'Request-PkAbort', 'Test-PkAbortSignal', 'Test-PkCancelRequested', diff --git a/README.md b/README.md index 0886df9..cedab1a 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ [![Tests](https://github.com/HalRiveria/PowerShell-ParallelKit/actions/workflows/tests.yml/badge.svg)](https://github.com/HalRiveria/PowerShell-ParallelKit/actions/workflows/tests.yml) -Run thousands of command-line programs, or blocks of PowerShell code, in parallel from Windows PowerShell 5.1 or PowerShell 7. One file, nothing to install. +Run thousands of command-line programs, or blocks of PowerShell code, in parallel from Windows PowerShell 5.1 or PowerShell 7. One file, nothing to install; or [a module](#as-a-module), if you'd rather import it. Starting programs in parallel from PowerShell is easy. Stopping them is the hard part: Ctrl+C cuts work off mid-file, programs keep running after the script that started them dies, and reading a program's output the simple way can deadlock. ParallelKit handles those parts: @@ -16,7 +16,7 @@ The kit is built to be reliable first and fast second. The aim is that a long ru Developed with assistance from Claude Code. The implementation, test harness, and development history are available for inspection. I encourage independent review and testing. -**Contents:** [Process-tree cleanup limitations](#process-tree-cleanup-limitations) · [Quick start](#quick-start) · [Who it's for](#who-its-for) · [Which function](#which-function) · [Setup](#setup) · [How it fits together](#how-it-fits-together) · [Run a list of programs](#run-a-list-of-programs) · [Process results](#process-results) · [Run PowerShell code in parallel](#run-powershell-code-in-parallel) · [The two rules for worker code](#the-two-rules-for-worker-code) · [Process dispatch with groups](#process-dispatch-with-groups) · [Single processes](#single-processes) · [Messages](#messages) · [Abort](#abort) · [Choosing limits](#choosing-limits) · [Limits](#limits) · [Testing](#testing) · [FAQ](#faq) · [Not planned](#not-planned) +**Contents:** [Process-tree cleanup limitations](#process-tree-cleanup-limitations) · [Quick start](#quick-start) · [Who it's for](#who-its-for) · [Which function](#which-function) · [Setup](#setup) · [As a module](#as-a-module) · [How it fits together](#how-it-fits-together) · [Run a list of programs](#run-a-list-of-programs) · [Process results](#process-results) · [Run PowerShell code in parallel](#run-powershell-code-in-parallel) · [The two rules for worker code](#the-two-rules-for-worker-code) · [Process dispatch with groups](#process-dispatch-with-groups) · [Single processes](#single-processes) · [Messages](#messages) · [Abort](#abort) · [Choosing limits](#choosing-limits) · [Limits](#limits) · [Testing](#testing) · [FAQ](#faq) · [Not planned](#not-planned) ## Process-tree cleanup limitations @@ -156,12 +156,59 @@ It works whether or not your script uses `Set-StrictMode`. The version is in the comment block at the top of the file, so a copy kept in your project still says which one it is. That block also carries the license notice; keep it with the file. -Dot-source it. It loads itself as an in-memory module named `ParallelKit`: nothing is installed and nothing goes on `$env:PSModulePath`, but `Get-Module` lists it while it's loaded. Dot-sourcing it again replaces the copy already loaded. +Dot-sourced, it loads as an in-memory module named `ParallelKit`: nothing is installed and nothing goes on `$env:PSModulePath`, but `Get-Module` lists it while it's loaded. Dot-sourcing it again replaces the copy already loaded. [As a module](#as-a-module) covers the other way to load it. Its public functions are imported globally, so they stay available for the rest of that PowerShell session, and a `.GetNewClosure()` block can call them however your script was started. Its internal helpers stay inside the module. +## As a module + +The kit also comes as a module, built from `ParallelKit.ps1`: the same code, with `Import-Module` in place of dot-sourcing. To build it from a copy of this repository and import it: + +```powershell +.\Build\New-ParallelKitModule.ps1 -OutputDirectory C:\Modules\ParallelKit +Import-Module C:\Modules\ParallelKit +``` + +With that `ParallelKit` folder somewhere on `$env:PSModulePath`, `Import-Module ParallelKit` finds it by name, and so does a call to any of its functions without importing it first. The rest of this README applies either way. + +
+If the import is refused + +A session keeps the compiled parts of the first version it loads, so importing another version whose compiled parts differ fails with "already loaded a different version of the kit". Unlike dot-sourcing, that doesn't stop your script by itself: it carries on with the version already loaded, or with none. `Import-Module -ErrorAction Stop` doesn't change that. Set `$ErrorActionPreference = 'Stop'` first, or import inside `try`/`catch`: + +```powershell +try { Import-Module ParallelKit } catch { throw } +``` + +On Windows PowerShell 5.1, a call that loads the module for you says only that it "could not be loaded", without the reason. Import it yourself to see why. + +
+ +
+Using it from your own module + +List it in your module's manifest (`RequiredModules = @('ParallelKit')`), or import it with `-Global`. Imported any other way, only your module sees the kit's functions, and a `.GetNewClosure()` block sees only global ones: a callback of yours that calls one then fails with "is not recognized". Importing by name often hides this, because PowerShell loads the module again for the callback, the newest version installed. + +`Import-Module -Prefix`, and `-Function` with only some of its functions, have the same limit. Import all of it under its own names. + +
+ +
+In workers + +A worker gets the functions meant for it whether or not the module is installed. The rest (`Invoke-PkRun`, `Set-PkMessageHandler` and the like) are for the main thread, and the worker-safety check refuses a worker that calls one. A call it can't see (through a variable, or with `-CheckWorkerSafety:$false`) fails if the module isn't installed. If it is, PowerShell loads it in the worker: the newest version installed, whatever your script loaded, even by dot-sourcing. If that version's compiled parts differ, loading it is refused. + +
+ +
+More than one copy in a session + +Use one way of loading it, and one version, per session. Dot-sourcing replaces a module already imported, but importing after dot-sourcing, or importing a second version, leaves both loaded, and the last one loaded is the one your calls reach. `Remove-Module ParallelKit` removes both. + +
+ ## How it fits together 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. @@ -377,7 +424,7 @@ Each worker runs in its own runspace: a separate PowerShell session inside the s - Each job hashtable's keys become the worker's parameters. The worker's `param()` block must declare every key, and every job must supply each parameter it makes `[Parameter(Mandatory)]` (`CancelToken` aside, which is filled in). Either mistake is an error; with a fixed `-JobParams` list it's caught before any worker starts, and a `-NextJobProvider` job is checked as it arrives. A worker with parameter sets isn't checked for mandatory ones, since what it needs depends on the set. - If the worker declares a `$CancelToken` parameter, it gets the run's cancellation token. - `-JobParams` takes a list or array of job hashtables. A single hashtable works too, so a list that happens to hold one job is fine. -- 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. +- A worker runspace starts empty. Name every one of your functions it calls in `-SharedFunctionNames`. The kit's own worker functions are always there (its [others](#as-a-module) aren't for workers), 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. - `-MaxConcurrent` has no default; you choose it. `-AbortTimeoutSeconds` (how long Ctrl+C waits for running workers) defaults to 60. @@ -638,9 +685,9 @@ powershell -NoProfile -File .\ParallelKit.Harness.ps1
What it prints, and the stress tests in Testing/ -It takes about five and a half minutes. It prints a `[PASS]`/`[FAIL]` line per check and exits 0 only if everything passed. A few checks send real Ctrl+C, Ctrl+Break and window-close events to child PowerShell processes in hidden consoles of their own, never to yours. Where a machine can't deliver those, they print `[SKIP]` with the reason instead; set `PK_HARNESS_NO_SKIP=1` to count skips as failures. A few `message handler failed` lines in the output are expected: some checks break the message handler on purpose to test the fallback. `-Section AO,BB` runs only those sections (and A, the setup), for working on one area; it isn't a full pass, and its last line says so. +It takes about five and a half minutes. It prints a `[PASS]`/`[FAIL]` line per check and exits 0 only if everything passed. A few checks send real Ctrl+C, Ctrl+Break and window-close events to child PowerShell processes in hidden consoles of their own, never to yours. Where a machine can't deliver those, they print `[SKIP]` with the reason instead; set `PK_HARNESS_NO_SKIP=1` to count skips as failures. A few `message handler failed` lines in the output are expected: some checks break the message handler on purpose to test the fallback. `-Section AO,BB` runs only those sections (and A, the setup), for working on one area; it isn't a full pass, and its last line says so. `-AsModule` builds [the module](#as-a-module) and tests that instead of dot-sourcing the file; `-AsModule -Section MODULE` runs the sections where that can make a difference, in about a minute and a half. -GitHub runs the same harness on Windows PowerShell 5.1 and on PowerShell 7 for every pull request and every change to `main`. It also runs the soak test below on both before each release ([runs](https://github.com/HalRiveria/PowerShell-ParallelKit/actions/workflows/soak.yml)). The other scripts in `Testing/` are run by hand. +GitHub runs the same harness on Windows PowerShell 5.1 and on PowerShell 7 for every pull request and every change to `main`, and then those sections on the module. It also runs the soak test below on both before each release ([runs](https://github.com/HalRiveria/PowerShell-ParallelKit/actions/workflows/soak.yml)). The other scripts in `Testing/` are run by hand. `Testing/` holds the longer stress tests and checks behind some of what this README says. They aren't part of the test suite and aren't needed to use the kit: @@ -752,7 +799,7 @@ Additions, changes, fixes, and other things that have been evaluated and decline - **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`. +- **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`. The module does have a build step, but the same `.ps1` always gives the same module, so you can build it and compare. - **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 timeouts.** `-AbortTimeoutSeconds` is whole seconds; 2.5 is rounded to a whole number. `-TimeoutSeconds`, the time limit on a program, does take fractions. From aebaec5a5e4236d5e6635f3ee0dc52e1b15a62d6 Mon Sep 17 00:00:00 2001 From: Hal <22532613+HalRiveria@users.noreply.github.com> Date: Tue, 1 Dec 2026 17:38:33 -0500 Subject: [PATCH 08/10] Put the module path back after an -AsModule run Co-Authored-By: Claude Opus 5.5 --- ParallelKit.Harness.ps1 | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/ParallelKit.Harness.ps1 b/ParallelKit.Harness.ps1 index 87123d4..c48938b 100644 --- a/ParallelKit.Harness.ps1 +++ b/ParallelKit.Harness.ps1 @@ -38,7 +38,10 @@ if ($AsModule) { $kitPath = Join-Path $moduleDir 'load.ps1' # This version: another may be installed. [System.IO.File]::WriteAllText($kitPath, 'Import-Module ParallelKit -RequiredVersion ' + $moduleVersion + "`r`n") - $env:PSModulePath = (Join-Path $moduleDir 'mods') + ';' + $env:PSModulePath + # Both put back at the end, for a run in a window that stays open. + $savedModulePath = $env:PSModulePath + $savedCachePath = $env:PSModuleAnalysisCachePath + $env:PSModulePath = (Join-Path $moduleDir 'mods') + ';' + $savedModulePath $env:PSModuleAnalysisCachePath = Join-Path $moduleDir 'ModuleAnalysisCache' } . $kitPath @@ -6002,7 +6005,11 @@ Write-Host "" Set-PkMessageHandler -Handler $null Reset-PkAbortState -if ($null -ne $moduleDir) { Remove-Item -LiteralPath $moduleDir -Recurse -Force -ErrorAction SilentlyContinue } +if ($null -ne $moduleDir) { + $env:PSModulePath = $savedModulePath + $env:PSModuleAnalysisCachePath = $savedCachePath + Remove-Item -LiteralPath $moduleDir -Recurse -Force -ErrorAction SilentlyContinue +} Write-Host "===============================================" $skipText = "" From 5f0f90c873a6b3161952c104240f4fa271c8731e Mon Sep 17 00:00:00 2001 From: Hal <22532613+HalRiveria@users.noreply.github.com> Date: Tue, 1 Dec 2026 18:31:26 -0500 Subject: [PATCH 09/10] Test, check and pack the module before a release A new workflow runs the harness on the module, checks that it builds the same under 5.1 and 7 and that PSScriptAnalyzer reports no errors, and keeps the packed module with the run. It publishes nothing. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/module.yml | 169 +++++++++++++++++++++++++++++++++++ README.md | 2 +- 2 files changed, 170 insertions(+), 1 deletion(-) create mode 100644 .github/workflows/module.yml diff --git a/.github/workflows/module.yml b/.github/workflows/module.yml new file mode 100644 index 0000000..e2ce0a1 --- /dev/null +++ b/.github/workflows/module.yml @@ -0,0 +1,169 @@ +name: Module + +# Tests the kit built as a PowerShell module, and packs it for the PowerShell +# Gallery. Nothing is published: the package is kept with the run. Before a +# release (a version's branch is release/X.Y or version/X.Y) it runs the whole +# harness on the module. On a published release, by hand, and on a pull request +# that changes the build, it runs the sections where loading can matter. Not a +# required check. +on: + push: + branches: ['release/**', 'version/**'] + pull_request: + paths: + - 'Build/**' + - '.github/workflows/module.yml' + release: + types: [published] + workflow_dispatch: + inputs: + tag: + description: Release tag to build (e.g. v4.0). Empty builds the branch it's run on. + required: false + +permissions: + contents: read + +env: + # As in tests.yml: the harness's console-event checks must run here. + PK_HARNESS_NO_SKIP: '1' + # Empty for a version's branch: the whole harness. + SECTIONS: ${{ github.event_name != 'push' && 'MODULE' || '' }} + +jobs: + # Windows PowerShell 5.1. test-pwsh is the same on PowerShell 7: keep the two + # in step. + test: + name: Module + runs-on: windows-latest + timeout-minutes: 20 + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ inputs.tag || github.event.release.tag_name || '' }} + + - name: Run the harness on the module + shell: powershell + run: | + $harness = @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', '.\ParallelKit.Harness.ps1', '-AsModule') + if ($env:SECTIONS) { $harness += @('-Section', $env:SECTIONS) } + & powershell.exe @harness + exit $LASTEXITCODE + + # PowerShell 7. Keep in step with test. + test-pwsh: + name: Module (PowerShell 7) + runs-on: windows-latest + timeout-minutes: 20 + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ inputs.tag || github.event.release.tag_name || '' }} + + - name: Run the harness on the module under pwsh + shell: pwsh + run: | + $harness = @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', '.\ParallelKit.Harness.ps1', '-AsModule') + if ($env:SECTIONS) { $harness += @('-Section', $env:SECTIONS) } + & pwsh @harness + exit $LASTEXITCODE + + package: + name: Module package + needs: [test, test-pwsh] + runs-on: windows-latest + timeout-minutes: 15 + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ inputs.tag || github.event.release.tag_name || '' }} + + - name: Check the tag against the kit's version + if: inputs.tag || github.event_name == 'release' + shell: pwsh + env: + TAG: ${{ inputs.tag || github.event.release.tag_name }} + run: | + $version = [regex]::Match((Get-Content -Raw .\ParallelKit.ps1), '(?m)^# Version (\d+\.\d+(?:\.\d+)?)\b').Groups[1].Value + if ($env:TAG -ne "v$version") { throw "The tag is '$($env:TAG)', but ParallelKit.ps1 says version '$version'. Tag the commit whose version it is." } + + - name: Build under Windows PowerShell + shell: powershell + run: | + & powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\Build\New-ParallelKitModule.ps1 -OutputDirectory .\out-5.1\ParallelKit + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + Test-ModuleManifest -Path .\out-5.1\ParallelKit\ParallelKit.psd1 -ErrorAction Stop | Format-List Name, Version, Guid, CompatiblePSEditions + + - name: Build under PowerShell 7, and compare + shell: pwsh + run: | + & pwsh -NoProfile -ExecutionPolicy Bypass -File .\Build\New-ParallelKitModule.ps1 -OutputDirectory .\out\ParallelKit + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + Test-ModuleManifest -Path .\out\ParallelKit\ParallelKit.psd1 -ErrorAction Stop | Format-List Name, Version, Guid, CompatiblePSEditions + foreach ($file in 'ParallelKit.psm1', 'ParallelKit.psd1') { + $hashes = @('out', 'out-5.1' | ForEach-Object { (Get-FileHash ".\$_\ParallelKit\$file").Hash }) + if ($hashes[0] -ne $hashes[1]) { throw "$file differs between the build under 5.1 ($($hashes[1])) and under 7 ($($hashes[0])). The same ParallelKit.ps1 must always give the same module." } + } + + - name: Check it with PSScriptAnalyzer + shell: pwsh + run: | + if (-not (Get-Module -ListAvailable PSScriptAnalyzer)) { Install-PSResource PSScriptAnalyzer -Version 1.25.0 -Repository PSGallery -TrustRepository -Scope CurrentUser -ErrorAction Stop } + # It sometimes fails inside with "Object reference not set", losing + # results, or hangs. So: a process of its own, a time limit, and only + # a run with no such error counts. + $analyze = Join-Path $env:RUNNER_TEMP 'analyze.ps1' + $found = Join-Path $env:RUNNER_TEMP 'analyzer.json' + @' + param([string]$Path, [string]$Out) + Import-Module PSScriptAnalyzer -ErrorAction Stop + $problems = $null + $results = @(Invoke-ScriptAnalyzer -Path $Path -Recurse -ErrorAction SilentlyContinue -ErrorVariable problems) + if ($problems) { Write-Output ("PSScriptAnalyzer itself failed: " + $problems[0]); exit 2 } + Write-Output ("PSScriptAnalyzer " + (Get-Module PSScriptAnalyzer).Version + ": " + $results.Count + " results") + ConvertTo-Json -InputObject @($results | ForEach-Object { @{ Severity = [string]$_.Severity; RuleName = $_.RuleName; Line = $_.Line; Message = $_.Message } }) | Set-Content -LiteralPath $Out + exit 0 + '@ | Set-Content -LiteralPath $analyze + $done = $false + foreach ($try in 1..5) { + $run = Start-Process -FilePath (Get-Process -Id $PID).Path -ArgumentList @('-NoProfile', '-File', "`"$analyze`"", '-Path', '.\out\ParallelKit', '-Out', "`"$found`"") -NoNewWindow -PassThru + if (-not $run.WaitForExit(120000)) { Write-Output "Try ${try}: still running after 2 minutes, stopped."; $run.Kill($true); continue } + if ($run.ExitCode -eq 0) { $done = $true; break } + } + if (-not $done) { throw "PSScriptAnalyzer didn't complete in 5 tries. Run this job again." } + $results = @(Get-Content -Raw -LiteralPath $found | ConvertFrom-Json) + $results | Group-Object Severity, RuleName | Format-Table Count, Name -AutoSize + $errors = @($results | Where-Object { $_.Severity -in 'Error', 'ParseError' }) + if ($errors.Count -gt 0) { + $errors | Format-Table RuleName, Line, Message -Wrap + throw "PSScriptAnalyzer reports $($errors.Count) error(s), listed above. The Gallery wants those fixed before a module is published." + } + + - name: Pack it + shell: pwsh + run: | + # Compress-PSResource came with PSResourceGet 1.1.0. + $have = Get-Module -ListAvailable Microsoft.PowerShell.PSResourceGet | Sort-Object Version -Descending | Select-Object -First 1 + if ($null -eq $have -or $have.Version -lt [version]'1.1.0') { + Install-PSResource Microsoft.PowerShell.PSResourceGet -Version 1.2.0 -Repository PSGallery -TrustRepository -Scope CurrentUser -ErrorAction Stop + # A fresh process, so the version just installed is the one loaded. + $have = Get-Module -ListAvailable Microsoft.PowerShell.PSResourceGet | Sort-Object Version -Descending | Select-Object -First 1 + } + $null = New-Item -ItemType Directory -Force -Path .\package + & pwsh -NoProfile -Command "Import-Module Microsoft.PowerShell.PSResourceGet -RequiredVersion $($have.Version) -ErrorAction Stop; Compress-PSResource -Path .\out\ParallelKit -DestinationPath .\package -ErrorAction Stop" + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + $packages = @(Get-ChildItem .\package\*.nupkg) + if ($packages.Count -ne 1) { throw "Expected one package in .\package, found $($packages.Count)." } + # The module's files are the same for every build; the package around + # them isn't, so both are listed. + $lines = @(Get-FileHash $packages[0].FullName, .\out\ParallelKit\ParallelKit.psm1, .\out\ParallelKit\ParallelKit.psd1 | ForEach-Object { $_.Hash + ' ' + (Split-Path -Leaf $_.Path) }) + $lines | Set-Content .\package\SHA256SUMS.txt + (@('### Module package', '', '```') + $lines + @('```')) | Add-Content $env:GITHUB_STEP_SUMMARY + $lines + + - name: Keep the package + uses: actions/upload-artifact@v4 + with: + name: ParallelKit-module + path: package/ + if-no-files-found: error diff --git a/README.md b/README.md index cedab1a..57502c8 100644 --- a/README.md +++ b/README.md @@ -687,7 +687,7 @@ powershell -NoProfile -File .\ParallelKit.Harness.ps1 It takes about five and a half minutes. It prints a `[PASS]`/`[FAIL]` line per check and exits 0 only if everything passed. A few checks send real Ctrl+C, Ctrl+Break and window-close events to child PowerShell processes in hidden consoles of their own, never to yours. Where a machine can't deliver those, they print `[SKIP]` with the reason instead; set `PK_HARNESS_NO_SKIP=1` to count skips as failures. A few `message handler failed` lines in the output are expected: some checks break the message handler on purpose to test the fallback. `-Section AO,BB` runs only those sections (and A, the setup), for working on one area; it isn't a full pass, and its last line says so. `-AsModule` builds [the module](#as-a-module) and tests that instead of dot-sourcing the file; `-AsModule -Section MODULE` runs the sections where that can make a difference, in about a minute and a half. -GitHub runs the same harness on Windows PowerShell 5.1 and on PowerShell 7 for every pull request and every change to `main`, and then those sections on the module. It also runs the soak test below on both before each release ([runs](https://github.com/HalRiveria/PowerShell-ParallelKit/actions/workflows/soak.yml)). The other scripts in `Testing/` are run by hand. +GitHub runs the same harness on Windows PowerShell 5.1 and on PowerShell 7 for every pull request and every change to `main`, and then those sections on the module. It also runs the soak test below on both before each release ([runs](https://github.com/HalRiveria/PowerShell-ParallelKit/actions/workflows/soak.yml)), and the whole harness on the module, which it then checks with PSScriptAnalyzer and packs ([runs](https://github.com/HalRiveria/PowerShell-ParallelKit/actions/workflows/module.yml)). The other scripts in `Testing/` are run by hand. `Testing/` holds the longer stress tests and checks behind some of what this README says. They aren't part of the test suite and aren't needed to use the kit: From df6348837b03a741383834a2f69189597ec80258 Mon Sep 17 00:00:00 2001 From: Hal <22532613+HalRiveria@users.noreply.github.com> Date: Tue, 1 Dec 2026 18:34:10 -0500 Subject: [PATCH 10/10] Harness: no module analysis cache of its own Co-Authored-By: Claude Opus 5.5 --- ParallelKit.Harness.ps1 | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/ParallelKit.Harness.ps1 b/ParallelKit.Harness.ps1 index c48938b..01f309c 100644 --- a/ParallelKit.Harness.ps1 +++ b/ParallelKit.Harness.ps1 @@ -38,11 +38,12 @@ if ($AsModule) { $kitPath = Join-Path $moduleDir 'load.ps1' # This version: another may be installed. [System.IO.File]::WriteAllText($kitPath, 'Import-Module ParallelKit -RequiredVersion ' + $moduleVersion + "`r`n") - # Both put back at the end, for a run in a window that stays open. + # Put back at the end, for a run in a window that stays open. Not with a + # module analysis cache of its own: an empty one has every child process + # analyze every module installed, which took GitHub's 5.1 runner most of a + # minute each. $savedModulePath = $env:PSModulePath - $savedCachePath = $env:PSModuleAnalysisCachePath $env:PSModulePath = (Join-Path $moduleDir 'mods') + ';' + $savedModulePath - $env:PSModuleAnalysisCachePath = Join-Path $moduleDir 'ModuleAnalysisCache' } . $kitPath @@ -5871,7 +5872,6 @@ function New-BmFile([string]$Name, [string]$Text) { return $path } $oldModulePath = $env:PSModulePath -$oldCachePath = $env:PSModuleAnalysisCachePath try { # The same bytes every time, with LF or CRLF, and only the wrapper gone. @@ -5940,7 +5940,6 @@ Test-Assert (@('PSEdition_Desktop', 'PSEdition_Core', 'Windows' | Where-Object { # Loaded in fresh processes, by name and by path: what a caller does with it. # -OnComplete and -ResultHandler are closures that call the kit's functions. $env:PSModulePath = $bmMods + ';' + $oldModulePath -$env:PSModuleAnalysisCachePath = Join-Path $bmDir 'ModuleAnalysisCache' $bmUse = @' try { $tag = 'ok' @@ -5997,7 +5996,6 @@ Test-Assert ($bmOtherBuild.Results[0].ExitCode -eq 0 -and $bmStaleOut -like '*re } finally { $env:PSModulePath = $oldModulePath - $env:PSModuleAnalysisCachePath = $oldCachePath Remove-Item -LiteralPath $bmDir -Recurse -Force -ErrorAction SilentlyContinue } Write-Host "" @@ -6007,7 +6005,6 @@ Set-PkMessageHandler -Handler $null Reset-PkAbortState if ($null -ne $moduleDir) { $env:PSModulePath = $savedModulePath - $env:PSModuleAnalysisCachePath = $savedCachePath Remove-Item -LiteralPath $moduleDir -Recurse -Force -ErrorAction SilentlyContinue }