Repository navigation
Expand file tree
/
Copy pathParallelKit.Harness.ps1
More file actions
2826 lines (2629 loc) · 198 KB
/
Copy pathParallelKit.Harness.ps1
File metadata and controls
2826 lines (2629 loc) · 198 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Test harness for ParallelKit.ps1. Real runspaces and real child processes
# (cmd.exe / ping.exe), nothing mocked.
#
# powershell -NoProfile -File .\ParallelKit.Harness.ps1
#
# Exit code 0 = all passed, 1 = any failed.
$ErrorActionPreference = "Stop"
# The whole suite runs under strict mode: a host project may well use it,
# and the kit must not depend on lenient hashtable/variable reads.
Set-StrictMode -Version Latest
. (Join-Path $PSScriptRoot "ParallelKit.ps1")
$script:passCount = 0
$script:failCount = 0
$script:skipCount = 0
# A few checks need things only some machines have (a console of their own,
# say). Where they can't run they print [SKIP] with the reason. Set
# PK_HARNESS_NO_SKIP=1 to count every skip as a failure instead.
$script:noSkip = ($env:PK_HARNESS_NO_SKIP -eq '1')
function Test-Assert {
param([bool]$Condition, [string]$Message)
if ($Condition) {
$script:passCount++
Write-Host (" [PASS] " + $Message) -ForegroundColor Green
} else {
$script:failCount++
Write-Host (" [FAIL] " + $Message) -ForegroundColor Red
}
}
function Test-Skip {
param([string]$Message)
if ($script:noSkip) {
$script:failCount++
Write-Host (" [FAIL] " + $Message + " (skipping isn't allowed: PK_HARNESS_NO_SKIP=1)") -ForegroundColor Red
} else {
$script:skipCount++
Write-Host (" [SKIP] " + $Message) -ForegroundColor Yellow
}
}
# Every message the kit emits lands here instead of on the console.
$script:messages = [System.Collections.Generic.List[hashtable]]::new()
$messageSink = $script:messages
Set-PkMessageHandler -Handler { param($Message, $Level) $messageSink.Add(@{ Message = $Message; Level = $Level }) }.GetNewClosure()
function Reset-Harness {
Reset-PkAbortState
$script:messages.Clear()
}
function New-JobList {
param([hashtable[]]$Jobs)
$list = [System.Collections.Generic.List[hashtable]]::new()
foreach ($j in $Jobs) { $list.Add($j) }
return ,$list
}
$cmdExe = Join-Path $env:SystemRoot "System32\cmd.exe"
# Whichever PowerShell is running the harness (powershell.exe or pwsh.exe),
# for the tests that need a fresh process of the same version.
$selfExe = [System.Diagnostics.Process]::GetCurrentProcess().MainModule.FileName
$pingExe = Join-Path $env:SystemRoot "System32\ping.exe"
# A user function the workers share.
function Get-HarnessDouble {
param([int]$Value)
return ($Value * 2)
}
# ==============================================================================
Write-Host "=== A: setup ===" -ForegroundColor Cyan
$init = Initialize-ParallelKit -MaxConcurrentProcesses 8
Test-Assert ($init.AbortHandler -eq $true) "abort handler registers"
Test-Assert ($init.ChildProcessJob -eq $true) "child-process job object initializes"
Test-Assert ($init.ThreadPool -eq $true) "thread pool minimum is raised"
$w = 0; $io = 0
[System.Threading.ThreadPool]::GetMinThreads([ref]$w, [ref]$io)
Test-Assert ($w -ge 128) "thread pool minimum is at least 128 worker threads"
Write-Host ""
# ==============================================================================
Write-Host "=== B: runspace jobs - results, concurrency cap, messages, shared functions ===" -ForegroundColor Cyan
Reset-Harness
$track = @{ Cur = 0; Max = 0 }
$gate = [object]::new()
$worker = {
param([int]$Id, $Track, $Gate)
[System.Threading.Monitor]::Enter($Gate)
try { $Track.Cur++; if ($Track.Cur -gt $Track.Max) { $Track.Max = $Track.Cur } } finally { [System.Threading.Monitor]::Exit($Gate) }
[System.Threading.Thread]::Sleep(300)
[System.Threading.Monitor]::Enter($Gate)
try { $Track.Cur-- } finally { [System.Threading.Monitor]::Exit($Gate) }
Write-PkMessage ("worker " + $Id + " done")
return @{ Id = $Id; Doubled = (Get-HarnessDouble -Value $Id) }
}
$jobs = New-JobList -Jobs @(1..8 | ForEach-Object { @{ Id = $_; Track = $track; Gate = $gate } })
$results = [System.Collections.Generic.List[hashtable]]::new()
$out = Invoke-PkRunspaceJobs -WorkerScript $worker -JobParams $jobs -MaxParallel 3 -SharedFunctionNames @('Get-HarnessDouble') `
-ResultHandler { param($r) $results.Add($r) }.GetNewClosure() -CheckWorkerSafety
Test-Assert ($results.Count -eq 8) "all 8 jobs return a result"
$sum = 0; foreach ($r in $results) { $sum += $r.Doubled }
Test-Assert ($sum -eq 72) "the shared user function ran inside the workers (sum of doubles = 72)"
Test-Assert ($track.Max -le 3 -and $track.Max -ge 2) ("never more than MaxParallel workers at once (peak " + $track.Max + ")")
Test-Assert (@($script:messages | Where-Object { $_.Message -like 'worker * done' }).Count -eq 8) "all 8 worker messages reach the main-thread handler"
Test-Assert ($out.CrashedCount -eq 0 -and -not $out.Aborted -and $out.ForceStoppedCount -eq 0) "a clean run reports no crashes, no abort, nothing force-stopped"
Test-Assert ([PkState]::SourceCount -eq 0) "the run's own cancellation source is unregistered afterwards"
Write-Host ""
# ==============================================================================
Write-Host "=== C: runspace jobs - lazy provider, crash handling, bad input ===" -ForegroundColor Cyan
Reset-Harness
$feed = @{ Next = 1 }
$provider = { if ($feed.Next -gt 5) { return $null }; $j = @{ Id = $feed.Next }; $feed.Next++; return $j }.GetNewClosure()
$results = [System.Collections.Generic.List[object]]::new()
$out = Invoke-PkRunspaceJobs -WorkerScript { param([int]$Id) return $Id } -NextJobProvider $provider -MaxParallel 2 `
-ResultHandler { param($r) $results.Add($r) }.GetNewClosure()
Test-Assert ($results.Count -eq 5) "-NextJobProvider feeds jobs until it returns null"
$crashes = [System.Collections.Generic.List[object]]::new()
$results = [System.Collections.Generic.List[object]]::new()
$jobs = New-JobList -Jobs @(@{ Id = 1 }, @{ Id = 2 }, @{ Id = 3 })
$out = Invoke-PkRunspaceJobs -WorkerScript { param([int]$Id) if ($Id -eq 2) { throw "boom" }; return $Id } -JobParams $jobs -MaxParallel 2 `
-ResultHandler { param($r) $results.Add($r) }.GetNewClosure() -JobCrashedHandler { param($e) $crashes.Add($e) }.GetNewClosure()
Test-Assert ($out.CrashedCount -eq 1 -and $crashes.Count -eq 1) "a worker that throws is counted and reported to -JobCrashedHandler"
Test-Assert ($results.Count -eq 2) "the other workers still return their results"
Test-Assert (@($script:messages | Where-Object { $_.Level -eq 'Error' -and $_.Message -like '*boom*' }).Count -eq 1) "the crash is reported as an Error message"
# Which job crashed: on the return object, and to a handler that asks for it.
$crashedProp = $out.PSObject.Properties['Crashed'] # read safely: strict mode throws on a missing property
Test-Assert ($null -ne $crashedProp -and @($crashedProp.Value).Count -eq 1 -and $crashedProp.Value[0].Job['Id'] -eq 2 -and $crashedProp.Value[0].Error -is [System.Management.Automation.ErrorRecord]) "the return object lists the crashed job and its error"
$crashWorker = { param([int]$Id) if ($Id -eq 2) { throw "boom" }; return $Id }
$seenJobs = [System.Collections.Generic.List[object]]::new()
$null = Invoke-PkRunspaceJobs -WorkerScript $crashWorker -JobParams $jobs -MaxParallel 2 -JobCrashedHandler { param($e, $job) $seenJobs.Add($job) }.GetNewClosure()
Test-Assert ($seenJobs.Count -eq 1 -and $null -ne $seenJobs[0] -and $seenJobs[0]['Id'] -eq 2) "a -JobCrashedHandler with a second parameter gets the job that crashed"
$seenArgs = @{ Count = -1; Id = $null }
$null = Invoke-PkRunspaceJobs -WorkerScript $crashWorker -JobParams $jobs -MaxParallel 2 -JobCrashedHandler { $seenArgs.Count = $args.Count; $seenArgs.Id = $args[1]['Id'] }.GetNewClosure()
Test-Assert ($seenArgs.Count -eq 2 -and $seenArgs.Id -eq 2) ("a -JobCrashedHandler with no param() gets the error and the job in `$args (count " + $seenArgs.Count + ")")
# One-parameter handlers that would throw on a second argument still work.
$advanced = @{ Calls = 0 }
$null = Invoke-PkRunspaceJobs -WorkerScript $crashWorker -JobParams $jobs -MaxParallel 2 -JobCrashedHandler { [CmdletBinding()] param($e) $advanced.Calls++ }.GetNewClosure()
Test-Assert ($advanced.Calls -eq 1) "a one-parameter [CmdletBinding()] -JobCrashedHandler is still called"
function Receive-HarnessCrash($e, $job) { $script:harnessCrashId = $job['Id'] }
$script:harnessCrashId = $null
$null = Invoke-PkRunspaceJobs -WorkerScript $crashWorker -JobParams $jobs -MaxParallel 2 -JobCrashedHandler ${function:Receive-HarnessCrash}
Test-Assert ($script:harnessCrashId -eq 2) "a function used as -JobCrashedHandler, with function f(`$e, `$job) parameters, gets the job"
# A handler that throws is reported, not swallowed.
Reset-Harness
$null = Invoke-PkRunspaceJobs -WorkerScript $crashWorker -JobParams $jobs -MaxParallel 2 -JobCrashedHandler { param($e) throw "handler bug" }
Test-Assert (@($script:messages | Where-Object { $_.Message -like '*-JobCrashedHandler threw*handler bug*' }).Count -eq 1) "a -JobCrashedHandler that throws is reported as a message"
# Workers that throw while an abort waits for them count as crashes too.
Reset-Harness
$poll = @{ Count = 0 }
$drainCrashes = [System.Collections.Generic.List[object]]::new()
$drainOut = Invoke-PkRunspaceJobs -MaxParallel 2 -JobParams (New-JobList -Jobs @(@{ Id = 1 }, @{ Id = 2 })) -WorkerScript {
param([int]$Id)
for ($i = 0; $i -lt 100; $i++) { if (Test-PkCancelRequested) { break }; [System.Threading.Thread]::Sleep(50) }
[System.Threading.Thread]::Sleep(500)
throw ("drain boom " + $Id)
} -PollCallback { $poll.Count++; if ($poll.Count -eq 3) { Request-PkAbort } }.GetNewClosure() -JobCrashedHandler { param($e, $job) $drainCrashes.Add($job['Id']) }.GetNewClosure()
$drainCrashedProp = $drainOut.PSObject.Properties['Crashed']
Test-Assert ($drainOut.Aborted -and $drainOut.CrashedCount -eq 2 -and $null -ne $drainCrashedProp -and @($drainCrashedProp.Value).Count -eq 2 -and $drainCrashes.Count -eq 2) ("workers that throw during an abort's drain are counted and reported (counted " + $drainOut.CrashedCount + ", handler calls " + $drainCrashes.Count + ")")
Reset-Harness
$threw = $false
try { $null = Invoke-PkRunspaceJobs -WorkerScript { param($Id) } -JobParams (New-JobList -Jobs @(@{ Id = 1 })) -MaxParallel 1 -SharedFunctionNames @('No-SuchFunction') } catch { $threw = ($_.ToString() -like "*No-SuchFunction*") }
Test-Assert $threw "an unknown -SharedFunctionNames entry fails up front with the name in the message"
$threw = $false
try { $null = Invoke-PkRunspaceJobs -WorkerScript { param($Id) } -JobParams (New-JobList -Jobs @(@{ Id = 1; Extra = 2 })) -MaxParallel 1 } catch { $threw = ($_.ToString() -like "*Extra*") }
Test-Assert $threw "a job key the worker doesn't declare fails with a clear message"
$emptyOut = Invoke-PkRunspaceJobs -WorkerScript { param($Id) } -JobParams ([System.Collections.Generic.List[hashtable]]::new()) -MaxParallel 1
Test-Assert ($emptyOut.CrashedCount -eq 0 -and -not $emptyOut.Aborted) "an empty job list returns immediately"
Write-Host ""
# ==============================================================================
Write-Host "=== D: runspace jobs - abort ===" -ForegroundColor Cyan
Reset-Harness
# Cooperative workers: stop as soon as they see the cancel.
$worker = {
param([int]$Id, $CancelToken)
for ($i = 0; $i -lt 100; $i++) {
if (Test-PkCancelRequested) { return @{ Id = $Id; Stopped = $true; TokenSeen = ($CancelToken -is [System.Threading.CancellationToken] -and $CancelToken.CanBeCanceled) } }
[System.Threading.Thread]::Sleep(100)
}
return @{ Id = $Id; Stopped = $false }
}
$jobs = New-JobList -Jobs @(1..6 | ForEach-Object { @{ Id = $_ } })
$results = [System.Collections.Generic.List[hashtable]]::new()
$poll = @{ Count = 0 }
$sw = [System.Diagnostics.Stopwatch]::StartNew()
$out = Invoke-PkRunspaceJobs -WorkerScript $worker -JobParams $jobs -MaxParallel 2 `
-ResultHandler { param($r) $results.Add($r) }.GetNewClosure() `
-PollCallback { $poll.Count++; if ($poll.Count -eq 5) { Request-PkAbort } }.GetNewClosure()
$sw.Stop()
Test-Assert ($out.Aborted -eq $true) "an abort mid-run is reported as Aborted"
Test-Assert ($results.Count -eq 2) ("only the 2 in-flight workers ran; the other 4 never started (got " + $results.Count + ")")
Test-Assert (@($results | Where-Object { $_.Stopped }).Count -eq 2) "in-flight workers saw the cancel and stopped early"
Test-Assert (@($results | Where-Object { $_.TokenSeen }).Count -eq 2) "a declared `$CancelToken parameter receives the run's token"
Test-Assert ($out.ForceStoppedCount -eq 0) "cooperative workers are not force-stopped"
Test-Assert ($sw.Elapsed.TotalSeconds -lt 8) ("the run ends promptly after the abort (" + [int]$sw.Elapsed.TotalSeconds + "s)")
Test-Assert (@($script:messages | Where-Object { $_.Message -like '*Abort requested*' }).Count -eq 1) "the abort is announced exactly once"
# A worker that ignores the cancel gets force-stopped after the drain timeout.
Reset-Harness
$poll = @{ Count = 0 }
$sw = [System.Diagnostics.Stopwatch]::StartNew()
$out = Invoke-PkRunspaceJobs -WorkerScript { param([int]$Id) [System.Threading.Thread]::Sleep(6000); return $Id } `
-JobParams (New-JobList -Jobs @(@{ Id = 1 }, @{ Id = 2 })) -MaxParallel 2 -DrainTimeoutSeconds 1 `
-PollCallback { $poll.Count++; if ($poll.Count -eq 3) { Request-PkAbort } }.GetNewClosure()
$sw.Stop()
Test-Assert ($out.ForceStoppedCount -eq 2) "workers that ignore the cancel are force-stopped after the drain timeout"
Test-Assert (@($script:messages | Where-Object { $_.Message -like '*Force-stopping 2 job(s)*' }).Count -eq 1) "the force-stop is announced"
Test-Assert ($sw.Elapsed.TotalSeconds -lt 4) ("force-stopped workers are abandoned, not waited for (took " + [math]::Round($sw.Elapsed.TotalSeconds, 1) + "s; the workers sleep 6s)")
Write-Host ""
# ==============================================================================
Write-Host "=== E: single processes ===" -ForegroundColor Cyan
Reset-Harness
$r = Invoke-PkProcessWithTimeout -FilePath $cmdExe -Arguments '/c echo hello& echo oops 1>&2& exit 3'
Test-Assert ($r.ExitCode -eq 3) "exit code is captured"
Test-Assert ($r.Stdout.Trim() -eq 'hello') "stdout is captured"
Test-Assert ($r.Stderr.Trim() -eq 'oops') "stderr is captured"
$threw = $false
$sw = [System.Diagnostics.Stopwatch]::StartNew()
try { $null = Invoke-PkProcessWithTimeout -FilePath $pingExe -Arguments '-n 30 127.0.0.1' -TimeoutMs 800 } catch { $threw = ($_.ToString() -like '*did not exit within*') }
$sw.Stop()
Test-Assert ($threw -and $sw.Elapsed.TotalSeconds -lt 6) "a process that overruns its time limit is killed and reported"
$threw = $false
try { $null = Start-PkProcess -FilePath 'C:\no\such\program.exe' } catch { $threw = ($_.ToString() -like "*could not start*") }
Test-Assert $threw "a program that can't be started throws a clear error (not a silent null)"
$j = Start-PkProcess -FilePath $cmdExe -Arguments '/c exit 0'
$null = Wait-PkProcess -Process $j.Proc -TimeoutMs 5000
Test-Assert ([PkChildProcessJob]::Assign($j.Proc) -or $j.Proc.HasExited) "started processes are tied to the job object"
$j.Proc.Dispose()
# ConvertTo-PkArgumentString: exact output for the tricky cases, then a
# round trip through a real program that prints each argument it received.
Test-Assert ((ConvertTo-PkArgumentString @('plain', 'two words', '')) -eq 'plain "two words" ""') "arguments with spaces are quoted, empty ones become `"`""
Test-Assert ((ConvertTo-PkArgumentString @('C:\dir with space\')) -eq '"C:\dir with space\\"') "a trailing backslash is doubled inside quotes"
Test-Assert ((ConvertTo-PkArgumentString @('say "hi"', 'a\"b')) -eq '"say \"hi\"" "a\\\"b"') "quotes are escaped, and backslashes before them doubled"
Test-Assert ((ConvertTo-PkArgumentString @('C:\no\spaces\')) -eq 'C:\no\spaces\') "an argument that needs no quotes is left alone"
# Built with the .NET Framework's csc.exe (on every Windows machine) rather
# than Add-Type, which can't build an .exe under PowerShell 7.
$argvExe = Join-Path $env:TEMP ("pk-argv-" + [guid]::NewGuid().ToString("N") + ".exe")
$argvSrc = [System.IO.Path]::ChangeExtension($argvExe, '.cs')
[System.IO.File]::WriteAllText($argvSrc, 'public static class PkArgv { public static void Main(string[] args) { foreach (string a in args) { System.Console.WriteLine("[" + a + "]"); } } }')
$cscExe = Join-Path $env:SystemRoot 'Microsoft.NET\Framework64\v4.0.30319\csc.exe'
$csc = $null
try { $csc = Invoke-PkProcessWithTimeout -FilePath $cscExe -Arguments (ConvertTo-PkArgumentString @('/nologo', ('/out:' + $argvExe), $argvSrc)) } catch { Write-Host " csc.exe failed to run: $_" }
[System.IO.File]::Delete($argvSrc)
$compiled = ($null -ne $csc -and $csc.ExitCode -eq 0 -and [System.IO.File]::Exists($argvExe))
Test-Assert $compiled "the argument-printing test program compiles"
if ($compiled) {
$tricky = @('plain', 'two words', '', 'C:\dir with space\', 'say "hi"', 'a\"b', 'tab here', 'x\\y', '\\server\share\')
$r = Invoke-PkProcessWithTimeout -FilePath $argvExe -Arguments (ConvertTo-PkArgumentString $tricky)
$received = @(([string]$r.Stdout).Split([string[]]@("`r`n"), [System.StringSplitOptions]::RemoveEmptyEntries))
$expected = @($tricky | ForEach-Object { "[" + $_ + "]" })
Test-Assert (($received -join '|') -eq ($expected -join '|')) ("a program receives exactly the arguments given (got " + ($received -join ' ') + ")")
try { [System.IO.File]::Delete($argvExe) } catch { } # temp file only; best effort
}
# -OutputEncoding: a program that writes UTF-8 bytes comes back intact when
# told so, and garbled when decoded as code page 437 (a default console).
$u8Exe = Join-Path $env:TEMP ("pk-u8-" + [guid]::NewGuid().ToString("N") + ".exe")
$u8Src = [System.IO.Path]::ChangeExtension($u8Exe, '.cs')
[System.IO.File]::WriteAllText($u8Src, 'public static class PkU8 { public static void Main() { string t = new string(new char[] { (char)0x63, (char)0x61, (char)0x66, (char)0xE9, (char)0x20, (char)0x65E5, (char)0x672C, (char)0x8A9E }); byte[] b = new System.Text.UTF8Encoding(false).GetBytes(t); var o = System.Console.OpenStandardOutput(); o.Write(b, 0, b.Length); o.Flush(); var e = System.Console.OpenStandardError(); e.Write(b, 0, b.Length); e.Flush(); } }')
$csc = $null
try { $csc = Invoke-PkProcessWithTimeout -FilePath $cscExe -Arguments (ConvertTo-PkArgumentString @('/nologo', ('/out:' + $u8Exe), $u8Src)) } catch { Write-Host " csc.exe failed to run: $_" }
[System.IO.File]::Delete($u8Src)
$compiled = ($null -ne $csc -and $csc.ExitCode -eq 0 -and [System.IO.File]::Exists($u8Exe))
Test-Assert $compiled "the UTF-8 test program compiles"
if ($compiled) {
$u8Text = 'caf' + [char]0xE9 + ' ' + [char]0x65E5 + [char]0x672C + [char]0x8A9E
$r = Invoke-PkProcessWithTimeout -FilePath $u8Exe -OutputEncoding 'utf-8'
$codes = { param($s) (([string]$s).ToCharArray() | ForEach-Object { '{0:X4}' -f [int]$_ }) -join ' ' }
Test-Assert ($r.Stdout -eq $u8Text -and $r.Stderr -eq $u8Text) ("-OutputEncoding 'utf-8' decodes a program's UTF-8 output, stdout and stderr (got " + (& $codes $r.Stdout) + " / " + (& $codes $r.Stderr) + ")")
$r = Invoke-PkProcessWithTimeout -FilePath $u8Exe -OutputEncoding 437
Test-Assert ($r.Stdout -ne $u8Text) "and decoding it as code page 437 garbles it, so the option really takes effect"
$batch = Invoke-PkProcessBatch -OutputEncoding 'utf8' -Commands @(@{ FilePath = $u8Exe; Name = 'default' }, @{ FilePath = $u8Exe; Name = 'own'; OutputEncoding = 437 })
$byName = @{}; foreach ($br in $batch.Results) { $byName[$br.Command['Name']] = $br.Stdout }
Test-Assert ($byName['default'] -eq $u8Text -and $byName['own'] -ne $u8Text) "batch: -OutputEncoding applies to every command, and a command's own OutputEncoding key overrides it"
try { [System.IO.File]::Delete($u8Exe) } catch { } # temp file only; best effort
}
Test-Assert ((& (Get-Module ParallelKit) Resolve-PkEncoding -Encoding '437').CodePage -eq 437) "a code page given as text ('437') is accepted"
# -OutputEncoding mustn't replace PowerShell's own $OutputEncoding inside the
# caller's callbacks.
$seen = @{ Value = 'unset' }
$null = Invoke-PkProcessBatch -OutputEncoding 'utf-8' -Commands @(@{ FilePath = $cmdExe; Arguments = '/c exit 0' }) -OnComplete { param($c, $r) $seen.Value = $OutputEncoding }.GetNewClosure()
Test-Assert ($seen.Value -is [System.Text.Encoding]) ("inside -OnComplete, `$OutputEncoding is still PowerShell's own (got [" + $seen.Value + "])")
$seen.Value = 'unset'
$null = Invoke-PkProcessBatch -Commands @(@{ FilePath = $cmdExe; Arguments = '/c exit 0' }) -OnComplete { param($c, $r) $seen.Value = $OutputEncoding }
Test-Assert ($seen.Value -is [System.Text.Encoding]) ("and in an -OnComplete without .GetNewClosure() too (got [" + $seen.Value + "])")
$threw = $false
try { $null = Invoke-PkProcessBatch -OutputEncoding 'no-such-encoding' -Commands @(@{ FilePath = $cmdExe; Arguments = '/c exit 0' }) } catch { $threw = ($_.ToString() -like "*'no-such-encoding' isn't an encoding*") }
Test-Assert $threw "an unknown -OutputEncoding fails the call with a clear message"
Write-Host ""
# ==============================================================================
Write-Host "=== F: process batch ===" -ForegroundColor Cyan
Reset-Harness
$commands = @(0..5 | ForEach-Object { @{ FilePath = $cmdExe; Arguments = ('/c echo item' + $_ + '& exit ' + $_); Tag = $_ } })
$commands += @{ FilePath = 'C:\no\such\program.exe'; Arguments = ''; Tag = 99 }
$seen = [System.Collections.Generic.List[int]]::new()
$batch = Invoke-PkProcessBatch -Commands $commands -MaxConcurrent 3 -OnComplete { param($c, $r) $seen.Add($c.Tag) }.GetNewClosure()
Test-Assert ($batch.Results.Count -eq 7) "every command gets a result"
$byTag = @{}; foreach ($r in $batch.Results) { $byTag[$r.Command.Tag] = $r }
Test-Assert ($byTag[4].ExitCode -eq 4 -and $byTag[4].Stdout.Trim() -eq 'item4') "each result carries its own command, exit code and output"
Test-Assert ($null -eq $byTag[99].ExitCode -and $byTag[99].StartError) "a command that can't start is reported, not dropped"
Test-Assert ($seen.Count -eq 6) "-OnComplete fires for each command that ran"
Test-Assert (-not $batch.Aborted) "a clean batch is not marked aborted"
$wd = Invoke-PkProcessBatch -Commands @(@{ FilePath = $cmdExe; Arguments = '/c cd'; WorkingDirectory = $env:SystemRoot }) -MaxConcurrent 1
Test-Assert ($wd.Results[0].Stdout.Trim() -ieq $env:SystemRoot) "a command's WorkingDirectory is honored"
# A foreach over nothing yields $null, not an empty array - the usual way to build the list when no files match.
$noCommands = foreach ($x in @()) { @{ FilePath = $cmdExe; Arguments = '/c exit 0' } }
$emptyBatch = $null
try { $emptyBatch = Invoke-PkProcessBatch -Commands $noCommands -MaxConcurrent 2 } catch { Write-Host " empty batch threw: $_" }
Test-Assert ($null -ne $emptyBatch -and $emptyBatch.Results.Count -eq 0 -and -not $emptyBatch.Aborted) "a batch given `$null (an empty foreach) returns no results"
Write-Host ""
# ==============================================================================
Write-Host "=== G: process dispatch - groups, limits, retries ===" -ForegroundColor Cyan
Reset-Harness
# 4 groups: 3 jobs, 0 jobs, 2 jobs, 1 job (which is retried once).
$groupDefs = @(
@{ Name = 'g1'; Count = 3 }, @{ Name = 'g2'; Count = 0 }, @{ Name = 'g3'; Count = 2 }, @{ Name = 'g4'; Count = 1; Retry = $true }
)
$feed = @{ Index = 0 }
$track = @{ Max = 0; Finalized = 0; Retried = 0 }
$completed = [System.Collections.Generic.List[string]]::new()
$dispatch = Invoke-PkProcessDispatch -MaxConcurrent 2 -MaxQueueAhead 2 `
-GroupProvider { if ($feed.Index -ge $groupDefs.Count) { return $null }; $g = $groupDefs[$feed.Index]; $feed.Index++; return $g }.GetNewClosure() `
-JobBuilder {
param($group)
$jobs = [System.Collections.Generic.List[hashtable]]::new()
for ($i = 0; $i -lt $group.Count; $i++) { $jobs.Add(@{ FilePath = $pingExe; Arguments = '-n 2 127.0.0.1'; Retry = [bool]$group.Retry }) }
return $jobs
}.GetNewClosure() `
-AbortPollCallback { param($running) if ($running.Count -gt $track.Max) { $track.Max = $running.Count } }.GetNewClosure() `
-JobFinalize {
param($job, $pending)
$r = Complete-PkProcess -Job $job
if ($job.Retry) {
$track.Retried++
$pending.Enqueue(@{ FilePath = $pingExe; Arguments = '-n 1 127.0.0.1'; Retry = $false; GroupKey = $job.GroupKey })
return @{ Requeued = $true }
}
$track.Finalized++
return @{ Success = ($r.ExitCode -eq 0) }
}.GetNewClosure() `
-GroupCompleteCallback { param($group) $completed.Add($group.Name) }.GetNewClosure()
Test-Assert ($track.Finalized -eq 6) ("all 6 jobs are finalized, the retried one once (got " + $track.Finalized + ")")
Test-Assert ($track.Retried -eq 1) "a job that returns Requeued is run again"
Test-Assert ($track.Max -eq 2) ("never more than MaxConcurrent processes at once (peak " + $track.Max + ")")
Test-Assert ($completed.Count -eq 4 -and ($completed -contains 'g2')) "every group completes, including the zero-job one"
Test-Assert ($completed.IndexOf('g4') -eq 3) "a group with a requeued job completes only after the retry finishes"
Test-Assert ($dispatch.GroupResults.Count -eq 4 -and -not $dispatch.Aborted) "one result per group, not aborted"
Test-Assert ([PkState]::SourceCount -eq 0) "the dispatcher's own cancellation source is unregistered afterwards"
# A job that can't start is counted and its group still completes.
Reset-Harness
$feed = @{ Given = $false }
$completed = [System.Collections.Generic.List[string]]::new()
$dispatch = Invoke-PkProcessDispatch -MaxConcurrent 2 `
-GroupProvider { if ($feed.Given) { return $null }; $feed.Given = $true; return @{ Name = 'bad' } }.GetNewClosure() `
-JobBuilder { param($g) return @(@{ FilePath = 'C:\no\such\program.exe'; Arguments = '' }, @{ FilePath = $cmdExe; Arguments = '/c exit 0' }) }.GetNewClosure() `
-JobFinalize { param($job, $pending) $null = Complete-PkProcess -Job $job } `
-GroupCompleteCallback { param($group) $completed.Add($group.Name) }.GetNewClosure()
Test-Assert ($dispatch.JobStarterFailedCount -eq 1) "a job that fails to start is counted"
Test-Assert ($completed.Count -eq 1) "its group still completes once the other job finishes"
Test-Assert (@($script:messages | Where-Object { $_.Level -eq 'Error' -and $_.Message -like '*JobStarter failed*' }).Count -eq 1) "the start failure is reported as an Error message"
foreach ($bad in @(0, -1, 'x')) {
$threw = $false
try { $null = Invoke-PkProcessDispatch -MaxConcurrent $bad -GroupProvider { return $null } -JobBuilder { param($g) } -JobFinalize { param($j, $p) } } catch { $threw = ($_.ToString() -like '*-MaxConcurrent must be*') }
Test-Assert $threw ("-MaxConcurrent '" + $bad + "' is refused up front instead of spinning forever")
}
$threw = $false
try { $null = Invoke-PkProcessDispatch -MaxConcurrent 1 -MaxQueueAhead 0 -GroupProvider { return $null } -JobBuilder { param($g) } -JobFinalize { param($j, $p) } } catch { $threw = ($_.ToString() -like '*-MaxQueueAhead must be*') }
Test-Assert $threw "-MaxQueueAhead 0 is refused up front"
# Zero-job groups hold their queue-ahead slot until released.
Reset-Harness
$feed = @{ Index = 0 }
$released = [System.Collections.Generic.HashSet[int]]::new()
$pulledAtFirstRelease = @{ Value = -1 }
$ticks = @{ Count = 0 }
$dispatch = Invoke-PkProcessDispatch -MaxConcurrent 1 -MaxQueueAhead 2 `
-GroupProvider { if ($feed.Index -ge 6) { return $null }; $g = @{ Id = $feed.Index }; $feed.Index++; return $g }.GetNewClosure() `
-JobBuilder { param($g) return @() } `
-JobFinalize { param($job, $pending) } `
-GroupReleaseCheck { param($g) return $released.Contains($g.Id) }.GetNewClosure() `
-AbortPollCallback {
param($running)
$ticks.Count++
if ($ticks.Count -eq 4) { $pulledAtFirstRelease.Value = $feed.Index }
if ($ticks.Count -ge 4) { for ($i = 0; $i -lt 6; $i++) { $null = $released.Add($i) } }
}.GetNewClosure()
Test-Assert ($pulledAtFirstRelease.Value -eq 2) ("with -GroupReleaseCheck, zero-job groups can't run ahead of MaxQueueAhead (pulled " + $pulledAtFirstRelease.Value + " before release)")
Test-Assert ($dispatch.GroupResults.Count -eq 6) "all groups complete once released"
Write-Host ""
# ==============================================================================
Write-Host "=== H: process dispatch - abort ===" -ForegroundColor Cyan
Reset-Harness
$feed = @{ Given = $false }
$cleaned = @{ Count = 0 }
$ticks = @{ Count = 0 }
$sw = [System.Diagnostics.Stopwatch]::StartNew()
$dispatch = Invoke-PkProcessDispatch -MaxConcurrent 2 -AbortTimeoutSeconds 1 `
-GroupProvider { if ($feed.Given) { return $null }; $feed.Given = $true; return @{ Name = 'slow' } }.GetNewClosure() `
-JobBuilder { param($g) return @(1..5 | ForEach-Object { @{ FilePath = $pingExe; Arguments = '-n 30 127.0.0.1' } }) }.GetNewClosure() `
-JobFinalize { param($job, $pending) $null = Complete-PkProcess -Job $job } `
-JobAbortCleanup { param($job) $cleaned.Count++ }.GetNewClosure() `
-AbortPollCallback { param($running) $ticks.Count++; if ($ticks.Count -eq 6) { Request-PkAbort } }.GetNewClosure()
$sw.Stop()
Test-Assert ($dispatch.Aborted) "an abort mid-dispatch is reported as Aborted"
Test-Assert ($dispatch.ForceKilledCount -eq 2) "the 2 running processes are force-killed after the abort timeout"
Test-Assert ($cleaned.Count -eq 5) ("-JobAbortCleanup runs for killed AND never-started jobs (got " + $cleaned.Count + ")")
Test-Assert ($dispatch -is [System.Management.Automation.PSCustomObject]) "the dispatcher returns exactly one result object, even on the force-kill path"
Test-Assert ($dispatch.GroupResults.Count -eq 1 -and $dispatch.GroupResults[0].Aborted) "the unfinished group is reported as aborted"
Test-Assert ($sw.Elapsed.TotalSeconds -lt 15) ("the dispatcher returns promptly (" + [int]$sw.Elapsed.TotalSeconds + "s), not after 30s of ping")
Write-Host ""
# ==============================================================================
Write-Host "=== I: dispatchers inside workers, sharing one process budget ===" -ForegroundColor Cyan
Reset-Harness
# Two "engines", each its own runspace running its own dispatcher, both
# drawing on one shared SemaphoreSlim of 2.
$budget = [System.Threading.SemaphoreSlim]::new(2, 2)
$engine = {
param([string]$Name, [System.Threading.SemaphoreSlim]$Budget, [string]$PingExe, $Peak)
$feed = @{ Index = 0 }
$done = @{ Count = 0 }
$dispatch = Invoke-PkProcessDispatch -MaxConcurrent $Budget `
-GroupProvider { if ($feed.Index -ge 2) { return $null }; $feed.Index++; return @{ Id = $feed.Index } }.GetNewClosure() `
-JobBuilder { param($g) return @(@{ FilePath = $PingExe; Arguments = '-n 2 127.0.0.1' }, @{ FilePath = $PingExe; Arguments = '-n 2 127.0.0.1' }) }.GetNewClosure() `
-AbortPollCallback { param($running) $inUse = 2 - $Budget.CurrentCount; if ($inUse -gt $Peak.Max) { $Peak.Max = $inUse } }.GetNewClosure() `
-JobFinalize { param($job, $pending) $r = Complete-PkProcess -Job $job; if ($r.ExitCode -eq 0) { $done.Count++ } }.GetNewClosure()
Write-PkMessage ("engine " + $Name + " finished " + $done.Count)
return @{ Name = $Name; Done = $done.Count; Aborted = $dispatch.Aborted }
}
$peak = @{ Max = 0 }
$results = [System.Collections.Generic.List[hashtable]]::new()
$jobs = New-JobList -Jobs @(@{ Name = 'A'; Budget = $budget; PingExe = $pingExe; Peak = $peak }, @{ Name = 'B'; Budget = $budget; PingExe = $pingExe; Peak = $peak })
$out = Invoke-PkRunspaceJobs -WorkerScript $engine -JobParams $jobs -MaxParallel 2 -ResultHandler { param($r) $results.Add($r) }.GetNewClosure() -CheckWorkerSafety
Test-Assert ($out.CrashedCount -eq 0) "dispatchers run inside worker runspaces without crashing"
$total = 0; foreach ($r in $results) { $total += $r.Done }
Test-Assert ($total -eq 8) ("both engines finish all their processes (8 total, got " + $total + ")")
Test-Assert ($peak.Max -le 2) ("the shared budget is never exceeded across both engines (peak " + $peak.Max + ")")
Test-Assert ($budget.CurrentCount -eq 2) "every budget slot is handed back"
Test-Assert (@($script:messages | Where-Object { $_.Message -like 'engine * finished 4' }).Count -eq 2) "messages written inside the engines reach the main thread"
$budget.Dispose()
Write-Host ""
# ==============================================================================
# Many threads registering/unregistering cancellation sources at once.
$churn = {
param([int]$Id)
for ($i = 0; $i -lt 300; $i++) {
$c = [System.Threading.CancellationTokenSource]::new()
Register-PkCancellationSource -Cts $c
Unregister-PkCancellationSource -Cts $c
$c.Dispose()
}
return $Id
}
$before = [PkState]::SourceCount
$churnOut = Invoke-PkRunspaceJobs -WorkerScript $churn -JobParams (New-JobList -Jobs @(1..6 | ForEach-Object { @{ Id = $_ } })) -MaxParallel 6
Test-Assert ($churnOut.CrashedCount -eq 0 -and [PkState]::SourceCount -eq $before) "cancellation sources can be registered and unregistered from 6 workers at once"
Write-Host ""
# ==============================================================================
Write-Host "=== J: Invoke-PkRun bracket ===" -ForegroundColor Cyan
Reset-Harness
$inside = @{ RunActive = $false }
$value = Invoke-PkRun -ScriptBlock { $inside.RunActive = [PkConsoleCtrl]::RunActive; return 42 }.GetNewClosure()
Test-Assert ($inside.RunActive -eq $true) "the handler is armed while the run's scriptblock executes"
Test-Assert ([PkConsoleCtrl]::RunActive -eq $false) "and disarmed afterwards"
Test-Assert ($value -eq 42) "the scriptblock's output passes through"
Test-Assert ([PkConsoleCtrl]::DrainComplete.IsSet) "the drain is marked complete on the way out"
$threw = $false
try { Invoke-PkRun -ScriptBlock { throw "inner" } } catch { $threw = $true }
Test-Assert ($threw -and [PkConsoleCtrl]::RunActive -eq $false) "an exception still disarms the handler"
# Nested runs: the inner one must not disarm or reset the outer one.
$nested = @{ AfterInner = $false; AbortKept = $false; Inner = 0 }
Invoke-PkRun -ScriptBlock {
Request-PkAbort
$nested.Inner = Invoke-PkRun -ScriptBlock { return 7 }
$nested.AfterInner = [PkConsoleCtrl]::RunActive
$nested.AbortKept = [PkConsoleCtrl]::AbortRequested
}.GetNewClosure()
Test-Assert ($nested.Inner -eq 7) "a nested Invoke-PkRun still runs its scriptblock and passes its output through"
Test-Assert ($nested.AfterInner -eq $true) "the outer run stays armed after a nested run ends"
Test-Assert ($nested.AbortKept -eq $true) "a nested run does not wipe the outer run's abort state"
Test-Assert ([PkConsoleCtrl]::RunActive -eq $false) "the outer run still disarms at its own end"
# A stale abort from a previous run must not leak into the next one.
Request-PkAbort
$null = Test-PkAbortSignal
$leaked = Invoke-PkRun -ScriptBlock { return (Test-PkAbortSignal) }
Test-Assert ($leaked -eq $false) "each run starts with a clean abort state"
Write-Host ""
# Every public function has Get-Help help: a synopsis, and a description for
# each of its parameters. The same list is the Export-ModuleMember list at the
# end of ParallelKit.ps1; keep the two in step.
$publicFunctions = @('Set-PkMessageHandler', 'Write-PkMessage', 'Initialize-ParallelKit', 'Register-PkCancellationSource',
'Unregister-PkCancellationSource', 'Reset-PkAbortState', 'Request-PkAbort', 'Test-PkAbortSignal', 'Test-PkCancelRequested',
'Get-PkAbortTriggerLabel', 'Invoke-PkRun', 'ConvertTo-PkArgumentString', 'Start-PkProcess', 'Stop-PkProcessTree',
'Wait-PkProcess', 'Complete-PkProcess', 'Invoke-PkProcessWithTimeout', 'Invoke-PkProcessDispatch', 'Invoke-PkProcessBatch',
'Invoke-PkRunspaceJobs', 'Test-PkWorkerSafety')
$helpGaps = foreach ($fn in $publicFunctions) {
$help = Get-Help -Name $fn -Full
if ([string]::IsNullOrWhiteSpace([string]$help.Synopsis) -or ([string]$help.Synopsis).Trim().StartsWith($fn)) { $fn + ': no synopsis' }
foreach ($p in (Get-Command -Name $fn).Parameters.Keys) {
if ($p -in [System.Management.Automation.PSCmdlet]::CommonParameters) { continue }
$ph = @($help.parameters.parameter | Where-Object { $_.name -eq $p })
$desc = ''
if ($ph.Count -gt 0 -and $null -ne $ph[0].PSObject.Properties['description']) { $desc = ($ph[0].description | ForEach-Object { $_.Text }) -join '' }
if ([string]::IsNullOrWhiteSpace($desc)) { $fn + ' -' + $p }
}
}
Test-Assert (@($helpGaps).Count -eq 0) ("every public function has Get-Help help for itself and each parameter (missing: " + (@($helpGaps) -join ', ') + ")")
# ==============================================================================
Write-Host "=== K: worker-safety check ===" -ForegroundColor Cyan
Reset-Harness
function Get-HarnessUnsafeState { return $script:someState }
function Get-HarnessUsesCmdlet { return (Get-Date) }
function Get-HarnessCallsOther { return (Get-HarnessDouble -Value 2) }
function Get-HarnessDelegate { return [Func[int]]{ 1 } }
function Get-HarnessIgnored { return $script:someState } # pk:ignore
$f = Test-PkWorkerSafety -WorkerScript { param($Id) return (Get-HarnessDouble -Value $Id) } -SharedFunctionNames @('Get-HarnessDouble')
Test-Assert ($f.Count -eq 0) "clean worker code produces no findings"
$f = Test-PkWorkerSafety -WorkerScript { param($Id) return (Get-HarnessDouble -Value $Id) }
Test-Assert ($f.Count -eq 1 -and $f[0].Rule -eq 'MissingFunction') "a worker calling an unshared function is flagged"
$f = Test-PkWorkerSafety -WorkerScript { param($Id) Get-HarnessCallsOther } -SharedFunctionNames @('Get-HarnessCallsOther')
Test-Assert ($f.Count -eq 1 -and $f[0].Rule -eq 'MissingFunction' -and $f[0].Where -eq 'function Get-HarnessCallsOther') "a shared function calling an unshared one is flagged"
$f = Test-PkWorkerSafety -WorkerScript { param($Id) Get-HarnessUnsafeState } -SharedFunctionNames @('Get-HarnessUnsafeState')
Test-Assert ($f.Count -eq 1 -and $f[0].Rule -eq 'ScriptVariable') "a shared function using `$script: is flagged"
$f = Test-PkWorkerSafety -WorkerScript { param($Id) $script:top = 1; $sb = { $script:nested = 2 } }
Test-Assert ($f.Count -eq 1 -and $f[0].Rule -eq 'ScriptVariable') "in the worker body, only `$script: inside a nested scriptblock is flagged"
$f = Test-PkWorkerSafety -WorkerScript { param($Id) Start-Sleep -Milliseconds 5; @(1, 2) | Where-Object { $_ -gt 1 } | ForEach-Object { $_ }; Get-HarnessUsesCmdlet } -SharedFunctionNames @('Get-HarnessUsesCmdlet')
Test-Assert ($f.Count -eq 0) ("cmdlets, including ones that take a scriptblock, pass the check in the worker body and in shared functions (got " + $f.Count + " finding(s))")
$f = Test-PkWorkerSafety -WorkerScript { param($Id) Get-HarnessDelegate } -SharedFunctionNames @('Get-HarnessDelegate')
Test-Assert ($f.Count -eq 1 -and $f[0].Rule -eq 'DelegateCast') "a scriptblock-to-delegate cast is flagged"
$f = Test-PkWorkerSafety -WorkerScript { param($Id) Get-HarnessIgnored } -SharedFunctionNames @('Get-HarnessIgnored')
Test-Assert ($f.Count -eq 0) "'# pk:ignore' on the line accepts a finding"
$f = Test-PkWorkerSafety -WorkerScript { param($Id) Write-PkMessage "x"; if (Test-PkCancelRequested) { return }; $null = Start-PkProcess -FilePath 'x' }
Test-Assert ($f.Count -eq 0) "the kit's own worker functions never need listing"
$threw = $false
try { $null = Invoke-PkRunspaceJobs -WorkerScript { param($Id) $null = [Func[int]]{ 1 } } -JobParams (New-JobList -Jobs @(@{ Id = 1 })) -MaxParallel 1 -CheckWorkerSafety } catch { $threw = ($_.ToString() -like '*Func*') }
Test-Assert $threw "-CheckWorkerSafety refuses to launch unsafe worker code, naming the problem"
$threw = $false
try { $null = Invoke-PkRunspaceJobs -WorkerScript { param($Id) $null = [Func[int]]{ 1 } } -JobParams (New-JobList -Jobs @(@{ Id = 1 })) -MaxParallel 1 } catch { $threw = ($_.ToString() -like '*Func*') }
Test-Assert $threw "the worker-safety check runs without being asked"
$out = $null
try { $out = Invoke-PkRunspaceJobs -WorkerScript { param($Id) $null = [Func[int]]{ 1 } } -JobParams (New-JobList -Jobs @(@{ Id = 1 })) -MaxParallel 1 -CheckWorkerSafety:$false } catch { Write-Host " opt-out threw: $_" }
Test-Assert ($null -ne $out -and $out.CrashedCount -eq 0) "-CheckWorkerSafety:`$false turns the check off"
$results = [System.Collections.Generic.List[object]]::new()
$out = Invoke-PkRunspaceJobs -WorkerScript { param($Id) return @(1, 2, 3) | Where-Object { $_ -gt 1 } | Measure-Object -Sum | ForEach-Object { $_.Sum + $Id } } `
-JobParams (New-JobList -Jobs @(@{ Id = 10 }, @{ Id = 20 })) -MaxParallel 2 -ResultHandler { param($r) $results.Add($r) }.GetNewClosure()
Test-Assert ($out.CrashedCount -eq 0 -and (@($results | Sort-Object) -join ',') -eq '15,25') "workers can run cmdlets, including ones that take a scriptblock"
$results = [System.Collections.Generic.List[object]]::new()
$out = Invoke-PkRunspaceJobs -WorkerScript { param($Path) return (Get-FileHash -LiteralPath $Path -Algorithm SHA256).Hash } `
-JobParams (New-JobList -Jobs @(@{ Path = $cmdExe })) -MaxParallel 1 -ResultHandler { param($r) $results.Add($r) }.GetNewClosure()
Test-Assert ($out.CrashedCount -eq 0 -and $results.Count -eq 1 -and $results[0] -eq (Get-FileHash -LiteralPath $cmdExe -Algorithm SHA256).Hash) "a function from a module (Get-FileHash) needn't be shared, and autoloads in the worker"
# A scriptblock passed as a job value runs against the main thread's session
# state - refused at launch, with the pass-as-text workaround.
$mainThreadBlock = { param($x) $x * 2 }
$threw = $false
try { $null = Invoke-PkRunspaceJobs -WorkerScript { param($Fn) } -JobParams (New-JobList -Jobs @(@{ Fn = 'ok' }, @{ Fn = $mainThreadBlock })) -MaxParallel 1 } catch { $threw = ($_.ToString() -like "*job 1*'Fn'*Create*Nothing was started*") }
Test-Assert $threw "a scriptblock job value is refused before any worker starts, naming the job and key"
$threw = $false
try { $null = Invoke-PkRunspaceJobs -WorkerScript { param($Fns) } -JobParams (New-JobList -Jobs @(@{ Fns = @(1, $mainThreadBlock) })) -MaxParallel 1 } catch { $threw = ($_.ToString() -like "*'Fns'*") }
Test-Assert $threw "a scriptblock inside an array job value is refused too"
$threw = $false
$providerState = @{ Given = 0 }
$provider = { if ($providerState.Given -ge 2) { return $null }; $providerState.Given++; if ($providerState.Given -eq 2) { return @{ Fn = $mainThreadBlock } }; return @{ Fn = 'ok' } }.GetNewClosure()
try { $null = Invoke-PkRunspaceJobs -WorkerScript { param($Fn) } -NextJobProvider $provider -MaxParallel 1 } catch { $threw = ($_.ToString() -like "*-NextJobProvider*'Fn'*") }
Test-Assert $threw "a scriptblock job value from -NextJobProvider is refused"
$results = [System.Collections.Generic.List[object]]::new()
$out = Invoke-PkRunspaceJobs -WorkerScript { param($FnText, $Id) $fn = [scriptblock]::Create($FnText); return (& $fn $Id) } `
-JobParams (New-JobList -Jobs @(@{ FnText = $mainThreadBlock.ToString(); Id = 4 })) -MaxParallel 1 -ResultHandler { param($r) $results.Add($r) }.GetNewClosure()
Test-Assert ($out.CrashedCount -eq 0 -and $results.Count -eq 1 -and $results[0] -eq 8) "the pass-as-text workaround runs"
Write-Host ""
# ==============================================================================
Write-Host "=== L: message handler ===" -ForegroundColor Cyan
Reset-Harness
Write-PkMessage "main-thread message" -Level Warn
Test-Assert ($script:messages.Count -eq 1 -and $script:messages[0].Level -eq 'Warn') "on the main thread, Write-PkMessage goes straight to the handler"
# Called from inside a closure, where a $script:-based handler would have vanished.
$closure = { Write-PkMessage "from a closure" }.GetNewClosure()
& $closure
Test-Assert ($script:messages.Count -eq 2) "the handler is still found when called from inside a .GetNewClosure()'d block"
Write-Host ""
# ==============================================================================
Write-Host "=== M: callbacks that output things ===" -ForegroundColor Cyan
Reset-Harness
# Every callback below emits stray output. None of it may reach a return value.
$poll = @{ Count = 0 }
$out = Invoke-PkRunspaceJobs -MaxParallel 2 -JobParams (New-JobList -Jobs @(1..4 | ForEach-Object { @{ Id = $_ } })) `
-WorkerScript { param([int]$Id) for ($i = 0; $i -lt 50; $i++) { if (Test-PkCancelRequested) { return $Id }; [System.Threading.Thread]::Sleep(100) }; return $Id } `
-ResultHandler { param($r) $true; 123 } `
-PollCallback { $poll.Count++; if ($poll.Count -eq 4) { Request-PkAbort }; "noise" }.GetNewClosure()
Test-Assert ($out -is [System.Management.Automation.PSCustomObject] -and $out.Aborted) "runspace jobs: noisy -ResultHandler/-PollCallback don't corrupt the result, even through an abort drain"
Reset-Harness
$crashOut = Invoke-PkRunspaceJobs -MaxParallel 1 -JobParams (New-JobList -Jobs @(@{ Id = 1 })) -WorkerScript { param($Id) throw "x" } -JobCrashedHandler { param($e) "noise"; 5 }
Test-Assert ($crashOut -is [System.Management.Automation.PSCustomObject] -and $crashOut.CrashedCount -eq 1) "runspace jobs: a noisy -JobCrashedHandler doesn't corrupt the result"
Reset-Harness
$feed = @{ Given = $false }; $ticks = @{ Count = 0 }
$noisy = Invoke-PkProcessDispatch -MaxConcurrent 1 -AbortTimeoutSeconds 1 `
-GroupProvider { if ($feed.Given) { return $null }; $feed.Given = $true; return @{ Name = 'n' } }.GetNewClosure() `
-JobBuilder { param($g) return @(@{ FilePath = $pingExe; Arguments = '-n 30 127.0.0.1' }, @{ FilePath = $pingExe; Arguments = '-n 30 127.0.0.1' }) }.GetNewClosure() `
-JobFinalize { param($job, $pending) $null = Complete-PkProcess -Job $job } `
-JobAbortCleanup { param($job) "noise"; $true } `
-GroupCompleteCallback { param($group) "noise"; 1 } `
-AbortPollCallback { param($running) $ticks.Count++; if ($ticks.Count -eq 5) { Request-PkAbort }; "noise" }.GetNewClosure()
Test-Assert ($noisy -is [System.Management.Automation.PSCustomObject] -and $noisy.ForceKilledCount -eq 1) "dispatch: noisy -JobAbortCleanup/-GroupCompleteCallback/-AbortPollCallback don't corrupt the result"
Reset-Harness
$noisyBatch = Invoke-PkProcessBatch -Commands @(@{ FilePath = $cmdExe; Arguments = '/c exit 0' }) -MaxConcurrent 1 -OnComplete { param($c, $r) "noise"; $true }
Test-Assert ($noisyBatch -is [System.Management.Automation.PSCustomObject] -and $noisyBatch.Results.Count -eq 1) "batch: a noisy -OnComplete doesn't corrupt the result"
Set-PkMessageHandler -Handler { param($Message, $Level) "noise"; 42 }
$leaked = Write-PkMessage "hello"
Test-Assert ($null -eq $leaked) "a message handler's output doesn't leak out of Write-PkMessage"
Set-PkMessageHandler -Handler { param($Message, $Level) $messageSink.Add(@{ Message = $Message; Level = $Level }) }.GetNewClosure()
Write-Host ""
# ==============================================================================
Write-Host "=== N: careless job starters and retries ===" -ForegroundColor Cyan
Reset-Harness
function Invoke-HarnessOneGroupDispatch {
# One group, $JobCount jobs, with the given starter/finalize.
param([scriptblock]$JobStarter, [scriptblock]$JobFinalize, [int]$JobCount = 1, [hashtable]$Done)
$feed = @{ Given = $false }
$count = $JobCount
return Invoke-PkProcessDispatch -MaxConcurrent 2 -AbortTimeoutSeconds 2 -JobStarter $JobStarter -JobFinalize $JobFinalize `
-GroupProvider { if ($feed.Given) { return $null }; $feed.Given = $true; return @{ Name = 'one' } }.GetNewClosure() `
-JobBuilder { param($g) return @(1..$count | ForEach-Object { @{ FilePath = $cmdExe; Arguments = '/c exit 0' } }) }.GetNewClosure() `
-GroupCompleteCallback { param($group) $Done.Groups++ }.GetNewClosure()
}
# Fills in the job it was given but forgets to return it.
$done = @{ Groups = 0; Jobs = 0 }
$sw = [System.Diagnostics.Stopwatch]::StartNew()
$d = Invoke-HarnessOneGroupDispatch -Done $done -JobCount 2 `
-JobStarter { param($job) $s = Start-PkProcess -FilePath $job.FilePath -Arguments $job.Arguments; $job.Proc = $s.Proc; $job.StdoutTask = $s.StdoutTask; $job.StderrTask = $s.StderrTask } `
-JobFinalize { param($job, $pending) $null = Complete-PkProcess -Job $job; $done.Jobs++ }.GetNewClosure()
$sw.Stop()
Test-Assert ($done.Jobs -eq 2 -and $done.Groups -eq 1) "a starter that fills in the job but forgets to return it still works"
Test-Assert ($sw.Elapsed.TotalSeconds -lt 10) "and the dispatcher doesn't hang on it"
# Returns the job, but with stray output in front of it.
Reset-Harness
$done = @{ Groups = 0; Jobs = 0 }
$d = Invoke-HarnessOneGroupDispatch -Done $done `
-JobStarter { param($job) "noise"; $s = Start-PkProcess -FilePath $job.FilePath -Arguments $job.Arguments; $job.Proc = $s.Proc; $job.StdoutTask = $s.StdoutTask; $job.StderrTask = $s.StderrTask; return $job } `
-JobFinalize { param($job, $pending) $null = Complete-PkProcess -Job $job; $done.Jobs++ }.GetNewClosure()
Test-Assert ($done.Jobs -eq 1 -and $d.JobStarterFailedCount -eq 0) "a starter that leaks output before the job is still understood"
# Never starts anything at all.
Reset-Harness
$done = @{ Groups = 0; Jobs = 0 }
$sw = [System.Diagnostics.Stopwatch]::StartNew()
$d = Invoke-HarnessOneGroupDispatch -Done $done -JobStarter { param($job) return $job } -JobFinalize { param($job, $pending) $done.Jobs++ }.GetNewClosure()
$sw.Stop()
Test-Assert ($d.JobStarterFailedCount -eq 1 -and $done.Groups -eq 1 -and $sw.Elapsed.TotalSeconds -lt 10) "a starter that never sets .Proc is reported as a failed start instead of spinning forever"
Test-Assert (@($script:messages | Where-Object { $_.Message -like "*did not set the job's .Proc*" }).Count -eq 1) "with a message saying what the starter got wrong"
# A retry job enqueued without its GroupKey.
Reset-Harness
$done = @{ Groups = 0; Jobs = 0; Retried = $false }
$d = Invoke-HarnessOneGroupDispatch -Done $done -JobStarter $null -JobFinalize {
param($job, $pending)
$null = Complete-PkProcess -Job $job
if (-not $done.Retried) {
$done.Retried = $true
$pending.Enqueue(@{ FilePath = $cmdExe; Arguments = '/c exit 0' }) # no GroupKey copied
return @{ Requeued = $true }
}
$done.Jobs++
}.GetNewClosure()
Test-Assert ($done.Jobs -eq 1 -and $done.Groups -eq 1 -and -not $d.Aborted) "a retry job enqueued without its GroupKey is still credited to the right group"
# Complete-PkProcess on a job with no read tasks.
$bare = Start-PkProcess -FilePath $cmdExe -Arguments '/c exit 5'
$null = Wait-PkProcess -Process $bare.Proc -TimeoutMs 5000
$threw = $false
try { $bareResult = Complete-PkProcess -Job @{ Proc = $bare.Proc } } catch { $threw = $true }
Test-Assert (-not $threw -and $bareResult.ExitCode -eq 5 -and $null -eq $bareResult.Stdout) "Complete-PkProcess copes with a job that has no output-read tasks"
$bare.Proc.Dispose()
Write-Host ""
# ==============================================================================
Write-Host "=== O: aborts and the caller's own tokens ===" -ForegroundColor Cyan
Reset-Harness
# A caller-supplied source is cancelled by an abort, and left registered nowhere.
$mine = [System.Threading.CancellationTokenSource]::new()
$poll = @{ Count = 0 }
$results = [System.Collections.Generic.List[object]]::new()
$out = Invoke-PkRunspaceJobs -MaxParallel 2 -Cts $mine -JobParams (New-JobList -Jobs @(1..6 | ForEach-Object { @{ Id = $_ } })) `
-WorkerScript { param([int]$Id) for ($i = 0; $i -lt 50; $i++) { if (Test-PkCancelRequested) { return $Id }; [System.Threading.Thread]::Sleep(100) }; return $Id } `
-ResultHandler { param($r) $results.Add($r) }.GetNewClosure() `
-PollCallback { $poll.Count++; if ($poll.Count -eq 4) { Request-PkAbort } }.GetNewClosure()
Test-Assert ($out.Aborted -and $mine.IsCancellationRequested) "runspace jobs: an abort cancels a caller-supplied -Cts"
Test-Assert ($results.Count -eq 2) ("so the remaining jobs are not launched (ran " + $results.Count + " of 6)")
Test-Assert ([PkState]::SourceCount -eq 0) "and the caller's source is not left registered"
$mine.Dispose()
Reset-Harness
$mine = [System.Threading.CancellationTokenSource]::new()
$feed = @{ Given = $false }; $ticks = @{ Count = 0 }
$sw = [System.Diagnostics.Stopwatch]::StartNew()
$d = Invoke-PkProcessDispatch -MaxConcurrent 1 -AbortTimeoutSeconds 1 -CancelToken $mine.Token `
-GroupProvider { if ($feed.Given) { return $null }; $feed.Given = $true; return @{ Name = 'c' } }.GetNewClosure() `
-JobBuilder { param($g) return @(1..3 | ForEach-Object { @{ FilePath = $pingExe; Arguments = '-n 30 127.0.0.1' } }) }.GetNewClosure() `
-JobFinalize { param($job, $pending) $null = Complete-PkProcess -Job $job } `
-AbortPollCallback { param($running) $ticks.Count++; if ($ticks.Count -eq 5) { Request-PkAbort } }.GetNewClosure()
$sw.Stop()
Test-Assert ($d.Aborted -and $sw.Elapsed.TotalSeconds -lt 15) "dispatch: an abort stops a run that was given the caller's own -CancelToken"
Test-Assert (-not $mine.IsCancellationRequested) "without cancelling the caller's own token"
Test-Assert ([PkState]::SourceCount -eq 0) "and nothing is left registered"
# ...and the caller's token still works as a cancel.
Reset-Harness
$feed = @{ Given = $false }; $ticks = @{ Count = 0 }
$d = Invoke-PkProcessDispatch -MaxConcurrent 1 -AbortTimeoutSeconds 1 -CancelToken $mine.Token `
-GroupProvider { if ($feed.Given) { return $null }; $feed.Given = $true; return @{ Name = 'c2' } }.GetNewClosure() `
-JobBuilder { param($g) return @(@{ FilePath = $pingExe; Arguments = '-n 30 127.0.0.1' }) }.GetNewClosure() `
-JobFinalize { param($job, $pending) $null = Complete-PkProcess -Job $job } `
-AbortPollCallback { param($running) $ticks.Count++; if ($ticks.Count -eq 5) { $mine.Cancel() } }.GetNewClosure()
Test-Assert ($d.Aborted -and $d.ForceKilledCount -eq 1) "dispatch: cancelling the caller's own token still stops the run"
$mine.Dispose()
# An abort stays in force until it is reset.
Reset-Harness
Request-PkAbort
$null = Test-PkAbortSignal
$results = [System.Collections.Generic.List[object]]::new()
$out = Invoke-PkRunspaceJobs -MaxParallel 2 -JobParams (New-JobList -Jobs @(1..4 | ForEach-Object { @{ Id = $_ } })) `
-WorkerScript { param([int]$Id) if (Test-PkCancelRequested) { return }; return $Id } -ResultHandler { param($r) $results.Add($r) }.GetNewClosure()
Test-Assert ($out.Aborted -eq $true -and $results.Count -eq 0) "a run started while an earlier abort is still in force reports Aborted instead of silently doing nothing"
$batchAfter = Invoke-PkProcessBatch -Commands @(@{ FilePath = $cmdExe; Arguments = '/c exit 0' }) -MaxConcurrent 1
Test-Assert ($batchAfter.Aborted -eq $true) "the same goes for a process batch"
Reset-PkAbortState
$results = [System.Collections.Generic.List[object]]::new()
$out = Invoke-PkRunspaceJobs -MaxParallel 2 -JobParams (New-JobList -Jobs @(1..4 | ForEach-Object { @{ Id = $_ } })) `
-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"
# Your own long step inside Invoke-PkRun has to poll.
Reset-Harness
$own = @{ Steps = 0 }
Invoke-PkRun -ScriptBlock {
for ($i = 0; $i -lt 1000; $i++) {
if ($i -eq 3) { Request-PkAbort }
if (Test-PkAbortSignal) { break }
$own.Steps++
}
}.GetNewClosure()
Test-Assert ($own.Steps -eq 3) "your own loop inside Invoke-PkRun can stop on an abort by polling Test-PkAbortSignal"
Test-Assert (@($script:messages | Where-Object { $_.Message -like '*Abort requested*' }).Count -eq 1) "and the abort is announced once"
# QuickEdit is put back the way it was found.
Reset-Harness
$quickEditBefore = [PkConsoleQuickEdit]::GetEnabled()
Invoke-PkRun -ScriptBlock { }
Test-Assert ($quickEditBefore -in @(-1, 0, 1) -and [PkConsoleQuickEdit]::GetEnabled() -eq $quickEditBefore) ("QuickEdit is left as it was found after a run (state " + $quickEditBefore + ")")
if ($quickEditBefore -eq 1) {
$null = [PkConsoleQuickEdit]::SetEnabled($false)
Invoke-PkRun -ScriptBlock { }
Test-Assert ([PkConsoleQuickEdit]::GetEnabled() -eq 0) "a console that had QuickEdit off still has it off after a run"
$null = [PkConsoleQuickEdit]::SetEnabled($true)
}
Write-Host ""
# ==============================================================================
Write-Host "=== P: edge cases - delegate detection, self-setup, careless callbacks ===" -ForegroundColor Cyan
Reset-Harness
# The safety check sees scriptblocks handed straight to .NET.
$f = Test-PkWorkerSafety -WorkerScript { param($Id) $d = [System.Collections.Concurrent.ConcurrentDictionary[string,int]]::new(); $null = $d.GetOrAdd('a', { 1 }) }
Test-Assert ($f.Count -eq 1 -and $f[0].Rule -eq 'DelegateCast') "a scriptblock passed straight to a .NET method is flagged"
$f = Test-PkWorkerSafety -WorkerScript { param($Id) $lazy = [System.Lazy[object]]::new({ 1 }) }
Test-Assert ($f.Count -eq 1 -and $f[0].Rule -eq 'DelegateCast') "a scriptblock passed to a .NET constructor is flagged"
$f = Test-PkWorkerSafety -WorkerScript { param($Id) $x = @(1, 2).ForEach({ $_ }); $y = @(1, 2).Where({ $_ }); $z = { 1 }.GetNewClosure() }
Test-Assert ($f.Count -eq 0) "PowerShell's own .ForEach()/.Where()/.GetNewClosure() are not flagged"
$f = Test-PkWorkerSafety -WorkerScript { param($Id) $factory = { 1 }; $lazy = [System.Lazy[object]]::new($factory) }
Test-Assert ($f.Count -eq 1 -and $f[0].Rule -eq 'DelegateCast' -and $f[0].Text -like '*$factory*') "a variable holding a scriptblock, passed to a .NET constructor, is flagged by name"
$f = Test-PkWorkerSafety -WorkerScript { param($Id) $add = { param($k, $old) $old + 1 }.GetNewClosure(); $d = [System.Collections.Concurrent.ConcurrentDictionary[string,int]]::new(); $null = $d.AddOrUpdate('a', 1, $add) }
Test-Assert ($f.Count -eq 1 -and $f[0].Rule -eq 'DelegateCast') "a variable holding a .GetNewClosure() block, passed to a .NET method, is flagged"
$f = Test-PkWorkerSafety -WorkerScript { param($Id) $sb = { $_ * 2 }; $n = 'x'; $x = @(1, 2).ForEach($sb); $null = $n.Contains($n) }
Test-Assert ($f.Count -eq 0) "a scriptblock variable given to .ForEach(), and other variables given to .NET methods, are not flagged"
$f = Test-PkWorkerSafety -WorkerScript { param($Id) $null = [System.Threading.Tasks.Task]::Run({ 1 }) # pk:ignore
}
Test-Assert ($f.Count -eq 0) "'# pk:ignore' accepts a finding on its line"
$f = Test-PkWorkerSafety -WorkerScript { param($Id) $h = { 1 }; $m = [System.Collections.Generic.Dictionary[string,scriptblock]]::new(); $m.Add('a', $h); $l = [System.Collections.Generic.List[scriptblock]]::new(); $l.Add({ 2 }); $q = [System.Collections.Generic.Queue[scriptblock]]::new(); $q.Enqueue($h) }
Test-Assert ($f.Count -eq 0) ("storing a scriptblock in a collection (.Add/.Enqueue) is not flagged (got " + $f.Count + ")")
$f = Test-PkWorkerSafety -WorkerScript { param($Id) $h = { 1 }; $d = [System.Collections.Concurrent.ConcurrentDictionary[string,object]]::new(); $null = $d.GetOrAdd('a', $h) }
Test-Assert ($f.Count -eq 1 -and $f[0].Rule -eq 'DelegateCast') "a scriptblock variable passed as a GetOrAdd factory is still flagged"
# MissingFunction through an alias, and for a module a worker can't load.
Set-Alias -Name hdbl -Value Get-HarnessDouble -Scope Global
$f = Test-PkWorkerSafety -WorkerScript { param($Id) hdbl -Value $Id }
Test-Assert ($f.Count -eq 1 -and $f[0].Rule -eq 'MissingFunction') "an alias to an unshared function of yours is flagged"
Remove-Item -LiteralPath Alias:\hdbl
$modName = "pk-temp-" + [guid]::NewGuid().ToString("N")
$modPath = Join-Path $env:TEMP ($modName + ".psm1")
[System.IO.File]::WriteAllText($modPath, 'function Get-PkTempModuleThing { 1 }')
Import-Module -Name $modPath -Global
$f = Test-PkWorkerSafety -WorkerScript { param($Id) Get-PkTempModuleThing }
Test-Assert ($f.Count -eq 1 -and $f[0].Rule -eq 'MissingFunction' -and $f[0].Text -like '*PSModulePath*') "a function from a module imported by path is flagged"
$f = Test-PkWorkerSafety -WorkerScript { param($Id) Get-PkTempModuleThing } -SharedFunctionNames @('Get-PkTempModuleThing')
Test-Assert ($f.Count -eq 0) "and listing it in -SharedFunctionNames clears it"
Remove-Module -Name $modName
[System.IO.File]::Delete($modPath)
# Job-value scan: nested values, typed arrays, and live shared collections.
$mainThreadBlock = { 1 }
Test-Assert ((& (Get-Module ParallelKit) Get-PkScriptBlockJobKey -Job @{ Steps = @(@{ Name = 'a'; Run = $mainThreadBlock }) }) -eq 'Steps') "a scriptblock two levels down in a job value is found"
Test-Assert ((& (Get-Module ParallelKit) Get-PkScriptBlockJobKey -Job @{ Opts = [pscustomobject]@{ OnDone = $mainThreadBlock } }) -eq 'Opts') "a scriptblock in a [pscustomobject] property is found"
$bigBytes = [byte[]]::new(20MB)
$sw = [System.Diagnostics.Stopwatch]::StartNew()
$key = & (Get-Module ParallelKit) Get-PkScriptBlockJobKey -Job @{ Data = $bigBytes; Paths = [string[]]::new(200000) }
$sw.Stop()
Test-Assert ($null -eq $key -and $sw.Elapsed.TotalSeconds -lt 1) ("a 20 MB byte[] and a 200k string[] are skipped, not walked (" + [int]$sw.Elapsed.TotalMilliseconds + "ms)")
$sink = [System.Collections.ArrayList]::Synchronized([System.Collections.ArrayList]::new())
for ($i = 0; $i -lt 20000; $i++) { $null = $sink.Add([pscustomobject]@{ N = $i }) }
$writer = [PowerShell]::Create()
$null = $writer.AddScript('param($s) while ($true) { $null = $s.Add(1); $s.RemoveAt(0) }').AddArgument($sink)
$writerHandle = $writer.BeginInvoke()
$scanError = $null
$sw = [System.Diagnostics.Stopwatch]::StartNew()
while ($sw.Elapsed.TotalSeconds -lt 3 -and $null -eq $scanError) {
try { $null = & (Get-Module ParallelKit) Get-PkScriptBlockJobKey -Job @{ Sink = $sink } } catch { $scanError = $_ }
}
$null = $writer.BeginStop($null, $null)
$writer.Dispose()
Test-Assert ($null -eq $scanError) ("scanning a collection other threads are changing doesn't throw (" + $scanError + ")")
# With no Initialize-ParallelKit at all, starting a process sets up the
# thread pool and the kill-on-close job object. Needs a fresh process.
$probeScript = Join-Path $env:TEMP ("pk-probe-" + [guid]::NewGuid().ToString("N") + ".ps1")
$kitPath = Join-Path $PSScriptRoot "ParallelKit.ps1"
[System.IO.File]::WriteAllText($probeScript, @"
. '$kitPath'
`$before = [PkChildProcessJob]::IsInitialized
`$j = Start-PkProcess -FilePath '$cmdExe' -Arguments '/c exit 0'
`$null = Wait-PkProcess -Process `$j.Proc -TimeoutMs 5000
`$w = 0; `$io = 0
[System.Threading.ThreadPool]::GetMinThreads([ref]`$w, [ref]`$io)
Write-Output ("before=" + `$before + " after=" + [PkChildProcessJob]::IsInitialized + " threads=" + `$w)
"@)
$probe = Invoke-PkProcessWithTimeout -FilePath $selfExe -Arguments ('-NoProfile -ExecutionPolicy Bypass -File "' + $probeScript + '"') -TimeoutMs 60000
[System.IO.File]::Delete($probeScript)
Test-Assert ($probe.Stdout -match 'before=False after=True') ("starting a process sets up child cleanup by itself (" + ([string]$probe.Stdout).Trim() + ")")
$probeThreads = 0
if ($probe.Stdout -match 'threads=(\d+)') { $probeThreads = [int]$Matches[1] }
Test-Assert ($probeThreads -ge 128) ("and raises the thread pool by itself (minimum " + $probeThreads + ")")
# 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. The kit's public functions are imported globally, so the batch (whose callbacks are
# closures) and a caller's closure that calls a kit function both work.
# Needs a fresh process, started with -Command rather than -File.
$promptScript = Join-Path $env:TEMP ("pk-prompt-" + [guid]::NewGuid().ToString("N") + ".ps1")
[System.IO.File]::WriteAllText($promptScript, @"
. '$kitPath'
`$b = Invoke-PkProcessBatch -Commands @(@{ FilePath = '$cmdExe'; Arguments = '/c exit 7' })
Write-Output ('batch=' + `$b.Results.Count + ',' + `$b.Results[0].ExitCode)
`$tag = 'ok'
`$closure = Invoke-PkRun { Test-PkCancelRequested | Out-Null; 'closure=' + `$tag }.GetNewClosure()
Write-Output `$closure
"@)
$prompt = Invoke-PkProcessWithTimeout -FilePath $selfExe -Arguments (ConvertTo-PkArgumentString @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command', ("& '" + $promptScript + "'"))) -TimeoutMs 60000
[System.IO.File]::Delete($promptScript)
Test-Assert ($prompt.Stdout -match 'batch=1,7') ("a batch works in a script run from a prompt (" + ([string]$prompt.Stdout + [string]$prompt.Stderr).Trim() + ")")
Test-Assert ($prompt.Stdout -match 'closure=ok') "and so does a .GetNewClosure() block that calls a kit function"
# Pasted into a larger script under strict mode, only the kit's functions
# are made global: the script's own (here one defined after the kit, and
# one before) are left alone, and loading raises no errors.
$embedScript = Join-Path $env:TEMP ("pk-embed-" + [guid]::NewGuid().ToString("N") + ".ps1")
[System.IO.File]::WriteAllText($embedScript, "Set-StrictMode -Version Latest`r`n`$ErrorActionPreference = 'Stop'`r`nfunction Get-HarnessBefore { 1 }`r`n`$fnAst = 'mine'`r`n" +
[System.IO.File]::ReadAllText($kitPath) +
"`r`nfunction Get-HarnessAfter { 2 }`r`nWrite-Output ('kitGlobal=' + [bool](Get-ChildItem Function: | Where-Object { `$_.Name -eq 'Start-PkProcess' }))`r`nWrite-Output ('caller var=' + `$fnAst)`r`n")
$embed = Invoke-PkProcessWithTimeout -FilePath $selfExe -Arguments (ConvertTo-PkArgumentString @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command', ("& '" + $embedScript + "'; 'before global=' + [bool](Get-Command Get-HarnessBefore -ErrorAction SilentlyContinue); 'after global=' + [bool](Get-Command Get-HarnessAfter -ErrorAction SilentlyContinue); 'kit global=' + [bool](Get-Command Start-PkProcess -ErrorAction SilentlyContinue)"))) -TimeoutMs 60000
[System.IO.File]::Delete($embedScript)
$embedOut = ([string]$embed.Stdout + [string]$embed.Stderr).Trim()
Test-Assert ($embedOut -match 'kit global=True' -and $embedOut -match 'before global=False' -and $embedOut -match 'after global=False' -and $embedOut -match 'caller var=mine' -and [string]::IsNullOrWhiteSpace([string]$embed.Stderr)) ("pasted into a larger script, only the kit's functions are made global, without errors or touching the script's variables (" + ($embedOut -replace '\s+', ' ') + ")")
# Loading the kit in Constrained Language Mode fails with a message that
# says so. Needs a fresh process: the mode can't be set back.
$clmScript = Join-Path $env:TEMP ("pk-clm-" + [guid]::NewGuid().ToString("N") + ".ps1")
[System.IO.File]::WriteAllText($clmScript, @"
`$ExecutionContext.SessionState.LanguageMode = 'ConstrainedLanguage'
try { . '$kitPath'; Write-Output 'loaded' } catch { Write-Output ('error: ' + `$_) }
"@)
$clm = Invoke-PkProcessWithTimeout -FilePath $selfExe -Arguments ('-NoProfile -ExecutionPolicy Bypass -File "' + $clmScript + '"') -TimeoutMs 60000
[System.IO.File]::Delete($clmScript)
Test-Assert ($clm.Stdout -like '*ConstrainedLanguage mode, but the kit needs FullLanguage*') ("loading in Constrained Language Mode fails with a message naming the problem (" + ([string]$clm.Stdout).Trim() + ")")
# The dispatcher sizes the pool for its own concurrency.
$feed = @{ Given = $false }
$null = Invoke-PkProcessDispatch -MaxConcurrent 100 -GroupProvider { return $null } -JobBuilder { param($g) } -JobFinalize { param($j, $p) }
$w = 0; $io = 0
[System.Threading.ThreadPool]::GetMinThreads([ref]$w, [ref]$io)
Test-Assert ($w -ge 232) ("the dispatcher raises the thread pool to fit -MaxConcurrent (minimum " + $w + " for 100 processes)")
# A one-line starter keeps the caller's job fields.
Reset-Harness
$feed = @{ Given = $false }
$seenTags = [System.Collections.Generic.List[object]]::new()
$d = Invoke-PkProcessDispatch -MaxConcurrent 2 `
-GroupProvider { if ($feed.Given) { return $null }; $feed.Given = $true; return @{ Name = 's' } }.GetNewClosure() `
-JobBuilder { param($g) return @(@{ FilePath = $cmdExe; Arguments = '/c exit 0'; Tag = 'first' }, @{ FilePath = $cmdExe; Arguments = '/c exit 0'; Tag = 'second' }) }.GetNewClosure() `
-JobStarter { param($job) Start-PkProcess -FilePath $job.FilePath -Arguments $job.Arguments } `
-JobFinalize { param($job, $pending) $r = Complete-PkProcess -Job $job; $seenTags.Add($job.Tag) }.GetNewClosure()
Test-Assert ($seenTags.Count -eq 2 -and ($seenTags -contains 'first') -and ($seenTags -contains 'second')) "a starter that is just 'Start-PkProcess ...' keeps the job's own fields for JobFinalize"
Test-Assert ($d.JobStarterFailedCount -eq 0 -and $d.GroupResults.Count -eq 1) "and the jobs run and complete normally"
# A message handler that throws.
Reset-Harness
Set-PkMessageHandler -Handler { param($Message, $Level) throw "log file locked" }
$results = [System.Collections.Generic.List[object]]::new()
$threw = $false
try {
$out = Invoke-PkRunspaceJobs -MaxParallel 2 -JobParams (New-JobList -Jobs @(@{ Id = 1 }, @{ Id = 2 }, @{ Id = 3 })) `
-WorkerScript { param([int]$Id) Write-PkMessage ("from " + $Id); if ($Id -eq 2) { throw "boom" }; return $Id } `
-ResultHandler { param($r) $results.Add($r) }.GetNewClosure()
} catch { $threw = $true }
Set-PkMessageHandler -Handler { param($Message, $Level) $messageSink.Add(@{ Message = $Message; Level = $Level }) }.GetNewClosure()
Test-Assert (-not $threw -and $out.CrashedCount -eq 1 -and $results.Count -eq 2) "a message handler that throws doesn't take the run down"
# Stray output from a builder and from a provider.
Reset-Harness
$feed = @{ Given = $false }
$done = @{ Jobs = 0 }
$seenGroups = [System.Collections.Generic.HashSet[string]]::new()
$d = Invoke-PkProcessDispatch -MaxConcurrent 1 `
-GroupProvider { if ($feed.Given) { return $null }; $feed.Given = $true; return @{ Name = 'b' } }.GetNewClosure() `
-JobBuilder { param($g) $seenGroups.Add($g.Name); "noise"; return @{ FilePath = $cmdExe; Arguments = '/c exit 0' } }.GetNewClosure() `
-JobFinalize { param($job, $pending) $null = Complete-PkProcess -Job $job; $done.Jobs++ }.GetNewClosure()
Test-Assert ($done.Jobs -eq 1 -and $d.GroupResults.Count -eq 1) "a job builder that lets stray output escape still gets its job run"
Test-Assert (@($script:messages | Where-Object { $_.Level -eq 'Warn' -and $_.Message -like '*-JobBuilder returned 2 value(s)*' }).Count -eq 1) "and the ignored values are reported"
Reset-Harness
$feed = @{ Next = 1 }
$results = [System.Collections.Generic.List[object]]::new()
$out = Invoke-PkRunspaceJobs -MaxParallel 2 -WorkerScript { param([int]$Id) return $Id } `
-NextJobProvider { if ($feed.Next -gt 3) { return $null }; "noise"; $j = @{ Id = $feed.Next }; $feed.Next++; return $j }.GetNewClosure() `
-ResultHandler { param($r) $results.Add($r) }.GetNewClosure()
Test-Assert ($results.Count -eq 3 -and $out.CrashedCount -eq 0) "a job provider that lets stray output escape still feeds its jobs"
# Working directory on the single-process helper.
$wdResult = Invoke-PkProcessWithTimeout -FilePath $cmdExe -Arguments '/c cd' -WorkingDirectory $env:SystemRoot
Test-Assert ($wdResult.Stdout.Trim() -ieq $env:SystemRoot) "Invoke-PkProcessWithTimeout honors -WorkingDirectory"
# A bad key in a fixed job list is caught before anything runs.
Reset-Harness
$ran = @{ Count = 0 }
$gate = [object]::new()
$threw = $false
try {
$null = Invoke-PkRunspaceJobs -MaxParallel 1 `
-JobParams (New-JobList -Jobs @(@{ Id = 1; Ran = $ran; Gate = $gate }, @{ Id = 2; Ran = $ran; Gate = $gate }, @{ Id = 3; Ran = $ran; Gate = $gate; Typo = 1 })) `
-WorkerScript { param([int]$Id, $Ran, $Gate) [System.Threading.Monitor]::Enter($Gate); try { $Ran.Count++ } finally { [System.Threading.Monitor]::Exit($Gate) }; return $Id }
} catch { $threw = ($_.ToString() -like "*job 2 supplies 'Typo'*Nothing was started*") }
[System.Threading.Thread]::Sleep(300)
Test-Assert ($threw -and $ran.Count -eq 0) ("a bad key in -JobParams is reported before any worker starts (workers run: " + $ran.Count + ")")
# Callbacks built WITHOUT .GetNewClosure() see the kit's locals by dynamic
# scope. A caller's $results.Add($r) in one used to land in the kit's own
# worker-output collection, which the kit was looping over: an endless loop.
# The guard throws instead of hanging the harness if that comes back.
Reset-Harness
$results = [System.Collections.Generic.List[object]]::new()
$loopGuard = @{ Calls = 0 }
$threw = $null
try {
$null = Invoke-PkRunspaceJobs -MaxParallel 2 -JobParams (New-JobList -Jobs @(@{ Id = 1 }, @{ Id = 2 })) -WorkerScript { param([int]$Id) $Id } -ResultHandler {
param($r)
$loopGuard.Calls++
if ($loopGuard.Calls -gt 20) { throw 'still looping after 20 handler calls' }
$results.Add($r)
}
} catch { $threw = $_.Exception.Message }
Test-Assert ($null -eq $threw -and $loopGuard.Calls -eq 2 -and $results.Count -eq 2) ("a -ResultHandler without a closure: `$results.Add reaches the caller's list and doesn't loop (calls=" + $loopGuard.Calls + ", count=" + $results.Count + ", threw=" + $threw + ")")
# The same on the abort-drain path, which collects results separately.
Reset-Harness
$results = [System.Collections.Generic.List[object]]::new()