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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 64 additions & 0 deletions ParallelKit.Harness.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -4092,6 +4092,70 @@ foreach ($rsName in 'ResultHandler', 'PollCallback', 'NextJobProvider') {
}
Write-Host ""

Write-Host "=== AT: a stray value next to a callback's answer ===" -ForegroundColor Cyan
# A value a callback lets out before its answer (an ArrayList.Add index, say)
# reaches the kit together with the answer, as one array. Each callback below
# leaks one; the kit must still read the answer it meant.

# -GroupReleaseCheck: `$log.Add($g); return $false` must not release the
# group. Only zero-job groups are held, and with -MaxQueueAhead 1 the next
# group is pulled only once the held one is released, on the third check.
Reset-Harness
$rc = @{ Given = 0; Checks = 0; PulledAfter = -1 }
$rcLog = [System.Collections.ArrayList]::new()
$rcRun = Invoke-PkProcessDispatch -MaxConcurrent 1 -MaxQueueAhead 1 `
-GroupProvider { if ($rc.Given -ge 2) { return $null }; $rc.Given++; if ($rc.Given -eq 2) { $rc.PulledAfter = $rc.Checks }; return ('g' + $rc.Given) }.GetNewClosure() `
-JobBuilder { param($g) return @() } `
-JobFinalize { param($job, $pending) } `
-GroupReleaseCheck { param($g) if ($g -ne 'g1') { return $true }; $rc.Checks++; $rcLog.Add($g); return ($rc.Checks -ge 3) }.GetNewClosure()
Test-Assert ($rc.PulledAfter -eq 3 -and $rcRun.GroupResults.Count -eq 2) ("a stray value from -GroupReleaseCheck doesn't release a held group: only its last value counts (next group pulled after check " + $rc.PulledAfter + " of 3)")

