From a37fa529a00df6438ecd9bcd61bde1dfcf4bbb6d Mon Sep 17 00:00:00 2001 From: HalRiveria-Bot <348968843+HalRiveria-Bot@users.noreply.github.com> Date: Thu, 3 Dec 2026 17:52:47 -0500 Subject: [PATCH 1/3] Warn when a killed program with no tree job of its own may have left something running --- ParallelKit.Harness.ps1 | 29 +++++++++++++++++++++------ ParallelKit.ps1 | 44 +++++++++++++++++++++++++++-------------- README.md | 2 +- 3 files changed, 53 insertions(+), 22 deletions(-) diff --git a/ParallelKit.Harness.ps1 b/ParallelKit.Harness.ps1 index 8084a86..dd688ee 100644 --- a/ParallelKit.Harness.ps1 +++ b/ParallelKit.Harness.ps1 @@ -4990,6 +4990,19 @@ foreach ($rxCase in @(@{ Hook = 'TestFailTerminate'; Says = "*Windows wouldn't e 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 + ")") } +# The same with the program still running: taskkill /T kills it but misses a +# child whose parent has exited (a .cmd that starts the ping and exits). +$rsW++ +$rxCmd = Join-Path $env:TEMP ('pk-harness-aw-' + $PID + '.cmd') +[System.IO.File]::WriteAllText($rxCmd, "@start `"`" /b ping -n 30 -w " + $rsW + " 127.0.0.1 >nul`r`n") +$rxError = $null +[PkChildProcessJob]::TestNoTreeJob = $true +[PkStreamReadTask]::TestFailRunAfter = 1 +[PkStreamReadTask]::TestFailRunDelayMs = 1500 +try { $null = Start-PkProcess -FilePath $cmdExe -Arguments ('/d /c start "" /b cmd /d /c "' + $rxCmd + '" & ping -n 30 127.0.0.1 >nul') } catch { $rxError = [string]$_ } finally { [PkStreamReadTask]::TestFailRunAfter = -1; [PkStreamReadTask]::TestFailRunDelayMs = 0; [PkChildProcessJob]::TestNoTreeJob = $false; Remove-Item -LiteralPath $rxCmd -ErrorAction SilentlyContinue } +$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 '*was stopped, but it has no Job Object of its own, so what it started may still be running*' -and $rxLeft.Count -eq 1) ("a failed start that kills a program with no tree job says what may still be running (" + $rxLeft.Count + " left running, error: " + $rxError + ")") Reset-Harness $rsW++ $dxArgs = '/d /c start "" /b ping -n 30 -w ' + $rsW + ' 127.0.0.1 >nul' @@ -6182,8 +6195,9 @@ try { Test-Assert ($bjOk -and $bjLeft.Count -eq 0 -and $bjTreeWarn.Count -eq 0) ($bjCase.Name + " with -KillTreeOnExit kills the program and doesn't warn about its tree (as expected: " + $bjOk + ", pings left " + $bjLeft.Count + ", " + $bjTreeWarn.Count + " warning(s): " + (@($bjTreeWarn | ForEach-Object { $_.Message }) -join ' | ') + ")") } - # A kill whose tree job Windows won't end (TestFailTerminate) misses a child -# whose parent exited, and warns once; otherwise nothing is left. + # A kill whose tree job Windows won't end (TestFailTerminate), or of a + # program with none (TestNoTreeJob, TestRefuseTreeJob), misses a child whose + # parent exited, and warns once; otherwise nothing is left. $bjOrphanCmd = Join-Path $env:TEMP ('pk-harness-bj-' + $PID + '.cmd') [System.IO.File]::WriteAllText($bjOrphanCmd, "@start `"`" /b ping -n 30 -w 4330 127.0.0.1 >nul`r`n") $bjOrphan = '/d /c start "" /b cmd /d /c "' + $bjOrphanCmd + '" & ping -n 30 127.0.0.1 >nul' @@ -6194,17 +6208,20 @@ try { ) try { foreach ($bjCase in $bjOrphanCases) { - foreach ($bjRefuse in $false, $true) { + foreach ($bjHook in '', 'TestFailTerminate', 'TestNoTreeJob', 'TestRefuseTreeJob') { Reset-Harness [PkChildProcessJob]::TestResetJobWarnings() - [PkChildProcessJob]::TestFailTerminate = $bjRefuse - try { $null = & $bjCase.Run } finally { [PkChildProcessJob]::TestFailTerminate = $false; Reset-PkAbortState } + if ($bjHook) { [PkChildProcessJob]::$bjHook = $true } + try { $null = & $bjCase.Run } finally { [PkChildProcessJob]::TestFailTerminate = $false; [PkChildProcessJob]::TestNoTreeJob = $false; [PkChildProcessJob]::TestRefuseTreeJob = $false; Reset-PkAbortState } Start-Sleep -Milliseconds 500 $bjLeft = @(Get-CimInstance Win32_Process -Filter "Name='PING.EXE' AND CommandLine LIKE '%-w 4330 %'") foreach ($p in $bjLeft) { Stop-Process -Id $p.ProcessId -Force -ErrorAction SilentlyContinue } $bjWarn = @($script:messages | Where-Object { $_.Level -eq 'Warn' -and $_.Message -like "*Killing process * may have left what it started running*" }) - if ($bjRefuse) { + if ($bjHook -eq 'TestFailTerminate') { Test-Assert ($bjLeft.Count -eq 1 -and $bjWarn.Count -eq 1) ($bjCase.Name + " whose tree job Windows won't end says what may still be running, once (pings left " + $bjLeft.Count + ", " + $bjWarn.Count + " warning(s))") + } elseif ($bjHook) { + $bjNoTree = @($bjWarn | Where-Object { $_.Message -like '*has no Job Object of its own*' }) + Test-Assert ($bjLeft.Count -eq 1 -and $bjWarn.Count -eq 1 -and $bjNoTree.Count -eq 1) ($bjCase.Name + " of a program with no tree job (" + $bjHook + ") says what may still be running, once (pings left " + $bjLeft.Count + ", " + $bjWarn.Count + " warning(s): " + (@($bjWarn | ForEach-Object { $_.Message }) -join ' | ') + ")") } else { Test-Assert ($bjLeft.Count -eq 0 -and $bjWarn.Count -eq 0) ($bjCase.Name + " ends a child whose parent has exited, through the tree job (pings left " + $bjLeft.Count + ", " + $bjWarn.Count + " warning(s))") } diff --git a/ParallelKit.ps1 b/ParallelKit.ps1 index 1043eee..4bb4a6d 100644 --- a/ParallelKit.ps1 +++ b/ParallelKit.ps1 @@ -1996,9 +1996,13 @@ function Stop-PkJobProcess { $running = @(foreach ($p in $procs) { if ($p.HasExited -eq $false) { $p } }) try { $null = Stop-PkProcessTree -Process @($procs) } catch { } # best effort; each job is still waited on and disposed after # Each killed program's tree job again, as Stop-PkProgramTree does after a - # kill: a second KillTree fails only if Windows won't end it. + # kill: a second KillTree fails only if Windows won't end it. A program + # with no tree job was killed by taskkill /T, which can miss some. foreach ($p in $running) { - try { if ([PkChildProcessJob]::HasTree($p) -and -not [PkChildProcessJob]::KillTree($p)) { Write-PkKillTreeWarning -ProcessId $p.Id -Why $Why } } catch { } # best effort, as above + try { + if (-not [PkChildProcessJob]::HasTree($p)) { Write-PkKillTreeWarning -ProcessId $p.Id -Why $Why -NoTree } + elseif (-not [PkChildProcessJob]::KillTree($p)) { Write-PkKillTreeWarning -ProcessId $p.Id -Why $Why } + } catch { } # best effort, as above } foreach ($job in $Jobs) { if ($job['KillTree']) { try { Stop-PkExitedJobTree -Job $job } catch { } } } # best effort, as above # The kills are done: release each tree job's handle now rather than at @@ -2060,9 +2064,9 @@ function Stop-PkTimedOutJob { # attempt, not one per dispatcher pass. $Job['TimeLimit'] = 0 $stopped = Stop-PkProgramTree -Process $proc - if ($stopped -eq 'Killed' -or $stopped -eq 'Refused') { + if ($stopped -eq 'Killed' -or $stopped -eq 'Refused' -or $stopped -eq 'KilledNoTree') { $Job['TimedOut'] = $true - if ($stopped -eq 'Refused') { Write-PkKillTreeWarning -ProcessId $proc.Id -Why 'its time limit' } + if ($stopped -ne 'Killed') { Write-PkKillTreeWarning -ProcessId $proc.Id -Why 'its time limit' -NoTree:($stopped -eq 'KilledNoTree') } } 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 } @@ -2071,9 +2075,10 @@ function Stop-PkTimedOutJob { function Stop-PkProgramTree { # Ends one program (Stop-PkProcessTree), checks its tree job after a kill, # and with -Leftovers ends what an exited one left. Returns Killed, - # NotKilled, Unknown (state unreadable), Exited, or Refused / NoTree when - # what it started may still be running. The force-stop kills in one batch - # instead, and Stop-PkJobProcess repeats this post-kill check. + # NotKilled, Unknown (state unreadable), Exited, or Refused / NoTree / + # KilledNoTree when what it started may still be running. The force-stop + # kills in one batch instead, and Stop-PkJobProcess repeats this post-kill + # check. 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. @@ -2096,9 +2101,10 @@ function Stop-PkProgramTree { 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 } + # Without a tree job, taskkill /T killed the program and the children it + # could find through their parents, missing any whose parent had exited; + # one that had exited can't be reached at all. + if ($killed) { return 'KilledNoTree' } return 'NoTree' } @@ -2121,21 +2127,29 @@ function Stop-PkFailedStartTree { '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.") } + 'KilledNoTree' { return ($name + " was stopped, but it has no Job Object of its own, so what it started may still be running.") } } return '' } function Write-PkKillTreeWarning { - # A kill whose tree job Windows wouldn't end. Once per session, shared with - # -KillTreeOnExit's warning for the same refusal (Stop-PkExitedJobTree). - param([int]$ProcessId, [string]$Why) + # A kill whose tree job Windows wouldn't end, or (-NoTree) of a program + # with none. Each once per session, shared with -KillTreeOnExit's warning + # for the same cause (Stop-PkExitedJobTree). + param([int]$ProcessId, [string]$Why, [switch]$NoTree) + if ($NoTree) { + if (-not [PkChildProcessJob]::ClaimNoTreeWarning()) { return } + Write-PkMessage ("[WARNING] Killing process " + $ProcessId + " (" + $Why + ") may have left what it started running: the program has no Job Object of its own, and taskkill /T misses a child whose parent has already exited. Shown once.") -Level Warn + return + } if (-not [PkChildProcessJob]::ClaimKillTreeWarning()) { return } Write-PkMessage ("[WARNING] Killing process " + $ProcessId + " (" + $Why + ") may have left what it started running: Windows wouldn't end the program's own Job Object. It still ends when PowerShell does. Shown once.") -Level Warn } function Stop-PkExitedJobTree { # -KillTreeOnExit: once a job's program has exited, ends what it left - # running. No tree job, or one Windows won't end, warns once per session. + # running. No tree job, or one Windows won't end, warns once per session, + # shared with Write-PkKillTreeWarning's warning for the same cause. # KillTree is cleared first, so each job gets one attempt, though the # dispatcher's poll calls this every pass. param([hashtable]$Job) @@ -2422,7 +2436,7 @@ function Invoke-PkProcessWithTimeout { if (-not $exited) { $stopped = 'Killed' try { $stopped = Stop-PkProgramTree -Process $job['Proc'] } catch { } # best effort - the throw below still reports why - if ($stopped -eq 'Refused') { Write-PkKillTreeWarning -ProcessId $job['Proc'].Id -Why $(if ($remainingMs -le 0) { 'its time limit' } else { 'an abort' }) } + if ($stopped -eq 'Refused' -or $stopped -eq 'KilledNoTree') { Write-PkKillTreeWarning -ProcessId $job['Proc'].Id -Why $(if ($remainingMs -le 0) { 'its time limit' } else { 'an abort' }) -NoTree:($stopped -eq 'KilledNoTree') } # Let the reads finish (the kill closes their pipes) before the # process is disposed. Bounded. try { $null = [System.Threading.Tasks.Task]::WaitAll(@($job['StdoutTask'], $job['StderrTask']), 500) } catch { } # a read error doesn't matter: the throw below reports the kill diff --git a/README.md b/README.md index ceae9ad..0974367 100644 --- a/README.md +++ b/README.md @@ -27,7 +27,7 @@ ParallelKit uses Windows Job Objects to clean up programs and their descendants. - **`AddedToJob`.** Creating a program inside the Job Object relies on a private part of .NET. Where the kit can't do that, it starts the program and adds it to the Job Object just after, and warns once. A child the program starts in that moment can escape. If Windows refuses to add a program that's still running, the kit warns once more, naming the process: that program isn't cleaned up if PowerShell is killed. - **`NoJob`.** If Windows won't give the kit a Job Object at all, it warns (once, when the first program's start is what sets it up), and programs left running when PowerShell is killed stay running. -- **Killing a program's tree** (a time limit, an abort's force-stop, `Stop-PkProcessTree`). A program the kit started is killed through a Job Object of its own, along with everything it started. One without that job (with `NoJob`, or where Windows refused it) goes to `taskkill /T` instead, and if `taskkill` can't start, fails or hangs, only the program itself is killed. Its children then run until PowerShell exits, or past that with `NoJob`. If Windows won't end a program's own Job Object, the kill also goes to `taskkill /T`, which misses a child whose parent has already exited; the kit warns about that once per session. +- **Killing a program's tree** (a time limit, an abort's force-stop, `Stop-PkProcessTree`). A program the kit started is killed through a Job Object of its own, along with everything it started. One without that job (with `NoJob`, or where Windows refused it), or whose job Windows won't end, goes to `taskkill /T` instead, which misses a child whose parent has already exited; if `taskkill` can't start, fails or hangs, only the program itself is killed. What's missed runs until PowerShell exits, or past that with `NoJob`. A time limit or a force-stop that may have missed something warns once per session. From a8436e99d5f1578925b81df54376e643f59ccecd Mon Sep 17 00:00:00 2001 From: HalRiveria-Bot <348968843+HalRiveria-Bot@users.noreply.github.com> Date: Thu, 3 Dec 2026 17:56:17 -0500 Subject: [PATCH 2/3] Fix the review's findings: warn only for a program the kill ended, and say what a kill without a tree job can miss --- ParallelKit.Harness.ps1 | 2 +- ParallelKit.ps1 | 17 +++++++++-------- README.md | 2 +- 3 files changed, 11 insertions(+), 10 deletions(-) diff --git a/ParallelKit.Harness.ps1 b/ParallelKit.Harness.ps1 index dd688ee..fbedb6e 100644 --- a/ParallelKit.Harness.ps1 +++ b/ParallelKit.Harness.ps1 @@ -4998,7 +4998,7 @@ $rxCmd = Join-Path $env:TEMP ('pk-harness-aw-' + $PID + '.cmd') $rxError = $null [PkChildProcessJob]::TestNoTreeJob = $true [PkStreamReadTask]::TestFailRunAfter = 1 -[PkStreamReadTask]::TestFailRunDelayMs = 1500 +[PkStreamReadTask]::TestFailRunDelayMs = 3000 try { $null = Start-PkProcess -FilePath $cmdExe -Arguments ('/d /c start "" /b cmd /d /c "' + $rxCmd + '" & ping -n 30 127.0.0.1 >nul') } catch { $rxError = [string]$_ } finally { [PkStreamReadTask]::TestFailRunAfter = -1; [PkStreamReadTask]::TestFailRunDelayMs = 0; [PkChildProcessJob]::TestNoTreeJob = $false; Remove-Item -LiteralPath $rxCmd -ErrorAction SilentlyContinue } $rxLeft = Get-HarnessRollbackLeft $rsW foreach ($l in $rxLeft) { Stop-Process -Id $l.ProcessId -Force -ErrorAction SilentlyContinue } diff --git a/ParallelKit.ps1 b/ParallelKit.ps1 index 4bb4a6d..dc1f31a 100644 --- a/ParallelKit.ps1 +++ b/ParallelKit.ps1 @@ -1994,13 +1994,14 @@ function Stop-PkJobProcess { param([System.Collections.Generic.List[hashtable]]$Jobs, [string]$Why = 'a force-stop') $procs = foreach ($job in $Jobs) { if ($job['Proc'] -is [System.Diagnostics.Process]) { $job['Proc'] } } $running = @(foreach ($p in $procs) { if ($p.HasExited -eq $false) { $p } }) - try { $null = Stop-PkProcessTree -Process @($procs) } catch { } # best effort; each job is still waited on and disposed after + $killed = $false + try { $killed = Stop-PkProcessTree -Process @($procs) } catch { } # best effort; each job is still waited on and disposed after # Each killed program's tree job again, as Stop-PkProgramTree does after a - # kill: a second KillTree fails only if Windows won't end it. A program - # with no tree job was killed by taskkill /T, which can miss some. + # kill: a second KillTree fails only if Windows won't end it. A killed + # program with no tree job may have left a child whose parent had exited. foreach ($p in $running) { try { - if (-not [PkChildProcessJob]::HasTree($p)) { Write-PkKillTreeWarning -ProcessId $p.Id -Why $Why -NoTree } + if (-not [PkChildProcessJob]::HasTree($p)) { if ($killed -and $p.HasExited) { Write-PkKillTreeWarning -ProcessId $p.Id -Why $Why -NoTree } } elseif (-not [PkChildProcessJob]::KillTree($p)) { Write-PkKillTreeWarning -ProcessId $p.Id -Why $Why } } catch { } # best effort, as above } @@ -2101,9 +2102,9 @@ function Stop-PkProgramTree { if ([PkChildProcessJob]::KillTree($Process)) { return $done } return 'Refused' } - # Without a tree job, taskkill /T killed the program and the children it - # could find through their parents, missing any whose parent had exited; - # one that had exited can't be reached at all. + # Without a tree job, the kill (taskkill /T, or the program alone if + # taskkill failed) misses at least a child whose parent had exited; what a + # program that had exited left can't be reached at all. if ($killed) { return 'KilledNoTree' } return 'NoTree' } @@ -2139,7 +2140,7 @@ function Write-PkKillTreeWarning { param([int]$ProcessId, [string]$Why, [switch]$NoTree) if ($NoTree) { if (-not [PkChildProcessJob]::ClaimNoTreeWarning()) { return } - Write-PkMessage ("[WARNING] Killing process " + $ProcessId + " (" + $Why + ") may have left what it started running: the program has no Job Object of its own, and taskkill /T misses a child whose parent has already exited. Shown once.") -Level Warn + Write-PkMessage ("[WARNING] Killing process " + $ProcessId + " (" + $Why + ") may have left what it started running: the program has no Job Object of its own, so killing it can miss what it started, such as a child whose parent has already exited. Shown once.") -Level Warn return } if (-not [PkChildProcessJob]::ClaimKillTreeWarning()) { return } diff --git a/README.md b/README.md index 0974367..bb0f83f 100644 --- a/README.md +++ b/README.md @@ -312,7 +312,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. 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. +`-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. Neither warns again if a time limit or a force-stop has already warned about the same cause. `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. From 4f626982c80b4352e80d0fe9e7d314b7e7af93ad Mon Sep 17 00:00:00 2001 From: HalRiveria-Bot <348968843+HalRiveria-Bot@users.noreply.github.com> Date: Thu, 3 Dec 2026 17:56:35 -0500 Subject: [PATCH 3/3] Name the no-tree warning in Stop-PkJobProcess's header --- ParallelKit.ps1 | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/ParallelKit.ps1 b/ParallelKit.ps1 index dc1f31a..d84c1e6 100644 --- a/ParallelKit.ps1 +++ b/ParallelKit.ps1 @@ -1989,8 +1989,9 @@ function Split-PkTaskkillArgumentList { function Stop-PkJobProcess { # Kills every running job's program in one Stop-PkProcessTree call (one # taskkill at most), then ends each killed program's tree job once more and - # warns, with -Why, if Windows won't; then -KillTreeOnExit's leftovers. Used - # by the dispatcher's force-stop and Invoke-PkProcessWithTimeout's cleanup. + # warns, with -Why, if Windows won't or the program has none; then + # -KillTreeOnExit's leftovers. Used by the dispatcher's force-stop and + # Invoke-PkProcessWithTimeout's cleanup. param([System.Collections.Generic.List[hashtable]]$Jobs, [string]$Why = 'a force-stop') $procs = foreach ($job in $Jobs) { if ($job['Proc'] -is [System.Diagnostics.Process]) { $job['Proc'] } } $running = @(foreach ($p in $procs) { if ($p.HasExited -eq $false) { $p } })