diff --git a/ParallelKit.Harness.ps1 b/ParallelKit.Harness.ps1 index a135c09..5ee4a6c 100644 --- a/ParallelKit.Harness.ps1 +++ b/ParallelKit.Harness.ps1 @@ -2387,7 +2387,9 @@ function Invoke-LimitGroup { return @{ Log = $log; Result = $result; Problem = $problem; Secs = $sw.Elapsed.TotalSeconds } } function Get-LimitEntry { param($Run, [string]$Name) return ,@($Run.Log | Where-Object { $_.Name -eq $Name }) } -function Get-LimitPingCount { param([int]$N) return @(Get-CimInstance Win32_Process -Filter "Name = 'PING.EXE'" | Where-Object { $_.CommandLine -like ("*-n " + $N + " 127.0.0.1*") }).Count } +# The pings a test started, told apart by their -n count. Also used by section AG. +function Get-LimitPing { param([int]$N) return @(Get-CimInstance Win32_Process -Filter "Name = 'PING.EXE'" | Where-Object { $_.CommandLine -like ("*-n " + $N + " 127.0.0.1*") }) } +function Get-LimitPingCount { param([int]$N) return @(Get-LimitPing $N).Count } # -TimeoutSeconds, and a job's own key overriding it in both directions. $limitRun = Invoke-LimitGroup -Extra @{ TimeoutSeconds = 2 } -Jobs @( @@ -2810,6 +2812,146 @@ Test-Assert ($null -ne $out -and $out.CrashedCount -eq 0) "a splatted CheckWorke Reset-Harness Write-Host "" +Write-Host "=== AG: a stopped run leaves no programs running ===" -ForegroundColor Cyan + +# PowerShell stopping a script (Ctrl+C outside Invoke-PkRun, a third press +# inside it, the runspace engine force-stopping a worker) skips catch blocks +# and runs only finally blocks. Each run below is stopped while its programs +# are running; each uses its own ping count so it can be told apart. +$stopKitPath = Join-Path $PSScriptRoot "ParallelKit.ps1" +function Stop-StrayPings { + param([int]$N) + Get-LimitPing $N | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue } +} +function Invoke-StoppedRun { + # Runs $Script (given the kit's path, then $ArgumentList) in its own + # [PowerShell], waits for $Expect pings of count $N, stops it, and + # returns how many were running before and after the stop. + param([scriptblock]$Script, [object[]]$ArgumentList = @(), [int]$N, [int]$Expect) + $ps = [PowerShell]::Create() + $null = $ps.AddScript($Script).AddArgument($stopKitPath) + foreach ($a in $ArgumentList) { $null = $ps.AddArgument($a) } + $null = $ps.BeginInvoke() + $sw = [System.Diagnostics.Stopwatch]::StartNew() + while ((Get-LimitPingCount $N) -lt $Expect -and $sw.Elapsed.TotalSeconds -lt 15) { Start-Sleep -Milliseconds 200 } + $before = Get-LimitPingCount $N + $ps.Stop() + $sw.Restart() + while ((Get-LimitPingCount $N) -gt 0 -and $sw.Elapsed.TotalSeconds -lt 3) { Start-Sleep -Milliseconds 200 } + $after = Get-LimitPingCount $N + Stop-StrayPings $N + $ps.Dispose() + return @{ Before = $before; After = $after } +} + +$stopRun = Invoke-StoppedRun -N 41 -Expect 2 -Script { + param($kit, $ping) + . $kit + Invoke-PkProcessBatch -MaxConcurrent 2 -Commands @(@{ FilePath = $ping; Arguments = '-n 41 127.0.0.1' }, @{ FilePath = $ping; Arguments = '-n 41 127.0.0.1' }) +} -ArgumentList @($pingExe) +Test-Assert ($stopRun.Before -eq 2 -and $stopRun.After -eq 0) ("stopping a batch kills its running programs (" + $stopRun.Before + " running, " + $stopRun.After + " left)") + +$stopBudget = [System.Threading.SemaphoreSlim]::new(2, 2) +$stopRun = Invoke-StoppedRun -N 42 -Expect 2 -Script { + param($kit, $ping, $budget) + . $kit + $feed = @{ Given = $false } + Invoke-PkProcessDispatch -MaxConcurrent $budget ` + -GroupProvider { if ($feed.Given) { return $null }; $feed.Given = $true; return 'g' }.GetNewClosure() ` + -JobBuilder { param($g) return @(@{ FilePath = $ping; Arguments = '-n 42 127.0.0.1' }, @{ FilePath = $ping; Arguments = '-n 42 127.0.0.1' }) }.GetNewClosure() ` + -JobFinalize { param($job, $q) $null = Complete-PkProcess -Job $job } +} -ArgumentList @($pingExe, $stopBudget) +Test-Assert ($stopRun.Before -eq 2 -and $stopRun.After -eq 0 -and $stopBudget.CurrentCount -eq 2) ("stopping a dispatcher kills its programs and gives back its shared slots (" + $stopRun.After + " left, " + $stopBudget.CurrentCount + " of 2 slots free)") + +# Stopped while -JobStarter is still running, after it set .Proc: the job +# isn't in the running list yet. +$stopBudget = [System.Threading.SemaphoreSlim]::new(2, 2) +$stopRun = Invoke-StoppedRun -N 44 -Expect 1 -Script { + param($kit, $ping, $budget) + . $kit + $feed = @{ Given = $false } + Invoke-PkProcessDispatch -MaxConcurrent $budget ` + -GroupProvider { if ($feed.Given) { return $null }; $feed.Given = $true; return 'g' }.GetNewClosure() ` + -JobBuilder { param($g) return @(@{ FilePath = $ping; Arguments = '-n 44 127.0.0.1' }) }.GetNewClosure() ` + -JobStarter { param($job) $s = Start-PkProcess -FilePath $job['FilePath'] -Arguments $job['Arguments']; $job['Proc'] = $s.Proc; $job['StdoutTask'] = $s.StdoutTask; $job['StderrTask'] = $s.StderrTask; Start-Sleep -Seconds 60; return $job } ` + -JobFinalize { param($job, $q) $null = Complete-PkProcess -Job $job } +} -ArgumentList @($pingExe, $stopBudget) +Test-Assert ($stopRun.Before -eq 1 -and $stopRun.After -eq 0 -and $stopBudget.CurrentCount -eq 2) ("stopping a dispatcher mid-start kills that program too and gives back its slot (" + $stopRun.After + " left, " + $stopBudget.CurrentCount + " of 2 slots free)") + +$stopRun = Invoke-StoppedRun -N 43 -Expect 1 -Script { + param($kit, $ping) + . $kit + Invoke-PkProcessWithTimeout -FilePath $ping -Arguments '-n 43 127.0.0.1' -TimeoutMs 120000 +} -ArgumentList @($pingExe) +Test-Assert ($stopRun.Before -eq 1 -and $stopRun.After -eq 0) ("stopping Invoke-PkProcessWithTimeout kills its program (" + $stopRun.Before + " running, " + $stopRun.After + " left)") + +# The runspace engine force-stops a worker whose dispatcher is still waiting +# out its own abort: the worker's programs must die with it. +Reset-Harness +$stopCts = [System.Threading.CancellationTokenSource]::new() +$stopWatch = [System.Diagnostics.Stopwatch]::StartNew() +$stopPoll = { if ($stopWatch.Elapsed.TotalSeconds -ge 1 -and (Get-LimitPingCount 46) -ge 2) { $stopCts.Cancel() } elseif ($stopWatch.Elapsed.TotalSeconds -ge 15) { $stopCts.Cancel() } }.GetNewClosure() +$stopOut = $null +try { + $stopOut = Invoke-PkRunspaceJobs -MaxParallel 1 -Cts $stopCts -DrainTimeoutSeconds 1 -AbortWaitMessage '' -PollCallback $stopPoll ` + -JobParams (New-JobList -Jobs @(@{ Ping = $pingExe })) ` + -WorkerScript { param($Ping) $null = Invoke-PkProcessBatch -MaxConcurrent 2 -Commands @(@{ FilePath = $Ping; Arguments = '-n 46 127.0.0.1' }, @{ FilePath = $Ping; Arguments = '-n 46 127.0.0.1' }) } +} catch { Write-Host " force-stopped worker run threw: $_" } +$stopWatch.Restart() +while ((Get-LimitPingCount 46) -gt 0 -and $stopWatch.Elapsed.TotalSeconds -lt 8) { Start-Sleep -Milliseconds 200 } +$stopLeft = Get-LimitPingCount 46 +Stop-StrayPings 46 +Test-Assert ($null -ne $stopOut -and $stopOut.ForceStoppedCount -eq 1 -and $stopLeft -eq 0) ("a force-stopped worker's programs are killed (" + $stopLeft + " left)") +$stopCts.Dispose() + +# Not a stop, but the same leak: a starter that started its program and then +# threw. The failed start is counted and reported; the program must not run on. +Reset-Harness +$stopBudget = [System.Threading.SemaphoreSlim]::new(2, 2) +$stopFeed = @{ Given = $false } +$stopResult = $null +try { + $stopResult = Invoke-PkProcessDispatch -MaxConcurrent $stopBudget ` + -GroupProvider { if ($stopFeed.Given) { return $null }; $stopFeed.Given = $true; return 'g' }.GetNewClosure() ` + -JobBuilder { param($g) return @(@{ FilePath = $pingExe; Arguments = '-n 48 127.0.0.1' }) }.GetNewClosure() ` + -JobStarter { param($job) $s = Start-PkProcess -FilePath $job['FilePath'] -Arguments $job['Arguments']; $job['Proc'] = $s.Proc; throw "starter failed after starting" } ` + -JobFinalize { param($job, $q) $null = Complete-PkProcess -Job $job } +} catch { Write-Host " throwing-starter run threw: $_" } +$stopLeft = Get-LimitPingCount 48 +Stop-StrayPings 48 +Test-Assert ($null -ne $stopResult -and $stopResult.JobStarterFailedCount -eq 1 -and $stopLeft -eq 0 -and $stopBudget.CurrentCount -eq 2) ("a starter that throws after starting its program doesn't leave it running (" + $stopLeft + " left, " + $stopBudget.CurrentCount + " of 2 slots free)") + +# An error out of the loop, after another job in the same pass was finalized +# and disposed: the teardown must still kill the job that's running. +Reset-Harness +$stopJobs = @(@{ Name = 'a'; FilePath = $cmdExe; Arguments = '/c exit 0' }, @{ Name = 'b'; FilePath = $cmdExe; Arguments = '/c exit 0' }, @{ Name = 'c'; FilePath = $pingExe; Arguments = '-n 47 127.0.0.1' }) +$stopFeed = @{ Given = $false } +$stopReady = @{ Done = $false } +$stopProblem = $null +try { + $null = Invoke-PkProcessDispatch -MaxConcurrent 3 ` + -GroupProvider { if ($stopFeed.Given) { return $null }; $stopFeed.Given = $true; return 'g' }.GetNewClosure() ` + -JobBuilder { param($g) return $stopJobs }.GetNewClosure() ` + -JobPollCompleted { + param($job) + if ($job['Name'] -eq 'c') { return $false } + # 'a' and 'b' only report done together, so both finish in one + # pass. Latched: 'a' is disposed once it's finalized. + if (-not $stopReady.Done) { + foreach ($j in $stopJobs[0..1]) { if ($null -eq $j['Proc'] -or -not $j['Proc'].HasExited) { return $false } } + if ((Get-LimitPingCount 47) -lt 1) { return $false } + $stopReady.Done = $true + } + return $true + }.GetNewClosure() ` + -JobFinalize { param($job, $q) $null = Complete-PkProcess -Job $job; if ($job['Name'] -eq 'b') { throw "finalize failed" } } +} catch { $stopProblem = [string]$_ } +$stopLeft = Get-LimitPingCount 47 +Stop-StrayPings 47 +Test-Assert ($stopProblem -like '*finalize failed*' -and $stopLeft -eq 0) ("an error after a job was finalized in the same pass still kills the running ones (" + $stopLeft + " left, problem: " + $stopProblem + ")") +Reset-Harness +Write-Host "" + Set-PkMessageHandler -Handler $null Reset-PkAbortState diff --git a/ParallelKit.ps1 b/ParallelKit.ps1 index f2f6738..aa6f2c3 100644 --- a/ParallelKit.ps1 +++ b/ParallelKit.ps1 @@ -1222,6 +1222,10 @@ function Invoke-PkProcessWithTimeout { } return Complete-PkProcess -Job $job -StreamTimeoutMs $StreamTimeoutMs } finally { + # Still running here only when PowerShell is stopping the script + # (that skips catch blocks, not finally ones): kill it before the + # process object goes. Best effort, as above. + try { if (-not $job['Proc'].HasExited) { $null = Stop-PkProcessTree -Process $job['Proc'] } } catch { } $job['Proc'].Dispose() } } @@ -1508,6 +1512,14 @@ function Invoke-PkProcessDispatchCore { JobStarterFailedCount = 0 } + # The job -JobStarter is working on: not in $pkRunning yet, but it may + # already have a program and a shared slot. + $pkStarting = $null + # Teardown is in a finally, guarded by this flag, not in a catch: when + # PowerShell stops the script (Ctrl+C outside Invoke-PkRun, the runspace + # engine force-stopping a worker) catch blocks are skipped and only + # finally blocks run. + $pkLoopDone = $false try { while ((-not $pkCancelToken.IsCancellationRequested) -and ` (-not $pkProviderExhausted -or $pkActiveGroupCount -gt 0 -or $pkPending.Count -gt 0 -or $pkRunning.Count -gt 0)) { @@ -1563,6 +1575,7 @@ function Invoke-PkProcessDispatchCore { $pkJob['Proc'] = $null; $pkJob['StdoutTask'] = $null; $pkJob['StderrTask'] = $null; $pkJob['Stopwatch'] = $null } $pkJob['SlotReleased'] = $false + $pkStarting = $pkJob # Before starting, so a bad key never leaves a program running. $pkStartFailureText = "ProcessDispatch: a job couldn't start: " $pkJob['TimeLimit'] = Get-PkJobTimeLimit -Job $pkJob -DefaultTimeoutSeconds $pkTimeoutSeconds @@ -1580,10 +1593,19 @@ function Invoke-PkProcessDispatchCore { $pkJob['TimedOut'] = $false if ($pkJob['TimeLimit'] -gt 0 -and $null -eq $pkJob['Stopwatch']) { $pkJob['Stopwatch'] = [System.Diagnostics.Stopwatch]::StartNew() } $pkRunning.Add($pkJob) + $pkStarting = $null } catch { # Release BEFORE reporting: if reporting throws, the slot # would otherwise leak (this job never reached $pkRunning, so - # the outer cleanup can't find it). + # the outer cleanup can't find it). $pkStarting is cleared + # first, so the teardown can't release the same slot again. + # A starter that started its program and then threw: nothing + # tracks that program now, so kill it before its slot goes back. + if ($pkJob['Proc'] -is [System.Diagnostics.Process]) { + try { $null = Stop-PkProcessTree -Process $pkJob['Proc'] } catch { } # best effort; the failed start is still reported below + try { $pkJob['Proc'].Dispose() } catch { } + } + $pkStarting = $null if ($pkIsSharedBudget) { $null = $pkMaxConcurrent.Release() } # The batch sets this key on its own jobs: it reports start failures itself. if (-not $pkJob['StartFailureReported']) { Write-PkMessage ($pkStartFailureText + $_) -Level Error } @@ -1662,150 +1684,147 @@ function Invoke-PkProcessDispatchCore { if ($pkIsSharedBudget -or -not $pkAnyFinished) { Wait-PkRunningJobs -Jobs $pkRunning -CancelToken $pkCancelToken -TimeoutMs 50 } } - } catch { - # Best-effort teardown on the way out; the original error is rethrown. - Stop-PkJobProcesses -Jobs $pkRunning - foreach ($pkJob in $pkRunning) { - try { if ($pkJob['Proc']) { $null = $pkJob['Proc'].WaitForExit(5000) } } catch { } - if (-not $pkJob['SlotReleased']) { - try { $null = & $pkJobAbortCleanup $pkJob } catch { } - if ($pkIsSharedBudget) { try { $null = $pkMaxConcurrent.Release() } catch { } } - } - try { if ($pkJob['Proc']) { $pkJob['Proc'].Dispose() } } catch { } - } - throw - } if ($pkCancelToken.IsCancellationRequested -and $pkRunning.Count -gt 0) { - try { - $pkAbortDeadline = [System.Diagnostics.Stopwatch]::StartNew() - while ($pkRunning.Count -gt 0 -and -not [PkConsoleCtrl]::IsCloseEvent -and -not [PkConsoleCtrl]::SkipDrain -and $pkAbortDeadline.Elapsed.TotalSeconds -lt $pkAbortTimeoutSeconds) { - # ---- BLOCK: graceful-wait loop ---- (keep in sync with the - # main poll pass above and the final pass below) - $pkStillWaiting = [System.Collections.Generic.List[hashtable]]::new() - foreach ($pkJob in $pkRunning) { - if ($pkJob['TimeLimit'] -gt 0) { Stop-PkTimedOutJob -Job $pkJob } - if (& $pkJobPollCompleted $pkJob) { - $pkPendingBefore = $pkPending.Count - $null = & $pkJobFinalize $pkJob $pkPending - try { if ($pkJob['Proc']) { $pkJob['Proc'].Dispose() } } catch { } - if ($pkIsSharedBudget) { $null = $pkMaxConcurrent.Release() } - $pkJob['SlotReleased'] = $true - # Whatever JobFinalize queued (a retry, follow-up steps) is counted - # into its group HERE, by looking at the queue - not by trusting a - # returned flag. A flag with nothing queued would hang the group - # forever; two follow-ups would let it finish early. - # Only when the queue actually grew - walking it on every finished - # job would cost a full pass over a large batch each time. - if ($pkPending.Count -gt $pkPendingBefore) { - $pkQueuedIndex = 0 - foreach ($pkQueued in $pkPending) { - if ($pkQueuedIndex -ge $pkPendingBefore) { - if ($null -eq $pkQueued['GroupKey']) { $pkQueued['GroupKey'] = $pkJob['GroupKey']; if (-not $pkQueued.ContainsKey('Group')) { $pkQueued['Group'] = $pkJob['Group'] } } - if ($pkGroupStates.ContainsKey($pkQueued['GroupKey'])) { $pkGroupStates[$pkQueued['GroupKey']].Outstanding++ } - } - $pkQueuedIndex++ + $pkAbortDeadline = [System.Diagnostics.Stopwatch]::StartNew() + while ($pkRunning.Count -gt 0 -and -not [PkConsoleCtrl]::IsCloseEvent -and -not [PkConsoleCtrl]::SkipDrain -and $pkAbortDeadline.Elapsed.TotalSeconds -lt $pkAbortTimeoutSeconds) { + # ---- BLOCK: graceful-wait loop ---- (keep in sync with the + # main poll pass above and the final pass below) + $pkStillWaiting = [System.Collections.Generic.List[hashtable]]::new() + foreach ($pkJob in $pkRunning) { + if ($pkJob['TimeLimit'] -gt 0) { Stop-PkTimedOutJob -Job $pkJob } + if (& $pkJobPollCompleted $pkJob) { + $pkPendingBefore = $pkPending.Count + $null = & $pkJobFinalize $pkJob $pkPending + try { if ($pkJob['Proc']) { $pkJob['Proc'].Dispose() } } catch { } + if ($pkIsSharedBudget) { $null = $pkMaxConcurrent.Release() } + $pkJob['SlotReleased'] = $true + # Whatever JobFinalize queued (a retry, follow-up steps) is counted + # into its group HERE, by looking at the queue - not by trusting a + # returned flag. A flag with nothing queued would hang the group + # forever; two follow-ups would let it finish early. + # Only when the queue actually grew - walking it on every finished + # job would cost a full pass over a large batch each time. + if ($pkPending.Count -gt $pkPendingBefore) { + $pkQueuedIndex = 0 + foreach ($pkQueued in $pkPending) { + if ($pkQueuedIndex -ge $pkPendingBefore) { + if ($null -eq $pkQueued['GroupKey']) { $pkQueued['GroupKey'] = $pkJob['GroupKey']; if (-not $pkQueued.ContainsKey('Group')) { $pkQueued['Group'] = $pkJob['Group'] } } + if ($pkGroupStates.ContainsKey($pkQueued['GroupKey'])) { $pkGroupStates[$pkQueued['GroupKey']].Outstanding++ } } + $pkQueuedIndex++ } - if ($null -ne $pkJob['GroupKey']) { - $pkKey = $pkJob['GroupKey'] - if ($pkGroupStates.ContainsKey($pkKey)) { - $pkState = $pkGroupStates[$pkKey] - $pkState.Outstanding-- - if ($pkState.Outstanding -le 0 -and -not $pkState.Completed) { - $null = & $pkGroupCompleteCallback $pkState.GroupInfo - $pkState.Completed = $true - $pkActiveGroupCount-- - $pkGroupResults.Add([pscustomobject][ordered]@{ GroupInfo = $pkState.GroupInfo; Completed = $true; Aborted = $false }) - } - } else { - Write-PkMessage ("ProcessDispatch: invariant violation - job's GroupKey is not registered (graceful-wait loop). This should be unreachable.") -Level Error + } + if ($null -ne $pkJob['GroupKey']) { + $pkKey = $pkJob['GroupKey'] + if ($pkGroupStates.ContainsKey($pkKey)) { + $pkState = $pkGroupStates[$pkKey] + $pkState.Outstanding-- + if ($pkState.Outstanding -le 0 -and -not $pkState.Completed) { + $null = & $pkGroupCompleteCallback $pkState.GroupInfo + $pkState.Completed = $true + $pkActiveGroupCount-- + $pkGroupResults.Add([pscustomobject][ordered]@{ GroupInfo = $pkState.GroupInfo; Completed = $true; Aborted = $false }) } + } else { + Write-PkMessage ("ProcessDispatch: invariant violation - job's GroupKey is not registered (graceful-wait loop). This should be unreachable.") -Level Error } - } else { - $pkStillWaiting.Add($pkJob) } + } else { + $pkStillWaiting.Add($pkJob) } - $pkRunning = $pkStillWaiting - if ($pkRunning.Count -gt 0) { [System.Threading.Thread]::Sleep(250) } } + $pkRunning = $pkStillWaiting + if ($pkRunning.Count -gt 0) { [System.Threading.Thread]::Sleep(250) } + } - # ---- BLOCK: mandatory final completion-check pass ---- - # A window-close can exit the loop above before a single poll, and - # a job can finish in the last 250ms before the deadline. One more - # pass so a finished job is never thrown away as "force-stopped". - # (keep in sync with the two blocks above, except the time limit: - # whatever is still running is force-stopped together just below) - if ($pkRunning.Count -gt 0) { - $pkStillWaiting = [System.Collections.Generic.List[hashtable]]::new() - foreach ($pkJob in $pkRunning) { - if (& $pkJobPollCompleted $pkJob) { - $pkPendingBefore = $pkPending.Count - $null = & $pkJobFinalize $pkJob $pkPending - try { if ($pkJob['Proc']) { $pkJob['Proc'].Dispose() } } catch { } - if ($pkIsSharedBudget) { $null = $pkMaxConcurrent.Release() } - $pkJob['SlotReleased'] = $true - # Whatever JobFinalize queued (a retry, follow-up steps) is counted - # into its group HERE, by looking at the queue - not by trusting a - # returned flag. A flag with nothing queued would hang the group - # forever; two follow-ups would let it finish early. - # Only when the queue actually grew - walking it on every finished - # job would cost a full pass over a large batch each time. - if ($pkPending.Count -gt $pkPendingBefore) { - $pkQueuedIndex = 0 - foreach ($pkQueued in $pkPending) { - if ($pkQueuedIndex -ge $pkPendingBefore) { - if ($null -eq $pkQueued['GroupKey']) { $pkQueued['GroupKey'] = $pkJob['GroupKey']; if (-not $pkQueued.ContainsKey('Group')) { $pkQueued['Group'] = $pkJob['Group'] } } - if ($pkGroupStates.ContainsKey($pkQueued['GroupKey'])) { $pkGroupStates[$pkQueued['GroupKey']].Outstanding++ } - } - $pkQueuedIndex++ + # ---- BLOCK: mandatory final completion-check pass ---- + # A window-close can exit the loop above before a single poll, and + # a job can finish in the last 250ms before the deadline. One more + # pass so a finished job is never thrown away as "force-stopped". + # (keep in sync with the two blocks above, except the time limit: + # whatever is still running is force-stopped together just below) + if ($pkRunning.Count -gt 0) { + $pkStillWaiting = [System.Collections.Generic.List[hashtable]]::new() + foreach ($pkJob in $pkRunning) { + if (& $pkJobPollCompleted $pkJob) { + $pkPendingBefore = $pkPending.Count + $null = & $pkJobFinalize $pkJob $pkPending + try { if ($pkJob['Proc']) { $pkJob['Proc'].Dispose() } } catch { } + if ($pkIsSharedBudget) { $null = $pkMaxConcurrent.Release() } + $pkJob['SlotReleased'] = $true + # Whatever JobFinalize queued (a retry, follow-up steps) is counted + # into its group HERE, by looking at the queue - not by trusting a + # returned flag. A flag with nothing queued would hang the group + # forever; two follow-ups would let it finish early. + # Only when the queue actually grew - walking it on every finished + # job would cost a full pass over a large batch each time. + if ($pkPending.Count -gt $pkPendingBefore) { + $pkQueuedIndex = 0 + foreach ($pkQueued in $pkPending) { + if ($pkQueuedIndex -ge $pkPendingBefore) { + if ($null -eq $pkQueued['GroupKey']) { $pkQueued['GroupKey'] = $pkJob['GroupKey']; if (-not $pkQueued.ContainsKey('Group')) { $pkQueued['Group'] = $pkJob['Group'] } } + if ($pkGroupStates.ContainsKey($pkQueued['GroupKey'])) { $pkGroupStates[$pkQueued['GroupKey']].Outstanding++ } } + $pkQueuedIndex++ } - if ($null -ne $pkJob['GroupKey']) { - $pkKey = $pkJob['GroupKey'] - if ($pkGroupStates.ContainsKey($pkKey)) { - $pkState = $pkGroupStates[$pkKey] - $pkState.Outstanding-- - if ($pkState.Outstanding -le 0 -and -not $pkState.Completed) { - $null = & $pkGroupCompleteCallback $pkState.GroupInfo - $pkState.Completed = $true - $pkActiveGroupCount-- - $pkGroupResults.Add([pscustomobject][ordered]@{ GroupInfo = $pkState.GroupInfo; Completed = $true; Aborted = $false }) - } - } else { - Write-PkMessage ("ProcessDispatch: invariant violation - job's GroupKey is not registered (final pass). This should be unreachable.") -Level Error + } + if ($null -ne $pkJob['GroupKey']) { + $pkKey = $pkJob['GroupKey'] + if ($pkGroupStates.ContainsKey($pkKey)) { + $pkState = $pkGroupStates[$pkKey] + $pkState.Outstanding-- + if ($pkState.Outstanding -le 0 -and -not $pkState.Completed) { + $null = & $pkGroupCompleteCallback $pkState.GroupInfo + $pkState.Completed = $true + $pkActiveGroupCount-- + $pkGroupResults.Add([pscustomobject][ordered]@{ GroupInfo = $pkState.GroupInfo; Completed = $true; Aborted = $false }) } + } else { + Write-PkMessage ("ProcessDispatch: invariant violation - job's GroupKey is not registered (final pass). This should be unreachable.") -Level Error } - } else { - $pkStillWaiting.Add($pkJob) } + } else { + $pkStillWaiting.Add($pkJob) } - $pkRunning = $pkStillWaiting } + $pkRunning = $pkStillWaiting + } - if ($pkRunning.Count -gt 0) { - $pkDispatchResult.ForceKilledCount = $pkRunning.Count - Write-PkMessage ("ProcessDispatch: force-stopping " + $pkRunning.Count + " job(s)" + (Get-PkForceStopReason -TimeoutSeconds $pkAbortTimeoutSeconds) + ".") -Level Warn - Stop-PkJobProcesses -Jobs $pkRunning - foreach ($pkJob in $pkRunning) { - try { if ($pkJob['Proc']) { $null = $pkJob['Proc'].WaitForExit(5000) } } catch { } - try { $null = & $pkJobAbortCleanup $pkJob } catch { } - try { if ($pkJob['Proc']) { $pkJob['Proc'].Dispose() } } catch { } - if ($pkIsSharedBudget) { try { $null = $pkMaxConcurrent.Release() } catch { } } - $pkJob['SlotReleased'] = $true - } - } - } catch { + # Same per-job steps as the teardown in the finally below; keep the two in step. + if ($pkRunning.Count -gt 0) { + $pkDispatchResult.ForceKilledCount = $pkRunning.Count + Write-PkMessage ("ProcessDispatch: force-stopping " + $pkRunning.Count + " job(s)" + (Get-PkForceStopReason -TimeoutSeconds $pkAbortTimeoutSeconds) + ".") -Level Warn Stop-PkJobProcesses -Jobs $pkRunning foreach ($pkJob in $pkRunning) { try { if ($pkJob['Proc']) { $null = $pkJob['Proc'].WaitForExit(5000) } } catch { } - if (-not $pkJob['SlotReleased']) { - try { $null = & $pkJobAbortCleanup $pkJob } catch { } - if ($pkIsSharedBudget) { try { $null = $pkMaxConcurrent.Release() } catch { } } - } + try { $null = & $pkJobAbortCleanup $pkJob } catch { } + try { if ($pkJob['Proc']) { $pkJob['Proc'].Dispose() } } catch { } + if ($pkIsSharedBudget) { try { $null = $pkMaxConcurrent.Release() } catch { } } + $pkJob['SlotReleased'] = $true + } + } + } + $pkLoopDone = $true + } finally { + if (-not $pkLoopDone) { + # Best-effort teardown on the way out of an error or a stop; an + # error carries on up by itself. A job with SlotReleased set was + # already finalized or force-stopped, and its process disposed: + # left alone, since a disposed Process makes Stop-PkProcessTree + # throw part-way through. Same per-job steps as the abort wait's + # force-stop above; keep the two in step. + $pkTearDown = [System.Collections.Generic.List[hashtable]]::new() + foreach ($pkJob in $pkRunning) { if (-not $pkJob['SlotReleased']) { $pkTearDown.Add($pkJob) } } + if ($null -ne $pkStarting -and -not $pkTearDown.Contains($pkStarting)) { $pkTearDown.Add($pkStarting) } + Stop-PkJobProcesses -Jobs $pkTearDown + foreach ($pkJob in $pkTearDown) { + try { if ($pkJob['Proc']) { $null = $pkJob['Proc'].WaitForExit(5000) } } catch { } + try { $null = & $pkJobAbortCleanup $pkJob } catch { } + if ($pkIsSharedBudget) { try { $null = $pkMaxConcurrent.Release() } catch { } } + $pkJob['SlotReleased'] = $true try { if ($pkJob['Proc']) { $pkJob['Proc'].Dispose() } } catch { } } - throw } }