# -GroupProvider: `$log.Add('end'); return $null` reaches the dispatcher as
# @(<index>, $null). That's the end, with a warning, not one more group
# (which asked again forever). A runaway is cut off after 10 calls.
Reset-Harness
$gp = @{ Given = 0; Calls = 0 }
$gpLog = [System.Collections.ArrayList]::new()
$gpError = $null
try {
$gpRun = Invoke-PkProcessDispatch -MaxConcurrent 1 `
-GroupProvider { $gp.Calls++; if ($gp.Calls -gt 10) { throw 'pk-test: runaway -GroupProvider' }; if ($gp.Given -ge 2) { $gpLog.Add('end'); return $null }; $gp.Given++; return ('g' + $gp.Given) }.GetNewClosure() `
-JobBuilder { param($g) return @{ FilePath = $cmdExe; Arguments = '/d /c exit 0' } }.GetNewClosure() `
-JobFinalize { param($job, $pending) $null = Complete-PkProcess -Job $job }
} catch { $gpError = [string]$_ }
$gpGroups = ''
if ($null -eq $gpError) { $gpGroups = (@($gpRun.GroupResults | ForEach-Object { [string]$_.GroupInfo }) -join ',') }
$gpWarned = @($script:messages | Where-Object { $_.Message -like '*-GroupProvider*' -and $_.Level -eq 'Warn' }).Count
Test-Assert ($null -eq $gpError -and $gpGroups -eq 'g1,g2' -and $gp.Calls -eq 3 -and $gpWarned -eq 1) ("output ending in `$null from -GroupProvider ends the groups, with a warning (groups: " + $gpGroups + ", calls: " + $gp.Calls + ", warnings: " + $gpWarned + ", error: " + $gpError + ")")

# A list as one group, written as the README shows it.
Reset-Harness
$gl = @{ Given = $false }
$glSeen = [System.Collections.Generic.List[object]]::new()
$null = Invoke-PkProcessDispatch -MaxConcurrent 1 `
-GroupProvider { if ($gl.Given) { return $null }; $gl.Given = $true; return ,@('a', 'b', 'c') }.GetNewClosure() `
-JobBuilder { param($g) $glSeen.Add($g); return @() }.GetNewClosure() `
-JobFinalize { param($job, $pending) }
Test-Assert ($glSeen.Count -eq 1 -and $glSeen[0] -is [array] -and ($glSeen[0] -join ',') -eq 'a,b,c' -and $script:messages.Count -eq 0) ("-GroupProvider returning ,@('a', 'b', 'c') gives one group holding the list, without a warning (" + $glSeen.Count + " group(s))")

# -NextJobProvider: only the last value decides. Two hashtables run the
# second, with a warning about the first; a hashtable let out before
# `return $null` isn't run: the run ends, with a warning.
foreach ($njCase in 'two jobs', 'job then null') {
Reset-Harness
$nj = @{ Calls = 0 }
$njRan = [System.Collections.Generic.List[int]]::new()
$njProvider = { $nj.Calls++; if ($nj.Calls -gt 1) { return $null }; @{ Id = 1 }; return @{ Id = 2 } }.GetNewClosure()
# A second call (only reached if the first didn't end the run) gives job 3, then the end.
if ($njCase -eq 'job then null') { $njProvider = { $nj.Calls++; if ($nj.Calls -gt 2) { return $null }; if ($nj.Calls -eq 2) { return @{ Id = 3 } }; @{ Id = 1 }; return $null }.GetNewClosure() }
$null = Invoke-PkRunspaceJobs -WorkerScript { param([int]$Id) $Id } -NextJobProvider $njProvider -MaxParallel 1 -ResultHandler { param($r) $njRan.Add($r) }.GetNewClosure()
$njWarned = @($script:messages | Where-Object { $_.Message -like '*-NextJobProvider*' -and $_.Level -eq 'Warn' }).Count
$njExpected = '2'
if ($njCase -eq 'job then null') { $njExpected = '' }
Test-Assert (($njRan -join ',') -eq $njExpected -and $nj.Calls -eq (2 - [int]($njCase -eq 'job then null')) -and $njWarned -eq 1) ("-NextJobProvider, " + $njCase + ": only the last value counts, the other is warned about (ran: [" + ($njRan -join ',') + "], calls: " + $nj.Calls + ", warnings: " + $njWarned + ")")
}
Write-Host ""

Set-PkMessageHandler -Handler $null
Reset-PkAbortState

Expand Down
46 changes: 38 additions & 8 deletions ParallelKit.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -1695,7 +1695,10 @@ function Invoke-PkProcessDispatch {
# argument per element), WorkingDirectory and OutputEncoding from the job. A
# job's TimeoutSeconds key overrides -TimeoutSeconds.
# .PARAMETER GroupProvider
# { } returning the next group, or $null when there are no more.
# { } returning the next group, or $null when there are no more, and
# outputting nothing else. Return a list as one group with a comma:
# return ,@('a', 'b'). Output ending in $null is taken as the end, with a
# warning, so a list group can't end in $null.
# .PARAMETER JobBuilder
# { param($group) } returning the group's job hashtable(s), or @() for none.
# .PARAMETER JobStarter
Expand Down Expand Up @@ -1732,6 +1735,7 @@ function Invoke-PkProcessDispatch {
# .PARAMETER GroupReleaseCheck
# { param($group) } returning $true to release a zero-job group's queue-ahead
# slot; until then it holds the slot. Runs on every loop pass, so keep it cheap.
# Only its last output value counts.
# .PARAMETER TimeoutSeconds
# Kill a job's program, and anything it started, still running after this long
# (default 0, no limit). A job's own TimeoutSeconds key overrides it, and 0 there
Expand Down Expand Up @@ -1972,14 +1976,28 @@ function Invoke-PkProcessDispatchCore {
(-not $pkProviderExhausted -or $pkActiveGroupCount -gt 0 -or $pkPending.Count -gt 0 -or $pkRunning.Count -gt 0)) {

for ($pkH = $pkHeldGroups.Count - 1; $pkH -ge 0; $pkH--) {
if ([bool](Invoke-PkCallback -PkCallback $pkGroupReleaseCheck -PkArgs @(,$pkHeldGroups[$pkH]) -PkName '-GroupReleaseCheck' -PkContext $pkCallbackContext)) {
$pkReleased = Invoke-PkCallback -PkCallback $pkGroupReleaseCheck -PkArgs @(,$pkHeldGroups[$pkH]) -PkName '-GroupReleaseCheck' -PkContext $pkCallbackContext
# Only the check's last value counts, as with -JobPollCompleted: a
# value it leaks first (an ArrayList.Add index) would release the group.
if ($pkReleased -is [object[]]) { $pkReleased = $pkReleased[-1] }
if ([bool]$pkReleased) {
$pkHeldGroups.RemoveAt($pkH)
$pkActiveGroupCount--
}
}

while ((-not $pkProviderExhausted) -and $pkActiveGroupCount -lt $pkMaxQueueAhead -and (-not $pkCancelToken.IsCancellationRequested)) {
$pkGroupInfo = Invoke-PkCallback -PkCallback $pkGroupProvider -PkName '-GroupProvider' -PkContext $pkCallbackContext
# A value the provider leaks before `return $null` (an ArrayList.Add
# index) arrives as @(<index>, $null). Taken as one more group, the
# dispatcher would ask again forever, so output ending in $null is
# the end. A list can't be told apart from that (wrapped or not, a
# list reaches here as the same array), so a list group can't end
# in $null.
if ($pkGroupInfo -is [object[]] -and $pkGroupInfo.Count -gt 0 -and $null -eq $pkGroupInfo[-1]) {
Write-PkMessage ("ProcessDispatch: -GroupProvider output " + ($pkGroupInfo.Count - 1) + " other value(s) along with `$null, taken as no more groups. Output only the group, or `$null alone to end (`$null = ... discards a value you don't want).") -Level Warn
$pkGroupInfo = $null
}
if ($null -eq $pkGroupInfo) { $pkProviderExhausted = $true; break }
# A fresh key per group, not the group value: two groups that
# compare equal (the same folder name) mustn't share a job count.
Expand Down Expand Up @@ -2721,7 +2739,9 @@ function Invoke-PkRunspaceJobs {
# -NextJobProvider.
# .PARAMETER NextJobProvider
# { } returning the next job hashtable, or $null when there are no more. Runs on
# the main thread, so jobs can be produced lazily.
# the main thread, so jobs can be produced lazily. Only its last value counts:
# $null ends the run, otherwise the last hashtable is the job; anything else
# it outputs is ignored, with a warning.
# .PARAMETER SharedFunctionNames
# Your functions the worker calls.
# .PARAMETER MaxParallel
Expand Down Expand Up @@ -2910,16 +2930,26 @@ function Invoke-PkRunspaceJobs {
$nextJob = $null
}
} else {
# Same as the dispatcher's builder: take the job
# hashtable, ignore anything else the provider let out.
# A job is one hashtable, so the last value decides: $null
# ends the run, otherwise the last hashtable is the job.
# Anything else the provider let out (a leaked index, or a
# hashtable before its answer) is ignored, with a warning.
$nextRaw = Invoke-PkCallback -PkCallback $NextJobProvider -PkName '-NextJobProvider' -PkContext $pkCallbackContext
$nextJob = $null
$rawItems = @($nextRaw) # empty when it output nothing: the end
$jobIndex = -1
if ($rawItems.Count -gt 0 -and $null -ne $rawItems[-1]) {
for ($rawIndex = $rawItems.Count - 1; $rawIndex -ge 0 -and $jobIndex -lt 0; $rawIndex--) {
if ($rawItems[$rawIndex] -is [hashtable]) { $jobIndex = $rawIndex }
}
}
if ($jobIndex -ge 0) { $nextJob = $rawItems[$jobIndex] }
$strayCount = 0
foreach ($rawItem in @($nextRaw)) {
if ($rawItem -is [hashtable]) { $nextJob = $rawItem } elseif ($null -ne $rawItem) { $strayCount++ }
for ($rawIndex = 0; $rawIndex -lt $rawItems.Count; $rawIndex++) {
if ($rawIndex -ne $jobIndex -and $null -ne $rawItems[$rawIndex]) { $strayCount++ }
}
if ($strayCount -gt 0) {
Invoke-PkMessageHandler -Level Warn -Message ("Invoke-PkRunspaceJobs: -NextJobProvider returned " + $strayCount + " value(s) that are not a job hashtable - ignored.")
Invoke-PkMessageHandler -Level Warn -Message ("Invoke-PkRunspaceJobs: -NextJobProvider output " + $strayCount + " value(s) besides its job hashtable or `$null - ignored. Output only the next job, or `$null when there are no more (`$null = ... discards a value you don't want).")
}
}
if ($null -eq $nextJob) { $scanExhausted = $true; break }
Expand Down
7 changes: 4 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@ Each worker runs in its own runspace: a separate PowerShell session inside the s
- 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.
- 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.
- `-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.
- `-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:
Expand Down Expand Up @@ -251,13 +251,14 @@ All of these callbacks run on whichever thread called the dispatcher: the main t
- `-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.
- 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`. (`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. 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.
- 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.
- 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. They can't corrupt the dispatcher's result by accident.
- 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.
- `-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.
- `-CancelToken` stops the dispatcher when canceled. An abort stops it either way, without canceling your token.
Expand Down
Loading