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/2] 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/2] 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.") } }