From 1236d8e95e096ebb24fdca1a0aeeab912c7bb56e Mon Sep 17 00:00:00 2001 From: Hal <22532613+HalRiveria@users.noreply.github.com> Date: Wed, 2 Dec 2026 17:53:28 -0500 Subject: [PATCH 1/9] Quote a list for cmd.exe under a drive-relative path too Batch-file quoting was picked by a pattern that needed a slash or the start of the path before 'cmd', so C:cmd.exe and C:cmd got the ordinary quoting, where a quote is written \" and cmd.exe doesn't honor it: an element like 'a" & echo X & "' ran a second command. The pattern now accepts a colon there too. Harness section AE runs the injection payload through C:cmd.exe, C:cmd and C:CMD.EXE. from System32. --- ParallelKit.Harness.ps1 | 18 ++++++++++++++++++ ParallelKit.ps1 | 4 ++-- 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/ParallelKit.Harness.ps1 b/ParallelKit.Harness.ps1 index b6a1171..0537669 100644 --- a/ParallelKit.Harness.ps1 +++ b/ParallelKit.Harness.ps1 @@ -3075,6 +3075,24 @@ if ($compiled) { Test-Assert ($cmdHits -eq 0 -and $cmdThrew -eq 0) ("a quote in a list element can't make cmd.exe /c run another command (" + $cmdHits + " of " + ($cmdNames.Count * $injPayloads.Count) + " did, " + $cmdThrew + " failed to run)") $cmdBatch = Invoke-PkProcessBatch -MaxConcurrent 1 -Commands @(@{ FilePath = 'cmd.exe'; WorkingDirectory = $injDir; Arguments = @('/d', '/c', 'echo', $injPayloads[0]) }) Test-Assert (-not [System.IO.File]::Exists($injMarker) -and $cmdBatch.Results[0].ExitCode -eq 0) "the same for cmd.exe through the batch" + # A drive-relative path (C:cmd.exe, from System32 as that drive's current + # folder) still names cmd.exe, so it gets the same quoting. + $sys32 = Join-Path $env:SystemRoot 'System32' + $cmdDrive = $sys32.Substring(0, 2) + $relHits = 0 + $relThrew = 0 + $relRan = 0 + Push-Location -LiteralPath $sys32 + try { + foreach ($cmdName in @(($cmdDrive + 'cmd.exe'), ($cmdDrive + 'cmd'), ($cmdDrive + 'CMD.EXE.'))) { + try { + $relResult = Invoke-PkProcessWithTimeout -FilePath $cmdName -Arguments @('/d', '/c', 'echo', $injPayloads[0]) -WorkingDirectory $injDir -TimeoutMs 10000 + if ($relResult.ExitCode -eq 0) { $relRan++ } + } catch { $relThrew++; Write-Host " injection probe threw: $_" } + if ([System.IO.File]::Exists($injMarker)) { $relHits++; [System.IO.File]::Delete($injMarker) } + } + } finally { Pop-Location } + Test-Assert ($relHits -eq 0 -and $relThrew -eq 0 -and $relRan -eq 3) ("nor under a drive-relative path to cmd.exe (" + $relHits + " of 3 did, " + $relThrew + " failed to run, " + $relRan + " ran)") # A line break would end cmd.exe's command line and drop the rest, so it's # refused for a batch file, and still fine for any other program. diff --git a/ParallelKit.ps1 b/ParallelKit.ps1 index 269f4c8..9cace24 100644 --- a/ParallelKit.ps1 +++ b/ParallelKit.ps1 @@ -1593,9 +1593,9 @@ function Resolve-PkArgumentList { # Windows drops trailing dots and spaces from a file name, so # 'run.cmd.' still runs through cmd.exe. cmd.exe itself, given a list # (cmd /c tool "a b"), reads its command line the same way, so it gets - # the same quoting. + # the same quoting, under a drive-relative path (C:cmd.exe) too. $exeName = $FilePath.Trim().Trim('"').TrimEnd(' ', '.') - $forBatchFile = ($exeName -match '\.(bat|cmd)$' -or $exeName -match '(^|[\\/])cmd(\.exe)?$') + $forBatchFile = ($exeName -match '\.(bat|cmd)$' -or $exeName -match '(^|[\\/:])cmd(\.exe)?$') return (ConvertTo-PkArgumentStringCore -Arguments @($Arguments) -ForBatchFile:$forBatchFile) } return [string]$Arguments From 4b28b0119612af5f225332e1969dc1301778b4e3 Mon Sep 17 00:00:00 2001 From: Hal <22532613+HalRiveria@users.noreply.github.com> Date: Wed, 2 Dec 2026 18:08:32 -0500 Subject: [PATCH 2/9] Start no more work once an abort is requested between the engines' checks Request-PkAbort and Ctrl+C only raise a flag; the engines stop on their token, which Test-PkAbortSignal cancels, and each main loop called it only after its launch step. So an abort requested before a runspace batch, or by a -ResultHandler, -NextJobProvider or the dispatcher's -PollCallback, still started a round of workers or programs first, and one raised by -JobFinalize had the dispatcher ask -GroupProvider for more groups. Both main loops now check the flag first, the dispatcher checks it again after -PollCallback, and the runspace engine's launch loop reads it per job. Harness section O covers each of those five cases. --- ParallelKit.Harness.ps1 | 42 +++++++++++++++++++++++++++++++++++++++++ ParallelKit.ps1 | 17 ++++++++++++++++- 2 files changed, 58 insertions(+), 1 deletion(-) diff --git a/ParallelKit.Harness.ps1 b/ParallelKit.Harness.ps1 index 0537669..1398b19 100644 --- a/ParallelKit.Harness.ps1 +++ b/ParallelKit.Harness.ps1 @@ -967,6 +967,48 @@ $out = Invoke-PkRunspaceBatch -MaxConcurrent 2 -JobParams (New-JobList -Jobs @(1 -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" +# An abort requested between the engines' checks (Request-PkAbort with no +# Test-PkAbortSignal after it, or from a callback) starts nothing more. +Reset-Harness +Request-PkAbort +$results = [System.Collections.Generic.List[object]]::new() +$out = Invoke-PkRunspaceBatch -MaxConcurrent 4 -JobParams (New-JobList -Jobs @(1..8 | ForEach-Object { @{ Id = $_ } })) ` + -WorkerScript { param([int]$Id) return $Id } -ResultHandler { param($r) $results.Add($r) }.GetNewClosure() +Test-Assert ($out.Aborted -and $results.Count -eq 0) ("runspace jobs: an abort requested before the run starts no worker (ran " + $results.Count + " of 8)") + +Reset-Harness +$results = [System.Collections.Generic.List[object]]::new() +$out = Invoke-PkRunspaceBatch -MaxConcurrent 2 -JobParams (New-JobList -Jobs @(1..20 | ForEach-Object { @{ Id = $_ } })) ` + -WorkerScript { param([int]$Id) [System.Threading.Thread]::Sleep(300); return $Id } ` + -ResultHandler { param($r) $results.Add($r); if ($results.Count -eq 1) { Request-PkAbort } }.GetNewClosure() +Test-Assert ($out.Aborted -and $results.Count -eq 2) ("runspace jobs: the slots a -ResultHandler frees after requesting an abort aren't refilled (ran " + $results.Count + " of 20)") + +Reset-Harness +$results = [System.Collections.Generic.List[object]]::new() +$feed = @{ Next = 0 } +$out = Invoke-PkRunspaceBatch -MaxConcurrent 4 -WorkerScript { param([int]$Id) [System.Threading.Thread]::Sleep(300); return $Id } ` + -NextJobProvider { if ($feed.Next -ge 8) { return $null }; $feed.Next++; if ($feed.Next -eq 2) { Request-PkAbort }; return @{ Id = $feed.Next } }.GetNewClosure() ` + -ResultHandler { param($r) $results.Add($r) }.GetNewClosure() +Test-Assert ($out.Aborted -and $feed.Next -eq 2 -and $results.Count -eq 2) ("runspace jobs: -NextJobProvider isn't asked again once it requests an abort (asked " + $feed.Next + " times, ran " + $results.Count + ")") + +Reset-Harness +$starts = @{ Count = 0 }; $feed = @{ Given = $false }; $ticks = @{ Count = 0 } +$d = Invoke-PkProcessDispatch -MaxConcurrent 3 -AbortTimeoutSeconds 5 ` + -GroupProvider { if ($feed.Given) { return $null }; $feed.Given = $true; return 'g' }.GetNewClosure() ` + -JobBuilder { param($g) return @(1..6 | ForEach-Object { @{ FilePath = $cmdExe; Arguments = '/c exit 0' } }) }.GetNewClosure() ` + -JobStarter { param($job) $starts.Count++; Start-PkProcess -FilePath $job['FilePath'] -Arguments $job['Arguments'] }.GetNewClosure() ` + -JobFinalize { param($job, $pending) $null = Complete-PkProcess -Job $job } ` + -PollCallback { param($running) $ticks.Count++; if ($ticks.Count -eq 1) { Request-PkAbort } }.GetNewClosure() +Test-Assert ($d.Aborted -and $starts.Count -eq 0) ("dispatch: a -PollCallback that requests an abort starts nothing more on that pass (started " + $starts.Count + " of 6)") + +Reset-Harness +$late = @{ Groups = 0; Aborting = $false; LateBuilds = 0 } +$d = Invoke-PkProcessDispatch -MaxConcurrent 1 -MaxQueueAhead 1 -AbortTimeoutSeconds 5 ` + -GroupProvider { if ($late.Groups -ge 5) { return $null }; $late.Groups++; return $late.Groups }.GetNewClosure() ` + -JobBuilder { param($g) if ($late.Aborting) { $late.LateBuilds++ }; return @(@{ FilePath = $cmdExe; Arguments = '/c exit 0' }) }.GetNewClosure() ` + -JobFinalize { param($job, $pending) $null = Complete-PkProcess -Job $job; if (-not $late.Aborting) { $late.Aborting = $true; Request-PkAbort } }.GetNewClosure() +Test-Assert ($d.Aborted -and $late.Groups -eq 1 -and $late.LateBuilds -eq 0) ("dispatch: a -JobFinalize that requests an abort gets no more groups from -GroupProvider (asked for " + $late.Groups + " group(s), " + $late.LateBuilds + " built after the abort)") + # Your own long step inside Invoke-PkRun has to poll. Reset-Harness $own = @{ Steps = 0 } diff --git a/ParallelKit.ps1 b/ParallelKit.ps1 index 9cace24..763e8ba 100644 --- a/ParallelKit.ps1 +++ b/ParallelKit.ps1 @@ -2735,6 +2735,13 @@ function Invoke-PkProcessDispatchCore { while ((-not $pkCancelToken.IsCancellationRequested) -and ` (-not $pkProviderExhausted -or $pkActiveGroupCount -gt 0 -or $pkPending.Count -gt 0 -or $pkRunning.Count -gt 0)) { + # An abort only raises a flag; Test-PkAbortSignal is what cancels the + # token. Checked first, so an abort raised since the last pass (by + # -JobFinalize, -GroupCompleteCallback, Ctrl+C during the wait) asks + # -GroupProvider for nothing more. The flag read is cheaper than a + # function call. + if ([PkConsoleCtrl]::AbortRequested) { $null = Test-PkAbortSignal } + for ($pkH = $pkHeldGroups.Count - 1; $pkH -ge 0; $pkH--) { $pkReleased = Invoke-PkCallback -PkCallback $pkGroupReleaseCheck -PkArgs @(,$pkHeldGroups[$pkH]) -PkName '-GroupReleaseCheck' -PkContext $pkCallbackContext # Only the check's last value counts, as with -JobPollCompleted: a @@ -2802,6 +2809,8 @@ function Invoke-PkProcessDispatchCore { $pkCbDone = $false $null = do { & $pkPollCallback @($pkRunning); $pkCbDone = $true } while ($false) if (-not $pkCbDone) { Write-PkCallbackLoopWarning -PkName '-PollCallback' -PkContext $pkCallbackContext } + # And again, so an abort it raised starts nothing on this pass. + if ([PkConsoleCtrl]::AbortRequested) { $null = Test-PkAbortSignal } } while ($pkPending.Count -gt 0 -and (-not $pkCancelToken.IsCancellationRequested) -and ` @@ -3803,7 +3812,13 @@ function Invoke-PkRunspaceBatch { while ((-not $scanExhausted -or $handles.Count -gt 0) -and -not $Cts.Token.IsCancellationRequested) { - while (-not $scanExhausted -and $handles.Count -lt $MaxConcurrent -and -not $Cts.Token.IsCancellationRequested) { + # An abort only raises a flag; Test-PkAbortSignal is what cancels + # the token. Checked before launching, so an abort raised since the + # last check (before the run, or by a -ResultHandler) starts + # nothing more, and per job, for one -NextJobProvider raises. The + # flag read is cheaper than a function call. + if ([PkConsoleCtrl]::AbortRequested) { $null = Test-PkAbortSignal } + while (-not $scanExhausted -and $handles.Count -lt $MaxConcurrent -and -not $Cts.Token.IsCancellationRequested -and -not [PkConsoleCtrl]::AbortRequested) { if ($null -ne $JobParams) { if ($fixedListIndex -lt $JobParams.Count) { $nextJob = $JobParams[$fixedListIndex] From 116c0fa3bcc16213287b2a9d0429fa16b7a7a40a Mon Sep 17 00:00:00 2001 From: Hal <22532613+HalRiveria@users.noreply.github.com> Date: Wed, 2 Dec 2026 18:24:23 -0500 Subject: [PATCH 3/9] Report every batch command as aborted when an abort is in force before it starts With the dispatcher now checking for an abort before it asks for any group, a batch started while an abort is in force never handed its commands to the dispatcher, so they came back with no results. The batch now reports each one as aborted itself. The harness's aborted-group callback test raises its abort once the group is built, since one already in force means no group is asked for, and section O checks that case for the dispatcher. --- ParallelKit.Harness.ps1 | 10 ++++++++-- ParallelKit.ps1 | 7 +++++++ 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/ParallelKit.Harness.ps1 b/ParallelKit.Harness.ps1 index 1398b19..8bcbfbf 100644 --- a/ParallelKit.Harness.ps1 +++ b/ParallelKit.Harness.ps1 @@ -975,6 +975,11 @@ $results = [System.Collections.Generic.List[object]]::new() $out = Invoke-PkRunspaceBatch -MaxConcurrent 4 -JobParams (New-JobList -Jobs @(1..8 | ForEach-Object { @{ Id = $_ } })) ` -WorkerScript { param([int]$Id) return $Id } -ResultHandler { param($r) $results.Add($r) }.GetNewClosure() Test-Assert ($out.Aborted -and $results.Count -eq 0) ("runspace jobs: an abort requested before the run starts no worker (ran " + $results.Count + " of 8)") +Reset-Harness +Request-PkAbort +$asked = @{ Count = 0 } +$d = Invoke-PkProcessDispatch -MaxConcurrent 1 -GroupProvider { $asked.Count++; return $null }.GetNewClosure() -JobBuilder { param($g) } -JobFinalize { param($job, $pending) } +Test-Assert ($d.Aborted -and $asked.Count -eq 0) ("dispatch: an abort requested before the run asks -GroupProvider for nothing (asked " + $asked.Count + " times)") Reset-Harness $results = [System.Collections.Generic.List[object]]::new() @@ -1767,13 +1772,14 @@ Test-Assert $threw "a negative -TimeoutSeconds is refused" # An aborted group still gets -GroupCompleteCallback (the README warns about # this - a caller zipping a folder there must check for the abort first). +# The abort comes once the group is built: one already in force means no +# group is asked for at all. Reset-Harness -Request-PkAbort $called = @{ Count = 0; SawAbort = $false } $feed = @{ Given = $false } $d = Invoke-PkProcessDispatch -MaxConcurrent 1 ` -GroupProvider { if ($feed.Given) { return $null }; $feed.Given = $true; return 'g' }.GetNewClosure() ` - -JobBuilder { param($g) return @(@{ FilePath = $cmdExe; Arguments = '/c exit 0' }) }.GetNewClosure() ` + -JobBuilder { param($g) Request-PkAbort; return @(@{ FilePath = $cmdExe; Arguments = '/c exit 0' }) }.GetNewClosure() ` -JobFinalize { param($job, $pending) $null = Complete-PkProcess -Job $job } ` -GroupCompleteCallback { param($g) $called.Count++; $called.SawAbort = [bool](Test-PkCancelRequested) }.GetNewClosure() Test-Assert ($d.Aborted -and $called.Count -eq 1 -and $called.SawAbort) "an aborted group still gets its -GroupCompleteCallback, and Test-PkCancelRequested is true inside it" diff --git a/ParallelKit.ps1 b/ParallelKit.ps1 index 763e8ba..e03127c 100644 --- a/ParallelKit.ps1 +++ b/ParallelKit.ps1 @@ -3396,6 +3396,13 @@ function Invoke-PkProcessBatch { Write-PkMessage ("Invoke-PkProcessBatch: " + $pkFailure.More + " more " + $pkCommandWord + " couldn't start '" + $pkFailure.FilePath + "' (" + $pkFailure.Cause + ").") -Level Error } } + # An abort already in force stops the dispatcher before it asks for the + # batch's one group, so no command reached it: each was kept from starting. + if (-not $pkState.Given) { + foreach ($pkC in $pkCommands) { + if ($null -ne $pkC) { $pkResults.Add((& $pkNewBatchResult -Command $pkC -Aborted)) } + } + } return [pscustomobject][ordered]@{ Results = $pkResults; Aborted = $pkDispatch.Aborted; ForceKilledCount = $pkDispatch.ForceKilledCount } } From d18f630ef0738a06b389d5dc3e9e4d6b6da733b8 Mon Sep 17 00:00:00 2001 From: Hal <22532613+HalRiveria@users.noreply.github.com> Date: Wed, 2 Dec 2026 18:39:53 -0500 Subject: [PATCH 4/9] End what a program left running when its start is rolled back after it exited When a program's output reader couldn't start, the rollback stopped the program with Stop-PkProcessTree, which passes over a program that has already exited, so a child it left running was never stopped. The dispatcher's cleanup when a -JobStarter throws after starting a program had the same gap. Both now kill the program's tree job first, which reaches its children whether or not it is still running, and fall back to Stop-PkProcessTree only when it has none. The rollback now also releases the tree job's handle and disposes the process, as the dispatcher's cleanup already disposed it. A test hook, PkStreamReadTask.TestFailRunDelayMs, holds the failing reader start so the program has exited by then; TypesVersion is 16. Harness section AW covers the rollback on both start paths and the dispatcher's cleanup. --- ParallelKit.Harness.ps1 | 41 +++++++++++++++++++++++++++++++++++++ ParallelKit.ps1 | 28 +++++++++++++++++++------ Source/PkChildProcessJob.cs | 11 ++++++++-- Source/PkConsoleCtrl.cs | 2 +- 4 files changed, 73 insertions(+), 9 deletions(-) diff --git a/ParallelKit.Harness.ps1 b/ParallelKit.Harness.ps1 index 8bcbfbf..f26c018 100644 --- a/ParallelKit.Harness.ps1 +++ b/ParallelKit.Harness.ps1 @@ -4858,6 +4858,47 @@ foreach ($rsPath in 'CreatedInJob', 'Process.Start', 'batch') { } } +# The same once the program has exited before the rollback: what it left +# running is still ended, through its tree job (a kill of the program itself +# passes over one that has exited). TestFailRunDelayMs holds the failing Run +# until cmd.exe, which only starts the ping, is gone. +foreach ($rxPath in 'CreatedInJob', 'Process.Start') { + $rsW++ + $rxArgs = '/d /c start "" /b ping -n 30 -w ' + $rsW + ' 127.0.0.1 >nul' + $rxError = $null + [PkChildProcessJob]::TestUseProcessStart = ($rxPath -eq 'Process.Start') + [PkStreamReadTask]::TestFailRunAfter = 1 + [PkStreamReadTask]::TestFailRunDelayMs = 2000 + try { $null = Start-PkProcess -FilePath $cmdExe -Arguments $rxArgs } catch { $rxError = [string]$_ } finally { [PkStreamReadTask]::TestFailRunAfter = -1; [PkStreamReadTask]::TestFailRunDelayMs = 0; [PkChildProcessJob]::TestUseProcessStart = $false } + $rxWait = [System.Diagnostics.Stopwatch]::StartNew() + do { + $rxLeft = @(Get-CimInstance Win32_Process -Filter "Name='PING.EXE'" | Where-Object { [string]$_.CommandLine -like ('*-w ' + $rsW + ' 127.0.0.1*') }) + if ($rxLeft.Count -eq 0) { break } + Start-Sleep -Milliseconds 100 + } while ($rxWait.ElapsedMilliseconds -lt 5000) + foreach ($l in $rxLeft) { Stop-Process -Id $l.ProcessId -Force -ErrorAction SilentlyContinue } + Test-Assert ($rxError -like '*could not start*' -and $rxLeft.Count -eq 0) ("a program that has exited when its reader fails still has what it started ended, " + $rxPath + " (" + $rxLeft.Count + " left running, error: " + $rxError + ")") +} + +# And the dispatcher's own cleanup when a -JobStarter throws after starting a +# program that has since exited. +$rsW++ +$dxArgs = '/d /c start "" /b ping -n 30 -w ' + $rsW + ' 127.0.0.1 >nul' +$dxFeed = @{ Given = $false } +$dx = Invoke-PkProcessDispatch -MaxConcurrent 1 -AbortTimeoutSeconds 5 ` + -GroupProvider { if ($dxFeed.Given) { return $null }; $dxFeed.Given = $true; return 'g' }.GetNewClosure() ` + -JobBuilder { param($g) return @(@{ FilePath = $cmdExe; Arguments = $dxArgs }) }.GetNewClosure() ` + -JobStarter { param($job) $s = Start-PkProcess -FilePath $job['FilePath'] -Arguments $job['Arguments']; $job['Proc'] = $s['Proc']; $null = Wait-PkProcess -Process $s['Proc'] -TimeoutMs 10000; throw "the starter failed after starting its program" }.GetNewClosure() ` + -JobFinalize { param($job, $pending) $null = Complete-PkProcess -Job $job } +$dxWait = [System.Diagnostics.Stopwatch]::StartNew() +do { + $dxLeft = @(Get-CimInstance Win32_Process -Filter "Name='PING.EXE'" | Where-Object { [string]$_.CommandLine -like ('*-w ' + $rsW + ' 127.0.0.1*') }) + if ($dxLeft.Count -eq 0) { break } + Start-Sleep -Milliseconds 100 +} while ($dxWait.ElapsedMilliseconds -lt 5000) +foreach ($l in $dxLeft) { Stop-Process -Id $l.ProcessId -Force -ErrorAction SilentlyContinue } +Test-Assert ($dx.JobStarterFailedCount -eq 1 -and $dxLeft.Count -eq 0) ("dispatch: a -JobStarter that throws after its program exited still has what the program started ended (" + $dxLeft.Count + " left running, " + $dx.JobStarterFailedCount + " start failure(s))") + # Initialize-ParallelKit reports the kit's version and how it starts programs. $ipHeader = [regex]::Match([System.IO.File]::ReadAllText($kitSource), '(?m)^# Version (\d+\.\d+(?:\.\d+)?)\b').Groups[1].Value $ipError = $null; $ip = $null; $ipAdded = $null diff --git a/ParallelKit.ps1 b/ParallelKit.ps1 index e03127c..3783a54 100644 --- a/ParallelKit.ps1 +++ b/ParallelKit.ps1 @@ -169,7 +169,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 = 15; + public const int TypesVersion = 16; // Locked: Register-/Unregister-PkCancellationSource are callable from // worker runspaces, and List is not safe for concurrent writers. @@ -404,13 +404,20 @@ public sealed class PkStreamReadTask : Task private PkStreamReadTask(Buffer buffer) : base(new Func(buffer.Pump), TaskCreationOptions.LongRunning) { _buffer = buffer; } // Harness only: n >= 0 makes the Run after the next n throw, as one whose - // thread can't be created would; -1, the default, is off. + // thread can't be created would; -1, the default, is off. With + // TestFailRunDelayMs above 0, that Run waits that long before throwing, so + // a program that ends at once has exited by then. public static int TestFailRunAfter = -1; + public static int TestFailRunDelayMs = 0; // maxChars: 0 for no cap. public static PkStreamReadTask Run(TextReader reader, int maxChars) { - if (TestFailRunAfter >= 0 && Interlocked.Decrement(ref TestFailRunAfter) < 0) { throw new InvalidOperationException("Harness: a reader thread that can't start (TestFailRunAfter)."); } + if (TestFailRunAfter >= 0 && Interlocked.Decrement(ref TestFailRunAfter) < 0) + { + if (TestFailRunDelayMs > 0) { Thread.Sleep(TestFailRunDelayMs); } + throw new InvalidOperationException("Harness: a reader thread that can't start (TestFailRunAfter)."); + } PkStreamReadTask task = new PkStreamReadTask(new Buffer(reader, maxChars)); task.Start(TaskScheduler.Default); return task; @@ -1085,7 +1092,7 @@ public static class PkChildProcessJob # 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 15) { +if ((& { try { [PkState]::TypesVersion } catch { 0 } }) -ne 16) { 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." } @@ -1830,7 +1837,12 @@ function Start-PkProcessCore { } catch { $reason = [string]$_ if ($_.Exception -is [System.Management.Automation.MethodInvocationException] -and $null -ne $_.Exception.InnerException) { $reason = $_.Exception.InnerException.Message } - try { $null = Stop-PkProcessTree -Process $proc } catch { } # best effort: the failed start below is what's reported + # Through its tree job first: that reaches what the program started + # even if it has exited already, which Stop-PkProcessTree passes over. + # The same steps as the dispatcher's start-failure catch. + try { if (-not [PkChildProcessJob]::KillTree($proc)) { $null = Stop-PkProcessTree -Process $proc } } catch { } # best effort: the failed start below is what's reported + try { [PkChildProcessJob]::ReleaseTree($proc) } catch { } # its tree job's handle, now rather than at garbage collection; nothing to report + try { $proc.Dispose() } catch { } # the same, for the process handle # A reader whose task started ends when the pipe closes with the # program; one that didn't start is closed here. if ($null -eq $stdoutTask) { try { $stdout.Dispose() } catch { } } # closing an unread pipe: nothing to report if it fails @@ -2858,8 +2870,12 @@ function Invoke-PkProcessDispatchCore { # starter started before throwing is killed first: nothing else # tracks it. $pkStarting is cleared before the release, so the # teardown can't release the slot again. + # Through its tree job first, which reaches what the program + # started even once it has exited (Stop-PkProcessTree passes + # over that). The same steps as Start-PkProcessCore's rollback. if ($pkJob['Proc'] -is [System.Diagnostics.Process]) { - try { $null = Stop-PkProcessTree -Process $pkJob['Proc'] } catch { } # best effort; the failed start is still reported below + try { if (-not [PkChildProcessJob]::KillTree($pkJob['Proc'])) { $null = Stop-PkProcessTree -Process $pkJob['Proc'] } } catch { } # best effort; the failed start is still reported below + try { [PkChildProcessJob]::ReleaseTree($pkJob['Proc']) } catch { } # its tree job's handle, now rather than at garbage collection try { $pkJob['Proc'].Dispose() } catch { } # the failed start is reported either way } $pkStarting = $null diff --git a/Source/PkChildProcessJob.cs b/Source/PkChildProcessJob.cs index 7e2a4a8..4150445 100644 --- a/Source/PkChildProcessJob.cs +++ b/Source/PkChildProcessJob.cs @@ -162,13 +162,20 @@ public string Keep(bool snapshot) private PkStreamReadTask(Buffer buffer) : base(new Func(buffer.Pump), TaskCreationOptions.LongRunning) { _buffer = buffer; } // Harness only: n >= 0 makes the Run after the next n throw, as one whose - // thread can't be created would; -1, the default, is off. + // thread can't be created would; -1, the default, is off. With + // TestFailRunDelayMs above 0, that Run waits that long before throwing, so + // a program that ends at once has exited by then. public static int TestFailRunAfter = -1; + public static int TestFailRunDelayMs = 0; // maxChars: 0 for no cap. public static PkStreamReadTask Run(TextReader reader, int maxChars) { - if (TestFailRunAfter >= 0 && Interlocked.Decrement(ref TestFailRunAfter) < 0) { throw new InvalidOperationException("Harness: a reader thread that can't start (TestFailRunAfter)."); } + if (TestFailRunAfter >= 0 && Interlocked.Decrement(ref TestFailRunAfter) < 0) + { + if (TestFailRunDelayMs > 0) { Thread.Sleep(TestFailRunDelayMs); } + throw new InvalidOperationException("Harness: a reader thread that can't start (TestFailRunAfter)."); + } PkStreamReadTask task = new PkStreamReadTask(new Buffer(reader, maxChars)); task.Start(TaskScheduler.Default); return task; diff --git a/Source/PkConsoleCtrl.cs b/Source/PkConsoleCtrl.cs index e908bcd..912018d 100644 --- a/Source/PkConsoleCtrl.cs +++ b/Source/PkConsoleCtrl.cs @@ -125,7 +125,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 = 15; + public const int TypesVersion = 16; // Locked: Register-/Unregister-PkCancellationSource are callable from // worker runspaces, and List is not safe for concurrent writers. From e49a6bbf44683ef228665e6d7076948abaacb823 Mon Sep 17 00:00:00 2001 From: Hal <22532613+HalRiveria@users.noreply.github.com> Date: Wed, 2 Dec 2026 18:58:26 -0500 Subject: [PATCH 5/9] Warn when -KillTreeOnExit can't end what an exited program left running Once a program exits, -KillTreeOnExit ends what it left running through the program's own Job Object, and discarded the result: if Windows wouldn't end that Job Object, the leftovers kept running with no sign, showing only as a stream timeout if they held the output. There is no fallback once the program is gone (taskkill /T finds children only through their parent), so it now warns, once per session, naming the process, like the warning for a program without a Job Object of its own. A test hook, PkChildProcessJob.TestFailTerminate, makes TerminateJobObject count as refused. Harness section BJ covers the batch, the dispatcher and Invoke-PkProcessWithTimeout, and that the warning shows once. The README's -KillTreeOnExit paragraph mentions it. --- ParallelKit.Harness.ps1 | 20 ++++++++++++++++++++ ParallelKit.ps1 | 25 +++++++++++++++++-------- README.md | 2 +- Source/PkChildProcessJob.cs | 14 +++++++++----- 4 files changed, 47 insertions(+), 14 deletions(-) diff --git a/ParallelKit.Harness.ps1 b/ParallelKit.Harness.ps1 index f26c018..22ea0be 100644 --- a/ParallelKit.Harness.ps1 +++ b/ParallelKit.Harness.ps1 @@ -5969,6 +5969,26 @@ try { try { Test-HarnessKillTree 'no tree job, a second time' { Invoke-HarnessTreeBatch @{ KillTreeOnExit = $true; StreamTimeoutMs = 500 } @{} $bjHeld } -Left } finally { [PkChildProcessJob]::TestNoTreeJob = $false } Test-Assert (@($script:messages | Where-Object { $_.Message -like '*-KillTreeOnExit*' }).Count -eq 1) ("and only once per process (" + @($script:messages | Where-Object { $_.Message -like '*-KillTreeOnExit*' }).Count + " warning(s) after a second program)") + # A tree job Windows won't end (TerminateJobObject fails) leaves what the + # program started running too: one warning naming the process, once per + # process, in each engine. + $bjFailTerminate = @( + @{ Name = 'tree job not ended, batch'; Run = { Invoke-HarnessTreeBatch @{ KillTreeOnExit = $true; StreamTimeoutMs = 500 } @{} $bjHeld } } + @{ Name = 'tree job not ended, dispatcher'; Run = { Invoke-HarnessTreeDispatch @{ KillTreeOnExit = $true; StreamTimeoutMs = 500 } @{} $bjHeld } } + @{ Name = 'tree job not ended, one program'; Run = { Invoke-PkProcessWithTimeout -FilePath $cmdExe -Arguments $bjHeld -KillTreeOnExit -StreamTimeoutMs 500 } } + ) + foreach ($bjCase in $bjFailTerminate) { + Reset-Harness + [PkChildProcessJob]::TestResetJobWarnings() + [PkChildProcessJob]::TestFailTerminate = $true + try { Test-HarnessKillTree $bjCase.Name $bjCase.Run -Left } finally { [PkChildProcessJob]::TestFailTerminate = $false } + $bjWarned = @($script:messages | Where-Object { $_.Level -eq 'Warn' -and $_.Message -like '*-KillTreeOnExit*process *may still be running*' }) + Test-Assert ($script:messages.Count -eq 1 -and $bjWarned.Count -eq 1) ("and says so in one warning naming the process (" + $script:messages.Count + " message(s): " + (@($script:messages | ForEach-Object { $_.Message }) -join ' | ') + ")") + } + [PkChildProcessJob]::TestFailTerminate = $true + try { Test-HarnessKillTree 'tree job not ended, a second time' { Invoke-HarnessTreeBatch @{ KillTreeOnExit = $true; StreamTimeoutMs = 500 } @{} $bjHeld } -Left } finally { [PkChildProcessJob]::TestFailTerminate = $false } + Test-Assert (@($script:messages | Where-Object { $_.Message -like '*may still be running*' }).Count -eq 1) ("and only once per process (" + @($script:messages | Where-Object { $_.Message -like '*may still be running*' }).Count + " warning(s) after a second program)") + # A force-stop: the program has exited, but the caller's poll never says # done, so neither the poll nor Complete-PkProcess kills what it left. Reset-Harness diff --git a/ParallelKit.ps1 b/ParallelKit.ps1 index 3783a54..edf169b 100644 --- a/ParallelKit.ps1 +++ b/ParallelKit.ps1 @@ -507,9 +507,11 @@ public static class PkChildProcessJob // Harness only: start programs without a tree job, to test the taskkill // path; or have TryStart's first CreateProcess, with the tree job, count - // as refused, to test its retry without one. + // as refused, to test its retry without one. TestFailTerminate makes + // KillTree's TerminateJobObject count as refused, leaving the tree running. public static bool TestNoTreeJob = false; public static bool TestRefuseTreeJob = false; + public static bool TestFailTerminate = false; private static void AddTree(Process process, IntPtr treeJob) { @@ -528,7 +530,7 @@ public static class PkChildProcessJob try { j.DangerousAddRef(ref added); - ended = TerminateJobObject(j.DangerousGetHandle(), 1); + ended = !TestFailTerminate && TerminateJobObject(j.DangerousGetHandle(), 1); } catch (ObjectDisposedException) { return false; } // released meanwhile: taskkill instead finally { if (added) { j.DangerousRelease(); } } @@ -863,12 +865,14 @@ public static class PkChildProcessJob public static void TestResetFallbackWarning() { Interlocked.Exchange(ref _fallbackWarned, 0); } // The same, once each, for a Job Object that couldn't be set up when // first needed, for a running program Windows wouldn't add to it, and for - // -KillTreeOnExit on a program without a tree job. - private static int _initWarned = 0, _assignWarned = 0, _noTreeWarned = 0; + // -KillTreeOnExit on a program without a tree job, or whose tree job + // Windows wouldn't end. + private static int _initWarned = 0, _assignWarned = 0, _noTreeWarned = 0, _killTreeWarned = 0; public static bool ClaimInitWarning() { return Interlocked.Exchange(ref _initWarned, 1) == 0; } public static bool ClaimAssignWarning() { return Interlocked.Exchange(ref _assignWarned, 1) == 0; } public static bool ClaimNoTreeWarning() { return Interlocked.Exchange(ref _noTreeWarned, 1) == 0; } - public static void TestResetJobWarnings() { Interlocked.Exchange(ref _initWarned, 0); Interlocked.Exchange(ref _assignWarned, 0); Interlocked.Exchange(ref _noTreeWarned, 0); } + public static bool ClaimKillTreeWarning() { return Interlocked.Exchange(ref _killTreeWarned, 1) == 0; } + public static void TestResetJobWarnings() { Interlocked.Exchange(ref _initWarned, 0); Interlocked.Exchange(ref _assignWarned, 0); Interlocked.Exchange(ref _noTreeWarned, 0); Interlocked.Exchange(ref _killTreeWarned, 0); } private static StringBuilder BuildCommandLine(string fileName, string arguments) { @@ -2059,8 +2063,9 @@ function Stop-PkExitedJobTree { # running, through its tree job. Does nothing while it runs, or for a .Proc # that isn't a Process. A program without a tree job (Windows wouldn't # give it one, the kit has no Job Object, or a custom starter started it) - # can't be reached: that warns, once per process. One try only: the - # dispatcher's poll runs this every pass. + # can't be reached: that warns, once per process, and so does a tree job + # Windows won't end. One try only: the dispatcher's poll runs this every + # pass. param([hashtable]$Job) $proc = $Job['Proc'] if ($proc -isnot [System.Diagnostics.Process] -or $proc.HasExited -ne $true) { return } @@ -2071,7 +2076,11 @@ function Stop-PkExitedJobTree { } return } - $null = [PkChildProcessJob]::KillTree($proc) + # Windows refusing to end the tree job has no fallback: with the program + # gone, taskkill /T can't find its children. + if (-not [PkChildProcessJob]::KillTree($proc) -and [PkChildProcessJob]::ClaimKillTreeWarning()) { + Write-PkMessage ("[WARNING] -KillTreeOnExit couldn't stop what process " + $proc.Id + " left running: Windows wouldn't end the program's own Job Object, so anything it started may still be running. It still ends when PowerShell does. Shown once.") -Level Warn + } } function Wait-PkProcess { diff --git a/README.md b/README.md index 73fc3ec..e438a7b 100644 --- a/README.md +++ b/README.md @@ -310,7 +310,7 @@ The per-command keys go on the command itself, for example one that keeps all of `-StreamTimeoutMs` (default 15000) is how long to wait for a program's output after it exits; see `StreamTimedOut` in [Process results](#process-results). -`-KillTreeOnExit` kills whatever a program started that's still running when the program itself exits, whether or not it holds the program's output open. It's off by default, since some tools leave a build server or a daemon running on purpose. A command's own `KillTreeOnExit` key, `$true` or `$false`, overrides it either way. `Invoke-PkProcessWithTimeout` and the dispatcher take it too; `Start-PkProcess` doesn't, since it returns before there's an exit to act on. It goes through the program's own Job Object, so for a program without one (`StartMode` `NoJob`, or Windows refused it) it can't kill anything; it warns once per session instead. `StartMode` `CreatedInJob` describes how programs start, not whether each one got its own Job Object. In `AddedToJob` mode it can miss a child the program started straight away. +`-KillTreeOnExit` kills whatever a program started that's still running when the program itself exits, whether or not it holds the program's output open. It's off by default, since some tools leave a build server or a daemon running on purpose. A command's own `KillTreeOnExit` key, `$true` or `$false`, overrides it either way. `Invoke-PkProcessWithTimeout` and the dispatcher take it too; `Start-PkProcess` doesn't, since it returns before there's an exit to act on. It goes through the program's own Job Object, so for a program without one (`StartMode` `NoJob`, or Windows refused it) it can't kill anything; it warns once per session instead. If Windows won't end a program's Job Object, what it started may still be running, and that warns once per session too. `StartMode` `CreatedInJob` describes how programs start, not whether each one got its own Job Object. In `AddedToJob` mode it can miss a child the program started straight away. diff --git a/Source/PkChildProcessJob.cs b/Source/PkChildProcessJob.cs index 4150445..42ae14a 100644 --- a/Source/PkChildProcessJob.cs +++ b/Source/PkChildProcessJob.cs @@ -265,9 +265,11 @@ private sealed class TreeJob : SafeHandleZeroOrMinusOneIsInvalid // Harness only: start programs without a tree job, to test the taskkill // path; or have TryStart's first CreateProcess, with the tree job, count - // as refused, to test its retry without one. + // as refused, to test its retry without one. TestFailTerminate makes + // KillTree's TerminateJobObject count as refused, leaving the tree running. public static bool TestNoTreeJob = false; public static bool TestRefuseTreeJob = false; + public static bool TestFailTerminate = false; private static void AddTree(Process process, IntPtr treeJob) { @@ -286,7 +288,7 @@ public static bool KillTree(Process process) try { j.DangerousAddRef(ref added); - ended = TerminateJobObject(j.DangerousGetHandle(), 1); + ended = !TestFailTerminate && TerminateJobObject(j.DangerousGetHandle(), 1); } catch (ObjectDisposedException) { return false; } // released meanwhile: taskkill instead finally { if (added) { j.DangerousRelease(); } } @@ -621,12 +623,14 @@ public static string StartMode public static void TestResetFallbackWarning() { Interlocked.Exchange(ref _fallbackWarned, 0); } // The same, once each, for a Job Object that couldn't be set up when // first needed, for a running program Windows wouldn't add to it, and for - // -KillTreeOnExit on a program without a tree job. - private static int _initWarned = 0, _assignWarned = 0, _noTreeWarned = 0; + // -KillTreeOnExit on a program without a tree job, or whose tree job + // Windows wouldn't end. + private static int _initWarned = 0, _assignWarned = 0, _noTreeWarned = 0, _killTreeWarned = 0; public static bool ClaimInitWarning() { return Interlocked.Exchange(ref _initWarned, 1) == 0; } public static bool ClaimAssignWarning() { return Interlocked.Exchange(ref _assignWarned, 1) == 0; } public static bool ClaimNoTreeWarning() { return Interlocked.Exchange(ref _noTreeWarned, 1) == 0; } - public static void TestResetJobWarnings() { Interlocked.Exchange(ref _initWarned, 0); Interlocked.Exchange(ref _assignWarned, 0); Interlocked.Exchange(ref _noTreeWarned, 0); } + public static bool ClaimKillTreeWarning() { return Interlocked.Exchange(ref _killTreeWarned, 1) == 0; } + public static void TestResetJobWarnings() { Interlocked.Exchange(ref _initWarned, 0); Interlocked.Exchange(ref _assignWarned, 0); Interlocked.Exchange(ref _noTreeWarned, 0); Interlocked.Exchange(ref _killTreeWarned, 0); } private static StringBuilder BuildCommandLine(string fileName, string arguments) { From ed1510505e8054c775b8c5dc96ccff2940bc0406 Mon Sep 17 00:00:00 2001 From: Hal <22532613+HalRiveria@users.noreply.github.com> Date: Wed, 2 Dec 2026 19:14:54 -0500 Subject: [PATCH 6/9] Accept a function's own scriptblock as -WorkerScript A function's scriptblock (${function:Name}) has the function as its Ast, which has no ParamBlock, so Invoke-PkRunspaceBatch saw no parameters: a job with values was refused ("doesn't declare it"), a declared $CancelToken wasn't filled in, and mandatory parameters weren't checked up front. The worker-safety check also counted the function's own body as a nested function, so a $script: at its top level was flagged, though the same body as a { } block isn't. The parameters are now read from function f($a) or from the body's param() block, as Get-PkHandlerParamCount already does for callbacks, and the safety check treats the function's own body as the worker's top level. Harness section BC covers both function forms. --- ParallelKit.Harness.ps1 | 29 +++++++++++++++++++++++++++++ ParallelKit.ps1 | 20 +++++++++++++++++--- 2 files changed, 46 insertions(+), 3 deletions(-) diff --git a/ParallelKit.Harness.ps1 b/ParallelKit.Harness.ps1 index 22ea0be..759343d 100644 --- a/ParallelKit.Harness.ps1 +++ b/ParallelKit.Harness.ps1 @@ -5277,6 +5277,35 @@ Test-Assert ($bcOut.Errors.Count -eq 0) ("a mandatory CancelToken and Mandatory $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 function's own scriptblock (${function:Name}) works as -WorkerScript, in +# both forms, function f { param(...) } and function f(...): its parameters +# are read, CancelToken is filled in, a missing mandatory one is refused up +# front, and the function's own top level may use $script:, as a { } block's +# may. +function Get-HarnessFnWorker { param([int]$Id, $CancelToken) return ([string]$Id + ':' + ($CancelToken -is [System.Threading.CancellationToken])) } +function Get-HarnessFnWorkerInline([int]$Id, [Parameter(Mandatory)][string]$Name) { return ([string]$Id + $Name) } +$bcFnResults = [System.Collections.Generic.List[object]]::new() +$bcError = $null +try { $null = Invoke-PkRunspaceBatch -MaxConcurrent 2 -JobParams @(@{ Id = 1 }, @{ Id = 2 }) -WorkerScript ${function:Get-HarnessFnWorker} -ResultHandler { param($r) $bcFnResults.Add($r) }.GetNewClosure() } catch { $bcError = [string]$_ } +$bcFnText = (@($bcFnResults | Sort-Object) -join ',') +Test-Assert ($null -eq $bcError -and $bcFnText -eq '1:True,2:True') ("-WorkerScript `${function:Name} with a param() block: its jobs bind and CancelToken is filled in (" + $bcFnText + ", error: " + $bcError + ")") +$bcFnResults = [System.Collections.Generic.List[object]]::new() +$bcError = $null +try { $null = Invoke-PkRunspaceBatch -MaxConcurrent 2 -JobParams @(@{ Id = 1; Name = 'a' }, @{ Id = 2; Name = 'b' }) -WorkerScript ${function:Get-HarnessFnWorkerInline} -ResultHandler { param($r) $bcFnResults.Add($r) }.GetNewClosure() } catch { $bcError = [string]$_ } +$bcFnText = (@($bcFnResults | Sort-Object) -join ',') +Test-Assert ($null -eq $bcError -and $bcFnText -eq '1a,2b') ("and declared as function f(...) (" + $bcFnText + ", error: " + $bcError + ")") +$bcError = $null +try { $null = Invoke-PkRunspaceBatch -MaxConcurrent 2 -JobParams @(@{ Id = 1; Name = 'a' }, @{ Id = 2 }) -WorkerScript ${function:Get-HarnessFnWorkerInline} } catch { $bcError = [string]$_ } +Test-Assert ($bcError -match "job 1 doesn't supply 'Name'") ("and its missing mandatory parameter is refused before anything starts (" + $bcError + ")") +function Get-HarnessFnScriptVar { param($Id) $script:bcFnCount = $Id; & { $script:bcFnNested } } +function Get-HarnessFnScriptVarInline($Id) { $script:bcFnCount = $Id } +$bcFindings = Test-PkWorkerSafety -WorkerScript ${function:Get-HarnessFnScriptVar} +$bcFindings = @($bcFindings | Where-Object { $_.Rule -eq 'ScriptVariable' }) +Test-Assert ($bcFindings.Count -eq 1 -and $bcFindings[0].Text -like '*bcFnNested*') ("`${function:Name}: `$script: at the function's top level isn't flagged, in a nested block it is (" + (@($bcFindings | ForEach-Object { $_.Text }) -join ' | ') + ")") +$bcFindings = Test-PkWorkerSafety -WorkerScript ${function:Get-HarnessFnScriptVarInline} +$bcFindings = @($bcFindings | Where-Object { $_.Rule -eq 'ScriptVariable' }) +Test-Assert ($bcFindings.Count -eq 0) ("and the same for function f(...) (" + (@($bcFindings | ForEach-Object { $_.Text }) -join ' | ') + ")") + # A code page read from a CSV or config file is a string. $bcResolve = { param($e) & (Get-Module ParallelKit) { param($x) try { (Resolve-PkEncoding -Encoding $x).CodePage } catch { 'refused' } } $e } $bcCodePages = @((& $bcResolve '65001'), (& $bcResolve ' 437 '), (& $bcResolve 65001), (& $bcResolve ([long]65001))) diff --git a/ParallelKit.ps1 b/ParallelKit.ps1 index edf169b..d4d14df 100644 --- a/ParallelKit.ps1 +++ b/ParallelKit.ps1 @@ -3734,8 +3734,18 @@ function Invoke-PkRunspaceBatch { # it out. $mandatoryParams = [System.Collections.Generic.List[string]]::new() $hasParameterSets = $false - if ($null -ne $WorkerScript.Ast.ParamBlock) { - foreach ($workerParam in $WorkerScript.Ast.ParamBlock.Parameters) { + # A function's own scriptblock (${function:Name}) has the function as its + # Ast: its parameters are in function f($a) or in its body's param() + # block, as Get-PkHandlerParamCount reads them. + $workerAst = $WorkerScript.Ast + $workerParamList = $null + if ($workerAst -is [System.Management.Automation.Language.FunctionDefinitionAst]) { + if ($null -ne $workerAst.Parameters) { $workerParamList = $workerAst.Parameters } + $workerAst = $workerAst.Body + } + if ($null -eq $workerParamList -and $null -ne $workerAst.ParamBlock) { $workerParamList = $workerAst.ParamBlock.Parameters } + if ($null -ne $workerParamList) { + foreach ($workerParam in $workerParamList) { $null = $declaredParams.Add($workerParam.Name.VariablePath.UserPath) $isMandatory = $false foreach ($paramAttr in $workerParam.Attributes) { @@ -4381,7 +4391,11 @@ function Test-PkWorkerSafetyCore { # A function defined inside the worker script is in the same # position as a shared one: called from a closure, its $script: # can read as empty. - foreach ($innerFn in $ast.FindAll({ param($node) $node -is [System.Management.Automation.Language.FunctionDefinitionAst] }, $true)) { $scriptVarScopes.Add($innerFn.Body) } + # Not the worker itself when it's a function (${function:Name}): + # its body is the worker's top level. + foreach ($innerFn in $ast.FindAll({ param($node) $node -is [System.Management.Automation.Language.FunctionDefinitionAst] }, $true)) { + if (-not [object]::ReferenceEquals($innerFn, $ast)) { $scriptVarScopes.Add($innerFn.Body) } + } } else { $scriptVarScopes.Add($ast) } From 0e9204ed42b6279af54b73fa442cd464ba8a4a5b Mon Sep 17 00:00:00 2001 From: Hal <22532613+HalRiveria@users.noreply.github.com> Date: Wed, 2 Dec 2026 19:15:15 -0500 Subject: [PATCH 7/9] Note in Get-PkHandlerParamCount that the runspace engine reads worker parameters the same way --- ParallelKit.ps1 | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ParallelKit.ps1 b/ParallelKit.ps1 index d4d14df..7305e22 100644 --- a/ParallelKit.ps1 +++ b/ParallelKit.ps1 @@ -3446,7 +3446,8 @@ function Get-PkWorkerSafeFunctionName { function Get-PkHandlerParamCount { # How many parameters a callback declares, or -1 if it has no param() - # block (it takes whatever it's given, in $args). + # block (it takes whatever it's given, in $args). Invoke-PkRunspaceBatch + # reads a -WorkerScript's parameters the same way. param([Parameter(Mandatory)][scriptblock]$Callback) $ast = $Callback.Ast if ($ast -is [System.Management.Automation.Language.FunctionDefinitionAst]) { From 4126363f1bb304e3aed90b0da3c199aebc4831f5 Mon Sep 17 00:00:00 2001 From: Hal <22532613+HalRiveria@users.noreply.github.com> Date: Wed, 2 Dec 2026 19:30:05 -0500 Subject: [PATCH 8/9] Refuse an argument with a NUL character before starting the program Windows reads a command line up to its first NUL, so an argument holding one was cut off there, and every argument after it was dropped, silently: cmd /c echo beforeafter next printed only "before". It's now an error before the program starts, naming the element for a list (also from ConvertTo-PkArgumentString), and for a string -Arguments, on both start paths and in every engine; in a batch it is that command's StartError. The README's Arguments section says so. Harness section AE covers a list, a string, Start-PkProcess, the batch and ConvertTo-PkArgumentString. --- ParallelKit.Harness.ps1 | 17 +++++++++++++++++ ParallelKit.ps1 | 10 ++++++++++ README.md | 2 ++ 3 files changed, 29 insertions(+) diff --git a/ParallelKit.Harness.ps1 b/ParallelKit.Harness.ps1 index 759343d..2f00ceb 100644 --- a/ParallelKit.Harness.ps1 +++ b/ParallelKit.Harness.ps1 @@ -3149,6 +3149,23 @@ if ($compiled) { $nlBatch = (Invoke-PkProcessBatch -MaxConcurrent 1 -Commands @(@{ FilePath = $fwdBat; Arguments = @(("b" + "`r" + "c")) })).Results[0] Test-Assert ($nlError -like '*element 2*line break*' -and [string]$nlBatch.StartError -like '*line break*') ("a line break in a list element for a .cmd is refused with a clear error (" + $nlError + ")") Test-Assert ((Get-BatchArgvText @(("b" + "`n" + "c"))) -eq ("[b" + "`n" + "c]")) "and still reaches an ordinary program" + + # A NUL would end the command line there and drop the rest, later + # arguments included, for any program: refused before starting, in a list + # or a string, on each way in. + $nul = [string][char]0 + $nulList = '' + try { $null = Invoke-PkProcessWithTimeout -FilePath $argvExe -Arguments @('a', ('before' + $nul + 'after'), 'next') -TimeoutMs 10000 } catch { $nulList = [string]$_ } + $nulString = '' + try { $null = Invoke-PkProcessWithTimeout -FilePath $argvExe -Arguments ('before' + $nul + 'after next') -TimeoutMs 10000 } catch { $nulString = [string]$_ } + $nulBatch = (Invoke-PkProcessBatch -MaxConcurrent 1 -Commands @(@{ FilePath = $argvExe; Arguments = @(('before' + $nul + 'after'), 'next') }, @{ FilePath = $argvExe; Arguments = ('before' + $nul + 'after') })).Results + $nulStart = '' + try { $null = Start-PkProcess -FilePath $argvExe -Arguments ('x' + $nul) } catch { $nulStart = [string]$_ } + $nulJoin = '' + try { $null = ConvertTo-PkArgumentString @(('x' + $nul)) } catch { $nulJoin = [string]$_ } + Test-Assert ($nulList -like '*element 2*NUL*' -and $nulString -like '*NUL*' -and $nulStart -like '*NUL*') ("a NUL in an argument is refused before the program starts, in a list or a string (list: " + $nulList + "; string: " + $nulString + "; Start-PkProcess: " + $nulStart + ")") + Test-Assert ([string]$nulBatch[0].StartError -like '*NUL*' -and [string]$nulBatch[1].StartError -like '*NUL*') ("and is the command's StartError in a batch (" + $nulBatch[0].StartError + " | " + $nulBatch[1].StartError + ")") + Test-Assert ($nulJoin -like '*element 1*NUL*') ("and ConvertTo-PkArgumentString refuses it too (" + $nulJoin + ")") try { [System.IO.Directory]::Delete($injDir, $true) } catch { } # temp folder only; best effort # A string is still exactly as written. diff --git a/ParallelKit.ps1 b/ParallelKit.ps1 index 7305e22..6895836 100644 --- a/ParallelKit.ps1 +++ b/ParallelKit.ps1 @@ -1551,6 +1551,11 @@ function ConvertTo-PkArgumentStringCore { if ($ForBatchFile -and $arg.IndexOfAny([char[]]@("`r", "`n")) -ge 0) { throw ("Arguments element " + $position + " contains a line break, which can't be passed to cmd.exe or a .bat or .cmd program: cmd.exe would end the command line there and drop the rest. Pass it another way (a file, an environment variable).") } + # Windows reads a command line up to its first NUL, for any program. + # Start-PkProcessCore checks a string -Arguments the same way. + if ($arg.IndexOf([char]0) -ge 0) { + throw ("Arguments element " + $position + " contains a NUL character, which can't be passed on a command line: Windows would end the command line there and drop the rest, later arguments included. Pass it another way (a file, an environment variable).") + } # The C runtime only needs whitespace and quotes quoted. The rest are for # cmd.exe, which runs a .bat/.cmd: it acts on & | < > ^ ( ) outside # quotes and splits batch arguments at , ; Quoting them is harmless @@ -1744,6 +1749,11 @@ function Start-PkProcessCore { ) $encoding = Resolve-PkEncoding -Encoding $OutputEncoding $commandLine = Resolve-PkArgumentList -Arguments $Arguments -FilePath $FilePath + # A list with a NUL is refused element by element in + # ConvertTo-PkArgumentStringCore; this catches a string. + if ($commandLine.IndexOf([char]0) -ge 0) { + throw "Arguments contains a NUL character, which can't be passed on a command line: Windows would end the command line there and drop the rest. Pass it another way (a file, an environment variable)." + } # 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 } diff --git a/README.md b/README.md index e438a7b..ba7ac7f 100644 --- a/README.md +++ b/README.md @@ -286,6 +286,8 @@ Each command is a hashtable with `FilePath`, `Arguments` and optionally `Working Only the list form gets this quoting. A string, including one built with `ConvertTo-PkArgumentString`, is passed as written. +A NUL character in an argument, in a list or a string, is an error for any program, raised before it starts: Windows would end the command line there and drop the rest. +
From 7325fae9f6b94cf8870efc8d6738c28d298ebd05 Mon Sep 17 00:00:00 2001 From: Hal <22532613+HalRiveria@users.noreply.github.com> Date: Wed, 2 Dec 2026 18:58:26 -0500 Subject: [PATCH 9/9] Warn when -KillTreeOnExit can't end what an exited program left running Once a program exits, -KillTreeOnExit ends what it left running through the program's own Job Object, and discarded the result: if Windows wouldn't end that Job Object, the leftovers kept running with no sign, showing only as a stream timeout if they held the output. There is no fallback once the program is gone (taskkill /T finds children only through their parent), so it now warns, once per session, naming the process, like the warning for a program without a Job Object of its own. A test hook, PkChildProcessJob.TestFailTerminate, makes TerminateJobObject count as refused. Harness section BJ covers the batch, the dispatcher and Invoke-PkProcessWithTimeout, and that the warning shows once. The README's -KillTreeOnExit paragraph mentions it. --- ParallelKit.Harness.ps1 | 20 ++++++++++++++++++++ ParallelKit.ps1 | 25 +++++++++++++++++-------- README.md | 2 +- Source/PkChildProcessJob.cs | 14 +++++++++----- 4 files changed, 47 insertions(+), 14 deletions(-) diff --git a/ParallelKit.Harness.ps1 b/ParallelKit.Harness.ps1 index f26c018..22ea0be 100644 --- a/ParallelKit.Harness.ps1 +++ b/ParallelKit.Harness.ps1 @@ -5969,6 +5969,26 @@ try { try { Test-HarnessKillTree 'no tree job, a second time' { Invoke-HarnessTreeBatch @{ KillTreeOnExit = $true; StreamTimeoutMs = 500 } @{} $bjHeld } -Left } finally { [PkChildProcessJob]::TestNoTreeJob = $false } Test-Assert (@($script:messages | Where-Object { $_.Message -like '*-KillTreeOnExit*' }).Count -eq 1) ("and only once per process (" + @($script:messages | Where-Object { $_.Message -like '*-KillTreeOnExit*' }).Count + " warning(s) after a second program)") + # A tree job Windows won't end (TerminateJobObject fails) leaves what the + # program started running too: one warning naming the process, once per + # process, in each engine. + $bjFailTerminate = @( + @{ Name = 'tree job not ended, batch'; Run = { Invoke-HarnessTreeBatch @{ KillTreeOnExit = $true; StreamTimeoutMs = 500 } @{} $bjHeld } } + @{ Name = 'tree job not ended, dispatcher'; Run = { Invoke-HarnessTreeDispatch @{ KillTreeOnExit = $true; StreamTimeoutMs = 500 } @{} $bjHeld } } + @{ Name = 'tree job not ended, one program'; Run = { Invoke-PkProcessWithTimeout -FilePath $cmdExe -Arguments $bjHeld -KillTreeOnExit -StreamTimeoutMs 500 } } + ) + foreach ($bjCase in $bjFailTerminate) { + Reset-Harness + [PkChildProcessJob]::TestResetJobWarnings() + [PkChildProcessJob]::TestFailTerminate = $true + try { Test-HarnessKillTree $bjCase.Name $bjCase.Run -Left } finally { [PkChildProcessJob]::TestFailTerminate = $false } + $bjWarned = @($script:messages | Where-Object { $_.Level -eq 'Warn' -and $_.Message -like '*-KillTreeOnExit*process *may still be running*' }) + Test-Assert ($script:messages.Count -eq 1 -and $bjWarned.Count -eq 1) ("and says so in one warning naming the process (" + $script:messages.Count + " message(s): " + (@($script:messages | ForEach-Object { $_.Message }) -join ' | ') + ")") + } + [PkChildProcessJob]::TestFailTerminate = $true + try { Test-HarnessKillTree 'tree job not ended, a second time' { Invoke-HarnessTreeBatch @{ KillTreeOnExit = $true; StreamTimeoutMs = 500 } @{} $bjHeld } -Left } finally { [PkChildProcessJob]::TestFailTerminate = $false } + Test-Assert (@($script:messages | Where-Object { $_.Message -like '*may still be running*' }).Count -eq 1) ("and only once per process (" + @($script:messages | Where-Object { $_.Message -like '*may still be running*' }).Count + " warning(s) after a second program)") + # A force-stop: the program has exited, but the caller's poll never says # done, so neither the poll nor Complete-PkProcess kills what it left. Reset-Harness diff --git a/ParallelKit.ps1 b/ParallelKit.ps1 index 3783a54..edf169b 100644 --- a/ParallelKit.ps1 +++ b/ParallelKit.ps1 @@ -507,9 +507,11 @@ public static class PkChildProcessJob // Harness only: start programs without a tree job, to test the taskkill // path; or have TryStart's first CreateProcess, with the tree job, count - // as refused, to test its retry without one. + // as refused, to test its retry without one. TestFailTerminate makes + // KillTree's TerminateJobObject count as refused, leaving the tree running. public static bool TestNoTreeJob = false; public static bool TestRefuseTreeJob = false; + public static bool TestFailTerminate = false; private static void AddTree(Process process, IntPtr treeJob) { @@ -528,7 +530,7 @@ public static class PkChildProcessJob try { j.DangerousAddRef(ref added); - ended = TerminateJobObject(j.DangerousGetHandle(), 1); + ended = !TestFailTerminate && TerminateJobObject(j.DangerousGetHandle(), 1); } catch (ObjectDisposedException) { return false; } // released meanwhile: taskkill instead finally { if (added) { j.DangerousRelease(); } } @@ -863,12 +865,14 @@ public static class PkChildProcessJob public static void TestResetFallbackWarning() { Interlocked.Exchange(ref _fallbackWarned, 0); } // The same, once each, for a Job Object that couldn't be set up when // first needed, for a running program Windows wouldn't add to it, and for - // -KillTreeOnExit on a program without a tree job. - private static int _initWarned = 0, _assignWarned = 0, _noTreeWarned = 0; + // -KillTreeOnExit on a program without a tree job, or whose tree job + // Windows wouldn't end. + private static int _initWarned = 0, _assignWarned = 0, _noTreeWarned = 0, _killTreeWarned = 0; public static bool ClaimInitWarning() { return Interlocked.Exchange(ref _initWarned, 1) == 0; } public static bool ClaimAssignWarning() { return Interlocked.Exchange(ref _assignWarned, 1) == 0; } public static bool ClaimNoTreeWarning() { return Interlocked.Exchange(ref _noTreeWarned, 1) == 0; } - public static void TestResetJobWarnings() { Interlocked.Exchange(ref _initWarned, 0); Interlocked.Exchange(ref _assignWarned, 0); Interlocked.Exchange(ref _noTreeWarned, 0); } + public static bool ClaimKillTreeWarning() { return Interlocked.Exchange(ref _killTreeWarned, 1) == 0; } + public static void TestResetJobWarnings() { Interlocked.Exchange(ref _initWarned, 0); Interlocked.Exchange(ref _assignWarned, 0); Interlocked.Exchange(ref _noTreeWarned, 0); Interlocked.Exchange(ref _killTreeWarned, 0); } private static StringBuilder BuildCommandLine(string fileName, string arguments) { @@ -2059,8 +2063,9 @@ function Stop-PkExitedJobTree { # running, through its tree job. Does nothing while it runs, or for a .Proc # that isn't a Process. A program without a tree job (Windows wouldn't # give it one, the kit has no Job Object, or a custom starter started it) - # can't be reached: that warns, once per process. One try only: the - # dispatcher's poll runs this every pass. + # can't be reached: that warns, once per process, and so does a tree job + # Windows won't end. One try only: the dispatcher's poll runs this every + # pass. param([hashtable]$Job) $proc = $Job['Proc'] if ($proc -isnot [System.Diagnostics.Process] -or $proc.HasExited -ne $true) { return } @@ -2071,7 +2076,11 @@ function Stop-PkExitedJobTree { } return } - $null = [PkChildProcessJob]::KillTree($proc) + # Windows refusing to end the tree job has no fallback: with the program + # gone, taskkill /T can't find its children. + if (-not [PkChildProcessJob]::KillTree($proc) -and [PkChildProcessJob]::ClaimKillTreeWarning()) { + Write-PkMessage ("[WARNING] -KillTreeOnExit couldn't stop what process " + $proc.Id + " left running: Windows wouldn't end the program's own Job Object, so anything it started may still be running. It still ends when PowerShell does. Shown once.") -Level Warn + } } function Wait-PkProcess { diff --git a/README.md b/README.md index 73fc3ec..e438a7b 100644 --- a/README.md +++ b/README.md @@ -310,7 +310,7 @@ The per-command keys go on the command itself, for example one that keeps all of `-StreamTimeoutMs` (default 15000) is how long to wait for a program's output after it exits; see `StreamTimedOut` in [Process results](#process-results). -`-KillTreeOnExit` kills whatever a program started that's still running when the program itself exits, whether or not it holds the program's output open. It's off by default, since some tools leave a build server or a daemon running on purpose. A command's own `KillTreeOnExit` key, `$true` or `$false`, overrides it either way. `Invoke-PkProcessWithTimeout` and the dispatcher take it too; `Start-PkProcess` doesn't, since it returns before there's an exit to act on. It goes through the program's own Job Object, so for a program without one (`StartMode` `NoJob`, or Windows refused it) it can't kill anything; it warns once per session instead. `StartMode` `CreatedInJob` describes how programs start, not whether each one got its own Job Object. In `AddedToJob` mode it can miss a child the program started straight away. +`-KillTreeOnExit` kills whatever a program started that's still running when the program itself exits, whether or not it holds the program's output open. It's off by default, since some tools leave a build server or a daemon running on purpose. A command's own `KillTreeOnExit` key, `$true` or `$false`, overrides it either way. `Invoke-PkProcessWithTimeout` and the dispatcher take it too; `Start-PkProcess` doesn't, since it returns before there's an exit to act on. It goes through the program's own Job Object, so for a program without one (`StartMode` `NoJob`, or Windows refused it) it can't kill anything; it warns once per session instead. If Windows won't end a program's Job Object, what it started may still be running, and that warns once per session too. `StartMode` `CreatedInJob` describes how programs start, not whether each one got its own Job Object. In `AddedToJob` mode it can miss a child the program started straight away.
diff --git a/Source/PkChildProcessJob.cs b/Source/PkChildProcessJob.cs index 4150445..42ae14a 100644 --- a/Source/PkChildProcessJob.cs +++ b/Source/PkChildProcessJob.cs @@ -265,9 +265,11 @@ private sealed class TreeJob : SafeHandleZeroOrMinusOneIsInvalid // Harness only: start programs without a tree job, to test the taskkill // path; or have TryStart's first CreateProcess, with the tree job, count - // as refused, to test its retry without one. + // as refused, to test its retry without one. TestFailTerminate makes + // KillTree's TerminateJobObject count as refused, leaving the tree running. public static bool TestNoTreeJob = false; public static bool TestRefuseTreeJob = false; + public static bool TestFailTerminate = false; private static void AddTree(Process process, IntPtr treeJob) { @@ -286,7 +288,7 @@ public static bool KillTree(Process process) try { j.DangerousAddRef(ref added); - ended = TerminateJobObject(j.DangerousGetHandle(), 1); + ended = !TestFailTerminate && TerminateJobObject(j.DangerousGetHandle(), 1); } catch (ObjectDisposedException) { return false; } // released meanwhile: taskkill instead finally { if (added) { j.DangerousRelease(); } } @@ -621,12 +623,14 @@ public static string StartMode public static void TestResetFallbackWarning() { Interlocked.Exchange(ref _fallbackWarned, 0); } // The same, once each, for a Job Object that couldn't be set up when // first needed, for a running program Windows wouldn't add to it, and for - // -KillTreeOnExit on a program without a tree job. - private static int _initWarned = 0, _assignWarned = 0, _noTreeWarned = 0; + // -KillTreeOnExit on a program without a tree job, or whose tree job + // Windows wouldn't end. + private static int _initWarned = 0, _assignWarned = 0, _noTreeWarned = 0, _killTreeWarned = 0; public static bool ClaimInitWarning() { return Interlocked.Exchange(ref _initWarned, 1) == 0; } public static bool ClaimAssignWarning() { return Interlocked.Exchange(ref _assignWarned, 1) == 0; } public static bool ClaimNoTreeWarning() { return Interlocked.Exchange(ref _noTreeWarned, 1) == 0; } - public static void TestResetJobWarnings() { Interlocked.Exchange(ref _initWarned, 0); Interlocked.Exchange(ref _assignWarned, 0); Interlocked.Exchange(ref _noTreeWarned, 0); } + public static bool ClaimKillTreeWarning() { return Interlocked.Exchange(ref _killTreeWarned, 1) == 0; } + public static void TestResetJobWarnings() { Interlocked.Exchange(ref _initWarned, 0); Interlocked.Exchange(ref _assignWarned, 0); Interlocked.Exchange(ref _noTreeWarned, 0); Interlocked.Exchange(ref _killTreeWarned, 0); } private static StringBuilder BuildCommandLine(string fileName, string arguments) {