diff --git a/.github/workflows/module.yml b/.github/workflows/module.yml index 70bf45a..2a9ebf5 100644 --- a/.github/workflows/module.yml +++ b/.github/workflows/module.yml @@ -1,11 +1,8 @@ name: Module -# Tests the kit built as a PowerShell module, and packs it for the PowerShell -# Gallery. Nothing is published: the package is kept with the run. Before a -# release (a version's branch is release/X.Y or version/X.Y) it runs the whole -# harness on the module. On a published release, by hand, and on a pull request -# that changes the build, it runs the sections where loading can matter. Not a -# required check. +# Tests the kit as a module and packs it for the Gallery (kept with the run, not +# published): the whole harness on a push to a release/ or version/ branch, the +# module sections (-Section MODULE) on everything else. on: push: branches: ['release/**', 'version/**'] diff --git a/.github/workflows/release-asset.yml b/.github/workflows/release-asset.yml index 8a155cc..e18a799 100644 --- a/.github/workflows/release-asset.yml +++ b/.github/workflows/release-asset.yml @@ -17,7 +17,8 @@ permissions: jobs: attach: name: Attach ParallelKit.ps1 - # Windows, so the attached file has Windows (CRLF) line endings. + # Windows, for powershell.exe; the file's CRLF line endings come from + # .gitattributes. runs-on: windows-latest steps: - uses: actions/checkout@v7 diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index f20fc94..b7244d9 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -13,10 +13,8 @@ permissions: # Ctrl+C/window-close checks must run here: a skip counts as a failure. env: PK_HARNESS_NO_SKIP: '1' - # A harness with no new assertion for this many minutes is dumped and - # killed by its own watchdog (the longest quiet stretch is about 20 s), so - # a hang fails its step with a dump to upload, instead of running into the - # job's time limit with nothing. + # A run with no new assertion for this long is dumped and killed by its own + # watchdog, so a hang fails its step with a dump to upload. PK_HARNESS_WATCHDOG_MINUTES: '2' jobs: @@ -27,8 +25,7 @@ jobs: steps: - uses: actions/checkout@v7 - # Windows PowerShell 5.1 (shell: powershell), the version the kit targets. - # A fresh powershell.exe so the kit's compiled types load clean. + # A fresh powershell.exe: a session keeps the C# types it compiled first. - name: Run ParallelKit.Harness.ps1 timeout-minutes: 14 shell: powershell @@ -48,12 +45,10 @@ jobs: & powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\ParallelKit.Harness.ps1 -AsModule -Section MODULE exit $LASTEXITCODE - # A section AH case that ran past its time limit leaves a full dump of - # its process there, for a debugger, and so does the harness itself - # when its watchdog finds it hung. Nothing is uploaded if none did. - # Cancelled too: a job that runs into its time limit is cancelled, not - # failed. The same in harness-pwsh below and both jobs of module.yml. The - # folder is set per step because a job's env can't use the runner context. + # Dumps of a harness case (section AH) or of the harness itself that hung, + # if any; also on a canceled (timed-out) job. The same in harness-pwsh and + # module.yml's jobs; the folder is set per step, as a job's env can't use + # the runner context. - name: Upload the dumps of cases that hung if: failure() || cancelled() uses: actions/upload-artifact@v7 @@ -99,10 +94,8 @@ jobs: if-no-files-found: ignore retention-days: 7 - # The C# in Source/: ParallelKit.ps1 carries the same code, and it compiles - # with no warnings as C# 5 with the .NET Framework's compiler (Add-Type's on - # Windows PowerShell 5.1), and with the .NET SDK for the .NET pwsh runs on, - # with the analyzer rules the script lists. + # Source/'s C# matches ParallelKit.ps1's copy and compiles warning-free as C# 5 + # with both .NET Framework's compiler and the .NET SDK. csharp: name: C# runs-on: windows-latest diff --git a/Build/New-ParallelKitModule.ps1 b/Build/New-ParallelKitModule.ps1 index 3e4b15b..67493ee 100644 --- a/Build/New-ParallelKitModule.ps1 +++ b/Build/New-ParallelKitModule.ps1 @@ -70,7 +70,8 @@ try { $SourcePath = (Get-Item -LiteralPath $SourcePath).FullName $OutputDirectory = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($OutputDirectory) - # The .ps1 is ASCII, which 5.1 and 7 read alike without a BOM. + # The .ps1 must be ASCII: without a byte-order mark, 5.1 and 7 read other + # bytes differently. $bytes = [System.IO.File]::ReadAllBytes($SourcePath) for ($i = 0; $i -lt $bytes.Length; $i++) { if ($bytes[$i] -gt 127) { Stop-PkBuild ("byte " + $i + " isn't ASCII. 5.1 and 7 would read the file differently.") } @@ -80,7 +81,8 @@ try { $lines = $source.TrimEnd("`n").Split("`n") $sourceAst = Get-PkBuildAst -Text $source -What 'the file' - # The three lines, in their places. + # Each wrapper line once: New-Module right after Remove-Module, and the + # closing line last. $removeAt = Get-PkBuildLineIndex -Lines $lines -Text $removeLine $openAt = Get-PkBuildLineIndex -Lines $lines -Text $openLine $closeAt = Get-PkBuildLineIndex -Lines $lines -Text $closeLine @@ -131,11 +133,10 @@ try { if ($header.Count -ne 1 -or $inCode.Count -ne 1) { Stop-PkBuild ("expected one '# Version X.Y' line and one `$version = [version]'X.Y' line, found " + $header.Count + " and " + $inCode.Count + ".") } $version = $header[0].Groups[1].Value if ($version -cne $inCode[0].Groups[1].Value) { Stop-PkBuild ("the header says version " + $version + " and Initialize-ParallelKit " + $inCode[0].Groups[1].Value + ".") } - # Three parts in the manifest. The package gets three whatever the manifest - # says, Windows PowerShell's built-in PowerShellGet installs into a folder - # named after the package's version, and PowerShell doesn't find a module - # whose version folder isn't its manifest's version. The harness works the - # same version out for its module folder (Get-HarnessModuleVersion). + # Three parts in the manifest: the package always gets three, Windows + # PowerShell's PowerShellGet installs it in a folder named after that, and + # PowerShell only finds a module whose folder name matches its manifest's + # version. The harness works it out the same way (Get-HarnessModuleVersion). $moduleVersion = $version if ($moduleVersion -notmatch '^\d+\.\d+\.\d+$') { $moduleVersion += '.0' } diff --git a/Build/Update-ParallelKitCSharp.ps1 b/Build/Update-ParallelKitCSharp.ps1 index c9abf7c..890c1bd 100644 --- a/Build/Update-ParallelKitCSharp.ps1 +++ b/Build/Update-ParallelKitCSharp.ps1 @@ -110,11 +110,12 @@ try { if ($null -eq $dotnet) { throw "Update-ParallelKitCSharp: -Compile needs the .NET SDK (dotnet) on PATH." } $runtime = (& $pwsh.Source -NoProfile -Command '[Environment]::Version.ToString(2)').Trim() $targetFramework = 'net' + $runtime - # Analyzer rules checked on top of the compiler's own warnings: ones about - # real faults, all clean today. Left out on purpose: style rules, and ones - # this code breaks deliberately (catch-all handlers that report the - # failure; DllImport of kernel32, a KnownDLL; handles a catch block - # releases, which the dispose rule can't follow). + # Analyzer rules checked on top of the compiler's warnings: ones about real + # faults. Left out on purpose: style rules, and ones this code breaks + # deliberately: catch-all handlers that report the failure, DllImport + # without a search-path attribute (kernel32 is a KnownDLL, always loaded + # from System32), and handles a catch block releases, which the dispose rule + # can't follow. $rules = @('CA1069', 'CA2002', 'CA2011', 'CA2013', 'CA2101', 'CA2200', 'CA2201', 'CA2208', 'CA2213', 'CA2216', 'CA2219', 'CA2241') $config = @('is_global = true') + @($rules | ForEach-Object { 'dotnet_diagnostic.' + $_ + '.severity = warning' }) foreach ($source in $sources) { diff --git a/ParallelKit.Harness.ps1 b/ParallelKit.Harness.ps1 index 9512b5e..8084a86 100644 --- a/ParallelKit.Harness.ps1 +++ b/ParallelKit.Harness.ps1 @@ -19,10 +19,9 @@ Set-StrictMode -Version Latest # The thread pool's minimum before the kit loads: the kit leaves it alone. $poolMinBefore = 0; $poolIoBefore = 0 [System.Threading.ThreadPool]::GetMinThreads([ref]$poolMinBefore, [ref]$poolIoBefore) -# What to load, here and in the child scripts, which dot-source $kitPath: the -# .ps1, or a one-line script that imports the module made from it. $kitSource is -# the file whose code runs, for the checks that read it; $kitPs1 is always the -# .ps1, for the checks on that file itself. +# What to load, here and in the child scripts: the .ps1, or a one-line script +# importing the module made from it. $kitSource is the code that runs; $kitPs1 +# is always the .ps1. $kitPs1 = Join-Path $PSScriptRoot "ParallelKit.ps1" $kitPath = $kitPs1 $kitSource = $kitPs1 @@ -44,12 +43,11 @@ if ($AsModule) { if ($LASTEXITCODE -ne 0) { Write-Host "The module couldn't be built (see above), so there's nothing to test." -ForegroundColor Red; exit 1 } $kitSource = Join-Path $moduleBuilt 'ParallelKit.psm1' $kitPath = Join-Path $moduleDir 'load.ps1' - # This version: another may be installed. + # This exact version: another copy of the module may be installed, and a + # plain Import-Module could load that one. [System.IO.File]::WriteAllText($kitPath, 'Import-Module ParallelKit -RequiredVersion ' + $moduleVersion + "`r`n") - # Put back at the end, for a run in a window that stays open. Not with a - # module analysis cache of its own: an empty one has every child process - # analyze every module installed, which took GitHub's 5.1 runner most of a - # minute each. + # Put back at the end. The module analysis cache is left alone: a new, empty + # one would have every child process analyze every installed module. $savedModulePath = $env:PSModulePath $env:PSModulePath = (Join-Path $moduleDir 'mods') + ';' + $savedModulePath } @@ -157,14 +155,8 @@ function Write-HarnessDump { # CI uploads this folder when the harness fails. $harnessDumpDir = if ($env:PK_HARNESS_DUMP_DIR) { $env:PK_HARNESS_DUMP_DIR } else { Join-Path $env:TEMP 'pk-harness-dumps' } -# A hang in the harness's own process would only end at CI's time limit, -# with nothing to show for it: the cases in AH have a time limit and a dump -# of their own, the rest doesn't. With PK_HARNESS_WATCHDOG_MINUTES set (CI -# sets it), a watchdog process waits on this one, and when no assertion has -# come for that long it dumps it into the dump folder, lists the programs it -# had running, and kills it and its tree by PID. The longest gap between -# assertions on CI is about 20 s. The watchdog shares this console, so what -# it says is in the log. +# With PK_HARNESS_WATCHDOG_MINUTES set (CI: 2), a watchdog dumps, lists and kills +# this process when no assertion comes for that long (CI's longest gap is ~20 s). $script:beatPath = $null $watchdogMinutes = 0.0 if ($env:PK_HARNESS_WATCHDOG_MINUTES) { @@ -180,11 +172,14 @@ $beat = 'PK_BEAT' $limit = [TimeSpan]::FromMinutes(PK_MINUTES) function Write-WatchdogLine([string]$Text) { [Console]::Out.WriteLine(' ' + $Text); [Console]::Out.Flush() } while (-not $harness.WaitForExit(5000)) { - # Gone once the harness is done; it may still be exiting. - if (-not [System.IO.File]::Exists($beat)) { continue } - if (([DateTime]::UtcNow - [System.IO.File]::GetLastWriteTimeUtc($beat)) -lt $limit) { continue } + # The harness removes the file when it's done; a missing file reads as + # written in 1601. + $written = [System.IO.File]::GetLastWriteTimeUtc($beat) + if ($written.Year -lt 2000 -or ([DateTime]::UtcNow - $written) -lt $limit) { continue } + $last = '(unreadable)' + try { $last = [System.IO.File]::ReadAllText($beat) } catch { } # removed just now: the dump still matters more $dump = Join-Path 'PK_DUMPDIR' ('harness-' + $harness.Id + '.dmp') - Write-WatchdogLine ('[FAIL] watchdog: no assertion for PK_MINUTES minute(s), so the harness is taken to have hung. The last one: ' + [System.IO.File]::ReadAllText($beat)) + Write-WatchdogLine ('[FAIL] watchdog: no assertion for PK_MINUTES minute(s), so the harness is taken to have hung. The last one: ' + $last) Write-WatchdogLine ('watchdog: dumping the harness (PID ' + $harness.Id + ') to ' + $dump) $dumpError = Write-HarnessDump -Process $harness -Path $dump if ($dumpError) { Write-WatchdogLine ('watchdog: ' + $dumpError) } @@ -1055,8 +1050,8 @@ $out = Invoke-PkRunspaceBatch -MaxConcurrent 2 -JobParams (New-JobList -Jobs @(1 -WorkerScript { param([int]$Id) if (Test-PkCancelRequested) { return }; return $Id } -ResultHandler { param($r) $results.Add($r) }.GetNewClosure() Test-Assert (-not $out.Aborted -and $results.Count -eq 4) "after Reset-PkAbortState the next run is normal again" -# An abort requested between the engines' checks (Request-PkAbort with no -# Test-PkAbortSignal after it, or from a callback) starts nothing more. +# An abort requested before a run, or from a callback, with no +# Test-PkAbortSignal call yet to act on it, still starts no more work. Reset-Harness Request-PkAbort $results = [System.Collections.Generic.List[object]]::new() @@ -1119,10 +1114,9 @@ $d = Invoke-PkProcessDispatch -MaxConcurrent 1 -MaxQueueAhead 1 -AbortTimeoutSec -JobBuilder { param($g) if ($late.Aborting) { $late.LateBuilds++ }; return @(@{ FilePath = $cmdExe; Arguments = '/c exit 0' }) }.GetNewClosure() ` -JobFinalize { param($job, $pending) $null = Complete-PkProcess -Job $job; if (-not $late.Aborting) { $late.Aborting = $true; Request-PkAbort } }.GetNewClosure() Test-Assert ($d.Aborted -and $late.Groups -eq 1 -and $late.LateBuilds -eq 0) ("dispatch: a -JobFinalize that requests an abort gets no more groups from -GroupProvider (asked for " + $late.Groups + " group(s), " + $late.LateBuilds + " built after the abort)") -# The same for an abort from the callbacks that run while groups are fetched, -# with room to queue 3 groups ahead: -GroupProvider isn't asked again, and no -# group asked for after the abort is built. -GroupCompleteCallback and -# -GroupReleaseCheck run there for groups with no jobs. +# The same for an abort from each callback that runs while groups are fetched, +# with 3 queued ahead: no more asks, and nothing built after it. Only the +# -JobBuilder case gives its groups a job. foreach ($fetchCase in 'GroupProvider', 'JobBuilder', 'GroupCompleteCallback', 'GroupReleaseCheck') { Reset-Harness $fetch = @{ Asked = 0; AbortedAt = -1; AskedAfter = 0; LateBuilds = 0; Case = $fetchCase } @@ -1283,12 +1277,10 @@ $probeThreads = -1; $probeWas = -2 if ($probe.Stdout -match 'threads=(\d+) was=(\d+)') { $probeThreads = [int]$Matches[1]; $probeWas = [int]$Matches[2] } Test-Assert ($probeThreads -eq $probeWas) ("and leaves the thread pool's minimum alone (" + $probeThreads + ", was " + $probeWas + ")") -# A script run the way a prompt runs it (& script, or .\script.ps1) holds -# the kit's functions in its own scope, where a .GetNewClosure() block can't -# see them. Dot-sourced or imported here, the kit's public functions are -# global, so a caller's closure that calls one works; the batch's own closures -# don't rely on that (section Z). -# Needs a fresh process, started with -Command rather than -File. +# A script run from a prompt (& script) keeps what it dot-sources in its own +# scope, out of a .GetNewClosure() block's sight; the kit's public functions are +# made global, so a closure can still call them. Needs a fresh process, started +# with -Command. $promptScript = Join-Path $env:TEMP ("pk-prompt-" + [guid]::NewGuid().ToString("N") + ".ps1") [System.IO.File]::WriteAllText($promptScript, @" . '$kitPath' @@ -1458,7 +1450,8 @@ $d = Invoke-HarnessOneGroupDispatch -Done $done -JobStarter $null -JobFinalize { $sw.Stop() Test-Assert ($done.Groups -eq 1 -and $sw.Elapsed.TotalSeconds -lt 10) "a JobFinalize return value is ignored - claiming a requeue with nothing queued doesn't hang the dispatcher" -# Two follow-up jobs, no flag: the group completes only after ALL of them. +# Two follow-up jobs queued, with no return value: the group completes only +# after both. Reset-Harness $feed = @{ Given = $false } $order = [System.Collections.Generic.List[string]]::new() @@ -1514,7 +1507,7 @@ $threw = $false try { $null = Invoke-PkRunspaceBatch -MaxConcurrent 1 -JobParams @(@{ Id = 1 }, $null) -WorkerScript { param($Id) } } catch { $threw = ($_.ToString() -like '*entry 1 is not a hashtable*') } Test-Assert $threw "-JobParams with a `$null entry fails the same way" -# So does a shared budget. +# A shared budget leaves the thread pool's minimum alone too. $bigBudget = [System.Threading.SemaphoreSlim]::new(150, 150) $null = Invoke-PkProcessDispatch -MaxConcurrent $bigBudget -GroupProvider { return $null } -JobBuilder { param($g) } -JobFinalize { param($j, $p) } $w = 0; $io = 0 @@ -1574,15 +1567,10 @@ $d = Invoke-PkProcessDispatch -MaxConcurrent 1 ` }.GetNewClosure() Test-Assert ($watches.Count -eq 2 -and $null -ne $watches[1] -and -not [object]::ReferenceEquals($watches[0], $watches[1])) "a job that goes around again gets a fresh stopwatch" -# A large batch isn't slowed by per-job queue walks. No processes: the -# starter/poll are stubs, so this times the dispatcher's own bookkeeping. -# Measured as a ratio, 20,000 jobs against 5,000 in the same run, so a slow -# runner doesn't fail it: linear bookkeeping takes about 4 times as long. A -# PowerShell-level walk of the queue per job made it 9 (7.7 s for 20,000 -# jobs on 5.1, inside the old 15 s limit). The quicker of two 5,000-job -# runs, so a slow spell there can't hide a walk. A ceiling of 45 s (about -# 3 times CI's slowest 5.1 runner) still catches a gross slowdown per job, -# which the ratio can't see. +# A large batch isn't slowed by walking the queue per job: stub starter and +# poll, so this times the dispatcher's bookkeeping. 20,000 jobs should take +# about 4 times as long as 5,000 in the same run; a per-job walk measured about +# 9, and the test fails at 8. A 45 s ceiling catches a gross slowdown per job. Reset-Harness function Measure-HarnessBookkeeping { param([int]$Count) @@ -1631,7 +1619,8 @@ $closeMessage = @($script:messages | Where-Object { $_.Message -like '*Window cl Test-Assert ($closeMessage.Count -eq 1 -and $closeMessage[0].Message -notlike '*please wait*' -and $closeMessage[0].Message -like '*stopping*') ("a window close is announced as stopping jobs, not waiting for them (" + (@($closeMessage | ForEach-Object { $_.Message }) -join ' | ') + ")") Reset-PkAbortState -# The same from inside a worker, where the run's cancel is what it sees. +# The same inside a worker, which sees the run's canceled token rather than the +# abort flag. Reset-Harness $poll = @{ Count = 0 } $workerErrors = [System.Collections.Generic.List[object]]::new() @@ -1715,18 +1704,18 @@ $threw = $false try { $null = Invoke-PkProcessWithTimeout -FilePath $pingExe -Arguments '-n 3 127.0.0.1' } catch { $threw = ($_.ToString() -like '*being aborted*') } Test-Assert $threw "while an abort is in force, the helper stops a program by default" $cleanup = $null -try { $cleanup = Invoke-PkProcessWithTimeout -FilePath $pingExe -Arguments '-n 3 127.0.0.1' -IgnoreAbort } catch { } +try { $cleanup = Invoke-PkProcessWithTimeout -FilePath $pingExe -Arguments '-n 3 127.0.0.1' -IgnoreAbort } catch { } # checked below: no result fails the assertion Test-Assert ($null -ne $cleanup -and $cleanup.ExitCode -eq 0) "-IgnoreAbort lets a cleanup program run to the end during an abort" -# A program quick enough to finish before the abort was looked at used to run. -# Each writes a file, so a run leaves a trace. +# During an abort, no program starts, however quick; each writes a file, so a +# start would leave a trace. $quickDir = Join-Path $env:TEMP ("pk-harness-quick-" + $PID) $null = New-Item -ItemType Directory -Force -Path $quickDir $quickError = $null try { $null = Invoke-PkProcessWithTimeout -FilePath $cmdExe -Arguments ('/c echo ran> "' + $quickDir + '\abort.txt"') } catch { $quickError = [string]$_ } Test-Assert ($quickError -like "*wasn't started because the run is being aborted*" -and -not (Test-Path -LiteralPath ($quickDir + '\abort.txt'))) ("during an abort, a quick program isn't started (" + $quickError + ")") $quick = $null -try { $quick = Invoke-PkProcessWithTimeout -FilePath $cmdExe -Arguments ('/c echo ran> "' + $quickDir + '\ignore.txt"') -IgnoreAbort } catch { } +try { $quick = Invoke-PkProcessWithTimeout -FilePath $cmdExe -Arguments ('/c echo ran> "' + $quickDir + '\ignore.txt"') -IgnoreAbort } catch { } # checked below: no result fails the assertion Test-Assert ($null -ne $quick -and (Test-Path -LiteralPath ($quickDir + '\ignore.txt'))) "-IgnoreAbort still runs it" Reset-Harness # The same in a worker, when its run is canceled rather than aborted. @@ -1849,10 +1838,9 @@ $null = Wait-PkProcess -Process $j.Proc -TimeoutMs 5000 Test-Assert (-not (Stop-PkProcessTree -Process $j.Proc)) "Stop-PkProcessTree reports `$false for a program that already exited" $j.Proc.Dispose() -# Every other place the kit kills a program kills its children too: a -# Invoke-PkProcessWithTimeout overrun, and the dispatcher's force-stop -# after an abort. Each test's ping has its own count, so a surviving one -# can be found by its command line. +# Every other kill takes the children too: an Invoke-PkProcessWithTimeout +# overrun and an abort's force-stop. Each ping has its own count, to find a +# survivor by its command line. function Get-HarnessPingCount([int]$Count) { return @(Get-CimInstance Win32_Process -Filter "Name = 'PING.EXE'" | Where-Object { $_.CommandLine -like ("*-n " + $Count + " 127.0.0.1*") }).Count } @@ -1883,10 +1871,9 @@ $killedPair = $false if ($null -ne $childProc) { $killedPair = Stop-PkProcessTree -Process @($parentJob.Proc, $childProc) } Test-Assert ($null -ne $childProc -and $killedPair -and $parentJob.Proc.HasExited -and $childProc.HasExited) ("Stop-PkProcessTree kills a parent and its child passed together, and says so (found child: " + ($null -ne $childProc) + ", returned: " + $killedPair + ")") $parentJob.Proc.Dispose(); if ($null -ne $childProc) { $childProc.Dispose() } -# A large kill: taskkill prints a line per process it kills (three per -# `cmd /c ping` tree). Left unread, that fills its output pipe and taskkill -# blocks until the 10 s wait gives up, leaving most children running. -# Started without tree jobs, so the kill goes to taskkill. +# A large kill through taskkill (no tree jobs): it prints a line per process, +# and an unread pipe would block it until its 10 s wait gives up, leaving +# children running. [PkChildProcessJob]::TestNoTreeJob = $true try { $many = @(1..40 | ForEach-Object { Start-PkProcess -FilePath $cmdExe -Arguments (& $nestedPing 49) }) } finally { [PkChildProcessJob]::TestNoTreeJob = $false } $waitMany = [System.Diagnostics.Stopwatch]::StartNew() @@ -1905,10 +1892,8 @@ $threw = $false try { $null = Invoke-PkProcessBatch -Commands @(@{ FilePath = $cmdExe; Arguments = '/c exit 0' }) -TimeoutSeconds -1 } catch { $threw = ($_.ToString() -like '*-TimeoutSeconds*') } Test-Assert $threw "a negative -TimeoutSeconds is refused" -# An aborted group still gets -GroupCompleteCallback (the README warns about -# this - a caller zipping a folder there must check for the abort first). -# The abort comes once the group is built: one already in force means no -# group is asked for at all. +# An aborted group still gets -GroupCompleteCallback, as the README warns; an +# abort already in force means no group is asked for at all. Reset-Harness $called = @{ Count = 0; SawAbort = $false } $feed = @{ Given = $false } @@ -1924,9 +1909,9 @@ Write-Host "" # ============================================================================== if (Test-HarnessSection 'U' "pressing Ctrl+C again") { -# [PkConsoleCtrl]::OnInterrupt is what the native handler calls for each -# Ctrl+C/Ctrl+Break press during a run, so calling it here is a key press -# minus Windows. Real console events are covered separately. +# [PkConsoleCtrl]::OnInterrupt is what the native handler calls for each Ctrl+C +# or Ctrl+Break press during a run; calling it directly is a press without +# Windows. Section V sends real console events. # The press sequence: start the abort, skip the drain, then let it through. Reset-Harness @@ -2010,8 +1995,8 @@ $sw.Stop() $null = $presser.PS.EndInvoke($presser.Handle); $presser.PS.Dispose() Test-Assert ($rsOut.Aborted -and $rsOut.ForceStoppedCount -eq 3 -and $sw.Elapsed.TotalSeconds -lt 8) ("runspace jobs: a second Ctrl+C force-stops running workers right away (" + [math]::Round($sw.Elapsed.TotalSeconds, 1) + "s, stopped " + $rsOut.ForceStoppedCount + "; the workers run 15s)") -# The handler thread a window close parks stays parked until the run ends, -# not just the drain, so the rest of the run gets Windows' few seconds. +# After a window close, the native handler's thread is held until the whole run +# ends, not just the abort's wait: Windows ends the process once it returns. Reset-Harness $parked = @{ AfterDrain = $null } $poll = @{ Count = 0 } @@ -2028,15 +2013,10 @@ Write-Host "" # ============================================================================== if (Test-HarnessSection 'V' "real console events (Ctrl+C, Ctrl+Break, window close)") { -# Everything above fakes the abort flags. Here Windows itself calls the kit's -# handler. Each scenario runs a child PowerShell in a console of its own (a -# hidden window), and the events go to that console only: Ctrl+C/Ctrl+Break -# from a helper process that attaches to it, a close as WM_CLOSE to its -# window. Nothing is ever sent to the console this harness runs in. -# -# The child also registers a probe handler after the kit's, so Windows calls -# it first. If the probe never saw the first event, Windows didn't deliver -# it, and the scenario is skipped rather than blamed on the kit. +# Real console events, through the kit's handler: each scenario runs a child +# PowerShell in a hidden console of its own, and the events go to that console +# only. A probe handler registered after the kit's runs first; if it never saw +# the event, Windows didn't deliver it, and the scenario is skipped. if (-not ([System.Management.Automation.PSTypeName]'PkHarnessWin').Type) { Add-Type -TypeDefinition @' @@ -2074,7 +2054,7 @@ public static class PkHarnessProbe { public static bool Register(string path) { _path = path; _h = new HandlerRoutine(H); return SetConsoleCtrlHandler(_h, true); } private static bool H(uint t) { // A lost line only makes the harness skip; a throw here would end the process. - try { File.AppendAllText(_path, DateTime.UtcNow.Ticks.ToString() + " event " + t + "\r\n"); } catch { } + try { File.AppendAllText(_path, DateTime.UtcNow.Ticks.ToString() + " event " + t + "\r\n"); } catch { } // a line the log can't take is only a missing trace return false; } } @@ -2107,8 +2087,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. +# The full version of the senders in Testing/stop-in-call (PkProbeSender) and +# Testing/ps7-native (PkPs7NativeSender), which send only one Ctrl+C. [System.IO.File]::WriteAllText($senderScript, @' param([int]$TargetPid, [int]$EventType, [string]$LogFile) Add-Type -TypeDefinition @" @@ -2162,13 +2142,11 @@ function Get-HarnessLogTicks { } $hostExe = [System.Diagnostics.Process]::GetCurrentProcess().MainModule.FileName -# Events: C = Ctrl+C, B = Ctrl+Break, X = window close. At = seconds after the -# child logs "ready" (or "idle" when there's no run), or 'idle' = just after -# the run has returned. An event after a Ctrl+C/Ctrl+Break also waits until -# that helper has reported back and 1.5s more (past the kit's 1s debounce): -# a helper still attached when the next event lands can be killed by it, and -# on a slow machine the helper itself can take seconds to start. -# WaitFor = what ends the scenario. +# Events: C = Ctrl+C, B = Ctrl+Break, X = window close. At: seconds after the +# child logs 'ready' (or 'idle' with no run), or 'idle' for just after the run +# returns. An event after C or B waits for that sender to report back, plus 1.5 +# s, past the kit's 1 s debounce between presses. WaitFor: what ends the +# scenario. $scenarios = @( @{ Name = 'ctrlc'; Mode = 'run'; Timeout = 3; Events = @(@{ Kind = 'C'; At = 1.5 }, @{ Kind = 'C'; At = 'idle' }); WaitFor = 'exit' } @{ Name = 'break'; Mode = 'run'; Timeout = 3; Events = @(@{ Kind = 'B'; At = 1.5 }); WaitFor = 'idle' } @@ -2275,7 +2253,8 @@ foreach ($s in $scenarios) { Test-Assert $false ($label + "the child loaded the kit and started (log: " + (@($lines | Select-Object -Last 3) -join ' | ') + ")") continue } - # Fill in when each Ctrl+C/Ctrl+Break was really sent, from the senders' logs. + # Fill in when each Ctrl+C or Ctrl+Break was really sent, from the 'sent' + # lines the sender processes write to their logs. $keySends = @($s.Sent | Where-Object { $_.Kind -ne 'X' }) $failedSend = @($sends | Where-Object { $_ -notlike 'sent *' }) if ($failedSend.Count -gt 0) { Test-Skip ($label + "couldn't send the console event (" + ($failedSend -join ', ') + ")"); continue } @@ -2467,11 +2446,9 @@ Write-Host "" # ============================================================================== if (Test-HarnessSection 'Y' "output that's been dropped is freed during the run") { -# 30 programs printing ~150 KB each. A caller who drops each output once it's -# handled shouldn't have the kit keep it alive until the run ends. Weak -# references show what a full GC can free while the last job is finishing. -# A few of the most recent jobs can still be referenced from the dispatch -# loop (5-7 at -MaxConcurrent 4, however long the run). +# 30 programs printing ~150 KB each: output a caller drops must not stay alive +# until the run ends. Weak references show what a full GC frees; the dispatch +# loop can still hold the last few jobs. Reset-Harness $chatty = @(1..30 | ForEach-Object { @{ FilePath = $cmdExe; Arguments = ('/c for /l %i in (1,1,1500) do @echo ' + ('x' * 100)) } }) $batchWeak = [System.Collections.Generic.List[System.WeakReference]]::new() @@ -2542,10 +2519,9 @@ $fromRun = Invoke-PkRun { $ScriptBlock } Remove-Variable -Name ScriptBlock Test-Assert ($fromRun -eq 'mine') ("Invoke-PkRun's block reads the caller's `$ScriptBlock, not Invoke-PkRun's parameter (" + $fromRun + ")") -# -SharedFunctionNames and Test-PkWorkerSafety find the caller's functions -# however the script was started. A script run from a prompt (& script) -# keeps its functions in its own scope, not global, so this needs a fresh -# process started with -Command. +# -SharedFunctionNames and Test-PkWorkerSafety find a script's functions even +# when it was run from a prompt, which keeps them in the script's own scope; +# that needs a fresh process. $lookupScript = Join-Path $env:TEMP ("pk-lookup-" + [guid]::NewGuid().ToString("N") + ".ps1") [System.IO.File]::WriteAllText($lookupScript, @" . '$kitPath' @@ -2592,10 +2568,9 @@ $modOut = ([string]$modRun.Stdout + [string]$modRun.Stderr).Trim() -replace '\s+ Test-Assert ($modOut -match 'module private=105') ("a module's private function can be shared with workers (" + $modOut + ")") Test-Assert ($modOut -match 'kit modules=1') "loading the kit a second time leaves one ParallelKit module, not two" -# The batch's own callbacks are closures, which only see global functions. The -# batch must not count on its public functions being global: here the kit is -# loaded inside another module, for that module only. One command runs and one -# can't start, so both of the kit's own closures that call a public function do. +# The batch's closures only see global functions, so it can't count on its +# public ones being global: here the kit is loaded inside another module, for +# that module only. if ($AsModule) { $scopeText = "Import-Module '" + (Join-Path $moduleBuilt 'ParallelKit.psd1') + "'" } else { @@ -2730,8 +2705,8 @@ Test-Assert ($fnDrive.FileText -like 'pk-fn ran in *') ("and so does a FilePath $noDrive = $null try { $null = Invoke-PkProcessWithTimeout -FilePath $cmdExe -Arguments '/c cd' -WorkingDirectory 'PkNoSuchDrive:\x' } catch { $noDrive = [string]$_ } Test-Assert ($noDrive -like '*could not start*') "a drive that doesn't exist anywhere still fails with a clear start error" -# PowerShell treats curly quotes as string delimiters too, so a path can't be -# allowed to end the literal it's embedded in when looked up in the caller's session. +# PowerShell also ends strings at curly quotes, and a drive lookup in the +# caller's session puts the path in a string: a path mustn't be able to end it. $curly = [string][char]0x2019 $global:pkHarnessInjected = $false try { $null = Invoke-PkProcessWithTimeout -FilePath $cmdExe -Arguments '/c cd' -WorkingDirectory ('PkNoDrive' + $curly + '); $global:pkHarnessInjected = $true; (' + $curly + ':\x') } catch { $null = $_ } # failing to start is expected here; only the flag matters @@ -2739,9 +2714,10 @@ $injected = $global:pkHarnessInjected Remove-Variable -Name pkHarnessInjected -Scope Global Test-Assert (-not $injected) "a path with a curly quote stays a path when it's looked up in the caller's session" -# \tools and C:tools depend on a current drive and folder: PowerShell's, not -# the process's. (Only a real test when the process's folder is on another -# drive, which it is on GitHub's runners and usually elsewhere.) +# A path with no drive (\Windows\System32) or a drive with no folder +# (C:System32) depends on PowerShell's current location, not the process's. A +# real test only when the process's folder is on another drive, as on GitHub's +# runners. Reset-Harness $windows = $env:SystemRoot $noDriveDir = $windows.Substring(2) + '\System32' @@ -2787,9 +2763,8 @@ Write-Host "" # ============================================================================== if (Test-HarnessSection 'AB' "a finished job's slot is refilled without waiting out a sleep") { -# Timing, so up to three tries: a busy machine can only make a run slower, and -# polling can't get under its floor however idle the machine is. -# Two 50 ms sleeps per program at -MaxConcurrent 1 can't average under 100 ms. +# A dispatcher that slept 50 ms between polls would need two sleeps per program +# at -MaxConcurrent 1, over 100 ms each; the test allows 90. $bestPerProgram = [double]::MaxValue for ($try = 0; $try -lt 3 -and $bestPerProgram -ge 90; $try++) { $shortCommands = foreach ($i in 1..30) { @{ FilePath = $cmdExe; Arguments = '/d /c exit 0' } } @@ -2801,7 +2776,8 @@ for ($try = 0; $try -lt 3 -and $bestPerProgram -ge 90; $try++) { Test-Assert ($shortBatch.Results.Count -eq 30) "every short program has a result" Test-Assert ($bestPerProgram -lt 90) ("short programs aren't held back by the poll (best average " + [int]$bestPerProgram + " ms each)") -# The same floor for runspace jobs: one 100 ms sleep per 20 ms worker. +# The same for runspace jobs: a 100 ms poll sleep per 20 ms worker would fail +# the 70 ms limit. $bestPerJob = [double]::MaxValue for ($try = 0; $try -lt 3 -and $bestPerJob -ge 70; $try++) { $sw = [System.Diagnostics.Stopwatch]::StartNew() @@ -2815,9 +2791,10 @@ for ($try = 0; $try -lt 3 -and $bestPerJob -ge 70; $try++) { } Test-Assert ($bestPerJob -lt 70) ("short workers aren't held back by the poll (best average " + [int]$bestPerJob + " ms each)") -# A -JobPollCompleted that keeps saying "not done" after a process exits must -# not leave that process's signaled handle in the wait, or the loop spins: -# first while the second program still runs, then with both exited. +# A -JobPollCompleted that keeps saying not done after its program exits mustn't +# leave that signaled handle in the wait, or every wait ends at once and the +# loop spins. Checked while the second program still runs, then with both +# exited. $spinState = @{ Given = $false; Polls = 0 } $spinRun = Invoke-PkProcessDispatch -MaxConcurrent 2 ` -GroupProvider { if ($spinState.Given) { return $null }; $spinState.Given = $true; return 'g' }.GetNewClosure() ` @@ -2826,7 +2803,7 @@ $spinRun = Invoke-PkProcessDispatch -MaxConcurrent 2 ` -JobFinalize { param($job, $q) $null = Complete-PkProcess -Job $job } Test-Assert ($spinRun.GroupResults.Count -eq 1 -and $spinState.Polls -lt 500) ("a lagging -JobPollCompleted doesn't spin the loop (" + $spinState.Polls + " polls in 2 s)") -# More running programs than one wait can hold. +# 70 programs at once: more than the 62 one wait can hold. $wideCommands = foreach ($i in 1..70) { @{ FilePath = $pingExe; Arguments = '-n 2 127.0.0.1' } } $wide = Invoke-PkProcessBatch -Commands $wideCommands -MaxConcurrent 70 $wideOk = @($wide.Results | Where-Object { $_.ExitCode -eq 0 }).Count @@ -2955,8 +2932,9 @@ Test-Assert ($fraction.Count -eq 1 -and $fraction[0].TimedOut -eq $true -and $fr $fractionBatch = Invoke-PkProcessBatch -TimeoutSeconds 0.4 -Commands @(@{ FilePath = $pingExe; Arguments = '-n 30 127.0.0.1' }) Test-Assert ($fractionBatch.Results[0].TimedOut -eq $true) "and neither is the batch's" -# On the main thread too, a plain callback reads the caller's $TimeoutSeconds: -# reading the kit's 0 here would finish the job at once. +# A plain callback must read the caller's $TimeoutSeconds (1.5 here), not the +# dispatcher's parameter of that name (left at its default, 0), which would end +# the job at once. $TimeoutSeconds = 1.5 $limitRun = Invoke-LimitGroup -Jobs @(@{ Name = 'plain'; FilePath = $cmdExe; Arguments = '/c exit 0' }) -Extra @{ TimeoutSeconds = 30 @@ -3202,12 +3180,9 @@ if ($compiled) { } try { [System.IO.File]::Delete($batFile) } catch { } # temp file only; best effort - # A quote in a list element for a .bat/.cmd: cmd.exe counts every quote, - # \" included, so with \" an element like a" & & " runs that - # command; the kit writes "" instead. The batch file does nothing, so only - # cmd.exe's reading of the command line could create the marker. It's a - # bare name in the working folder, so a space in %TEMP% can't send it - # elsewhere and let the check pass anyway. + # A quote in a list element for a .bat or .cmd is written "", since with \" + # an element like a" & & " would run . The batch file + # does nothing, so only cmd.exe reading the line could create the marker. $injDir = Join-Path $env:TEMP ("pk-inj-" + [guid]::NewGuid().ToString("N")) $null = New-Item -ItemType Directory -Path $injDir $injMarker = Join-Path $injDir 'pk-marker.txt' @@ -3239,9 +3214,8 @@ if ($compiled) { $fwdExpected = (@($fwdArgs | ForEach-Object { '[' + $_ + ']' }) -join '') Test-Assert ($text -ceq $fwdExpected) ("a .cmd that passes %* on gets the list through exactly (" + $text + ")") - # cmd.exe itself given a list gets the same quoting: the program after /c - # still gets the list exactly (spaces, quotes, trailing backslashes), and - # no element can make cmd.exe run another command. Under any spelling of + # cmd.exe given a list gets the same quoting: the program after /c gets the + # list exactly, and no element runs another command, under any spelling of # cmd.exe's name. $text = $null try { $text = Get-ArgvText (Invoke-PkProcessWithTimeout -FilePath $cmdExe -Arguments (@('/d', '/c', $argvExe) + $fwdArgs) -TimeoutMs 10000).Stdout } catch { $text = "threw: $_" } @@ -3431,10 +3405,9 @@ Write-Host "" # ============================================================================== if (Test-HarnessSection 'AG' "a stopped run leaves no programs running") { -# 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. +# PowerShell stopping a script skips catch blocks and runs only finally ones. +# Each run is stopped while its programs run; each has its own ping count, to +# find its programs. 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 @@ -3547,8 +3520,9 @@ try { -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. + # 'a' and 'b' report done together, so both finish in one pass. The + # flag stays set: 'a' is disposed once finalized, so it can't be + # checked again. 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 } @@ -3651,19 +3625,14 @@ Write-Host "" # ============================================================================== if (Test-HarnessSection 'AH' "'continue' or 'break' in a callback stays in the callback") { -# PowerShell sends continue/break to the nearest loop on the call stack, which -# for a callback is one of the kit's own. Each case runs in a PowerShell -# process of its own, so one that hangs fails after a time limit and names the -# case, instead of hanging the suite: a [PowerShell] in this process couldn't -# promise that, since its Stop() waits for the case and can block for good. In -# each, KEYWORD becomes the keyword; the case sets $kwOk and $kwDetail. The kit -# must finish the run correctly and warn once. +# continue/break in a callback goes to the nearest loop on the stack: one of the +# kit's. Each case runs in its own process, so one that hangs fails after a time +# limit instead of hanging the suite. KEYWORD becomes the keyword; the case sets +# $kwOk and $kwDetail. function Invoke-HarnessCaseProcess { - # Runs a program, for the cases a fresh PowerShell of the harness's own - # version, and waits up to $TimeoutMs. Not through the kit, which is what's - # under test. On a timeout it first records what the process was doing (its - # child processes, and a dump when $DumpPath is given), then kills it and - # its tree by PID. + # Runs a program (for the cases, a fresh PowerShell of this version), not + # through the kit, and waits up to $TimeoutMs. On a timeout it lists its + # children, dumps it if asked, then kills its tree by PID. param([string]$FilePath, [string]$Arguments, [int]$TimeoutMs, [string]$DumpPath = '') $psi = [System.Diagnostics.ProcessStartInfo]::new($FilePath, $Arguments) $psi.UseShellExecute = $false @@ -3679,8 +3648,8 @@ function Invoke-HarnessCaseProcess { $r.ExitCode = $p.ExitCode } else { $r.TimedOut = $true - # The kill happens whatever the notes before it do: the harness runs - # with errors stopping it, and a hung case must not outlive it. + # The kill runs even if listing the children or the dump throws: the + # harness stops on errors, and a hung case mustn't outlive it. try { try { $r.Children = @(Get-CimInstance Win32_Process -Filter ("ParentProcessId = " + $p.Id) -OperationTimeoutSec 30 | ForEach-Object { @{ Name = [string]$_.Name; Pid = [int]$_.ProcessId } }) @@ -3702,8 +3671,8 @@ $kwDumpDir = $harnessDumpDir $kwWork = Join-Path $env:TEMP ("pk-harness-ah-" + $PID) $null = [System.IO.Directory]::CreateDirectory($kwWork) -# The time limit itself, on a case that can't be stopped from inside: a .NET -# wait with no timeout, with a ping.exe of its own running. +# Invoke-HarnessCaseProcess's time limit, on a case that never ends by itself: a +# .NET wait with no timeout, with a ping.exe of its own running. $kwHangScript = Join-Path $kwWork 'hang.ps1' [System.IO.File]::WriteAllText($kwHangScript, "`$i = [System.Diagnostics.ProcessStartInfo]::new('" + $pingExe + "', '-n 30 127.0.0.1')`r`n`$i.UseShellExecute = `$false; `$i.CreateNoWindow = `$true; `$i.RedirectStandardOutput = `$true`r`n`$c = [System.Diagnostics.Process]::Start(`$i)`r`n'started ' + `$c.Id`r`n`$null = [System.Threading.ManualResetEvent]::new(`$false).WaitOne()`r`n") $kwSw = [System.Diagnostics.Stopwatch]::StartNew() @@ -3713,8 +3682,8 @@ $kwHangPing = @($kwHang.Children | Where-Object { $_.Name -eq 'PING.EXE' }) $kwHangLeft = @($kwHangPing | Where-Object { $null -ne (Get-Process -Id $_.Pid -ErrorAction SilentlyContinue) }) Test-Assert ($kwHang.TimedOut -and $kwHang.Gone -and $kwSw.Elapsed.TotalSeconds -lt 20 -and $kwHang.Stdout -like 'started *') ("a case that can't be stopped is cut off at its time limit, with its output so far (" + $kwHangSecs + " s, gone: " + $kwHang.Gone + ", output: " + $kwHang.Stdout.Trim() + $(if (-not $kwHang.TimedOut) { "; it ended by itself, exit code 0x" + ([int]$kwHang.ExitCode).ToString('X8') + ", stderr: " + $kwHang.Stderr.Trim() }) + ")") Test-Assert ($kwHangPing.Count -eq 1 -and $kwHangLeft.Count -eq 0) ("its child processes are listed, and killed with it (ping listed " + $kwHangPing.Count + "x, left running " + $kwHangLeft.Count + ")") -# The dump, on ping.exe as the program that runs too long: a full dump of a -# PowerShell is hundreds of MB, one of ping a few. +# The dump is taken of ping.exe running past its limit: a full dump of +# PowerShell is hundreds of MB, ping's a few. $kwDumpFile = Join-Path $kwWork 'check.dmp' $kwDumped = Invoke-HarnessCaseProcess -FilePath $pingExe -Arguments '-n 30 127.0.0.1' -TimeoutMs 1000 -DumpPath $kwDumpFile $kwDumpSize = if (Test-Path -LiteralPath $kwDumpFile) { (Get-Item -LiteralPath $kwDumpFile).Length } else { 0 } @@ -3863,7 +3832,7 @@ foreach ($kwName in $kwCases.Keys) { # a temp folder left behind isn't worth stopping the harness for. try { Remove-Item -LiteralPath $kwWork -Recurse -Force } catch { Write-Host (" (left " + $kwWork + ": " + $_.Exception.Message + ")") } -# The wrap hands back what a callback returned as it was: a one-element +# Invoke-PkCallback returns what a callback returned as it was: a one-element # array returned whole (`,@(...)`) is still that array. Reset-Harness $kwFeed = @{ Given = $false } @@ -3933,13 +3902,10 @@ Write-Host "" # ============================================================================== if (Test-HarnessSection 'AJ' "a tree kill counts a program it killed, even if taskkill reports failure") { -# taskkill /T exits non-zero when any process in the tree couldn't be killed, -# even though the program itself was. A child that refuses PROCESS_TERMINATE -# (its DACL denies it) makes that happen every time. The Job Object still -# ends it when this process exits, and it's a short ping anyway. An elevated -# taskkill may ignore the DACL; then the child dies too, and the check below -# still holds but doesn't exercise the failure path (the message says so). -# The protecting is done by Protect-HarnessPingChild, at the top of the file. +# taskkill /T exits non-zero if any process in the tree can't be killed: here a +# child whose DACL denies PROCESS_TERMINATE (Protect-HarnessPingChild). An +# elevated taskkill may kill it anyway; the assertion's message then says the +# failure path wasn't exercised. Reset-Harness # Without a tree job, so the kill goes to taskkill. Section BF has the same @@ -3975,8 +3941,8 @@ Write-Host "" # ============================================================================== if (Test-HarnessSection 'AK' "3.0 parameter changes") { -# Complete-PkProcess -Dispose is a switch, and only -Job binds by position, so -# -Dispose $true is an error instead of a 1 ms -StreamTimeoutMs. +# -Dispose is a switch and only -Job binds by position, so `Complete-PkProcess +# $job -Dispose $true` is an error, not $true bound to -StreamTimeoutMs as 1 ms. Reset-Harness $apiStarted = Start-PkProcess -FilePath $cmdExe -Arguments '/c echo pk-api' $null = $apiStarted.Proc.WaitForExit(10000) @@ -4030,11 +3996,9 @@ Write-Host "" # ============================================================================== if (Test-HarnessSection 'AL' "a job is marked done before its shared slot is released") { -# Released first, a stop landing before the mark has the teardown release the -# slot again, leaving a shared budget one above its limit. The window is one -# statement wide, too narrow to hit from a test, so this reads the dispatcher's -# code: the statement right before each `if ($pkIsSharedBudget) { ...Release() }` -# marks the job done (SlotReleased set, or $pkStarting cleared on a failed start). +# A stop between releasing a slot and marking the job done would release it +# twice. Too narrow to hit, so this reads the code: right before each +# shared-budget Release(), the job is marked done. $slotCoreAst = & (Get-Module ParallelKit) { (Get-Command Invoke-PkProcessDispatchCore).ScriptBlock.Ast } $slotReleases = @($slotCoreAst.FindAll({ param($a) $a -is [System.Management.Automation.Language.InvokeMemberExpressionAst] -and $a.Member.Extent.Text -eq 'Release' -and $a.Expression.Extent.Text -eq '$pkMaxConcurrent' }, $true)) $slotMarkedFirst = 0 @@ -4054,12 +4018,11 @@ Write-Host "" # ============================================================================== if (Test-HarnessSection 'AM' "a program is in the Job Object from its first instruction") { -# Start-PkProcess has Windows create the program inside the kit's Job Object, -# so a child it starts at once (cmd /c tool.exe) is in the job too. The race -# this closes can't be forced, so these check the mechanism: .NET's start lock -# is found (without it the kit falls back to Process.Start), grandchildren are -# in the job, output isn't held open by a plain Process.Start elsewhere, and -# the fallback still works. +# Windows creates the program inside the kit's Job Object, so a child it starts +# at once is in it too. The gap this closes (a child starting before its parent +# is added) can't be forced, so these check the mechanism: the start lock is +# found, grandchildren are in the job, output isn't held by another start, and +# the fallback works. $lockKind = [PkChildProcessJob]::StartLockKind Test-Assert ($lockKind -match '^(Monitor|Lock):s_[Cc]reateProcessLock$') ("the kit holds .NET's process-start lock on this runtime (" + $lockKind + "); if not, a new .NET changed it and the kit is back to Process.Start") @@ -4133,11 +4096,9 @@ Write-Host "" # ============================================================================== if (Test-HarnessSection 'AN' "static checks on the kit's own code") { -# Rules that are easy to break in one place without any other test noticing: -# the dispatcher's copied blocks drifting apart, a user callback called -# without the continue/break guard, an empty catch with no reason. Each check -# reads the kit's source, then an edited copy that breaks the rule once, so a -# check that has stopped seeing anything fails too. +# Rules easy to break in one place unnoticed: copied blocks drifting apart, a +# callback called without the continue/break guard, an empty catch with no +# reason. Each check runs on the kit, then on a copy that breaks it once. $anSource = [System.IO.File]::ReadAllText($kitSource) function Get-HarnessCodeText { @@ -4167,12 +4128,10 @@ function Get-HarnessDispatchCore { } function Get-HarnessFinalizePassDrift { - # The dispatcher's three poll/finalize passes (main loop, graceful wait, - # final pass) are copies on purpose: a shared function cost too much per - # job on 5.1. They must match apart from two intended differences: the - # final pass has no time-limit check (what's left is force-stopped right - # after), and each invariant message names its own pass. Returns what's - # wrong; empty when they match. + # The dispatcher's three poll/finalize passes are copies on purpose (a + # shared function costs too much per job on 5.1). They must match, apart + # from the final pass's missing time-limit check and each invariant + # message's pass name. param([string]$Source) $problems = [System.Collections.Generic.List[string]]::new() $core = Get-HarnessDispatchCore -Source $Source @@ -4240,14 +4199,10 @@ function Get-HarnessForceStopDrift { } function Get-HarnessUnguardedCallbacks { - # Every call of a user callback (`& $cb`, `. $cb`, `& $h['cb']`) must be - # Invoke-PkCallback's guard or its inlined copy: `$flag = $false`, then - # `do { & $cb ...; $flag = $true } while ($false)`, then - # `if (-not $flag) { }`. `$cb.Invoke()` skips the guard - # altogether, so it's refused. The variables below hold the kit's own - # helpers, not callbacks; a new helper captured into a variable goes on - # this list. Invoke-PkRun's `& $ScriptBlock` is the run itself, not called - # from a loop. Returns @{ Calls; Problems }. + # Every call of a user callback must go through Invoke-PkCallback or its + # inlined do { ... } while ($false) guard; $cb.Invoke() is refused. The + # variables listed hold the kit's own helpers, not callbacks; a new helper + # goes on the list. Returns @{ Calls; Problems }. param([string]$Source) $internal = @('$pkNewBatchResult', '$pkGetStartFailureCause', '$pkGetJobTimeLimit', '$pkGetJobOutputLimit', '$pkGetJobSwitch', '$pkStopExitedJobTree', '$pkReportStartFailure', '$pkStartProcessCore', '$pkWriteCallbackLoopWarning', '$pkWriteMessage', '$pkCompleteProcess') $problems = [System.Collections.Generic.List[string]]::new() @@ -4372,18 +4327,10 @@ Write-Host "" # ============================================================================== if (Test-HarnessSection 'AP' "repeated runs don't leak handles, threads or runspaces") { -# Counted after a warm-up: the first runs grow the thread pool and JIT -# caches (on 5.1, handles climb about 100 over the first 20 runspace runs, -# then hold). After that the handle count still jumps by a few hundred and -# back between runs, on both runtimes and with a bare RunspacePool too, so -# one reading before and one after isn't enough: this compares the lowest -# reading over the last 20 warm-up runs with the lowest over the last 20 -# measured ones. A leak raises that floor; the jumps don't. A leak of one -# handle, thread or runspace per run shows well past these margins. For the -# runspace engine the handle count isn't checked: it can sit 250-450 higher -# for 10-50 runs at a time, the same with a bare RunspacePool, which hides -# any leak worth looking for. Its thread and runspace counts are exact, and -# catch a pool or runspace left open. +# After a warm-up (thread pool, JIT), the lowest handle, thread and runspace +# count over the last 20 warm-up runs against the last 20 measured: counts swing +# by hundreds between runs, but a leak raises the floor. The runspace engine's +# handles aren't checked: they swing too far. function Get-HarnessResourceCount { [System.GC]::Collect(); [System.GC]::WaitForPendingFinalizers(); [System.GC]::Collect() $me = [System.Diagnostics.Process]::GetCurrentProcess() @@ -4436,11 +4383,9 @@ Write-Host "" # ============================================================================== if (Test-HarnessSection 'AQ' "killing PowerShell outright leaves no programs running") { -# The README's "no orphans": PowerShell killed with Stop-Process -Force runs -# no cleanup at all, so only the kit's Job Object can end its programs. A -# child PowerShell starts 3 `cmd /c ping` jobs and is killed; none of the -# pings may survive. Both start paths: created inside the job, and -# Process.Start then added to it. +# The README's "no orphans": PowerShell killed with Stop-Process -Force runs no +# cleanup, so only the Job Object can end its programs. A child PowerShell +# starts 3 pings and is killed; none may survive, on either start path. $killScript = Join-Path $env:TEMP ("pk-hardkill-" + [guid]::NewGuid().ToString("N") + ".ps1") [System.IO.File]::WriteAllText($killScript, @' param([string]$Kit, [int]$Fallback) @@ -4500,10 +4445,8 @@ Write-Host "" # ============================================================================== if (Test-HarnessSection 'AR' "both start paths give the same results") { -# Creating a program inside the Job Object re-does what Process.Start does -# (command line, environment, working folder, output encoding, exit code), -# and Process.Start is the fallback when that can't be used. One table, run -# both ways, must come back the same. +# The in-job start re-does Process.Start's work, and Process.Start is its +# fallback: one table, run both ways, must come back the same. $parityExe = Join-Path $env:TEMP ("pk-parity-" + [guid]::NewGuid().ToString("N") + ".exe") $paritySrc = [System.IO.Path]::ChangeExtension($parityExe, '.cs') [System.IO.File]::WriteAllText($paritySrc, @' @@ -4563,11 +4506,9 @@ Write-Host "" # ============================================================================== if (Test-HarnessSection 'AS' "a callback that throws while programs run") { -# The exception comes out of the call, every program is killed, and a shared -# budget gets every slot back. Each case throws once a long ping is running; -# its count (-n 53) marks it for the check afterwards. Groups: 'long' first -# (the ping), then 'quick' ones (cmd /c exit 0), or empty ones for -# -GroupReleaseCheck, which is only asked about groups with no jobs. +# A callback that throws: the exception comes out, every program is killed, and +# a shared budget gets its slots back. Each case throws once a long ping (-n 53) +# runs. function Get-HarnessMarkedPings { return ,@(Get-CimInstance Win32_Process -Filter "Name='PING.EXE'" | Where-Object { [string]$_.CommandLine -like '* -n 53 *' }) } @@ -4608,16 +4549,14 @@ foreach ($throwName in 'PollCallback', 'GroupCompleteCallback', 'JobBuilder', 'G for ($t = 0; $t -lt 20 -and $throwLeft.Count -gt 0; $t++) { Start-Sleep -Milliseconds 100; $throwLeft = Get-HarnessMarkedPings } foreach ($l in $throwLeft) { Stop-Process -Id $l.ProcessId -Force -ErrorAction SilentlyContinue } $throwSlots = $throwBudget.CurrentCount - if ($throwSlots -lt 2) { $null = $throwBudget.Release(2 - $throwSlots) } # so one failure doesn't fail the cases after it + if ($throwSlots -lt 2) { $null = $throwBudget.Release(2 - $throwSlots) } # a throw can leave slots taken; put them back so the next case starts full Test-Assert ($st.Thrown -and $throwError -like ('*pk-test: ' + $throwName + '*') -and $throwLeft.Count -eq 0 -and $throwSlots -eq 2 -and $sw.Elapsed.TotalSeconds -lt 15) ("dispatcher: -" + $throwName + " throwing while a program runs: the exception comes out, nothing is left running, the shared budget gets its slots back (threw while running: " + $st.Thrown + ", error: " + $throwError + ", left running: " + $throwLeft.Count + ", slots: " + $throwSlots + " of 2, " + [math]::Round($sw.Elapsed.TotalSeconds, 1) + "s)") } $throwBudget.Dispose() # The runspace engine: a throwing -ResultHandler, -PollCallback or -# -NextJobProvider stops the run, stops the running workers (their pipelines -# are stopped, then the pool closes) and lets the exception out. Each worker -# notes when it starts and sleeps in 25 ms steps, so a stop lands at once; -# each throwing callback first waits for two workers to be running. +# -NextJobProvider stops the run and its workers and lets the exception out. +# Each throws once two workers run. $rsWorker = { param([int]$Id, [int]$Ms, $Seen) $Seen[$Id] = 'started' @@ -4670,9 +4609,10 @@ if (Test-HarnessSection 'AT' "a stray value next to a callback's answer") { # 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. +# -GroupReleaseCheck: a value it leaks ($rcLog.Add($g)) must not release the +# group; its answer still decides. 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() @@ -4711,10 +4651,9 @@ $null = Invoke-PkProcessDispatch -MaxConcurrent 1 ` -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))") -# -GroupProvider outputting several values in one call: they're one group, as -# without the comma, and the run warns once, with how many arrived. One value, -# $null, nothing, and a list returned with a comma (one value, even holding one -# item) aren't warned about. Each provider gives two groups, if it gives any. +# -GroupProvider outputting several values in one call: one group, with one +# warning. One value, $null, nothing and a list returned with a comma aren't +# warned about. $gvCases = [ordered]@{ 'one value' = @{ Provider = { if ($gv.Calls++ -ge 2) { return $null }; return ('g' + $gv.Calls) }; Groups = 'g1|g2'; Count = 0 } '$null' = @{ Provider = { return $null }; Groups = ''; Count = 0 } @@ -4757,7 +4696,8 @@ foreach ($njCase in 'two jobs', 'job then null') { $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. + # A second call would give job 3; it must never come, since the first call's + # last value, $null, ends the run. 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-PkRunspaceBatch -WorkerScript { param([int]$Id) $Id } -NextJobProvider $njProvider -MaxConcurrent 1 -ResultHandler { param($r) $njRan.Add($r) }.GetNewClosure() $njWarned = @($script:messages | Where-Object { $_.Message -like '*-NextJobProvider*' -and $_.Level -eq 'Warn' }).Count @@ -4770,11 +4710,8 @@ Write-Host "" # ============================================================================== if (Test-HarnessSection 'AU' "time limits that can't work are refused up front") { -# NaN and +Infinity for -TimeoutSeconds acted as no limit; a negative wait -# either waited until the program (or the leftover child holding its output) -# ended, defeating the parameter, or failed later with .NET's own message. -# Each must be refused before anything starts, naming the command and the -# parameter. 0 stays meaningful: no limit, or don't wait. +# NaN, +Infinity and negative waits must be refused before anything starts, +# naming the command and parameter. 0 is still taken: no limit, or don't wait. Reset-Harness $tlJob = @{ FilePath = $cmdExe; Arguments = '/d /c exit 0' } $tlDispatch = @{ @@ -4806,7 +4743,7 @@ foreach ($tlName in $tlCases.Keys) { if ($null -ne $tlStarted) { $null = Complete-PkProcess $tlStarted -Dispose } Test-Assert ($null -ne $tlError -and $tlError.StartsWith($tlCase.Expect + ' must be') -and $sw.Elapsed.TotalSeconds -lt 2) ($tlName + " is refused up front with a clear message (error: " + $tlError + ")") } -# 0 is still taken where it means something: don't wait. +# 0 is still taken for the waits below: don't wait at all. $s = Start-PkProcess -FilePath $cmdExe -Arguments '/d /c exit 0' $tlZero = $null try { @@ -4822,17 +4759,14 @@ Write-Host "" # ============================================================================== if (Test-HarnessSection 'AV' "the tree kill with many programs, or a taskkill that hangs") { -# One taskkill command line for every program hit Windows' 32,767-character -# limit at roughly 2,500-3,000 programs, so taskkill couldn't start and only -# the programs themselves were killed, not their children. And a taskkill -# still running after its wait was left running. These drive the tree kill's -# core through its test parameters: a shorter argument limit, a shorter wait, -# and a stand-in for taskkill that logs its arguments and can hang. +# The tree kill's core through its test parameters: a shorter argument limit +# (one taskkill line per few thousand programs), a shorter wait, and a stand-in +# taskkill that logs and can hang. $tkKit = Get-Module ParallelKit $tkIds = [int[]](1000000..1002999) $tkLimit = 32000 - (Join-Path $env:SystemRoot 'System32\taskkill.exe').Length $tkLists = $null -try { $tkLists = & $tkKit Split-PkTaskkillArgumentList -Ids $tkIds -MaxLength $tkLimit } catch { $tkLists = @() } # a list returned whole: assigned, not wrapped +try { $tkLists = & $tkKit Split-PkTaskkillArgumentList -Ids $tkIds -MaxLength $tkLimit } catch { $tkLists = @() } # assigned, not wrapped: the list stays whole, so .Count below counts command lines $tkSeen = @{} $tkTooLong = 0 foreach ($line in $tkLists) { @@ -4927,10 +4861,9 @@ Write-Host "" # ============================================================================== if (Test-HarnessSection 'AW' "when a program can't be created in the Job Object") { -# A start whose setup fails (pipes, the attribute list, the job attribute) -# falls back to Process.Start and the Job Object just after, with a warning -# shown once, since that costs the cleanup of a child the program starts -# straight away. The harness's own switch to that path stays quiet. +# A start whose setup inside the Job Object fails falls back to Process.Start, +# then adds the program to the job, with one warning; TestUseProcessStart, the +# harness's switch to that path, doesn't warn. Reset-Harness $fbReset = [PkChildProcessJob].GetMethod('TestResetFallbackWarning') if ($null -ne $fbReset) { $null = $fbReset.Invoke($null, @()) } @@ -4963,17 +4896,17 @@ foreach ($l in $rdLeft) { Stop-Process -Id $l.ProcessId -Force -ErrorAction Sile Test-Assert ($rdError -like '*could not start*' -and $rdLeft.Count -eq 0) ("a program whose output readers fail to build is ended and the start reported as failed (" + $rdLeft.Count + " left running, error: " + $rdError + ")") # Nor is one whose readers can't start once it runs (no thread to be had): on -# both start paths, whichever reader fails, the start fails and the program -# and what it started are ended. Each case's ping has its own -w, to find it. +# both start paths and through the batch, whichever reader fails, the start +# fails and the program and what it started are ended. Each case's ping has its +# own -w, to find it. $rsW = 4240 foreach ($rsPath in 'CreatedInJob', 'Process.Start', 'batch') { foreach ($rsAfter in 0, 1) { if ($rsPath -eq 'batch' -and $rsAfter -eq 0) { continue } $rsW++ - # On the Process.Start path a program runs before it's added to its Job - # Object, so a child it starts straight away can escape it (the gap the - # README's Limits gives for AddedToJob). There the tagged ping starts a - # second later, and the failing Run waits until it's up. + # On the Process.Start path a child started at once can escape the job + # (README Limits, AddedToJob), so there the ping, found by its -w + # number, starts a second later. $rsArgs = '/d /c ping -n 30 -w ' + $rsW + ' 127.0.0.1 >nul' $rsDelayMs = 0 if ($rsPath -eq 'Process.Start') { $rsArgs = '/d /c ping -n 2 127.0.0.1 >nul & ping -n 30 -w ' + $rsW + ' 127.0.0.1 >nul'; $rsDelayMs = 2500 } @@ -4996,11 +4929,9 @@ foreach ($rsPath in 'CreatedInJob', 'Process.Start', 'batch') { } } -# The same once the program has exited before the rollback: what it left -# running is still ended, through its tree job (a kill of the program itself -# passes over one that has exited). TestFailRunDelayMs holds the failing Run -# until cmd.exe, which only starts the ping, is gone. On the Process.Start path -# the ping starts a second later, as above. +# The same when the program has already exited by the time its failed start is +# undone: its tree job still ends what it left. TestFailRunDelayMs holds the +# failing Run until cmd.exe is gone. foreach ($rxPath in 'CreatedInJob', 'Process.Start') { $rsW++ $rxArgs = '/d /c start "" /b ping -n 30 -w ' + $rsW + ' 127.0.0.1 >nul' @@ -5040,10 +4971,9 @@ do { foreach ($l in $dxLeft) { Stop-Process -Id $l.ProcessId -Force -ErrorAction SilentlyContinue } Test-Assert ($dx.JobStarterFailedCount -eq 1 -and $dxLeft.Count -eq 0) ("dispatch: a -JobStarter that throws after its program exited still has what the program started ended (" + $dxLeft.Count + " left running, " + $dx.JobStarterFailedCount + " start failure(s))") -# When that can't be done, the start's failure says so, rather than that the -# program was stopped: Windows won't end the program's tree job -# (TestFailTerminate), or it has none (TestNoTreeJob). The tagged ping is -# left running then, and killed here by its tag. +# When what it left can't be ended (TestFailTerminate, TestNoTreeJob), the +# failure says so; the ping, found by its -w number, is left running and killed +# here. function Get-HarnessRollbackLeft([int]$Tag) { # The tagged pings still running after a moment. Start-Sleep -Milliseconds 1000 @@ -5094,13 +5024,10 @@ Write-Host "" # ============================================================================== if (Test-HarnessSection 'AX' "output held open by a leftover child is cut short, not lost") { -# The test program writes "out" and "err", then leaves a copy of itself -# holding one of the two open for 3 s, writing nothing. The copy is started -# with a handle list, so it inherits only that pipe: cmd's `start /b`, and -# even .NET's Process.Start, hand a child both. Modes: stdout / stderr (the -# stream left held), partial (stdout held, ending in half a UTF-8 -# character), split (no copy; a UTF-8 character written in two parts, -# 300 ms apart). +# The test program writes out and err, then leaves a copy of itself holding one +# of them open for 3 s, started with a handle list so it inherits only that +# pipe. Modes: stdout, stderr, partial (ends in half a UTF-8 character), split +# (a character in two writes). $holdExe = Join-Path $env:TEMP ("pk-hold-" + [guid]::NewGuid().ToString("N") + ".exe") $holdSrc = [System.IO.Path]::ChangeExtension($holdExe, '.cs') [System.IO.File]::WriteAllText($holdSrc, @' @@ -5232,13 +5159,9 @@ Write-Host "" # ============================================================================== if (Test-HarnessSection 'AZ' "programs left holding their output don't hold up a new program's") { -# Each holder is a ping, started by a cmd that exits at once, holding stdout -# and stderr: two blocked reads. Enough of them to take more threads than the -# pool's minimum. With the reads on pool threads, the new program's reads -# queued behind the holders' while the pool grew a thread at a time, and it -# came back empty at its stream timeout. In a fresh PowerShell: earlier -# sections raise this one's pool minimum (the 20,000-job dispatch to over -# 2000), and once raised, lowering it again doesn't bring back the slow growth. +# Pings holding stdout and stderr, enough to take more threads than the pool's +# minimum: a new program's reads mustn't wait behind theirs. In a fresh +# PowerShell, since earlier sections raise the pool minimum. Reset-Harness $azScript = Join-Path $env:TEMP ("pk-heldreads-" + [guid]::NewGuid().ToString("N") + ".ps1") [System.IO.File]::WriteAllText($azScript, @' @@ -5292,11 +5215,9 @@ Write-Host "" # ============================================================================== if (Test-HarnessSection 'BA' "after a stream timeout, the read drains without keeping the text") { -# The read of a held stream goes on to its end, but nobody can get what it -# reads after the result was handed over, so it isn't kept. The reader is -# closed at the end of every stream, rather than at the next garbage -# collection. Test-only reads that a build without them lacks count as a -# failure, not an error. +# A held stream's read goes on to its end without keeping what arrives after the +# result was handed over, and its reader is closed at the end. On a build +# without the test-only reads, the checks fail rather than throw. Reset-Harness function Get-HarnessReadState($Task, [string]$Name) { try { return $Task.$Name } catch { return 'missing' } # an older build has no such test-only read @@ -5335,9 +5256,9 @@ foreach ($baPath in 'created in the job', 'Process.Start fallback') { Test-Assert ($r.Stdout -match 'out' -and $r.Stderr -match 'err' -and $baOut -eq $true -and $baErr -eq $true) ($baPath + ": both readers are closed once a program's output ends (stdout " + $baOut + ", stderr " + $baErr + ")") } -# One read fails while the other stream is still held: the failure is +# One read fails while the other stream is still held: the failure must be # reported, not just the timeout. Task.WaitAll with a timeout throws only once -# every task has finished, so it didn't throw here. +# every task has finished, so it can't report it. $s = Start-PkProcess -FilePath $cmdExe -Arguments '/d /c exit 0' $null = $s['Proc'].WaitForExit(10000) $null = [System.Threading.Tasks.Task]::WaitAll(@($s['StdoutTask'], $s['StderrTask']), 10000) @@ -5360,9 +5281,8 @@ Write-Host "" # ============================================================================== if (Test-HarnessSection 'BB' "a job waiting for its output doesn't hold up the others") { # Each held command's cmd exits at once and leaves a ping holding its output -# for a few seconds, so its output ends well inside the stream timeout. The -# wait for it used to run inside -JobFinalize, on the dispatch loop's own -# thread: no other job was polled, started, timed or stopped meanwhile. +# for a few seconds, well inside the stream timeout. Other jobs must be +# polled, started, timed and stopped while it waits. Reset-Harness try { # Two slots: one job waits about 6 s for its output while four 1 s @@ -5428,8 +5348,7 @@ Write-Host "" if (Test-HarnessSection 'BC' "up-front checks: mandatory worker parameters, a code page as a string") { Reset-Harness # A job that leaves out a mandatory parameter is refused before anything -# starts, like a key the worker doesn't declare. It used to run, fail in -# binding, and land in Errors. +# starts, like a key the worker doesn't declare. $bcRan = [System.Collections.Generic.List[object]]::new() $bcError = $null try { @@ -5448,9 +5367,8 @@ $bcJob = [hashtable]::new(); $bcJob['name'] = 'a' $bcOut = $null; $bcError = $null try { $bcOut = Invoke-PkRunspaceBatch -MaxConcurrent 1 -JobParams @(,$bcJob) -WorkerScript { param([Parameter(Mandatory)][string]$Name) $Name } } catch { $bcError = [string]$_ } Test-Assert ($null -eq $bcError -and $null -ne $bcOut -and $bcOut.Errors.Count -eq 0) ("a mandatory parameter supplied in another case, in a case-sensitive hashtable, isn't counted as missing (" + $bcError + ")") -# A case-sensitive job's own 'canceltoken' is its CancelToken, as binding -# would have it: the kit doesn't put its own in its place. The caller's token -# here is cancelled, so the worker can tell which one it got. +# A case-sensitive job's 'canceltoken' is its CancelToken; the caller's here is +# canceled, so the worker can tell which one it got. $bcMine = [System.Threading.CancellationTokenSource]::new(); $bcMine.Cancel() $bcTokenWorker = { param($Id, $CancelToken) $CancelToken.IsCancellationRequested } $bcJob = [hashtable]::new(); $bcJob['canceltoken'] = $bcMine.Token; $bcJob['Id'] = 1 @@ -5491,11 +5409,9 @@ Test-Assert ($bcOut.Errors.Count -eq 0) ("a mandatory CancelToken and Mandatory $bcOut = Invoke-PkRunspaceBatch -MaxConcurrent 2 -JobParams @(@{ A = 1 }) -WorkerScript { param([Parameter(Mandatory, ParameterSetName = 'A')]$A, [Parameter(Mandatory, ParameterSetName = 'B')]$B) $A } Test-Assert ($bcOut.Errors.Count -eq 0) ("a worker with parameter sets isn't refused for the other set's mandatory parameter (" + $bcOut.Errors.Count + " errors)") -# A function's own scriptblock (${function:Name}) works as -WorkerScript, in -# both forms, function f { param(...) } and function f(...): its parameters -# are read, CancelToken is filled in, a missing mandatory one is refused up -# front, and the function's own top level may use $script:, as a { } block's -# may. +# ${function:Name} as -WorkerScript, in both forms: its parameters are read, +# CancelToken is filled in, a missing mandatory one is refused, and its top +# level may use $script:. function Get-HarnessFnWorker { param([int]$Id, $CancelToken) return ([string]$Id + ':' + ($CancelToken -is [System.Threading.CancellationToken])) } function Get-HarnessFnWorkerInline([int]$Id, [Parameter(Mandatory)][string]$Name) { return ([string]$Id + $Name) } $bcFnResults = [System.Collections.Generic.List[object]]::new() @@ -5536,10 +5452,9 @@ Write-Host "" # ============================================================================== if (Test-HarnessSection 'BD' "-StreamTimeoutMs on the batch and the dispatcher") { -# The wait for held output was fixed at 15 s in both, and since the wait -# moved into the dispatcher's default poll, a shorter -StreamTimeoutMs passed -# to Complete-PkProcess in -JobFinalize no longer shortened it. Each held -# command leaves a ping (-w 4321, BB's helpers) holding its output for 8 s. +# -StreamTimeoutMs sets the wait for held output in both, also when passed to +# Complete-PkProcess in -JobFinalize. Each held command (New-HarnessHeldCommand) +# leaves a ping (-w 4321) holding its output for 8 s. Reset-Harness function Invoke-HarnessHeldDispatch { param([int]$StreamTimeoutMs, $FinalizeTimeoutMs) @@ -5586,8 +5501,8 @@ try { Test-Assert ($null -ne $bdRun -and $bdRun.Result.StreamTimedOut -and $bdRun.Seconds -ge 2.5 -and $bdRun.Seconds -lt 6) ("dispatcher -StreamTimeoutMs 1000, Complete-PkProcess -StreamTimeoutMs 3000: waits the rest, about 3 s in all (" + $(if ($bdRun) { [string]$bdRun.Seconds + " s" } else { $bdError }) + ")") Stop-HarnessTaggedPings - # A job -JobFinalize re-queues waits the dispatcher's limit again, from - # its own new exit. + # A job that -JobFinalize puts back in the queue waits up to + # -StreamTimeoutMs again, counted from its new run's exit. $bdFeed = @{ Given = $false } $bdGot = [System.Collections.Generic.List[object]]::new() $bdJobs = @(New-HarnessHeldCommand -Seconds 8 -Key 'again') @@ -5604,8 +5519,9 @@ try { Test-Assert ($bdGot.Count -eq 2 -and $bdBoth -eq 2 -and $sw.Elapsed.TotalSeconds -lt 5) ("dispatcher -StreamTimeoutMs 1000: a re-queued job is given up on after about a second again (" + $bdBoth + " of " + $bdGot.Count + " runs timed out with their output, " + [math]::Round($sw.Elapsed.TotalSeconds, 1) + " s" + $(if ($bdError) { ", error: " + $bdError }) + ")") Stop-HarnessTaggedPings - # Inside a worker the kit isn't a module: the default poll still carries - # the limit it was given. + # Inside a worker the kit is plain copied functions, not a module: the + # dispatcher's default poll must still use the -StreamTimeoutMs it was + # given. $bdRes = [System.Collections.Generic.List[object]]::new() $bdOut = Invoke-PkRunspaceBatch -MaxConcurrent 1 -JobParams @(@{ Cmd = $cmdExe }) -ResultHandler { param($r) $bdRes.Add($r) }.GetNewClosure() -WorkerScript { param($Cmd) @@ -5665,10 +5581,8 @@ Test-Assert ($beR.Stdout -ceq "01234HIJ`r`n" -and $beR.StdoutDroppedChars -eq 12 $beR = Get-HarnessCapRun -Arguments '/d /c 1>&2 echo 0123456789ABCDEFGHIJ' -Cap 10 Test-Assert ($beR.Stderr -ceq "01234HIJ`r`n" -and $beR.StderrDroppedChars -eq 12 -and $beR.StdoutDroppedChars -eq 0) ("stderr is capped the same way, on its own ('" + ([string]$beR.Stderr -replace "`r", '\r' -replace "`n", '\n') + "', dropped " + $beR.StderrDroppedChars + ")") -# A cut never splits a surrogate pair. cmd /u writes UTF-16: four emoji are -# 8 characters, plus CRLF. A cap of 7 puts the head's end inside a pair (its -# first half, and the slot, go to the tail) and the tail's start inside -# another. +# A cut never splits a surrogate pair. Four emoji plus CRLF under a cap of 7: +# the head's end and the tail's start both land inside pairs. $beEmoji = [char]::ConvertFromUtf32(0x1F600) $beR = Get-HarnessCapRun -Arguments ('/d /u /c echo ' + $beEmoji * 4) -Cap 7 -Encoding 'unicode' $beText = [string]$beR.Stdout @@ -5678,8 +5592,9 @@ for ($i = 0; $i -lt $beText.Length; $i++) { elseif ([char]::IsLowSurrogate($beText[$i])) { $beLone++ } } Test-Assert ($beText -ceq ($beEmoji * 2 + "`r`n") -and $beLone -eq 0 -and $beR.StdoutDroppedChars -eq 4) ("a cut inside a surrogate pair drops the whole pair, never half (" + $beText.Length + " characters kept, " + $beLone + " half pairs, dropped " + $beR.StdoutDroppedChars + ")") -# Output exactly as long as the cap is kept whole, even with a pair where the -# head would end: the tail takes the slot the head turns away. +# Output exactly as long as the cap is kept whole, even when the first half +# would end on half a surrogate pair: the second half takes that half and its +# place. $beR = Get-HarnessCapRun -Arguments ('/d /u /c echo ab' + $beEmoji + 'c') -Cap 7 -Encoding 'unicode' Test-Assert ($beR.Stdout -ceq ('ab' + $beEmoji + "c`r`n") -and $beR.StdoutDroppedChars -eq 0) ("output exactly at the cap, with a surrogate pair at the head's end, comes back whole (" + ((Format-HarnessCapRun $beR) -replace [regex]::Escape($beEmoji), '') + ")") $beText = foreach ($beCase in @(@{ Text = $beEmoji; Cap = 2 }, @{ Text = 'a' + $beEmoji + 'b'; Cap = 4 }, @{ Text = 'ab' + $beEmoji + 'cd'; Cap = 6 })) { @@ -5691,7 +5606,7 @@ Test-Assert ($null -eq $beText) ("the same for an emoji under a cap of 2, anul' $null = Wait-PkProcess -Process $bfJob['Proc'] -TimeoutMs 10000 $bfUp = Wait-HarnessTagPings @('4327') @@ -5909,7 +5823,8 @@ $bgWhy = $null $bgAssigned = [PkChildProcessJob]::Assign($bgGone['Proc'], [ref]$bgWhy) Test-Assert (-not $bgAssigned -and -not [string]::IsNullOrEmpty($bgWhy) -and $bgWhy -notlike 'Win32 error*') ("a process that can't be read isn't added, and the reason says what was thrown (" + $bgWhy + ")") -# .NET's start lock not found, as a future .NET that moved it would bring. +# As if .NET's start lock weren't found, which a later .NET that moved it would +# cause. Reset-Harness [PkChildProcessJob]::TestResetFallbackWarning() $bgMode = $null; $bgExits = @() @@ -5983,8 +5898,9 @@ $bhSource = [System.IO.File]::ReadAllText($PSCommandPath) $bhLeaks = @(Get-HarnessSectionLeaks $bhSource) Test-Assert ($bhLeaks.Count -eq 0) ("no section uses another section's variables, functions or types (" + ($bhLeaks -join '; ') + ")") Test-Assert (@($allSections | Select-Object -Unique).Count -eq $allSections.Count -and $allSections[0] -eq 'A' -and $allSections -contains 'BH') ("every section has a name of its own (" + $allSections.Count + " sections)") -# The check still sees each kind: an edited copy with one of each. (SECTION, -# so the copy's headings aren't read as this file's own.) +# The check still sees each kind: an edited copy with one of each. Its sections +# use the placeholder SECTION, so this file's own scan doesn't take them for +# real sections. $bhFound = @(Get-HarnessSectionLeaks ($bhSource + @' if (SECTION 'ZY' "defines") { @@ -6012,10 +5928,9 @@ Write-Host "" # ============================================================================== if (Test-HarnessSection 'BI' "programs get NUL as stdin, unless -InheritStdin") { -# In a fresh PowerShell with a file as its stdin, on each start path. cmd's -# set /p on a file takes one line and leaves the rest, so each program here -# that inherits stdin reads the next line, and one that doesn't reads nothing. -# Each is time-limited: a program left reading would otherwise hang the test. +# A fresh PowerShell with a file as stdin, on each start path: a program that +# inherits it reads the next line, one that doesn't reads nothing. Each is +# time-limited. Reset-Harness $biScript = Join-Path $env:TEMP ("pk-bi-" + [guid]::NewGuid().ToString("N") + ".ps1") $biInput = [System.IO.Path]::ChangeExtension($biScript, '.txt') @@ -6096,10 +6011,9 @@ try { foreach ($biFile in $biScript, $biInput, $biBat) { [System.IO.File]::Delete($biFile) } } -# A console whose input code page is UTF-8: on .NET Framework, Process.Start -# writes a byte-order mark into a redirected stdin, which a program would read -# as input. Only the fallback path on 5.1, where Process.Start takes no -# encoding for it. Read back through findstr, which prints any line it gets. +# A UTF-8 console input code page: on .NET Framework, Process.Start writes a +# byte-order mark into a redirected stdin (5.1's fallback path only). Read back +# through findstr. Reset-Harness $biScript = Join-Path $env:TEMP ("pk-bi-" + [guid]::NewGuid().ToString("N") + ".ps1") [System.IO.File]::WriteAllText($biScript, @' @@ -6116,7 +6030,7 @@ foreach ($fallback in $false, $true) { try { $biRun = Invoke-PkProcessWithTimeout -FilePath $selfExe -Arguments ('-NoProfile -ExecutionPolicy Bypass -File "' + $biScript + '" -Kit "' + $kitPath + '"') -TimeoutMs 60000 } finally { [System.IO.File]::Delete($biScript) } $biReads = @([regex]::Matches([string]$biRun.Stdout, 'READ=\d+ EXIT=\d+') | ForEach-Object { $_.Value }) -join '; ' $biWanted = @('READ=0 EXIT=1; READ=0 EXIT=1') -if ($PSVersionTable.PSVersion.Major -lt 6) { $biWanted += 'READ=0 EXIT=1; READ=5 EXIT=0' } # "1:" and the mark's three bytes +if ($PSVersionTable.PSVersion.Major -lt 6) { $biWanted += 'READ=0 EXIT=1; READ=5 EXIT=0' } # findstr's "1:" prefix plus the byte-order mark's three bytes Test-Assert ($biWanted -contains $biReads) ("stdin is empty with a UTF-8 console too, on both start paths, apart from 5.1's byte-order mark on the fallback (" + $biReads + ")") Reset-Harness Write-Host "" @@ -6124,16 +6038,15 @@ Write-Host "" # ============================================================================== if (Test-HarnessSection 'BJ' "-KillTreeOnExit: what a program left running goes when it exits") { -# Each program leaves a ping behind (-w 4328, so this section can find and -# kill its own) and exits with code 5 about a second in: by then it's in its -# tree job on both start paths. The ping holds the program's output, except -# where the test says it holds none. +# Each program leaves a ping (-w 4328) and exits with code 5 about a second in, +# by when it's in its tree job. The ping holds its output unless the test says +# otherwise. Reset-Harness function Get-HarnessLeftPingCount { return @(Get-CimInstance Win32_Process -Filter "Name='PING.EXE' AND CommandLine LIKE '%-w 4328 %'").Count } function Stop-HarnessLeftPings { foreach ($p in @(Get-CimInstance Win32_Process -Filter "Name='PING.EXE' AND CommandLine LIKE '%-w 4328 %'")) { Stop-Process -Id $p.ProcessId -Force -ErrorAction SilentlyContinue } } $bjHeld = '/d /c ping -n 2 127.0.0.1 >nul& echo before& start /b ping -n 30 -w 4328 127.0.0.1 >nul& exit 5' -# A start /b child holds the pipes whatever it's redirected to; one started -# through the shell doesn't get them. +# A child cmd starts with start /b holds the pipes whatever it's redirected to; +# one started with Start-Process from PowerShell doesn't get them. $bjLoose = '-NoProfile -Command "Start-Process ping.exe -WindowStyle Hidden -ArgumentList ''-n 30 -w 4328 127.0.0.1''; Start-Sleep -Milliseconds 300; ''before''; exit 5"' function Test-HarnessKillTree { # Runs $Run, which returns a result with ExitCode, Stdout and StreamTimedOut @@ -6179,7 +6092,8 @@ try { } [PkChildProcessJob]::TestUseProcessStart = $false - # Not only when the output is held. + # Also when the leftover holds no output: $bjLoose's ping is started with + # Start-Process, which inherits no pipes. Test-HarnessKillTree 'a leftover that holds no output, one program' { Invoke-PkProcessWithTimeout -FilePath $selfExe -Arguments $bjLoose -KillTreeOnExit } Test-HarnessKillTree 'a leftover that holds no output, batch' { Invoke-HarnessTreeBatch @{ KillTreeOnExit = $true } @{ FilePath = $selfExe } $bjLoose } @@ -6202,15 +6116,16 @@ try { -JobFinalize { param($j, $q) } Test-Assert ($bjDispatch.JobStarterFailedCount -eq 1 -and $bjStarted.Count -eq 0 -and @($script:messages | Where-Object { $_.Message -like "*a job couldn't start: KillTreeOnExit must be*" }).Count -eq 1) ("a bad key on a dispatcher job is refused before its starter runs (failed " + $bjDispatch.JobStarterFailedCount + ", starter calls " + $bjStarted.Count + ")") - # A custom starter's program, and a custom poll: the kill is - # Complete-PkProcess's then. + # With a custom -JobStarter or -JobPollCompleted, -KillTreeOnExit still ends + # the tree, through Complete-PkProcess in -JobFinalize. $bjStarter = { param($job) $s = Start-PkProcess -FilePath $job['FilePath'] -Arguments $job['Arguments']; foreach ($k in 'Proc', 'StdoutTask', 'StderrTask', 'Stopwatch') { $job[$k] = $s[$k] }; return $job } Test-HarnessKillTree 'a custom starter' { Invoke-HarnessTreeDispatch @{ KillTreeOnExit = $true; JobStarter = $bjStarter } @{} $bjHeld } Test-HarnessKillTree 'a custom poll' { Invoke-HarnessTreeDispatch @{ KillTreeOnExit = $true; JobPollCompleted = { param($j) return $j['Proc'].HasExited } } @{} $bjHeld } # A program without a tree job can't have what it left killed: it's left - # alone, with one warning naming -KillTreeOnExit, once per process. With - # the kit's tree job turned off, or Windows refusing it, in each engine. + # alone, with one warning naming -KillTreeOnExit, once per session. With the + # kit's tree job turned off or refused by Windows, through the batch, the + # dispatcher and Invoke-PkProcessWithTimeout. $bjNoTree = @( @{ Name = 'no tree job, batch'; Hook = 'TestNoTreeJob'; Run = { Invoke-HarnessTreeBatch @{ KillTreeOnExit = $true; StreamTimeoutMs = 500 } @{} $bjHeld } } @{ Name = 'no tree job, dispatcher'; Hook = 'TestNoTreeJob'; Run = { Invoke-HarnessTreeDispatch @{ KillTreeOnExit = $true; StreamTimeoutMs = 500 } @{} $bjHeld } } @@ -6230,7 +6145,8 @@ try { # A tree job Windows won't end (TerminateJobObject fails) leaves what the # program started running too: one warning naming the process, once per - # process, in each engine. + # session, through the batch, the dispatcher and + # Invoke-PkProcessWithTimeout. $bjFailTerminate = @( @{ Name = 'tree job not ended, batch'; Run = { Invoke-HarnessTreeBatch @{ KillTreeOnExit = $true; StreamTimeoutMs = 500 } @{} $bjHeld } } @{ Name = 'tree job not ended, dispatcher'; Run = { Invoke-HarnessTreeDispatch @{ KillTreeOnExit = $true; StreamTimeoutMs = 500 } @{} $bjHeld } } @@ -6266,6 +6182,36 @@ try { Test-Assert ($bjOk -and $bjLeft.Count -eq 0 -and $bjTreeWarn.Count -eq 0) ($bjCase.Name + " with -KillTreeOnExit kills the program and doesn't warn about its tree (as expected: " + $bjOk + ", pings left " + $bjLeft.Count + ", " + $bjTreeWarn.Count + " warning(s): " + (@($bjTreeWarn | ForEach-Object { $_.Message }) -join ' | ') + ")") } + # A kill whose tree job Windows won't end (TestFailTerminate) misses a child +# whose parent exited, and warns once; otherwise nothing is left. + $bjOrphanCmd = Join-Path $env:TEMP ('pk-harness-bj-' + $PID + '.cmd') + [System.IO.File]::WriteAllText($bjOrphanCmd, "@start `"`" /b ping -n 30 -w 4330 127.0.0.1 >nul`r`n") + $bjOrphan = '/d /c start "" /b cmd /d /c "' + $bjOrphanCmd + '" & ping -n 30 127.0.0.1 >nul' + $bjOrphanCases = @( + @{ Name = 'a time-limit kill'; Run = { $r = Invoke-HarnessTreeDispatch @{ TimeoutSeconds = 2; StreamTimeoutMs = 500 } @{} $bjOrphan } } + @{ Name = "an abort's force-stop"; Run = { $bjTicks = @{ N = 0 }; $r = Invoke-HarnessTreeDispatch @{ AbortTimeoutSeconds = 0; StreamTimeoutMs = 500; PollCallback = { param($x) $bjTicks.N++; if ($bjTicks.N -eq 20) { Request-PkAbort } }.GetNewClosure() } @{} $bjOrphan; Reset-PkAbortState } } + @{ Name = "Invoke-PkProcessWithTimeout's limit"; Run = { try { $null = Invoke-PkProcessWithTimeout -FilePath $cmdExe -Arguments $bjOrphan -TimeoutMs 2000 -StreamTimeoutMs 500 } catch { } } } # the limit throws by design; the pings and warnings are checked + ) + try { + foreach ($bjCase in $bjOrphanCases) { + foreach ($bjRefuse in $false, $true) { + Reset-Harness + [PkChildProcessJob]::TestResetJobWarnings() + [PkChildProcessJob]::TestFailTerminate = $bjRefuse + try { $null = & $bjCase.Run } finally { [PkChildProcessJob]::TestFailTerminate = $false; Reset-PkAbortState } + Start-Sleep -Milliseconds 500 + $bjLeft = @(Get-CimInstance Win32_Process -Filter "Name='PING.EXE' AND CommandLine LIKE '%-w 4330 %'") + foreach ($p in $bjLeft) { Stop-Process -Id $p.ProcessId -Force -ErrorAction SilentlyContinue } + $bjWarn = @($script:messages | Where-Object { $_.Level -eq 'Warn' -and $_.Message -like "*Killing process * may have left what it started running*" }) + if ($bjRefuse) { + Test-Assert ($bjLeft.Count -eq 1 -and $bjWarn.Count -eq 1) ($bjCase.Name + " whose tree job Windows won't end says what may still be running, once (pings left " + $bjLeft.Count + ", " + $bjWarn.Count + " warning(s))") + } else { + Test-Assert ($bjLeft.Count -eq 0 -and $bjWarn.Count -eq 0) ($bjCase.Name + " ends a child whose parent has exited, through the tree job (pings left " + $bjLeft.Count + ", " + $bjWarn.Count + " warning(s))") + } + } + } + } finally { Remove-Item -LiteralPath $bjOrphanCmd -ErrorAction SilentlyContinue } + # A force-stop: the program has exited, but the caller's poll never says # done, so neither the poll nor Complete-PkProcess kills what it left. Reset-Harness @@ -6304,10 +6250,9 @@ Write-Host "" # ============================================================================== if (Test-HarnessSection 'BK' "the worker-safety check looks a module up once") { -# Whether a worker can load the module a command comes from is asked of -# Get-Module -ListAvailable, which searches all of PSModulePath on 5.1. Counted -# with a stand-in Get-Module inside the kit, and two modules of the harness's -# own: one on PSModulePath, one imported by path from elsewhere. +# Get-Module -ListAvailable searches all of PSModulePath on 5.1, so the check +# asks once per module. Lookups are counted with a stand-in Get-Module inside +# the kit, for a module on PSModulePath and one imported by path. Reset-Harness $bkRoot = Join-Path $env:TEMP ("pk-bk-" + [guid]::NewGuid().ToString("N")) $bkTag = [guid]::NewGuid().ToString("N").Substring(0, 8) @@ -6411,7 +6356,8 @@ $blFound = Get-HarnessUndeclared ([scriptblock]::Create("param(`$Id)`n. `$env:PK Test-Assert ($blFound -eq '') ("'# pk:ignore' on the line accepts it (flagged: '" + $blFound + "')") $blFound = Test-PkWorkerSafety -WorkerScript ([scriptblock]::Create("param(`$Id)`n`$fromHelper # pk:ignore`n`$fromHelper")) Test-Assert ($blFound.Count -eq 1 -and $blFound[0].Line -eq 3 -and $blFound[0].Where -eq 'worker script') ("but not the same name on another line (" + $blFound.Count + " finding(s))") -# A shared function reading its caller's variables is ordinary PowerShell. +# Functions named in -SharedFunctionNames aren't checked for this: one reading +# its caller's variables is ordinary PowerShell. function Get-HarnessReadsCaller { return $callersVariable } $blFound = Get-HarnessUndeclared { param($Id) Get-HarnessReadsCaller } @('Get-HarnessReadsCaller') Test-Assert ($blFound -eq '') ("shared functions aren't checked for it (flagged: '" + $blFound + "')") @@ -6419,7 +6365,9 @@ Test-Assert ($blFound -eq '') ("shared functions aren't checked for it (flagged: $blFound = Get-HarnessUndeclared { param($Id) $sb = { $script:blNested }; & $sb } Test-Assert ($blFound -eq 'ScriptVariable') ("`$script: in a nested block is one finding, not two ('" + $blFound + "')") -# A closure gets the reason, and the run is refused. +# A worker reading a caller's variable is told to pass it as a job value; one +# made with .GetNewClosure() is also told that the closure doesn't carry the +# variable into a worker. $blPrefix = 'P' $blPlain = { param($Id) "[$blPrefix$Id]" } $blFound = Test-PkWorkerSafety -WorkerScript $blPlain @@ -6549,8 +6497,9 @@ $bmVersionsWrong = @(foreach ($r in (Invoke-PkProcessBatch -MaxConcurrent 2 -Com }) Test-Assert ($bmVersionCommands.Count -eq 2 -and $bmVersionsWrong.Count -eq 0) ("the manifest's version has three parts: 9.8 is 9.8.0, 9.8.7 stays (not: " + ($bmVersionsWrong -join '; ') + ")") -# Loaded in fresh processes, by name and by path: what a caller does with it. -# -OnComplete and -ResultHandler are closures that call the kit's functions. +# The module loaded in fresh processes, by name and by path, and used as a +# caller would: -OnComplete and -ResultHandler are closures that call the kit's +# functions. $env:PSModulePath = $bmMods + ';' + $oldModulePath $bmUse = @' try { @@ -6597,8 +6546,9 @@ $m = Get-Module ParallelKit $bmShown = ([string](Invoke-PkProcessWithTimeout -FilePath $selfExe -Arguments @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', $bmShow) -TimeoutMs 60000).Stdout).Trim() -replace '\s+', ' ' Test-Assert ($bmShown -like ('functions=' + $publicFunctions.Count + ' others=0 private=False help=Runs a block with graceful*')) ("and only its public functions come out (" + $bmShown + ")") -# A copy with other compiled types is refused, and the one loaded stays. Only -# try/catch or $ErrorActionPreference stops the script there. +# A copy with other compiled types is refused, and the one loaded stays. The +# refusal doesn't stop the script by itself: only try/catch or +# $ErrorActionPreference does. $bmOther = Join-Path $bmDir 'other' $bmOtherText = [regex]::Replace([regex]::Replace($bmText, 'TypesVersion = \d+;', 'TypesVersion = 999;'), 'catch \{ 0 \} \}\) -ne \d+\)', 'catch { 0 } }) -ne 999)') $bmOtherBuild = Invoke-PkProcessBatch -Commands @(Get-BmBuildCommand (New-BmFile 'other.ps1' $bmOtherText) $bmOther) @@ -6615,10 +6565,8 @@ Write-Host "" # ============================================================================== if (Test-HarnessSection 'BN' "the C# in Source/ and in ParallelKit.ps1 match") { -# The C# is edited in Source/*.cs, and Build/Update-ParallelKitCSharp.ps1 -# copies it into ParallelKit.ps1's Add-Type blocks. Its checks are tested on a -# copy of the kit and its sources in %TEMP%. Compiling (-Compile) needs the -# .NET SDK, so it's checked by CI's C# job, not here. +# Build/Update-ParallelKitCSharp.ps1's checks, on a copy of the kit and its +# sources in %TEMP%. -Compile needs the .NET SDK, so CI's C# job checks it. $bnScript = Join-Path $PSScriptRoot 'Build\Update-ParallelKitCSharp.ps1' $null = & $bnScript -Check 6>$null Test-Assert ($LASTEXITCODE -eq 0) "ParallelKit.ps1's C# matches Source/*.cs (Build/Update-ParallelKitCSharp.ps1 -Check)" @@ -6664,10 +6612,9 @@ Write-Host "" # ============================================================================== if (Test-HarnessSection 'BO' "a program or working folder past 260 characters starts by its short name") { -# Windows refuses a program path of 260 characters or more, and a working -# folder of 259 or more, even with long paths enabled; the kit tries once more -# with their 8.3 short names. Those exist only where the volume makes them, so -# the cases that need them skip without. +# Windows won't start a program by a 260+ character path or in a 259+ folder; +# the kit retries with 8.3 short names, which exist only where the volume makes +# them, so those cases skip without. Reset-Harness $boPrefix = [string][char]92 + [char]92 + '?' + [char]92 $boRoot = Join-Path $env:TEMP ("pk-harness-bo-" + $PID) diff --git a/ParallelKit.ps1 b/ParallelKit.ps1 index 853ed78..1043eee 100644 --- a/ParallelKit.ps1 +++ b/ParallelKit.ps1 @@ -14,9 +14,9 @@ # hanging or crashing. # # Works under Set-StrictMode: read job hashtables as $job['Name'], never -# $job.Name, which throws there for a key that isn't set yet. State lives in -# the static [PkState] class, never in $script: variables: a function called -# from a .GetNewClosure() block can see an empty $script: scope. +# $job.Name, which throws there for a key that isn't set. State lives in the +# static [PkState] class, not $script: variables: a kit function called from a +# .GetNewClosure() block can find its $script: scope empty. # Add-Type needs FullLanguage: say so, rather than fail on Add-Type's error. if ($ExecutionContext.SessionState.LanguageMode -ne 'FullLanguage') { @@ -25,12 +25,10 @@ if ($ExecutionContext.SessionState.LanguageMode -ne 'FullLanguage') { "Ask whoever manages the machine to allow this script, or run it where that policy doesn't apply.") } -# The kit runs as a module, so a callback you pass in sees your variables, -# never the kit's, and the private helpers stay out of your session. The .ps1 -# makes itself one in memory: it removes a copy loaded earlier, and its -# New-Module's -ErrorAction Stop makes a throw in here (the stale-types check) -# stop the script that loads the kit. Build/New-ParallelKitModule.ps1 leaves -# that wrapper out of the module it makes. +# Loaded as an in-memory module, so the kit's own variables and helpers stay out +# of your session. New-Module's -ErrorAction Stop makes a throw in here stop the +# script that loads the kit; Build/New-ParallelKitModule.ps1 leaves this wrapper +# out. Get-Module -Name ParallelKit | Remove-Module New-Module -Name ParallelKit -ErrorAction Stop -ScriptBlock { @@ -67,10 +65,10 @@ public static class PkConsoleCtrl public static readonly ManualResetEventSlim DrainComplete = new ManualResetEventSlim(false); public static int DrainWaitMs = 65000; - // Ctrl+C presses: the first starts the abort, the next skips the drain - // (force-stops running jobs now), the one after that is let through to - // PowerShell, which stops the script. A press within SkipDebounceMs of - // the last counted one is a double tap or key repeat, and is ignored. + // Ctrl+C presses: the first starts the abort, the second skips the wait for + // running work (force-stops it now), the third goes to PowerShell, which + // stops the script. A press within SkipDebounceMs of the last counted one + // is ignored. public static volatile bool SkipDrain = false; public static volatile string PressedKey = null; // "Ctrl+C" / "Ctrl+Break" once a press started the abort public static int SkipDebounceMs = 1000; @@ -125,8 +123,9 @@ public static class PkConsoleCtrl AbortRequested = true; return true; } - // An abort is already under way (this press, Request-PkAbort or a - // close). A press that follows a counted one too closely is ignored. + // An abort is already under way (an earlier press, Request-PkAbort + // or a window close). A press too soon after the last counted one + // is ignored. if (_lastPressTimestamp != 0) { double sinceLastMs = (now - _lastPressTimestamp) * 1000.0 / System.Diagnostics.Stopwatch.Frequency; @@ -261,25 +260,8 @@ public sealed class PkStartedProcess public StreamReader Stderr; } -// Reads one of a program's output streams to its end, in chunks, so what has -// arrived can be taken at any time (Snapshot): something the program started -// can hold the stream open long after it exits. The first snapshot taken -// before the end is the stream's text from then on, and the task's result; -// without one, the result is the whole text. The read goes on to the end -// either way, dropping what it no longer needs, so nothing that writes to the -// stream blocks on a full pipe. The reader is closed there. -// -// No text ends in half a character: the decoder carries one split across two -// reads over to the next, and a snapshot leaves out a surrogate pair's first -// half whose second hasn't arrived. With a cap (maxChars), only the first half -// and the last half of a longer stream are kept, never split inside a pair, -// and DroppedChars counts the rest. -// -// Each read has a thread of its own (LongRunning), not a pool thread: it -// blocks until every holder of the stream's write end has let go (at the -// latest when PowerShell exits: they're in the Job Object). Leftover programs -// holding their output would otherwise use up the pool, and a new program's -// reads would wait for it to grow and hit their stream timeout. +// Reads an output stream to its end on a thread of its own, so what has +// arrived can be taken at any time (Snapshot) while a leftover child holds it. public sealed class PkStreamReadTask : Task { private sealed class Buffer @@ -292,11 +274,9 @@ public sealed class PkStreamReadTask : Task private string _kept; private readonly object _gate = new object(); public volatile bool ReaderClosed; - // The cap's tail: the last chars read, a ring once it's full. It - // grows with the output, so a cap costs nothing until output reaches - // it. _tailCap is 0 with no cap. A head that turns away a pair's - // first half gives the tail its slot, before the tail is allocated, - // so output that fits the cap is kept whole. + // The cap's tail: the last chars read, a ring once full, grown with the + // output. _tailCap is 0 with no cap; it grows by one when the head + // hands it the first half of a surrogate pair it can't keep. private readonly int _headCap; private int _tailCap; private bool _headFull; @@ -409,10 +389,9 @@ public sealed class PkStreamReadTask : Task private readonly Buffer _buffer; private PkStreamReadTask(Buffer buffer) : base(new Func(buffer.Pump), TaskCreationOptions.LongRunning) { _buffer = buffer; } - // Harness only: n >= 0 makes the Run after the next n throw, as one whose - // thread can't be created would; -1, the default, is off. With - // TestFailRunDelayMs above 0, that Run waits that long before throwing, so - // a program that ends at once has exited by then. + // Harness only: n >= 0 lets n more Runs succeed, then makes the next throw + // (0: the next one), as if its thread couldn't start; -1 is off. + // TestFailRunDelayMs waits that long first. public static int TestFailRunAfter = -1; public static int TestFailRunDelayMs = 0; @@ -443,12 +422,9 @@ public sealed class PkStreamReadTask : Task public bool TestReaderClosed { get { return _buffer.ReaderClosed; } } } -// A Windows Job Object with KILL_ON_JOB_CLOSE: every child process assigned -// to it dies when this process exits for ANY reason, force-kill included. -// Each program the kit starts also gets a job of its own (its tree job), -// nested in that one, so the program and everything it started can be -// killed at once (KillTree), including a child whose parent has already -// exited, which taskkill /T can't find. +// A Job Object with KILL_ON_JOB_CLOSE: everything in it dies when this process +// exits, force-kill included. Each program also gets a nested tree job, so +// KillTree ends it and everything it started, orphans included. public static class PkChildProcessJob { private const int JobObjectExtendedLimitInformation = 9; @@ -511,10 +487,8 @@ public static class PkChildProcessJob } private static readonly ConditionalWeakTable _treeJobs = new ConditionalWeakTable(); - // Harness only: start programs without a tree job, to test the taskkill - // path; or have TryStart's first CreateProcess, with the tree job, count - // as refused, to test its retry without one. TestFailTerminate makes - // KillTree's TerminateJobObject count as refused, leaving the tree running. + // Harness only: start without a tree job, have TryStart's first try with it + // count as refused, or have KillTree's TerminateJobObject count as refused. public static bool TestNoTreeJob = false; public static bool TestRefuseTreeJob = false; public static bool TestFailTerminate = false; @@ -525,11 +499,9 @@ public static class PkChildProcessJob catch (ArgumentException) { CloseHandle(treeJob); } // already has one: a second Assign of the same Process } - // Kills every process in the program's tree job. False if it has none, - // or Windows refused: Stop-PkProcessTree then uses taskkill. The job stays open - // until ReleaseTree (Complete-PkProcess, or the kit's own kill paths) or - // garbage collection, so a second KillTree, as -KillTreeOnExit makes - // after a time-limit kill or a force-stop, ends an empty job and succeeds. + // Ends every process in the program's tree job; false with no tree job or + // on a refusal. The job stays open until ReleaseTree, so a second KillTree + // ends an empty job and succeeds. public static bool KillTree(Process process) { if (process == null) { return false; } @@ -606,12 +578,9 @@ public static class PkChildProcessJob } } - // Never throws: a failed assignment only loses the force-kill cleanup - // for that one process. Once it's in the kit's job, it also gets a tree - // job (Windows nests it); without one, a kill uses taskkill. reason says - // why it failed ("Win32 error 5", or what was thrown), null when it - // worked. Per call: LastError is shared, and another thread's start can - // change it before the caller reads it. + // Never throws: a failed assignment only loses cleanup for that process. A + // program in the kit's job gets a nested tree job too. reason is why it + // failed, null when it worked (LastError is shared across threads). public static bool Assign(System.Diagnostics.Process process, out string reason) { reason = null; @@ -640,25 +609,8 @@ public static class PkChildProcessJob } // ---- Starting a program inside the job from its first instruction ---- - // - // Process.Start can only be followed by Assign, so a program that starts a - // child straight away (cmd /c tool.exe) can do so before it's in the job, - // and that child survives a force-kill. TryStart has Windows put the - // program in the job as it creates it (PROC_THREAD_ATTRIBUTE_JOB_LIST, - // Windows 10 / Server 2016+), so its children join too. - // - // Everything else copies Process.Start with UseShellExecute = false: - // command line, Windows' own search for a bare name, CREATE_NO_WINDOW, - // redirected stdout/stderr, and the default encoding. stdin is NUL, or - // PowerShell's own as Process.Start passes it. - // - // The pipe ends the child writes to must be inheritable while it's - // created, and a plain Process.Start elsewhere in PowerShell inherits - // every inheritable handle: it would hold our output open until it exits. - // .NET's own start lock keeps those apart, so TryStart takes it (found by - // reflection) and returns null, for Process.Start plus Assign, when it - // isn't there in a form it knows. The handle list keeps our child from - // inheriting anyone else's handles. + // Process.Start then Assign lets an immediate child escape the job, so + // TryStart creates the program in it, holding .NET's start lock. private const uint CREATE_SUSPENDED = 0x4; private const uint CREATE_UNICODE_ENVIRONMENT = 0x400; @@ -746,10 +698,10 @@ public static class PkChildProcessJob [DllImport("kernel32.dll")] private static extern uint GetConsoleOutputCP(); - // .NET's process-start lock: a plain object (5.1, 7.6) is held with - // Monitor; a System.Threading.Lock (where newer .NET is moving its locks) - // through its own Enter/Exit, by reflection since 5.1 has no such type. - // Monitor on a Lock wouldn't keep out its Enter, hence the type check. + // .NET's process-start lock: a plain object (in Windows PowerShell 5.1's + // .NET Framework and PowerShell 7.6's .NET) through Monitor; a + // System.Threading.Lock, where newer .NET moves its locks, through its own + // Enter/Exit, by reflection since 5.1 has no such type. private sealed class StartLock { public readonly string Kind; @@ -851,11 +803,9 @@ public static class PkChildProcessJob public static bool TestFailSetup = false; public static bool TestFailReaders = false; - // How programs start here, for Initialize-ParallelKit: "CreatedInJob" - // (TryStart), "AddedToJob" (Process.Start, then the job: no usable start - // lock, or the harness switch), or "NoJob" (the job couldn't be set up, - // so nothing is cleaned up on a kill). A single start can still fall back - // from CreatedInJob when its setup fails; that warns. + // How programs start, for Initialize-ParallelKit: CreatedInJob (TryStart), + // AddedToJob (Process.Start, then the job) or NoJob (no cleanup on a kill). + // One start can still fall back, with a warning. public static string StartMode { get @@ -870,10 +820,8 @@ public static class PkChildProcessJob private static int _fallbackWarned = 0; public static bool ClaimFallbackWarning() { return Interlocked.Exchange(ref _fallbackWarned, 1) == 0; } public static void TestResetFallbackWarning() { Interlocked.Exchange(ref _fallbackWarned, 0); } - // The same, once each, for a Job Object that couldn't be set up when - // first needed, for a running program Windows wouldn't add to it, and for - // -KillTreeOnExit on a program without a tree job, or whose tree job - // Windows wouldn't end. + // The same, once each: no Job Object, a program Windows wouldn't add to it, + // -KillTreeOnExit without a tree job, and a tree job Windows wouldn't end. private static int _initWarned = 0, _assignWarned = 0, _noTreeWarned = 0, _killTreeWarned = 0; public static bool ClaimInitWarning() { return Interlocked.Exchange(ref _initWarned, 1) == 0; } public static bool ClaimAssignWarning() { return Interlocked.Exchange(ref _assignWarned, 1) == 0; } @@ -884,11 +832,9 @@ public static class PkChildProcessJob [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] private static extern uint GetShortPathName(string lpszLongPath, StringBuilder lpszShortPath, uint cchBuffer); - // The 8.3 short form of a full path, or null when it has none that differs: - // the path doesn't exist, isn't rooted, or the volume doesn't make short - // names. Asked with the \\?\ prefix, which works past 260 characters on - // both runtimes (without it, PowerShell 7 fails there); the answer comes - // back without it, since CreateProcess refuses a prefixed program path. + // A full path's 8.3 short form, or null if it has none that differs. Asked + // with the \\?\ prefix (needed past 260 characters on PowerShell 7), answered without + // it, since CreateProcess refuses a prefixed program path. public static string GetShortPath(string path) { if (string.IsNullOrEmpty(path)) { return null; } @@ -957,12 +903,8 @@ public static class PkChildProcessJob return nul; } - // Starts the program in the job, or returns null when it can't do that - // safely: the caller then uses Process.Start and Assign. fallbackReason - // says why, for the caller's one-time warning; it stays null where no - // warning is due (no job, which has its own; the harness switch). Throws - // Win32Exception when Windows refuses to create the program, as - // Process.Start does. encoding null: the console's output code page. + // Starts the program in the job, or returns null (with fallbackReason) for + // Process.Start and Assign. Throws as Process.Start does. public static PkStartedProcess TryStart(string fileName, string arguments, string workingDirectory, Encoding encoding, bool inheritStdin, out string fallbackReason) { fallbackReason = null; @@ -997,10 +939,9 @@ public static class PkChildProcessJob CreateOutputPipe(out outRead, out outWrite); CreateOutputPipe(out errRead, out errWrite); - // NUL, so a program that reads its input gets the end of it - // at once. Or, asked for, PowerShell's own as Process.Start - // passes it: listed only if inheritable, the only case the - // child could use it. + // NUL, so a program reading its input gets the end at once; + // or, asked for, PowerShell's own, listed only if + // inheritable. bool stdinInherit = true; if (inheritStdin) { @@ -1058,10 +999,9 @@ public static class PkChildProcessJob if (started) { started = CreateProcess(null, commandLine, IntPtr.Zero, IntPtr.Zero, true, flags, IntPtr.Zero, dir, ref si, out pi); } if (!started && jobCount == 2) { - // Once more without the tree job, in case that's what Windows - // refused (nesting it): the program still starts, and a kill - // then uses taskkill. A program that can't start at all fails - // again, with its own error. + // Once more without the tree job, in case nesting it is + // what Windows refused; a program that can't start fails + // again with its own error. DeleteProcThreadAttributeList(attrList); attrReady = false; CloseHandle(treeJob); treeJob = IntPtr.Zero; jobCount = 1; int retryError = SetStartAttributes(attrList, attrSize, handleArr, handleCount, jobArr, jobCount); @@ -1138,9 +1078,8 @@ public static class PkChildProcessJob '@ -Language CSharp } -# A session that loaded another version keeps that one's compiled types. Say -# so, rather than fail later with a missing-method error. Keep this number in -# sync with [PkState]::TypesVersion. +# Another version's compiled types stay loaded: say so rather than fail later. +# Keep in step with [PkState]::TypesVersion. if ((& { try { [PkState]::TypesVersion } catch { 0 } }) -ne 16) { throw "ParallelKit: this PowerShell session already loaded a different version of the kit, and its compiled parts can't be swapped out. Close this window and start a new one." } @@ -1183,9 +1122,9 @@ function Invoke-PkMessageHandler { $handler = [PkState]::MessageHandler if ($null -ne $handler) { try { - # Invoke-PkCallback's do/while, inlined: its warning is itself a - # message. Warns on the console, once per handler (a note on the - # scriptblock). + # Invoke-PkCallback's do/while, inlined. Its warning goes straight + # to the console, not through the handler that just misbehaved; once + # per handler. $handlerDone = $false do { $null = & $handler $Message $Level; $handlerDone = $true } while ($false) if (-not $handlerDone -and $null -eq $handler.PSObject.Properties['PkLoopWarned']) { @@ -1245,16 +1184,12 @@ function Receive-PkWorkerMessage { } function Invoke-PkCallback { - # Calls one of the caller's callbacks and returns its output. A `continue` - # or `break` in a callback goes to the nearest loop on the call stack, even - # across the module boundary: one of the kit's, which then skips its - # bookkeeping or never ends. This do/while catches it instead, so it ends - # only the callback, like `return`. A labeled `break outer` still reaches - # the caller's loop. Inlined where a callback runs per job or per result - # (on 5.1 this call more than doubled the dispatcher's own time per job), - # in Invoke-PkMessageHandler, and for -GroupProvider in - # Invoke-PkProcessDispatchCore, which counts the values it outputs. - # pk-prefixed: in a worker, a callback without .GetNewClosure() sees this frame. + # Calls a caller's callback. A continue or break in it would jump to the + # nearest loop on the call stack, one of the kit's; the do/while catches it, + # so it ends only the callback. Inlined where a callback runs per job or per + # result, since the call is costly on 5.1. Variables are pk-prefixed: in a + # worker, a callback without .GetNewClosure() can read this function's + # variables by name. param( [Parameter(Mandatory)][scriptblock]$PkCallback, [object[]]$PkArgs = @(), @@ -1269,9 +1204,8 @@ function Invoke-PkCallback { } function Write-PkCallbackLoopWarning { - # For a callback that used continue/break (see Invoke-PkCallback). Warns - # once per -PkName in a run. -PkContext is the run's @{ Prefix; Warned }: - # Prefix names the engine, Warned the names already warned about. + # Warns once per -PkName in a run that a callback used continue/break. + # -PkContext is the run's @{ Prefix; Warned }. param([string]$PkName, [hashtable]$PkContext) $pkWarned = $PkContext['Warned'] if ($pkWarned.ContainsKey($PkName)) { return } @@ -1292,9 +1226,9 @@ function Register-PkAbortHandler { } function Initialize-PkChildProcessJob { - # -Once: warn only the first time it fails in this session. For the - # setup a start does when nothing set the job up first, which retries on - # every start after a failure. Write-PkMessage: a start can be in a worker. + # -Once: warn only on the first failure this session, since every start that + # finds no Job Object retries the setup. Write-PkMessage, because a start + # can run in a worker. param([switch]$Once) if ([PkChildProcessJob]::Initialize()) { return $true } if (-not $Once -or [PkChildProcessJob]::ClaimInitWarning()) { @@ -1320,7 +1254,7 @@ function Initialize-ParallelKit { param() $handlerOk = Register-PkAbortHandler $jobOk = Initialize-PkChildProcessJob - # The header's Version line: the version PR changes both, and the harness + # Keep in step with the Version line in this file's header; the harness # checks they match. $version = [version]'4.2' return [pscustomobject][ordered]@{ AbortHandler = $handlerOk; ChildProcessJob = $jobOk; Version = $version; StartMode = [PkChildProcessJob]::StartMode } @@ -1408,7 +1342,8 @@ function Test-PkAbortSignal { } $pressedKey = [PkConsoleCtrl]::PressedKey $abortMessage = if ([PkState]::CloseAbort) { - # No drain on a close: Windows ends the process within seconds. + # A window close doesn't wait for running work: Windows ends the + # process within seconds. "[ABORT] Window close detected - stopping current jobs now..." } elseif ($null -ne $pressedKey) { "[ABORT] " + $pressedKey + " detected - finishing current jobs, please wait... Press Ctrl+C again to stop them now." @@ -1462,8 +1397,9 @@ function Get-PkForceStopReason { } function Complete-PkAbortDrain { - # Releases the native handler thread. Idempotent; safe on a run that was - # never aborted. + # Sets DrainComplete, releasing the native console handler's thread that + # waits on it after a window close. Idempotent; safe on a run that was never + # aborted. try { [PkConsoleCtrl]::DrainComplete.Set() } catch { } # nothing useful to do if the event itself is broken } @@ -1498,9 +1434,8 @@ function Invoke-PkRun { [bool]$DisableQuickEdit = $true, [bool]$KeepAwake = $true ) - # Already inside a run: just run it. Re-arming would wipe the outer run's - # abort state, and disarming afterwards would leave the rest of it - # unprotected. + # Already in a run: re-arming would wipe the outer run's abort state, and + # disarming would leave the rest of it unprotected. if ([PkConsoleCtrl]::RunActive) { & $ScriptBlock return @@ -1571,13 +1506,9 @@ function ConvertTo-PkArgumentString { } function ConvertTo-PkArgumentStringCore { - # ConvertTo-PkArgumentString's body. -ForBatchFile: for cmd.exe or a .bat - # or .cmd, whose command line cmd.exe reads first, a quote is written "" - # instead of \". cmd.exe counts every quote, \" included, so with \" an - # argument like a" & del ... & " runs a second command. "" keeps the count - # even, and the C runtime (not the old msvcrt.dll) still reads it as one - # quote in a program the batch file passes %* to. A line break would end - # cmd.exe's command line, so it's refused. + # ConvertTo-PkArgumentString's body. -ForBatchFile writes a quote as "" + # (cmd.exe counts every quote, so \" lets an argument run a second command). + # A line break is refused: it ends cmd.exe's command line. param( [AllowNull()] [AllowEmptyCollection()] @@ -1603,10 +1534,9 @@ function ConvertTo-PkArgumentStringCore { if ($arg.IndexOf([char]0) -ge 0) { throw ("Arguments element " + $position + " contains a NUL character, which can't be passed on a command line: Windows would end the command line there and drop the rest, later arguments included. Pass it another way (a file, an environment variable).") } - # The C runtime only needs whitespace and quotes quoted. The rest are for - # cmd.exe, which runs a .bat/.cmd: it acts on & | < > ^ ( ) outside - # quotes and splits batch arguments at , ; Quoting them is harmless - # to other programs. + # The C runtime only needs whitespace and quotes quoted; cmd.exe also + # acts on & | < > ^ ( ) and splits batch arguments at , ; Quoting those + # is harmless to other programs. if ($arg.Length -gt 0 -and $arg.IndexOfAny([char[]]@(' ', "`t", "`n", "`v", '"', '&', '|', '<', '>', '^', '(', ')', ',', ';')) -lt 0) { $parts.Add($arg) continue @@ -1641,11 +1571,9 @@ function ConvertTo-PkArgumentStringCore { } function Resolve-PkArgumentList { - # -Arguments as given -> the command line: a string as written, a list - # quoted one argument per element (a [string] cast would join it with - # spaces, or $OFS), a lone file or folder object as its full path. - # -FilePath picks batch-file quoting for cmd.exe or a .bat or .cmd. A bare - # name only finds an .exe, so a batch file always has its extension here. + # -Arguments -> the command line: a string as written, a list quoted per + # element, a file object as its path. -FilePath picks batch-file quoting for + # cmd.exe, .bat and .cmd. param($Arguments, [string]$FilePath = '') if ($null -eq $Arguments) { return '' } if ($Arguments -is [string]) { return $Arguments } @@ -1653,10 +1581,9 @@ function Resolve-PkArgumentList { throw ("Arguments must be one string or a list of arguments (got a " + $Arguments.GetType().Name + ").") } if ($Arguments -is [System.Collections.IEnumerable] -or $Arguments -is [System.IO.FileSystemInfo]) { - # Windows drops trailing dots and spaces from a file name, so - # 'run.cmd.' still runs through cmd.exe. cmd.exe itself, given a list - # (cmd /c tool "a b"), reads its command line the same way, so it gets - # the same quoting, under a drive-relative path (C:cmd.exe) too. + # Windows drops trailing dots and spaces, so 'run.cmd.' runs through + # cmd.exe too; cmd.exe itself, even drive-relative (C:cmd.exe), reads + # its command line the same way. $exeName = $FilePath.Trim().Trim('"').TrimEnd(' ', '.') $forBatchFile = ($exeName -match '\.(bat|cmd)$' -or $exeName -match '(^|[\\/:])cmd(\.exe)?$') return (ConvertTo-PkArgumentStringCore -Arguments @($Arguments) -ForBatchFile:$forBatchFile) @@ -1665,16 +1592,15 @@ function Resolve-PkArgumentList { } function Resolve-PkEncoding { - # -OutputEncoding as given (an Encoding, a code page number, or a name - # like 'utf-8' or 'utf8') -> an Encoding, or $null for "not set". A code - # page can come as a string of digits too ('65001' from a CSV or config). + # -OutputEncoding (an Encoding, a code page, possibly as digits, or a name) + # -> an Encoding, or $null for not set. param($Encoding) if ($null -eq $Encoding -or ($Encoding -is [string] -and $Encoding -eq '')) { return $null } if ($Encoding -is [System.Text.Encoding]) { return $Encoding } # .NET Framework doesn't know the name 'utf8'; no BOM either way, since # this only decodes. if ($Encoding -is [string] -and $Encoding -in @('utf8', 'utf-8')) { return [System.Text.UTF8Encoding]::new($false) } - # Any whole number, too: ConvertFrom-Json on 7 gives an Int64. + # Any whole number, too: ConvertFrom-Json on PowerShell 7 gives an Int64. $codePage = 0 $digits = ([string]$Encoding).Trim() if ($digits -match '^[0-9]+$' -and [int]::TryParse($digits, [ref]$codePage)) { $Encoding = $codePage } @@ -1687,11 +1613,9 @@ function Resolve-PkEncoding { } function Resolve-PkFileSystemPath { - # A path the way PowerShell reads it, turned into one Windows can use: - # relative to the current location, or on a drive like Data:\ or ~. - # Anything that isn't a file-system path to PowerShell (relative while - # the current location is HKLM:, say) is taken relative to $Here, the - # last file-system location. + # A PowerShell path -> one Windows can use: relative to the current + # location, or on a PS drive. A path that isn't a file-system one to + # PowerShell is taken relative to $Here, the last file-system location. param([string]$Path, [string]$Here, [System.Management.Automation.SessionState]$CallerState) # Only a complete path goes straight through. \tools and C:tools depend on # a current drive and folder, which are PowerShell's here, not the process's. @@ -1703,9 +1627,8 @@ function Resolve-PkFileSystemPath { $resolved = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Path, [ref]$provider, [ref]$drive) if ($provider.Name -eq 'FileSystem') { return $resolved } } catch { $lookupFailed = $true } - # A drive this module can't see: New-PSDrive inside the caller's function - # makes one visible only from that function. Ask again from there, the - # way Get-PkCallerFunction does (see its notes on InvokeScript). + # A drive only the caller's function can see (New-PSDrive inside it): ask + # again from there, as Get-PkCallerFunction does. if ($lookupFailed -and $null -ne $CallerState) { $q = [string][char]39 $text = @' @@ -1781,9 +1704,8 @@ function Start-PkProcess { } function Start-PkProcessCore { - # Start-PkProcess's body. -CallerState: the session of whoever called the - # public function, for paths only visible from there. Deep inside the - # module, $PSCmdlet no longer leads back to the caller. + # Start-PkProcess's body. -CallerState: the public function's caller's + # session, for paths only visible from there. param( [Parameter(Mandatory)] [string]$FilePath, @@ -1815,22 +1737,22 @@ function Start-PkProcessCore { } $psi.RedirectStandardOutput = $true $psi.RedirectStandardError = $true - # On the Process.Start path, an empty stdin is a pipe closed at once below. - # On .NET Framework with a UTF-8 console, Process.Start itself has written a - # byte-order mark into it by then, and takes no encoding to stop that. + # Without -InheritStdin, stdin is a pipe closed right after the start, so + # the program reads end-of-input at once. On .NET Framework with a UTF-8 + # console, Process.Start has already written a byte-order mark into it, and + # nothing stops that. $psi.RedirectStandardInput = -not $InheritStdin $psi.CreateNoWindow = $true - # Relative paths mean your current location, not the process's working - # directory, which Set-Location never changes. From a location that isn't - # on disk (HKLM:) that's the last file-system one. If that folder is gone, - # the process's working directory. + # Relative paths mean your current location (the last file-system one if + # that's HKLM:), not the process's working directory, which Set-Location + # never changes. $here = $ExecutionContext.SessionState.Path.CurrentFileSystemLocation.ProviderPath if (-not [System.IO.Directory]::Exists($here)) { $here = $null } - # In a try/catch: a .NET call that throws doesn't reliably stop the - # script, and a $null process would be polled forever. The path handling - # is in here too: it throws on characters Windows doesn't allow. + # In a try/catch: a .NET call that throws doesn't reliably stop the script, + # and a $null process would be polled forever. The path handling throws on + # characters Windows doesn't allow. $started = $null $lengthNote = "" try { @@ -1846,15 +1768,15 @@ function Start-PkProcessCore { $psi.FileName = Resolve-PkFileSystemPath -Path $FilePath -Here $here -CallerState $CallerState } # In the job from its first instruction where possible; otherwise - # Process.Start, and the job just after (a child it starts at once - # can miss it then). + # Process.Start, then the job (a child started at once can miss it). $fallbackReason = $null $firstError = $null while ($true) { try { $started = [PkChildProcessJob]::TryStart($psi.FileName, $psi.Arguments, $psi.WorkingDirectory, $encoding, $InheritStdin, [ref]$fallbackReason) if ($null -eq $started) { - # Once per process: the cost is the same for every program after. + # Once per session: every later start falls back the same + # way, at the same cost. if ($null -ne $fallbackReason -and [PkChildProcessJob]::ClaimFallbackWarning()) { Write-PkMessage ("[WARNING] Starting programs with Process.Start and adding them to the Job Object just after, because " + $fallbackReason + ". A child a program starts straight away (cmd /c tool.exe) can escape the cleanup if PowerShell is killed outright. Shown once.") -Level Warn } @@ -1866,17 +1788,16 @@ function Start-PkProcessCore { break } catch { if ($null -ne $firstError) { - # The short names failed too: the first error, for the paths given. + # The 8.3 short-name retry failed too: put the paths back + # and throw the first error. $psi.FileName = $longFile $psi.WorkingDirectory = $longDir throw $firstError } $firstError = $_ - # Windows refuses a program path of 260 characters or more and - # a working folder of 259 or more (it adds a backslash), on both - # start paths and even with long paths enabled. The 8.3 short - # names, where the volume has them, start fine: one more try - # with those. + # Windows won't start a program by a path of 260+ characters or + # in a folder of 259+, even with long paths on. Try once more + # with the 8.3 short names, where the volume has them. $longFile = $psi.FileName $longDir = $psi.WorkingDirectory $shortFile = $null @@ -1900,7 +1821,8 @@ function Start-PkProcessCore { $reason = [string]$_ if ($_.Exception -is [System.Management.Automation.MethodInvocationException] -and $null -ne $_.Exception.InnerException) { $reason = $_.Exception.InnerException.Message } if ($lengthNote) { $reason = $reason.TrimEnd('.') + ". " + $lengthNote } - # The original goes along as the inner exception: the batch reads Windows' error code from it. + # The original goes along as the inner exception: + # Get-PkStartFailureCause reads Windows' error code from it. throw [System.Management.Automation.RuntimeException]::new("Start-PkProcess: could not start '" + $FilePath + "'" + $tried + ": " + $reason, $_.Exception) } # The output is read in chunks (PkStreamReadTask), so Complete-PkProcess @@ -1910,9 +1832,9 @@ function Start-PkProcessCore { $stdout = $started.Stdout $stderr = $started.Stderr } else { - # Windows also refuses a program that has already exited (error 5), as - # quick ones often have by now: only one still running is a real gap. - # With no job at all, the setup above has warned already. + # Assign fails with error 5 for a program that has already exited, which + # is harmless: only a running one outside the Job Object is worth a + # warning. With no Job Object at all, the setup has warned already. $assignWhy = $null if (-not [PkChildProcessJob]::Assign($proc, [ref]$assignWhy) -and [PkChildProcessJob]::IsInitialized -and -not $proc.HasExited -and [PkChildProcessJob]::ClaimAssignWarning()) { Write-PkMessage ("[WARNING] Windows wouldn't add a program to the kit's Job Object (process " + $proc.Id + ", " + $psi.FileName + ": " + $assignWhy + "). It isn't cleaned up if PowerShell is killed outright, and killing it reaches what it started only through taskkill. Shown once.") -Level Warn @@ -1920,9 +1842,8 @@ function Start-PkProcessCore { $stdout = $proc.StandardOutput $stderr = $proc.StandardError } - # The program is running now. If a reader can't start (no thread to be - # had), nothing would read its output and nobody would hold the program: - # end it and what it started, and fail the start instead. + # If a reader can't start, nothing would read the output or hold the + # program: end it and what it started, and fail the start. $stdoutTask = $null try { $stdoutTask = [PkStreamReadTask]::Run($stdout, $MaxOutputChars) @@ -1939,8 +1860,8 @@ function Start-PkProcessCore { if ($treeNote) { $failure = "Start-PkProcess: could not start '" + $FilePath + "': its output couldn't be read (" + $reason + "). " + $treeNote } throw [System.Management.Automation.RuntimeException]::new($failure, $_.Exception) } - # The dispatcher's default starter and the batch's starter copy these four - # keys onto their job: a new key goes in all three. + # Invoke-PkProcessDispatch's default starter and Invoke-PkProcessBatch's + # starter copy these four keys onto their jobs: a new key goes in all three. return @{ Proc = $proc StdoutTask = $stdoutTask @@ -1976,9 +1897,8 @@ function Stop-PkProcessTree { } function Stop-PkProcessTreeCore { - # Stop-PkProcessTree's body. The other parameters are for the harness: a - # stand-in for taskkill, a shorter wait for it, and a shorter limit on its - # argument list. + # Stop-PkProcessTree's body. The other parameters are the harness's: a + # stand-in taskkill, a shorter wait, a shorter argument-list limit. param( [AllowEmptyCollection()] [System.Diagnostics.Process[]]$Process, @@ -1992,15 +1912,13 @@ function Stop-PkProcessTreeCore { foreach ($p in $Process) { if ($null -ne $p -and $p.HasExited -eq $false -and $null -ne $p.Id) { $alive.Add($p) } } if ($alive.Count -eq 0) { return $false } $killed = $false - # A program the kit started has a tree job: killing that ends the program - # and everything it started at once, a child whose parent already exited - # included. taskkill /T only finds children through their parent, so it's - # for the rest: a program without a tree job, or one Windows wouldn't end. + # A tree job ends the program and everything it started, an orphaned child + # included; taskkill /T, which finds children only through their parent, is + # for the rest. $viaTaskkill = [System.Collections.Generic.List[System.Diagnostics.Process]]::new() foreach ($p in $alive) { if ([PkChildProcessJob]::KillTree($p)) { $killed = $true } else { $viaTaskkill.Add($p) } } # One command line for every PID passes Windows' 32,767-character limit at - # roughly 2,500-3,000 programs, and then taskkill can't start at all: so as - # many taskkill calls as the limit needs. + # roughly 2,500 programs: as many taskkill calls as it takes. if ($MaxArgumentLength -le 0) { $MaxArgumentLength = 32000 - $TaskkillPath.Length } $ids = [int[]]@(foreach ($p in $viaTaskkill) { $p.Id }) foreach ($taskkillArgs in $(if ($ids.Count -gt 0) { Split-PkTaskkillArgumentList -Ids $ids -MaxLength $MaxArgumentLength })) { @@ -2021,19 +1939,16 @@ function Stop-PkProcessTreeCore { try { $null = [System.Threading.Tasks.Task]::WaitAll(@($taskkillOut, $taskkillErr), 2000) } catch { } # the reads only keep the pipes drained; their text isn't used } else { # Still running after its wait (hung, or held up by security - # software): killed, so it isn't left running outside the - # Job Object. The fallback below kills the programs. + # software): killed, so it isn't left outside the Job + # Object. The fallback below kills the programs. try { $taskkill.Kill(); $null = $taskkill.WaitForExit(2000) } catch { } # it exited between the wait and the kill } } finally { $taskkill.Dispose() } } catch { } # taskkill missing or blocked: the fallback below still kills each process itself } - # taskkill fails if any process in the trees couldn't be killed, even when - # it killed the program: one already gone (a child in another listed tree, - # or a `cmd /c` that ended once taskkill killed its child, which it does - # first) or one it wasn't allowed to kill. So a listed process now gone - # counts as killed, even one that just exited on its own. Only - # Stop-PkTimedOutJob reads the result, and it only kills overdue programs. + # taskkill fails if any process in a tree couldn't be killed, even when it + # killed the program, so a listed process now gone counts as killed. + # Stop-PkProgramTree reads the result. if (-not $killed) { foreach ($p in $alive) { if ($p.HasExited) { $killed = $true; break } } } @@ -2051,9 +1966,8 @@ function Stop-PkProcessTreeCore { } function Split-PkTaskkillArgumentList { - # taskkill argument lists ('/T /F /PID 1 /PID 2 ...') for these PIDs, as - # few as fit, each at most MaxLength characters (a single PID that doesn't - # fit still gets a list of its own). Returns a list of strings. + # taskkill argument lists ('/T /F /PID 1 /PID 2 ...') for these PIDs, as few + # as fit in MaxLength characters each. param([int[]]$Ids, [int]$MaxLength) $lists = [System.Collections.Generic.List[string]]::new() $current = [System.Text.StringBuilder]::new('/T /F') @@ -2073,23 +1987,30 @@ function Split-PkTaskkillArgumentList { } function Stop-PkJobProcess { - # The dispatcher's force-stop: every running job's tree in one - # Stop-PkProcessTree call. A custom starter's .Proc may not be a Process; - # those are skipped. Stop-PkProcessTree passes over a program that has - # exited; with -KillTreeOnExit, what that left running goes as well. - param([System.Collections.Generic.List[hashtable]]$Jobs) + # Kills every running job's program in one Stop-PkProcessTree call (one + # taskkill at most), then ends each killed program's tree job once more and + # warns, with -Why, if Windows won't; then -KillTreeOnExit's leftovers. Used + # by the dispatcher's force-stop and Invoke-PkProcessWithTimeout's cleanup. + param([System.Collections.Generic.List[hashtable]]$Jobs, [string]$Why = 'a force-stop') $procs = foreach ($job in $Jobs) { if ($job['Proc'] -is [System.Diagnostics.Process]) { $job['Proc'] } } + $running = @(foreach ($p in $procs) { if ($p.HasExited -eq $false) { $p } }) try { $null = Stop-PkProcessTree -Process @($procs) } catch { } # best effort; each job is still waited on and disposed after + # Each killed program's tree job again, as Stop-PkProgramTree does after a + # kill: a second KillTree fails only if Windows won't end it. + foreach ($p in $running) { + try { if ([PkChildProcessJob]::HasTree($p) -and -not [PkChildProcessJob]::KillTree($p)) { Write-PkKillTreeWarning -ProcessId $p.Id -Why $Why } } catch { } # best effort, as above + } foreach ($job in $Jobs) { if ($job['KillTree']) { try { Stop-PkExitedJobTree -Job $job } catch { } } } # best effort, as above - # The kills are done: the tree jobs' handles can go now, not at garbage - # collection (KillTree leaves them open, and these jobs aren't completed). + # The kills are done: release each tree job's handle now rather than at + # garbage collection, since KillTree leaves it open and these jobs won't + # reach Complete-PkProcess, which would release it. foreach ($job in $Jobs) { if ($job['Proc'] -is [System.Diagnostics.Process]) { try { [PkChildProcessJob]::ReleaseTree($job['Proc']) } catch { } } } # nothing to report } function Get-PkJobTimeLimit { - # A dispatcher job's time limit in seconds: its own TimeoutSeconds key if it - # has one, else the default. 0 = no limit. Throws on a bad key. The batch - # and dispatcher check their -TimeoutSeconds by the same rule. + # A job's time limit in seconds: its TimeoutSeconds key, else the default; 0 + # = none. Throws on a bad key, by the same rule as the engines' + # -TimeoutSeconds. param([hashtable]$Job, [double]$DefaultTimeoutSeconds = 0) $value = $Job['TimeoutSeconds'] if ($null -eq $value) { return $DefaultTimeoutSeconds } @@ -2102,9 +2023,8 @@ function Get-PkJobTimeLimit { } function Get-PkJobOutputLimit { - # A job's output cap in characters: its own MaxOutputChars key if it has - # one, else the default. 0 = no cap. Throws on a bad key, as - # Get-PkJobTimeLimit does for TimeoutSeconds. + # A job's output cap: its MaxOutputChars key, else the default; 0 = none. + # Throws on a bad key. param([hashtable]$Job, [int]$DefaultMaxOutputChars = 0) $value = $Job['MaxOutputChars'] if ($null -eq $value) { return $DefaultMaxOutputChars } @@ -2118,9 +2038,7 @@ function Get-PkJobOutputLimit { function Get-PkJobSwitch { # A job's own $true/$false key (InheritStdin, KillTreeOnExit), else the - # default: the engine's switch of the same name. Throws on anything else, as - # Get-PkJobTimeLimit does for TimeoutSeconds. Text is taken ('True', as a - # CSV gives it), but not a number. + # engine's switch. Text like 'True' is taken; a number isn't. param([hashtable]$Job, [string]$Key, [bool]$Default = $false) $value = $Job[$Key] if ($null -eq $value) { return $Default } @@ -2130,42 +2048,32 @@ function Get-PkJobSwitch { } function Stop-PkTimedOutJob { - # Kills a dispatcher job's program tree once it passes its TimeLimit and - # sets TimedOut; the job is then finalized like any other. Only a .Proc - # that is a real Process is timed. + # Kills a dispatcher job's program tree once it passes its TimeLimit, and + # sets TimedOut. Only a real Process is timed. param([hashtable]$Job) $proc = $Job['Proc'] $clock = $Job['Stopwatch'] if ($proc -isnot [System.Diagnostics.Process] -or $clock -isnot [System.Diagnostics.Stopwatch]) { return } if ($proc.HasExited -or $clock.Elapsed.TotalSeconds -lt $Job['TimeLimit']) { return } - # Only flagged if this call did the killing: a program that exited on its - # own right at the deadline didn't time out. One try only: this runs every - # pass, and a program that can't be killed would start a taskkill each time. + # TimedOut only if this call killed it: one that exited right at the + # deadline didn't time out. TimeLimit is set to 0 first, so there's one + # attempt, not one per dispatcher pass. $Job['TimeLimit'] = 0 $stopped = Stop-PkProgramTree -Process $proc - if ($stopped -eq 'Killed') { + if ($stopped -eq 'Killed' -or $stopped -eq 'Refused') { $Job['TimedOut'] = $true + if ($stopped -eq 'Refused') { Write-PkKillTreeWarning -ProcessId $proc.Id -Why 'its time limit' } } elseif ($stopped -eq 'NotKilled' -or $stopped -eq 'Unknown') { Write-PkMessage ("ProcessDispatch: a job passed its time limit, but its program (process " + $proc.Id + ") couldn't be stopped. It holds its slot until it exits.") -Level Warn } } function Stop-PkProgramTree { - # Ends one program and, with -Leftovers, what it started, and says how - # that went. Every kill path for one program goes through here: the - # time-limit kill, -KillTreeOnExit (Stop-PkExitedJobTree, which the - # force-stop and Complete-PkProcess call too) and a failed start's - # rollback (Stop-PkFailedStartTree). The force-stop kills the running - # programs in one Stop-PkProcessTree call first, for one taskkill. - # A running program goes to Stop-PkProcessTree: its tree job, else - # taskkill /T. One that has exited can only be reached through its tree - # job, since taskkill /T finds children through their parent. Returns - # Killed (it was running, and this call ended it), NotKilled (it's still - # running), Unknown (its state can't be read: never started, or - # disposed), Exited (it had exited), or, with -Leftovers, NoTree or Refused - # when what it started may still be running: it had exited and has no - # tree job, or Windows wouldn't end its tree job. Otherwise -Leftovers - # has ended what it started too. + # Ends one program (Stop-PkProcessTree), checks its tree job after a kill, + # and with -Leftovers ends what an exited one left. Returns Killed, + # NotKilled, Unknown (state unreadable), Exited, or Refused / NoTree when + # what it started may still be running. The force-stop kills in one batch + # instead, and Stop-PkJobProcess repeats this post-kill check. param([Parameter(Mandatory)][System.Diagnostics.Process]$Process, [switch]$Leftovers) # A Process never started, or disposed, reads $null here (no throw): it # can't be read or killed by its handle. Its tree job still works. @@ -2180,12 +2088,10 @@ function Stop-PkProgramTree { } $done = 'Exited' if ($killed) { $done = 'Killed' } - if (-not $Leftovers) { return $done } - # Through the tree job even after a kill: if Windows wouldn't end it, - # Stop-PkProcessTree's taskkill /T got the program but can miss what it - # started. A second KillTree ends an empty job, so it fails only then. - # Windows refusing has no fallback: taskkill /T finds children only - # through a parent that's still running. + if (-not $killed -and -not $Leftovers) { return $done } + # The tree job even after a kill: if Windows wouldn't end it, taskkill /T + # can miss an orphaned child. A second KillTree ends an empty job, so it + # fails only on a refusal, which has no fallback. if ([PkChildProcessJob]::HasTree($Process)) { if ([PkChildProcessJob]::KillTree($Process)) { return $done } return 'Refused' @@ -2197,13 +2103,12 @@ function Stop-PkProgramTree { } function Stop-PkFailedStartTree { - # A failed start's rollback, when the program had started: Start-PkProcessCore - # when a reader can't start, the dispatcher when a -JobStarter throws - # after starting one. Ends it and what it started, running or not, lets - # go of its tree job and process handle, and returns '' or a sentence - # for the start's failure report on what may still be running. + # A failed start's rollback: ends the program and what it started, releases + # its tree job and handle, and returns '' or a sentence for the failure + # report on what may still be running. param([Parameter(Mandatory)][System.Diagnostics.Process]$Process) - # $null once disposed (a custom starter may have): no number then. + # Process.Id reads $null once the Process is disposed (a custom -JobStarter + # may have done that): the sentence then names no process. $id = $Process.Id $stopped = 'Exited' try { $stopped = Stop-PkProgramTree -Process $Process -Leftovers } catch { } # best effort: the failed start is what's reported @@ -2220,14 +2125,19 @@ function Stop-PkFailedStartTree { return '' } +function Write-PkKillTreeWarning { + # A kill whose tree job Windows wouldn't end. Once per session, shared with + # -KillTreeOnExit's warning for the same refusal (Stop-PkExitedJobTree). + param([int]$ProcessId, [string]$Why) + if (-not [PkChildProcessJob]::ClaimKillTreeWarning()) { return } + Write-PkMessage ("[WARNING] Killing process " + $ProcessId + " (" + $Why + ") may have left what it started running: Windows wouldn't end the program's own Job Object. It still ends when PowerShell does. Shown once.") -Level Warn +} + function Stop-PkExitedJobTree { - # -KillTreeOnExit: once a job's program has exited, kills what it left - # running, through Stop-PkProgramTree. Does nothing while it runs, or for - # a .Proc that isn't a Process. A program without a tree job (Windows - # wouldn't give it one, the kit has no Job Object, or a custom starter - # started it) can't be reached: that warns, once per session, and so does - # a tree job Windows won't end. One try only: the dispatcher's poll runs - # this every pass. + # -KillTreeOnExit: once a job's program has exited, ends what it left + # running. No tree job, or one Windows won't end, warns once per session. + # KillTree is cleared first, so each job gets one attempt, though the + # dispatcher's poll calls this every pass. param([hashtable]$Job) $proc = $Job['Proc'] if ($proc -isnot [System.Diagnostics.Process] -or $proc.HasExited -ne $true) { return } @@ -2260,7 +2170,8 @@ function Wait-PkProcess { ) # -1 would wait until the program exits, forever if it never does. if ($TimeoutMs -lt 0) { throw ("Wait-PkProcess: -TimeoutMs must be 0 or more (got " + $TimeoutMs + "). It's how long to wait, in milliseconds; 0 just checks.") } - # Same handle wrapping as Wait-PkRunningJob. + # A WaitHandle borrows the process handle, as in Wait-PkRunningJob; its own + # handle goes back before Dispose, so Dispose doesn't close the process's. $waitHandle = [System.Threading.ManualResetEvent]::new($false) $origHandle = $waitHandle.SafeWaitHandle $waitHandle.SafeWaitHandle = [Microsoft.Win32.SafeHandles.SafeWaitHandle]::new($Process.Handle, $false) @@ -2275,10 +2186,9 @@ function Wait-PkProcess { function Wait-PkRunningJob { # The dispatch loop's pause: until a running program exits, the token is # canceled, or TimeoutMs passes. Exited programs aren't waited on: a - # -JobPollCompleted can keep saying "not done" after the exit, and the - # signaled handle would spin a core. A job with no real process, or past - # the 63 handles WaitAny holds on an STA thread (one is the token), is only - # noticed when the time is up. Same handle wrapping as Wait-PkProcess. + # -JobPollCompleted that still says not done would leave a signaled handle + # that ends every wait at once. WaitAny takes 63 handles on an STA thread, + # so at most 62 programs plus the token. param( [System.Collections.Generic.List[hashtable]]$Jobs, [System.Threading.CancellationToken]$CancelToken, @@ -2304,8 +2214,8 @@ function Wait-PkRunningJob { return } } catch { - # A process that can't be read or waited on (a starter's own, say) is - # the job's -JobPollCompleted to deal with; here it just means sleeping. + # A process that can't be waited on (one a custom -JobStarter made, say) + # is left to -JobPollCompleted; here it only means sleeping. } finally { for ($i = 0; $i -lt $origHandles.Count; $i++) { $waits[$i].SafeWaitHandle = $origHandles[$i] @@ -2316,10 +2226,8 @@ function Wait-PkRunningJob { } function Get-PkProcessDuration { - # How long a 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. $null if it isn't a Process (a custom starter's), - # hasn't exited, or was already disposed (Dispose loses the times). + # How long a program ran, start to exit or kill; $null if it isn't a + # Process, hasn't exited, or was disposed (Dispose loses the times). param($Process) if ($Process -isnot [System.Diagnostics.Process]) { return $null } try { @@ -2363,37 +2271,31 @@ function Complete-PkProcess { param( [Parameter(Mandatory, Position = 0)] [hashtable]$Job, - # Invoke-PkProcessWithTimeout's, Invoke-PkProcessDispatch's and - # Invoke-PkProcessBatch's -StreamTimeoutMs default to the same 15000: - # keep the four in step. + # The same 15000 default as Invoke-PkProcessWithTimeout, + # Invoke-PkProcessDispatch and Invoke-PkProcessBatch: keep the four in + # step. [int]$StreamTimeoutMs = 15000, [switch]$Dispose ) - # -1 would wait until the output closes, however long a leftover child - # holds it. Invoke-PkProcessWithTimeout checks it too, before starting its - # program. + # -1 would wait as long as a leftover child holds the output. + # Invoke-PkProcessWithTimeout checks it before starting its program. if ($StreamTimeoutMs -lt 0) { throw ("Complete-PkProcess: -StreamTimeoutMs must be 0 or more (got " + $StreamTimeoutMs + "). It's how long to wait for the output after the program exits, in milliseconds; 0 doesn't wait.") } $result = [ordered]@{ ExitCode = $null; Stdout = $null; Stderr = $null; StreamTimedOut = $false; StreamError = $null; Duration = $null StdoutDroppedChars = [long]0; StderrDroppedChars = [long]0 } - # -KillTreeOnExit, set by Invoke-PkProcessWithTimeout and the dispatcher, - # whose default poll has done this already. Before the output wait, since - # that's what the leftovers hold up. + # -KillTreeOnExit before waiting for the output: what the program left + # running can hold its pipes open. The dispatcher's default poll may have + # done it already. if ($Job['KillTree']) { Stop-PkExitedJobTree -Job $Job } - # A custom starter's job may have no read tasks, and a read can fail. - # Neither throws: this runs inside JobFinalize, where a throw stops the - # whole dispatcher. + # A custom starter's job may have no read tasks, and a read can fail: + # neither throws, since a throw in -JobFinalize stops the dispatcher. $tasks = [System.Collections.Generic.List[System.Threading.Tasks.Task]]::new() if ($null -ne $Job['StdoutTask']) { $tasks.Add($Job['StdoutTask']) } if ($null -ne $Job['StderrTask']) { $tasks.Add($Job['StderrTask']) } - # The dispatcher's default poll waits for the output alongside the other - # jobs, timing it with OutputWait: only what's left of the wait here. The - # final pass after an abort's wait sets OutputWaitOver: at most 250 ms - # then, enough for a program that exited just before to have its output - # read to the end, short enough for a window close. - # OutputWaitMs is the dispatcher's -StreamTimeoutMs, set with OutputWait, - # and used when the caller passes none of its own. + # After the dispatcher's default poll, only what's left of the wait + # (OutputWait, OutputWaitMs). Once an abort's wait is over (OutputWaitOver), + # at most 250 ms. $limitMs = $StreamTimeoutMs if ($Job['OutputWait'] -is [System.Diagnostics.Stopwatch]) { if (-not $PSBoundParameters.ContainsKey('StreamTimeoutMs') -and $Job['OutputWaitMs'] -is [int]) { $limitMs = $Job['OutputWaitMs'] } @@ -2408,29 +2310,27 @@ function Complete-PkProcess { } catch { $result.StreamError = [string]$_.Exception.Message } - # The failed read's own reason, rather than WaitAll's wrapper. Read - # from the tasks: WaitAll throws only once every task has finished, - # so it says nothing of a read that failed while the other stream was - # still held open. + # The failed read's own reason, read from each task: WaitAll throws only + # once both have finished. foreach ($task in $tasks) { if ($task.IsFaulted) { $result.StreamError = [string]$task.Exception.GetBaseException().Message; break } } } - # A stream still open at the timeout (a program the job's own started can - # hold it open) gives the text that arrived before it, each stream on its - # own; its read carries on in the background, dropping what arrives after - # (Snapshot keeps the text it returns). + # A stream still open at the timeout gives what arrived before it; its read + # goes on in the background, and Snapshot keeps the text it returns. $ranToCompletion = [System.Threading.Tasks.TaskStatus]::RanToCompletion foreach ($stream in 'Stdout', 'Stderr') { $task = $Job[$stream + 'Task'] if ($null -eq $task) { continue } if ($task.Status -eq $ranToCompletion) { $result[$stream] = $task.Result } elseif (-not $task.IsCompleted -and $task -is [PkStreamReadTask]) { $result[$stream] = $task.Snapshot() } - # After the text is taken, which fixes the count. + # Read DroppedChars after taking the text: the count is fixed once the + # text is. if ($task -is [PkStreamReadTask]) { $result[$stream + 'DroppedChars'] = $task.DroppedChars } } $result.ExitCode = $Job['Proc'].ExitCode - # The program's end, not the output's: before Dispose, which loses it. + # The program's run time, not the output's: read before Dispose, which loses + # the process times. $result.Duration = Get-PkProcessDuration -Process $Job['Proc'] # The program has exited: its tree job's handle can go. Anything it left # running stays in the kit's job. @@ -2486,9 +2386,8 @@ function Invoke-PkProcessWithTimeout { [string]$FilePath, $Arguments = "", [int]$TimeoutMs = 60000, - # Complete-PkProcess's, Invoke-PkProcessDispatch's and - # Invoke-PkProcessBatch's -StreamTimeoutMs default to the same 15000: - # keep the four in step. + # The same 15000 default as Complete-PkProcess, Invoke-PkProcessDispatch + # and Invoke-PkProcessBatch: keep the four in step. [int]$StreamTimeoutMs = 15000, [string]$WorkingDirectory = "", $OutputEncoding = $null, @@ -2521,22 +2420,23 @@ function Invoke-PkProcessWithTimeout { if (-not $exited -and -not $IgnoreAbort -and ((Test-PkAbortSignal) -or (Test-PkCancelRequested))) { $stopWhy = "was stopped because the run is being aborted"; break } } if (-not $exited) { - try { $null = Stop-PkProgramTree -Process $job['Proc'] } catch { } # best effort - the throw below still reports why - # Let the output reads finish (the kill closes their pipes) before - # the process is disposed under them. Bounded; a read error doesn't - # matter here. - try { $null = [System.Threading.Tasks.Task]::WaitAll(@($job['StdoutTask'], $job['StderrTask']), 500) } catch { } + $stopped = 'Killed' + try { $stopped = Stop-PkProgramTree -Process $job['Proc'] } catch { } # best effort - the throw below still reports why + if ($stopped -eq 'Refused') { Write-PkKillTreeWarning -ProcessId $job['Proc'].Id -Why $(if ($remainingMs -le 0) { 'its time limit' } else { 'an abort' }) } + # Let the reads finish (the kill closes their pipes) before the + # process is disposed. Bounded. + try { $null = [System.Threading.Tasks.Task]::WaitAll(@($job['StdoutTask'], $job['StderrTask']), 500) } catch { } # a read error doesn't matter: the throw below reports the kill + if ($stopped -eq 'NotKilled' -or $stopped -eq 'Unknown') { throw ("'" + $FilePath + "' " + $stopWhy + ", and couldn't be killed: process " + $job['Proc'].Id + " may still be running") } throw ("'" + $FilePath + "' " + $stopWhy + " - killed") } return Complete-PkProcess -Job $job -StreamTimeoutMs $StreamTimeoutMs } finally { - # The force-stop's steps, before the process object goes: the program - # if it's still running (only when PowerShell is stopping the script, - # which skips catch blocks, not finally ones), what it left if it - # exited before Complete-PkProcess with -KillTreeOnExit, and its tree - # job's handle (a kill leaves it open). + # Before the Process is disposed: kill the program if it's still running + # (only when PowerShell is stopping the script, which skips catch + # blocks), end -KillTreeOnExit's leftovers, and release the tree job's + # handle. $stopJobs = [System.Collections.Generic.List[hashtable]]::new(); $stopJobs.Add($job) - Stop-PkJobProcess -Jobs $stopJobs + Stop-PkJobProcess -Jobs $stopJobs -Why 'a stopped script' $job['Proc'].Dispose() } } @@ -2658,17 +2558,19 @@ function Invoke-PkProcessDispatch { [int]$MaxQueueAhead = 3, [scriptblock]$GroupReleaseCheck = $null, [double]$TimeoutSeconds = 0, - # Complete-PkProcess's, Invoke-PkProcessWithTimeout's and - # Invoke-PkProcessBatch's -StreamTimeoutMs default to the same 15000: - # keep the four in step. + # The same 15000 default as Complete-PkProcess, + # Invoke-PkProcessWithTimeout and Invoke-PkProcessBatch: keep the four + # in step. [int]$StreamTimeoutMs = 15000, [int]$MaxOutputChars = 0, [switch]$InheritStdin, [switch]$KillTreeOnExit ) - # pk-prefixed, parameters included: inside a worker runspace the kit isn't - # a module, so a callback without .GetNewClosure() sees this frame's - # variables. Same in Add-PkDispatchGroupJob, Invoke-PkProcessDispatchCore, Invoke-PkProcessBatch. + # Variables are pk-prefixed, parameters included: in a worker the kit is + # plain copied functions, not a module, so a callback without + # .GetNewClosure() can read this function's variables by name. The same in + # Add-PkDispatchGroupJob, Invoke-PkProcessDispatchCore and + # Invoke-PkProcessBatch. $pkGroupProvider = $GroupProvider $pkJobBuilder = $JobBuilder $pkJobStarter = $JobStarter @@ -2698,12 +2600,9 @@ function Invoke-PkProcessDispatch { $pkMaxConcurrent = $pkMaxConcurrentInt } if ($pkMaxQueueAhead -lt 1) { throw "Invoke-PkProcessDispatch: -MaxQueueAhead must be at least 1." } - # Invoke-PkProcessBatch makes the same -MaxConcurrent, -TimeoutSeconds, - # -AbortTimeoutSeconds, -StreamTimeoutMs and -MaxOutputChars checks, so its - # errors name the batch: keep the two in step. Start-PkProcess and - # Invoke-PkProcessWithTimeout check -MaxOutputChars the same way. NaN and - # +Infinity pass a `-lt 0` test and would mean no limit. A job's own - # TimeoutSeconds key follows the same rule (Get-PkJobTimeLimit). + # The same checks as Invoke-PkProcessBatch's (keep the two in step), and + # -MaxOutputChars as Start-PkProcess's. NaN and +Infinity pass `-lt 0` and + # would mean no limit. if ([double]::IsNaN($pkTimeoutSeconds) -or [double]::IsInfinity($pkTimeoutSeconds) -or $pkTimeoutSeconds -lt 0) { throw ("Invoke-PkProcessDispatch: -TimeoutSeconds must be a number of seconds, 0 (no limit) or more (got " + $pkTimeoutSeconds + ").") } @@ -2722,8 +2621,8 @@ function Invoke-PkProcessDispatch { $pkJobStarter = { param($pkJob) $pkStarted = Start-PkProcessCore -CallerState $pkCallerState -FilePath $pkJob['FilePath'] -Arguments $pkJob['Arguments'] -WorkingDirectory ([string]$pkJob['WorkingDirectory']) -OutputEncoding $pkJob['OutputEncoding'] -MaxOutputChars (Get-PkJobOutputLimit -Job $pkJob -DefaultMaxOutputChars $pkMaxOutputChars) -InheritStdin:(Get-PkJobSwitch -Job $pkJob -Key 'InheritStdin' -Default $pkInheritStdin) - # Start-PkProcessCore's four keys; the batch's starter copies them - # too: a new key goes in all three. + # Start-PkProcessCore's four keys; Invoke-PkProcessBatch's starter + # copies them too: a new key goes in all three places. $pkJob['Proc'] = $pkStarted.Proc; $pkJob['StdoutTask'] = $pkStarted.StdoutTask; $pkJob['StderrTask'] = $pkStarted.StderrTask $pkJob['Stopwatch'] = $pkStarted.Stopwatch return $pkJob @@ -2734,18 +2633,11 @@ function Invoke-PkProcessDispatch { if ($null -eq $pkJobPollCompleted) { # The closure below can't see the module's private functions. $pkStopExitedJobTree = ${function:Stop-PkExitedJobTree} - # Done once the program has exited and its output has been read, so - # Complete-PkProcess in -JobFinalize has nothing to wait for: waiting - # there would stall the whole loop. A job whose output a leftover - # program holds open keeps its slot until the reads end or - # -StreamTimeoutMs passes, timed by OutputWait. The limit goes on the - # job as OutputWaitMs, so a Complete-PkProcess given no -StreamTimeoutMs - # of its own waits only what's left of it (nothing). After an abort's - # wait the final pass sets OutputWaitOver: it takes what has arrived. - # KillTree (-KillTreeOnExit) kills what the program left running first, - # so nothing is left to hold the output. - # A closure, so it carries this call's $pkStreamTimeoutMs itself - # rather than finding it by dynamic scope. + # Done once the program has exited and its output is read, so + # Complete-PkProcess in -JobFinalize doesn't stall the loop. If + # something the program left running holds the output open, the job + # keeps its slot up to -StreamTimeoutMs (timed by its OutputWait and + # OutputWaitMs keys). $pkJobPollCompleted = { param($pkJob) if (-not $pkJob['Proc'].HasExited) { return $false } @@ -2772,9 +2664,8 @@ function Invoke-PkProcessDispatch { $pkCancelToken = $pkOwnCts.Token } } else { - # Nothing cancels the caller's token on Ctrl+C, so run on a linked - # source an abort does cancel. In a worker it also follows the run's - # token. + # Nothing cancels the caller's token on Ctrl+C: run on a linked source + # an abort does cancel (and, in a worker, the run's token). $pkLinkTokens = [System.Collections.Generic.List[System.Threading.CancellationToken]]::new() $pkLinkTokens.Add($pkCancelToken) if ($null -ne $global:PkCancelToken) { $pkLinkTokens.Add($global:PkCancelToken) } @@ -2799,11 +2690,9 @@ function Invoke-PkProcessDispatch { } function Add-PkDispatchGroupJob { - # Builds one group's jobs, tags them with the group and queues them; - # returns how many. Its own function so the group's job list dies with - # this call: in the dispatch loop's frame it kept every finished job's - # output alive for the whole run, and nulling the variables there didn't - # release it. + # Builds one group's jobs, tags and queues them; returns how many. A + # function of its own so the job list goes with the call instead of keeping + # finished jobs' output alive in the loop's frame. param( [Parameter(Mandatory)][scriptblock]$JobBuilder, $GroupInfo, @@ -2811,9 +2700,11 @@ function Add-PkDispatchGroupJob { [Parameter(Mandatory)][System.Collections.Generic.Queue[hashtable]]$Pending, [hashtable]$CallbackContext ) - # pk-prefixed, parameters included: inside a worker runspace the kit isn't - # a module, so a callback without .GetNewClosure() sees this frame's - # variables. Same in Invoke-PkProcessDispatch, Invoke-PkProcessDispatchCore, Invoke-PkProcessBatch. + # Variables are pk-prefixed, parameters included: in a worker the kit is + # plain copied functions, not a module, so a callback without + # .GetNewClosure() can read this function's variables by name. The same in + # Invoke-PkProcessDispatch, Invoke-PkProcessDispatchCore and + # Invoke-PkProcessBatch. $pkJobBuilder = $JobBuilder $pkGroupInfo = $GroupInfo $pkGroupKey = $GroupKey @@ -2821,7 +2712,7 @@ function Add-PkDispatchGroupJob { $pkCallbackContext = $CallbackContext Remove-Variable -Name JobBuilder, GroupInfo, GroupKey, Pending, CallbackContext -Scope Local $pkRawJobs = Invoke-PkCallback -PkCallback $pkJobBuilder -PkArgs @(,$pkGroupInfo) -PkName '-JobBuilder' -PkContext $pkCallbackContext - # Assigned in each branch, not `$x = if ... else ...`: captured that way, + # Assigned in each branch, not as `$x = if ... else ...`: captured that way, # a single hashtable is enumerated into its key/value pairs. if ($null -eq $pkRawJobs) { $pkRawJobList = @() } else { $pkRawJobList = @($pkRawJobs) } # Keep only real job hashtables: a builder that lets a stray @@ -2859,9 +2750,11 @@ function Invoke-PkProcessDispatchCore { [double]$TimeoutSeconds = 0, [bool]$KillTreeOnExit = $false ) - # pk-prefixed, parameters included: inside a worker runspace the kit isn't - # a module, so a callback without .GetNewClosure() sees this frame's - # variables. Same in Add-PkDispatchGroupJob, Invoke-PkProcessDispatch, Invoke-PkProcessBatch. + # Variables are pk-prefixed, parameters included: in a worker the kit is + # plain copied functions, not a module, so a callback without + # .GetNewClosure() can read this function's variables by name. The same in + # Add-PkDispatchGroupJob, Invoke-PkProcessDispatch and + # Invoke-PkProcessBatch. $pkGroupProvider = $GroupProvider $pkJobBuilder = $JobBuilder $pkJobStarter = $JobStarter @@ -2901,9 +2794,8 @@ function Invoke-PkProcessDispatchCore { # The job -JobStarter is working on: not in $pkRunning yet, but it may # already have a program and a shared slot. $pkStarting = $null - # The job -JobFinalize is working on. It has finished, so if -JobFinalize - # throws, the teardown skips -JobAbortCleanup for it (that's for jobs it - # kills) and only gives back its slot. + # The job -JobFinalize is on: if it throws, the teardown gives back the slot + # but skips -JobAbortCleanup, which is for jobs it kills. $pkFinalizing = $null # Invoke-PkCallback's -PkContext: callbacks that used continue/break are # warned about once each, under this prefix. @@ -2911,19 +2803,17 @@ function Invoke-PkProcessDispatchCore { # -GroupProvider outputting several values in one call is warned about # once per run. $pkProviderWarned = $false - # Teardown is in a finally, guarded by this flag: when PowerShell stops - # the script (Ctrl+C outside Invoke-PkRun, the runspace engine - # force-stopping a worker), catch blocks are skipped. + # The teardown is in a finally, since a stop (Ctrl+C outside Invoke-PkRun, a + # force-stopped worker) skips catch blocks; this flag says the loop ended + # normally, so the finally has nothing to tear down. $pkLoopDone = $false try { while ((-not $pkCancelToken.IsCancellationRequested) -and ` (-not $pkProviderExhausted -or $pkActiveGroupCount -gt 0 -or $pkPending.Count -gt 0 -or $pkRunning.Count -gt 0)) { - # An abort only raises a flag; Test-PkAbortSignal is what cancels the - # token. Checked first, so an abort raised since the last pass (by - # -JobFinalize, -GroupCompleteCallback, Ctrl+C during the wait) asks - # -GroupProvider for nothing more. The flag read is cheaper than a - # function call. + # The abort flag, before asking for more: an abort raises it, and + # Test-PkAbortSignal cancels the token. A field read is cheaper than the + # call. if ([PkConsoleCtrl]::AbortRequested) { $null = Test-PkAbortSignal } for ($pkH = $pkHeldGroups.Count - 1; $pkH -ge 0; $pkH--) { @@ -2937,21 +2827,17 @@ function Invoke-PkProcessDispatchCore { } } - # The abort flag per group too, so an abort raised by -GroupProvider, - # -JobBuilder, -GroupReleaseCheck or -GroupCompleteCallback asks for - # no more groups on this pass. + # The flag per group too, so an abort from a group callback asks for no + # more groups this pass. while ((-not $pkProviderExhausted) -and $pkActiveGroupCount -lt $pkMaxQueueAhead -and (-not $pkCancelToken.IsCancellationRequested) -and (-not [PkConsoleCtrl]::AbortRequested)) { # Invoke-PkCallback inlined, to count the values the provider - # output. Collected by plain assignment, `return ,@('a', 'b')` (one - # value, a list) and two values output separately are the same - # array, and only the second is a mistake. @() keeps one value per - # element, each as it was output (a ForEach-Object or a .NET - # collection's Add() would change a value's PSObject wrapper). + # outputs: @() collects each one as output, and `return ,@('a', + # 'b')` counts as one value. $pkCbDone = $false $pkProvided = @(do { & $pkGroupProvider; $pkCbDone = $true } while ($false)) if (-not $pkCbDone) { Write-PkCallbackLoopWarning -PkName '-GroupProvider' -PkContext $pkCallbackContext } - # The group is what assignment gives: one value as itself, several - # as one array (unchanged; it only gets a warning now). + # One value is the group itself; several become one array, the + # group, with a warning once per run. $pkGroupInfo = $null if ($pkProvided.Count -eq 1) { $pkGroupInfo = $pkProvided[0] } elseif ($pkProvided.Count -gt 1) { @@ -2962,12 +2848,9 @@ function Invoke-PkProcessDispatchCore { Write-PkMessage ("ProcessDispatch: -GroupProvider output " + $pkProvided.Count + " values in one call, taken together as one group. Output one value per call: `$null = ... discards a value you don't want (an ArrayList.Add index), and return ,`$list returns a list as one group. Shown once per run.") -Level Warn } } - # A value the provider leaks before `return $null` (an ArrayList.Add - # index) arrives as @(, $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. + # Output ending in $null is the end: a leaked value before `return + # $null` arrives as @(, $null), and asking again would never + # stop. 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 @@ -3000,26 +2883,25 @@ function Invoke-PkProcessDispatchCore { if ([PkConsoleCtrl]::AbortRequested) { $null = Test-PkAbortSignal } } - # The abort flag per job too, so a Ctrl+C or a -JobStarter's abort - # starts no more on this pass; before the shared budget's Wait(0), - # which would take a slot. + # The flag per job too, so a Ctrl+C or a -JobStarter's abort starts no + # more this pass; before the shared budget's Wait(0), which takes a + # slot. while ($pkPending.Count -gt 0 -and (-not $pkCancelToken.IsCancellationRequested) -and (-not [PkConsoleCtrl]::AbortRequested) -and ` $(if ($pkIsSharedBudget) { $pkMaxConcurrent.Wait(0) } else { $pkRunning.Count -lt $pkMaxConcurrent })) { $pkJob = $pkPending.Dequeue() try { - # The running job is always the caller's own object: a starter - # that forgets to return it, or leaks other output, would - # otherwise leave something un-pollable running. A different - # hashtable it outputs (a bare Start-PkProcess result) has its - # fields folded in. A job JobFinalize re-queued still carries - # its old, disposed process: cleared first. + # The running job is always the caller's own object; a hashtable + # the starter outputs has its fields folded in. A re-queued job + # still has its disposed process: cleared first. if ($pkJob['SlotReleased']) { $pkJob['Proc'] = $null; $pkJob['StdoutTask'] = $null; $pkJob['StderrTask'] = $null; $pkJob['Stopwatch'] = $null $pkJob['OutputWait'] = $null; $pkJob['OutputWaitOver'] = $null; $pkJob['OutputWaitMs'] = $null } $pkJob['SlotReleased'] = $false $pkStarting = $pkJob - # Before starting, so a bad key never leaves a program running. + # The job's own TimeoutSeconds and KillTreeOnExit keys are + # checked before the start, so a bad one never leaves a program + # running. $pkStartFailureText = "ProcessDispatch: a job couldn't start: " $pkJob['TimeLimit'] = Get-PkJobTimeLimit -Job $pkJob -DefaultTimeoutSeconds $pkTimeoutSeconds # The null test saves the call, which runs per job. @@ -3043,16 +2925,15 @@ function Invoke-PkProcessDispatchCore { $pkRunning.Add($pkJob) $pkStarting = $null } catch { - # Release before reporting: this job isn't in $pkRunning, so if - # reporting threw, nothing would release its slot. A program the - # starter started before throwing is killed first: nothing else - # tracks it. $pkStarting is cleared before the release, so the - # teardown can't release the slot again. + # Release before reporting, since this job isn't in $pkRunning; + # its program, if started, is killed first. $pkStarting is + # cleared first, so the teardown can't release the slot again. $pkTreeNote = '' if ($pkJob['Proc'] -is [System.Diagnostics.Process]) { $pkTreeNote = Stop-PkFailedStartTree -Process $pkJob['Proc'] } $pkStarting = $null if ($pkIsSharedBudget) { $null = $pkMaxConcurrent.Release() } - # The batch sets this key on its own jobs: it reports start failures itself. + # Invoke-PkProcessBatch sets StartFailureReported on its jobs + # and reports their start failures itself. if (-not $pkJob['StartFailureReported']) { $pkFailure = $pkStartFailureText + $_ if ($pkTreeNote) { $pkFailure = $pkFailure.TrimEnd().TrimEnd('.') + '. ' + $pkTreeNote } @@ -3076,8 +2957,8 @@ function Invoke-PkProcessDispatchCore { } # ---- BLOCK: main dispatch loop's poll pass ---- - # Same poll/finalize/completion sequence as the graceful-wait loop - # and the mandatory final pass below - keep all three in sync. + # The same as the graceful-wait loop and the final pass below: keep all + # three in sync. $pkStillRunning = [System.Collections.Generic.List[hashtable]]::new() foreach ($pkJob in $pkRunning) { if ($pkJob['TimeLimit'] -gt 0) { Stop-PkTimedOutJob -Job $pkJob } @@ -3094,15 +2975,13 @@ function Invoke-PkProcessDispatchCore { $null = do { & $pkJobFinalize $pkJob $pkPending; $pkCbDone = $true } while ($false) $pkFinalizing = $null if (-not $pkCbDone) { Write-PkCallbackLoopWarning -PkName '-JobFinalize' -PkContext $pkCallbackContext } - # Marked done first: a stop landing after the Release or the - # Dispose would otherwise have the teardown release the slot a - # second time and treat the disposed job as still running. + # Marked done first: a stop after the Release or Dispose would + # otherwise release the slot again. $pkJob['SlotReleased'] = $true if ($pkIsSharedBudget) { $null = $pkMaxConcurrent.Release() } try { if ($pkJob['Proc']) { $pkJob['Proc'].Dispose() } } catch { } # a failed Dispose can't affect the result already taken - # Whatever JobFinalize queued (a retry, follow-ups) joins its group - # here, read off the queue rather than a returned flag. Only when the - # queue grew: walking it for every job is slow on a large batch. + # What JobFinalize queued joins its group here; only when the + # queue grew, since walking it is slow. if ($pkPending.Count -gt $pkPendingBefore) { $pkQueuedIndex = 0 foreach ($pkQueued in $pkPending) { @@ -3132,10 +3011,10 @@ function Invoke-PkProcessDispatchCore { $pkStillRunning.Add($pkJob) } } - # A finished job freed a slot: refill it right away. Not on a shared - # budget, where a sibling dispatcher only looks every 50 ms and - # refilling at once starved it. The 50 ms cap is how soon an abort or a - # sibling's released slot is noticed: neither wakes the wait. + # A freed slot is refilled at once, except with a shared budget (a + # SemaphoreSlim other dispatchers also use), where they look every 50 ms + # and refilling at once would starve them. The 50 ms cap is how soon an + # abort or another dispatcher's freed slot is noticed. $pkAnyFinished = ($pkStillRunning.Count -lt $pkRunning.Count) $pkRunning = $pkStillRunning @@ -3164,9 +3043,8 @@ function Invoke-PkProcessDispatchCore { $pkJob['SlotReleased'] = $true # first: see the main poll pass if ($pkIsSharedBudget) { $null = $pkMaxConcurrent.Release() } try { if ($pkJob['Proc']) { $pkJob['Proc'].Dispose() } } catch { } # a failed Dispose can't affect the result already taken - # Whatever JobFinalize queued (a retry, follow-ups) joins its group - # here, read off the queue rather than a returned flag. Only when the - # queue grew: walking it for every job is slow on a large batch. + # What JobFinalize queued joins its group here; only when + # the queue grew, since walking it is slow. if ($pkPending.Count -gt $pkPendingBefore) { $pkQueuedIndex = 0 foreach ($pkQueued in $pkPending) { @@ -3200,16 +3078,11 @@ function Invoke-PkProcessDispatchCore { if ($pkRunning.Count -gt 0) { [System.Threading.Thread]::Sleep(250) } } - # ---- BLOCK: final pass ---- - # A window close can end the loop above before any poll, and a job can - # finish just before the deadline: a finished job mustn't count as - # force-stopped. Keep in sync with the two blocks above, minus the time - # limit (whatever is left is force-stopped just below). + # A finished job mustn't count as force-stopped. The same steps as the + # two blocks above, without the time-limit check. if ($pkRunning.Count -gt 0) { - # The wait is over: a job whose program has finished, and that is - # only waiting for its output, takes what has arrived (the default - # poll and Complete-PkProcess read this) rather than being - # force-stopped. + # The wait is over: a job only waiting for its output takes what has + # arrived instead of being force-stopped. foreach ($pkJob in $pkRunning) { $pkJob['OutputWaitOver'] = $true } $pkStillWaiting = [System.Collections.Generic.List[hashtable]]::new() foreach ($pkJob in $pkRunning) { @@ -3227,9 +3100,8 @@ function Invoke-PkProcessDispatchCore { $pkJob['SlotReleased'] = $true # first: see the main poll pass if ($pkIsSharedBudget) { $null = $pkMaxConcurrent.Release() } try { if ($pkJob['Proc']) { $pkJob['Proc'].Dispose() } } catch { } # a failed Dispose can't affect the result already taken - # Whatever JobFinalize queued (a retry, follow-ups) joins its group - # here, read off the queue rather than a returned flag. Only when the - # queue grew: walking it for every job is slow on a large batch. + # What JobFinalize queued joins its group here; only when + # the queue grew, since walking it is slow. if ($pkPending.Count -gt $pkPendingBefore) { $pkQueuedIndex = 0 foreach ($pkQueued in $pkPending) { @@ -3279,11 +3151,9 @@ function Invoke-PkProcessDispatchCore { $pkLoopDone = $true } finally { if (-not $pkLoopDone) { - # Best-effort teardown after an error or a stop (an error carries - # on up by itself). Jobs with SlotReleased set are already done: - # their slot is released and their process disposed, or both are - # about to be. Same per-job steps as the force-stop above; keep the - # two in step. + # Best-effort teardown after an error or a stop. Jobs with + # SlotReleased are done already. The same per-job steps as the + # 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) } @@ -3300,9 +3170,8 @@ function Invoke-PkProcessDispatchCore { } } - # Jobs still pending here were never started (only reachable via - # cancellation). Clean them up and count them off, or their group could - # never be reported. + # Jobs never started (cancellation only): clean them up and count them off, + # or their group is never reported. if ($pkPending.Count -gt 0) { foreach ($pkJob in $pkPending) { try { $null = Invoke-PkCallback -PkCallback $pkJobAbortCleanup -PkArgs @(,$pkJob) -PkName '-JobAbortCleanup' -PkContext $pkCallbackContext } catch { } # one job's failed cleanup mustn't skip the others' @@ -3315,9 +3184,9 @@ function Invoke-PkProcessDispatchCore { $pkDispatchResult.Aborted = $pkCancelToken.IsCancellationRequested foreach ($pkState in $pkGroupStates.Values) { if (-not $pkState.Completed) { - # An aborted group still gets its callback: it's where the caller - # credits the jobs that did finish. Swallowed, so one failing - # callback doesn't cost the other groups their results. + # An aborted group still gets -GroupCompleteCallback, where the + # caller can count the jobs that finished. A throw there is + # swallowed, so the other groups still get theirs. try { $null = Invoke-PkCallback -PkCallback $pkGroupCompleteCallback -PkArgs @(,$pkState.GroupInfo) -PkName '-GroupCompleteCallback' -PkContext $pkCallbackContext } catch { } $pkState.Completed = $true $pkGroupResults.Add([pscustomobject][ordered]@{ GroupInfo = $pkState.GroupInfo; Completed = $false; Aborted = $true }) @@ -3328,10 +3197,9 @@ function Invoke-PkProcessDispatchCore { } function New-PkBatchResult { - # One Invoke-PkProcessBatch result, the same shape however the command - # ended: ran (-Completed is Complete-PkProcess's object), couldn't start - # (-StartError), or stopped by an abort (-Aborted; -Process is its program, - # if it was started, for how long it ran). + # One batch result, the same shape however the command ended: ran + # (-Completed), couldn't start (-StartError) or was stopped by an abort + # (-Aborted, with -Process for its run time). param( [hashtable]$Command, $Completed = $null, @@ -3355,16 +3223,19 @@ function New-PkBatchResult { } function Get-PkStartFailureCause { - # Why a command couldn't start, for telling repeats apart: Windows' own text - # for the error code where there is one, because on 7 the exception's text - # for one failure differs by working directory. + # Why a command couldn't start, for telling repeats apart: Windows' text for + # the error code, since on 7 the exception's text varies by working + # directory. param([Parameter(Mandatory)][System.Management.Automation.ErrorRecord]$StartError) + $innermost = $StartError.Exception for ($e = $StartError.Exception; $null -ne $e; $e = $e.InnerException) { if ($e -is [System.ComponentModel.Win32Exception]) { return [System.ComponentModel.Win32Exception]::new($e.NativeErrorCode).Message.TrimEnd('.') } + $innermost = $e } - return [string]$StartError + # The innermost message: an outer one can name the process. + return $innermost.Message } function Invoke-PkProcessBatch { @@ -3433,17 +3304,19 @@ function Invoke-PkProcessBatch { [int]$AbortTimeoutSeconds = 60, [double]$TimeoutSeconds = 0, $OutputEncoding = $null, - # Complete-PkProcess's, Invoke-PkProcessWithTimeout's and - # Invoke-PkProcessDispatch's -StreamTimeoutMs default to the same - # 15000: keep the four in step. + # The same 15000 default as Complete-PkProcess, + # Invoke-PkProcessWithTimeout and Invoke-PkProcessDispatch: keep the + # four in step. [int]$StreamTimeoutMs = 15000, [int]$MaxOutputChars = 0, [switch]$InheritStdin, [switch]$KillTreeOnExit ) - # pk-prefixed, parameters included: inside a worker runspace the kit isn't - # a module, so a callback without .GetNewClosure() sees this frame's - # variables. Same in Add-PkDispatchGroupJob, Invoke-PkProcessDispatch, Invoke-PkProcessDispatchCore. + # Variables are pk-prefixed, parameters included: in a worker the kit is + # plain copied functions, not a module, so a callback without + # .GetNewClosure() can read this function's variables by name. The same in + # Add-PkDispatchGroupJob, Invoke-PkProcessDispatch and + # Invoke-PkProcessDispatchCore. $pkCommands = $Commands $pkMaxConcurrent = $MaxConcurrent $pkOnComplete = $OnComplete @@ -3458,9 +3331,8 @@ function Invoke-PkProcessBatch { # Checked once here, so a bad name fails the call instead of every command. $null = Resolve-PkEncoding -Encoding $pkOutputEncoding - # Invoke-PkProcessDispatch makes the same five checks; these name the - # batch. Keep the two in step. Get-PkJobTimeLimit checks a job's own - # TimeoutSeconds key by the same rule. + # The same checks as Invoke-PkProcessDispatch's, naming the batch: keep the + # two in step. if ($pkMaxConcurrent -lt 1) { throw ("Invoke-PkProcessBatch: -MaxConcurrent must be at least 1 (got " + $pkMaxConcurrent + ").") } if ([double]::IsNaN($pkTimeoutSeconds) -or [double]::IsInfinity($pkTimeoutSeconds) -or $pkTimeoutSeconds -lt 0) { throw ("Invoke-PkProcessBatch: -TimeoutSeconds must be a number of seconds, 0 (no limit) or more (got " + $pkTimeoutSeconds + ").") @@ -3477,9 +3349,9 @@ function Invoke-PkProcessBatch { $pkResults = [System.Collections.Generic.List[object]]::new() $pkState = @{ Given = $false } - # The closures below can't see the module's functions (a .GetNewClosure() - # block only sees global ones), so take these along: the public ones too, - # which aren't global when the kit is loaded for one module only. + # A .GetNewClosure() block can only call global functions, and the kit's + # aren't global when it's imported into another module, so the closures take + # these along, public ones included. $pkNewBatchResult = ${function:New-PkBatchResult} $pkStartProcessCore = ${function:Start-PkProcessCore} $pkGetJobTimeLimit = ${function:Get-PkJobTimeLimit} @@ -3548,8 +3420,8 @@ function Invoke-PkProcessBatch { & $pkReportStartFailure $pkJob['Command'] $_ throw } - # Start-PkProcessCore's four keys; the dispatcher's default starter - # copies them too: a new key goes in all three. + # Start-PkProcessCore's four keys; Invoke-PkProcessDispatch's default + # starter copies them too: a new key goes in all three places. $pkJob['Proc'] = $pkStarted.Proc; $pkJob['StdoutTask'] = $pkStarted.StdoutTask; $pkJob['StderrTask'] = $pkStarted.StderrTask $pkJob['Stopwatch'] = $pkStarted.Stopwatch return $pkJob @@ -3609,13 +3481,12 @@ function Get-PkWorkerSafeFunctionName { return @('Write-PkMessage', 'Test-PkAbortSignal', 'Test-PkCancelRequested', 'Initialize-PkChildProcessJob', 'Stop-PkProcessTree', 'Stop-PkProcessTreeCore', 'Split-PkTaskkillArgumentList', 'Stop-PkJobProcess', 'Get-PkProcessDuration', 'Resolve-PkEncoding', 'Start-PkProcess', 'Wait-PkProcess', 'Wait-PkRunningJob', 'Complete-PkProcess', 'Invoke-PkProcessWithTimeout', 'Invoke-PkProcessDispatch', 'Invoke-PkProcessDispatchCore', 'Invoke-PkProcessBatch', - 'Register-PkCancellationSource', 'Unregister-PkCancellationSource', 'New-PkBatchResult', 'Get-PkJobOutputLimit', 'Get-PkJobSwitch', 'Stop-PkExitedJobTree', 'Stop-PkProgramTree', 'Stop-PkFailedStartTree', 'ConvertTo-PkArgumentString', 'Get-PkForceStopReason', 'Resolve-PkFileSystemPath', 'Add-PkDispatchGroupJob', 'Start-PkProcessCore', 'Get-PkJobTimeLimit', 'Stop-PkTimedOutJob', 'Get-PkStartFailureCause', 'Resolve-PkArgumentList', 'Invoke-PkCallback', 'Write-PkCallbackLoopWarning', 'ConvertTo-PkArgumentStringCore') + 'Register-PkCancellationSource', 'Unregister-PkCancellationSource', 'New-PkBatchResult', 'Get-PkJobOutputLimit', 'Get-PkJobSwitch', 'Stop-PkExitedJobTree', 'Stop-PkProgramTree', 'Stop-PkFailedStartTree', 'Write-PkKillTreeWarning', 'ConvertTo-PkArgumentString', 'Get-PkForceStopReason', 'Resolve-PkFileSystemPath', 'Add-PkDispatchGroupJob', 'Start-PkProcessCore', 'Get-PkJobTimeLimit', 'Stop-PkTimedOutJob', 'Get-PkStartFailureCause', 'Resolve-PkArgumentList', 'Invoke-PkCallback', 'Write-PkCallbackLoopWarning', 'ConvertTo-PkArgumentStringCore') } function Get-PkHandlerParamCount { - # How many parameters a callback declares, or -1 if it has no param() - # block (it takes whatever it's given, in $args). Invoke-PkRunspaceBatch - # reads a -WorkerScript's parameters the same way. + # How many parameters a callback declares, or -1 with no param() block. + # Invoke-PkRunspaceBatch reads a -WorkerScript the same way. param([Parameter(Mandatory)][scriptblock]$Callback) $ast = $Callback.Ast if ($ast -is [System.Management.Automation.Language.FunctionDefinitionAst]) { @@ -3642,9 +3513,8 @@ function Add-PkCrashedJob { Invoke-PkMessageHandler -Level Error -Message ("Error collecting runspace result" + $PkWhen + ": " + $PkError) if ($null -eq $PkHandler) { return } try { - # The job only goes to a handler that has room for it: a one-parameter - # handler with [CmdletBinding()] or [Parameter()] would throw on a - # second argument. + # The job only goes to a handler with room for it: a one-parameter + # advanced function would throw on a second argument. $pkParamCount = Get-PkHandlerParamCount -Callback $PkHandler $pkHandlerArgs = @($PkError, $PkJob) if ($pkParamCount -ne -1 -and $pkParamCount -lt 2) { $pkHandlerArgs = @(,$PkError) } @@ -3656,10 +3526,9 @@ function Add-PkCrashedJob { } function Add-PkJobError { - # A finished worker's non-terminating errors: print each and record it - # with its job. Shared by the main loop and the abort drain. Called for a - # crashed worker too: its error stream holds only the errors before the - # one that stopped it. + # Prints a finished worker's non-terminating errors and records each with + # its job; for a crashed one, the errors before the crash. Shared by the + # main loop and the abort drain. param( [Parameter(Mandatory)][System.Collections.Specialized.OrderedDictionary]$PkOutcome, [hashtable]$PkJob, @@ -3673,9 +3542,8 @@ function Add-PkJobError { } function Receive-PkCompletedHandle { - # The abort drain's collection pass: each finished worker's errors, crash - # and results, as Invoke-PkRunspaceBatch's main loop does it. Returns the - # workers still running. + # The abort drain's collection pass, as Invoke-PkRunspaceBatch's main loop + # does it. Returns the workers still running. param( [System.Collections.Generic.List[hashtable]]$Handles, [scriptblock]$ResultHandler, @@ -3715,10 +3583,10 @@ function Receive-PkCompletedHandle { } function Invoke-PkGracefulDrain { - # After an abort: give running workers $TimeoutSeconds to finish, collect - # what they return, force-stop the rest. Leaves the native handler thread - # parked: on a window close it's released when Invoke-PkRun ends, so the - # rest of the run still gets the few seconds Windows allows. + # After an abort: give running workers $TimeoutSeconds, collect what they + # return, force-stop the rest. After a window close, the native console + # handler's thread stays held until Invoke-PkRun ends, since Windows ends + # the process once it returns. param( [Parameter(Mandatory)] [AllowEmptyCollection()] @@ -3897,15 +3765,13 @@ function Invoke-PkRunspaceBatch { # Passing a parameter the worker doesn't declare fails the whole invoke # with an unhelpful binding error. $declaredParams = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase) - # Leaving out a mandatory one fails that job in binding, after others have - # started. Not checked with parameter sets, where what's needed depends on - # the set, and not for CancelToken, which is filled in when a job leaves - # it out. + # A missing mandatory one would fail that job in binding after others + # started. Not checked with parameter sets, nor for CancelToken, which is + # filled in. $mandatoryParams = [System.Collections.Generic.List[string]]::new() $hasParameterSets = $false - # A function's own scriptblock (${function:Name}) has the function as its - # Ast: its parameters are in function f($a) or in its body's param() - # block, as Get-PkHandlerParamCount reads them. + # ${function:Name}'s Ast is the function: its parameters are in f($a) or its + # body's param() block. $workerAst = $WorkerScript.Ast $workerParamList = $null if ($workerAst -is [System.Management.Automation.Language.FunctionDefinitionAst]) { @@ -3990,9 +3856,8 @@ function Invoke-PkRunspaceBatch { $allShared = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase) foreach ($n in (Get-PkWorkerSafeFunctionName)) { $null = $allShared.Add($n) } foreach ($n in $SharedFunctionNames) { $null = $allShared.Add($n) } - # The kit's worker functions come from this module; yours from where - # you called this (a script's own functions, functions inside a - # function, a module's private ones). + # The kit's worker functions come from this module, yours from where you + # called this. $kitWorkerNames = [System.Collections.Generic.HashSet[string]]::new([string[]]@(Get-PkWorkerSafeFunctionName), [System.StringComparer]::OrdinalIgnoreCase) $callerFns = Get-PkCallerFunction -SessionState $PSCmdlet.SessionState -Name @($allShared | Where-Object { -not $kitWorkerNames.Contains($_) }) foreach ($sharedFn in $allShared) { @@ -4015,23 +3880,18 @@ function Invoke-PkRunspaceBatch { # Each job starts in the caller's current location: the real folder, # since a New-PSDrive drive doesn't exist in the worker. $workerLocation = $ExecutionContext.SessionState.Path.CurrentFileSystemLocation.ProviderPath - # Every job runs this: move to that folder, then run the worker in its - # own scope with the job's values. Per job, because runspaces are - # reused. One script, not a Set-Location statement before the worker: - # with a second statement a pool runspace's pipeline never completed - # (5.1 and 7). The prefix shares the worker's first line, so error line - # numbers match its code. If the folder is gone, the job runs wherever - # its runspace is. + # Each job moves to that folder, then runs the worker in its own scope. + # One script, sharing the worker's first line so error line numbers + # match: with a separate Set-Location statement first, a pool runspace's + # pipeline never completes. $jobScript = 'param([string]$PkJobLocation, [hashtable]$PkJobValues) if ($PkJobLocation) { Set-Location -LiteralPath $PkJobLocation -ErrorAction SilentlyContinue }; & {' + $WorkerScript.ToString() + "`n} @PkJobValues" while ((-not $scanExhausted -or $handles.Count -gt 0) -and -not $Cts.Token.IsCancellationRequested) { - # An abort only raises a flag; Test-PkAbortSignal is what cancels - # the token. Checked before launching, so an abort raised since the - # last check (before the run, or by a -ResultHandler) starts - # nothing more, and per job, for one -NextJobProvider raises. The - # flag read is cheaper than a function call. + # The abort flag before launching, and per job: an abort raises it, + # and Test-PkAbortSignal cancels the token. A field read is cheaper + # than the call. if ([PkConsoleCtrl]::AbortRequested) { $null = Test-PkAbortSignal } while (-not $scanExhausted -and $handles.Count -lt $MaxConcurrent -and -not $Cts.Token.IsCancellationRequested -and -not [PkConsoleCtrl]::AbortRequested) { if ($null -ne $JobParams) { @@ -4042,10 +3902,9 @@ function Invoke-PkRunspaceBatch { $nextJob = $null } } else { - # 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. + # The last value decides: $null ends the run, else the last + # hashtable is the job. Anything else it output 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 @@ -4083,10 +3942,8 @@ function Invoke-PkRunspaceBatch { $jobValues = @{} foreach ($key in $nextJob.Keys) { $jobValues[$key] = $nextJob[$key] } - # $jobValues is case-insensitive, like binding: fewer keys than - # the job means a case-sensitive [hashtable]::new() job had two - # differing only in case (a -JobParams job's were refused before - # the run). + # $jobValues is case-insensitive: fewer keys means a + # case-sensitive job had two differing only in case. if ($jobValues.Count -ne $nextJob.Count) { throw ("Invoke-PkRunspaceBatch: a job from -NextJobProvider supplies " + (Get-PkCaseDuplicateJobKey -Job $nextJob) + ", which differ only in case. Parameter names don't, so the worker would get only one of them. Keep one.") } @@ -4141,10 +3998,10 @@ function Invoke-PkRunspaceBatch { } $handles = $stillPending if ($handles.Count -gt 0 -and ($scanExhausted -or $handles.Count -ge $MaxConcurrent)) { - # Until a worker finishes or the token is canceled. The 100 ms cap - # keeps worker messages, -PollCallback and the abort flag moving. - # WaitAny holds 63 handles at most on an STA thread, one of them the - # token; a worker past that is only noticed when the time is up. + # Until a worker finishes or the token is canceled; at most 100 + # ms, to keep worker messages and the abort flag moving. WaitAny + # takes 63 handles on an STA thread: at most 62 workers plus the + # token. $workerWaits = [System.Collections.Generic.List[System.Threading.WaitHandle]]::new() foreach ($h in $handles) { if ($workerWaits.Count -ge 62) { break } @@ -4177,10 +4034,9 @@ function Invoke-PkRunspaceBatch { # A worker stuck in a .NET call can't be stopped, and Dispose() # would wait for it, so close in the background. if ($stillRunning) { - # An abandoned worker can run on to its last line once its call - # returns. Cancel the token so one that checks - # Test-PkCancelRequested before an irreversible step is told, - # even on a non-abort exit (one of your callbacks threw). + # An abandoned worker can run on once its call returns: cancel + # the token so one that checks Test-PkCancelRequested is told, + # even on a non-abort exit. try { $Cts.Cancel() } catch { } # already disposed by its owner: nothing left to tell try { $null = $pool.BeginClose($null, $null) } catch { } # teardown only; the exception in flight, if any, is the one to surface } @@ -4202,15 +4058,9 @@ function Invoke-PkRunspaceBatch { # ============================================================================== function Get-PkCallerFunction { - # Looks function names up in the caller's session state, from its current - # scope: a script's own functions, functions defined inside the calling - # function, a calling module's private ones. Get-Item Function: here would - # search this module, and InvokeCommand.GetCommand only finds global ones. - # A scriptblock made from text and run with InvokeScript(SessionState) is - # dot-sourced into the caller's scope, so the work happens inside & { } - # with the names as quoted literals: nothing is assigned there. - # -FollowAlias follows an alias to its function. Returns a hashtable: - # name -> FunctionInfo (missing = not found). + # Looks function names up in the caller's session state from its current + # scope, inside & { } with the names as literals. Returns name -> + # FunctionInfo; -FollowAlias follows an alias to its function. param( [Parameter(Mandatory)][System.Management.Automation.SessionState]$SessionState, [string[]]$Name, @@ -4250,28 +4100,19 @@ function Get-PkCallerFunction { } function Get-PkCommandKind { - # What a worker would need to run a command, given what the caller's - # session resolves its name to ($Fn from Get-PkCallerFunction -FollowAlias, - # or $null): 'Function' (one of your session's functions - must be - # shared), 'UnloadableModuleFunction' (from a module a worker can't - # autoload), or 'Other' (cmdlet, program, autoloadable module function, - # or unknown). Uses the Alias: and Function: drives, not Get-Command, - # which searches every module on $env:PSModulePath for a name that - # doesn't resolve, on every Invoke-PkRunspaceBatch call. + # What a worker needs to run a command the caller's session resolves to $Fn: + # 'Function' (yours, must be shared), 'UnloadableModuleFunction' (from a + # module a worker can't autoload) or 'Other'. The names are resolved through + # the Alias: and Function: drives, since Get-Command searches every module + # for a name it can't find. param([System.Management.Automation.FunctionInfo]$Fn) if ($null -eq $Fn) { return 'Other' } if ([string]::IsNullOrEmpty($Fn.ModuleName)) { return 'Function' } - # The kit's own: a worker is given only the worker-safe ones, so the rest - # are treated like your own functions. (With the kit's module installed a - # worker could auto-load them, but they aren't made for workers.) + # The kit's own: a worker gets only the worker-safe ones, so the rest count + # as your functions. if ($Fn.ModuleName -eq 'ParallelKit') { return 'Function' } - # A module function (Get-FileHash, say) autoloads in a worker like a - # cmdlet does - but only if the module can be found by name. One imported - # by path from elsewhere can't. Remembered for the session: on 5.1 each - # lookup searches all of PSModulePath (51 ms with 154 modules on it), for - # every Invoke-PkRunspaceBatch call. So a module installed mid-session is - # missed until a new window, but one added to PSModulePath isn't: that's - # part of the key. + # A module function autoloads in a worker only if its module can be found by + # name. Cached per session (a lookup is slow on 5.1), keyed by PSModulePath. $key = $env:PSModulePath + '|' + $Fn.ModuleName $found = $false if (-not [PkState]::ModuleFound.TryGetValue($key, [ref]$found)) { @@ -4283,10 +4124,8 @@ function Get-PkCommandKind { } function Get-PkCaseDuplicateJobKey { - # Two keys of a job hashtable that differ only in case, as "'Id' and - # 'id'", else $null. Only a case-sensitive [hashtable]::new() can hold - # them; the worker's copy is case-insensitive, like parameter binding, so - # they'd collapse into one, the later silently winning. + # Two keys differing only in case, as "'Id' and 'id'", else $null. They'd + # collapse into one in the worker's case-insensitive copy. param([Parameter(Mandatory)][hashtable]$Job) $seen = @{} foreach ($key in $Job.Keys) { @@ -4298,12 +4137,9 @@ function Get-PkCaseDuplicateJobKey { } function Get-PkScriptBlockJobKey { - # The first key of a job hashtable whose value is a scriptblock, or holds - # one up to three levels down (in arrays, lists, dictionaries and - # [pscustomobject]s), else $null. A scriptblock belongs to the runspace - # that made it: run in a worker it executes against the main thread's - # session state, which can corrupt it (the kit's own functions vanish - # mid-run), crash, or hang. + # The first job key holding a scriptblock, up to three levels down, else + # $null. Run in a worker, a scriptblock executes against the main thread's + # session state, which can corrupt it or hang. param([Parameter(Mandatory)][hashtable]$Job) foreach ($key in $Job.Keys) { if (Test-PkHoldsScriptBlock -Value $Job[$key] -Depth 3) { return [string]$key } @@ -4312,10 +4148,8 @@ function Get-PkScriptBlockJobKey { } function Test-PkHoldsScriptBlock { - # Get-PkScriptBlockJobKey's walk. Leaves (strings, numbers) are checked - # inline rather than through a call, so a big object[] stays cheap, and - # a collection whose element type can't hold anything (byte[], string[], - # List[int]) isn't walked at all. + # Get-PkScriptBlockJobKey's walk. Leaves are checked inline, and a + # collection of value types or strings isn't walked. param($Value, [int]$Depth) if ($null -eq $Value) { return $false } if ($Value -is [scriptblock]) { return $true } @@ -4341,9 +4175,8 @@ function Test-PkHoldsScriptBlock { if ($Depth -gt 1 -and (Test-PkHoldsScriptBlock -Value $inner -Depth ($Depth - 1))) { return $true } } } catch { - # A collection other threads are changing (a results sink shared by - # workers) can't be enumerated safely, and PowerShell may wrap the - # error, so catch anything. Skip it: such sinks hold results, not code. + # A collection other threads are changing can't be enumerated safely: + # skip it (such sinks hold results, not code). return $false } return $false @@ -4357,9 +4190,7 @@ function Get-PkScriptBlockJobMessage { } function Get-PkPredefinedVariable { - # The names a worker can read without declaring them: what a fresh - # runspace has, what PowerShell makes on demand, and the kit's own worker - # globals. Read once per session. + # The names a worker can read without declaring them. Read once per session. $known = [PkState]::PredefinedVariables if ($null -ne $known) { return ,$known } $known = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase) @@ -4368,13 +4199,12 @@ function Get-PkPredefinedVariable { $null = $ps.AddScript('Get-ChildItem Variable: | ForEach-Object { $_.Name }') foreach ($name in $ps.EndInvoke($ps.BeginInvoke())) { $null = $known.Add([string]$name) } } finally { $ps.Dispose() } - # A fixed list, since PowerShell only makes these where they mean - # something (in a pipeline, after -match or a program, in an event's - # action, ...), so a fresh runspace has none of them. + # PowerShell makes these only where they mean something, so a fresh runspace + # has none. foreach ($name in '_', 'PSItem', 'Matches', 'LASTEXITCODE', 'this', 'PSCmdlet', 'foreach', 'switch', 'OFS', 'PROFILE', 'Event', 'EventArgs', 'EventSubscriber', 'Sender', 'SourceIdentifier', 'PSSenderInfo', 'PSDebugContext', 'PSLogUserData', 'PSModuleAutoLoadingPreference') { $null = $known.Add($name) } - # Automatic or preference variables only one of 5.1 and 7 has, so a worker - # written for both can test for them. + # Automatic or preference variables that exist on only one of 5.1 and 7, so + # a worker written for both can test for them. foreach ($name in 'IsWindows', 'IsLinux', 'IsMacOS', 'IsCoreCLR', 'PSStyle', 'EnabledExperimentalFeatures', 'PSNativeCommandArgumentPassing', 'PSNativeCommandUseErrorActionPreference', 'ConsoleFileName', 'MaximumAliasCount', 'MaximumDriveCount', 'MaximumErrorCount', 'MaximumFunctionCount', 'MaximumVariableCount') { $null = $known.Add($name) } $null = $known.Add('PkWorkerQueue'); $null = $known.Add('PkCancelToken') @@ -4395,7 +4225,7 @@ function Get-PkCommandVariable { # the name. $takesValue = @('Value', 'Description', 'Option', 'Scope', 'Visibility', 'Include', 'Exclude', 'FileName', 'BaseDirectory', 'UICulture', 'SupportedCommand', 'ErrorAction', 'WarningAction', 'InformationAction', 'ProgressAction', 'OutBuffer', 'ea', 'wa', 'infa', 'proga', 'ob') - $expect = '' # what the next bare element is: a parameter's 'name' or 'value', or nothing's + $expect = '' # what the next bare element is: a parameter's 'name', its 'value', or '' for neither $positionalDone = $false foreach ($element in ($Command.CommandElements | Select-Object -Skip 1)) { $value = $element @@ -4424,9 +4254,9 @@ function Get-PkCommandVariable { } function Get-PkUndeclaredVariable { - # The variable reads in a worker's code whose variable it never declares - # or assigns, anywhere in it (order is ignored), as VariableExpressionAsts. - # Left out: $global: and drive-qualified ones. + # The variables a worker reads but never declares or assigns (order + # ignored), as VariableExpressionAsts. $global: and drive-qualified ones are + # left out. param([System.Management.Automation.Language.Ast]$Ast) $declared = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase) $reads = [System.Collections.Generic.List[object]]::new() @@ -4585,11 +4415,9 @@ function Test-PkWorkerSafetyCore { $scriptVarScopes = [System.Collections.Generic.List[object]]::new() if ($t.IsWorkerBody) { foreach ($nested in $ast.FindAll({ param($node) $node -is [System.Management.Automation.Language.ScriptBlockExpressionAst] }, $true)) { $scriptVarScopes.Add($nested) } - # A function defined inside the worker script is in the same - # position as a shared one: called from a closure, its $script: - # can read as empty. - # Not the worker itself when it's a function (${function:Name}): - # its body is the worker's top level. + # A function defined inside the worker is like a shared one: called + # from a closure, its $script: can read as empty. The worker itself, + # given as ${function:Name}, isn't one of these. foreach ($innerFn in $ast.FindAll({ param($node) $node -is [System.Management.Automation.Language.FunctionDefinitionAst] }, $true)) { if (-not [object]::ReferenceEquals($innerFn, $ast)) { $scriptVarScopes.Add($innerFn.Body) } } @@ -4606,9 +4434,8 @@ function Test-PkWorkerSafetyCore { } } - # Not shared functions: one reading its caller's variables is ordinary. - # Each name once, at its first line without pk:ignore. A $script: the - # rule above looked at isn't a second finding. + # Not shared functions. Each name once, at its first line without + # pk:ignore. if ($t.IsWorkerBody) { $closureNote = "" if ($null -ne $WorkerScript.Module -and $WorkerScript.Module.Name -like '__DynamicModule_*') { $closureNote = ".GetNewClosure() doesn't carry variables into a worker: " } @@ -4629,15 +4456,10 @@ function Test-PkWorkerSafetyCore { Text = ($t.Where + " (line " + $cv.Extent.StartLineNumber + ") casts a scriptblock to the delegate [" + $cv.Type.TypeName.Name + "] - this can hang or crash a worker") }) } - # The implicit form: a scriptblock literal, or a variable assigned one - # anywhere in this code, passed to a method or constructor: - # $dict.GetOrAdd($k, { }), [System.Lazy[object]]::new($factory). .NET - # gets a delegate all the same. Either can be wrapped (see - # Get-PkUnwrappedExpression). Matched by variable name, not flow. - # .ForEach()/.Where() take real scriptblocks. Storage methods - # ($list.Add($sb), $queue.Enqueue($sb)) make no delegate and aren't - # flagged, so a collection typed to hold delegates (List[Func[object]]) - # isn't caught. + # A scriptblock, or a variable assigned one anywhere here (matched by + # name, not by tracking data flow), passed to a .NET method or + # constructor becomes a delegate. Storage methods (Add, Enqueue, ...) + # make no delegate and aren't flagged. $storageMethods = @('Add', 'AddRange', 'Insert', 'Enqueue', 'Push', 'TryAdd', 'Contains', 'Remove', 'IndexOf', 'set_Item') $scriptBlockVars = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase) foreach ($assign in $ast.FindAll({ param($node) $node -is [System.Management.Automation.Language.AssignmentStatementAst] }, $true)) { @@ -4674,10 +4496,9 @@ function Test-PkWorkerSafetyCore { # Public functions (the ones README.md documents) # ============================================================================== -# Dot-sourcing imports these globally: a .GetNewClosure() block only sees global -# functions, so a callback of yours can call them. The same list is -# $publicFunctions in ParallelKit.Harness.ps1; keep the two in step. The module's -# manifest is made from this one. +# Dot-sourcing imports these globally, so callbacks can call them. Keep in step +# with the harness's $publicFunctions; the module's manifest is made from this +# list. Export-ModuleMember -Function @( 'Set-PkMessageHandler', 'Write-PkMessage', 'Initialize-ParallelKit', 'Register-PkCancellationSource', 'Unregister-PkCancellationSource', 'Reset-PkAbortState', 'Request-PkAbort', 'Test-PkAbortSignal', 'Test-PkCancelRequested', diff --git a/README.md b/README.md index 32548e4..ceae9ad 100644 --- a/README.md +++ b/README.md @@ -27,7 +27,7 @@ ParallelKit uses Windows Job Objects to clean up programs and their descendants. - **`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. If Windows refuses to add a program that's still running, the kit warns once more, naming the process: that program isn't cleaned up if PowerShell is killed. - **`NoJob`.** If Windows won't give the kit a Job Object at all, it warns (once, when the first program's start is what sets it up), 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`. +- **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`. If Windows won't end a program's own Job Object, the kill also goes to `taskkill /T`, which misses a child whose parent has already exited; the kit warns about that once per session. diff --git a/Source/PkChildProcessJob.cs b/Source/PkChildProcessJob.cs index ca71486..e3b668e 100644 --- a/Source/PkChildProcessJob.cs +++ b/Source/PkChildProcessJob.cs @@ -17,25 +17,8 @@ public sealed class PkStartedProcess public StreamReader Stderr; } -// Reads one of a program's output streams to its end, in chunks, so what has -// arrived can be taken at any time (Snapshot): something the program started -// can hold the stream open long after it exits. The first snapshot taken -// before the end is the stream's text from then on, and the task's result; -// without one, the result is the whole text. The read goes on to the end -// either way, dropping what it no longer needs, so nothing that writes to the -// stream blocks on a full pipe. The reader is closed there. -// -// No text ends in half a character: the decoder carries one split across two -// reads over to the next, and a snapshot leaves out a surrogate pair's first -// half whose second hasn't arrived. With a cap (maxChars), only the first half -// and the last half of a longer stream are kept, never split inside a pair, -// and DroppedChars counts the rest. -// -// Each read has a thread of its own (LongRunning), not a pool thread: it -// blocks until every holder of the stream's write end has let go (at the -// latest when PowerShell exits: they're in the Job Object). Leftover programs -// holding their output would otherwise use up the pool, and a new program's -// reads would wait for it to grow and hit their stream timeout. +// Reads an output stream to its end on a thread of its own, so what has +// arrived can be taken at any time (Snapshot) while a leftover child holds it. public sealed class PkStreamReadTask : Task { private sealed class Buffer @@ -48,11 +31,9 @@ private sealed class Buffer private string _kept; private readonly object _gate = new object(); public volatile bool ReaderClosed; - // The cap's tail: the last chars read, a ring once it's full. It - // grows with the output, so a cap costs nothing until output reaches - // it. _tailCap is 0 with no cap. A head that turns away a pair's - // first half gives the tail its slot, before the tail is allocated, - // so output that fits the cap is kept whole. + // The cap's tail: the last chars read, a ring once full, grown with the + // output. _tailCap is 0 with no cap; it grows by one when the head + // hands it the first half of a surrogate pair it can't keep. private readonly int _headCap; private int _tailCap; private bool _headFull; @@ -165,10 +146,9 @@ public string Keep(bool snapshot) private readonly Buffer _buffer; private PkStreamReadTask(Buffer buffer) : base(new Func(buffer.Pump), TaskCreationOptions.LongRunning) { _buffer = buffer; } - // Harness only: n >= 0 makes the Run after the next n throw, as one whose - // thread can't be created would; -1, the default, is off. With - // TestFailRunDelayMs above 0, that Run waits that long before throwing, so - // a program that ends at once has exited by then. + // Harness only: n >= 0 lets n more Runs succeed, then makes the next throw + // (0: the next one), as if its thread couldn't start; -1 is off. + // TestFailRunDelayMs waits that long first. public static int TestFailRunAfter = -1; public static int TestFailRunDelayMs = 0; @@ -199,12 +179,9 @@ public static PkStreamReadTask Run(TextReader reader, int maxChars) public bool TestReaderClosed { get { return _buffer.ReaderClosed; } } } -// A Windows Job Object with KILL_ON_JOB_CLOSE: every child process assigned -// to it dies when this process exits for ANY reason, force-kill included. -// Each program the kit starts also gets a job of its own (its tree job), -// nested in that one, so the program and everything it started can be -// killed at once (KillTree), including a child whose parent has already -// exited, which taskkill /T can't find. +// A Job Object with KILL_ON_JOB_CLOSE: everything in it dies when this process +// exits, force-kill included. Each program also gets a nested tree job, so +// KillTree ends it and everything it started, orphans included. public static class PkChildProcessJob { private const int JobObjectExtendedLimitInformation = 9; @@ -267,10 +244,8 @@ private sealed class TreeJob : SafeHandleZeroOrMinusOneIsInvalid } private static readonly ConditionalWeakTable _treeJobs = new ConditionalWeakTable(); - // Harness only: start programs without a tree job, to test the taskkill - // path; or have TryStart's first CreateProcess, with the tree job, count - // as refused, to test its retry without one. TestFailTerminate makes - // KillTree's TerminateJobObject count as refused, leaving the tree running. + // Harness only: start without a tree job, have TryStart's first try with it + // count as refused, or have KillTree's TerminateJobObject count as refused. public static bool TestNoTreeJob = false; public static bool TestRefuseTreeJob = false; public static bool TestFailTerminate = false; @@ -281,11 +256,9 @@ private static void AddTree(Process process, IntPtr treeJob) catch (ArgumentException) { CloseHandle(treeJob); } // already has one: a second Assign of the same Process } - // Kills every process in the program's tree job. False if it has none, - // or Windows refused: Stop-PkProcessTree then uses taskkill. The job stays open - // until ReleaseTree (Complete-PkProcess, or the kit's own kill paths) or - // garbage collection, so a second KillTree, as -KillTreeOnExit makes - // after a time-limit kill or a force-stop, ends an empty job and succeeds. + // Ends every process in the program's tree job; false with no tree job or + // on a refusal. The job stays open until ReleaseTree, so a second KillTree + // ends an empty job and succeeds. public static bool KillTree(Process process) { if (process == null) { return false; } @@ -362,12 +335,9 @@ public static bool Initialize() } } - // Never throws: a failed assignment only loses the force-kill cleanup - // for that one process. Once it's in the kit's job, it also gets a tree - // job (Windows nests it); without one, a kill uses taskkill. reason says - // why it failed ("Win32 error 5", or what was thrown), null when it - // worked. Per call: LastError is shared, and another thread's start can - // change it before the caller reads it. + // Never throws: a failed assignment only loses cleanup for that process. A + // program in the kit's job gets a nested tree job too. reason is why it + // failed, null when it worked (LastError is shared across threads). public static bool Assign(System.Diagnostics.Process process, out string reason) { reason = null; @@ -396,25 +366,8 @@ public static bool Assign(System.Diagnostics.Process process, out string reason) } // ---- Starting a program inside the job from its first instruction ---- - // - // Process.Start can only be followed by Assign, so a program that starts a - // child straight away (cmd /c tool.exe) can do so before it's in the job, - // and that child survives a force-kill. TryStart has Windows put the - // program in the job as it creates it (PROC_THREAD_ATTRIBUTE_JOB_LIST, - // Windows 10 / Server 2016+), so its children join too. - // - // Everything else copies Process.Start with UseShellExecute = false: - // command line, Windows' own search for a bare name, CREATE_NO_WINDOW, - // redirected stdout/stderr, and the default encoding. stdin is NUL, or - // PowerShell's own as Process.Start passes it. - // - // The pipe ends the child writes to must be inheritable while it's - // created, and a plain Process.Start elsewhere in PowerShell inherits - // every inheritable handle: it would hold our output open until it exits. - // .NET's own start lock keeps those apart, so TryStart takes it (found by - // reflection) and returns null, for Process.Start plus Assign, when it - // isn't there in a form it knows. The handle list keeps our child from - // inheriting anyone else's handles. + // Process.Start then Assign lets an immediate child escape the job, so + // TryStart creates the program in it, holding .NET's start lock. private const uint CREATE_SUSPENDED = 0x4; private const uint CREATE_UNICODE_ENVIRONMENT = 0x400; @@ -502,10 +455,10 @@ private static extern bool UpdateProcThreadAttribute(IntPtr lpAttributeList, uin [DllImport("kernel32.dll")] private static extern uint GetConsoleOutputCP(); - // .NET's process-start lock: a plain object (5.1, 7.6) is held with - // Monitor; a System.Threading.Lock (where newer .NET is moving its locks) - // through its own Enter/Exit, by reflection since 5.1 has no such type. - // Monitor on a Lock wouldn't keep out its Enter, hence the type check. + // .NET's process-start lock: a plain object (in Windows PowerShell 5.1's + // .NET Framework and PowerShell 7.6's .NET) through Monitor; a + // System.Threading.Lock, where newer .NET moves its locks, through its own + // Enter/Exit, by reflection since 5.1 has no such type. private sealed class StartLock { public readonly string Kind; @@ -607,11 +560,9 @@ private static int SetStartAttributes(IntPtr attrList, IntPtr attrSize, IntPtr h public static bool TestFailSetup = false; public static bool TestFailReaders = false; - // How programs start here, for Initialize-ParallelKit: "CreatedInJob" - // (TryStart), "AddedToJob" (Process.Start, then the job: no usable start - // lock, or the harness switch), or "NoJob" (the job couldn't be set up, - // so nothing is cleaned up on a kill). A single start can still fall back - // from CreatedInJob when its setup fails; that warns. + // How programs start, for Initialize-ParallelKit: CreatedInJob (TryStart), + // AddedToJob (Process.Start, then the job) or NoJob (no cleanup on a kill). + // One start can still fall back, with a warning. public static string StartMode { get @@ -626,10 +577,8 @@ public static string StartMode private static int _fallbackWarned = 0; public static bool ClaimFallbackWarning() { return Interlocked.Exchange(ref _fallbackWarned, 1) == 0; } public static void TestResetFallbackWarning() { Interlocked.Exchange(ref _fallbackWarned, 0); } - // The same, once each, for a Job Object that couldn't be set up when - // first needed, for a running program Windows wouldn't add to it, and for - // -KillTreeOnExit on a program without a tree job, or whose tree job - // Windows wouldn't end. + // The same, once each: no Job Object, a program Windows wouldn't add to it, + // -KillTreeOnExit without a tree job, and a tree job Windows wouldn't end. private static int _initWarned = 0, _assignWarned = 0, _noTreeWarned = 0, _killTreeWarned = 0; public static bool ClaimInitWarning() { return Interlocked.Exchange(ref _initWarned, 1) == 0; } public static bool ClaimAssignWarning() { return Interlocked.Exchange(ref _assignWarned, 1) == 0; } @@ -640,11 +589,9 @@ public static string StartMode [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] private static extern uint GetShortPathName(string lpszLongPath, StringBuilder lpszShortPath, uint cchBuffer); - // The 8.3 short form of a full path, or null when it has none that differs: - // the path doesn't exist, isn't rooted, or the volume doesn't make short - // names. Asked with the \\?\ prefix, which works past 260 characters on - // both runtimes (without it, PowerShell 7 fails there); the answer comes - // back without it, since CreateProcess refuses a prefixed program path. + // A full path's 8.3 short form, or null if it has none that differs. Asked + // with the \\?\ prefix (needed past 260 characters on PowerShell 7), answered without + // it, since CreateProcess refuses a prefixed program path. public static string GetShortPath(string path) { if (string.IsNullOrEmpty(path)) { return null; } @@ -713,12 +660,8 @@ private static IntPtr OpenNulForRead() return nul; } - // Starts the program in the job, or returns null when it can't do that - // safely: the caller then uses Process.Start and Assign. fallbackReason - // says why, for the caller's one-time warning; it stays null where no - // warning is due (no job, which has its own; the harness switch). Throws - // Win32Exception when Windows refuses to create the program, as - // Process.Start does. encoding null: the console's output code page. + // Starts the program in the job, or returns null (with fallbackReason) for + // Process.Start and Assign. Throws as Process.Start does. public static PkStartedProcess TryStart(string fileName, string arguments, string workingDirectory, Encoding encoding, bool inheritStdin, out string fallbackReason) { fallbackReason = null; @@ -753,10 +696,9 @@ public static PkStartedProcess TryStart(string fileName, string arguments, strin CreateOutputPipe(out outRead, out outWrite); CreateOutputPipe(out errRead, out errWrite); - // NUL, so a program that reads its input gets the end of it - // at once. Or, asked for, PowerShell's own as Process.Start - // passes it: listed only if inheritable, the only case the - // child could use it. + // NUL, so a program reading its input gets the end at once; + // or, asked for, PowerShell's own, listed only if + // inheritable. bool stdinInherit = true; if (inheritStdin) { @@ -814,10 +756,9 @@ public static PkStartedProcess TryStart(string fileName, string arguments, strin if (started) { started = CreateProcess(null, commandLine, IntPtr.Zero, IntPtr.Zero, true, flags, IntPtr.Zero, dir, ref si, out pi); } if (!started && jobCount == 2) { - // Once more without the tree job, in case that's what Windows - // refused (nesting it): the program still starts, and a kill - // then uses taskkill. A program that can't start at all fails - // again, with its own error. + // Once more without the tree job, in case nesting it is + // what Windows refused; a program that can't start fails + // again with its own error. DeleteProcThreadAttributeList(attrList); attrReady = false; CloseHandle(treeJob); treeJob = IntPtr.Zero; jobCount = 1; int retryError = SetStartAttributes(attrList, attrSize, handleArr, handleCount, jobArr, jobCount); diff --git a/Source/PkConsoleCtrl.cs b/Source/PkConsoleCtrl.cs index a01c64c..fb60685 100644 --- a/Source/PkConsoleCtrl.cs +++ b/Source/PkConsoleCtrl.cs @@ -23,10 +23,10 @@ public static class PkConsoleCtrl public static readonly ManualResetEventSlim DrainComplete = new ManualResetEventSlim(false); public static int DrainWaitMs = 65000; - // Ctrl+C presses: the first starts the abort, the next skips the drain - // (force-stops running jobs now), the one after that is let through to - // PowerShell, which stops the script. A press within SkipDebounceMs of - // the last counted one is a double tap or key repeat, and is ignored. + // Ctrl+C presses: the first starts the abort, the second skips the wait for + // running work (force-stops it now), the third goes to PowerShell, which + // stops the script. A press within SkipDebounceMs of the last counted one + // is ignored. public static volatile bool SkipDrain = false; public static volatile string PressedKey = null; // "Ctrl+C" / "Ctrl+Break" once a press started the abort public static int SkipDebounceMs = 1000; @@ -81,8 +81,9 @@ public static bool OnInterrupt(string key) AbortRequested = true; return true; } - // An abort is already under way (this press, Request-PkAbort or a - // close). A press that follows a counted one too closely is ignored. + // An abort is already under way (an earlier press, Request-PkAbort + // or a window close). A press too soon after the last counted one + // is ignored. if (_lastPressTimestamp != 0) { double sinceLastMs = (now - _lastPressTimestamp) * 1000.0 / System.Diagnostics.Stopwatch.Frequency;