Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 45 additions & 4 deletions ParallelKit.Harness.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down
94 changes: 66 additions & 28 deletions ParallelKit.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<T> is not safe for concurrent writers.
Expand Down Expand Up @@ -403,9 +403,14 @@ public sealed class PkStreamReadTask : Task<string>
private readonly Buffer _buffer;
private PkStreamReadTask(Buffer buffer) : base(new Func<string>(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 InvalidOperationException("Harness: a reader thread that can't start (TestFailRunAfter)."); }
PkStreamReadTask task = new PkStreamReadTask(new Buffer(reader, maxChars));
task.Start(TaskScheduler.Default);
return task;
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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)
{
Expand Down Expand Up @@ -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."
}

Expand Down Expand Up @@ -1256,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 }
}

Expand Down Expand Up @@ -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()
}
}
Expand Down Expand Up @@ -2017,13 +2044,21 @@ 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, 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: 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
}
$null = [PkChildProcessJob]::KillTree($proc)
}

Expand Down Expand Up @@ -2256,7 +2291,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.
Expand Down Expand Up @@ -2412,7 +2448,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
Expand Down Expand Up @@ -3173,7 +3210,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,
Expand Down
Loading