From 284dffbc4468bb93f1735d6e7dfb4632c96836b8 Mon Sep 17 00:00:00 2001 From: Hal <22532613+HalRiveria@users.noreply.github.com> Date: Mon, 30 Nov 2026 15:30:39 -0500 Subject: [PATCH 1/2] Worker-safety check: flag a variable the worker never declares A worker is rebuilt from its text in an empty runspace, so a variable of the script's, or one a .GetNewClosure() captured, read as empty with no error. New finding: UndeclaredVariable. Co-Authored-By: Claude Opus 5.5 --- ParallelKit.Harness.ps1 | 91 +++++++++++++++++++++++++++- ParallelKit.ps1 | 131 +++++++++++++++++++++++++++++++++++++++- README.md | 3 +- 3 files changed, 221 insertions(+), 4 deletions(-) diff --git a/ParallelKit.Harness.ps1 b/ParallelKit.Harness.ps1 index a0cdcbd..34a69cf 100644 --- a/ParallelKit.Harness.ps1 +++ b/ParallelKit.Harness.ps1 @@ -5274,10 +5274,11 @@ function Get-HarnessSectionLeaks([string]$Source) { switch ($node.GetType().Name) { 'AssignmentStatementAst' { # $x = 1, [int]$x = 1 and $x, $y = 1, 2; not $x.Key = 1. + # (A convert is an AttributedExpressionAst.) $targets = @($node.Left) if ($node.Left -is [System.Management.Automation.Language.ArrayLiteralAst]) { $targets = @($node.Left.Elements) } foreach ($target in $targets) { - while ($target -is [System.Management.Automation.Language.ConvertExpressionAst]) { $target = $target.Child } + while ($target -is [System.Management.Automation.Language.AttributedExpressionAst]) { $target = $target.Child } if ($target -is [System.Management.Automation.Language.VariableExpressionAst]) { $null = $defines[$id].Add((& $bare $target)) } } } @@ -5297,7 +5298,7 @@ function Get-HarnessSectionLeaks([string]$Source) { foreach ($id in $defines.Keys) { $elsewhere.UnionWith($defines[$id]) } foreach ($id in $uses.Keys) { foreach ($name in $uses[$id]) { - if ($name -eq '$null' -or -not $elsewhere.Contains($name) -or $defines[$id].Contains($name) -or $defines['A'].Contains($name)) { continue } + if ($name -in '$null', '$OFS' -or -not $elsewhere.Contains($name) -or $defines[$id].Contains($name) -or $defines['A'].Contains($name)) { continue } $id + ' uses ' + $name } } @@ -5623,6 +5624,92 @@ try { Write-Host "" } +# ============================================================================== +if (Test-HarnessSection 'BL' "a worker that reads a variable it never declares is flagged") { +# A worker is rebuilt from its text in a runspace that starts empty, so a +# variable of the script's (or one a closure captured) reads as empty there. +Reset-Harness +function Get-HarnessUndeclared([scriptblock]$Worker, [string[]]$Shared = @()) { + # The names the check flags, in order. + $names = foreach ($f in (Test-PkWorkerSafety -WorkerScript $Worker -SharedFunctionNames $Shared)) { + if ($f.Rule -ne 'UndeclaredVariable') { $f.Rule; continue } + [regex]::Match($f.Text, 'reads \$(\S+?),').Groups[1].Value + } + return (@($names) -join ',') +} +# Each worker here declares or assigns all it reads. +$blClean = [ordered]@{ + 'its own parameters, and ones of blocks and functions inside it' = { param($Id) function Add-One { param([int]$n, [int]$step = 1) $n + $step } $sb = { param($x) $x * $Id }; & $sb (Add-One 1) } + 'a function''s parameters written after its name' = { param($Id) function Add-Two($n) { $n + 2 }; Add-Two $Id } + 'assignments: plain, typed, an attribute, several at once, in parentheses, += and ++' = { $a = 1; [int]$b = 2; [ValidateNotNull()]$c = 3; $d, [string]$e = 4, 5; ($g) = 6; $h += 7; $i++; --$j; "$a$b$c$d$e$g$h$i$j" } + 'a variable assigned after the line that reads it' = { param($Id) if ($seen) { 'again' }; $seen = $Id } + 'foreach and for variables' = { foreach ($f in 1..2) { $f }; for ($n = 0; $n -lt 2; $n++) { $n } } + 'the common parameters that fill a variable' = { Get-Item 'x' -OutVariable ov1 -ErrorVariable +ev1 -WarningVariable 'wv1' -InformationVariable:iv1 -PipelineVariable pv1 | ForEach-Object { "$ov1$ev1$wv1$iv1$pv1" } } + 'their aliases, and a shortened name' = { Get-Item 'x' -ov ov2 -ev ev2 -wv wv2 -iv iv2 -pv pv2 -ErrorVar ev3 | ForEach-Object { "$ov2$ev2$wv2$iv2$pv2$ev3" } } + 'Set-Variable and New-Variable with a literal name' = { Set-Variable sv1 1; Set-Variable -Value 2 -Name sv2; New-Variable -Force 'nv1' 3; Set-Variable -Name sv3, sv4 -Value 1; sv sv5 1; Set-Variable -ErrorAction Stop -OutVariable sv6 sv7 1; "$sv1$sv2$nv1$sv3$sv4$sv5$sv6$sv7" } + 'Tee-Object, -SessionVariable, -ResponseHeadersVariable and -StatusCodeVariable' = { 1 | Tee-Object -Variable tee1; Invoke-RestMethod 'x' -SessionVariable se1 -ResponseHeadersVariable rh1 -StatusCodeVariable st1; "$tee1$se1$rh1$st1" } + 'Import-LocalizedData, by name and by position, and a data block' = { Import-LocalizedData -BindingVariable text1; Import-LocalizedData text2; data text3 { 'x' }; "$text1$text2$text3" } + '[ref]' = { param($Id) $null = [int]::TryParse($Id, [ref]$number); $number } + 'automatic variables' = { param($Id) @($Id) | ForEach-Object { $_; $PSItem }; if ('a' -match 'a') { $Matches[0] }; cmd /c exit 0; $LASTEXITCODE; $args; $input; $PSBoundParameters.Count; $MyInvocation; $Error; $PID; $HOME; $Host; $PSVersionTable; $?; $null; $true; $false; $switch; $foreach; $this; $PSCmdlet; $OFS; $PROFILE; $Event; $EventArgs; $Sender; $EventSubscriber; $SourceIdentifier; $ExecutionContext; $PSScriptRoot; $NestedPromptLevel; $StackTrace } + 'preference variables' = { $ErrorActionPreference; $VerbosePreference; $ProgressPreference; $InformationPreference; $ConfirmPreference; $WhatIfPreference; $OutputEncoding; $PSDefaultParameterValues; $PSModuleAutoLoadingPreference } + 'automatic variables only one of 5.1 and 7 has' = { if ($IsWindows -or $IsLinux -or $IsMacOS -or $IsCoreCLR) { $PSStyle }; $PSNativeCommandUseErrorActionPreference; $PSNativeCommandArgumentPassing; $EnabledExperimentalFeatures; $ConsoleFileName; $MaximumErrorCount } + 'drive-qualified names, $global: ones and the kit''s own' = { $env:TEMP; ${function:prompt}; $variable:x; $global:shared; $PkCancelToken; $global:PkWorkerQueue } + '$script: and $local: names the worker assigns itself' = { $script:top = 1; $script:top; $top; $local:here = 2; $here } + 'a method and a static member' = { param($Id) $Id.ToString(); [Environment]::NewLine; $h = @{}; $h.Key = 1; $h['x'] = 2; $h } +} +foreach ($blName in $blClean.Keys) { + $blFound = Get-HarnessUndeclared $blClean[$blName] + Test-Assert ($blFound -eq '') ("not flagged: " + $blName + " (flagged: '" + $blFound + "')") +} +# And these read something they don't. +$blFlagged = [ordered]@{ + 'a plain read' = @('prefix', { param($Id) $prefix + $Id }) + 'in a string' = @('prefix', { param($Id) "[$prefix$Id] $($Id)" }) + 'in a nested block and a function' = @('blOuter,blInner', { param($Id) $sb = { $blOuter }; function Get-It { $blInner }; & $sb; Get-It }) + 'a splat' = @('options', { param($Id) Get-Item @options }) + 'a member or an element of one' = @('cfg,list,map', { param($Id) $cfg.Path; $list[0]; $map['x'] = $Id }) + 'a default value' = @('fallback', { param($Id, $Name = $fallback) $Name }) + 'each name once, at its first line' = @('blOne,blTwo', { param($Id) $blOne; $blTwo; $blOne; $BLONE }) + 'a name set by a name that isn''t literal' = @('made', { param($Id) Set-Variable -Name $Id -Value 1; $made }) + 'the value given to Set-Variable, not its name' = @('val', { param($Id) Set-Variable -Name x -Value 'val'; $x; $val }) +} +foreach ($blName in $blFlagged.Keys) { + $blFound = Get-HarnessUndeclared $blFlagged[$blName][1] + Test-Assert ($blFound -eq $blFlagged[$blName][0]) ("flagged: " + $blName + " (flagged: '" + $blFound + "', expected '" + $blFlagged[$blName][0] + "')") +} + +# '# pk:ignore' accepts the line; another line's read of it is still flagged. +$blFound = Get-HarnessUndeclared ([scriptblock]::Create("param(`$Id)`n. `$env:PK_HELPER`n`$fromHelper + `$Id # pk:ignore")) +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. +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 + "')") +# $script: in a nested block is flagged once, by its own rule. +$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. +$blPrefix = 'P' +$blPlain = { param($Id) "[$blPrefix$Id]" } +$blFound = Test-PkWorkerSafety -WorkerScript $blPlain +$blPlainText = @($blFound | ForEach-Object { $_.Text }) -join '; ' +$blFound = Test-PkWorkerSafety -WorkerScript $blPlain.GetNewClosure() +$blClosureText = @($blFound | ForEach-Object { $_.Text }) -join '; ' +Test-Assert ($blPlainText -like '*$blPrefix*job value*' -and $blPlainText -notlike '*GetNewClosure*') ("the message says to pass it as a job value (" + $blPlainText + ")") +Test-Assert ($blClosureText -like '*$blPrefix*GetNewClosure() doesn''t carry*job value*') ("and for a closure, that .GetNewClosure() doesn't carry variables into a worker (" + $blClosureText + ")") +$blResults = [System.Collections.Generic.List[object]]::new(); $blThrew = '' +try { $null = Invoke-PkRunspaceJobs -MaxParallel 1 -JobParams @{ Id = 1 } -WorkerScript $blPlain.GetNewClosure() -ResultHandler { param($r) $blResults.Add($r) }.GetNewClosure() } catch { $blThrew = [string]$_ } +Test-Assert ($blThrew -like '*worker-safety rules*$blPrefix*' -and $blResults.Count -eq 0) ("a closure worker that would lose its variable is refused before anything runs (results " + ($blResults -join ',') + ", error: " + $blThrew + ")") +$blResults.Clear() +$null = Invoke-PkRunspaceJobs -MaxParallel 1 -JobParams @{ Id = 1 } -WorkerScript $blPlain -CheckWorkerSafety:$false -ResultHandler { param($r) $blResults.Add($r) }.GetNewClosure() +Test-Assert ($blResults.Count -eq 1 -and $blResults[0] -eq '[1]') ("with the check off it runs, and reads it as empty (" + ($blResults -join ',') + ")") +Reset-Harness +Write-Host "" +} + Set-PkMessageHandler -Handler $null Reset-PkAbortState diff --git a/ParallelKit.ps1 b/ParallelKit.ps1 index 904ac1b..4dcc7ba 100644 --- a/ParallelKit.ps1 +++ b/ParallelKit.ps1 @@ -179,6 +179,9 @@ public static class PkState // module by name, under "|". public static readonly System.Collections.Concurrent.ConcurrentDictionary ModuleFound = new System.Collections.Concurrent.ConcurrentDictionary(StringComparer.OrdinalIgnoreCase); + + // Get-PkPredefinedVariables' answer for this session. + public static HashSet PredefinedVariables = null; } '@ -Language CSharp } @@ -4045,6 +4048,112 @@ function Get-PkScriptBlockJobMessage { "Pass its text instead (`$sb.ToString()) and rebuild it in the worker with [scriptblock]::Create(`$text), or pass -CheckWorkerSafety:`$false to skip this check.") } +function Get-PkPredefinedVariables { + # 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. + $known = [PkState]::PredefinedVariables + if ($null -ne $known) { return ,$known } + $known = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase) + $ps = [PowerShell]::Create() + try { + $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. + 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. + 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') + [PkState]::PredefinedVariables = $known + return ,$known +} + +function Get-PkCommandVariables { + # The variables a command assigns by name, where the name is written out: + # -OutVariable x and the like, Set-Variable x, Import-LocalizedData x. + param([System.Management.Automation.Language.CommandAst]$Command) + $fillers = @('OutVariable', 'ErrorVariable', 'WarningVariable', 'InformationVariable', 'PipelineVariable', + 'SessionVariable', 'ResponseHeadersVariable', 'StatusCodeVariable', 'BindingVariable', 'Variable') + $fillerAliases = @('ov', 'ev', 'wv', 'iv', 'pv', 'rhv', 'sv') + $namesFirst = $Command.GetCommandName() -in @('Set-Variable', 'New-Variable', 'sv', 'nv', 'set', 'Import-LocalizedData') + # Those commands' other parameters that take a value, so it isn't read as + # 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 + $positionalDone = $false + foreach ($element in ($Command.CommandElements | Select-Object -Skip 1)) { + $value = $element + if ($element -is [System.Management.Automation.Language.CommandParameterAst]) { + $parameter = $element.ParameterName + $kind = '' + # Shortened names too (-ErrorVar), as PowerShell takes them. + if ($parameter -in $fillerAliases -or ($parameter.Length -ge 4 -and @($fillers -like ($parameter + '*')).Count -gt 0)) { $kind = 'name' } + elseif ($namesFirst -and 'Name' -like ($parameter + '*')) { $kind = 'name'; $positionalDone = $true } + elseif (@($takesValue -like ($parameter + '*')).Count -gt 0) { $kind = 'value' } + $expect = '' + if ($null -eq $element.Argument) { $expect = $kind; continue } + $value = $element.Argument + } else { + $kind = $expect + $expect = '' + if ($kind -eq '' -and $namesFirst -and -not $positionalDone) { $kind = 'name'; $positionalDone = $true } + } + if ($kind -ne 'name') { continue } + $items = @($value) + if ($value -is [System.Management.Automation.Language.ArrayLiteralAst]) { $items = @($value.Elements) } + foreach ($item in $items) { + if ($item -is [System.Management.Automation.Language.StringConstantExpressionAst]) { $item.Value.TrimStart('+') -replace '^(global|script|local|private):', '' } + } + } +} + +function Get-PkUndeclaredVariables { + # 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. + param([System.Management.Automation.Language.Ast]$Ast) + $declared = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase) + $reads = [System.Collections.Generic.List[object]]::new() + $targets = [System.Collections.Generic.Stack[object]]::new() + foreach ($node in $Ast.FindAll({ $true }, $true)) { + switch ($node.GetType().Name) { + 'VariableExpressionAst' { $reads.Add($node) } + 'ParameterAst' { $targets.Push($node.Name) } + 'AssignmentStatementAst' { $targets.Push($node.Left) } + 'ForEachStatementAst' { $targets.Push($node.Variable) } + 'DataStatementAst' { if ($node.Variable) { $null = $declared.Add($node.Variable) } } + 'UnaryExpressionAst' { if ([string]$node.TokenKind -match '^(Prefix|Postfix)?(PlusPlus|MinusMinus)$') { $targets.Push($node.Child) } } + 'ConvertExpressionAst' { if ($node.Type.TypeName.FullName -eq 'ref') { $targets.Push($node.Child) } } + 'CommandAst' { foreach ($name in (Get-PkCommandVariables -Command $node)) { $null = $declared.Add($name) } } + } + # An assignment's target, unwrapped: [int]$x, ($x) and $x, $y. Not + # $x.Key or $x[0], which read $x. + while ($targets.Count -gt 0) { + $target = $targets.Pop() + if ($target -is [System.Management.Automation.Language.VariableExpressionAst]) { $null = $declared.Add(($target.VariablePath.UserPath -replace '^(global|script|local|private|variable):', '')) } + elseif ($target -is [System.Management.Automation.Language.AttributedExpressionAst]) { $targets.Push($target.Child) } # [int]$x too: a convert is one of these + elseif ($target -is [System.Management.Automation.Language.ArrayLiteralAst]) { foreach ($element in $target.Elements) { $targets.Push($element) } } + elseif ($target -is [System.Management.Automation.Language.CommandExpressionAst]) { $targets.Push($target.Expression) } + elseif ($target -is [System.Management.Automation.Language.PipelineAst] -and $target.PipelineElements.Count -eq 1) { $targets.Push($target.PipelineElements[0]) } + elseif ($target -is [System.Management.Automation.Language.ParenExpressionAst]) { $targets.Push($target.Pipeline) } + } + } + $predefined = Get-PkPredefinedVariables + foreach ($read in $reads) { + $path = $read.VariablePath + if ($path.IsDriveQualified -or $path.IsGlobal -or $path.UserPath -like 'variable:*') { continue } # PowerShell doesn't count Variable: as a drive there + $name = $path.UserPath -replace '^(script|local|private):', '' + if (-not $declared.Contains($name) -and -not $predefined.Contains($name)) { $read } + } +} + function Test-PkWorkerSafety { # .SYNOPSIS # Checks worker code against the worker rules without running it. @@ -4056,8 +4165,12 @@ function Test-PkWorkerSafety { # worker, uses $script: # DelegateCast a scriptblock is cast to a .NET delegate, or passed into # a .NET method or constructor that turns it into one + # UndeclaredVariable the worker reads a variable it never declares or + # assigns: your script's variables, and what + # .GetNewClosure() captured, don't reach a worker # Put "# pk:ignore" on a line to accept a finding there. Commands run through a - # variable (& $cmd) aren't seen. + # variable (& $cmd) aren't seen. Variables count as assigned wherever in the + # worker that happens, and $global: ones aren't checked. # .PARAMETER WorkerScript # The worker scriptblock. # .PARAMETER SharedFunctionNames @@ -4166,6 +4279,22 @@ 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. + if ($t.IsWorkerBody) { + $closureNote = "" + if ($null -ne $WorkerScript.Module -and $WorkerScript.Module.Name -like '__DynamicModule_*') { $closureNote = ".GetNewClosure() doesn't carry variables into a worker: " } + $seenNames = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase) + foreach ($ref in (Get-PkUndeclaredVariables -Ast $ast)) { + if ($seenRefs.Contains($ref.Extent.StartOffset)) { continue } + if ($ref.Extent.StartScriptPosition.Line -match '#\s*pk:ignore') { continue } + if (-not $seenNames.Add($ref.VariablePath.UserPath)) { continue } + $findings.Add([pscustomobject][ordered]@{ Rule = 'UndeclaredVariable'; Where = $t.Where; Line = $ref.Extent.StartLineNumber + Text = ($t.Where + " (line " + $ref.Extent.StartLineNumber + ") reads `$" + $ref.VariablePath.UserPath + ", which it never declares or assigns, so it's empty in a worker - " + $closureNote + "pass it as a job value, or add '# pk:ignore' if something the worker runs sets it") }) + } + } + foreach ($cv in $ast.FindAll({ param($node) $node -is [System.Management.Automation.Language.ConvertExpressionAst] }, $true)) { if ($cv.Type.TypeName.Name -notmatch '^(System\.)?(Func|Action|Predicate|Comparison|Converter)(\[|`|$)') { continue } if ($cv.Extent.StartScriptPosition.Line -match '#\s*pk:ignore') { continue } diff --git a/README.md b/README.md index 4456982..1516d45 100644 --- a/README.md +++ b/README.md @@ -379,6 +379,7 @@ Each worker runs in its own runspace: a separate PowerShell session inside the s - If the worker declares a `$CancelToken` parameter, it gets the run's cancellation token. - `-JobParams` takes a list or array of job hashtables. A single hashtable works too, so a list that happens to hold one job is fine. - A worker runspace starts empty. Name every one of your functions it calls in `-SharedFunctionNames`. The kit's own worker functions are always there, and cmdlets and functions from installed modules load on their own. A module you imported by path isn't installed, so list its functions too (or put it on `$env:PSModulePath`). The kit looks each module up once per session, so one it didn't find and you then install is only seen in a new window. +- Your script's variables aren't in the worker either: pass what it needs as job values. `.GetNewClosure()` on the worker doesn't carry them over, since the worker is rebuilt from its text. A worker that reads a variable it never declares or assigns is refused; see [How the kit checks them](#the-two-rules-for-worker-code). - Each job starts in your current location (the real folder, if you're on a `New-PSDrive` drive), in a fresh scope. A folder change or a variable one job makes, preference variables like `$ErrorActionPreference` included, doesn't carry over to the next job. Relative paths in .NET calls such as `[System.IO.File]::ReadAllText('x.txt')` still go by the process's working directory, as they do outside workers, so give .NET full paths. - `-MaxParallel` has no default; you choose it. `-DrainTimeoutSeconds` (how long Ctrl+C waits for running workers) defaults to 60. The process engines' names, `-MaxConcurrent` and `-AbortTimeoutSeconds`, work here too. @@ -427,7 +428,7 @@ Everything else is fine in a worker, cmdlets included. Callbacks that run on the
How the kit checks them -`Invoke-PkRunspaceJobs` checks both rules before it starts anything, and refuses to launch code that breaks them, naming the line or the job key. Pass `-CheckWorkerSafety:$false` to turn that off. The code check is also available on its own as `Test-PkWorkerSafety -WorkerScript $w -SharedFunctionNames $names`, which returns a list of findings (including functions the worker calls but you didn't share), for use in your own tests. For rule 2 it flags written casts, and scriptblocks passed into a .NET method or constructor, either written in the call or through a variable they were assigned to. `# pk:ignore` on a line accepts a finding. Storing a scriptblock in a collection (`$list.Add($sb)`, `$queue.Enqueue($sb)`) isn't flagged, since that makes no delegate. It can't see commands run through a variable (`& $cmd`), a collection typed to hold delegates (`List[Func[object]]`, whose `.Add` converts), or a scriptblock buried more than three levels deep in a job value. +`Invoke-PkRunspaceJobs` checks both rules before it starts anything, and refuses to launch code that breaks them, naming the line or the job key. Pass `-CheckWorkerSafety:$false` to turn that off. The code check is also available on its own as `Test-PkWorkerSafety -WorkerScript $w -SharedFunctionNames $names`, which returns a list of findings (including functions the worker calls but you didn't share), for use in your own tests. For rule 2 it flags written casts, and scriptblocks passed into a .NET method or constructor, either written in the call or through a variable they were assigned to. `# pk:ignore` on a line accepts a finding. Storing a scriptblock in a collection (`$list.Add($sb)`, `$queue.Enqueue($sb)`) isn't flagged, since that makes no delegate. The check also refuses a worker that reads a variable it never declares or assigns anywhere (`UndeclaredVariable`), since it would read as empty: one of your script's, or one a `.GetNewClosure()` captured. Parameters, assignments, loop variables, `[ref]`, `-OutVariable` and its kind, `Set-Variable` with a literal name, and PowerShell's own variables all count as declared. `$global:` names and drive-qualified ones (`$env:`) aren't checked, and neither are shared functions, which may read their caller's variables. If something the worker runs sets the variable (a helper file it dot-sources, a module it imports), put `# pk:ignore` on the line that reads it. It can't see commands run through a variable (`& $cmd`), a collection typed to hold delegates (`List[Func[object]]`, whose `.Add` converts), or a scriptblock buried more than three levels deep in a job value.
From b409fa0ee8354de38516aa5cc864ab0e1d0ad542 Mon Sep 17 00:00:00 2001 From: Hal <22532613+HalRiveria@users.noreply.github.com> Date: Mon, 30 Nov 2026 15:31:23 -0500 Subject: [PATCH 2/2] Read module-qualified Set-Variable too in the undeclared-variable check Co-Authored-By: Claude Opus 5.5 --- ParallelKit.Harness.ps1 | 4 ++-- ParallelKit.ps1 | 3 ++- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/ParallelKit.Harness.ps1 b/ParallelKit.Harness.ps1 index 34a69cf..c9f132e 100644 --- a/ParallelKit.Harness.ps1 +++ b/ParallelKit.Harness.ps1 @@ -5646,11 +5646,11 @@ $blClean = [ordered]@{ 'foreach and for variables' = { foreach ($f in 1..2) { $f }; for ($n = 0; $n -lt 2; $n++) { $n } } 'the common parameters that fill a variable' = { Get-Item 'x' -OutVariable ov1 -ErrorVariable +ev1 -WarningVariable 'wv1' -InformationVariable:iv1 -PipelineVariable pv1 | ForEach-Object { "$ov1$ev1$wv1$iv1$pv1" } } 'their aliases, and a shortened name' = { Get-Item 'x' -ov ov2 -ev ev2 -wv wv2 -iv iv2 -pv pv2 -ErrorVar ev3 | ForEach-Object { "$ov2$ev2$wv2$iv2$pv2$ev3" } } - 'Set-Variable and New-Variable with a literal name' = { Set-Variable sv1 1; Set-Variable -Value 2 -Name sv2; New-Variable -Force 'nv1' 3; Set-Variable -Name sv3, sv4 -Value 1; sv sv5 1; Set-Variable -ErrorAction Stop -OutVariable sv6 sv7 1; "$sv1$sv2$nv1$sv3$sv4$sv5$sv6$sv7" } + 'Set-Variable and New-Variable with a literal name' = { Set-Variable sv1 1; Set-Variable -Value 2 -Name sv2; New-Variable -Force 'nv1' 3; Set-Variable -Name sv3, sv4 -Value 1; sv sv5 1; Set-Variable -ErrorAction Stop -OutVariable sv6 sv7 1; Microsoft.PowerShell.Utility\Set-Variable sv8 1; "$sv1$sv2$nv1$sv3$sv4$sv5$sv6$sv7$sv8" } 'Tee-Object, -SessionVariable, -ResponseHeadersVariable and -StatusCodeVariable' = { 1 | Tee-Object -Variable tee1; Invoke-RestMethod 'x' -SessionVariable se1 -ResponseHeadersVariable rh1 -StatusCodeVariable st1; "$tee1$se1$rh1$st1" } 'Import-LocalizedData, by name and by position, and a data block' = { Import-LocalizedData -BindingVariable text1; Import-LocalizedData text2; data text3 { 'x' }; "$text1$text2$text3" } '[ref]' = { param($Id) $null = [int]::TryParse($Id, [ref]$number); $number } - 'automatic variables' = { param($Id) @($Id) | ForEach-Object { $_; $PSItem }; if ('a' -match 'a') { $Matches[0] }; cmd /c exit 0; $LASTEXITCODE; $args; $input; $PSBoundParameters.Count; $MyInvocation; $Error; $PID; $HOME; $Host; $PSVersionTable; $?; $null; $true; $false; $switch; $foreach; $this; $PSCmdlet; $OFS; $PROFILE; $Event; $EventArgs; $Sender; $EventSubscriber; $SourceIdentifier; $ExecutionContext; $PSScriptRoot; $NestedPromptLevel; $StackTrace } + 'automatic variables' = { param($Id) @($Id) | ForEach-Object { $_; $PSItem }; if ('a' -match 'a') { $Matches[0] }; cmd /c exit 0; $LASTEXITCODE; $args; $input; $PSBoundParameters.Count; $MyInvocation; $Error; $PID; $HOME; $Host; $PSVersionTable; $?; $^; $$; $null; $true; $false; $switch; $foreach; $this; $PSCmdlet; $OFS; $PROFILE; $Event; $EventArgs; $Sender; $EventSubscriber; $SourceIdentifier; $ExecutionContext; $PSScriptRoot; $NestedPromptLevel; $StackTrace } 'preference variables' = { $ErrorActionPreference; $VerbosePreference; $ProgressPreference; $InformationPreference; $ConfirmPreference; $WhatIfPreference; $OutputEncoding; $PSDefaultParameterValues; $PSModuleAutoLoadingPreference } 'automatic variables only one of 5.1 and 7 has' = { if ($IsWindows -or $IsLinux -or $IsMacOS -or $IsCoreCLR) { $PSStyle }; $PSNativeCommandUseErrorActionPreference; $PSNativeCommandArgumentPassing; $EnabledExperimentalFeatures; $ConsoleFileName; $MaximumErrorCount } 'drive-qualified names, $global: ones and the kit''s own' = { $env:TEMP; ${function:prompt}; $variable:x; $global:shared; $PkCancelToken; $global:PkWorkerQueue } diff --git a/ParallelKit.ps1 b/ParallelKit.ps1 index 4dcc7ba..37bd6e4 100644 --- a/ParallelKit.ps1 +++ b/ParallelKit.ps1 @@ -4081,7 +4081,8 @@ function Get-PkCommandVariables { $fillers = @('OutVariable', 'ErrorVariable', 'WarningVariable', 'InformationVariable', 'PipelineVariable', 'SessionVariable', 'ResponseHeadersVariable', 'StatusCodeVariable', 'BindingVariable', 'Variable') $fillerAliases = @('ov', 'ev', 'wv', 'iv', 'pv', 'rhv', 'sv') - $namesFirst = $Command.GetCommandName() -in @('Set-Variable', 'New-Variable', 'sv', 'nv', 'set', 'Import-LocalizedData') + # Without a module prefix (Microsoft.PowerShell.Utility\Set-Variable). + $namesFirst = ([string]$Command.GetCommandName() -replace '^.*\\', '') -in @('Set-Variable', 'New-Variable', 'sv', 'nv', 'set', 'Import-LocalizedData') # Those commands' other parameters that take a value, so it isn't read as # the name. $takesValue = @('Value', 'Description', 'Option', 'Scope', 'Visibility', 'Include', 'Exclude', 'FileName', 'BaseDirectory', 'UICulture', 'SupportedCommand',