Skip to content

Accept a function's own scriptblock as -WorkerScript - #117

Merged
HalRiveria merged 9 commits into
mainfrom
fix/function-worker-script
Dec 3, 2026
Merged

HalRiveria merged 9 commits into
mainfrom
fix/function-worker-script

Conversation

@HalRiveria-Bot

Copy link
Copy Markdown
Collaborator

Depends on #116, merge after it.

What was wrong: a function's own scriptblock (${function:Name}) has the function itself (a FunctionDefinitionAst) as its .Ast. That has no .ParamBlock, so Invoke-PkRunspaceBatch saw no parameters:

  • A job with values was refused: "job 0 supplies 'Id', but -WorkerScript's param() block doesn't declare it."
  • With @{} jobs it ran, but a declared $CancelToken read $null, and mandatory parameters weren't checked up front.

Test-PkWorkerSafety also counted the function's own body as a nested function, so a $script: at its top level was flagged as ScriptVariable. The same body as a { } block isn't flagged, and the README says the top level is fine. The worker itself would run: the scriptblock's text is param(...) ... for both function f { param(...) } and function f(...).

What changed:

  • The worker's parameters are read from function f($a) or from its body's param() block, as Get-PkHandlerParamCount already reads a callback's. Each now has a comment naming the other.
  • The safety check treats the function's own body as the worker's top level. A function defined inside the worker is still checked as before.

How it was tested: harness section BC runs ${function:Name} workers in both forms: a param() block with a $CancelToken, and function f([int]$Id, [Parameter(Mandatory)][string]$Name). It also checks a job missing the mandatory parameter is refused before anything starts, and runs Test-PkWorkerSafety on a top-level and a nested $script: in each form.

Before the fix (Windows PowerShell 5.1 and PowerShell 7, the same on both):

[FAIL] -WorkerScript ${function:Name} with a param() block: its jobs bind and CancelToken is filled in (, error: Invoke-PkRunspaceBatch: job 0 supplies 'Id', but -WorkerScript's param() block doesn't declare it. Nothing was started.)
[FAIL] and declared as function f(...) (, error: ... doesn't declare it. Nothing was started.)
[FAIL] and its missing mandatory parameter is refused before anything starts (... doesn't declare it. Nothing was started.)
[FAIL] ${function:Name}: $script: at the function's top level isn't flagged, in a nested block it is (... uses $script:bcFnNested ... | ... uses $script:bcFnCount ...)
[FAIL] and the same for function f(...) (... uses $script:bcFnCount ...)

After: all five pass. Sections K, P and BL (the rest of the safety check's tests) pass too.

Full harness: all 771 assertions pass on Windows PowerShell 5.1 and on PowerShell 7.

Batch-file quoting was picked by a pattern that needed a slash or the start of the path before 'cmd', so C:cmd.exe and C:cmd got the ordinary quoting, where a quote is written \" and cmd.exe doesn't honor it: an element like 'a" & echo X & "' ran a second command. The pattern now accepts a colon there too. Harness section AE runs the injection payload through C:cmd.exe, C:cmd and C:CMD.EXE. from System32.
…ecks

Request-PkAbort and Ctrl+C only raise a flag; the engines stop on their token, which Test-PkAbortSignal cancels, and each main loop called it only after its launch step. So an abort requested before a runspace batch, or by a -ResultHandler, -NextJobProvider or the dispatcher's -PollCallback, still started a round of workers or programs first, and one raised by -JobFinalize had the dispatcher ask -GroupProvider for more groups.

Both main loops now check the flag first, the dispatcher checks it again after -PollCallback, and the runspace engine's launch loop reads it per job. Harness section O covers each of those five cases.
…e it starts

With the dispatcher now checking for an abort before it asks for any group, a batch started while an abort is in force never handed its commands to the dispatcher, so they came back with no results. The batch now reports each one as aborted itself. The harness's aborted-group callback test raises its abort once the group is built, since one already in force means no group is asked for, and section O checks that case for the dispatcher.
…t exited

When a program's output reader couldn't start, the rollback stopped the program with Stop-PkProcessTree, which passes over a program that has already exited, so a child it left running was never stopped. The dispatcher's cleanup when a -JobStarter throws after starting a program had the same gap. Both now kill the program's tree job first, which reaches its children whether or not it is still running, and fall back to Stop-PkProcessTree only when it has none. The rollback now also releases the tree job's handle and disposes the process, as the dispatcher's cleanup already disposed it.

A test hook, PkStreamReadTask.TestFailRunDelayMs, holds the failing reader start so the program has exited by then; TypesVersion is 16. Harness section AW covers the rollback on both start paths and the dispatcher's cleanup.
Once a program exits, -KillTreeOnExit ends what it left running through the program's own Job Object, and discarded the result: if Windows wouldn't end that Job Object, the leftovers kept running with no sign, showing only as a stream timeout if they held the output. There is no fallback once the program is gone (taskkill /T finds children only through their parent), so it now warns, once per session, naming the process, like the warning for a program without a Job Object of its own.

A test hook, PkChildProcessJob.TestFailTerminate, makes TerminateJobObject count as refused. Harness section BJ covers the batch, the dispatcher and Invoke-PkProcessWithTimeout, and that the warning shows once. The README's -KillTreeOnExit paragraph mentions it.
A function's scriptblock (${function:Name}) has the function as its Ast, which has no ParamBlock, so Invoke-PkRunspaceBatch saw no parameters: a job with values was refused ("doesn't declare it"), a declared $CancelToken wasn't filled in, and mandatory parameters weren't checked up front. The worker-safety check also counted the function's own body as a nested function, so a $script: at its top level was flagged, though the same body as a { } block isn't.

The parameters are now read from function f($a) or from the body's param() block, as Get-PkHandlerParamCount already does for callbacks, and the safety check treats the function's own body as the worker's top level. Harness section BC covers both function forms.
Once a program exits, -KillTreeOnExit ends what it left running through the program's own Job Object, and discarded the result: if Windows wouldn't end that Job Object, the leftovers kept running with no sign, showing only as a stream timeout if they held the output. There is no fallback once the program is gone (taskkill /T finds children only through their parent), so it now warns, once per session, naming the process, like the warning for a program without a Job Object of its own.

A test hook, PkChildProcessJob.TestFailTerminate, makes TerminateJobObject count as refused. Harness section BJ covers the batch, the dispatcher and Invoke-PkProcessWithTimeout, and that the warning shows once. The README's -KillTreeOnExit paragraph mentions it.
@HalRiveria
HalRiveria force-pushed the fix/killtree-failure-warning branch from 8b69970 to 7325fae Compare December 3, 2026 00:53
Base automatically changed from fix/killtree-failure-warning to main December 3, 2026 01:02
@HalRiveria
HalRiveria merged commit 6d2776e into main Dec 3, 2026
3 checks passed
@HalRiveria
HalRiveria deleted the fix/function-worker-script branch December 3, 2026 01:06
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants