From a3a59ade397e343d00b08c0b34ad1b5adc2ed712 Mon Sep 17 00:00:00 2001 From: Hal <22532613+HalRiveria@users.noreply.github.com> Date: Wed, 2 Dec 2026 13:19:42 -0500 Subject: [PATCH 1/4] Stop a program whose output readers can't start; warn when -KillTreeOnExit can't reach a program's tree --- ParallelKit.Harness.ps1 | 49 ++++++++++++++++++-- ParallelKit.ps1 | 89 ++++++++++++++++++++++++++----------- README.md | 4 +- Source/PkChildProcessJob.cs | 20 ++++++--- Source/PkConsoleCtrl.cs | 2 +- 5 files changed, 126 insertions(+), 38 deletions(-) diff --git a/ParallelKit.Harness.ps1 b/ParallelKit.Harness.ps1 index d35d570..b6a1171 100644 --- a/ParallelKit.Harness.ps1 +++ b/ParallelKit.Harness.ps1 @@ -4765,6 +4765,33 @@ $rdLeft = @(Get-CimInstance Win32_Process -Filter "Name='PING.EXE'" | Where-Obje foreach ($l in $rdLeft) { Stop-Process -Id $l.ProcessId -Force -ErrorAction SilentlyContinue } Test-Assert ($rdError -like '*could not start*' -and $rdLeft.Count -eq 0) ("a program whose output readers fail to build is ended and the start reported as failed (" + $rdLeft.Count + " left running, error: " + $rdError + ")") +# Nor is one whose readers can't start once it runs (no thread to be had): on +# both start paths, whichever reader fails, the start fails and the program +# and what it started are ended. Each case's ping has its own -w, to find it. +$rsW = 4240 +foreach ($rsPath in 'CreatedInJob', 'Process.Start', 'batch') { + foreach ($rsAfter in 0, 1) { + if ($rsPath -eq 'batch' -and $rsAfter -eq 0) { continue } + $rsW++ + $rsArgs = '/d /c ping -n 30 -w ' + $rsW + ' 127.0.0.1 >nul' + $rsError = $null + [PkChildProcessJob]::TestUseProcessStart = ($rsPath -eq 'Process.Start') + [PkStreamReadTask]::TestFailRunAfter = $rsAfter + 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 } + $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*') }) + if ($rsLeft.Count -eq 0) { break } + Start-Sleep -Milliseconds 100 + } while ($rsWait.ElapsedMilliseconds -lt 5000) + foreach ($l in $rsLeft) { Stop-Process -Id $l.ProcessId -Force -ErrorAction SilentlyContinue } + Test-Assert ($rsError -like '*could not start*' -and $rsLeft.Count -eq 0) ("a program whose " + @('stdout', 'stderr')[$rsAfter] + " reader can't start is ended and the start reported as failed, " + $rsPath + " (" + $rsLeft.Count + " left running, error: " + $rsError + ")") + } +} + # 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 @@ -5815,11 +5842,25 @@ try { Test-HarnessKillTree 'a custom starter' { Invoke-HarnessTreeDispatch @{ KillTreeOnExit = $true; JobStarter = $bjStarter } @{} $bjHeld } Test-HarnessKillTree 'a custom poll' { Invoke-HarnessTreeDispatch @{ KillTreeOnExit = $true; JobPollCompleted = { param($j) return $j['Proc'].HasExited } } @{} $bjHeld } - # A program without a tree job is left alone, with no warning. - Reset-Harness + # A program without a tree job can't have what it left killed: it's left + # alone, with one warning naming -KillTreeOnExit, once per process. With + # the kit's tree job turned off, or Windows refusing it, in each engine. + $bjNoTree = @( + @{ Name = 'no tree job, batch'; Hook = 'TestNoTreeJob'; Run = { Invoke-HarnessTreeBatch @{ KillTreeOnExit = $true; StreamTimeoutMs = 500 } @{} $bjHeld } } + @{ Name = 'no tree job, dispatcher'; Hook = 'TestNoTreeJob'; Run = { Invoke-HarnessTreeDispatch @{ KillTreeOnExit = $true; StreamTimeoutMs = 500 } @{} $bjHeld } } + @{ Name = 'tree job refused, one program'; Hook = 'TestRefuseTreeJob'; Run = { Invoke-PkProcessWithTimeout -FilePath $cmdExe -Arguments $bjHeld -KillTreeOnExit -StreamTimeoutMs 500 } } + ) + foreach ($bjCase in $bjNoTree) { + Reset-Harness + [PkChildProcessJob]::TestResetJobWarnings() + [PkChildProcessJob]::($bjCase.Hook) = $true + try { Test-HarnessKillTree $bjCase.Name $bjCase.Run -Left } finally { [PkChildProcessJob]::($bjCase.Hook) = $false } + $bjWarned = @($script:messages | Where-Object { $_.Level -eq 'Warn' -and $_.Message -like '*-KillTreeOnExit*' }) + Test-Assert ($script:messages.Count -eq 1 -and $bjWarned.Count -eq 1) ("and says so in one warning naming -KillTreeOnExit (" + $script:messages.Count + " message(s): " + (@($script:messages | ForEach-Object { $_.Message }) -join ' | ') + ")") + } [PkChildProcessJob]::TestNoTreeJob = $true - try { Test-HarnessKillTree 'no tree job' { Invoke-HarnessTreeBatch @{ KillTreeOnExit = $true; StreamTimeoutMs = 500 } @{} $bjHeld } -Left } finally { [PkChildProcessJob]::TestNoTreeJob = $false } - Test-Assert ($script:messages.Count -eq 0) ("and nothing is said about it (" + $script:messages.Count + " message(s))") + try { Test-HarnessKillTree 'no tree job, a second time' { Invoke-HarnessTreeBatch @{ KillTreeOnExit = $true; StreamTimeoutMs = 500 } @{} $bjHeld } -Left } finally { [PkChildProcessJob]::TestNoTreeJob = $false } + Test-Assert (@($script:messages | Where-Object { $_.Message -like '*-KillTreeOnExit*' }).Count -eq 1) ("and only once per process (" + @($script:messages | Where-Object { $_.Message -like '*-KillTreeOnExit*' }).Count + " warning(s) after a second program)") # A 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. diff --git a/ParallelKit.ps1 b/ParallelKit.ps1 index 9fd2c91..7796a70 100644 --- a/ParallelKit.ps1 +++ b/ParallelKit.ps1 @@ -169,7 +169,7 @@ public static class PkState // Bump this, and the check after the type definitions, whenever any C# // in this file changes: a session keeps the types it compiled first. - public const int TypesVersion = 14; + public const int TypesVersion = 15; // Locked: Register-/Unregister-PkCancellationSource are callable from // worker runspaces, and List is not safe for concurrent writers. @@ -403,9 +403,14 @@ public sealed class PkStreamReadTask : Task private readonly Buffer _buffer; private PkStreamReadTask(Buffer buffer) : base(new Func(buffer.Pump), TaskCreationOptions.LongRunning) { _buffer = buffer; } + // Harness only: n >= 0 makes the Run after the next n throw, as one whose + // thread can't be created would; -1, the default, is off. + public static int TestFailRunAfter = -1; + // maxChars: 0 for no cap. public static PkStreamReadTask Run(TextReader reader, int maxChars) { + if (TestFailRunAfter >= 0 && Interlocked.Decrement(ref TestFailRunAfter) < 0) { throw new OutOfMemoryException("Harness: a reader thread that can't start (TestFailRunAfter)."); } PkStreamReadTask task = new PkStreamReadTask(new Buffer(reader, maxChars)); task.Start(TaskScheduler.Default); return task; @@ -533,13 +538,16 @@ public static class PkChildProcessJob if (_treeJobs.TryGetValue(process, out j)) { _treeJobs.Remove(process); j.Dispose(); } } - // Harness only: whether the program has a tree job. - public static bool TestHasTree(Process process) + // Whether the program has a tree job, which KillTree needs. + public static bool HasTree(Process process) { TreeJob j; return process != null && _treeJobs.TryGetValue(process, out j); } + // Harness only: the same as HasTree. + public static bool TestHasTree(Process process) { return HasTree(process); } + // Never closed: Windows closes it when this process exits, and that is // what kills the children. private static IntPtr _job = IntPtr.Zero; @@ -847,11 +855,13 @@ public static class PkChildProcessJob public static bool ClaimFallbackWarning() { return Interlocked.Exchange(ref _fallbackWarned, 1) == 0; } public static void TestResetFallbackWarning() { Interlocked.Exchange(ref _fallbackWarned, 0); } // The same, once each, for a Job Object that couldn't be set up when - // first needed, and for a running program Windows wouldn't add to it. - private static int _initWarned = 0, _assignWarned = 0; + // first needed, for a running program Windows wouldn't add to it, and for + // -KillTreeOnExit on a program without a tree job. + private static int _initWarned = 0, _assignWarned = 0, _noTreeWarned = 0; public static bool ClaimInitWarning() { return Interlocked.Exchange(ref _initWarned, 1) == 0; } public static bool ClaimAssignWarning() { return Interlocked.Exchange(ref _assignWarned, 1) == 0; } - public static void TestResetJobWarnings() { Interlocked.Exchange(ref _initWarned, 0); Interlocked.Exchange(ref _assignWarned, 0); } + public static bool ClaimNoTreeWarning() { return Interlocked.Exchange(ref _noTreeWarned, 1) == 0; } + public static void TestResetJobWarnings() { Interlocked.Exchange(ref _initWarned, 0); Interlocked.Exchange(ref _assignWarned, 0); Interlocked.Exchange(ref _noTreeWarned, 0); } private static StringBuilder BuildCommandLine(string fileName, string arguments) { @@ -1075,7 +1085,7 @@ public static class PkChildProcessJob # A session that loaded another version keeps that one's compiled types. Say # so, rather than fail later with a missing-method error. Keep this number in # sync with [PkState]::TypesVersion. -if ((& { try { [PkState]::TypesVersion } catch { 0 } }) -ne 14) { +if ((& { try { [PkState]::TypesVersion } catch { 0 } }) -ne 15) { throw "ParallelKit: this PowerShell session already loaded a different version of the kit, and its compiled parts can't be swapped out. Close this window and start a new one." } @@ -1796,24 +1806,41 @@ function Start-PkProcessCore { # batch's starter copy those keys onto their jobs: a new key goes in all # four places. if ($null -ne $started) { - return @{ - Proc = $started.Process - StdoutTask = [PkStreamReadTask]::Run($started.Stdout, $MaxOutputChars) - StderrTask = [PkStreamReadTask]::Run($started.Stderr, $MaxOutputChars) - Stopwatch = [System.Diagnostics.Stopwatch]::StartNew() + $proc = $started.Process + $stdout = $started.Stdout + $stderr = $started.Stderr + } else { + # Windows also refuses a program that has already exited (error 5), as + # quick ones often have by now: only one still running is a real gap. + # With no job at all, the setup above has warned already. + $assignWhy = $null + if (-not [PkChildProcessJob]::Assign($proc, [ref]$assignWhy) -and [PkChildProcessJob]::IsInitialized -and -not $proc.HasExited -and [PkChildProcessJob]::ClaimAssignWarning()) { + Write-PkMessage ("[WARNING] Windows wouldn't add a program to the kit's Job Object (process " + $proc.Id + ", " + $psi.FileName + ": " + $assignWhy + "). It isn't cleaned up if PowerShell is killed outright, and killing it reaches what it started only through taskkill. Shown once.") -Level Warn } + $stdout = $proc.StandardOutput + $stderr = $proc.StandardError } - # Windows also refuses a program that has already exited (error 5), as - # quick ones often have by now: only one still running is a real gap. - # With no job at all, the setup above has warned already. - $assignWhy = $null - if (-not [PkChildProcessJob]::Assign($proc, [ref]$assignWhy) -and [PkChildProcessJob]::IsInitialized -and -not $proc.HasExited -and [PkChildProcessJob]::ClaimAssignWarning()) { - Write-PkMessage ("[WARNING] Windows wouldn't add a program to the kit's Job Object (process " + $proc.Id + ", " + $psi.FileName + ": " + $assignWhy + "). It isn't cleaned up if PowerShell is killed outright, and killing it reaches what it started only through taskkill. Shown once.") -Level Warn + # The program is running now. If a reader can't start (no thread to be + # had), nothing would read its output and nobody would hold the program: + # end it and what it started, and fail the start instead. + $stdoutTask = $null + try { + $stdoutTask = [PkStreamReadTask]::Run($stdout, $MaxOutputChars) + $stderrTask = [PkStreamReadTask]::Run($stderr, $MaxOutputChars) + } catch { + $reason = [string]$_ + if ($_.Exception -is [System.Management.Automation.MethodInvocationException] -and $null -ne $_.Exception.InnerException) { $reason = $_.Exception.InnerException.Message } + try { $null = Stop-PkProcessTree -Process $proc } catch { } # best effort: the failed start below is what's reported + # 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) } return @{ Proc = $proc - StdoutTask = [PkStreamReadTask]::Run($proc.StandardOutput, $MaxOutputChars) - StderrTask = [PkStreamReadTask]::Run($proc.StandardError, $MaxOutputChars) + StdoutTask = $stdoutTask + StderrTask = $stderrTask Stopwatch = [System.Diagnostics.Stopwatch]::StartNew() } } @@ -2017,13 +2044,20 @@ function Stop-PkTimedOutJob { 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 without a - # tree job (a .Proc that isn't a Process, or a program Windows wouldn't - # give one). One try only: the dispatcher's poll runs this every pass. + # 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, or the kit has no Job Object) can't be reached: that warns, + # once per process. 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: Windows didn't give it a Job Object of its own, so anything it started is left running. Shown once.") -Level Warn + } + return + } $null = [PkChildProcessJob]::KillTree($proc) } @@ -2256,7 +2290,8 @@ function Invoke-PkProcessWithTimeout { # .PARAMETER KillTreeOnExit # When the 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. + # gave a Job Object of its own, the normal case; for one without, it warns + # once per session. # .PARAMETER IgnoreAbort # Start and keep going during an abort, for a cleanup or restore step that has # to run because of it. @@ -2412,7 +2447,8 @@ function Invoke-PkProcessDispatch { # .PARAMETER KillTreeOnExit # 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. A job's own KillTreeOnExit + # 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 # your own, Complete-PkProcess does, so it needs -JobFinalize to call that. # .OUTPUTS @@ -3173,7 +3209,8 @@ function Invoke-PkProcessBatch { # .PARAMETER KillTreeOnExit # 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. A command's own + # 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. # .OUTPUTS # An object with Results, Aborted and ForceKilledCount. Each result has Command, diff --git a/README.md b/README.md index a123e49..021eee2 100644 --- a/README.md +++ b/README.md @@ -310,7 +310,7 @@ The per-command keys go on the command itself, for example one that keeps all of `-StreamTimeoutMs` (default 15000) is how long to wait for a program's output after it exits; see `StreamTimedOut` in [Process results](#process-results). -`-KillTreeOnExit` kills whatever a program started that's still running when the program itself exits, whether or not it holds the program's output open. It's off by default, since some tools leave a build server or a daemon running on purpose. A command's own `KillTreeOnExit` key, `$true` or `$false`, overrides it either way. `Invoke-PkProcessWithTimeout` and the dispatcher take it too; `Start-PkProcess` doesn't, since it returns before there's an exit to act on. It goes through the program's own Job Object, so it does nothing, with no warning, for a program without one (`StartMode` `NoJob`, or Windows refused it). 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. `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. @@ -665,7 +665,7 @@ Other pieces: `Request-PkAbort` triggers the same abort from code. `Test-PkAbort ## Choosing limits -- **`-MaxConcurrent` for programs.** For programs that use one CPU core each, start at `[Environment]::ProcessorCount`. Many encoders (image, video, compression) already use several cores per file, so fewer copies at once is often as fast and uses less memory. Programs that mostly wait on disk or network can go higher. Try a few values on real work; the best number depends on the tool. +- **`-MaxConcurrent` for programs.** For programs that use one CPU core each, start at `[Environment]::ProcessorCount`. Many encoders (image, video, compression) already use several cores per file, so fewer copies at once is often as fast and uses less memory. Programs that mostly wait on disk or network can go higher. Try a few values on real work; the best number depends on the tool. Each running program also takes two threads in your PowerShell process, one reading each of its output streams, so a few hundred programs at once means several hundred threads (and a child left holding a program's output keeps its thread until it lets go). - **`-MaxConcurrent` for runspace jobs.** Same idea: the core count for CPU-heavy PowerShell work. Each runspace costs some memory and startup time, so very high values rarely help. - **Several dispatchers at once** (for example, one per runspace job) should share one `SemaphoreSlim` as `-MaxConcurrent`, so their combined total stays under the limit you picked. They take turns: each pauses up to 50 ms after a program finishes so the others can get the free slot, which costs very short programs some speed compared with a dispatcher of their own. diff --git a/Source/PkChildProcessJob.cs b/Source/PkChildProcessJob.cs index 96602cf..fad7d8b 100644 --- a/Source/PkChildProcessJob.cs +++ b/Source/PkChildProcessJob.cs @@ -161,9 +161,14 @@ public string Keep(bool snapshot) private readonly Buffer _buffer; private PkStreamReadTask(Buffer buffer) : base(new Func(buffer.Pump), TaskCreationOptions.LongRunning) { _buffer = buffer; } + // Harness only: n >= 0 makes the Run after the next n throw, as one whose + // thread can't be created would; -1, the default, is off. + public static int TestFailRunAfter = -1; + // maxChars: 0 for no cap. public static PkStreamReadTask Run(TextReader reader, int maxChars) { + if (TestFailRunAfter >= 0 && Interlocked.Decrement(ref TestFailRunAfter) < 0) { throw new OutOfMemoryException("Harness: a reader thread that can't start (TestFailRunAfter)."); } PkStreamReadTask task = new PkStreamReadTask(new Buffer(reader, maxChars)); task.Start(TaskScheduler.Default); return task; @@ -291,13 +296,16 @@ public static void ReleaseTree(Process process) if (_treeJobs.TryGetValue(process, out j)) { _treeJobs.Remove(process); j.Dispose(); } } - // Harness only: whether the program has a tree job. - public static bool TestHasTree(Process process) + // Whether the program has a tree job, which KillTree needs. + public static bool HasTree(Process process) { TreeJob j; return process != null && _treeJobs.TryGetValue(process, out j); } + // Harness only: the same as HasTree. + public static bool TestHasTree(Process process) { return HasTree(process); } + // Never closed: Windows closes it when this process exits, and that is // what kills the children. private static IntPtr _job = IntPtr.Zero; @@ -605,11 +613,13 @@ public static string StartMode public static bool ClaimFallbackWarning() { return Interlocked.Exchange(ref _fallbackWarned, 1) == 0; } public static void TestResetFallbackWarning() { Interlocked.Exchange(ref _fallbackWarned, 0); } // The same, once each, for a Job Object that couldn't be set up when - // first needed, and for a running program Windows wouldn't add to it. - private static int _initWarned = 0, _assignWarned = 0; + // first needed, for a running program Windows wouldn't add to it, and for + // -KillTreeOnExit on a program without a tree job. + private static int _initWarned = 0, _assignWarned = 0, _noTreeWarned = 0; public static bool ClaimInitWarning() { return Interlocked.Exchange(ref _initWarned, 1) == 0; } public static bool ClaimAssignWarning() { return Interlocked.Exchange(ref _assignWarned, 1) == 0; } - public static void TestResetJobWarnings() { Interlocked.Exchange(ref _initWarned, 0); Interlocked.Exchange(ref _assignWarned, 0); } + public static bool ClaimNoTreeWarning() { return Interlocked.Exchange(ref _noTreeWarned, 1) == 0; } + public static void TestResetJobWarnings() { Interlocked.Exchange(ref _initWarned, 0); Interlocked.Exchange(ref _assignWarned, 0); Interlocked.Exchange(ref _noTreeWarned, 0); } private static StringBuilder BuildCommandLine(string fileName, string arguments) { diff --git a/Source/PkConsoleCtrl.cs b/Source/PkConsoleCtrl.cs index 5c587f3..e908bcd 100644 --- a/Source/PkConsoleCtrl.cs +++ b/Source/PkConsoleCtrl.cs @@ -125,7 +125,7 @@ public static class PkState // Bump this, and the check after the type definitions, whenever any C# // in this file changes: a session keeps the types it compiled first. - public const int TypesVersion = 14; + public const int TypesVersion = 15; // Locked: Register-/Unregister-PkCancellationSource are callable from // worker runspaces, and List is not safe for concurrent writers. From 2cc467a266ed8f91612a34e3e009ecd77db4c838 Mon Sep 17 00:00:00 2001 From: Hal <22532613+HalRiveria@users.noreply.github.com> Date: Wed, 2 Dec 2026 13:20:34 -0500 Subject: [PATCH 2/4] Name every case the -KillTreeOnExit warning covers --- ParallelKit.ps1 | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/ParallelKit.ps1 b/ParallelKit.ps1 index 7796a70..ab637ec 100644 --- a/ParallelKit.ps1 +++ b/ParallelKit.ps1 @@ -2046,15 +2046,16 @@ 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, or the kit has no Job Object) can't be reached: that warns, - # once per process. One try only: the dispatcher's poll runs this every pass. + # give it one, the kit has no Job Object, or a custom starter started it) + # can't be reached: that warns, once per process. One try only: the + # dispatcher's poll runs this every pass. 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: Windows didn't give it a Job Object of its own, so anything it started is left running. Shown once.") -Level Warn + 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 } From 3ef03aee0b17bec680a1ac4152a2cc096c3ebf7f Mon Sep 17 00:00:00 2001 From: Hal <22532613+HalRiveria@users.noreply.github.com> Date: Wed, 2 Dec 2026 13:38:02 -0500 Subject: [PATCH 3/4] Throw InvalidOperationException from the reader-start test hook (CA2201) --- ParallelKit.ps1 | 2 +- Source/PkChildProcessJob.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/ParallelKit.ps1 b/ParallelKit.ps1 index ab637ec..ec8ae1d 100644 --- a/ParallelKit.ps1 +++ b/ParallelKit.ps1 @@ -410,7 +410,7 @@ public sealed class PkStreamReadTask : Task // maxChars: 0 for no cap. public static PkStreamReadTask Run(TextReader reader, int maxChars) { - if (TestFailRunAfter >= 0 && Interlocked.Decrement(ref TestFailRunAfter) < 0) { throw new OutOfMemoryException("Harness: a reader thread that can't start (TestFailRunAfter)."); } + if (TestFailRunAfter >= 0 && Interlocked.Decrement(ref TestFailRunAfter) < 0) { throw new InvalidOperationException("Harness: a reader thread that can't start (TestFailRunAfter)."); } PkStreamReadTask task = new PkStreamReadTask(new Buffer(reader, maxChars)); task.Start(TaskScheduler.Default); return task; diff --git a/Source/PkChildProcessJob.cs b/Source/PkChildProcessJob.cs index fad7d8b..7e2a4a8 100644 --- a/Source/PkChildProcessJob.cs +++ b/Source/PkChildProcessJob.cs @@ -168,7 +168,7 @@ public string Keep(bool snapshot) // maxChars: 0 for no cap. public static PkStreamReadTask Run(TextReader reader, int maxChars) { - if (TestFailRunAfter >= 0 && Interlocked.Decrement(ref TestFailRunAfter) < 0) { throw new OutOfMemoryException("Harness: a reader thread that can't start (TestFailRunAfter)."); } + if (TestFailRunAfter >= 0 && Interlocked.Decrement(ref TestFailRunAfter) < 0) { throw new InvalidOperationException("Harness: a reader thread that can't start (TestFailRunAfter)."); } PkStreamReadTask task = new PkStreamReadTask(new Buffer(reader, maxChars)); task.Start(TaskScheduler.Default); return task; From dfdf9ae1892f8adb99ef214fe1d5dd8077821979 Mon Sep 17 00:00:00 2001 From: Hal <22532613+HalRiveria@users.noreply.github.com> Date: Wed, 2 Dec 2026 13:51:18 -0500 Subject: [PATCH 4/4] Version 4.2 --- ParallelKit.ps1 | 4 ++-- README.md | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/ParallelKit.ps1 b/ParallelKit.ps1 index ec8ae1d..269f4c8 100644 --- a/ParallelKit.ps1 +++ b/ParallelKit.ps1 @@ -2,7 +2,7 @@ # graceful Ctrl+C/window-close handling for Windows PowerShell 5.1 and # PowerShell 7. # -# Version 4.1 - https://github.com/HalRiveria/PowerShell-ParallelKit +# Version 4.2 - https://github.com/HalRiveria/PowerShell-ParallelKit # (Initialize-ParallelKit reports the version too: change both together. The # module's manifest takes it from here.) # Copyright (c) 2026 HalRiveria. MIT License: keep this notice with any copy; @@ -1266,7 +1266,7 @@ function Initialize-ParallelKit { $jobOk = Initialize-PkChildProcessJob # The header's Version line: the version PR changes both, and the harness # checks they match. - $version = [version]'4.1' + $version = [version]'4.2' return [pscustomobject][ordered]@{ AbortHandler = $handlerOk; ChildProcessJob = $jobOk; Version = $version; StartMode = [PkChildProcessJob]::StartMode } } diff --git a/README.md b/README.md index 021eee2..73fc3ec 100644 --- a/README.md +++ b/README.md @@ -121,7 +121,7 @@ Each one has built-in help: `Get-Help Invoke-PkProcessBatch -Full` shows its par ## Setup -Requires Windows, with Windows PowerShell 5.1 or PowerShell 7. Download `ParallelKit.ps1` from the [Releases page](https://github.com/HalRiveria/PowerShell-ParallelKit/releases) (this README describes version 4.1 and later), put it in your project, and dot-source it from your script: +Requires Windows, with Windows PowerShell 5.1 or PowerShell 7. Download `ParallelKit.ps1` from the [Releases page](https://github.com/HalRiveria/PowerShell-ParallelKit/releases) (this README describes version 4.2 and later), put it in your project, and dot-source it from your script: ```powershell . "$PSScriptRoot\ParallelKit.ps1" @@ -180,7 +180,7 @@ Import-Module C:\Modules\ParallelKit Installed, or built into a `ParallelKit` folder somewhere on `$env:PSModulePath`, `Import-Module ParallelKit` finds it by name, and so does a call to any of its functions without importing it first. The rest of this README applies either way. -The module's version always has three parts: the kit's X.Y (what `Initialize-ParallelKit` reports) is the module's X.Y.0, and an X.Y.Z version stays as it is. So for 4.1, `Get-Module ParallelKit` shows 4.1.0, and that's the version `Import-Module -RequiredVersion` takes. +The module's version always has three parts: the kit's X.Y (what `Initialize-ParallelKit` reports) is the module's X.Y.0, and an X.Y.Z version stays as it is. So for 4.2, `Get-Module ParallelKit` shows 4.2.0, and that's the version `Import-Module -RequiredVersion` takes.
If the import is refused