From 0d7b6503d5709dcd692da5045fff547afada9bad Mon Sep 17 00:00:00 2001 From: HalRiveria-Bot <348968843+HalRiveria-Bot@users.noreply.github.com> Date: Thu, 3 Dec 2026 12:25:33 -0500 Subject: [PATCH 1/4] End a program's tree through one function, and say when a failed start leaves something running Every kill path for one program now goes through Stop-PkProgramTree: the time-limit kill, -KillTreeOnExit, Invoke-PkProcessWithTimeout's kills and a failed start's rollback. The two rollbacks (a reader that can't start, a -JobStarter that throws after starting its program) share Stop-PkFailedStartTree, and when Windows won't end the program's tree job, or an exited program has none, the start's failure now says what it started may still be running instead of that it was stopped. Invoke-PkProcessWithTimeout's cleanup uses the force-stop's steps. --- ParallelKit.Harness.ps1 | 37 +++++++++++ ParallelKit.ps1 | 134 ++++++++++++++++++++++++++++------------ 2 files changed, 130 insertions(+), 41 deletions(-) diff --git a/ParallelKit.Harness.ps1 b/ParallelKit.Harness.ps1 index da93028..9512b5e 100644 --- a/ParallelKit.Harness.ps1 +++ b/ParallelKit.Harness.ps1 @@ -5040,6 +5040,43 @@ do { 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))") +# When that can't be done, the start's failure says so, rather than that the +# program was stopped: Windows won't end the program's tree job +# (TestFailTerminate), or it has none (TestNoTreeJob). The tagged ping is +# left running then, and killed here by its tag. +function Get-HarnessRollbackLeft([int]$Tag) { + # The tagged pings still running after a moment. + Start-Sleep -Milliseconds 1000 + return ,@(Get-CimInstance Win32_Process -Filter "Name='PING.EXE'" | Where-Object { [string]$_.CommandLine -like ('*-w ' + $Tag + ' 127.0.0.1*') }) +} +foreach ($rxCase in @(@{ Hook = 'TestFailTerminate'; Says = "*Windows wouldn't end its own Job Object, so what it started may still be running*" }, @{ Hook = 'TestNoTreeJob'; Says = '*has no Job Object of its own, so what it started may still be running*' })) { + $rsW++ + $rxError = $null + [PkChildProcessJob]::($rxCase.Hook) = $true + [PkStreamReadTask]::TestFailRunAfter = 1 + [PkStreamReadTask]::TestFailRunDelayMs = 2000 + try { $null = Start-PkProcess -FilePath $cmdExe -Arguments ('/d /c start "" /b ping -n 30 -w ' + $rsW + ' 127.0.0.1 >nul') } catch { $rxError = [string]$_ } finally { [PkStreamReadTask]::TestFailRunAfter = -1; [PkStreamReadTask]::TestFailRunDelayMs = 0; [PkChildProcessJob]::($rxCase.Hook) = $false } + $rxLeft = Get-HarnessRollbackLeft $rsW + foreach ($l in $rxLeft) { Stop-Process -Id $l.ProcessId -Force -ErrorAction SilentlyContinue } + Test-Assert ($rxError -like '*could not start*' -and $rxError -like $rxCase.Says -and $rxError -notlike '*so it was stopped*' -and $rxLeft.Count -eq 1) ("a failed start whose leftovers can't be ended says so (" + $rxCase.Hook + ": " + $rxLeft.Count + " left running, error: " + $rxError + ")") +} +Reset-Harness +$rsW++ +$dxArgs = '/d /c start "" /b ping -n 30 -w ' + $rsW + ' 127.0.0.1 >nul' +$dxFeed = @{ Given = $false } +[PkChildProcessJob]::TestFailTerminate = $true +try { + $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 } +} finally { [PkChildProcessJob]::TestFailTerminate = $false } +$dxLeft = Get-HarnessRollbackLeft $rsW +foreach ($l in $dxLeft) { Stop-Process -Id $l.ProcessId -Force -ErrorAction SilentlyContinue } +$dxSaid = @($script:messages | Where-Object { $_.Level -eq 'Error' } | ForEach-Object { $_.Message }) -join ' | ' +Test-Assert ($dx.JobStarterFailedCount -eq 1 -and $dxSaid -like "*the starter failed after starting its program. Its program (process *) has ended, but Windows wouldn't end its own Job Object*" -and $dxLeft.Count -eq 1) ("dispatch: and so does a -JobStarter's (" + $dxLeft.Count + " left running, error: " + $dxSaid + ")") + # 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 da3d002..e313d28 100644 --- a/ParallelKit.ps1 +++ b/ParallelKit.ps1 @@ -1931,17 +1931,14 @@ function Start-PkProcessCore { } catch { $reason = [string]$_ if ($_.Exception -is [System.Management.Automation.MethodInvocationException] -and $null -ne $_.Exception.InnerException) { $reason = $_.Exception.InnerException.Message } - # 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 + $treeNote = Stop-PkFailedStartTree -Process $proc # 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 try { $stderr.Dispose() } catch { } # the same - throw [System.Management.Automation.RuntimeException]::new("Start-PkProcess: could not start '" + $FilePath + "': its output couldn't be read (" + $reason + "), so it was stopped.", $_.Exception) + $failure = "Start-PkProcess: could not start '" + $FilePath + "': its output couldn't be read (" + $reason + "), so it was stopped." + if ($treeNote) { $failure = "Start-PkProcess: could not start '" + $FilePath + "': its output couldn't be read (" + $reason + "). " + $treeNote } + throw [System.Management.Automation.RuntimeException]::new($failure, $_.Exception) } return @{ Proc = $proc @@ -2144,34 +2141,92 @@ function Stop-PkTimedOutJob { # own right at the deadline didn't time out. One try only: this runs every # pass, and a program that can't be killed would start a taskkill each time. $Job['TimeLimit'] = 0 - if (Stop-PkProcessTree -Process $proc) { + $stopped = Stop-PkProgramTree -Process $proc + if ($stopped -eq 'Killed') { $Job['TimedOut'] = $true - } elseif (-not $proc.HasExited) { + } elseif ($stopped -eq 'NotKilled') { Write-PkMessage ("ProcessDispatch: a job passed its time limit, but its program (process " + $proc.Id + ") couldn't be stopped. It holds its slot until it exits.") -Level Warn } } +function Stop-PkProgramTree { + # Ends one program and, with -Leftovers, what it started, and says how + # that went. Every kill path for one program goes through here: the + # time-limit kill, -KillTreeOnExit (Stop-PkExitedJobTree, which the + # force-stop and Complete-PkProcess call too) and a failed start's + # rollback (Stop-PkFailedStartTree). The force-stop kills the running + # programs in one Stop-PkProcessTree call first, for one taskkill. + # A running program goes to Stop-PkProcessTree: its tree job, else + # taskkill /T. One that has exited can only be reached through its tree + # job, since taskkill /T finds children through their parent. Returns + # Killed (it was running, and this call ended it), NotKilled (it's still + # running), Exited (it had exited), or, with -Leftovers, NoTree or Refused + # when what it started may still be running: it had exited and has no + # tree job, or Windows wouldn't end its tree job. Otherwise -Leftovers + # has ended what it started too. + param([Parameter(Mandatory)][System.Diagnostics.Process]$Process, [switch]$Leftovers) + $killed = $false + if ($Process.HasExited -eq $false) { + $killed = Stop-PkProcessTree -Process $Process + if (-not $killed -and -not $Process.HasExited) { return 'NotKilled' } + } + $done = 'Exited' + if ($killed) { $done = 'Killed' } + if (-not $Leftovers) { return $done } + # Through the tree job even after a kill: if Windows wouldn't end it, + # Stop-PkProcessTree's taskkill /T got the program but can miss what it + # started. A second KillTree ends an empty job, so it fails only then. + # Windows refusing has no fallback: taskkill /T finds children only + # through a parent that's still running. + if ([PkChildProcessJob]::HasTree($Process)) { + if ([PkChildProcessJob]::KillTree($Process)) { return $done } + return 'Refused' + } + # Without a tree job, a program taskkill /T just killed took what it + # could see with it; one that had exited can't be reached at all. + if ($killed) { return $done } + return 'NoTree' +} + +function Stop-PkFailedStartTree { + # A failed start's rollback, when the program had started: Start-PkProcessCore + # when a reader can't start, the dispatcher when a -JobStarter throws + # after starting one. Ends it and what it started, running or not, lets + # go of its tree job and process handle, and returns '' or a sentence + # for the start's failure report on what may still be running. + param([Parameter(Mandatory)][System.Diagnostics.Process]$Process) + $id = $null + $stopped = 'Exited' + try { $id = $Process.Id } catch { } # disposed by a custom starter: the sentence then names no process + try { $stopped = Stop-PkProgramTree -Process $Process -Leftovers } catch { } # best effort: the failed start is what's reported + try { [PkChildProcessJob]::ReleaseTree($Process) } catch { } # its tree job's handle, now rather than at garbage collection + try { $Process.Dispose() } catch { } # the same, for the process handle + $name = 'The program' + if ($null -ne $id) { $name = 'Its program (process ' + $id + ')' } + switch ($stopped) { + 'NotKilled' { return ($name + " couldn't be stopped and is still running.") } + 'Refused' { return ($name + " has ended, but Windows wouldn't end its own Job Object, so what it started may still be running. That ends when PowerShell does.") } + 'NoTree' { return ($name + " had ended, and it has no Job Object of its own, so what it started may still be running.") } + } + return '' +} + function Stop-PkExitedJobTree { # -KillTreeOnExit: once a job's program has exited, kills what it left - # 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, and so does a tree job - # Windows won't end. One try only: the dispatcher's poll runs this every - # pass. + # running, through Stop-PkProgramTree. 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 session, 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 } $Job['KillTree'] = $false - if (-not [PkChildProcessJob]::HasTree($proc)) { - if ([PkChildProcessJob]::ClaimNoTreeWarning()) { - Write-PkMessage ("[WARNING] -KillTreeOnExit can't stop what process " + $proc.Id + " left running: the program has no Job Object of its own (Windows refused one, the kit has no Job Object, or the kit didn't start it), so anything it started is left running. Shown once.") -Level Warn - } - return - } - # 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()) { + $stopped = Stop-PkProgramTree -Process $proc -Leftovers + if ($stopped -eq 'NoTree' -and [PkChildProcessJob]::ClaimNoTreeWarning()) { + Write-PkMessage ("[WARNING] -KillTreeOnExit can't stop what process " + $proc.Id + " left running: the program has no Job Object of its own (Windows refused one, the kit has no Job Object, or the kit didn't start it), so anything it started is left running. Shown once.") -Level Warn + } elseif ($stopped -eq 'Refused' -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 } } @@ -2453,7 +2508,7 @@ function Invoke-PkProcessWithTimeout { if (-not $exited -and -not $IgnoreAbort -and ((Test-PkAbortSignal) -or (Test-PkCancelRequested))) { $stopWhy = "was stopped because the run is being aborted"; break } } if (-not $exited) { - try { $null = Stop-PkProcessTree -Process $job['Proc'] } catch { } # best effort - the throw below still reports why + try { $null = Stop-PkProgramTree -Process $job['Proc'] } catch { } # best effort - the throw below still reports why # Let the output reads finish (the kill closes their pipes) before # the process is disposed under them. Bounded; a read error doesn't # matter here. @@ -2465,12 +2520,11 @@ function Invoke-PkProcessWithTimeout { # Still running here only when PowerShell is stopping the script # (that skips catch blocks, not finally ones): kill it before the # process object goes. Best effort, as above. - try { if (-not $job['Proc'].HasExited) { $null = Stop-PkProcessTree -Process $job['Proc'] } } catch { } - # Stopped between the program's exit and Complete-PkProcess. As above. - try { if ($job['KillTree']) { Stop-PkExitedJobTree -Job $job } } catch { } - # Its tree job's handle, when a kill (which leaves it open) came - # instead of Complete-PkProcess, which closes it. - try { [PkChildProcessJob]::ReleaseTree($job['Proc']) } catch { } # nothing to report + # The force-stop's steps: the program if it's running, with + # -KillTreeOnExit what it left if it exited before Complete-PkProcess, + # and its tree job's handle (a kill leaves it open). + $stopJobs = [System.Collections.Generic.List[hashtable]]::new(); $stopJobs.Add($job) + Stop-PkJobProcess -Jobs $stopJobs $job['Proc'].Dispose() } } @@ -2981,18 +3035,16 @@ 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 { 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 - } + $pkTreeNote = '' + if ($pkJob['Proc'] -is [System.Diagnostics.Process]) { $pkTreeNote = Stop-PkFailedStartTree -Process $pkJob['Proc'] } $pkStarting = $null if ($pkIsSharedBudget) { $null = $pkMaxConcurrent.Release() } # The batch sets this key on its own jobs: it reports start failures itself. - if (-not $pkJob['StartFailureReported']) { Write-PkMessage ($pkStartFailureText + $_) -Level Error } + if (-not $pkJob['StartFailureReported']) { + $pkFailure = $pkStartFailureText + $_ + if ($pkTreeNote) { $pkFailure = $pkFailure.TrimEnd().TrimEnd('.') + '. ' + $pkTreeNote } + Write-PkMessage $pkFailure -Level Error + } $pkDispatchResult.JobStarterFailedCount++ $pkKey = $pkJob['GroupKey'] if ($pkGroupStates.ContainsKey($pkKey)) { @@ -3543,7 +3595,7 @@ function Get-PkWorkerSafeFunctionName { return @('Write-PkMessage', 'Test-PkAbortSignal', 'Test-PkCancelRequested', 'Initialize-PkChildProcessJob', 'Stop-PkProcessTree', 'Stop-PkProcessTreeCore', 'Split-PkTaskkillArgumentList', 'Stop-PkJobProcess', 'Get-PkProcessDuration', 'Resolve-PkEncoding', 'Start-PkProcess', 'Wait-PkProcess', 'Wait-PkRunningJob', 'Complete-PkProcess', 'Invoke-PkProcessWithTimeout', 'Invoke-PkProcessDispatch', 'Invoke-PkProcessDispatchCore', 'Invoke-PkProcessBatch', - 'Register-PkCancellationSource', 'Unregister-PkCancellationSource', 'New-PkBatchResult', 'Get-PkJobOutputLimit', 'Get-PkJobSwitch', 'Stop-PkExitedJobTree', 'ConvertTo-PkArgumentString', 'Get-PkForceStopReason', 'Resolve-PkFileSystemPath', 'Add-PkDispatchGroupJob', 'Start-PkProcessCore', 'Get-PkJobTimeLimit', 'Stop-PkTimedOutJob', 'Get-PkStartFailureCause', 'Resolve-PkArgumentList', 'Invoke-PkCallback', 'Write-PkCallbackLoopWarning', 'ConvertTo-PkArgumentStringCore') + 'Register-PkCancellationSource', 'Unregister-PkCancellationSource', 'New-PkBatchResult', 'Get-PkJobOutputLimit', 'Get-PkJobSwitch', 'Stop-PkExitedJobTree', 'Stop-PkProgramTree', 'Stop-PkFailedStartTree', 'ConvertTo-PkArgumentString', 'Get-PkForceStopReason', 'Resolve-PkFileSystemPath', 'Add-PkDispatchGroupJob', 'Start-PkProcessCore', 'Get-PkJobTimeLimit', 'Stop-PkTimedOutJob', 'Get-PkStartFailureCause', 'Resolve-PkArgumentList', 'Invoke-PkCallback', 'Write-PkCallbackLoopWarning', 'ConvertTo-PkArgumentStringCore') } function Get-PkHandlerParamCount { From 77104beb27416afad888c58602ba8c3a1a160df9 Mon Sep 17 00:00:00 2001 From: HalRiveria-Bot <348968843+HalRiveria-Bot@users.noreply.github.com> Date: Thu, 3 Dec 2026 12:34:41 -0500 Subject: [PATCH 2/4] Stop-PkProgramTree: a Process whose state can't be read isn't taken as exited --- ParallelKit.ps1 | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/ParallelKit.ps1 b/ParallelKit.ps1 index e313d28..6baf2cc 100644 --- a/ParallelKit.ps1 +++ b/ParallelKit.ps1 @@ -2144,7 +2144,7 @@ function Stop-PkTimedOutJob { $stopped = Stop-PkProgramTree -Process $proc if ($stopped -eq 'Killed') { $Job['TimedOut'] = $true - } elseif ($stopped -eq 'NotKilled') { + } elseif ($stopped -eq 'NotKilled' -or $stopped -eq 'Unknown') { Write-PkMessage ("ProcessDispatch: a job passed its time limit, but its program (process " + $proc.Id + ") couldn't be stopped. It holds its slot until it exits.") -Level Warn } } @@ -2160,11 +2160,18 @@ function Stop-PkProgramTree { # taskkill /T. One that has exited can only be reached through its tree # job, since taskkill /T finds children through their parent. Returns # Killed (it was running, and this call ended it), NotKilled (it's still - # running), Exited (it had exited), or, with -Leftovers, NoTree or Refused + # running), Unknown (its state can't be read: never started, or + # disposed), Exited (it had exited), or, with -Leftovers, NoTree or Refused # when what it started may still be running: it had exited and has no # tree job, or Windows wouldn't end its tree job. Otherwise -Leftovers # has ended what it started too. param([Parameter(Mandatory)][System.Diagnostics.Process]$Process, [switch]$Leftovers) + # A Process never started, or disposed, reads $null here (no throw): it + # can't be read or killed by its handle. Its tree job still works. + if ($null -eq $Process.HasExited) { + if ($Leftovers -and [PkChildProcessJob]::KillTree($Process)) { return 'Exited' } + return 'Unknown' + } $killed = $false if ($Process.HasExited -eq $false) { $killed = Stop-PkProcessTree -Process $Process @@ -2205,6 +2212,7 @@ function Stop-PkFailedStartTree { if ($null -ne $id) { $name = 'Its program (process ' + $id + ')' } switch ($stopped) { 'NotKilled' { return ($name + " couldn't be stopped and is still running.") } + 'Unknown' { return ($name + "'s state couldn't be read (its Process object was disposed), so it and what it started may still be running.") } 'Refused' { return ($name + " has ended, but Windows wouldn't end its own Job Object, so what it started may still be running. That ends when PowerShell does.") } 'NoTree' { return ($name + " had ended, and it has no Job Object of its own, so what it started may still be running.") } } From 52dc42a25d9f7c59eac9caf9ae31dfb6cb2a38d8 Mon Sep 17 00:00:00 2001 From: HalRiveria-Bot <348968843+HalRiveria-Bot@users.noreply.github.com> Date: Thu, 3 Dec 2026 12:50:13 -0500 Subject: [PATCH 3/4] Bring drifted copies back in step Invoke-PkRunspaceBatch's -MaxConcurrent error now says what it got, as the other engines' do; every -StreamTimeoutMs default of 15000 names the other three; and the comments on Start-PkProcessCore's four job keys say they're copied in three places, not four. --- ParallelKit.ps1 | 30 +++++++++++++++++++----------- 1 file changed, 19 insertions(+), 11 deletions(-) diff --git a/ParallelKit.ps1 b/ParallelKit.ps1 index 6baf2cc..34161d5 100644 --- a/ParallelKit.ps1 +++ b/ParallelKit.ps1 @@ -1940,6 +1940,8 @@ function Start-PkProcessCore { if ($treeNote) { $failure = "Start-PkProcess: could not start '" + $FilePath + "': its output couldn't be read (" + $reason + "). " + $treeNote } throw [System.Management.Automation.RuntimeException]::new($failure, $_.Exception) } + # The dispatcher's default starter and the batch's starter copy these four + # keys onto their job: a new key goes in all three. return @{ Proc = $proc StdoutTask = $stdoutTask @@ -2362,8 +2364,9 @@ function Complete-PkProcess { param( [Parameter(Mandatory, Position = 0)] [hashtable]$Job, - # Invoke-PkProcessDispatch's and Invoke-PkProcessBatch's -StreamTimeoutMs - # default to the same 15000: keep the three in step. + # Invoke-PkProcessWithTimeout's, Invoke-PkProcessDispatch's and + # Invoke-PkProcessBatch's -StreamTimeoutMs default to the same 15000: + # keep the four in step. [int]$StreamTimeoutMs = 15000, [switch]$Dispose ) @@ -2484,6 +2487,9 @@ function Invoke-PkProcessWithTimeout { [string]$FilePath, $Arguments = "", [int]$TimeoutMs = 60000, + # Complete-PkProcess's, Invoke-PkProcessDispatch's and + # Invoke-PkProcessBatch's -StreamTimeoutMs default to the same 15000: + # keep the four in step. [int]$StreamTimeoutMs = 15000, [string]$WorkingDirectory = "", $OutputEncoding = $null, @@ -2654,8 +2660,9 @@ function Invoke-PkProcessDispatch { [int]$MaxQueueAhead = 3, [scriptblock]$GroupReleaseCheck = $null, [double]$TimeoutSeconds = 0, - # Complete-PkProcess's and Invoke-PkProcessBatch's -StreamTimeoutMs - # default to the same 15000: keep the three in step. + # Complete-PkProcess's, Invoke-PkProcessWithTimeout's and + # Invoke-PkProcessBatch's -StreamTimeoutMs default to the same 15000: + # keep the four in step. [int]$StreamTimeoutMs = 15000, [int]$MaxOutputChars = 0, [switch]$InheritStdin, @@ -2717,8 +2724,8 @@ function Invoke-PkProcessDispatch { $pkJobStarter = { param($pkJob) $pkStarted = Start-PkProcessCore -CallerState $pkCallerState -FilePath $pkJob['FilePath'] -Arguments $pkJob['Arguments'] -WorkingDirectory ([string]$pkJob['WorkingDirectory']) -OutputEncoding $pkJob['OutputEncoding'] -MaxOutputChars (Get-PkJobOutputLimit -Job $pkJob -DefaultMaxOutputChars $pkMaxOutputChars) -InheritStdin:(Get-PkJobSwitch -Job $pkJob -Key 'InheritStdin' -Default $pkInheritStdin) - # Start-PkProcessCore's four keys (it builds them in two places); the - # batch's starter copies them too: a new key goes in all four. + # Start-PkProcessCore's four keys; the batch's starter copies them + # too: a new key goes in all three. $pkJob['Proc'] = $pkStarted.Proc; $pkJob['StdoutTask'] = $pkStarted.StdoutTask; $pkJob['StderrTask'] = $pkStarted.StderrTask $pkJob['Stopwatch'] = $pkStarted.Stopwatch return $pkJob @@ -3428,8 +3435,9 @@ function Invoke-PkProcessBatch { [int]$AbortTimeoutSeconds = 60, [double]$TimeoutSeconds = 0, $OutputEncoding = $null, - # Complete-PkProcess's and Invoke-PkProcessDispatch's -StreamTimeoutMs - # default to the same 15000: keep the three in step. + # Complete-PkProcess's, Invoke-PkProcessWithTimeout's and + # Invoke-PkProcessDispatch's -StreamTimeoutMs default to the same + # 15000: keep the four in step. [int]$StreamTimeoutMs = 15000, [int]$MaxOutputChars = 0, [switch]$InheritStdin, @@ -3542,8 +3550,8 @@ function Invoke-PkProcessBatch { & $pkReportStartFailure $pkJob['Command'] $_ throw } - # Start-PkProcessCore's four keys (it builds them in two places); the - # dispatcher's default starter copies them too: a new key goes in all four. + # Start-PkProcessCore's four keys; the dispatcher's default starter + # copies them too: a new key goes in all three. $pkJob['Proc'] = $pkStarted.Proc; $pkJob['StdoutTask'] = $pkStarted.StdoutTask; $pkJob['StderrTask'] = $pkStarted.StderrTask $pkJob['Stopwatch'] = $pkStarted.Stopwatch return $pkJob @@ -3853,7 +3861,7 @@ function Invoke-PkRunspaceBatch { if ($null -ne $JobParams -and $null -ne $NextJobProvider) { throw "Invoke-PkRunspaceBatch: supply only one of -JobParams or -NextJobProvider, not both." } - if ($MaxConcurrent -lt 1) { throw "Invoke-PkRunspaceBatch: -MaxConcurrent must be at least 1." } + if ($MaxConcurrent -lt 1) { throw ("Invoke-PkRunspaceBatch: -MaxConcurrent must be at least 1 (got " + $MaxConcurrent + ").") } if ($AbortTimeoutSeconds -lt 0) { throw ("Invoke-PkRunspaceBatch: -AbortTimeoutSeconds must be 0 or more (got " + $AbortTimeoutSeconds + "). It's how long an abort waits for running workers before force-stopping them; 0 doesn't wait.") } From 0986c974c078c1ef30cb08d7f4733b9fe02afbba Mon Sep 17 00:00:00 2001 From: HalRiveria-Bot <348968843+HalRiveria-Bot@users.noreply.github.com> Date: Thu, 3 Dec 2026 12:51:17 -0500 Subject: [PATCH 4/4] Comments: drop a stale one, fix ones that point nowhere, and reflow two help lines The note on Start-PkProcessCore's result no longer says it builds it in two places; PkState's note says why it's static instead of pointing at a note the C# file doesn't have; the TypesVersion note says once per release; KillTree's notes name Stop-PkProcessTree as what falls back to taskkill; Invoke-PkProcessWithTimeout's cleanup has one comment instead of two; and a comment that cited a review finding stands on its own. --- ParallelKit.ps1 | 48 ++++++++++++++++++------------------- Source/PkChildProcessJob.cs | 4 ++-- Source/PkConsoleCtrl.cs | 10 ++++---- 3 files changed, 31 insertions(+), 31 deletions(-) diff --git a/ParallelKit.ps1 b/ParallelKit.ps1 index 34161d5..853ed78 100644 --- a/ParallelKit.ps1 +++ b/ParallelKit.ps1 @@ -159,16 +159,18 @@ public static class PkSleepBlock public static bool Unblock() { return SetThreadExecutionState(0x80000000u) != 0; } } -// Main-thread bookkeeping. Static on purpose: see the note at the top of this -// file. +// Main-thread bookkeeping. Static on purpose, not $script: variables: a +// function called from a .GetNewClosure() block can see an empty $script: +// scope. public static class PkState { public static bool AbortLatched = false; public static bool CloseAbort = false; public static object MessageHandler = null; // a PowerShell scriptblock, or null for the default - // Bump this, and the check after the type definitions, whenever any C# - // in this file changes: a session keeps the types it compiled first. + // A session keeps the types it compiled first. Bump this, and the check + // after the type definitions in ParallelKit.ps1, once in a release that + // changes any of the kit's C#. public const int TypesVersion = 16; // Locked: Register-/Unregister-PkCancellationSource are callable from @@ -524,7 +526,7 @@ public static class PkChildProcessJob } // Kills every process in the program's tree job. False if it has none, - // or Windows refused: the caller then uses taskkill. The job stays open + // or Windows refused: Stop-PkProcessTree then uses taskkill. The job stays open // until ReleaseTree (Complete-PkProcess, or the kit's own kill paths) or // garbage collection, so a second KillTree, as -KillTreeOnExit makes // after a time-limit kill or a force-stop, ends an empty job and succeeds. @@ -539,7 +541,7 @@ public static class PkChildProcessJob j.DangerousAddRef(ref added); ended = !TestFailTerminate && TerminateJobObject(j.DangerousGetHandle(), 1); } - catch (ObjectDisposedException) { return false; } // released meanwhile: taskkill instead + catch (ObjectDisposedException) { return false; } // released meanwhile: as if it had none finally { if (added) { j.DangerousRelease(); } } return ended; } @@ -1902,10 +1904,7 @@ function Start-PkProcessCore { throw [System.Management.Automation.RuntimeException]::new("Start-PkProcess: could not start '" + $FilePath + "'" + $tried + ": " + $reason, $_.Exception) } # The output is read in chunks (PkStreamReadTask), so Complete-PkProcess - # can keep what arrived when a stream times out. The two hashtables below - # have the same four keys, and the dispatcher's default starter and the - # batch's starter copy those keys onto their jobs: a new key goes in all - # four places. + # can keep what arrived when a stream times out. if ($null -ne $started) { $proc = $started.Process $stdout = $started.Stdout @@ -2204,9 +2203,9 @@ function Stop-PkFailedStartTree { # go of its tree job and process handle, and returns '' or a sentence # for the start's failure report on what may still be running. param([Parameter(Mandatory)][System.Diagnostics.Process]$Process) - $id = $null + # $null once disposed (a custom starter may have): no number then. + $id = $Process.Id $stopped = 'Exited' - try { $id = $Process.Id } catch { } # disposed by a custom starter: the sentence then names no process try { $stopped = Stop-PkProgramTree -Process $Process -Leftovers } catch { } # best effort: the failed start is what's reported try { [PkChildProcessJob]::ReleaseTree($Process) } catch { } # its tree job's handle, now rather than at garbage collection try { $Process.Dispose() } catch { } # the same, for the process handle @@ -2531,12 +2530,11 @@ function Invoke-PkProcessWithTimeout { } return Complete-PkProcess -Job $job -StreamTimeoutMs $StreamTimeoutMs } finally { - # Still running here only when PowerShell is stopping the script - # (that skips catch blocks, not finally ones): kill it before the - # process object goes. Best effort, as above. - # The force-stop's steps: the program if it's running, with - # -KillTreeOnExit what it left if it exited before Complete-PkProcess, - # and its tree job's handle (a kill leaves it open). + # The force-stop's steps, before the process object goes: the program + # if it's still running (only when PowerShell is stopping the script, + # which skips catch blocks, not finally ones), what it left if it + # exited before Complete-PkProcess with -KillTreeOnExit, and its tree + # job's handle (a kill leaves it open). $stopJobs = [System.Collections.Generic.List[hashtable]]::new(); $stopJobs.Add($job) Stop-PkJobProcess -Jobs $stopJobs $job['Proc'].Dispose() @@ -2634,8 +2632,8 @@ function Invoke-PkProcessDispatch { # When a job's program exits, kill whatever it started that's still running, # so nothing it left behind holds its output open. Only for a program Windows # gave a Job Object of its own, the normal case; for one without, it warns - # once per session. A job's own KillTreeOnExit - # key overrides it either way. The default -JobPollCompleted does it; with + # once per session. A job's own KillTreeOnExit key overrides it either + # way. The default -JobPollCompleted does it; with # your own, Complete-PkProcess does, so it needs -JobFinalize to call that. # .OUTPUTS # An object with GroupResults, Aborted, ForceKilledCount and @@ -3414,8 +3412,8 @@ function Invoke-PkProcessBatch { # When a program exits, kill whatever it started that's still running, so # nothing it left behind holds its output open. Only for a program Windows # gave a Job Object of its own, the normal case; for one without, it warns - # once per session. A command's own - # KillTreeOnExit key overrides it either way. + # once per session. A command's own KillTreeOnExit key overrides it + # either way. # .OUTPUTS # An object with Results, Aborted and ForceKilledCount. Each result has Command, # ExitCode, Stdout, Stderr, StreamTimedOut, StreamError, StartError, Aborted, @@ -3692,7 +3690,7 @@ function Receive-PkCompletedHandle { $pkCrash = $null try { try { $pkWorkerOutput = $h.PS.EndInvoke($h.Handle) } catch { $pkCrash = $_ } - # Same as Invoke-PkRunspaceBatch' main loop: its errors, then the + # Same as Invoke-PkRunspaceBatch's main loop: its errors, then the # crash, in the order they happened. Add-PkJobError -PkOutcome $Outcome -PkJob $h['Job'] -PkErrors $h.PS.Streams.Error if ($null -ne $pkCrash) { @@ -4272,8 +4270,8 @@ function Get-PkCommandKind { # by path from elsewhere can't. Remembered for the session: on 5.1 each # lookup searches all of PSModulePath (51 ms with 154 modules on it), for # every Invoke-PkRunspaceBatch call. So a module installed mid-session is - # missed until a new window, but one put on PSModulePath, as the finding - # suggests, isn't: that's part of the key. + # missed until a new window, but one added to PSModulePath isn't: that's + # part of the key. $key = $env:PSModulePath + '|' + $Fn.ModuleName $found = $false if (-not [PkState]::ModuleFound.TryGetValue($key, [ref]$found)) { diff --git a/Source/PkChildProcessJob.cs b/Source/PkChildProcessJob.cs index ee54788..ca71486 100644 --- a/Source/PkChildProcessJob.cs +++ b/Source/PkChildProcessJob.cs @@ -282,7 +282,7 @@ private static void AddTree(Process process, IntPtr treeJob) } // Kills every process in the program's tree job. False if it has none, - // or Windows refused: the caller then uses taskkill. The job stays open + // or Windows refused: Stop-PkProcessTree then uses taskkill. The job stays open // until ReleaseTree (Complete-PkProcess, or the kit's own kill paths) or // garbage collection, so a second KillTree, as -KillTreeOnExit makes // after a time-limit kill or a force-stop, ends an empty job and succeeds. @@ -297,7 +297,7 @@ public static bool KillTree(Process process) j.DangerousAddRef(ref added); ended = !TestFailTerminate && TerminateJobObject(j.DangerousGetHandle(), 1); } - catch (ObjectDisposedException) { return false; } // released meanwhile: taskkill instead + catch (ObjectDisposedException) { return false; } // released meanwhile: as if it had none finally { if (added) { j.DangerousRelease(); } } return ended; } diff --git a/Source/PkConsoleCtrl.cs b/Source/PkConsoleCtrl.cs index 912018d..a01c64c 100644 --- a/Source/PkConsoleCtrl.cs +++ b/Source/PkConsoleCtrl.cs @@ -115,16 +115,18 @@ public static class PkSleepBlock public static bool Unblock() { return SetThreadExecutionState(0x80000000u) != 0; } } -// Main-thread bookkeeping. Static on purpose: see the note at the top of this -// file. +// Main-thread bookkeeping. Static on purpose, not $script: variables: a +// function called from a .GetNewClosure() block can see an empty $script: +// scope. public static class PkState { public static bool AbortLatched = false; public static bool CloseAbort = false; public static object MessageHandler = null; // a PowerShell scriptblock, or null for the default - // Bump this, and the check after the type definitions, whenever any C# - // in this file changes: a session keeps the types it compiled first. + // A session keeps the types it compiled first. Bump this, and the check + // after the type definitions in ParallelKit.ps1, once in a release that + // changes any of the kit's C#. public const int TypesVersion = 16; // Locked: Register-/Unregister-PkCancellationSource are callable from