From 9e3e2c8f4fad11547107dd9b3ab4720edfbe729e Mon Sep 17 00:00:00 2001 From: Hal <22532613+HalRiveria@users.noreply.github.com> Date: Wed, 2 Dec 2026 20:08:14 -0500 Subject: [PATCH 1/7] README: the ConvertTo-PkArgumentString row names cmd.exe among the programs a list is quoted for --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ba7ac7f..156fa59 100644 --- a/README.md +++ b/README.md @@ -619,7 +619,7 @@ For one program at a time, outside the engines. All of these are safe in worker | Function | Use | |---|---| | `Invoke-PkProcessWithTimeout -FilePath -Arguments -TimeoutMs` | Run one program and wait, with a hard time limit (default 60s). Returns the [process result](#process-results) fields marked "all". If it overruns, or the run is aborted, the program is killed and this **throws**; called while an abort or cancel is already in force, it throws without starting the program. Add `-IgnoreAbort` for a cleanup step that must run anyway. | -| `ConvertTo-PkArgumentString @(args)` | Join a list of arguments into one correctly quoted command line. `-Arguments` / `Arguments` also take the list directly, and then also quote it for `cmd.exe` when the program is a `.bat` or `.cmd`. | +| `ConvertTo-PkArgumentString @(args)` | Join a list of arguments into one correctly quoted command line. `-Arguments` / `Arguments` also take the list directly, and then also quote it for `cmd.exe` when the program is `cmd.exe`, a `.bat` or a `.cmd`. | | `Start-PkProcess -FilePath -Arguments` | Start one hidden, with output captured in the background. Returns `@{ Proc; StdoutTask; StderrTask; Stopwatch }`; throws if it can't start. | | `Wait-PkProcess -Process -TimeoutMs` | Wait for exit with a timeout that can't overrun. Returns `$true` if it exited. | | `Complete-PkProcess -Job` | Collect exit code and output from a finished one (`-Job` is what `Start-PkProcess` returned). Same result as `Invoke-PkProcessWithTimeout`. | From 40b1f0a09ab2a7b7ff60510a0960452bc7bb1080 Mon Sep 17 00:00:00 2001 From: Hal <22532613+HalRiveria@users.noreply.github.com> Date: Wed, 2 Dec 2026 20:22:48 -0500 Subject: [PATCH 2/7] Check for an abort before each start in the dispatcher The dispatcher checks for an abort once per pass, and its start loop read only the token, which that check cancels. So a Ctrl+C landing while the loop was starting programs, or a -JobStarter that requested an abort, still filled every free slot on that pass. The start loop now also reads the abort flag before each job, ahead of the shared budget's Wait(0) so no slot is taken for a job that won't start. Harness section O covers a -JobStarter that requests an abort, with a plain limit and with a shared budget. --- ParallelKit.Harness.ps1 | 18 ++++++++++++++++++ ParallelKit.ps1 | 5 ++++- 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/ParallelKit.Harness.ps1 b/ParallelKit.Harness.ps1 index 2f00ceb..d608450 100644 --- a/ParallelKit.Harness.ps1 +++ b/ParallelKit.Harness.ps1 @@ -1005,6 +1005,24 @@ $d = Invoke-PkProcessDispatch -MaxConcurrent 3 -AbortTimeoutSeconds 5 ` -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 +$starts = @{ Count = 0 }; $feed = @{ Given = $false } +$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++; if ($starts.Count -eq 1) { Request-PkAbort }; Start-PkProcess -FilePath $job['FilePath'] -Arguments $job['Arguments'] }.GetNewClosure() ` + -JobFinalize { param($job, $pending) $null = Complete-PkProcess -Job $job } +Test-Assert ($d.Aborted -and $starts.Count -eq 1) ("dispatch: a -JobStarter that requests an abort starts nothing more after its own program (started " + $starts.Count + " of 6)") +Reset-Harness +$budget = [System.Threading.SemaphoreSlim]::new(3, 3) +$starts = @{ Count = 0 }; $feed = @{ Given = $false } +$d = Invoke-PkProcessDispatch -MaxConcurrent $budget -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++; if ($starts.Count -eq 1) { Request-PkAbort }; Start-PkProcess -FilePath $job['FilePath'] -Arguments $job['Arguments'] }.GetNewClosure() ` + -JobFinalize { param($job, $pending) $null = Complete-PkProcess -Job $job } +Test-Assert ($d.Aborted -and $starts.Count -eq 1 -and $budget.CurrentCount -eq 3) ("and on a shared budget, without taking a slot it doesn't use (started " + $starts.Count + " of 6, " + $budget.CurrentCount + " of 3 slots free after)") +$budget.Dispose() Reset-Harness $late = @{ Groups = 0; Aborting = $false; LateBuilds = 0 } diff --git a/ParallelKit.ps1 b/ParallelKit.ps1 index 6895836..2c63253 100644 --- a/ParallelKit.ps1 +++ b/ParallelKit.ps1 @@ -2844,7 +2844,10 @@ function Invoke-PkProcessDispatchCore { if ([PkConsoleCtrl]::AbortRequested) { $null = Test-PkAbortSignal } } - while ($pkPending.Count -gt 0 -and (-not $pkCancelToken.IsCancellationRequested) -and ` + # The abort flag per job too, so a Ctrl+C or a -JobStarter's abort + # starts no more on this pass; before the shared budget's Wait(0), + # which would take a slot. + while ($pkPending.Count -gt 0 -and (-not $pkCancelToken.IsCancellationRequested) -and (-not [PkConsoleCtrl]::AbortRequested) -and ` $(if ($pkIsSharedBudget) { $pkMaxConcurrent.Wait(0) } else { $pkRunning.Count -lt $pkMaxConcurrent })) { $pkJob = $pkPending.Dequeue() try { From c82dfd3693efb9b14095511bf1e8287fc7679cac Mon Sep 17 00:00:00 2001 From: Hal <22532613+HalRiveria@users.noreply.github.com> Date: Wed, 2 Dec 2026 20:36:52 -0500 Subject: [PATCH 3/7] Harness: wait for a killed tree to go before counting what's left The test that kills a live tree listed beside a disposed process counted leftover pings right after Stop-PkProcessTree returned. Ending a Job Object returns before Windows has finished tearing its processes down, so on a CI runner the ping was still listed once. It now waits up to 5 seconds for it to go, as the other kill tests do. --- ParallelKit.Harness.ps1 | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/ParallelKit.Harness.ps1 b/ParallelKit.Harness.ps1 index 2f00ceb..6e12203 100644 --- a/ParallelKit.Harness.ps1 +++ b/ParallelKit.Harness.ps1 @@ -3464,7 +3464,10 @@ while ((Get-LimitPingCount 53) -lt 1 -and $dispWait.Elapsed.TotalSeconds -lt 5) $dispThrew = $null $dispKilled = $false try { $dispKilled = Stop-PkProcessTree -Process @($dispGone.Proc, $dispLive.Proc) } catch { $dispThrew = [string]$_ } -$dispLeft = Get-LimitPingCount 53 +# Ending a Job Object returns before Windows has torn its processes down: +# give the ping a moment to go. +$dispWait = [System.Diagnostics.Stopwatch]::StartNew() +do { $dispLeft = Get-LimitPingCount 53; if ($dispLeft -eq 0) { break }; Start-Sleep -Milliseconds 100 } while ($dispWait.Elapsed.TotalSeconds -lt 5) Stop-StrayPings 53 Test-Assert ($null -eq $dispThrew -and $dispKilled -and $dispLeft -eq 0 -and $dispLive.Proc.HasExited) ("Stop-PkProcessTree kills a live tree listed beside a disposed process (" + $dispLeft + " left, returned " + $dispKilled + ", threw: " + $dispThrew + ")") try { if (-not $dispLive.Proc.HasExited) { $dispLive.Proc.Kill() } } catch { } # cleanup after a failure; already-exited is fine From e1276f4f0a103c85bee1534e42c4bc7d05ef3edd Mon Sep 17 00:00:00 2001 From: Hal <22532613+HalRiveria@users.noreply.github.com> Date: Wed, 2 Dec 2026 20:55:44 -0500 Subject: [PATCH 4/7] Keep a killed program's tree job until it's completed, so -KillTreeOnExit doesn't warn after the kit's own kill With -KillTreeOnExit, a program the kit killed (for its time limit, Invoke-PkProcessWithTimeout's limit, or an abort's force-stop) got the warning that it "has no Job Object of its own". KillTree closed the program's tree job once it had ended it, so -KillTreeOnExit, ending it again once the program had exited, found no tree job. KillTree now leaves the tree job open: a second KillTree ends an empty job and succeeds, quietly. Complete-PkProcess closes it as before, and so do the force-stop and Invoke-PkProcessWithTimeout's cleanup, which dispose a killed program without completing it. Harness section BJ covers the three kills; BF's check that a kill releases the tree job now expects the release at Complete-PkProcess, and a second KillTree to succeed. The README's Limits also says a program whose path is over 260 characters can't be started: Windows refuses it, long paths enabled or not. --- ParallelKit.Harness.ps1 | 30 +++++++++++++++++++++++++++--- ParallelKit.ps1 | 13 ++++++++++--- README.md | 1 + Source/PkChildProcessJob.cs | 7 ++++--- 4 files changed, 42 insertions(+), 9 deletions(-) diff --git a/ParallelKit.Harness.ps1 b/ParallelKit.Harness.ps1 index d31f838..856c32e 100644 --- a/ParallelKit.Harness.ps1 +++ b/ParallelKit.Harness.ps1 @@ -5605,11 +5605,17 @@ try { $bfUp = Wait-HarnessTagPings @('4325', '4326') $bfHas = [PkChildProcessJob]::TestHasTree($bfJob['Proc']) $bfKilled = Stop-PkProcessTree -Process $bfJob['Proc'] - $bfReleased = -not [PkChildProcessJob]::TestHasTree($bfJob['Proc']) + # The kill keeps the tree job, so a later KillTree on it succeeds; + # Complete-PkProcess lets go of it. + $bfKept = [PkChildProcessJob]::TestHasTree($bfJob['Proc']) Start-Sleep -Milliseconds 300 $bfOrphans = @(Get-HarnessTagPings '4325').Count; $bfOwn = @(Get-HarnessTagPings '4326').Count - Test-Assert ($bfUp -and $bfHas -and $bfKilled -and $bfReleased -and $bfJob['Proc'].HasExited -and $bfOrphans -eq 0 -and $bfOwn -eq 0) ($bfMode + ": Stop-PkProcessTree kills a child whose parent already exited, and lets go of the tree job (both pings up: " + $bfUp + ", tree job: " + $bfHas + ", released: " + $bfReleased + ", orphans left " + $bfOrphans + ", own left " + $bfOwn + ")") - $null = Complete-PkProcess -Job $bfJob -StreamTimeoutMs 0 -Dispose + $bfAgain = [PkChildProcessJob]::KillTree($bfJob['Proc']) + $null = Complete-PkProcess -Job $bfJob -StreamTimeoutMs 0 + $bfReleased = -not [PkChildProcessJob]::TestHasTree($bfJob['Proc']) + $bfExited = $bfJob['Proc'].HasExited + $bfJob['Proc'].Dispose() + Test-Assert ($bfUp -and $bfHas -and $bfKilled -and $bfKept -and $bfAgain -and $bfReleased -and $bfExited -and $bfOrphans -eq 0 -and $bfOwn -eq 0) ($bfMode + ": Stop-PkProcessTree kills a child whose parent already exited; the tree job stays until Complete-PkProcess (both pings up: " + $bfUp + ", tree job: " + $bfHas + ", kept after the kill: " + $bfKept + ", killed again: " + $bfAgain + ", released: " + $bfReleased + ", orphans left " + $bfOrphans + ", own left " + $bfOwn + ")") Stop-HarnessTagPings } @@ -6056,6 +6062,24 @@ try { 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 program the kit kills (its time limit, Invoke-PkProcessWithTimeout's + # limit, an abort's force-stop) has had its tree ended by that kill, so + # -KillTreeOnExit ending it again afterwards has nothing to warn about. + $bjKilled = @( + @{ Name = 'a time-limit kill in a batch'; Run = { $r = (Invoke-PkProcessBatch -TimeoutSeconds 1 -KillTreeOnExit -Commands @(@{ FilePath = $pingExe; Arguments = '-n 30 -w 4329 127.0.0.1' })).Results[0]; [bool]$r.TimedOut } } + @{ Name = "Invoke-PkProcessWithTimeout's limit"; Run = { $t = $false; try { $null = Invoke-PkProcessWithTimeout -FilePath $pingExe -Arguments '-n 30 -w 4329 127.0.0.1' -TimeoutMs 1000 -KillTreeOnExit } catch { $t = ([string]$_ -like '*killed*') }; $t } } + @{ Name = "an abort's force-stop"; Run = { $b = Invoke-PkProcessBatch -MaxConcurrent 2 -AbortTimeoutSeconds 1 -KillTreeOnExit -OnComplete { param($c, $r) if ($c['Key'] -eq 'quick') { Request-PkAbort } } -Commands @(@{ FilePath = $pingExe; Arguments = '-n 30 -w 4329 127.0.0.1'; Key = 'long' }, @{ FilePath = $cmdExe; Arguments = '/d /c ping -n 3 127.0.0.1 >nul'; Key = 'quick' }); Reset-PkAbortState; ($b.Aborted -and $b.ForceKilledCount -eq 1) } } + ) + foreach ($bjCase in $bjKilled) { + Reset-Harness + [PkChildProcessJob]::TestResetJobWarnings() + $bjOk = & $bjCase.Run + $bjLeft = @(Get-CimInstance Win32_Process -Filter "Name='PING.EXE' AND CommandLine LIKE '%-w 4329 %'") + foreach ($p in $bjLeft) { Stop-Process -Id $p.ProcessId -Force -ErrorAction SilentlyContinue } + $bjTreeWarn = @($script:messages | Where-Object { $_.Message -like '*-KillTreeOnExit*' }) + 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 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 2c63253..8198f3b 100644 --- a/ParallelKit.ps1 +++ b/ParallelKit.ps1 @@ -520,7 +520,10 @@ 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. + // or Windows refused: the caller 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. public static bool KillTree(Process process) { if (process == null) { return false; } @@ -534,8 +537,6 @@ public static class PkChildProcessJob } catch (ObjectDisposedException) { return false; } // released meanwhile: taskkill instead finally { if (added) { j.DangerousRelease(); } } - // The tree is gone: its job's handle can go now rather than with the Process. - if (ended) { ReleaseTree(process); } return ended; } @@ -2003,6 +2004,9 @@ function Stop-PkJobProcess { $procs = foreach ($job in $Jobs) { if ($job['Proc'] -is [System.Diagnostics.Process]) { $job['Proc'] } } try { $null = Stop-PkProcessTree -Process @($procs) } catch { } # best effort; each job is still waited on and disposed after foreach ($job in $Jobs) { if ($job['KillTree']) { try { Stop-PkExitedJobTree -Job $job } catch { } } } # best effort, as above + # The kills are done: the tree jobs' handles can go now, not at garbage + # collection (KillTree leaves them open, and these jobs aren't completed). + foreach ($job in $Jobs) { if ($job['Proc'] -is [System.Diagnostics.Process]) { try { [PkChildProcessJob]::ReleaseTree($job['Proc']) } catch { } } } # nothing to report } function Get-PkJobTimeLimit { @@ -2385,6 +2389,9 @@ function Invoke-PkProcessWithTimeout { 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 $job['Proc'].Dispose() } } diff --git a/README.md b/README.md index 156fa59..a0200bd 100644 --- a/README.md +++ b/README.md @@ -683,6 +683,7 @@ Other pieces: `Request-PkAbort` triggers the same abort from code. `Test-PkAbort - If a program can't be started inside the Job Object (`Initialize-ParallelKit`'s `StartMode` isn't `CreatedInJob`, or the one-time warning says so), then on Windows PowerShell with a UTF-8 console its stdin isn't quite empty: .NET Framework puts a byte-order mark in it. - A program's output is collected in memory and handed over when it exits; there's no live line-by-line output. A program that prints gigabytes will use that much memory, unless `-MaxOutputChars` caps what's kept. A batch keeps every result, output included, until it returns, which adds up over thousands of chatty programs. If you only need the output in `-OnComplete`, drop it there with `$result.Stdout = $null; $result.Stderr = $null` and it's freed as the batch goes. - A program can't start a child outside the kit's Job Object. One that tries (`CREATE_BREAKAWAY_FROM_JOB`) gets "access denied" from Windows, which can look like a bug in the program. The kit doesn't allow it on purpose, since that child would escape the cleanup. +- A program whose path is longer than 260 characters can't be started. Windows refuses it, even with long paths enabled and in the `\\?\` form, and so does PowerShell's own `& $exe`; the start fails with "The system cannot find the file specified". - Child-process cleanup has the gaps listed under [Process-tree cleanup limitations](#process-tree-cleanup-limitations). ## Testing diff --git a/Source/PkChildProcessJob.cs b/Source/PkChildProcessJob.cs index 42ae14a..17ea7f0 100644 --- a/Source/PkChildProcessJob.cs +++ b/Source/PkChildProcessJob.cs @@ -278,7 +278,10 @@ 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. + // or Windows refused: the caller 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. public static bool KillTree(Process process) { if (process == null) { return false; } @@ -292,8 +295,6 @@ public static bool KillTree(Process process) } catch (ObjectDisposedException) { return false; } // released meanwhile: taskkill instead finally { if (added) { j.DangerousRelease(); } } - // The tree is gone: its job's handle can go now rather than with the Process. - if (ended) { ReleaseTree(process); } return ended; } From c06e4a44aa16b593be18aa88860b29b4ffa1ebcf Mon Sep 17 00:00:00 2001 From: Hal <22532613+HalRiveria@users.noreply.github.com> Date: Wed, 2 Dec 2026 20:56:54 -0500 Subject: [PATCH 5/7] README: say only what was checked about a program path over 260 characters --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index a0200bd..b1604d0 100644 --- a/README.md +++ b/README.md @@ -683,7 +683,7 @@ Other pieces: `Request-PkAbort` triggers the same abort from code. `Test-PkAbort - If a program can't be started inside the Job Object (`Initialize-ParallelKit`'s `StartMode` isn't `CreatedInJob`, or the one-time warning says so), then on Windows PowerShell with a UTF-8 console its stdin isn't quite empty: .NET Framework puts a byte-order mark in it. - A program's output is collected in memory and handed over when it exits; there's no live line-by-line output. A program that prints gigabytes will use that much memory, unless `-MaxOutputChars` caps what's kept. A batch keeps every result, output included, until it returns, which adds up over thousands of chatty programs. If you only need the output in `-OnComplete`, drop it there with `$result.Stdout = $null; $result.Stderr = $null` and it's freed as the batch goes. - A program can't start a child outside the kit's Job Object. One that tries (`CREATE_BREAKAWAY_FROM_JOB`) gets "access denied" from Windows, which can look like a bug in the program. The kit doesn't allow it on purpose, since that child would escape the cleanup. -- A program whose path is longer than 260 characters can't be started. Windows refuses it, even with long paths enabled and in the `\\?\` form, and so does PowerShell's own `& $exe`; the start fails with "The system cannot find the file specified". +- A program whose path is longer than 260 characters can't be started, even with long paths enabled and in the `\\?\` form: Windows refuses it, and the start fails with "The filename or extension is too long" (or, for a plain path on PowerShell 7, "The system cannot find the file specified"). - Child-process cleanup has the gaps listed under [Process-tree cleanup limitations](#process-tree-cleanup-limitations). ## Testing From e7bb51001218e626685d7919c918442a1109df49 Mon Sep 17 00:00:00 2001 From: Hal <22532613+HalRiveria@users.noreply.github.com> Date: Wed, 2 Dec 2026 21:30:30 -0500 Subject: [PATCH 6/7] Harness: wait for a killed tree to go before counting what's left, in every dispatcher kill test On CI, 'a -JobFinalize that throws gets no -JobAbortCleanup for its finished job' failed under Windows PowerShell 5.1 with 1 ping left: it counted leftover pings right after the dispatcher's teardown kill, and ending a Job Object returns before Windows has torn its processes down. Five other tests count the same way. They now all use one helper, Get-LimitPingLeft, which waits up to 5 seconds for the pings to go, and still fails one that survives. --- ParallelKit.Harness.ps1 | 24 +++++++++++++++--------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/ParallelKit.Harness.ps1 b/ParallelKit.Harness.ps1 index 856c32e..ba7c4f4 100644 --- a/ParallelKit.Harness.ps1 +++ b/ParallelKit.Harness.ps1 @@ -191,6 +191,15 @@ function Invoke-LimitGroup { # The pings a test started, told apart by their -n count. function Get-LimitPing { param([int]$N) return @(Get-CimInstance Win32_Process -Filter "Name = 'PING.EXE'" | Where-Object { $_.CommandLine -like ("*-n " + $N + " 127.0.0.1*") }) } function Get-LimitPingCount { param([int]$N) return @(Get-LimitPing $N).Count } +# The pings left after a kill. Ending a Job Object returns before Windows has +# torn its processes down, so a count taken at once can still see one: wait up +# to 5 s for them to go. +function Get-LimitPingLeft { + param([int]$N) + $sw = [System.Diagnostics.Stopwatch]::StartNew() + do { $left = Get-LimitPingCount $N; if ($left -eq 0) { break }; Start-Sleep -Milliseconds 100 } while ($sw.Elapsed.TotalSeconds -lt 5) + return $left +} function Stop-StrayPings { param([int]$N) Get-LimitPing $N | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue } @@ -3412,7 +3421,7 @@ try { -JobStarter { param($job) $s = Start-PkProcess -FilePath $job['FilePath'] -Arguments $job['Arguments']; $job['Proc'] = $s.Proc; throw "starter failed after starting" } ` -JobFinalize { param($job, $q) $null = Complete-PkProcess -Job $job } } catch { Write-Host " throwing-starter run threw: $_" } -$stopLeft = Get-LimitPingCount 48 +$stopLeft = Get-LimitPingLeft 48 Stop-StrayPings 48 Test-Assert ($null -ne $stopResult -and $stopResult.JobStarterFailedCount -eq 1 -and $stopLeft -eq 0 -and $stopBudget.CurrentCount -eq 2) ("a starter that throws after starting its program doesn't leave it running (" + $stopLeft + " left, " + $stopBudget.CurrentCount + " of 2 slots free)") @@ -3441,7 +3450,7 @@ try { }.GetNewClosure() ` -JobFinalize { param($job, $q) $null = Complete-PkProcess -Job $job; if ($job['Name'] -eq 'b') { throw "finalize failed" } } } catch { $stopProblem = [string]$_ } -$stopLeft = Get-LimitPingCount 47 +$stopLeft = Get-LimitPingLeft 47 Stop-StrayPings 47 Test-Assert ($stopProblem -like '*finalize failed*' -and $stopLeft -eq 0) ("an error after a job was finalized in the same pass still kills the running ones (" + $stopLeft + " left, problem: " + $stopProblem + ")") @@ -3467,7 +3476,7 @@ try { }.GetNewClosure() ` -JobFinalize { param($job, $q) $null = Complete-PkProcess -Job $job -Dispose; throw "finalize failed after dispose" } } catch { $dispProblem = [string]$_ } -$dispLeft = Get-LimitPingCount 51 +$dispLeft = Get-LimitPingLeft 51 Stop-StrayPings 51 Test-Assert ($dispProblem -like '*finalize failed after dispose*' -and $dispLeft -eq 0) ("a -JobFinalize that disposes its process and throws still has the running jobs killed (" + $dispLeft + " of 3 left, problem: " + $dispProblem + ")") @@ -3482,10 +3491,7 @@ while ((Get-LimitPingCount 53) -lt 1 -and $dispWait.Elapsed.TotalSeconds -lt 5) $dispThrew = $null $dispKilled = $false try { $dispKilled = Stop-PkProcessTree -Process @($dispGone.Proc, $dispLive.Proc) } catch { $dispThrew = [string]$_ } -# Ending a Job Object returns before Windows has torn its processes down: -# give the ping a moment to go. -$dispWait = [System.Diagnostics.Stopwatch]::StartNew() -do { $dispLeft = Get-LimitPingCount 53; if ($dispLeft -eq 0) { break }; Start-Sleep -Milliseconds 100 } while ($dispWait.Elapsed.TotalSeconds -lt 5) +$dispLeft = Get-LimitPingLeft 53 Stop-StrayPings 53 Test-Assert ($null -eq $dispThrew -and $dispKilled -and $dispLeft -eq 0 -and $dispLive.Proc.HasExited) ("Stop-PkProcessTree kills a live tree listed beside a disposed process (" + $dispLeft + " left, returned " + $dispKilled + ", threw: " + $dispThrew + ")") try { if (-not $dispLive.Proc.HasExited) { $dispLive.Proc.Kill() } } catch { } # cleanup after a failure; already-exited is fine @@ -3513,7 +3519,7 @@ try { -JobFinalize { param($job, $q) $null = Complete-PkProcess -Job $job; throw "finalize failed" } ` -JobAbortCleanup { param($job) $fcCleaned.Add($job['Name']) }.GetNewClosure() } catch { $fcProblem = [string]$_ } -$fcLeft = Get-LimitPingCount 55 +$fcLeft = Get-LimitPingLeft 55 Stop-StrayPings 55 Test-Assert ($fcProblem -like '*finalize failed*' -and ($fcCleaned -join ',') -eq 'run' -and $fcLeft -eq 0 -and $fcBudget.CurrentCount -eq 2) ("a -JobFinalize that throws gets no -JobAbortCleanup for its finished job, only for the killed one (cleaned: " + ($fcCleaned -join ',') + ", " + $fcLeft + " left, " + $fcBudget.CurrentCount + " of 2 slots free)") @@ -3789,7 +3795,7 @@ $kwLabeled = 'unset' :kwOuter foreach ($kwI in 1..1) { $kwLabeled = Invoke-PkProcessBatch -MaxConcurrent 2 -Commands @(@{ FilePath = $cmdExe; Arguments = '/c exit 0' }, @{ FilePath = $pingExe; Arguments = '-n 35 127.0.0.1' }) -OnComplete { param($c, $r) break kwOuter } } -$kwLeft = Get-LimitPingCount 35 +$kwLeft = Get-LimitPingLeft 35 Stop-StrayPings 35 Test-Assert ($kwLabeled -eq 'unset' -and $kwLeft -eq 0) ("a labeled break out of a callback leaves the call and kills its programs (" + $kwLeft + " left)") Reset-Harness From da3b3d7a2bd869c204cd4b287abb749b167132ae Mon Sep 17 00:00:00 2001 From: Hal <22532613+HalRiveria@users.noreply.github.com> Date: Wed, 2 Dec 2026 21:45:11 -0500 Subject: [PATCH 7/7] Harness: start the tagged child a second later in AW's Process.Start reader-failure cases On the Process.Start path a program runs before the kit adds it to its Job Object, so a child it starts straight away can start outside its tree job and survive the kill, the gap the README's Limits gives for AddedToJob. Two AW tests started their tagged ping straight away on that path, and on a slow CI runner one failed with the ping left running. On that path the ping now starts about a second later, after the program is in its Job Object, and the failing reader start waits until it's up. --- ParallelKit.Harness.ps1 | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/ParallelKit.Harness.ps1 b/ParallelKit.Harness.ps1 index ba7c4f4..4d9b997 100644 --- a/ParallelKit.Harness.ps1 +++ b/ParallelKit.Harness.ps1 @@ -4883,14 +4883,21 @@ foreach ($rsPath in 'CreatedInJob', 'Process.Start', 'batch') { foreach ($rsAfter in 0, 1) { if ($rsPath -eq 'batch' -and $rsAfter -eq 0) { continue } $rsW++ + # On the Process.Start path a program runs before it's added to its Job + # Object, so a child it starts straight away can escape it (the gap the + # README's Limits gives for AddedToJob). There the tagged ping starts a + # second later, and the failing Run waits until it's up. $rsArgs = '/d /c ping -n 30 -w ' + $rsW + ' 127.0.0.1 >nul' + $rsDelayMs = 0 + if ($rsPath -eq 'Process.Start') { $rsArgs = '/d /c ping -n 2 127.0.0.1 >nul & ping -n 30 -w ' + $rsW + ' 127.0.0.1 >nul'; $rsDelayMs = 2500 } $rsError = $null [PkChildProcessJob]::TestUseProcessStart = ($rsPath -eq 'Process.Start') [PkStreamReadTask]::TestFailRunAfter = $rsAfter + [PkStreamReadTask]::TestFailRunDelayMs = $rsDelayMs try { if ($rsPath -eq 'batch') { $rsError = [string](Invoke-PkProcessBatch -Commands @(@{ FilePath = $cmdExe; Arguments = $rsArgs })).Results[0].StartError } else { $null = Start-PkProcess -FilePath $cmdExe -Arguments $rsArgs } - } catch { $rsError = [string]$_ } finally { [PkStreamReadTask]::TestFailRunAfter = -1; [PkChildProcessJob]::TestUseProcessStart = $false } + } catch { $rsError = [string]$_ } finally { [PkStreamReadTask]::TestFailRunAfter = -1; [PkStreamReadTask]::TestFailRunDelayMs = 0; [PkChildProcessJob]::TestUseProcessStart = $false } $rsWait = [System.Diagnostics.Stopwatch]::StartNew() do { $rsLeft = @(Get-CimInstance Win32_Process -Filter "Name='PING.EXE' OR Name='cmd.exe'" | Where-Object { [string]$_.CommandLine -like ('*-w ' + $rsW + ' 127.0.0.1*') }) @@ -4905,14 +4912,17 @@ 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. +# until cmd.exe, which only starts the ping, is gone. On the Process.Start path +# the ping starts a second later, as above. foreach ($rxPath in 'CreatedInJob', 'Process.Start') { $rsW++ $rxArgs = '/d /c start "" /b ping -n 30 -w ' + $rsW + ' 127.0.0.1 >nul' + $rxDelayMs = 2000 + if ($rxPath -eq 'Process.Start') { $rxArgs = '/d /c ping -n 2 127.0.0.1 >nul & start "" /b ping -n 30 -w ' + $rsW + ' 127.0.0.1 >nul'; $rxDelayMs = 3500 } $rxError = $null [PkChildProcessJob]::TestUseProcessStart = ($rxPath -eq 'Process.Start') [PkStreamReadTask]::TestFailRunAfter = 1 - [PkStreamReadTask]::TestFailRunDelayMs = 2000 + [PkStreamReadTask]::TestFailRunDelayMs = $rxDelayMs 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 {