From 3c8eea5fbf55ef7238ec1ef3885a3d0bb6beb1fe Mon Sep 17 00:00:00 2001 From: Hal <22532613+HalRiveria@users.noreply.github.com> Date: Tue, 1 Dec 2026 16:12:28 -0500 Subject: [PATCH 1/4] Invoke-PkProcessBatch no longer needs the kit's functions to be global Two of the batch's own closures called Complete-PkProcess and Write-PkMessage by name. A .GetNewClosure() block only sees global functions, so a batch failed with "'Complete-PkProcess' is not recognized" when the kit was loaded for one module only. They're captured up front now, like the private helpers. Co-Authored-By: Claude Opus 5.5 --- ParallelKit.Harness.ps1 | 37 ++++++++++++++++++++++++++++++++++--- ParallelKit.ps1 | 13 ++++++++----- 2 files changed, 42 insertions(+), 8 deletions(-) diff --git a/ParallelKit.Harness.ps1 b/ParallelKit.Harness.ps1 index c9f132e..b9eea4e 100644 --- a/ParallelKit.Harness.ps1 +++ b/ParallelKit.Harness.ps1 @@ -1032,8 +1032,9 @@ Test-Assert ($probeThreads -eq $probeWas) ("and leaves the thread pool's minimum # A script run the way a prompt runs it (& script, or .\script.ps1) holds # the kit's functions in its own scope, where a .GetNewClosure() block can't -# see them. The kit's public functions are imported globally, so the batch (whose callbacks are -# closures) and a caller's closure that calls a kit function both work. +# see them. The kit's public functions are imported globally, so a caller's +# closure that calls one works; the batch's own closures don't rely on that +# (section Z). # Needs a fresh process, started with -Command rather than -File. $promptScript = Join-Path $env:TEMP ("pk-prompt-" + [guid]::NewGuid().ToString("N") + ".ps1") [System.IO.File]::WriteAllText($promptScript, @" @@ -2308,6 +2309,36 @@ Remove-Item -LiteralPath $modDir -Recurse -Force -ErrorAction SilentlyContinue $modOut = ([string]$modRun.Stdout + [string]$modRun.Stderr).Trim() -replace '\s+', ' ' Test-Assert ($modOut -match 'module private=105') ("a module's private function can be shared with workers (" + $modOut + ")") Test-Assert ($modOut -match 'kit modules=1') "loading the kit a second time leaves one ParallelKit module, not two" + +# The batch's own callbacks are closures, which only see global functions. The +# batch must not count on its public functions being global: here the kit is +# loaded inside another module, for that module only. One command runs and one +# can't start, so both of the kit's own closures that call a public function do. +$scopeText = [System.IO.File]::ReadAllText($kitPath) +$scopeClose = '} | Import-Module -Global' +Test-Assert ([regex]::Matches($scopeText, [regex]::Escape($scopeClose)).Count -eq 1) "the kit's last line is still the import this test rewrites" +$scopeDir = Join-Path $env:TEMP ("pk-harness-scope-" + $PID) +$null = New-Item -ItemType Directory -Force -Path $scopeDir +$scopeModule = Join-Path $scopeDir 'PkHarnessScope.psm1' +[System.IO.File]::WriteAllText($scopeModule, $scopeText.Replace($scopeClose, '} | Import-Module') + @' + +function Invoke-ScopeBatch { + $codes = [System.Collections.Generic.List[object]]::new() + $batch = Invoke-PkProcessBatch -Commands @( + @{ FilePath = $env:ComSpec; Arguments = '/c exit 7' } + @{ FilePath = 'C:\pk-harness-no-such-program.exe'; Arguments = '' } + ) -OnComplete { param($c, $r) $codes.Add($r.ExitCode) }.GetNewClosure() + 'finished=' + ($codes -join ',') + ' results=' + $batch.Results.Count + ' starterrors=' + @($batch.Results | Where-Object { $_.StartError }).Count +} +Export-ModuleMember -Function Invoke-ScopeBatch +'@) +$scopeScript = Join-Path $scopeDir 'use.ps1' +[System.IO.File]::WriteAllText($scopeScript, "Import-Module '" + $scopeModule + "'`r`n'kit global=' + [bool](Get-ChildItem Function: | Where-Object { `$_.Name -eq 'Complete-PkProcess' })`r`ntry { Invoke-ScopeBatch } catch { 'error: ' + `$_ }`r`n") +$scopeRun = Invoke-PkProcessWithTimeout -FilePath $selfExe -Arguments (ConvertTo-PkArgumentString @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command', ("& '" + $scopeScript + "'"))) -TimeoutMs 60000 +Remove-Item -LiteralPath $scopeDir -Recurse -Force -ErrorAction SilentlyContinue +$scopeOut = ([string]$scopeRun.Stdout + [string]$scopeRun.Stderr).Trim() -replace '\s+', ' ' +Test-Assert ($scopeOut -match 'kit global=False' -and $scopeOut -match 'finished=7 results=2 starterrors=1') ("a batch runs when the kit's functions aren't global (" + $scopeOut + ")") +Test-Assert ($scopeOut -match "a command couldn't start") "and reports the command that couldn't start" Write-Host "" } @@ -3810,7 +3841,7 @@ function Get-HarnessUnguardedCallbacks { # this list. Invoke-PkRun's `& $ScriptBlock` is the run itself, not called # from a loop. Returns @{ Calls; Problems }. param([string]$Source) - $internal = @('$pkNewBatchResult', '$pkGetStartFailureCause', '$pkGetJobTimeLimit', '$pkGetJobMaxOutputChars', '$pkGetJobSwitch', '$pkStopExitedJobTree', '$pkReportStartFailure', '$pkStartProcessCore', '$pkWriteCallbackLoopWarning') + $internal = @('$pkNewBatchResult', '$pkGetStartFailureCause', '$pkGetJobTimeLimit', '$pkGetJobMaxOutputChars', '$pkGetJobSwitch', '$pkStopExitedJobTree', '$pkReportStartFailure', '$pkStartProcessCore', '$pkWriteCallbackLoopWarning', '$pkWriteMessage', '$pkCompleteProcess') $problems = [System.Collections.Generic.List[string]]::new() $tokens = $null; $errors = $null $ast = [System.Management.Automation.Language.Parser]::ParseInput($Source, [ref]$tokens, [ref]$errors) diff --git a/ParallelKit.ps1 b/ParallelKit.ps1 index 3c5f4d7..d3a1d09 100644 --- a/ParallelKit.ps1 +++ b/ParallelKit.ps1 @@ -3224,8 +3224,9 @@ function Invoke-PkProcessBatch { $pkResults = [System.Collections.Generic.List[object]]::new() $pkState = @{ Given = $false } - # The closures below can't see the module's private functions (a - # .GetNewClosure() block only sees global ones), so take these along. + # The closures below can't see the module's functions (a .GetNewClosure() + # block only sees global ones), so take these along: the public ones too, + # which aren't global when the kit is loaded for one module only. $pkNewBatchResult = ${function:New-PkBatchResult} $pkStartProcessCore = ${function:Start-PkProcessCore} $pkGetJobTimeLimit = ${function:Get-PkJobTimeLimit} @@ -3233,6 +3234,8 @@ function Invoke-PkProcessBatch { $pkGetJobSwitch = ${function:Get-PkJobSwitch} $pkGetStartFailureCause = ${function:Get-PkStartFailureCause} $pkWriteCallbackLoopWarning = ${function:Write-PkCallbackLoopWarning} + $pkWriteMessage = ${function:Write-PkMessage} + $pkCompleteProcess = ${function:Complete-PkProcess} # Invoke-PkCallback's -PkContext: callbacks that used continue/break are # warned about once each, under this prefix. $pkCallbackContext = @{ Prefix = 'Invoke-PkProcessBatch: '; Warned = @{} } @@ -3252,7 +3255,7 @@ function Invoke-PkProcessBatch { return } $pkStartFailures[$pkFailureKey] = @{ FilePath = $pkFilePath; Cause = $pkCause; More = 0 } - Write-PkMessage ("Invoke-PkProcessBatch: a command couldn't start: " + $pkError) -Level Error + & $pkWriteMessage ("Invoke-PkProcessBatch: a command couldn't start: " + $pkError) -Level Error }.GetNewClosure() $pkGroupProvider = { @@ -3302,7 +3305,7 @@ function Invoke-PkProcessBatch { $pkJobFinalize = { param($pkJob, $pkPendingQueue) - $pkR = & $pkNewBatchResult -Command $pkJob['Command'] -Completed (Complete-PkProcess -Job $pkJob) -TimedOut ([bool]$pkJob['TimedOut']) + $pkR = & $pkNewBatchResult -Command $pkJob['Command'] -Completed (& $pkCompleteProcess -Job $pkJob) -TimedOut ([bool]$pkJob['TimedOut']) $pkResults.Add($pkR) if ($null -ne $pkOnComplete) { # Invoke-PkCallback, inlined: this runs per command. @@ -4350,7 +4353,7 @@ function Test-PkWorkerSafetyCore { # ============================================================================== # Imported globally: a .GetNewClosure() block only sees global functions, -# so this lets the batch's callbacks, and yours, call them. The same list is +# so this lets a callback of yours call them. The same list is # $publicFunctions in ParallelKit.Harness.ps1; keep the two in step. Export-ModuleMember -Function @( 'Set-PkMessageHandler', 'Write-PkMessage', 'Initialize-ParallelKit', 'Register-PkCancellationSource', From 1ec5c06b7ce913df40c6ff05f7f9d6a3540068c1 Mon Sep 17 00:00:00 2001 From: Hal <22532613+HalRiveria@users.noreply.github.com> Date: Tue, 1 Dec 2026 16:24:37 -0500 Subject: [PATCH 2/4] Set-PkMessageHandler throws in worker code A worker given the function (-SharedFunctionNames takes it) could set a handler made in its own runspace, which the main thread then ran for every message. Running another runspace's scriptblock can hang or crash PowerShell. Co-Authored-By: Claude Opus 5.5 --- ParallelKit.Harness.ps1 | 12 ++++++++++++ ParallelKit.ps1 | 6 ++++++ README.md | 2 +- 3 files changed, 19 insertions(+), 1 deletion(-) diff --git a/ParallelKit.Harness.ps1 b/ParallelKit.Harness.ps1 index b9eea4e..86def59 100644 --- a/ParallelKit.Harness.ps1 +++ b/ParallelKit.Harness.ps1 @@ -801,6 +801,18 @@ Set-PkMessageHandler -Handler { param($Message, $Level) "noise"; 42 } $leaked = Write-PkMessage "hello" Test-Assert ($null -eq $leaked) "a message handler's output doesn't leak out of Write-PkMessage" Set-PkMessageHandler -Handler { param($Message, $Level) $messageSink.Add(@{ Message = $Message; Level = $Level }) }.GetNewClosure() + +# Set in a worker, the handler would be the worker's scriptblock, run by the main thread. +$handlerCrash = [System.Collections.Generic.List[string]]::new() +$handlerBefore = [PkState]::MessageHandler +$handlerRun = Invoke-PkRunspaceJobs -MaxParallel 1 -JobParams (New-JobList -Jobs @(@{ Reset = $false }, @{ Reset = $true })) -SharedFunctionNames Set-PkMessageHandler -JobCrashedHandler { param($e) $handlerCrash.Add([string]$e.Exception.InnerException.Message) }.GetNewClosure() -WorkerScript { + param($Reset) + if ($Reset) { Set-PkMessageHandler $null } else { Set-PkMessageHandler { param($Message, $Level) } } +} +$handlerKept = [object]::ReferenceEquals($handlerBefore, [PkState]::MessageHandler) +[PkState]::MessageHandler = $handlerBefore +Test-Assert ($handlerRun.CrashedCount -eq 2 -and @($handlerCrash | Where-Object { $_ -like '*Set-PkMessageHandler*main thread*' }).Count -eq 2) ("Set-PkMessageHandler throws in a worker, for a handler or `$null (" + ($handlerCrash -join '; ') + ")") +Test-Assert $handlerKept "and leaves the handler as it was" Write-Host "" } diff --git a/ParallelKit.ps1 b/ParallelKit.ps1 index d3a1d09..d618f85 100644 --- a/ParallelKit.ps1 +++ b/ParallelKit.ps1 @@ -1098,12 +1098,18 @@ function Set-PkMessageHandler { # always runs on the main thread, including for messages from worker code. If it # throws, the message is shown on the console instead and the run carries on. # Leave it early with return: continue and break end it too, but warn once. + # Throws in worker code; call it on the main thread. # .PARAMETER Handler # { param($Message, $Level) ... }, or $null to go back to the default (console). # .EXAMPLE # Set-PkMessageHandler { param($Message, $Level) Add-Content run.log "$Level $Message" } [CmdletBinding()] param([scriptblock]$Handler) + # A worker's scriptblock belongs to its runspace: the main thread running + # it can hang or crash. + if ($null -ne $global:PkWorkerQueue) { + throw "Set-PkMessageHandler: this is worker code, and the handler can only be set on the main thread, which runs it. Set it before starting the workers; Write-PkMessage in a worker already goes to it." + } [PkState]::MessageHandler = $Handler } diff --git a/README.md b/README.md index e7d2f61..23d0df5 100644 --- a/README.md +++ b/README.md @@ -578,7 +578,7 @@ Workers can't safely write to the console. `Write-PkMessage "text" -Level Info|W Set-PkMessageHandler { param($Message, $Level) Write-MyLog $Message $Level } ``` -The handler always runs on the main thread, so it can use anything. The kit's own notices (abort announcements, crashed workers, force-stops) go through the same handler. If your handler throws, the message is shown on the console instead and the run carries on. `Set-PkMessageHandler $null` restores the default. +The handler always runs on the main thread, so it can use anything. The kit's own notices (abort announcements, crashed workers, force-stops) go through the same handler. If your handler throws, the message is shown on the console instead and the run carries on. `Set-PkMessageHandler $null` restores the default. Call it on the main thread: in worker code it throws. ## Abort From 4a2e332ad35e8d3ad8f303b811ae281a48a759b3 Mon Sep 17 00:00:00 2001 From: Hal <22532613+HalRiveria@users.noreply.github.com> Date: Tue, 1 Dec 2026 16:37:08 -0500 Subject: [PATCH 3/4] Invoke-PkProcessWithTimeout starts nothing during an abort or cancel It only looked for an abort after its first 200 ms wait, so a program that finished sooner ran to the end and returned normally, and a slower one ran for about 200 ms before it was killed. It now throws before starting the program, unless -IgnoreAbort is given. Co-Authored-By: Claude Opus 5.5 --- ParallelKit.Harness.ps1 | 28 ++++++++++++++++++++++++++++ ParallelKit.ps1 | 10 +++++++--- README.md | 2 +- 3 files changed, 36 insertions(+), 4 deletions(-) diff --git a/ParallelKit.Harness.ps1 b/ParallelKit.Harness.ps1 index 86def59..f0ce80d 100644 --- a/ParallelKit.Harness.ps1 +++ b/ParallelKit.Harness.ps1 @@ -1477,6 +1477,34 @@ $cleanup = $null try { $cleanup = Invoke-PkProcessWithTimeout -FilePath $pingExe -Arguments '-n 3 127.0.0.1' -IgnoreAbort } catch { } Test-Assert ($null -ne $cleanup -and $cleanup.ExitCode -eq 0) "-IgnoreAbort lets a cleanup program run to the end during an abort" +# A program quick enough to finish before the abort was looked at used to run. +# Each writes a file, so a run leaves a trace. +$quickDir = Join-Path $env:TEMP ("pk-harness-quick-" + $PID) +$null = New-Item -ItemType Directory -Force -Path $quickDir +$quickError = $null +try { $null = Invoke-PkProcessWithTimeout -FilePath $cmdExe -Arguments ('/c echo ran> "' + $quickDir + '\abort.txt"') } catch { $quickError = [string]$_ } +Test-Assert ($quickError -like "*wasn't started because the run is being aborted*" -and -not (Test-Path -LiteralPath ($quickDir + '\abort.txt'))) ("during an abort, a quick program isn't started (" + $quickError + ")") +$quick = $null +try { $quick = Invoke-PkProcessWithTimeout -FilePath $cmdExe -Arguments ('/c echo ran> "' + $quickDir + '\ignore.txt"') -IgnoreAbort } catch { } +Test-Assert ($null -ne $quick -and (Test-Path -LiteralPath ($quickDir + '\ignore.txt'))) "-IgnoreAbort still runs it" +Reset-Harness +# The same in a worker, when its run is canceled rather than aborted. +$quickCts = [System.Threading.CancellationTokenSource]::new() +$quickCrash = [System.Collections.Generic.List[string]]::new() +$quickPolls = @{ Count = 0 } +$null = Invoke-PkRunspaceJobs -MaxParallel 1 -Cts $quickCts -DrainTimeoutSeconds 20 -JobParams (New-JobList -Jobs @(@{ Cmd = $cmdExe; Dir = $quickDir })) ` + -PollCallback { $quickPolls.Count++; if ($quickPolls.Count -eq 3) { $quickCts.Cancel() } }.GetNewClosure() ` + -JobCrashedHandler { param($e) $quickCrash.Add([string]$e.Exception.InnerException.Message) }.GetNewClosure() -WorkerScript { + param($Cmd, $Dir) + $waited = [System.Diagnostics.Stopwatch]::StartNew() + while (-not (Test-PkCancelRequested) -and $waited.Elapsed.TotalSeconds -lt 15) { [System.Threading.Thread]::Sleep(20) } + $null = Invoke-PkProcessWithTimeout -FilePath $Cmd -Arguments ('/c echo ran> "' + $Dir + '\ignored.txt"') -IgnoreAbort + $null = Invoke-PkProcessWithTimeout -FilePath $Cmd -Arguments ('/c echo ran> "' + $Dir + '\cancel.txt"') + } +Test-Assert ($quickCrash.Count -eq 1 -and $quickCrash[0] -like "*wasn't started because the run is being aborted*" -and -not (Test-Path -LiteralPath ($quickDir + '\cancel.txt')) -and (Test-Path -LiteralPath ($quickDir + '\ignored.txt'))) ("in a worker whose run is canceled, a quick program isn't started, except with -IgnoreAbort (" + ($quickCrash -join '; ') + ")") +$quickCts.Dispose() +Remove-Item -LiteralPath $quickDir -Recurse -Force -ErrorAction SilentlyContinue + # A job's own Group field is left alone. Reset-Harness $feed = @{ Given = $false } diff --git a/ParallelKit.ps1 b/ParallelKit.ps1 index d618f85..b1af98b 100644 --- a/ParallelKit.ps1 +++ b/ParallelKit.ps1 @@ -2244,7 +2244,8 @@ function Invoke-PkProcessWithTimeout { # .DESCRIPTION # Throws if the program had to be killed: because it ran past -TimeoutMs, or # because the run was aborted or canceled while it was going. Anything the - # program started is killed with it. + # program started is killed with it. During an abort or cancel it throws + # without starting the program. # .PARAMETER FilePath # The program to run. # .PARAMETER Arguments @@ -2270,8 +2271,8 @@ function Invoke-PkProcessWithTimeout { # nothing it left behind holds its output open. Only for a program Windows # gave a Job Object of its own, the normal case. # .PARAMETER IgnoreAbort - # Keep going during an abort, for a cleanup or restore step that has to run - # because of it. + # Start and keep going during an abort, for a cleanup or restore step that has + # to run because of it. # .OUTPUTS # Complete-PkProcess's object: ExitCode, Stdout, Stderr, StreamTimedOut, # StreamError, Duration (how long the program ran, from its start to its @@ -2298,6 +2299,9 @@ function Invoke-PkProcessWithTimeout { # Start-PkProcess, Invoke-PkProcessBatch and Invoke-PkProcessDispatch make the # same check: keep the four in step. if ($MaxOutputChars -lt 0) { throw ("Invoke-PkProcessWithTimeout: -MaxOutputChars must be 0 (no cap) or more (got " + $MaxOutputChars + "). It's how many characters of each output stream to keep.") } + # Here as well as in the loop, which only looks after its first wait: a + # quick program would have run to the end by then. + if (-not $IgnoreAbort -and ((Test-PkAbortSignal) -or (Test-PkCancelRequested))) { throw ("'" + $FilePath + "' wasn't started because the run is being aborted") } $job = Start-PkProcessCore -FilePath $FilePath -Arguments $Arguments -WorkingDirectory $WorkingDirectory -OutputEncoding $OutputEncoding -MaxOutputChars $MaxOutputChars -InheritStdin:$InheritStdin -CallerState $PSCmdlet.SessionState $job['KillTree'] = $KillTreeOnExit.IsPresent try { diff --git a/README.md b/README.md index 23d0df5..70dd329 100644 --- a/README.md +++ b/README.md @@ -561,7 +561,7 @@ For one program at a time, outside the engines. All of these are safe in worker | Function | Use | |---|---| -| `Invoke-PkProcessWithTimeout -FilePath -Arguments -TimeoutMs` | Run one program and wait, with a hard time limit (default 60s). Returns the [process result](#process-results) fields marked "all". If it overruns, or the run is aborted, the program is killed and this **throws**; add `-IgnoreAbort` for a cleanup step that must finish anyway. | +| `Invoke-PkProcessWithTimeout -FilePath -Arguments -TimeoutMs` | Run one program and wait, with a hard time limit (default 60s). Returns the [process result](#process-results) fields marked "all". If it overruns, or the run is aborted, the program is killed and this **throws**; called while an abort or cancel is already in force, it throws without starting the program. Add `-IgnoreAbort` for a cleanup step that must run anyway. | | `ConvertTo-PkArgumentString @(args)` | Join a list of arguments into one correctly quoted command line. `-Arguments` / `Arguments` also take the list directly, and then also quote it for `cmd.exe` when the program is a `.bat` or `.cmd`. | | `Start-PkProcess -FilePath -Arguments` | Start one hidden, with output captured in the background. Returns `@{ Proc; StdoutTask; StderrTask; Stopwatch }`; throws if it can't start. | | `Wait-PkProcess -Process -TimeoutMs` | Wait for exit with a timeout that can't overrun. Returns `$true` if it exited. | From fde58ffff2c1c38b7ec59b5476c44f4cdf48caa3 Mon Sep 17 00:00:00 2001 From: Hal <22532613+HalRiveria@users.noreply.github.com> Date: Tue, 1 Dec 2026 16:49:18 -0500 Subject: [PATCH 4/4] 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.