From 5aa27bae6976ed61f77414cf173a693efc07b795 Mon Sep 17 00:00:00 2001 From: Hal <22532613+HalRiveria@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:44:33 -0500 Subject: [PATCH 1/3] Revise the README and add tests for its examples and PowerShell 7 claims Collapsible sections, Mermaid diagrams, a section on where process-tree cleanup can fall short, what the kit adds on PowerShell 7, and corrected examples. Testing/readme-examples runs the README's code examples; Testing/ps7-native checks the PowerShell 7 behavior the README describes. Co-Authored-By: Claude Opus 5.5 --- README.md | 504 +++++++++++++++++++++++++------- Testing/ps7-native/run.ps1 | 162 ++++++++++ Testing/readme-examples/run.ps1 | 294 +++++++++++++++++++ 3 files changed, 855 insertions(+), 105 deletions(-) create mode 100644 Testing/ps7-native/run.ps1 create mode 100644 Testing/readme-examples/run.ps1 diff --git a/README.md b/README.md index 9b10b42..633e903 100644 --- a/README.md +++ b/README.md @@ -2,16 +2,34 @@ [![Tests](https://github.com/HalRiveria/PowerShell-ParallelKit/actions/workflows/tests.yml/badge.svg)](https://github.com/HalRiveria/PowerShell-ParallelKit/actions/workflows/tests.yml) -Run thousands of command-line programs, or blocks of PowerShell code, in parallel from Windows PowerShell 5.1 (or PowerShell 7 on Windows), and stop cleanly when you press Ctrl+C. One file, nothing to install. +Run thousands of command-line programs, or blocks of PowerShell code, in parallel from Windows PowerShell 5.1 or PowerShell 7. One file, nothing to install. -- **Process dispatch** - run many external programs, a set number at a time, with their output captured. -- **Runspace jobs** - run a PowerShell worker script many times in parallel. -- **Graceful abort** - Ctrl+C lets in-flight work finish and stops cleanly, instead of killing everything mid-write. Closing the window stops what's left right away, since Windows allows only a few seconds. -- **No orphans** - programs the script started die with it, even if it's force-closed. +Starting programs in parallel from PowerShell is easy. Stopping them is the hard part: Ctrl+C cuts work off mid-file, programs keep running after the script that started them dies, and reading a program's output the simple way can deadlock. ParallelKit handles those parts: -Built with Claude Code. +- **Programs run directly**, a set number at a time, with stdout and stderr read in the background so a full pipe can't deadlock, instead of a PowerShell thread tied up waiting on each one. +- **Graceful Ctrl+C with `Invoke-PkRun`.** No new work starts, running work gets time to finish (60 seconds by default), and then what's left is stopped and reported, with a cleanup call for each in the group dispatcher. Closing the window stops what's left right away, since Windows allows only a few seconds. +- **Process-tree cleanup.** In the normal `CreatedInJob` mode, each program is created inside a Windows Job Object. Windows then terminates it and its descendants when PowerShell exits, even if PowerShell is killed outright. The documented fallback modes have some limitations. +- **Runspace jobs with safety checks.** Run a PowerShell worker script many times in parallel. Before anything starts, the kit checks the worker code for the two mistakes that make runspace code hang, crash or quietly read nothing. +- **Work in groups.** A folder at a time, say, with retries or follow-up steps per file and a callback when each folder is done. -**Contents:** [Quick start](#quick-start) · [Who it's for](#who-its-for) · [Why Not Use X?](#why-not-use-x) · [Setup](#setup) · [Run a list of programs](#run-a-list-of-programs) · [Run PowerShell code in parallel](#run-powershell-code-in-parallel) · [The two rules for worker code](#the-two-rules-for-worker-code) · [Process dispatch with groups](#process-dispatch-with-groups) · [Single processes](#single-processes) · [Messages](#messages) · [Abort](#abort) · [Choosing limits](#choosing-limits) · [Limits](#limits) · [Testing](#testing) · [FAQ](#faq) +The kit is built to be reliable first and fast second. The aim is that a long run either finishes or stops cleanly, and that whatever goes wrong along the way is reported rather than lost. A program that can't start, runs past its time limit or holds its output open, a worker that crashes, or a Ctrl+C partway through: each is handled and shows up in what the call returns, instead of hanging or killing your script. Closing the window is the exception: Windows allows only a few seconds, so the kit stops the programs at once, and PowerShell closes with the window. The main harness exercises real programs and runspaces, with no mocked process execution. GitHub Actions runs it against Windows PowerShell 5.1 and PowerShell 7 on every pull request and every change to `main`. Additional targeted regression and stress suites are maintained under `Testing/` and can be run independently. + +Developed with assistance from Claude Code. The implementation, test harness, and development history are available for inspection. I encourage independent review and testing. + +**Contents:** [Process-tree cleanup limitations](#process-tree-cleanup-limitations) · [Quick start](#quick-start) · [Who it's for](#who-its-for) · [Which function](#which-function) · [Setup](#setup) · [How it fits together](#how-it-fits-together) · [Run a list of programs](#run-a-list-of-programs) · [Process results](#process-results) · [Run PowerShell code in parallel](#run-powershell-code-in-parallel) · [The two rules for worker code](#the-two-rules-for-worker-code) · [Process dispatch with groups](#process-dispatch-with-groups) · [Single processes](#single-processes) · [Messages](#messages) · [Abort](#abort) · [Choosing limits](#choosing-limits) · [Limits](#limits) · [Testing](#testing) · [FAQ](#faq) + +## Process-tree cleanup limitations + +ParallelKit uses Windows Job Objects to clean up programs and their descendants. The following cases can prevent cleanup from reaching every process in a tree. + +
+The three cases + +- **`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. +- **`NoJob`.** If Windows won't give the kit a Job Object at all, it warns, 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`. + +
## Quick start @@ -27,42 +45,35 @@ $commands = foreach ($f in Get-ChildItem *.png) { $batch = Invoke-PkRun { Invoke-PkProcessBatch -Commands $commands -MaxConcurrent 6 } foreach ($r in $batch.Results) { - if ($r.Aborted) { continue } # stopped by Ctrl+C before it finished; no exit code + if ($r.Aborted) { continue } # stopped by Ctrl+C before it finished; no exit code + if ($r.StartError) { continue } # couldn't start; the kit has already said why if ($r.ExitCode -ne 0) { Write-Warning ('Failed: ' + $r.Command.Arguments) } } ``` -That's all you need for this case. The worker rules, closures and callback details further down don't apply to it: they only matter for running PowerShell code in parallel (`Invoke-PkRunspaceJobs`) or for the group dispatcher. [Run a list of programs](#run-a-list-of-programs) covers the result fields and options. +That's all you need for this case. The worker rules, closures and callback details further down don't apply to it: they only matter for running PowerShell code in parallel (`Invoke-PkRunspaceJobs`) or for the group dispatcher. [Run a list of programs](#run-a-list-of-programs) covers the options, and [Process results](#process-results) what comes back. ## Who it's for Scripts that have to run on Windows PowerShell 5.1, the version built into Windows 10 (1607 and later), Windows 11 and Windows Server 2016 and later. Usually that's because PowerShell 7 isn't installed or isn't allowed on the machines involved, or because the script has to run anywhere without asking anyone to install anything. +On PowerShell 7, `ForEach-Object -Parallel` is the simpler choice for plain parallel PowerShell code. For external programs the kit still adds things 7 doesn't do for you: programs run directly, without a runspace thread waiting on each one; Ctrl+C lets running ones finish before the rest are stopped, with a cleanup call for each; a time limit per program kills it and everything it started; they die with the script even if PowerShell is killed; and work can come in groups, with retries and a step when each group is done. The full test suite runs on 7 for every change. + The typical job is batch work over lots of files with a command-line tool: converting images, audio or video, compressing archives, running a check or build step per file. That's what the process side is built for, and it's where most of the kit's care has gone. -For plain parallel loops of PowerShell code, other tools are simpler (see [Why Not Use X?](#why-not-use-x)). Reach for ParallelKit when you need any of these: +For plain parallel loops of PowerShell code, other tools are simpler. Reach for ParallelKit when you need any of these: - Ctrl+C that lets running work finish instead of cutting it off mid-file. -- Child processes that are cleaned up even if the script is killed outright. +- Child processes that are cleaned up even if the script is killed outright (with the exceptions under [Process-tree cleanup limitations](#process-tree-cleanup-limitations)). - A cap on how many external programs run at once, with their output captured without risk of a full-pipe deadlock. - Work that comes in groups (a folder at a time, say), with retries or follow-up steps per file and something to do when each group is finished. -Which function you want: - -| You have | Use | -|---|---| -| A flat list of external programs to run | `Invoke-PkProcessBatch` | -| Programs that come in groups, with something to do when each group is done | `Invoke-PkProcessDispatch` | -| PowerShell code to run in parallel | `Invoke-PkRunspaceJobs` | -| One program to run with a time limit | `Invoke-PkProcessWithTimeout` | - -Wrap any of them in `Invoke-PkRun { ... }` to get graceful Ctrl+C. (For `Invoke-PkProcessWithTimeout` that means the program is killed and the call throws, instead of the whole script dying.) - -## Why Not Use X? +
+Why not use something else? For running PowerShell code in parallel, most of these are fine and some are simpler. ParallelKit is mainly about running external programs, and about what happens when a run is stopped partway through. -- **PowerShell 7's `ForEach-Object -Parallel`.** The easy answer for plain parallel PowerShell code if you can use PowerShell 7. ParallelKit was built for scripts and machines stuck on 5.1, though it runs on 7 too, where it still adds the external-program handling and graceful Ctrl+C. `ForEach-Object -Parallel` also refuses a scriptblock passed by `$using:`, rather than letting it run where it isn't safe. +- **PowerShell 7's `ForEach-Object -Parallel`.** The easy answer for plain parallel PowerShell code if you can use PowerShell 7. For external programs, ParallelKit adds what it doesn't do: see [Who it's for](#who-its-for). `ForEach-Object -Parallel` also refuses a scriptblock passed by `$using:`, rather than letting it run where it isn't safe. - **`Start-Job`.** Built in, but each job is a whole new `powershell.exe` process, so every job costs noticeable startup time and memory, and what it returns comes back as serialized copies (properties only, no methods). 5.1's `Start-Job` has no throttle either, so you write the wait-for-a-free-slot loop yourself. Fine for a handful of long jobs, poor for thousands of short ones. - **ThreadJob (`Start-ThreadJob`).** Runs jobs as runspaces in the same process, with a `-ThrottleLimit`. On 5.1 it's the best fit for plain parallel scriptblocks, if you can install a module from the PowerShell Gallery (`Microsoft.PowerShell.ThreadJob`; it ships with PowerShell 7, not 5.1). - **PoshRSJob (`Start-RSJob`).** A community module from the Gallery, also runspace-based, with a `-Throttle` limit and a job-style interface. It hasn't had a release since 2018, it can report a job as Completed before its output is ready (run `Wait-RSJob` before `Receive-RSJob`), and it's hit harder than ThreadJob by the [scriptblock problem](#faq). Where both are an option, ThreadJob is the better pick. @@ -71,12 +82,42 @@ For running PowerShell code in parallel, most of these are fine and some are sim - **`Start-Process` in a loop.** Starts programs without waiting, but can only send their output to files, and the throttling and waiting are up to you. Using `System.Diagnostics.Process` directly gets output into memory, but reading stdout and then stderr the simple way deadlocks once a program fills the pipe you aren't reading. The kit reads both in the background. - **`Invoke-Command -AsJob` against localhost.** Needs PowerShell remoting enabled (on by default only on Windows Server), and connecting to your own machine needs an elevated session, all for no gain on one machine. -What none of them do for you: +
+ +## Which function -- On Ctrl+C, let running work finish (up to a time limit), then stop what's left and call your cleanup for each job that was killed. A window close does the same without the wait. -- Kill the programs your script started if the script itself is killed. Windows doesn't do that on its own: a process's children keep running after it dies. -- Run external programs directly, with a cap and captured output, instead of tying up a PowerShell thread to wait on each one. -- Work in groups, with retries and a step when each group finishes. +The kit's public functions, by what they're for. Everything else in the file is an internal helper that stays inside the module and can change between versions. + +| Function | What it's for | +|---|---| +| **Engines** | | +| `Invoke-PkProcessBatch` | Run a flat list of external programs, a set number at a time, and get one result per command. | +| `Invoke-PkProcessDispatch` | Run programs that come in groups, with retries or follow-up jobs and a callback when each group is done. | +| `Invoke-PkRunspaceJobs` | Run a PowerShell worker script many times in parallel, in runspaces. | +| `Invoke-PkRun` | Wrap any of the above for graceful Ctrl+C: running work finishes before the rest is stopped. | +| **One program** | | +| `Invoke-PkProcessWithTimeout` | Run one program and wait for it, with a hard time limit. | +| `Start-PkProcess` | Start one program hidden, with its output read in the background, and return at once. | +| `Wait-PkProcess` | Wait for a started program to exit, with a timeout that can't overrun. | +| `Complete-PkProcess` | Collect a finished program's exit code and output. | +| `Stop-PkProcessTree` | Kill one or more programs and everything they started. | +| `ConvertTo-PkArgumentString` | Join a list of arguments into one correctly quoted command line. | +| **Abort and cancellation** | | +| `Test-PkAbortSignal` | Main thread: has an abort (Ctrl+C, window close, `Request-PkAbort`) started? | +| `Test-PkCancelRequested` | Worker code: is this run being canceled or aborted? Check it before anything irreversible. | +| `Request-PkAbort` | Start an abort from code, the same as Ctrl+C. | +| `Reset-PkAbortState` | Clear a finished abort, to call an engine again outside `Invoke-PkRun`. | +| `Register-PkCancellationSource` | Add your own `CancellationTokenSource` to the set an abort cancels. | +| `Unregister-PkCancellationSource` | Take one back out. | +| `Get-PkAbortTriggerLabel` | Say what started the abort: Ctrl+C, Ctrl+Break, a window close or `Request-PkAbort`. | +| **Messages** | | +| `Write-PkMessage` | Write a message from anywhere, worker code included; it's delivered on the main thread. | +| `Set-PkMessageHandler` | Send the kit's messages, and yours, to your own logging. | +| **Setup and checks** | | +| `Initialize-ParallelKit` | Set up Ctrl+C handling and child-process cleanup up front, and report how it went. Optional. | +| `Test-PkWorkerSafety` | A static check for the common ways worker code breaks [the two rules](#the-two-rules-for-worker-code), for your own tests. It catches likely mistakes; it doesn't prove code safe. | + +Each one has built-in help: `Get-Help Invoke-PkProcessBatch -Full` shows its parameters, their defaults, what it returns and an example. That's the parameter reference; this README explains how the pieces behave. ## Setup @@ -84,13 +125,34 @@ Requires Windows, with Windows PowerShell 5.1 or PowerShell 7. Download `Paralle ```powershell . "$PSScriptRoot\ParallelKit.ps1" -$null = Initialize-ParallelKit +$pk = Initialize-ParallelKit # optional; warns by itself if part of the setup fails +if ($pk.StartMode -eq 'NoJob') { + # Only for a script that must not leave programs running if PowerShell is killed. + # AddedToJob passes: it still cleans up, with the gaps under Process-tree cleanup limitations. + throw 'ParallelKit has no Job Object here, so programs would outlive a killed script.' +} ``` If you downloaded the file, Windows marks it as coming from the internet and your execution policy may refuse to load it. Run `Unblock-File .\ParallelKit.ps1` once to clear that. If your machines only run signed scripts (the `AllSigned` execution policy), the file has to be signed with a certificate they trust. The release copy isn't signed. +
+What Initialize-ParallelKit returns + +`Initialize-ParallelKit` is optional. It registers the Ctrl+C handler and sets up child-process cleanup up front; the engines set up what they need on first use either way. The kit leaves the thread pool's settings alone. It returns an object with: + +- `AbortHandler`: `$true` if the Ctrl+C handler was registered. A failure also prints a warning. +- `ChildProcessJob`: `$true` if the Job Object for child-process cleanup was set up. A failure also prints a warning, and is the same case as `StartMode` `NoJob`. +- `ThreadPool`: always `$true`, kept for scripts that check it. +- `Version`: the kit's version. +- `StartMode`: how the kit starts programs here. `CreatedInJob` (inside the Job Object, the normal case), `AddedToJob` (started, then added to it just after) or `NoJob` (no cleanup if PowerShell is killed). It's the default for the session, not a promise for every program: one whose start can't be set up inside the Job Object falls back to `AddedToJob`, with a warning. See [Process-tree cleanup limitations](#process-tree-cleanup-limitations). + +
+ +
+How it loads + It works whether or not your script uses `Set-StrictMode`. The version is in the comment block at the top of the file, so a copy kept in your project still says which one it is. That block also carries the license notice; keep it with the file. @@ -99,12 +161,33 @@ Dot-source it. It loads itself as an in-memory module named `ParallelKit`: nothi Its public functions are imported globally, so they stay available for the rest of that PowerShell session, and a `.GetNewClosure()` block can call them however your script was started. Its internal helpers stay inside the module. -`Initialize-ParallelKit` is optional. It registers the Ctrl+C handler and sets up child-process cleanup up front; the engines set up what they need on first use either way. The kit leaves the thread pool's settings alone. It returns an object with `AbortHandler` and `ChildProcessJob`, each `$true` if that part worked (a failure also prints a warning), `ThreadPool`, always `$true` (kept for scripts that check it), `Version`, the kit's version, and `StartMode`, how the kit starts programs here: `CreatedInJob` (inside the Job Object, the normal case), `AddedToJob` (started, then added to it just after) or `NoJob` (no cleanup if PowerShell is killed). It's the default for the session, not a promise for every program: one whose start can't be set up inside the Job Object falls back to `AddedToJob`, with a warning. +
+ +## How it fits together + +Two engines do the work: the process side runs external programs, and `Invoke-PkRunspaceJobs` runs PowerShell code. `Invoke-PkRun` is an optional wrapper around either one that turns Ctrl+C into a graceful abort. + +```mermaid +flowchart TB + subgraph run ["Invoke-PkRun (optional): graceful Ctrl+C, no idle sleep, QuickEdit off"] + B["Invoke-PkProcessBatch"] --> D["Invoke-PkProcessDispatch"] + D -->|"default starter"| S["Start-PkProcess"] + W["Invoke-PkProcessWithTimeout"] --> S + R["Invoke-PkRunspaceJobs"] --> P["Runspace pool running your worker script"] + end + S --> J["Each program inside the kit's Job Object, with a job of its own for killing its tree"] + P -.->|"a worker can call the process functions too"| D +``` -Each public function has built-in help: `Get-Help Invoke-PkProcessBatch -Full` shows its parameters, their defaults, what it returns and an example. +- `Invoke-PkProcessBatch` is a thin layer over the dispatcher: a flat list is one group. Both start programs through `Start-PkProcess` unless you give the dispatcher a starter of your own. +- Every program the kit starts goes into one Job Object, which Windows closes when PowerShell exits, killing whatever is still in it. Each program also gets a Job Object of its own, nested in that one, so a time limit or a force-stop kills it and everything it started at once. +- The runspace engine doesn't start programs itself, but worker code can call any of the process functions, the dispatcher included. +- All of them share one abort state (Ctrl+C, window close, `Request-PkAbort`) and one message handler. A worker's messages are queued and delivered on the main thread. ## Run a list of programs +`Invoke-PkProcessBatch` takes a list of commands, runs a set number at a time, and returns one result per command. + ```powershell # Any command-line tool works. cjxl is a JPEG XL image encoder. $commands = foreach ($f in Get-ChildItem *.png) { @@ -123,7 +206,10 @@ $batch = Invoke-PkRun { Invoke-PkProcessBatch @batchParams } Long parameter lists in these examples use splatting (`@batchParams`) instead of trailing backticks: it's easier to read, and a stray space after a backtick can't break it. -Each command is a hashtable with `FilePath`, `Arguments` and optionally `WorkingDirectory`, plus any keys of your own. Programs run hidden, with their output captured. +Each command is a hashtable with `FilePath`, `Arguments` and optionally `WorkingDirectory`, plus any keys of your own, which come back on its result. Programs run hidden, with their output captured. `-OnComplete` runs on the main thread as each command finishes. [Process results](#process-results) covers what comes back. + +
+Arguments and quoting, cmd.exe and .bat files `Arguments` is either one string, passed to the program exactly as written, or a list with one argument per element: `Arguments = @($in, $out)` works with spaces in the paths. With a list: @@ -134,20 +220,17 @@ Each command is a hashtable with `FilePath`, `Arguments` and optionally `Working Only the list form gets this quoting. A string, including one built with `ConvertTo-PkArgumentString`, is passed as written. -Programs run in your current location (`Get-Location`) unless a command says otherwise, and a relative `WorkingDirectory`, or a `FilePath` with a folder in it like `.\tools\cjxl.exe`, is relative to that location too. Drives PowerShell knows, like `~` or one made with `New-PSDrive`, work in both. A bare name like `cjxl.exe` is found the way Windows finds programs, mostly on `PATH`. Only an `.exe` is found without its extension (Windows doesn't use `PATHEXT` here), so a `.cmd` wrapper such as `npm` has to be written out: `npm.cmd`. A `.bat` or `.cmd` program can't run in a network-share (`\\server\share`) folder: `cmd.exe` falls back to `C:\Windows` there, so give such commands a local `WorkingDirectory`. +
-`Invoke-PkProcessBatch` returns an object with `Results`, `Aborted` and `ForceKilledCount`. Each result is an object with `Command`, `ExitCode`, `Stdout`, `Stderr`, `StreamTimedOut`, `StreamError`, `StartError`, `Aborted`, `TimedOut`, `Duration`, `StdoutDroppedChars` and `StderrDroppedChars`, every field always present, so `$batch.Results | Format-Table` reads well: +
+Where programs run and how they're found -- `Command` is your original command hashtable, so extra keys like `Source` above come back with it. -- `ExitCode` is whatever the program returned. The kit doesn't treat a non-zero code as a failure; that's for you to decide. -- `StartError` is set when the program couldn't be started (not found, say). Every command is still tried and gets its own result, but repeats of the same failure for the same program print once, with a count at the end. -- `Aborted` is `$true` for a command an abort killed or kept from starting. -- `TimedOut` is `$true` for a program `-TimeoutSeconds` killed. -- `Duration` is how long the program ran, from its start to its exit or kill, as a `[TimeSpan]`: not the time it waited for a slot, nor any wait for its output afterwards. It's `$null` for a command that never started. Sorting on it finds the slow ones: `$batch.Results | Sort-Object Duration -Descending | Select-Object -First 10`. -- `StdoutDroppedChars` and `StderrDroppedChars` count the characters `-MaxOutputChars` left out of each stream; 0 when nothing was, or with no cap. -- `StreamTimedOut` means the output read gave up 15 seconds after the program exited (`-StreamTimeoutMs` changes that, in milliseconds; 0 doesn't wait), on stdout, stderr or both, which only happens when a program it started is still holding the output open. Each stream comes back with what arrived before then: one held open is cut short, the other is whole. The read of a held stream carries on in the background until that program lets go of it; it's in the kit's Job Object, so that's when PowerShell exits at the latest. Until then that read keeps a thread of its own, one per held stream, so other programs' output isn't held up behind it, and drops what it reads, so a program that keeps writing doesn't fill memory with output nobody can get. What came back is that stream's text from then on, so calling `Complete-PkProcess` again on the same job returns the same text, and so does the read task's `Result` once the stream ends. `StreamError` means a read failed, and that stream comes back `$null`; it can be set alongside `StreamTimedOut` when the other stream was held open. While a program's output is held open, its command keeps its slot, but the other commands carry on: they keep starting, finishing and being killed at their time limits, and an abort is acted on at once. If an abort's wait for running programs ends while one is still waiting for its output, it gets what has arrived, with `StreamTimedOut`, rather than counting as force-stopped. +Programs run in your current location (`Get-Location`) unless a command says otherwise, and a relative `WorkingDirectory`, or a `FilePath` with a folder in it like `.\tools\cjxl.exe`, is relative to that location too. Drives PowerShell knows, like `~` or one made with `New-PSDrive`, work in both. A bare name like `cjxl.exe` is found the way Windows finds programs, mostly on `PATH`. Only an `.exe` is found without its extension (Windows doesn't use `PATHEXT` here), so a `.cmd` wrapper such as `npm` has to be written out: `npm.cmd`. A `.bat` or `.cmd` program can't run in a network-share (`\\server\share`) folder: `cmd.exe` falls back to `C:\Windows` there, so give such commands a local `WorkingDirectory`. -`Results` is in the order commands finished, not the order you gave them. Use `Command` to match them up, or give each command your own key (`Index = $n`) and sort on it: `$batch.Results | Sort-Object { $_.Command.Index }`. +
+ +
+Defaults, time limits and output caps `-OnComplete` runs as each command finishes, but only for commands that actually ran. Check `Results` for the ones that couldn't start or were aborted. A progress counter driven from `-OnComplete` won't reach the total if any did, so count from `$batch.Results` afterwards for the final numbers. Defaults: `-MaxConcurrent` 4, `-AbortTimeoutSeconds` 60 (how long Ctrl+C waits for running programs), `-TimeoutSeconds` 0 (no limit). The runspace engine's names, `-MaxParallel` and `-DrainTimeoutSeconds`, work here too, and on the dispatcher. @@ -155,12 +238,95 @@ Programs run in your current location (`Get-Location`) unless a command says oth `-MaxOutputChars 100000` keeps at most 100,000 characters of each program's stdout and stderr. Past that, the first half and the last half are kept, so the start and the end of a long log are both there, and `StdoutDroppedChars` / `StderrDroppedChars` say how many characters were left out. The rest is still read, so the program never stalls on a full pipe. The default, 0, keeps everything. A command's own `MaxOutputChars` key overrides it; 0 opts that command out. `Start-PkProcess`, `Invoke-PkProcessWithTimeout` and the dispatcher take it too. +Both per-command keys go on the command itself, for example one that keeps all of its output and gets 30 seconds: `@{ FilePath = 'tool.exe'; Arguments = @('x'); MaxOutputChars = 0; TimeoutSeconds = 30 }`. + +`-StreamTimeoutMs` (default 15000) is how long to wait for a program's output after it exits; see `StreamTimedOut` in [Process results](#process-results). + +
+ +
+Output encoding + Output is decoded in the console's code page unless you say otherwise, which is right for Windows' own tools. Many cross-platform tools write UTF-8 instead, and their non-ASCII output (accented or Japanese file names, say) comes back garbled. Pass `-OutputEncoding 'utf-8'` for the whole batch, or put an `OutputEncoding` key on one command. It also takes a code page number (`65001`, `437`, or the same as a string, as read from a CSV or config file) or a `[System.Text.Encoding]`, and the same option exists on `Invoke-PkProcessWithTimeout` and `Start-PkProcess` (and as a job key for the dispatcher's default starter). -`Invoke-PkRun { ... }` is what makes Ctrl+C graceful. Whatever the block outputs is passed through, so `$batch` above gets the batch result. It also stops the PC idle-sleeping until the run ends (`-KeepAwake $false` to opt out); the display can still turn off. Without `Invoke-PkRun` the engines still work, but Ctrl+C kills the script the normal way. See "Abort" below for what it means for your own code inside the braces. +
+ +
+What Invoke-PkRun adds + +`Invoke-PkRun { ... }` is what makes Ctrl+C graceful. Whatever the block outputs is passed through, so `$batch` above gets the batch result. It also stops the PC idle-sleeping until the run ends (`-KeepAwake $false` to opt out); the display can still turn off. Without `Invoke-PkRun` the engines still work, but Ctrl+C kills the script the normal way. See [Abort](#abort) for what it means for your own code inside the braces. + +
+ +## Process results + +`Invoke-PkProcessBatch` returns an object with `Results`, `Aborted` and `ForceKilledCount`. `Results` holds one object per command, with every field always present, so `$batch.Results | Format-Table` reads well. `Complete-PkProcess` and `Invoke-PkProcessWithTimeout` return the fields marked "all". + +| Field | From | What it means | +|---|---|---| +| `Command` | batch | Your original command hashtable, so extra keys like `Source` above come back with it. | +| `ExitCode` | all | Whatever the program returned. `$null` for a command that never started or that an abort killed. | +| `Stdout`, `Stderr` | all | The program's output, as text. Can be partial: see `StreamTimedOut`, `TimedOut` and the dropped counts. `$null` for a command that never started or that an abort killed, and for a stream whose read failed. | +| `StartError` | batch | Why the program couldn't be started (not found, say). Every command is still tried and gets its own result, but repeats of the same failure for the same program print once, with a count at the end. | +| `Aborted` | batch | `$true` for a command an abort killed or kept from starting. | +| `TimedOut` | batch | `$true` for a program `-TimeoutSeconds` killed. The dispatcher sets `$job['TimedOut']` instead. | +| `Duration` | all | How long the program ran, from its start to its exit or kill, as a `[TimeSpan]`. `$null` for a command that never started. | +| `StreamTimedOut` | all | The output read gave up `-StreamTimeoutMs` after the program exited, because a program it started still held the output open. | +| `StreamError` | all | A read failed; that stream comes back `$null`. | +| `StdoutDroppedChars`, `StderrDroppedChars` | all | How many characters `-MaxOutputChars` left out of each stream; 0 when nothing was, or with no cap. | + +Things that are easy to mix up: + +- **A non-zero exit code isn't a kit failure.** The kit doesn't judge exit codes; that's for you to decide. +- **A stream timeout isn't a time limit.** `StreamTimedOut` means the program had already exited, but something it started kept its output open. `TimedOut` means the program itself ran past `-TimeoutSeconds` and was killed. +- **A time limit isn't an abort.** A timed-out command gets its exit code and the output it wrote, goes through `-OnComplete`, and the rest of the batch carries on. An aborted one has no exit code or output and skips `-OnComplete`. +- **A command that never started has no `Duration`.** That covers a `StartError` and a command an abort kept from starting. +- **`Duration` is the program's time, not the command's.** It leaves out the wait for a slot and any wait for output after the exit. Sorting on it finds the slow ones: `$batch.Results | Sort-Object Duration -Descending | Select-Object -First 10`. + +`Results` is in the order commands finished, not the order you gave them. Use `Command` to match them up, or give each command your own key (`Index = $n`) and sort on it: `$batch.Results | Sort-Object { $_.Command.Index }`. + +
+A program's lifecycle + +A program can be done while its output isn't: whatever it started can hold its output open after it exits. This is the path one command takes: + +```mermaid +flowchart TD + Q["Queued: waiting for a slot"] -->|"abort before it starts"| A["Aborted, no Duration (dispatcher: JobAbortCleanup)"] + Q -->|"slot free"| S["Created suspended inside the Job Object, then resumed"] + S -->|"can't start"| E["StartError: no Duration"] + S --> R["Running: Duration counts from here"] + R -->|"exits"| D["Program done: Duration stops"] + R -->|"-TimeoutSeconds"| T["Killed with its tree: TimedOut"] + T --> D + R -->|"abort's force-stop"| K["Killed with its tree: Aborted, no output (dispatcher: JobAbortCleanup)"] + D --> O{"Both output streams closed?"} + O -->|"yes"| W["Result with all its output"] + O -->|"a program it started holds one open"| H["Waits up to -StreamTimeoutMs after the exit"] + H --> P["Result with StreamTimedOut and what arrived"] +``` + +During an abort's wait, running programs carry on as normal and end up with normal results. Only the ones still running when the wait ends, or when Ctrl+C is pressed again or the window closes, are force-stopped. + +
+ +
+When output is held open (StreamTimedOut in detail) + +`StreamTimedOut` means the output read gave up 15 seconds after the program exited (`-StreamTimeoutMs` changes that, in milliseconds; 0 doesn't wait), on stdout, stderr or both, which only happens when a program it started is still holding the output open. Each stream comes back with what arrived before then: one held open is cut short, the other is whole. + +The read of a held stream carries on in the background until that program lets go of it; it's in the kit's Job Object, so that's when PowerShell exits at the latest. Until then that read keeps a thread of its own, one per held stream, so other programs' output isn't held up behind it, and drops what it reads, so a program that keeps writing doesn't fill memory with output nobody can get. What came back is that stream's text from then on, so calling `Complete-PkProcess` again on the same job returns the same text, and so does the read task's `Result` once the stream ends. + +`StreamError` means a read failed, and that stream comes back `$null`; it can be set alongside `StreamTimedOut` when the other stream was held open. + +While a program's output is held open, its command keeps its slot, but the other commands carry on: they keep starting, finishing and being killed at their time limits, and an abort is acted on at once. If an abort's wait for running programs ends while one is still waiting for its output, it gets what has arrived, with `StreamTimedOut`, rather than counting as force-stopped. + +
## Run PowerShell code in parallel +`Invoke-PkRunspaceJobs` runs a worker script once per job, a set number at a time, and hands what each one returns to your result handler on the main thread. + ```powershell # Worker code can use cmdlets - see "The two rules" below for what it can't do. function Get-FileSha { @@ -187,31 +353,48 @@ $jobsParams = @{ $out = Invoke-PkRun { Invoke-PkRunspaceJobs @jobsParams } ``` -Each worker runs in its own runspace: a separate PowerShell session inside the same process, with its own variables and functions. That separation is what makes running them at the same time safe, and also why a worker can't see your script's variables or functions unless you hand them over. +Each worker runs in its own runspace: a separate PowerShell session inside the same process, with its own variables and functions. That separation is what makes running them at the same time safe, and also why a worker can't see your script's variables or functions unless you hand them over. Read [the two rules for worker code](#the-two-rules-for-worker-code) before writing one. + +
+Jobs, parameters and shared functions - Each job hashtable's keys become the worker's parameters. The worker's `param()` block must declare every key, and every job must supply each parameter it makes `[Parameter(Mandatory)]` (`CancelToken` aside, which is filled in). Either mistake is an error; with a fixed `-JobParams` list it's caught before any worker starts, and a `-NextJobProvider` job is checked as it arrives. A worker with parameter sets isn't checked for mandatory ones, since what it needs depends on the set. - If the worker declares a `$CancelToken` parameter, it gets the run's cancellation token. - `-JobParams` takes a list or array of job hashtables. A single hashtable works too, so a list that happens to hold one job is fine. - A worker runspace starts empty. Name every one of your functions it calls in `-SharedFunctionNames`. The kit's own worker functions are always there, and cmdlets and functions from installed modules load on their own. A module you imported by path isn't installed, so list its functions too (or put it on `$env:PSModulePath`). - Each job starts in your current location (the real folder, if you're on a `New-PSDrive` drive), in a fresh scope. A folder change or a variable one job makes, preference variables like `$ErrorActionPreference` included, doesn't carry over to the next job. Relative paths in .NET calls such as `[System.IO.File]::ReadAllText('x.txt')` still go by the process's working directory, as they do outside workers, so give .NET full paths. +- `-MaxParallel` has no default; you choose it. `-DrainTimeoutSeconds` (how long Ctrl+C waits for running workers) defaults to 60. The process engines' names, `-MaxConcurrent` and `-AbortTimeoutSeconds`, work here too. + +
+ +
+Results, callbacks and lazy jobs + - Whatever the worker returns is handed to `-ResultHandler` on the main thread, once per object returned, in the order workers finish. Return something that identifies the job with each result, as the example's `Path` does. - `-NextJobProvider { ... }` can replace `-JobParams` to produce jobs lazily: it's called on the main thread for the next job hashtable, and returns `$null` when there are no more. Each call outputs one job or `$null`, and nothing else. Only the last value counts: if it's `$null` the run ends, otherwise the last hashtable is the job. Anything else is ignored, with a warning. - `-PollCallback { ... }` runs on the main thread on every loop pass, for progress display and the like. That's at least every 0.1 s, and can be many times more often when jobs finish quickly, so keep it cheap. +- If `-ResultHandler`, `-PollCallback` or `-NextJobProvider` throws, the run stops: workers still going are told to stop and the exception comes out of the call. +- Returns an object with `ForceStoppedCount`, `CrashedCount`, `Aborted`, `Crashed` and `Errors`. `ForceStoppedCount` is how many workers an abort stopped waiting for; one stuck in a .NET call keeps running (see [Limits](#limits)). `Crashed` lists the `Job` and `Error` of each worker that threw. `Errors` lists the `Job` and `Error` of each non-terminating error a worker wrote, including any written before it threw. A force-stopped worker is in neither list. Every entry is kept until the call returns, so a worker that can write thousands of errors (walking a tree of folders it can't read, say) should handle them itself, e.g. with `-ErrorAction SilentlyContinue -ErrorVariable`. + +
+ +
+Errors and crashed workers + - `-JobCrashedHandler { param($err, $job) ... }` is told when a worker throws, including while an abort waits for running workers, with the job hashtable that crashed. Leave `$job` out of `param()` if you don't need it. `$err.Exception.InnerException` is the worker's own error. That job's result handler isn't called, and anything the worker output before throwing is lost. If the handler itself throws, that's reported as a message and the run carries on. -- Only an error that stops the worker counts as a crash: `throw`, a cmdlet with `-ErrorAction Stop`, or any error once the worker sets `$ErrorActionPreference = 'Stop'`. A non-terminating error (a locked file in `Get-FileHash`, a `Write-Error`), or an exception from a .NET method such as `[System.IO.File]::ReadAllText(...)`, only ends that one statement. It's printed as `Runspace error: ...` and recorded in the result's `Errors` list with its job, and whatever the worker returned still goes to `-ResultHandler` as if it had worked. Workers start with PowerShell's default preferences and no strict mode, whatever your script uses. To catch every failure and know which input it came from, have the worker return its own error object: +- Only an error that stops the worker counts as a crash: `throw`, a cmdlet with `-ErrorAction Stop`, or any error once the worker sets `$ErrorActionPreference = 'Stop'`. On 5.1, though, functions from script modules only see a preference set at the top level of a script, and a worker always runs in a scope of its own. `Get-FileHash` is one of those functions on 5.1 (it's a compiled cmdlet on 7), so give it, and commands like it, `-ErrorAction Stop` as well. A non-terminating error (a locked file in `Get-FileHash`, a `Write-Error`), or an exception from a .NET method such as `[System.IO.File]::ReadAllText(...)`, only ends that one statement. It's printed as `Runspace error: ...` and recorded in the result's `Errors` list with its job, and whatever the worker returned still goes to `-ResultHandler` as if it had worked. Workers start with PowerShell's default preferences and no strict mode, whatever your script uses. To catch every failure and know which input it came from, have the worker return its own error object: ```powershell WorkerScript = { param($Path) $ErrorActionPreference = 'Stop' - try { [pscustomobject]@{ Path = $Path; Hash = (Get-FileHash -LiteralPath $Path).Hash; Error = $null } } + try { [pscustomobject]@{ Path = $Path; Hash = (Get-FileHash -LiteralPath $Path -ErrorAction Stop).Hash; Error = $null } } catch { [pscustomobject]@{ Path = $Path; Hash = $null; Error = $_.Exception.Message } } } ``` - Don't call `exit` in a worker. It ends that job quietly (not as a crash) and sets your whole script's exit code. -- `-MaxParallel` has no default; you choose it. `-DrainTimeoutSeconds` (how long Ctrl+C waits for running workers) defaults to 60. The process engines' names, `-MaxConcurrent` and `-AbortTimeoutSeconds`, work here too. -- If `-ResultHandler`, `-PollCallback` or `-NextJobProvider` throws, the run stops: workers still going are told to stop and the exception comes out of the call. -- Returns an object with `ForceStoppedCount`, `CrashedCount`, `Aborted`, `Crashed` and `Errors`. `ForceStoppedCount` is how many workers an abort stopped waiting for; one stuck in a .NET call keeps running (see Limits). `Crashed` lists the `Job` and `Error` of each worker that threw. `Errors` lists the `Job` and `Error` of each non-terminating error a worker wrote, including any written before it threw. A force-stopped worker is in neither list. Every entry is kept until the call returns, so a worker that can write thousands of errors (walking a tree of folders it can't read, say) should handle them itself, e.g. with `-ErrorAction SilentlyContinue -ErrorVariable`. + +
## The two rules for worker code @@ -224,69 +407,150 @@ Worker code is the worker script, every function in `-SharedFunctionNames`, and Everything else is fine in a worker, cmdlets included. Callbacks that run on the main thread (`-ResultHandler`, `-PollCallback`, `-NextJobProvider`, `-OnComplete`, the message handler) are not worker code and can use anything. +
+How the kit checks them + `Invoke-PkRunspaceJobs` checks both rules before it starts anything, and refuses to launch code that breaks them, naming the line or the job key. Pass `-CheckWorkerSafety:$false` to turn that off. The code check is also available on its own as `Test-PkWorkerSafety -WorkerScript $w -SharedFunctionNames $names`, which returns a list of findings (including functions the worker calls but you didn't share), for use in your own tests. For rule 2 it flags written casts, and scriptblocks passed into a .NET method or constructor, either written in the call or through a variable they were assigned to. `# pk:ignore` on a line accepts a finding. Storing a scriptblock in a collection (`$list.Add($sb)`, `$queue.Enqueue($sb)`) isn't flagged, since that makes no delegate. It can't see commands run through a variable (`& $cmd`), a collection typed to hold delegates (`List[Func[object]]`, whose `.Add` converts), or a scriptblock buried more than three levels deep in a job value. -### Why these rules exist +
+ +
+Why these rules exist Both were found chasing real, intermittent failures, and neither is in Microsoft's documentation as far as we could find. - **`$script:` variables.** A function listed in `-SharedFunctionNames` is recreated inside the worker from its source text, so it's no longer attached to your script and its `$script:` points somewhere else. Inside a `.GetNewClosure()` block, `$script:` points at a private copy. Either way the read comes back empty, with no error. - **Scriptblocks.** A scriptblock belongs to the runspace that created it, and runs against that runspace's session state wherever it's called from ([PowerShell issue #4003](https://github.com/PowerShell/PowerShell/issues/4003)). When a delegate makes .NET call one from another runspace's thread, PowerShell can hand the call back to the owning runspace's thread. If that thread is itself waiting, and the scriptblock runs another scriptblock inside it (a `Where-Object { }` filter, a nested delegate), it deadlocks. Even when it doesn't deadlock, two threads using one session state at once can crash the process. A scriptblock passed in as a job value is the same case: in stress tests, 8 workers running one passed from the main thread broke 88 of 90 runs, usually by corrupting the main thread's session state so the kit's own functions vanished mid-run, even when the scriptblock held nothing but .NET calls. Passed as text and rebuilt in the worker, the same code ran clean in all 30 runs. +
+ ## Process dispatch with groups -`Invoke-PkProcessBatch` covers a flat list. `Invoke-PkProcessDispatch` is the engine under it, for work that comes in groups (a folder of files, say) where something should happen when each group finishes: +`Invoke-PkProcessBatch` covers a flat list. `Invoke-PkProcessDispatch` is the engine under it, for work that comes in groups (a folder of files, say) where something should happen when each group finishes. This example converts each subfolder's PNGs to lossless JPEG XL, retries a failed file once, and zips each folder whose files all converted: ```powershell +. "$PSScriptRoot\ParallelKit.ps1" + +# One group per subfolder of D:\Scans: convert its PNGs to lossless JPEG XL, then zip each finished folder. +$folders = [System.Collections.Generic.Queue[object]]::new() +foreach ($d in Get-ChildItem -LiteralPath 'D:\Scans' -Directory) { $folders.Enqueue($d) } +$failed = @{} # folder path -> how many of its files didn't convert + $dispatchParams = @{ - MaxConcurrent = 6 - GroupProvider = { <# next group object, or $null when done #> } - JobBuilder = { param($group) <# hashtable job(s): @{ FilePath; Arguments; WorkingDirectory; ... } #> } - JobFinalize = { param($job, $pending) $r = Complete-PkProcess -Job $job; <# ... #> } - JobAbortCleanup = { param($job) <# delete a killed job's partial output #> } - GroupCompleteCallback = { param($group) <# e.g. zip the folder #> } + MaxConcurrent = 6 + GroupProvider = { + # The next folder, or $null when there are none left. Called as the run needs more work, a few folders ahead. + if ($folders.Count -eq 0) { return $null } + return $folders.Dequeue() + } + JobBuilder = { + param($folder) + # One job per PNG. A folder's files are listed only when its turn comes. + $failed[$folder.FullName] = 0 + foreach ($f in Get-ChildItem -LiteralPath $folder.FullName -Filter *.png -File) { + $out = [System.IO.Path]::ChangeExtension($f.FullName, '.jxl') + @{ FilePath = 'cjxl.exe'; Arguments = @($f.FullName, $out, '-d', '0'); Out = $out; Tries = 1 } + } + } + JobFinalize = { + param($job, $pending) + $r = Complete-PkProcess -Job $job + if ($r.ExitCode -eq 0) { return } + if ($job.Tries -lt 2) { + # A follow-up job: one more try. It joins the same folder, which isn't complete until it's done. + $pending.Enqueue(@{ FilePath = $job.FilePath; Arguments = $job.Arguments; Out = $job.Out; Tries = $job.Tries + 1 }) + return + } + $failed[$job.Group.FullName]++ + Write-PkMessage "FAILED: $($job.Out)" -Level Error + } + JobAbortCleanup = { + param($job) + # An abort killed this conversion, or kept it from starting. Only one that started can have left a partial file. + if ($null -ne $job.Proc) { Remove-Item -LiteralPath $job.Out -ErrorAction SilentlyContinue } + } + GroupCompleteCallback = { + param($folder) + # Also runs for a folder an abort cut short: don't zip a partial set. + if ((Test-PkCancelRequested) -or $failed[$folder.FullName] -gt 0) { return } + $converted = @(Get-ChildItem -LiteralPath $folder.FullName -Filter *.jxl -File) + if ($converted.Count -gt 0) { + Compress-Archive -LiteralPath $converted.FullName -DestinationPath "$($folder.FullName).zip" -Force + } + } +} +$dispatch = Invoke-PkRun { Invoke-PkProcessDispatch @dispatchParams } + +foreach ($g in $dispatch.GroupResults) { + if ($g.Aborted) { Write-Warning "$($g.GroupInfo.Name): cut short by Ctrl+C, not zipped" } + elseif ($failed[$g.GroupInfo.FullName] -gt 0) { Write-Warning "$($g.GroupInfo.Name): $($failed[$g.GroupInfo.FullName]) file(s) failed, not zipped" } } -$dispatch = Invoke-PkProcessDispatch @dispatchParams ``` -All of these callbacks run on whichever thread called the dispatcher: the main thread normally, or the worker if you call it from inside a runspace job (in which case the worker rules apply to them). +All of these callbacks run on whichever thread called the dispatcher: the main thread normally, or the worker if you call it from inside a runspace job (in which case the worker rules apply to them). The dispatcher returns an object with `GroupResults`, `Aborted`, `ForceKilledCount` and `JobStarterFailedCount`. `GroupResults` holds one object with `GroupInfo`, `Completed` and `Aborted` per group, where `GroupInfo` is the group value. + +
+Groups and the group provider - **`-GroupCompleteCallback` also runs for a group an abort cut short**, so you can record the jobs in it that did finish. Before doing anything irreversible there (zipping the folder, deleting sources), check `Test-PkCancelRequested` (or your own `-CancelToken`) and skip it if true. -- `-JobFinalize` is called once per finished job. Collect its exit code and output there with `Complete-PkProcess -Job $job`; the dispatcher disposes the process right after. With the default `-JobPollCompleted`, a job is finished once its program has exited and its output has been read, or `-StreamTimeoutMs` after the exit (15 seconds by default) when a program it started holds the output open (the job keeps its slot meanwhile, and the other jobs carry on), so `Complete-PkProcess` there has nothing left to wait for: given no `-StreamTimeoutMs` of its own, it uses the dispatcher's. A longer one there waits only the rest, but on the dispatch loop's own thread, holding up the other jobs; to wait less, set the dispatcher's `-StreamTimeoutMs` instead. With your own `-JobPollCompleted`, `Complete-PkProcess` waits as it does anywhere else. - Groups are pulled lazily, at most `-MaxQueueAhead` (default 3) ahead. - A group can be any value: a hashtable, a path, a name. Each job gets its group as `$job.Group`. - Each `-GroupProvider` call outputs exactly one group, or `$null` to end, and nothing else: `return $group`, `return ,@('a', 'b', 'c')` for a list as one group (the comma keeps a one-item list a list), or `return $null`. Anything else it lets out (an `ArrayList.Add` index, say) becomes part of the group, so discard it with `$null = ...`. Output that ends in `$null` is taken as the end, with a warning, so a list group can't end in `$null`. -- The dispatcher keeps its state on the job hashtables. Don't use these names for your own job fields: `GroupKey`, `SlotReleased`, `Proc`, `StdoutTask`, `StderrTask`, `Stopwatch`, `TimeLimit`, `TimedOut`, `StartFailureReported`, `OutputWait`, `OutputWaitOver`, `OutputWaitMs`. (`Group` is yours if you set it yourself.) -- `-TimeoutSeconds 600` kills a job's program, and anything it started, if it's still running after 10 minutes. The default, 0, means no limit, and it can be fractional. A job's own `TimeoutSeconds` key overrides it; 0 opts the job out, and a bad value is a failed start. `-MaxOutputChars` works the same way, with a job's `MaxOutputChars` key, for the default starter. The killed job still goes through `-JobFinalize`, where `$job['TimedOut']` is `$true`, and other jobs carry on. The limit stays in force while an abort waits for running jobs. A retry gets a fresh clock. A job whose `.Proc` isn't a process isn't timed: `-JobPollCompleted` is the place for its limit. +- `-GroupReleaseCheck { param($group) }` makes a group with zero jobs keep its queue-ahead slot until the check returns true. Use it to stop one dispatcher racing ahead of another that it's paired with. The dispatcher doesn't return until every held group has been released, unless the run is canceled or aborted. It runs on every loop pass, so keep it cheap. Only its last output value counts, so a stray value written before the answer doesn't release the group. + +
+ +
+Jobs: finalizing, retries, time limits and reserved names + +- `-JobFinalize` is called once per finished job. Collect its exit code and output there with `Complete-PkProcess -Job $job`; the dispatcher disposes the process right after. + - **When a job counts as finished** (with the default `-JobPollCompleted`): once its program has exited and its output has been read. + - **When the output is held open** by a program it started: the job counts as finished `-StreamTimeoutMs` after the exit (15 seconds by default). It keeps its slot until then, and the other jobs carry on. + - **`Complete-PkProcess` in `-JobFinalize`** has nothing left to wait for, so it returns at once. Given no `-StreamTimeoutMs` of its own, it uses the dispatcher's. A longer one there waits only the difference, but on the dispatch loop's own thread, holding up the other jobs. To wait less, set the dispatcher's `-StreamTimeoutMs` instead. + - **With your own `-JobPollCompleted`**, none of this applies: `Complete-PkProcess` waits as it does anywhere else. - To retry a job or add follow-up work, enqueue job hashtables onto `$pending` inside `-JobFinalize`. They join the same group, and the group isn't complete until they've all finished. A retry can start within milliseconds of the failure, so cap the number of retries, and don't count on the gap for something like a locked file to clear. +- `-JobAbortCleanup { param($job) }` is called for each job an abort killed or kept from starting, to remove its partial output. +- `-TimeoutSeconds 600` kills a job's program, and anything it started, if it's still running after 10 minutes. The default, 0, means no limit, and it can be fractional. A job's own `TimeoutSeconds` key overrides it; 0 opts the job out, and a bad value is a failed start. `-MaxOutputChars` works the same way, with a job's `MaxOutputChars` key, for the default starter. The killed job still goes through `-JobFinalize`, where `$job['TimedOut']` is `$true`, and other jobs carry on. The limit stays in force while an abort waits for running jobs. A retry gets a fresh clock. A job whose `.Proc` isn't a process isn't timed: `-JobPollCompleted` is the place for its limit. +- The dispatcher keeps its state on the job hashtables. Don't use these names for your own job fields: `GroupKey`, `SlotReleased`, `Proc`, `StdoutTask`, `StderrTask`, `Stopwatch`, `TimeLimit`, `TimedOut`, `StartFailureReported`, `OutputWait`, `OutputWaitOver`, `OutputWaitMs`. (`Group` is yours if you set it yourself.) + +
+ +
+Custom starters, polling and sharing a limit + - Supply `-JobStarter { param($job) ... }` to start jobs yourself. It must set `$job.Proc` and should return the job. A starter that is just `Start-PkProcess ...` works too: its result is folded into your job. Throw to report a job that couldn't start. -- Whatever your callbacks output is thrown away, apart from the return values listed here. Where a callback returns something, output only that: `-JobPollCompleted` and `-GroupReleaseCheck` go by their last value and `-JobBuilder` ignores anything that isn't a job hashtable, but a stray value from `-GroupProvider` becomes part of the group. -- `-MaxConcurrent` can be a `SemaphoreSlim` shared by several dispatchers that must stay under one combined limit. It works inside workers, so two runspace jobs can each run a dispatcher against one shared budget. -- `-GroupReleaseCheck { param($group) }` makes a group with zero jobs keep its queue-ahead slot until the check returns true. Use it to stop one dispatcher racing ahead of another that it's paired with. The dispatcher doesn't return until every held group has been released, unless the run is canceled or aborted. It runs on every loop pass, so keep it cheap. Only its last output value counts, so a stray value written before the answer doesn't release the group. - `-JobPollCompleted { param($job) }` replaces the default "has the process exited" check. Use it for a custom starter whose job isn't a plain process. Only its last output value counts, so a stray value written before the answer doesn't mark the job done. - `-PollCallback { param($runningJobs) }` runs on every loop pass, with the jobs currently running (`-AbortPollCallback`, its name before 3.0, also works). That's about every 50 ms, and can be many times more often when programs finish quickly, so keep it cheap. +- `-MaxConcurrent` can be a `SemaphoreSlim` shared by several dispatchers that must stay under one combined limit. It works inside workers, so two runspace jobs can each run a dispatcher against one shared budget. - `-CancelToken` stops the dispatcher when canceled. An abort stops it either way, without canceling your token. +- Whatever your callbacks output is thrown away, apart from the return values listed here. Where a callback returns something, output only that: `-JobPollCompleted` and `-GroupReleaseCheck` go by their last value and `-JobBuilder` ignores anything that isn't a job hashtable, but a stray value from `-GroupProvider` becomes part of the group. - An exception from one of your callbacks stops the dispatcher: running processes are killed and the exception is rethrown. -- Returns an object with `GroupResults`, `Aborted`, `ForceKilledCount` and `JobStarterFailedCount`. `GroupResults` holds one object with `GroupInfo`, `Completed` and `Aborted` per group, where `GroupInfo` is the group value. -Callbacks: a plain `{ ... }` callback sees your variables and functions from where you called the kit, not the kit's internals, so `.GetNewClosure()` isn't needed for that, inside a worker runspace or out. The one exception is inside a worker, where it can also see the kit's own variables, which all start with `pk`, so don't give yours names starting with `pk`. Keep any state a callback changes in a hashtable (`$state = @{ Count = 0 }`, then `$state.Count++`). A plain variable assigned inside a callback doesn't stick between calls. A `.GetNewClosure()` block can't see functions your script defines when the script is run from a prompt (`.\script.ps1`); the kit's own functions always work, but define any of yours that a closure calls as `function global:Get-Thing { ... }`. +
+ +
+What callbacks can see, and leaving one early + +A plain `{ ... }` callback sees your variables and functions from where you called the kit, not the kit's internals, so `.GetNewClosure()` isn't needed for that, inside a worker runspace or out. The one exception is inside a worker, where it can also see the kit's own variables, which all start with `pk`, so don't give yours names starting with `pk`. Keep any state a callback changes in a hashtable (`$state = @{ Count = 0 }`, then `$state.Count++`). A plain variable assigned inside a callback doesn't stick between calls. A `.GetNewClosure()` block can't see functions your script defines when the script is run from a prompt (`.\script.ps1`); the kit's own functions always work, but define any of yours that a closure calls as `function global:Get-Thing { ... }`. To leave any callback early, use `return`. PowerShell sends a `continue` or `break` to the nearest loop, which for a callback is one of the kit's own, so the kit catches them and treats them as `return`, with a warning (once per callback per call, or once per message handler). A labeled `break` to a loop of yours (`break outer`) does leave the kit's call: it stops there, kills the programs it started and returns nothing. +
+ ## Single processes +For one program at a time, outside the engines. All of these are safe in worker code. + | Function | Use | |---|---| -| `Invoke-PkProcessWithTimeout -FilePath -Arguments -TimeoutMs` | Run one program and wait, with a hard time limit (default 60s). Returns an object with `ExitCode`, `Stdout`, `Stderr`, `StreamTimedOut`, `StreamError`, `Duration`, `StdoutDroppedChars` and `StderrDroppedChars`. If it overruns, or the run is aborted, the program is killed and this **throws**; add `-IgnoreAbort` for a cleanup step that must finish anyway. | +| `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**; add `-IgnoreAbort` for a cleanup step that must finish 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`. | | `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`. | -| `Stop-PkProcessTree -Process` | Kill one or more programs and every program they started. A program the kit started is killed through its own Job Object, which also reaches a child whose parent has already exited; anything else goes to `taskkill /T` (as few calls as Windows' command-line limit allows). For one program, returns `$true` if it killed it (even if part of its tree couldn't be) and `$false` if it had already exited. | - -`Invoke-PkProcessWithTimeout` and `Start-PkProcess` also take `-WorkingDirectory`. +| `Stop-PkProcessTree -Process` | Kill one or more programs and every program they started. A program the kit started is killed through its own Job Object, which also reaches a child whose parent has already exited; anything else goes to `taskkill /T` (as few calls as Windows' command-line limit allows), and if `taskkill` can't start, fails or hangs, only the listed programs are killed. For one program, returns `$true` if it killed it (even if part of its tree couldn't be) and `$false` if it had already exited. See [Process-tree cleanup limitations](#process-tree-cleanup-limitations). | -All of these are safe in worker code. +`Invoke-PkProcessWithTimeout` and `Start-PkProcess` also take `-WorkingDirectory`. Wrapped in `Invoke-PkRun`, `Invoke-PkProcessWithTimeout` makes Ctrl+C kill the program and throw, instead of the whole script dying. ## Messages @@ -305,7 +569,7 @@ Inside `Invoke-PkRun { ... }`, Ctrl+C: 1. stops new jobs from starting, 2. cancels the run's token (`Test-PkCancelRequested` turns true in workers), 3. waits for in-flight work (`-AbortTimeoutSeconds`, default 60; every engine also takes it as `-DrainTimeoutSeconds`), -4. force-stops whatever is left, calling `-JobAbortCleanup` for each killed or never-started process job. +4. force-stops whatever is left. The batch marks each killed or never-started command's result `Aborted`; the group dispatcher calls `-JobAbortCleanup` for each such job. Press Ctrl+C again to skip step 3: whatever is still running is force-stopped right away, and your script carries on. A third press stops the script the way Ctrl+C normally does, and the kit's engines still kill the programs they started. Presses less than a second apart count as one, and Ctrl+Break works the same as Ctrl+C. @@ -317,10 +581,15 @@ Three things to know: - **An abort stays in force until it's reset.** `Invoke-PkRun` resets it at the start of each run. If you call an engine again outside `Invoke-PkRun` after an abort, it returns right away with `Aborted = $true`. Call `Reset-PkAbortState` first if you mean to carry on. - **Your script carries on after an abort.** The engines return with `Aborted = $true` and the rest of your script runs. If an abort should end it, say so: `if ($batch.Aborted) { exit 1 }`. +
+QuickEdit, and the other abort functions + `Invoke-PkRun` also turns off the console's QuickEdit mode for the length of the run (`-DisableQuickEdit $false` to opt out). With QuickEdit on in the classic console window, one stray click starts a text selection, and the script freezes at its next console write until the selection is cleared. That looks exactly like a hang. It's turned back on afterwards if it was on before. Other pieces: `Request-PkAbort` triggers the same abort from code. `Test-PkAbortSignal` asks whether one is under way. `Register-PkCancellationSource` adds your own `CancellationTokenSource` to the set an abort cancels, and `Unregister-PkCancellationSource` takes it back out (a `-Cts` you pass to `Invoke-PkRunspaceJobs` is added automatically; a `-CancelToken` you pass to the dispatcher isn't canceled by an abort, but the dispatcher stops either way). `Get-PkAbortTriggerLabel` says which kind of abort it was. +
+ ## 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. @@ -329,26 +598,30 @@ Other pieces: `Request-PkAbort` triggers the same abort from code. `Test-PkAbort ## Limits -- Windows only (console and Job Object APIs). Built for Windows PowerShell 5.1; PowerShell 7 on Windows passes the same test suite. +- Windows only (console and Job Object APIs), on Windows PowerShell 5.1 or PowerShell 7. - Run it in a PowerShell console window or an editor's terminal (graceful Ctrl+C tested in Windows Terminal, Visual Studio's built-in terminal and VS Code's terminal, including the PowerShell extension's). The Windows PowerShell ISE isn't supported: tested there, the kit loads and runs, but the ISE has no console, so Ctrl+C stops the script outright, with no graceful drain and no cleanup callbacks. - It needs FullLanguage mode, since it compiles a little C# with `Add-Type` when loaded. On a machine locked down to Constrained Language Mode (usually by AppLocker or Windows Defender Application Control), loading it fails with a message saying so. Some endpoint security products also flag scripts that compile code calling Windows APIs at runtime; if yours blocks the kit, that's the likely reason. - After changing `ParallelKit.ps1` itself, start a new PowerShell window. A session keeps the kit's compiled parts until it closes; the kit tells you if it finds an older copy loaded. -- One run at a time per process. The abort state is shared. A nested `Invoke-PkRun` just runs inside the outer one. +- Only one outer `Invoke-PkRun` abort scope can exist per PowerShell process. Nested calls reuse the existing scope. Multiple dispatchers can run concurrently where supported; they share the process-wide abort state and can share a `SemaphoreSlim` to enforce a combined concurrency limit. - A worker stuck inside a long .NET call can't be interrupted. Force-stop stops waiting for it and returns. The worker is NOT killed: once that call returns it can carry on to the end of its script. Before any step that can't be undone (deleting a source file, say), have the worker check `Test-PkCancelRequested` and skip the step if it's true. - Programs run hidden, and there's no way to send them input. A program that stops to ask a question will sit there until it's killed. - 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. +- Child-process cleanup has the gaps listed under [Process-tree cleanup limitations](#process-tree-cleanup-limitations). ## Testing -`ParallelKit.Harness.ps1` is the test suite. It isn't needed at runtime. Run it in a fresh window (see "Limits" above): +`ParallelKit.Harness.ps1` is the test suite. It isn't needed at runtime. It uses real runspaces and real child processes (`cmd.exe`, `ping.exe`), with nothing mocked. Run it in a fresh window (see [Limits](#limits)): ```powershell powershell -NoProfile -File .\ParallelKit.Harness.ps1 ``` -It uses real runspaces and real child processes (`cmd.exe`, `ping.exe`), with nothing mocked, so it takes two to three minutes. It prints a `[PASS]`/`[FAIL]` line per check and exits 0 only if everything passed. A few checks send real Ctrl+C, Ctrl+Break and window-close events to child PowerShell processes in hidden consoles of their own, never to yours. Where a machine can't deliver those, they print `[SKIP]` with the reason instead; set `PK_HARNESS_NO_SKIP=1` to count skips as failures. A few `message handler failed` lines in the output are expected: some checks break the message handler on purpose to test the fallback. +
+What it prints, and the stress tests in Testing/ + +It takes about three and a half minutes. It prints a `[PASS]`/`[FAIL]` line per check and exits 0 only if everything passed. A few checks send real Ctrl+C, Ctrl+Break and window-close events to child PowerShell processes in hidden consoles of their own, never to yours. Where a machine can't deliver those, they print `[SKIP]` with the reason instead; set `PK_HARNESS_NO_SKIP=1` to count skips as failures. A few `message handler failed` lines in the output are expected: some checks break the message handler on purpose to test the fallback. -GitHub runs the same harness on Windows PowerShell 5.1 and on PowerShell 7 for every pull request and every change to `main`. +GitHub runs the same harness on Windows PowerShell 5.1 and on PowerShell 7 for every pull request and every change to `main`. The harness is the only thing GitHub runs: the scripts in `Testing/` below are run by hand. `Testing/` holds the longer stress tests and checks behind some of what this README says. They aren't part of the test suite and aren't needed to use the kit: @@ -362,22 +635,27 @@ GitHub runs the same harness on Windows PowerShell 5.1 and on PowerShell 7 for e ``` - `Testing/hosts/check-host.ps1` checks the kit in a host you choose, such as an editor's terminal or a scheduled task. -- `Testing/force-kill/run.ps1` checks [No orphans](#parallelkit): it starts `cmd /c ping` jobs, kills the PowerShell running them outright, and counts any `ping` left running. Expect none. +- `Testing/force-kill/run.ps1` checks the intro's process-tree cleanup claim: it starts `cmd /c ping` jobs, kills the PowerShell running them outright, and counts any `ping` left running. Expect none. - `Testing/stop-in-call/run.ps1` shows where PowerShell acts on a stop (a third Ctrl+C, or the runspace engine's force-stop): never inside a .NET call, which runs to the end, and only at the next function or cmdlet call. That's behind the Limits note on workers stuck in a .NET call. +- `Testing/readme-examples/run.ps1` runs this README's code examples, read straight from it, with and without StrictMode, and checks they do what it says. The group example also runs with both kinds of Ctrl+C. It needs `cjxl.exe` on `PATH`, since the examples use it. Under a minute. +- `Testing/ps7-native/run.ps1` shows, without the kit, what PowerShell 7 does in the cases [Who it's for](#who-its-for) lists: a killed script leaves its programs running, `ForEach-Object -Parallel -TimeoutSeconds` doesn't stop a running program, and Ctrl+C stops running programs at once. Run it with `pwsh`. About half a minute. - `Testing/soak/run.ps1` runs 15,000 programs and 6,000 runspace jobs, round by round, and fails if PowerShell's handles, threads or memory keep growing. It takes about three minutes. +
+ ## FAQ -**Can I use cmdlets in worker code?** +
+Can I use cmdlets in worker code? Yes. What a worker can't do is run a scriptblock that came from another runspace: one handed to .NET as a delegate, or one passed in as a job value. [The two rules](#the-two-rules-for-worker-code) cover it, and the kit checks for both before it starts. -**Do ThreadJob and PoshRSJob have the same scriptblock problem?** - -Yes, both. Neither one rebuilds or refuses a scriptblock you pass to a job (by `-ArgumentList` or `$using:`), so it still runs against your script's session state, just from the job's thread. [The two rules](#the-two-rules-for-worker-code) apply to them as well; they just don't check for you. `ForEach-Object -Parallel` does refuse a `$using:` scriptblock, and in [PowerShell issue #12378](https://github.com/PowerShell/PowerShell/issues/12378) a PowerShell team member wrote of that check: "this should also be disallowed for Start-ThreadJob." +
-What the tests showed +Do ThreadJob and PoshRSJob have the same scriptblock problem? + +Yes, both. Neither one rebuilds or refuses a scriptblock you pass to a job (by `-ArgumentList` or `$using:`), so it still runs against your script's session state, just from the job's thread. [The two rules](#the-two-rules-for-worker-code) apply to them as well; they just don't check for you. `ForEach-Object -Parallel` does refuse a `$using:` scriptblock, and in [PowerShell issue #12378](https://github.com/PowerShell/PowerShell/issues/12378) a PowerShell team member wrote of that check: "this should also be disallowed for Start-ThreadJob." In tests with 8 jobs, a scriptblock passed as a job value crashed PowerShell or broke the calling script (its own functions vanished mid-run) in nearly every run where the script was doing anything else at the same time. ThreadJob only got away with it when the script did nothing but sit in `Wait-Job` until the jobs finished. PoshRSJob never did, since `Start-RSJob` is itself PowerShell code that's still running while the first jobs start. A delegate made in your script was handed back to your script's thread to run. With ThreadJob that gave wrong results in some runs while the script was busy, and a deadlock in nearly every run while it waited in `Wait-Job`. With PoshRSJob it failed every time. Passed as text and rebuilt in the job, the same code ran clean every time. @@ -385,45 +663,61 @@ The test scripts and results are in [`Testing/third-party`](Testing/third-party)
-**Does it work in PowerShell 7, or on Linux or macOS?** +
+Does it work in PowerShell 7, or on Linux or macOS? -PowerShell 7 on Windows, yes: Windows PowerShell 5.1 is the main target, but the full test suite runs on both for every change. Linux and macOS are out, since Ctrl+C handling, child-process cleanup and keep-awake all use Windows APIs. On 7, `ForEach-Object -Parallel` is simpler for plain parallel PowerShell code; the kit is still useful for running external programs and for stopping cleanly on Ctrl+C. +PowerShell 7 on Windows, yes: the full test suite runs on 5.1 and 7 for every change, and [Who it's for](#who-its-for) says what the kit adds there. Linux and macOS are out, since Ctrl+C handling, child-process cleanup and keep-awake all use Windows APIs. + +
-**Does it need admin rights?** +
+Does it need admin rights? No. Nothing it does needs elevation. -**What happens to running programs when I press Ctrl+C?** +
-Inside `Invoke-PkRun`, no new ones start, and the running ones get up to 60 seconds by default to finish. Anything still running after that is killed, and `-JobAbortCleanup` is called for each so you can delete its partial output. Press Ctrl+C again to kill them right away instead of waiting. See [Abort](#abort). +
+What happens to running programs when I press Ctrl+C? -**And if the script is killed outright, from Task Manager say?** +Inside `Invoke-PkRun`, no new ones start, and the running ones get up to 60 seconds by default to finish. Anything still running after that is killed. The batch marks its result `Aborted`; the group dispatcher calls `-JobAbortCleanup` for it, so you can delete its partial output. Press Ctrl+C again to kill them right away instead of waiting. See [Abort](#abort). -The programs it started are killed with it, through a Windows Job Object. There's no waiting period and no cleanup callback in that case, so partial output files can be left behind. Each program is created inside the Job Object, so anything it starts is in it too, however soon. If the kit can't do that on some system (it relies on a private part of .NET), 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. `Initialize-ParallelKit`'s `StartMode` says which way it works. +
-**Can I show progress?** +
+And if the script is killed outright, from Task Manager say? -Yes. `-OnComplete` (batch) and `-PollCallback` (runspace jobs) run on the main thread, so `Write-Progress` or anything else works there. What you can't get is a program's output line by line while it runs: it's handed over when the program exits. +The programs it started are killed with it, through a Windows Job Object. There's no waiting period and no cleanup callback in that case, so partial output files can be left behind. Each program is created inside the Job Object, so anything it starts is in it too, however soon. If the kit can't do that on some system (it relies on a private part of .NET), 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. `Initialize-ParallelKit`'s `StartMode` says which way it works, and [Process-tree cleanup limitations](#process-tree-cleanup-limitations) lists the other cases. -**How many should I run at once?** +
-Start from the CPU core count and measure. [Choosing limits](#choosing-limits) has more. +
+Does a program I start get my Ctrl+C too? -**Can I pipe into it?** +No. Programs start without a window, in a hidden console of their own, so Ctrl+C in your window never reaches them. That's what lets them finish while the kit drains. When it does need to stop one (a timeout, or an abort's force-stop), the kit kills it along with anything it started, through a Job Object of the program's own, so even a child whose parent has already exited goes with it. -No. The engines take a list of hashtables (`-Commands`, `-JobParams`) rather than pipeline input, because each job needs several named values and the kit wants the whole list (or a provider for it) before it starts. Build the list with `foreach`, as the examples do: `$commands = foreach ($f in Get-ChildItem *.png) { @{ FilePath = ...; Arguments = ... } }`. +
-**Which functions are meant to be used?** +
+Can I show progress? -The ones in this README: the engines, the [single-process functions](#single-processes), and the abort and message functions named in their sections. Everything else is an internal helper that stays inside the module and can change between versions. +Yes. `-OnComplete` (batch), `-JobFinalize` and `-PollCallback` (group dispatcher), and `-PollCallback` (runspace jobs) run on the main thread, so `Write-Progress` or anything else works there. What you can't get is a program's output line by line while it runs: it's handed over when the program exits. -**Does a program I start get my Ctrl+C too?** +
-No. Programs start without a window, in a hidden console of their own, so Ctrl+C in your window never reaches them. That's what lets them finish while the kit drains. When it does need to stop one (a timeout, or an abort's force-stop), the kit kills it along with anything it started, through a Job Object of the program's own, so even a child whose parent has already exited goes with it. +
+How many should I run at once? -**Was this written by AI?** +Start from the CPU core count and measure. [Choosing limits](#choosing-limits) has more. + +
-It was built with Claude Code, as the top of this page says. The worker rules and abort behavior come from hangs and bugs reproduced in real runs, and the test harness runs real processes and runspaces, with nothing mocked, on every change. +
+Can I pipe into it? + +No. The engines take a list of hashtables (`-Commands`, `-JobParams`) rather than pipeline input, because each job needs several named values and the kit wants the whole list (or a provider for it) before it starts. Build the list with `foreach`, as the examples do: `$commands = foreach ($f in Get-ChildItem *.png) { @{ FilePath = ...; Arguments = ... } }`. + +
## Bugs and questions diff --git a/Testing/ps7-native/run.ps1 b/Testing/ps7-native/run.ps1 new file mode 100644 index 0000000..fc2b983 --- /dev/null +++ b/Testing/ps7-native/run.ps1 @@ -0,0 +1,162 @@ +# PowerShell 7 without the kit: what happens to programs run through +# ForEach-Object -Parallel in the cases the README's "Who it's for" lists? +# Nothing here loads ParallelKit. Each check runs a plain PowerShell 7 script, +# and passes when PowerShell behaves the way the README says it does: +# +# 1. Killed outright (taskkill /F, as Task Manager's End task does), the +# script's programs keep running. The kit's own check of this is +# Testing/force-kill, which expects none left. +# 2. -TimeoutSeconds doesn't stop a program that's already running: the +# call returns only once the programs have ended on their own. +# 3. Ctrl+C stops the script and its running programs at once, even ones +# that ignore Ctrl+C themselves: no wait for running work, and no +# cleanup step for what was stopped. +# +# pwsh -NoProfile -File .\Testing\ps7-native\run.ps1 +# +# Check 3 sends a real Ctrl+C to a script in a hidden console of its own, +# never to yours. Expected: ALL PASSED. Takes about half a minute. +param([int]$ProgramSeconds = 20) +Set-StrictMode -Version Latest +$ErrorActionPreference = 'Stop' + +if ($PSVersionTable.PSVersion.Major -lt 7) { + Write-Host 'This checks PowerShell 7 itself: run it with pwsh, not powershell.' + exit 2 +} + +$work = Join-Path ([IO.Path]::GetTempPath()) ("pk-ps7-native-" + $PID) +$null = New-Item -ItemType Directory -Path $work -Force +# A tag on each program's command line, so only this run's are counted. The +# scripts that start them get the tag without its 'prog' end. +$tag = 'pkps7native' + $PID +$progTag = $tag + 'prog' +$exe = (Get-Process -Id $PID).Path +# Start-Process doesn't quote -ArgumentList elements: paths are quoted by hand. +function Get-Quoted([string]$Path) { return '"' + $Path + '"' } +$pingCount = $ProgramSeconds + 1 +$failures = 0 +function Test-Check([bool]$Ok, [string]$What) { + if ($Ok) { Write-Host "[PASS] $What" } else { Write-Host "[FAIL] $What"; $script:failures++ } +} +function Get-Tagged { + # This run's programs: the cmd.exe running each ping, or the PowerShell that ignores Ctrl+C. + @(Get-CimInstance Win32_Process | Where-Object { $null -ne $_.CommandLine -and $_.CommandLine.Contains($progTag) }) +} +function Stop-Tagged { + foreach ($p in Get-Tagged) { Stop-Process -Id $p.ProcessId -Force -ErrorAction SilentlyContinue } + foreach ($p in @(Get-CimInstance Win32_Process -Filter "Name='PING.EXE'" | Where-Object { $null -ne $_.CommandLine -and $_.CommandLine.Contains("-n $pingCount ") })) { + Stop-Process -Id $p.ProcessId -Force -ErrorAction SilentlyContinue + } +} +function Wait-Tagged([int]$Count, [int]$Seconds = 30) { + $deadline = (Get-Date).AddSeconds($Seconds) + while ((Get-Date) -lt $deadline -and @(Get-Tagged).Count -lt $Count) { Start-Sleep -Milliseconds 200 } + return @(Get-Tagged).Count +} +# The program each -Parallel iteration runs: cmd.exe running ping, tagged with a rem. +$program = '& cmd.exe /d /c "ping -n ' + $pingCount + ' 127.0.0.1 >nul & rem ' + $progTag + '"' + +Write-Host ("PowerShell " + $PSVersionTable.PSVersion + ", no kit loaded") +try { + # 1. Killed outright. + $script1 = Join-Path $work 'killed.ps1' + [IO.File]::WriteAllText($script1, ('1..3 | ForEach-Object -Parallel { ' + $program + ' } -ThrottleLimit 3')) + $p1 = Start-Process $exe -ArgumentList '-NoProfile', '-File', (Get-Quoted $script1) -WindowStyle Hidden -PassThru + $before = Wait-Tagged 3 + $null = & taskkill.exe /F /PID $p1.Id 2>&1 # PowerShell only, not its tree + Start-Sleep -Seconds 2 + $after = @(Get-Tagged).Count + Test-Check ($before -eq 3 -and $after -eq 3) "1. killed outright, PowerShell left its programs running ($after of $before still running)" + Stop-Tagged + + # 2. -TimeoutSeconds. + $sw = [Diagnostics.Stopwatch]::StartNew() + $output = [System.Collections.Generic.List[string]]::new() + try { + 1..3 | ForEach-Object -Parallel ([scriptblock]::Create($program + '; "ended on its own, exit $LASTEXITCODE"')) -ThrottleLimit 3 -TimeoutSeconds 3 | ForEach-Object { $output.Add([string]$_) } + } catch { + # -TimeoutSeconds ends the call with "The pipeline has been stopped." + $output.Add('stopped: ' + $_.Exception.Message) + } + $sw.Stop() + $ended = @($output | Where-Object { $_ -like 'ended on its own*' }).Count + Test-Check ($sw.Elapsed.TotalSeconds -ge ($ProgramSeconds - 2) -and $ended -ge 1) ("2. -TimeoutSeconds 3 returned after " + [int]$sw.Elapsed.TotalSeconds + " s, once the programs had run their " + $ProgramSeconds + " s ($ended of 3 reported ending on their own)") + Stop-Tagged + + # 3. Ctrl+C, to programs that ignore Ctrl+C themselves. + $ignore = Join-Path $work 'ignore.ps1' + [IO.File]::WriteAllText($ignore, @' +param([string]$Log, [string]$Tag, [int]$Seconds) +Add-Type -Name C -Namespace PkIgnoreCtrlC -MemberDefinition '[DllImport("kernel32.dll")] public static extern bool SetConsoleCtrlHandler(System.IntPtr h, bool add);' +$null = [PkIgnoreCtrlC.C]::SetConsoleCtrlHandler([IntPtr]::Zero, $true) +# A log of its own: three programs appending to one at once can collide. +$Log = $Log + '.' + $PID +[IO.File]::AppendAllText($Log, "ignoring Ctrl+C`r`n") +Start-Sleep -Seconds $Seconds +[IO.File]::AppendAllText($Log, "ran to the end`r`n") +'@) + $log = Join-Path $work 'ctrlc.log' + $script3 = Join-Path $work 'ctrlc.ps1' + [IO.File]::WriteAllText($script3, @' +param([string]$Exe, [string]$Ignore, [string]$Log, [string]$Tag, [int]$Seconds) +# Started from a tool, this may inherit "ignore Ctrl+C"; a user's console doesn't. Clear it. +Add-Type -Name P -Namespace PkCtrlCTest -MemberDefinition '[DllImport("kernel32.dll")] public static extern bool SetConsoleCtrlHandler(System.IntPtr h, bool add);' +$null = [PkCtrlCTest.P]::SetConsoleCtrlHandler([IntPtr]::Zero, $false) +try { + 1..3 | ForEach-Object -Parallel { & $using:Exe -NoProfile -File $using:Ignore -Log $using:Log -Tag ($using:Tag + 'prog') -Seconds $using:Seconds } -ThrottleLimit 3 + [IO.File]::AppendAllText($Log, "script carried on after the pipeline`r`n") +} finally { [IO.File]::AppendAllText($Log, "script stopped`r`n") } +'@) + $p3 = Start-Process $exe -ArgumentList '-NoProfile', '-File', (Get-Quoted $script3), '-Exe', (Get-Quoted $exe), '-Ignore', (Get-Quoted $ignore), '-Log', (Get-Quoted $log), '-Tag', $tag, '-Seconds', $ProgramSeconds -WindowStyle Hidden -PassThru + $before = Wait-Tagged 3 + Start-Sleep -Seconds 1 + $sender = Join-Path $work 'sender.ps1' + [IO.File]::WriteAllText($sender, @' +param([int]$TargetPid) +Add-Type -TypeDefinition @" +using System; +using System.Runtime.InteropServices; +public static class PkPs7NativeSender { + public delegate bool HandlerRoutine(uint ctrlType); + [DllImport("kernel32.dll", SetLastError = true)] public static extern bool FreeConsole(); + [DllImport("kernel32.dll", SetLastError = true)] public static extern bool AttachConsole(uint pid); + [DllImport("kernel32.dll", SetLastError = true)] public static extern bool SetConsoleCtrlHandler(HandlerRoutine h, bool add); + [DllImport("kernel32.dll", SetLastError = true)] public static extern bool GenerateConsoleCtrlEvent(uint ev, uint group); + private static HandlerRoutine _swallow = new HandlerRoutine(Swallow); + private static bool Swallow(uint ctrlType) { return true; } + public static int Send(uint pid) { + FreeConsole(); + if (!AttachConsole(pid)) { return 1; } + // Attached to the same console, so this gets the Ctrl+C too. + SetConsoleCtrlHandler(_swallow, true); + if (!GenerateConsoleCtrlEvent(0, 0)) { return 2; } + System.Threading.Thread.Sleep(300); + FreeConsole(); + return 0; + } +} +"@ +exit [PkPs7NativeSender]::Send([uint32]$TargetPid) +'@) + # In a hidden console of its own, so it can attach to the script's console. + $s = Start-Process $exe -ArgumentList '-NoProfile', '-File', (Get-Quoted $sender), '-TargetPid', $p3.Id -WindowStyle Hidden -PassThru -Wait + Start-Sleep -Seconds 2 + $p3.Refresh() + $lines = @(foreach ($f in @(Get-ChildItem -Path ($log + '*') -File)) { Get-Content -LiteralPath $f.FullName }) + $left = @(Get-Tagged).Count + Test-Check ($s.ExitCode -eq 0) "3. Ctrl+C sent (sender exit $($s.ExitCode))" + Test-Check (@($lines | Where-Object { $_ -eq 'ignoring Ctrl+C' }).Count -eq 3) "3. the three programs were set to ignore Ctrl+C" + Test-Check ($p3.HasExited -and ($lines -contains 'script stopped') -and -not ($lines -contains 'script carried on after the pipeline')) '3. Ctrl+C stopped the script' + Test-Check ($before -eq 3 -and $left -eq 0 -and -not ($lines -contains 'ran to the end')) "3. its programs were stopped too, within 2 s, though they ignore Ctrl+C ($left of $before still running)" + if (-not $p3.HasExited) { Stop-Process -Id $p3.Id -Force -ErrorAction SilentlyContinue } +} finally { + # The scripts first, so none starts another program, then their programs. + foreach ($p in @(Get-Variable -Name p1, p3 -ValueOnly -ErrorAction SilentlyContinue)) { + if ($null -ne $p -and -not $p.HasExited) { Stop-Process -Id $p.Id -Force -ErrorAction SilentlyContinue } + } + Stop-Tagged + Remove-Item -LiteralPath $work -Recurse -Force -ErrorAction SilentlyContinue +} +if ($failures -eq 0) { Write-Host 'ALL PASSED' } else { Write-Host ($failures.ToString() + ' FAILED') } +exit $failures diff --git a/Testing/readme-examples/run.ps1 b/Testing/readme-examples/run.ps1 new file mode 100644 index 0000000..4cba8b9 --- /dev/null +++ b/Testing/readme-examples/run.ps1 @@ -0,0 +1,294 @@ +# README examples check: do the code examples in README.md run, and do what +# the README says they do? +# +# Each example is read straight out of README.md (found by a line of text it +# contains, so the check follows the README as it changes), saved as its own +# script with only the kit's path and the data folder filled in, and run in a +# fresh PowerShell of the same kind as this one, once without StrictMode and +# once with it. Checks after each one confirm what it did. The group-dispatch +# example also runs with an abort that lets running jobs finish and one that +# kills them. One more check covers the README's note that on 5.1 a worker's +# $ErrorActionPreference doesn't reach Get-FileHash. +# +# powershell -NoProfile -File .\Testing\readme-examples\run.ps1 +# pwsh -NoProfile -File .\Testing\readme-examples\run.ps1 +# +# The examples convert images with cjxl.exe (libjxl's JPEG XL encoder), so it +# has to be on PATH. Expected: ALL PASSED. Takes under a minute. -ReadmePath +# checks a draft instead of README.md. +param( + [string]$ReadmePath = (Join-Path $PSScriptRoot '..\..\README.md'), + [string]$KitPath = (Join-Path $PSScriptRoot '..\..\ParallelKit.ps1') +) +Set-StrictMode -Version Latest +$ErrorActionPreference = 'Stop' + +$ReadmePath = (Resolve-Path -LiteralPath $ReadmePath).ProviderPath +$KitPath = (Resolve-Path -LiteralPath $KitPath).ProviderPath +if (-not (Get-Command cjxl.exe -CommandType Application -ErrorAction SilentlyContinue)) { + Write-Host 'cjxl.exe is not on PATH. The README examples convert PNGs with it: install libjxl (for example, winget install libjxl) and run this again.' + exit 2 +} + +# Every ```powershell block in the README, its indentation removed. +function Get-ReadmeBlocks { + param([string]$Path) + $blocks = [System.Collections.Generic.List[string]]::new() + $lines = [IO.File]::ReadAllLines($Path) + $i = 0 + while ($i -lt $lines.Length) { + $m = [regex]::Match($lines[$i], '^(\s*)```powershell\s*$') + $i++ + if (-not $m.Success) { continue } + $indent = $m.Groups[1].Value.Length + $body = [System.Collections.Generic.List[string]]::new() + while ($i -lt $lines.Length -and $lines[$i] -notmatch '^\s*```\s*$') { + $l = $lines[$i] + if ($l.Length -ge $indent -and $l.Substring(0, $indent).Trim() -eq '') { $l = $l.Substring($indent) } + $body.Add($l); $i++ + } + $i++ + $blocks.Add(($body -join "`r`n")) + } + return $blocks +} + +$blocks = Get-ReadmeBlocks -Path $ReadmePath +function Get-Example { + # The one block holding this text. A miss means the README changed: update the marker. + param([string]$Marker) + $found = @($blocks | Where-Object { $_.Contains($Marker) }) + if ($found.Count -ne 1) { throw ("README examples check: expected one code block in README.md containing '" + $Marker + "', found " + $found.Count + ". If the example changed, update its marker in this script.") } + # Ends with a line break, like each piece it's joined to: a here-string has none of its own. + return $found[0].Replace('"$PSScriptRoot\ParallelKit.ps1"', '$Kit') + "`r`n" +} + +# Set up at the top of every test script: the data folder, a few PNGs and a +# broken one, and a check function. +$prelude = @' +param([string]$Kit, [string]$Data, [switch]$Strict) +if ($Strict) { Set-StrictMode -Version Latest } +$ErrorActionPreference = 'Stop' +$script:fails = 0 +function Test-Check([bool]$Ok, [string]$What) { if ($Ok) { "[PASS] $What" } else { "[FAIL] $What"; $script:fails++ } } +Add-Type -AssemblyName System.Drawing +function New-TestPng([string]$Path, [int]$Size) { + # Random pixels, so a big one takes cjxl a moment. + $bmp = [System.Drawing.Bitmap]::new($Size, $Size, [System.Drawing.Imaging.PixelFormat]::Format24bppRgb) + $rect = [System.Drawing.Rectangle]::new(0, 0, $Size, $Size) + $bits = $bmp.LockBits($rect, [System.Drawing.Imaging.ImageLockMode]::WriteOnly, $bmp.PixelFormat) + $bytes = [byte[]]::new($bits.Stride * $Size) + [System.Random]::new($Path.Length).NextBytes($bytes) + [System.Runtime.InteropServices.Marshal]::Copy($bytes, 0, $bits.Scan0, $bytes.Length) + $bmp.UnlockBits($bits) + $bmp.Save($Path, [System.Drawing.Imaging.ImageFormat]::Png); $bmp.Dispose() +} +$null = New-Item -ItemType Directory -Path $Data -Force +Set-Location -LiteralPath $Data +'@ +$pngs = @' +foreach ($n in 'a', 'b', 'c') { New-TestPng (Join-Path $Data "$n.png") 32 } +Set-Content -LiteralPath (Join-Path $Data 'bad.png') -Value 'not a png' + +'@ +$ending = @' + +Set-Location -LiteralPath ([IO.Path]::GetTempPath()) +exit $script:fails +'@ + +$tests = [System.Collections.Generic.List[hashtable]]::new() + +$tests.Add(@{ Name = 'Quick start'; Body = $pngs + (Get-Example 'Invoke-PkProcessBatch -Commands $commands -MaxConcurrent 6') + @' + +Test-Check ($batch.Results.Count -eq 4) "a result per command ($($batch.Results.Count) of 4)" +Test-Check (@($batch.Results | Where-Object { $_.ExitCode -eq 0 }).Count -eq 3) 'the three good PNGs converted' +Test-Check (@(Get-ChildItem -Filter *.png.jxl).Count -eq 3) 'three .png.jxl files written' +Test-Check (@($batch.Results | Where-Object { $_.ExitCode -ne 0 }).Count -eq 1) 'bad.png is the one failure' +$top = @($batch.Results | Sort-Object Duration -Descending | Select-Object -First 10) +Test-Check ($top.Count -eq 4 -and $top[0].Duration -is [TimeSpan]) 'the Sort-Object Duration line works' +'@ }) + +$tests.Add(@{ Name = 'Setup'; Body = (Get-Example '$pk = Initialize-ParallelKit') + @' + +Test-Check ($null -ne $pk -and $pk.StartMode -eq 'CreatedInJob') "Initialize-ParallelKit's result read (StartMode $($pk.StartMode))" +'@ }) + +$tests.Add(@{ Name = 'Run a list of programs'; Body = $pngs + @' +. $Kit +$global:messages = [System.Collections.Generic.List[string]]::new() +Set-PkMessageHandler { param($Message, $Level) $global:messages.Add("$Level $Message") } + +'@ + (Get-Example '$batchParams = @{') + @' + +Test-Check ($batch.Results.Count -eq 4) "a result per command ($($batch.Results.Count) of 4)" +Test-Check (@($batch.Results | Where-Object { $_.Command.Source -is [System.IO.FileInfo] }).Count -eq 4) 'Source comes back on each result''s Command' +Test-Check (@($global:messages | Where-Object { $_ -eq 'Error FAILED: bad.png' }).Count -eq 1) "-OnComplete reported bad.png ($($global:messages -join '; '))" +$n = 0; $indexed = foreach ($c in $commands) { $c2 = $c.Clone(); $c2.Index = $n++; $c2 } +$again = Invoke-PkProcessBatch -Commands $indexed -MaxConcurrent 6 +Test-Check ((@($again.Results | Sort-Object { $_.Command.Index }) | ForEach-Object { $_.Command.Index }) -join ',' -eq '0,1,2,3') 'the Index sort line puts results back in order' +Set-PkMessageHandler $null +'@ }) + +$tests.Add(@{ Name = 'Run PowerShell code in parallel'; Body = $pngs + ". `$Kit`r`n" + (Get-Example 'function Get-FileSha') + @' + +$expected = @{}; foreach ($f in Get-ChildItem -File) { $expected[$f.FullName] = (Get-FileHash -LiteralPath $f.FullName -Algorithm SHA256).Hash } +Test-Check ($shaByPath.Count -eq $expected.Count) "a hash per file ($($shaByPath.Count) of $($expected.Count))" +Test-Check (@($expected.Keys | Where-Object { $shaByPath[$_] -ne $expected[$_] }).Count -eq 0) 'every hash matches Get-FileHash' +Test-Check ($out.CrashedCount -eq 0 -and -not $out.Aborted) 'no crashes, not aborted' +'@ }) + +$tests.Add(@{ Name = 'Worker that returns its own error object'; Body = $pngs + @' +. $Kit +$global:results = [System.Collections.Generic.List[object]]::new() +$jobsParams = @{ + MaxParallel = 2 + JobParams = @(@{ Path = (Join-Path $Data 'a.png') }, @{ Path = (Join-Path $Data 'missing.png') }) + ResultHandler = { param($r) $global:results.Add($r) } + +'@ + (Get-Example 'Error = $_.Exception.Message') + @' + +} +$out = Invoke-PkRunspaceJobs @jobsParams +Test-Check ($global:results.Count -eq 2) "a result per job ($($global:results.Count) of 2)" +$good = @($global:results | Where-Object { $_.Path -like '*a.png' })[0] +$missing = @($global:results | Where-Object { $_.Path -like '*missing.png' })[0] +Test-Check ($null -ne $good.Hash -and $null -eq $good.Error) 'an existing file gets a hash and no error' +Test-Check ($null -eq $missing.Hash -and $missing.Error -like '*missing.png*') "a missing file gets an error object ($($missing.Error))" +Test-Check ($out.CrashedCount -eq 0) 'nothing counted as a crash' +'@ }) + +$tests.Add(@{ Name = 'Messages'; Body = @' +. $Kit +$global:log = [System.Collections.Generic.List[string]]::new() +function Write-MyLog($Message, $Level) { $global:log.Add("$Level|$Message") } + +'@ + (Get-Example 'Set-PkMessageHandler { param($Message, $Level)') + @' + +$null = Invoke-PkRunspaceJobs -MaxParallel 2 -JobParams @(@{ N = 1 }) -WorkerScript { param($N) Write-PkMessage "from worker $N" -Level Warning } +Write-PkMessage 'from the main thread' -Level Error +Test-Check ($global:log -contains 'Warn|from worker 1') "a worker's -Level Warning arrives as Warn ($($global:log -join '; '))" +Test-Check ($global:log -contains 'Error|from the main thread') 'a main-thread message arrives' +Set-PkMessageHandler $null +'@ }) + +# The group-dispatch example, three ways. Its folder is the data folder. +$group = (Get-Example '$dispatchParams = @{').Replace("'D:\Scans'", '$Data') +$abortAfterFive = '$abortAt = @{ n = 0 }; $dispatchParams.PollCallback = { if (++$abortAt.n -eq 5) { Request-PkAbort } }' + "`r`n" +$dispatchLine = '$dispatch = Invoke-PkRun' +if (-not $group.Contains($dispatchLine)) { throw "README examples check: the group-dispatch example no longer has the line '$dispatchLine', which the abort tests hook into. Update this script." } + +$tests.Add(@{ Name = 'Process dispatch with groups'; Body = @' +$a = New-Item -ItemType Directory -Path (Join-Path $Data 'A'); 0..3 | ForEach-Object { New-TestPng (Join-Path $a "p$_.png") 64 } +$b = New-Item -ItemType Directory -Path (Join-Path $Data 'B'); 0..2 | ForEach-Object { New-TestPng (Join-Path $b "p$_.png") 64 } +Set-Content -LiteralPath (Join-Path $b 'bad.png') -Value 'not a png' +$null = New-Item -ItemType Directory -Path (Join-Path $Data 'C empty') +$d = New-Item -ItemType Directory -Path (Join-Path $Data 'D [x]'); 0..1 | ForEach-Object { New-TestPng (Join-Path $d "p$_.png") 64 } + +'@ + $group + @' + +Test-Check (-not $dispatch.Aborted) 'not aborted' +Test-Check (@($dispatch.GroupResults).Count -eq 4) "a result per folder ($(@($dispatch.GroupResults).Count) of 4)" +Test-Check (Test-Path -LiteralPath (Join-Path $Data 'A.zip')) 'folder A zipped' +Add-Type -AssemblyName System.IO.Compression.FileSystem +$zip = [System.IO.Compression.ZipFile]::OpenRead((Join-Path $Data 'A.zip')); $entries = $zip.Entries.Count; $zip.Dispose() +Test-Check ($entries -eq 4) "A.zip holds its four .jxl files ($entries)" +Test-Check (-not (Test-Path -LiteralPath (Join-Path $Data 'B.zip'))) 'folder B, with a bad file, not zipped' +Test-Check ($failed[(Join-Path $Data 'B')] -eq 1) 'B counts one failure, after its retry' +Test-Check (-not (Test-Path -LiteralPath (Join-Path $Data 'C empty.zip'))) 'the empty folder not zipped' +Test-Check (Test-Path -LiteralPath (Join-Path $Data 'D [x].zip')) 'a folder with brackets in its name zipped' +'@ }) + +$bigFolder = @' +$a = New-Item -ItemType Directory -Path (Join-Path $Data 'A'); 0..29 | ForEach-Object { New-TestPng (Join-Path $a ("p{0:D2}.png" -f $_)) 1200 } +# A file a job that never starts would write: an abort's cleanup must leave it alone. +Set-Content -LiteralPath (Join-Path $a 'p29.jxl') -Value 'SENTINEL' +$b = New-Item -ItemType Directory -Path (Join-Path $Data 'B'); 0..1 | ForEach-Object { New-TestPng (Join-Path $b "p$_.png") 64 } + +'@ +$abortChecks = @' + +Test-Check ([bool]$dispatch.Aborted) 'aborted' +$ga = @($dispatch.GroupResults | Where-Object { $_.GroupInfo.Name -eq 'A' }) +Test-Check ($ga.Count -eq 1 -and $ga[0].Aborted) 'folder A marked Aborted' +Test-Check (-not (Test-Path -LiteralPath (Join-Path $Data 'A.zip'))) 'folder A not zipped' +Test-Check (-not (Test-Path -LiteralPath (Join-Path $Data 'B.zip'))) 'folder B not zipped' +Test-Check ((Get-Content -LiteralPath (Join-Path $a 'p29.jxl') -Raw).Trim() -eq 'SENTINEL') 'a never-started job''s existing file left alone' + +'@ + +$tests.Add(@{ Name = 'Process dispatch with groups, Ctrl+C that lets running jobs finish'; Body = $bigFolder + $group.Replace($dispatchLine, $abortAfterFive + $dispatchLine) + $abortChecks + @' +$jxl = @(Get-ChildItem -LiteralPath $a -Filter *.jxl).Count +Test-Check ($jxl -gt 1 -and $jxl -lt 30) "the running jobs finished, the rest never started ($($jxl - 1) of 29 converted)" +'@ }) + +$tests.Add(@{ Name = 'Process dispatch with groups, Ctrl+C that kills running jobs'; Body = @' +'@ + $bigFolder + @' +# Stand-ins for partial output where the first six jobs, the ones running when they're killed, write. +0..5 | ForEach-Object { Set-Content -LiteralPath (Join-Path $a ("p{0:D2}.jxl" -f $_)) -Value 'STALE' } + +'@ + $group.Replace($dispatchLine, $abortAfterFive + '$dispatchParams.AbortTimeoutSeconds = 0' + "`r`n" + $dispatchLine) + $abortChecks + @' +Test-Check ($dispatch.ForceKilledCount -gt 0) "running jobs force-killed ($($dispatch.ForceKilledCount))" +$left = @(0..5 | Where-Object { Test-Path -LiteralPath (Join-Path $a ("p{0:D2}.jxl" -f $_)) }) +Test-Check ($left.Count -eq 0) "-JobAbortCleanup removed the killed jobs' files ($($left.Count) of 6 left)" +'@ }) + +# Behind the README's 5.1 note in "Errors and crashed workers". Not an example. +$tests.Add(@{ Name = "Get-FileHash and a worker's `$ErrorActionPreference"; Body = @' +. $Kit +$missingFile = Join-Path $Data 'missing.png' +$global:results = [System.Collections.Generic.List[string]]::new() +$null = Invoke-PkRunspaceJobs -MaxParallel 1 -JobParams @(@{ Path = $missingFile; UseParam = $false }, @{ Path = $missingFile; UseParam = $true }) -ResultHandler { param($r) $global:results.Add($r) } -WorkerScript { + param($Path, $UseParam) + $ErrorActionPreference = 'Stop' + try { + if ($UseParam) { $null = Get-FileHash -LiteralPath $Path -ErrorAction Stop } else { $null = Get-FileHash -LiteralPath $Path } + "$UseParam not caught" + } catch { "$UseParam caught" } +} 2>$null +$isFunction = (Get-Command Get-FileHash).CommandType -eq 'Function' +Test-Check ($global:results -contains 'True caught') '-ErrorAction Stop catches a missing file in a worker' +if ($isFunction) { + Test-Check ($global:results -contains 'False not caught') "Get-FileHash is a function here, and the worker's preference alone doesn't catch it, as the README says" +} else { + Test-Check ($global:results -contains 'False caught') 'Get-FileHash is a cmdlet here, and the preference alone catches it' +} +'@ }) + +$exe = (Get-Process -Id $PID).Path +$work = Join-Path ([IO.Path]::GetTempPath()) ("pk-readme-examples-" + $PID) +$null = New-Item -ItemType Directory -Path $work -Force +Write-Host ("PowerShell " + $PSVersionTable.PSVersion + ", README: " + $ReadmePath + ", kit: " + $KitPath) +$failures = 0 +try { + $t = 0 + foreach ($test in $tests) { + $t++ + $script = Join-Path $work ("test" + $t + ".ps1") + [IO.File]::WriteAllText($script, ($prelude + "`r`n" + $test['Body'] + $ending), [Text.UTF8Encoding]::new($true)) + foreach ($strict in $false, $true) { + $data = Join-Path $work ("data" + $t + $(if ($strict) { '-strict' } else { '' })) + $label = $test['Name'] + $(if ($strict) { ', StrictMode' } else { '' }) + $argList = @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', $script, '-Kit', $KitPath, '-Data', $data) + if ($strict) { $argList += '-Strict' } + # Native stderr comes back as error records: Continue, or 5.1 stops on the first. + $ErrorActionPreference = 'Continue' + $output = @(& $exe @argList 2>&1 | ForEach-Object { [string]$_ }) + $code = $LASTEXITCODE + $ErrorActionPreference = 'Stop' + $checks = @($output | Where-Object { $_ -match '^\[(PASS|FAIL)\]' }) + $failed = @($checks | Where-Object { $_ -like '`[FAIL`]*' }) + if ($code -ne 0 -or $failed.Count -gt 0 -or $checks.Count -eq 0) { + $failures++ + Write-Host ("[FAIL] " + $label + " (exit " + $code + "). Its output:") + $output | ForEach-Object { Write-Host (" " + $_) } + } else { + Write-Host ("[PASS] " + $label + " (" + $checks.Count + " checks)") + } + } + } +} finally { + Remove-Item -LiteralPath $work -Recurse -Force -ErrorAction SilentlyContinue +} +if ($failures -eq 0) { Write-Host 'ALL PASSED' } else { Write-Host ($failures.ToString() + ' FAILED') } +exit $failures From a6000a23d06863695083b5563e42a28ff354dcd1 Mon Sep 17 00:00:00 2001 From: Hal <22532613+HalRiveria@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:55:10 -0500 Subject: [PATCH 2/3] Update the harness run time in the README Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 633e903..feddefb 100644 --- a/README.md +++ b/README.md @@ -619,7 +619,7 @@ powershell -NoProfile -File .\ParallelKit.Harness.ps1
What it prints, and the stress tests in Testing/ -It takes about three and a half minutes. It prints a `[PASS]`/`[FAIL]` line per check and exits 0 only if everything passed. A few checks send real Ctrl+C, Ctrl+Break and window-close events to child PowerShell processes in hidden consoles of their own, never to yours. Where a machine can't deliver those, they print `[SKIP]` with the reason instead; set `PK_HARNESS_NO_SKIP=1` to count skips as failures. A few `message handler failed` lines in the output are expected: some checks break the message handler on purpose to test the fallback. +It takes about four and a half minutes. It prints a `[PASS]`/`[FAIL]` line per check and exits 0 only if everything passed. A few checks send real Ctrl+C, Ctrl+Break and window-close events to child PowerShell processes in hidden consoles of their own, never to yours. Where a machine can't deliver those, they print `[SKIP]` with the reason instead; set `PK_HARNESS_NO_SKIP=1` to count skips as failures. A few `message handler failed` lines in the output are expected: some checks break the message handler on purpose to test the fallback. GitHub runs the same harness on Windows PowerShell 5.1 and on PowerShell 7 for every pull request and every change to `main`. The harness is the only thing GitHub runs: the scripts in `Testing/` below are run by hand. From 3e0474e3efaf775a9049b679586b9b4b8da7cf17 Mon Sep 17 00:00:00 2001 From: Hal <22532613+HalRiveria@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:09:54 -0500 Subject: [PATCH 3/3] Fix review findings in the README and test scripts - Limits: one Invoke-PkRun at a time per process, said plainly. - Lifecycle diagram: starting inside the Job Object depends on StartMode. - Testing: the harness is the only test GitHub runs. - readme-examples: the kill-abort check no longer fails when a job finishes before the abort. - ps7-native: only this run's ping processes are stopped. - Each copy of the Ctrl+C sender names the other two. Co-Authored-By: Claude Opus 5.5 --- ParallelKit.Harness.ps1 | 2 ++ README.md | 6 +++--- Testing/ps7-native/run.ps1 | 9 +++++++-- Testing/readme-examples/run.ps1 | 5 +++-- Testing/stop-in-call/run.ps1 | 2 ++ 5 files changed, 17 insertions(+), 7 deletions(-) diff --git a/ParallelKit.Harness.ps1 b/ParallelKit.Harness.ps1 index 0e0822c..859ffc8 100644 --- a/ParallelKit.Harness.ps1 +++ b/ParallelKit.Harness.ps1 @@ -1667,6 +1667,8 @@ foreach ($i in 1..60) { Start-Sleep -Seconds 1 } Write-ChildLog "END" '@) +# The same sender as Testing/stop-in-call's PkProbeSender and Testing/ps7-native's +# PkPs7NativeSender, which are cut down to one Ctrl+C. [System.IO.File]::WriteAllText($senderScript, @' param([int]$TargetPid, [int]$EventType, [string]$LogFile) Add-Type -TypeDefinition @" diff --git a/README.md b/README.md index feddefb..c68b105 100644 --- a/README.md +++ b/README.md @@ -293,7 +293,7 @@ A program can be done while its output isn't: whatever it started can hold its o ```mermaid flowchart TD Q["Queued: waiting for a slot"] -->|"abort before it starts"| A["Aborted, no Duration (dispatcher: JobAbortCleanup)"] - Q -->|"slot free"| S["Created suspended inside the Job Object, then resumed"] + Q -->|"slot free"| S["Started inside the Job Object (see StartMode)"] S -->|"can't start"| E["StartError: no Duration"] S --> R["Running: Duration counts from here"] R -->|"exits"| D["Program done: Duration stops"] @@ -602,7 +602,7 @@ Other pieces: `Request-PkAbort` triggers the same abort from code. `Test-PkAbort - Run it in a PowerShell console window or an editor's terminal (graceful Ctrl+C tested in Windows Terminal, Visual Studio's built-in terminal and VS Code's terminal, including the PowerShell extension's). The Windows PowerShell ISE isn't supported: tested there, the kit loads and runs, but the ISE has no console, so Ctrl+C stops the script outright, with no graceful drain and no cleanup callbacks. - It needs FullLanguage mode, since it compiles a little C# with `Add-Type` when loaded. On a machine locked down to Constrained Language Mode (usually by AppLocker or Windows Defender Application Control), loading it fails with a message saying so. Some endpoint security products also flag scripts that compile code calling Windows APIs at runtime; if yours blocks the kit, that's the likely reason. - After changing `ParallelKit.ps1` itself, start a new PowerShell window. A session keeps the kit's compiled parts until it closes; the kit tells you if it finds an older copy loaded. -- Only one outer `Invoke-PkRun` abort scope can exist per PowerShell process. Nested calls reuse the existing scope. Multiple dispatchers can run concurrently where supported; they share the process-wide abort state and can share a `SemaphoreSlim` to enforce a combined concurrency limit. +- One `Invoke-PkRun` at a time per PowerShell process: a call made while one is already running, nested or from another runspace, just runs inside it. Several dispatchers can run at once inside one run (one per runspace job, say); they share its abort state and can share a `SemaphoreSlim` to enforce a combined concurrency limit. - A worker stuck inside a long .NET call can't be interrupted. Force-stop stops waiting for it and returns. The worker is NOT killed: once that call returns it can carry on to the end of its script. Before any step that can't be undone (deleting a source file, say), have the worker check `Test-PkCancelRequested` and skip the step if it's true. - Programs run hidden, and there's no way to send them input. A program that stops to ask a question will sit there until it's killed. - 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. @@ -621,7 +621,7 @@ powershell -NoProfile -File .\ParallelKit.Harness.ps1 It takes about four and a half minutes. It prints a `[PASS]`/`[FAIL]` line per check and exits 0 only if everything passed. A few checks send real Ctrl+C, Ctrl+Break and window-close events to child PowerShell processes in hidden consoles of their own, never to yours. Where a machine can't deliver those, they print `[SKIP]` with the reason instead; set `PK_HARNESS_NO_SKIP=1` to count skips as failures. A few `message handler failed` lines in the output are expected: some checks break the message handler on purpose to test the fallback. -GitHub runs the same harness on Windows PowerShell 5.1 and on PowerShell 7 for every pull request and every change to `main`. The harness is the only thing GitHub runs: the scripts in `Testing/` below are run by hand. +GitHub runs the same harness on Windows PowerShell 5.1 and on PowerShell 7 for every pull request and every change to `main`. The harness is the only test GitHub runs: the scripts in `Testing/` below are run by hand. `Testing/` holds the longer stress tests and checks behind some of what this README says. They aren't part of the test suite and aren't needed to use the kit: diff --git a/Testing/ps7-native/run.ps1 b/Testing/ps7-native/run.ps1 index fc2b983..e053965 100644 --- a/Testing/ps7-native/run.ps1 +++ b/Testing/ps7-native/run.ps1 @@ -44,10 +44,13 @@ function Get-Tagged { @(Get-CimInstance Win32_Process | Where-Object { $null -ne $_.CommandLine -and $_.CommandLine.Contains($progTag) }) } function Stop-Tagged { - foreach ($p in Get-Tagged) { Stop-Process -Id $p.ProcessId -Force -ErrorAction SilentlyContinue } - foreach ($p in @(Get-CimInstance Win32_Process -Filter "Name='PING.EXE'" | Where-Object { $null -ne $_.CommandLine -and $_.CommandLine.Contains("-n $pingCount ") })) { + $tagged = @(Get-Tagged) + $ids = @($tagged | ForEach-Object { $_.ProcessId }) + # A tagged cmd.exe's ping has no tag of its own: it's found by its parent, before that goes. + foreach ($p in @(Get-CimInstance Win32_Process -Filter "Name='PING.EXE'" | Where-Object { $ids -contains $_.ParentProcessId })) { Stop-Process -Id $p.ProcessId -Force -ErrorAction SilentlyContinue } + foreach ($p in $tagged) { Stop-Process -Id $p.ProcessId -Force -ErrorAction SilentlyContinue } } function Wait-Tagged([int]$Count, [int]$Seconds = 30) { $deadline = (Get-Date).AddSeconds($Seconds) @@ -111,6 +114,8 @@ try { $p3 = Start-Process $exe -ArgumentList '-NoProfile', '-File', (Get-Quoted $script3), '-Exe', (Get-Quoted $exe), '-Ignore', (Get-Quoted $ignore), '-Log', (Get-Quoted $log), '-Tag', $tag, '-Seconds', $ProgramSeconds -WindowStyle Hidden -PassThru $before = Wait-Tagged 3 Start-Sleep -Seconds 1 + # The same sender as ParallelKit.Harness.ps1's PkHarnessSender and + # Testing/stop-in-call's PkProbeSender, cut down to one Ctrl+C. $sender = Join-Path $work 'sender.ps1' [IO.File]::WriteAllText($sender, @' param([int]$TargetPid) diff --git a/Testing/readme-examples/run.ps1 b/Testing/readme-examples/run.ps1 index 4cba8b9..d299f75 100644 --- a/Testing/readme-examples/run.ps1 +++ b/Testing/readme-examples/run.ps1 @@ -229,8 +229,9 @@ $tests.Add(@{ Name = 'Process dispatch with groups, Ctrl+C that kills running jo '@ + $group.Replace($dispatchLine, $abortAfterFive + '$dispatchParams.AbortTimeoutSeconds = 0' + "`r`n" + $dispatchLine) + $abortChecks + @' Test-Check ($dispatch.ForceKilledCount -gt 0) "running jobs force-killed ($($dispatch.ForceKilledCount))" -$left = @(0..5 | Where-Object { Test-Path -LiteralPath (Join-Path $a ("p{0:D2}.jxl" -f $_)) }) -Test-Check ($left.Count -eq 0) "-JobAbortCleanup removed the killed jobs' files ($($left.Count) of 6 left)" +# A job that finished before the abort replaced its stand-in with real output, which stays. +$left = @(0..5 | Where-Object { $p = Join-Path $a ("p{0:D2}.jxl" -f $_); (Test-Path -LiteralPath $p) -and (Get-Content -LiteralPath $p -Raw) -match 'STALE' }) +Test-Check ($left.Count -eq 0) "-JobAbortCleanup removed the killed jobs' files ($($left.Count) of 6 stand-ins left)" '@ }) # Behind the README's 5.1 note in "Errors and crashed workers". Not an example. diff --git a/Testing/stop-in-call/run.ps1 b/Testing/stop-in-call/run.ps1 index e6f8857..e566d19 100644 --- a/Testing/stop-in-call/run.ps1 +++ b/Testing/stop-in-call/run.ps1 @@ -91,6 +91,8 @@ try { } '@) +# The same sender as ParallelKit.Harness.ps1's PkHarnessSender and +# Testing/ps7-native's PkPs7NativeSender, cut down to one Ctrl+C. $senderScript = Join-Path $dir 'sender.ps1' [IO.File]::WriteAllText($senderScript, @' param([int]$TargetPid, [string]$LogFile)