-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathRun-AutonomousIntegrationLoop.ps1
More file actions
872 lines (782 loc) · 40.9 KB
/
Copy pathRun-AutonomousIntegrationLoop.ps1
File metadata and controls
872 lines (782 loc) · 40.9 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
<#
.SYNOPSIS
Autonomous integration compare loop runner for CI or local soak.
.DESCRIPTION
Wraps Invoke-IntegrationCompareLoop providing environment driven defaults so it can
be launched with zero parameters in a prepared environment. Intended for:
* Long running CI soak jobs gathering latency/diff telemetry.
* Developer guard loops (optionally fail on first diff).
* HTML / Markdown / Text diff summary emission.
The script is resilient: validates required inputs, surfaces a concise summary to stdout,
and (optionally) writes snapshot & run summary JSON artifacts.
.PARAMETER Base
Path to base VI (or label when using -SkipValidation -PassThroughPaths for dry runs).
Default: $env:LV_BASE_VI
.PARAMETER Head
Path to head VI (or label). Default: $env:LV_HEAD_VI
.PARAMETER MaxIterations
Number of iterations to execute (0 = infinite until Ctrl+C). Default: $env:LOOP_MAX_ITERATIONS or 1.
.PARAMETER IntervalSeconds
Delay between iterations (can be fractional). Default: $env:LOOP_INTERVAL_SECONDS or 0.
.PARAMETER DiffSummaryFormat
None | Text | Markdown | Html. Default: $env:LOOP_DIFF_SUMMARY_FORMAT or None.
.PARAMETER DiffSummaryPath
Path to write diff summary fragment (overwritten). Default: $env:LOOP_DIFF_SUMMARY_PATH or diff-summary.html/.md/.txt inferred from format when omitted.
.PARAMETER CustomPercentiles
Comma/space list (exclusive 0..100) for additional percentile metrics. Default from $env:LOOP_CUSTOM_PERCENTILES.
.PARAMETER RunSummaryJsonPath
Path for final run summary JSON. Default: $env:LOOP_RUN_SUMMARY_JSON or 'loop-run-summary.json' in current dir when set via env LOOP_EMIT_RUN_SUMMARY=1.
.PARAMETER MetricsSnapshotEvery
Emit per-N iteration metrics snapshot lines when >0. Default: $env:LOOP_SNAPSHOT_EVERY.
.PARAMETER MetricsSnapshotPath
File path for NDJSON snapshot emission. Default: $env:LOOP_SNAPSHOT_PATH or 'loop-snapshots.ndjson' when cadence >0 and path not provided.
.PARAMETER FailOnDiff
Break loop on first diff. Default: $env:LOOP_FAIL_ON_DIFF = 'true'.
.PARAMETER AdaptiveInterval
Enable backoff. Default: $env:LOOP_ADAPTIVE = 'false'.
.PARAMETER HistogramBins
Bin count for latency histogram (0 disables). Default: $env:LOOP_HISTOGRAM_BINS.
.PARAMETER CustomExecutor
Provide a scriptblock for dependency injection (testing / simulation). If omitted a real CLI invocation occurs.
To force simulation via env set LOOP_SIMULATE=1.
.PARAMETER DryRun
When set, validates environment/parameters, prints the resolved invocation plan, then exits without running the loop.
.PARAMETER LogVerbosity
Controls internal script logging (not the loop's own data output). Values: Quiet | Normal | Verbose.
Can be set via env LOOP_LOG_VERBOSITY. Quiet suppresses non-error informational lines; Verbose emits extra diagnostics.
.PARAMETER JsonLogPath
When provided (or via env LOOP_JSON_LOG) each high-level event is appended as one line of JSON (NDJSON) with a timestamp and type.
.PARAMETER NoStepSummary
Suppress appending diff summary fragment to $GITHUB_STEP_SUMMARY (or set env LOOP_NO_STEP_SUMMARY=1).
.PARAMETER NoConsoleSummary
Suppress the human-readable console summary block (or set env LOOP_NO_CONSOLE_SUMMARY=1). JSON logging unaffected.
.PARAMETER DiffExitCode
When provided (or env LOOP_DIFF_EXIT_CODE) use this exit code if the loop succeeds and diffs were detected (ErrorCount=0, DiffCount>0). Default behavior leaves exit code 0.
.PARAMETER JsonLogMaxBytes
Max file size in bytes before rotation (env LOOP_JSON_LOG_MAX_BYTES). If exceeded a numbered roll is performed.
.PARAMETER JsonLogMaxRolls
Maximum number of rotated log files to retain (env LOOP_JSON_LOG_MAX_ROLLS). Oldest removed after exceeding.
.PARAMETER JsonLogMaxAgeSeconds
Max age in seconds before forcing a rotation on next write regardless of size (env LOOP_JSON_LOG_MAX_AGE_SECONDS).
.PARAMETER FinalStatusJsonPath
Emit machine-readable final status JSON document (env LOOP_FINAL_STATUS_JSON) containing core metrics & schema.
.OUTPUTS
Writes key result fields and optionally diff summary to stdout. Exit code 0 when Succeeded, 1 otherwise.
.EXAMPLES
# Minimal (env must supply LV_BASE_VI & LV_HEAD_VI)
pwsh -File scripts/Run-AutonomousIntegrationLoop.ps1
# Simulated diff soak with snapshots
$env:LV_BASE_VI='VI1.vi'; $env:LV_HEAD_VI='VI2.vi'
$env:LOOP_SIMULATE=1
$env:LOOP_DIFF_SUMMARY_FORMAT='Html'
$env:LOOP_MAX_ITERATIONS=25
$env:LOOP_SNAPSHOT_EVERY=5
pwsh -File scripts/Run-AutonomousIntegrationLoop.ps1
.NOTES
Set -Verbose for extra diagnostic output.
#>
[CmdletBinding()]
param(
[string]$Base = $env:LV_BASE_VI,
[string]$Head = $env:LV_HEAD_VI,
[int]$MaxIterations = ($env:LOOP_MAX_ITERATIONS -as [int]),
[double]$IntervalSeconds = ($env:LOOP_INTERVAL_SECONDS -as [double]),
[ValidateSet('None','Text','Markdown','Html')]
[string]$DiffSummaryFormat = $( if ($env:LOOP_DIFF_SUMMARY_FORMAT) { $env:LOOP_DIFF_SUMMARY_FORMAT } else { 'None' } ),
[string]$DiffSummaryPath = $env:LOOP_DIFF_SUMMARY_PATH,
[string]$LvCompareArgs,
[string]$CustomPercentiles = $env:LOOP_CUSTOM_PERCENTILES,
[string]$RunSummaryJsonPath = $env:LOOP_RUN_SUMMARY_JSON,
[int]$MetricsSnapshotEvery = ($env:LOOP_SNAPSHOT_EVERY -as [int]),
[string]$MetricsSnapshotPath = $env:LOOP_SNAPSHOT_PATH,
[switch]$FailOnDiff,
[switch]$AdaptiveInterval,
[int]$HistogramBins = ($env:LOOP_HISTOGRAM_BINS -as [int]),
[scriptblock]$CustomExecutor
, [switch]$DryRun
, [ValidateSet('Quiet','Normal','Verbose','Debug')][string]$LogVerbosity = $( if ($env:LOOP_LOG_VERBOSITY) { $env:LOOP_LOG_VERBOSITY } else { 'Normal' } )
, [string]$JsonLogPath = $env:LOOP_JSON_LOG
, [switch]$NoStepSummary
, [switch]$NoConsoleSummary
, [int]$DiffExitCode = ($env:LOOP_DIFF_EXIT_CODE -as [int])
, [int]$JsonLogMaxBytes = ($env:LOOP_JSON_LOG_MAX_BYTES -as [int])
, [int]$JsonLogMaxRolls = ($env:LOOP_JSON_LOG_MAX_ROLLS -as [int])
, [int]$JsonLogMaxAgeSeconds = ($env:LOOP_JSON_LOG_MAX_AGE_SECONDS -as [int])
, [string]$FinalStatusJsonPath = $env:LOOP_FINAL_STATUS_JSON
, [switch]$RenderReport
, [switch]$UseTestStandHarness
, [string]$TestStandHarnessPath = $env:LOOP_TESTSTAND_HARNESS_PATH
, [string]$TestStandOutputRoot = $env:LOOP_TESTSTAND_OUTPUT_ROOT
, [ValidateSet('detect','spawn','skip')][string]$TestStandWarmup = $( if ($env:LOOP_TESTSTAND_WARMUP) { $env:LOOP_TESTSTAND_WARMUP } else { 'skip' } )
, [ValidateSet('single-compare','dual-plane-parity')][string]$TestStandSuiteClass = $( if ($env:LOOP_TESTSTAND_SUITE_CLASS) { $env:LOOP_TESTSTAND_SUITE_CLASS } else { 'single-compare' } )
, [switch]$TestStandRenderReport
, [switch]$TestStandCloseLabVIEW
, [switch]$TestStandCloseLVCompare
, [int]$TestStandTimeoutSeconds = ($env:LOOP_TESTSTAND_TIMEOUT_SECONDS -as [int])
, [switch]$TestStandDisableTimeout
, [string]$TestStandLabVIEWPath = $env:LOOP_TESTSTAND_LABVIEW_PATH
, [string]$TestStandLabVIEW64Path = $env:LOOP_TESTSTAND_LABVIEW64_PATH
, [string]$TestStandLabVIEW32Path = $env:LOOP_TESTSTAND_LABVIEW32_PATH
, [string]$TestStandLVComparePath = $env:LOOP_TESTSTAND_LVCOMPARE_PATH
, [string]$TestStandAgentId = $env:LOOP_TESTSTAND_AGENT_ID
, [string]$TestStandAgentClass = $env:LOOP_TESTSTAND_AGENT_CLASS
, [string]$TestStandExecutionCellLeasePath = $env:LOOP_TESTSTAND_EXECUTION_CELL_LEASE_PATH
, [string]$TestStandExecutionCellId = $env:LOOP_TESTSTAND_EXECUTION_CELL_ID
, [string]$TestStandExecutionCellLeaseId = $env:LOOP_TESTSTAND_EXECUTION_CELL_LEASE_ID
, [string]$TestStandHarnessInstanceLeasePath = $env:LOOP_TESTSTAND_HARNESS_INSTANCE_LEASE_PATH
, [string]$TestStandHarnessInstanceId = $env:LOOP_TESTSTAND_HARNESS_INSTANCE_ID
, [switch]$TestStandReplaceFlags
)
function Set-LoopExit {
param([int]$Code)
$global:LASTEXITCODE = $Code
exit $Code
}
function Get-ExecutionCellLeaseMetadata {
param([string]$LeasePath)
$metadata = [ordered]@{
cellClass = $null
suiteClass = $null
operatorAuthorizationRef = $null
premiumSaganMode = $false
}
if ([string]::IsNullOrWhiteSpace($LeasePath)) {
return [pscustomobject]$metadata
}
try {
$resolvedLeasePath = (Resolve-Path -LiteralPath $LeasePath -ErrorAction Stop).Path
$payload = Get-Content -LiteralPath $resolvedLeasePath -Raw | ConvertFrom-Json -ErrorAction Stop
$summary = if ($payload -and $payload.PSObject.Properties.Name -contains 'summary') { $payload.summary } else { $null }
$lease = if ($payload -and $payload.PSObject.Properties.Name -contains 'lease') { $payload.lease } else { $null }
$request = if ($lease -and $lease.PSObject.Properties.Name -contains 'request') { $lease.request } else { $null }
$grant = if ($lease -and $lease.PSObject.Properties.Name -contains 'grant') { $lease.grant } else { $null }
$summaryCellClass = if ($summary) { $summary.cellClass } else { $null }
$requestCellClass = if ($request) { $request.cellClass } else { $null }
foreach ($candidate in @($summaryCellClass, $requestCellClass)) {
if (-not [string]::IsNullOrWhiteSpace($candidate)) {
$metadata.cellClass = [string]$candidate
break
}
}
$summarySuiteClass = if ($summary) { $summary.suiteClass } else { $null }
$requestSuiteClass = if ($request) { $request.suiteClass } else { $null }
foreach ($candidate in @($summarySuiteClass, $requestSuiteClass)) {
if (-not [string]::IsNullOrWhiteSpace($candidate)) {
$metadata.suiteClass = [string]$candidate
break
}
}
$summaryOperatorAuthorizationRef = if ($summary) { $summary.operatorAuthorizationRef } else { $null }
$requestOperatorAuthorizationRef = if ($request) { $request.operatorAuthorizationRef } else { $null }
foreach ($candidate in @($summaryOperatorAuthorizationRef, $requestOperatorAuthorizationRef)) {
if (-not [string]::IsNullOrWhiteSpace($candidate)) {
$metadata.operatorAuthorizationRef = [string]$candidate
break
}
}
if ($summary -and $summary.PSObject.Properties.Name -contains 'premiumSaganMode') {
$metadata.premiumSaganMode = [bool]$summary.premiumSaganMode
} elseif ($grant -and $grant.PSObject.Properties.Name -contains 'premiumSaganMode') {
$metadata.premiumSaganMode = [bool]$grant.premiumSaganMode
}
} catch {}
return [pscustomobject]$metadata
}
function Get-HarnessInstanceLeaseMetadata {
param([string]$LeasePath)
$metadata = [ordered]@{
leaseId = $null
}
if ([string]::IsNullOrWhiteSpace($LeasePath)) {
return [pscustomobject]$metadata
}
try {
$resolvedLeasePath = (Resolve-Path -LiteralPath $LeasePath -ErrorAction Stop).Path
$payload = Get-Content -LiteralPath $resolvedLeasePath -Raw | ConvertFrom-Json -ErrorAction Stop
$grant = if ($payload -and $payload.PSObject.Properties.Name -contains 'grant') { $payload.grant } else { $null }
if ($grant -and $grant.PSObject.Properties.Name -contains 'leaseId' -and -not [string]::IsNullOrWhiteSpace($grant.leaseId)) {
$metadata.leaseId = [string]$grant.leaseId
}
} catch {}
return [pscustomobject]$metadata
}
function Get-TestStandHarnessSessionMetadata {
param([string]$IterationRoot)
$metadata = [ordered]@{
harnessInstanceId = $null
harnessInstanceLeaseId = $null
harnessInstanceLeasePath = $null
}
if ([string]::IsNullOrWhiteSpace($IterationRoot)) {
return [pscustomobject]$metadata
}
try {
$sessionIndexPath = Join-Path $IterationRoot 'session-index.json'
if (-not (Test-Path -LiteralPath $sessionIndexPath -PathType Leaf)) {
return [pscustomobject]$metadata
}
$payload = Get-Content -LiteralPath $sessionIndexPath -Raw | ConvertFrom-Json -ErrorAction Stop
$harnessInstance = if ($payload -and $payload.PSObject.Properties.Name -contains 'harnessInstance') { $payload.harnessInstance } else { $null }
if ($harnessInstance) {
if ($harnessInstance.PSObject.Properties.Name -contains 'instanceId' -and -not [string]::IsNullOrWhiteSpace($harnessInstance.instanceId)) {
$metadata.harnessInstanceId = [string]$harnessInstance.instanceId
}
if ($harnessInstance.PSObject.Properties.Name -contains 'leaseId' -and -not [string]::IsNullOrWhiteSpace($harnessInstance.leaseId)) {
$metadata.harnessInstanceLeaseId = [string]$harnessInstance.leaseId
}
if ($harnessInstance.PSObject.Properties.Name -contains 'leasePath' -and -not [string]::IsNullOrWhiteSpace($harnessInstance.leasePath)) {
$metadata.harnessInstanceLeasePath = [string]$harnessInstance.leasePath
}
}
} catch {}
return [pscustomobject]$metadata
}
# Defaults / fallbacks
if (-not $MaxIterations) { $MaxIterations = 1 }
if ($null -eq $IntervalSeconds) { $IntervalSeconds = 0 }
if (-not $HistogramBins) { $HistogramBins = 0 }
try {
$repoRoot = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path
} catch {
$repoRoot = (Get-Location).Path
}
# Initialize switches from env when not explicitly passed
if (-not $PSBoundParameters.ContainsKey('FailOnDiff')) {
if ($env:LOOP_FAIL_ON_DIFF) { if ($env:LOOP_FAIL_ON_DIFF -match '^(1|true)$') { $FailOnDiff = $true } }
else { $FailOnDiff = $true }
}
if (-not $PSBoundParameters.ContainsKey('AdaptiveInterval')) {
if ($env:LOOP_ADAPTIVE -and $env:LOOP_ADAPTIVE -match '^(1|true)$') { $AdaptiveInterval = $true }
}
# Honor suppression env flags if switches not explicitly passed
if (-not $PSBoundParameters.ContainsKey('NoStepSummary') -and $env:LOOP_NO_STEP_SUMMARY -match '^(1|true)$') { $NoStepSummary = $true }
if (-not $PSBoundParameters.ContainsKey('NoConsoleSummary') -and $env:LOOP_NO_CONSOLE_SUMMARY -match '^(1|true)$') { $NoConsoleSummary = $true }
$simulate = $false
if ($env:LOOP_SIMULATE -match '^(1|true)$') { $simulate = $true }
if (-not $Base -or -not $Head) { Write-Error 'Base/Head not provided (set LV_BASE_VI & LV_HEAD_VI or pass -Base/-Head).'; Set-LoopExit 1 }
# Infer summary path if format chosen and no path provided
if (-not $DiffSummaryPath -and $DiffSummaryFormat -ne 'None') {
$ext = switch ($DiffSummaryFormat) { 'Html' { 'html' } 'Markdown' { 'md' } default { 'txt' } }
$DiffSummaryPath = "diff-summary.$ext"
}
# Infer snapshot path
if ($MetricsSnapshotEvery -gt 0 -and -not $MetricsSnapshotPath) { $MetricsSnapshotPath = 'loop-snapshots.ndjson' }
# Infer run summary path if env flag set
if (-not $RunSummaryJsonPath -and $env:LOOP_EMIT_RUN_SUMMARY -match '^(1|true)$') { $RunSummaryJsonPath = 'loop-run-summary.json' }
if (-not $PSBoundParameters.ContainsKey('RenderReport') -and $DiffSummaryFormat -ne 'None') { $RenderReport = $true }
if (-not $PSBoundParameters.ContainsKey('UseTestStandHarness') -and $env:LOOP_USE_TESTSTAND_HARNESS -match '^(1|true)$') { $UseTestStandHarness = $true }
if (-not $PSBoundParameters.ContainsKey('TestStandRenderReport') -and $env:LOOP_TESTSTAND_RENDER_REPORT -match '^(1|true)$') { $TestStandRenderReport = $true }
if (-not $PSBoundParameters.ContainsKey('TestStandCloseLabVIEW') -and $env:LOOP_TESTSTAND_CLOSE_LABVIEW -match '^(1|true)$') { $TestStandCloseLabVIEW = $true }
if (-not $PSBoundParameters.ContainsKey('TestStandCloseLVCompare') -and $env:LOOP_TESTSTAND_CLOSE_LVCOMPARE -match '^(1|true)$') { $TestStandCloseLVCompare = $true }
if (-not $PSBoundParameters.ContainsKey('TestStandDisableTimeout') -and $env:LOOP_TESTSTAND_DISABLE_TIMEOUT -match '^(1|true)$') { $TestStandDisableTimeout = $true }
if (-not $PSBoundParameters.ContainsKey('TestStandReplaceFlags') -and $env:LOOP_TESTSTAND_REPLACE_FLAGS -match '^(1|true)$') { $TestStandReplaceFlags = $true }
if ($UseTestStandHarness -and $RenderReport -and -not $PSBoundParameters.ContainsKey('TestStandRenderReport') -and -not ($env:LOOP_TESTSTAND_RENDER_REPORT -match '^(1|true)$')) { $TestStandRenderReport = $true }
$explicitLvCompareArgs = $false
if ($PSBoundParameters.ContainsKey('LvCompareArgs')) {
$explicitLvCompareArgs = $true
} elseif (-not [string]::IsNullOrWhiteSpace($env:LOOP_LVCOMPARE_ARGS)) {
$LvCompareArgs = $env:LOOP_LVCOMPARE_ARGS
$explicitLvCompareArgs = $true
}
Import-Module (Join-Path $PSScriptRoot '../module/CompareLoop/CompareLoop.psd1') -Force
$preClean = $false
if ($env:LOOP_PRE_CLEAN -match '^(1|true)$') { $preClean = $true }
if ($preClean) {
try {
. (Join-Path $PSScriptRoot 'Ensure-LVCompareClean.ps1')
$k1 = Stop-LVCompareProcesses -Quiet
$k2 = Stop-LabVIEWProcesses -Quiet
if ($k1 -gt 0 -or $k2 -gt 0) { Write-Host "Pre-cleaned LVCompare=$k1, LabVIEW=$k2 stray process(es)." -ForegroundColor DarkYellow }
} catch {
Write-Host "Pre-clean attempt failed: $($_.Exception.Message)" -ForegroundColor DarkYellow
}
}
if ($UseTestStandHarness -and $CustomExecutor) {
throw 'Cannot combine -UseTestStandHarness with -CustomExecutor.'
}
if ($UseTestStandHarness -and $simulate) { $simulate = $false }
$executor = $null
$skipValidation = $false
$passThroughPaths = $false
$bypassCliValidation = $false
$harnessPlan = $null
if ($CustomExecutor) {
$executor = $CustomExecutor
$skipValidation = $true
$passThroughPaths = $true
$bypassCliValidation = $true
} elseif ($simulate) {
# Allow explicit simulation of exit code 0 (previous logic treated 0 as unset due to -not test)
$exitCode = ($env:LOOP_SIMULATE_EXIT_CODE -as [int])
if ([string]::IsNullOrWhiteSpace($env:LOOP_SIMULATE_EXIT_CODE)) { $exitCode = 1 }
$delayMs = ($env:LOOP_SIMULATE_DELAY_MS -as [int]); if (-not $delayMs) { $delayMs = 5 }
$localDelay = $delayMs; if (-not $localDelay) { $localDelay = 5 }
$localExit = $exitCode
# Lexical closure: variables from outer scope ($localDelay,$localExit) are captured automatically
$executor = { param($CliPath,$Base,$Head,$ExecArgs) Start-Sleep -Milliseconds $localDelay; return $localExit }
$skipValidation = $true
$passThroughPaths = $true
$bypassCliValidation = $true
}
if ($UseTestStandHarness) {
if (-not $TestStandHarnessPath) { $TestStandHarnessPath = Join-Path $repoRoot 'tools' 'TestStand-CompareHarness.ps1' }
if (-not (Test-Path -LiteralPath $TestStandHarnessPath -PathType Leaf)) {
throw "TestStand harness not found at $TestStandHarnessPath"
}
if (-not $TestStandOutputRoot) { $TestStandOutputRoot = 'tests/results/teststand-loop' }
if (-not [System.IO.Path]::IsPathRooted($TestStandOutputRoot)) {
$TestStandOutputRoot = Join-Path $repoRoot $TestStandOutputRoot
}
if (-not (Test-Path -LiteralPath $TestStandOutputRoot)) {
New-Item -ItemType Directory -Path $TestStandOutputRoot -Force | Out-Null
}
$resolvedHarness = (Resolve-Path -LiteralPath $TestStandHarnessPath -ErrorAction Stop).Path
$resolvedOutputRoot = (Resolve-Path -LiteralPath $TestStandOutputRoot -ErrorAction Stop).Path
$warmupMode = $TestStandWarmup
$renderReport = [bool]$TestStandRenderReport
$closeLabVIEW = [bool]$TestStandCloseLabVIEW
$closeLVCompare = [bool]$TestStandCloseLVCompare
$disableTimeout = [bool]$TestStandDisableTimeout
$timeoutValue = if ($PSBoundParameters.ContainsKey('TestStandTimeoutSeconds') -or $env:LOOP_TESTSTAND_TIMEOUT_SECONDS) { $TestStandTimeoutSeconds } else { $null }
$labviewPath = $TestStandLabVIEWPath
$labview64Path = $TestStandLabVIEW64Path
$labview32Path = $TestStandLabVIEW32Path
$lvcomparePath = $TestStandLVComparePath
$replaceFlags = [bool]$TestStandReplaceFlags
$executionCellLeasePath = $TestStandExecutionCellLeasePath
$executionCellId = $TestStandExecutionCellId
$executionCellLeaseId = $TestStandExecutionCellLeaseId
$executionCellLeaseMetadata = Get-ExecutionCellLeaseMetadata -LeasePath $executionCellLeasePath
$agentId = $TestStandAgentId
$agentClass = $TestStandAgentClass
$harnessInstanceLeasePath = $TestStandHarnessInstanceLeasePath
$harnessInstanceLeaseMetadata = Get-HarnessInstanceLeaseMetadata -LeasePath $harnessInstanceLeasePath
$harnessInstanceId = $TestStandHarnessInstanceId
$harnessIteration = [ref]0
$latestHarnessSessionMetadata = [ref]([pscustomobject]@{
harnessInstanceId = $null
harnessInstanceLeaseId = $null
harnessInstanceLeasePath = $null
})
$executor = {
param($CliPath,$BasePath,$HeadPath,$ArgsList)
$null = $CliPath
$currentIteration = $harnessIteration.Value + 1
$harnessIteration.Value = $currentIteration
$iterationLabel = ('iteration-{0:D4}' -f $currentIteration)
$iterationRoot = Join-Path $resolvedOutputRoot $iterationLabel
try { if (Test-Path -LiteralPath $iterationRoot) { Remove-Item -LiteralPath $iterationRoot -Recurse -Force -ErrorAction SilentlyContinue } } catch {}
New-Item -ItemType Directory -Path $iterationRoot -Force | Out-Null
$harnessParams = [ordered]@{
BaseVi = $BasePath
HeadVi = $HeadPath
OutputRoot = $iterationRoot
Warmup = $warmupMode
}
if ($labviewPath) { $harnessParams.LabVIEWExePath = $labviewPath }
if ($labview64Path) { $harnessParams.LabVIEW64ExePath = $labview64Path }
if ($labview32Path) { $harnessParams.LabVIEW32ExePath = $labview32Path }
if ($lvcomparePath) { $harnessParams.LVComparePath = $lvcomparePath }
if ($TestStandSuiteClass -ne 'single-compare') { $harnessParams.SuiteClass = $TestStandSuiteClass }
if ($agentId) { $harnessParams.AgentId = $agentId }
if ($agentClass) { $harnessParams.AgentClass = $agentClass }
if ($executionCellLeasePath) { $harnessParams.ExecutionCellLeasePath = $executionCellLeasePath }
if ($executionCellId) { $harnessParams.ExecutionCellId = $executionCellId }
if ($executionCellLeaseId) { $harnessParams.ExecutionCellLeaseId = $executionCellLeaseId }
if ($harnessInstanceLeasePath) { $harnessParams.HarnessInstanceLeasePath = $harnessInstanceLeasePath }
if ($harnessInstanceId) { $harnessParams.HarnessInstanceId = $harnessInstanceId }
if ($renderReport) { $harnessParams.RenderReport = $true }
if ($closeLabVIEW) { $harnessParams.CloseLabVIEW = $true }
if ($closeLVCompare) { $harnessParams.CloseLVCompare = $true }
if ($disableTimeout) { $harnessParams.DisableTimeout = $true }
if ($timeoutValue -and $timeoutValue -gt 0) { $harnessParams.TimeoutSeconds = $timeoutValue }
if ($ArgsList -and $ArgsList.Count -gt 0) { $harnessParams.Flags = $ArgsList }
if ($replaceFlags) { $harnessParams.ReplaceFlags = $true }
$originalHarnessLog = $env:HARNESS_LOG
$restoreHarnessLog = $false
if ([string]::IsNullOrWhiteSpace($originalHarnessLog)) {
$env:HARNESS_LOG = Join-Path (Split-Path -Parent $iterationRoot) 'harness-log.ndjson'
$restoreHarnessLog = $true
}
$activeHarnessLog = $env:HARNESS_LOG
if ($activeHarnessLog) {
$logDir = Split-Path -Parent $activeHarnessLog
if ($logDir -and -not (Test-Path -LiteralPath $logDir)) { New-Item -ItemType Directory -Path $logDir -Force | Out-Null }
}
$iterationExecutionTopology = [ordered]@{
runtimeSurface = 'windows-native-teststand'
processModelClass = if ($TestStandSuiteClass -eq 'dual-plane-parity') { 'parallel-process-model' } else { 'sequential-process-model' }
windowsOnly = $true
requestedSimultaneous = ($TestStandSuiteClass -eq 'dual-plane-parity')
cellClass = $executionCellLeaseMetadata.cellClass
executionCellLeasePath = $executionCellLeasePath
executionCellId = $executionCellId
executionCellLeaseId = $executionCellLeaseId
harnessInstanceLeasePath = $harnessInstanceLeasePath
harnessInstanceLeaseId = $harnessInstanceLeaseMetadata.leaseId
harnessInstanceId = $harnessInstanceId
}
$exitCode = 0
Write-JsonEvent 'harnessInvoke' @{ iteration=$currentIteration; output=$iterationRoot; status='start'; executionTopology=$iterationExecutionTopology }
try {
& $resolvedHarness @harnessParams | Out-Null
$exitCode = $LASTEXITCODE
$sessionMetadata = Get-TestStandHarnessSessionMetadata -IterationRoot $iterationRoot
if (-not [string]::IsNullOrWhiteSpace($sessionMetadata.harnessInstanceId) -or -not [string]::IsNullOrWhiteSpace($sessionMetadata.harnessInstanceLeaseId) -or -not [string]::IsNullOrWhiteSpace($sessionMetadata.harnessInstanceLeasePath)) {
$latestHarnessSessionMetadata.Value = $sessionMetadata
if (-not [string]::IsNullOrWhiteSpace($sessionMetadata.harnessInstanceId)) {
$iterationExecutionTopology.harnessInstanceId = $sessionMetadata.harnessInstanceId
}
if (-not [string]::IsNullOrWhiteSpace($sessionMetadata.harnessInstanceLeaseId)) {
$iterationExecutionTopology.harnessInstanceLeaseId = $sessionMetadata.harnessInstanceLeaseId
}
if (-not [string]::IsNullOrWhiteSpace($sessionMetadata.harnessInstanceLeasePath)) {
$iterationExecutionTopology.harnessInstanceLeasePath = $sessionMetadata.harnessInstanceLeasePath
}
}
} catch {
Write-JsonEvent 'harnessResult' @{ iteration=$currentIteration; status='exception'; message=$_.Exception.Message; executionTopology=$iterationExecutionTopology }
throw
} finally {
if ($restoreHarnessLog) {
Remove-Item Env:HARNESS_LOG -ErrorAction SilentlyContinue
} else {
$env:HARNESS_LOG = $originalHarnessLog
}
}
Write-JsonEvent 'harnessResult' @{ iteration=$currentIteration; exitCode=$exitCode; executionTopology=$iterationExecutionTopology }
return $exitCode
}
$skipValidation = $false
$passThroughPaths = $false
$bypassCliValidation = $true
$harnessPlan = [ordered]@{
path = $resolvedHarness
output = $resolvedOutputRoot
warmup = $warmupMode
suiteClass = $TestStandSuiteClass
runtimeSurface = 'windows-native-teststand'
processModelClass = if ($TestStandSuiteClass -eq 'dual-plane-parity') { 'parallel-process-model' } else { 'sequential-process-model' }
windowsOnly = $true
requestedSimultaneous = ($TestStandSuiteClass -eq 'dual-plane-parity')
renderReport = $renderReport
closeLabVIEW = $closeLabVIEW
closeLVCompare = $closeLVCompare
disableTimeout = $disableTimeout
timeout = $timeoutValue
labviewPath = $labviewPath
labview64Path = $labview64Path
labview32Path = $labview32Path
agentId = $agentId
agentClass = $agentClass
cellClass = $executionCellLeaseMetadata.cellClass
operatorAuthorizationRef = $executionCellLeaseMetadata.operatorAuthorizationRef
premiumSaganMode = [bool]$executionCellLeaseMetadata.premiumSaganMode
executionCellLeasePath = $executionCellLeasePath
executionCellId = $executionCellId
executionCellLeaseId = $executionCellLeaseId
harnessInstanceLeasePath = $harnessInstanceLeasePath
harnessInstanceLeaseId = $harnessInstanceLeaseMetadata.leaseId
harnessInstanceId = $harnessInstanceId
}
}
$invokeParams = @{
Base = $Base
Head = $Head
MaxIterations = $MaxIterations
IntervalSeconds = $IntervalSeconds
DiffSummaryFormat = $DiffSummaryFormat
DiffSummaryPath = $DiffSummaryPath
FailOnDiff = $FailOnDiff
HistogramBins = $HistogramBins
Quiet = $true
}
if ($explicitLvCompareArgs) { $invokeParams.LvCompareArgs = $LvCompareArgs }
if ($CustomPercentiles) { $invokeParams.CustomPercentiles = $CustomPercentiles }
if ($MetricsSnapshotEvery -gt 0) {
$invokeParams.MetricsSnapshotEvery = $MetricsSnapshotEvery
$invokeParams.MetricsSnapshotPath = $MetricsSnapshotPath
}
if ($RunSummaryJsonPath) { $invokeParams.RunSummaryJsonPath = $RunSummaryJsonPath }
if ($AdaptiveInterval) { $invokeParams.AdaptiveInterval = $true }
if ($executor) {
$invokeParams.CompareExecutor = $executor
if ($skipValidation) { $invokeParams.SkipValidation = $true }
if ($passThroughPaths) { $invokeParams.PassThroughPaths = $true }
if ($bypassCliValidation) { $invokeParams.BypassCliValidation = $true }
}
if ($RenderReport) { $invokeParams.RenderReport = $true }
function Write-Detail {
param([string]$Message,[string]$Level='Info')
switch ($LogVerbosity) {
'Quiet' { if ($Level -eq 'Error') { Write-Host $Message } }
'Normal' { if ($Level -notin @('Debug','Trace')) { Write-Host $Message } }
'Verbose' { if ($Level -ne 'Trace') { Write-Host $Message } }
'Debug' { Write-Host $Message }
}
}
function Write-JsonEvent {
param([string]$Type,[hashtable]$Data)
if (-not $JsonLogPath) { return }
$schemaVersion = 'loop-script-events-v1'
$payload = [ordered]@{
timestamp = (Get-Date).ToString('o')
type = $Type
schema = $schemaVersion
}
if ($Data) { foreach ($k in $Data.Keys) { $payload[$k] = $Data[$k] } }
Ensure-JsonLog -Path $JsonLogPath
try { ($payload | ConvertTo-Json -Compress) | Add-Content -Path $JsonLogPath } catch { Write-Detail "Failed JSON log append: $($_.Exception.Message)" 'Error' }
}
function Invoke-LabVIEWCloser {
param([string]$Context = 'post-loop')
$closeScript = Join-Path $repoRoot 'tools' 'Close-LabVIEW.ps1'
if (-not (Test-Path -LiteralPath $closeScript -PathType Leaf)) {
Write-Detail "LabVIEW close skipped (script missing at $closeScript)." 'Debug'
Write-JsonEvent 'labviewClose' @{ status='skipped'; reason='script-missing'; context=$Context; path=$closeScript }
return
}
$version = @(
$env:LOOP_LABVIEW_VERSION,
$env:LABVIEW_VERSION,
$env:MINIMUM_SUPPORTED_LV_VERSION
) | Where-Object { $_ } | Select-Object -First 1
if (-not $version) { $version = '2025' }
$bitness = @(
$env:LOOP_LABVIEW_BITNESS,
$env:LABVIEW_BITNESS,
$env:MINIMUM_SUPPORTED_LV_BITNESS
) | Where-Object { $_ } | Select-Object -First 1
if (-not $bitness) { $bitness = '64' }
Write-Detail "Invoking Close-LabVIEW.ps1 (version=$version, bitness=$bitness, context=$Context)." 'Debug'
try {
& $closeScript -MinimumSupportedLVVersion $version -SupportedBitness $bitness
$exitCode = $LASTEXITCODE
Write-JsonEvent 'labviewClose' @{
status = if ($exitCode -eq 0) { 'completed' } else { 'failed' }
exitCode = $exitCode
version = $version
bitness = $bitness
context = $Context
}
if ($exitCode -ne 0) {
Write-Detail "Close-LabVIEW.ps1 exited with code $exitCode." 'Error'
}
} catch {
Write-JsonEvent 'labviewClose' @{
status = 'exception'
message = $_.Exception.Message
version = $version
bitness = $bitness
context = $Context
}
Write-Detail "Close-LabVIEW.ps1 threw: $($_.Exception.Message)" 'Error'
}
}
$shouldCloseLabVIEW = (-not $UseTestStandHarness) -and (-not $executor)
function Ensure-JsonLog {
param([string]$Path)
if (-not $Path) { return }
$dir = Split-Path -Parent $Path
if ($dir -and -not (Test-Path $dir)) { New-Item -ItemType Directory -Path $dir | Out-Null }
if (-not (Test-Path $Path)) {
New-Item -ItemType File -Path $Path | Out-Null
# meta create event (cannot call Write-JsonEvent recursively before file exists safely)
($([ordered]@{ timestamp=(Get-Date).ToString('o'); type='meta'; action='create'; target=$Path; schema='loop-script-events-v1' }) | ConvertTo-Json -Compress) | Add-Content -Path $Path
return
}
$needsRotate = $false
if ($JsonLogMaxBytes -and (Get-Item $Path).Length -gt $JsonLogMaxBytes) { $needsRotate = $true }
if ($JsonLogMaxAgeSeconds -and $JsonLogMaxAgeSeconds -gt 0) {
$ageSec = (New-TimeSpan -Start (Get-Item $Path).CreationTimeUtc -End (Get-Date).ToUniversalTime()).TotalSeconds
if ($ageSec -ge $JsonLogMaxAgeSeconds) { $needsRotate = $true }
}
if ($needsRotate) { Rotate-JsonLog -Path $Path }
}
function Rotate-JsonLog {
param([string]$Path)
try {
$base = Split-Path -Leaf $Path
$dir = Split-Path -Parent $Path
$rolls = Get-ChildItem -Path $dir -Filter "$base.*.roll" -ErrorAction SilentlyContinue | Sort-Object Name
$next = if ($rolls) { ([int]($rolls[-1].Name.Split('.')[-2]) + 1) } else { 1 }
$rolled = Join-Path $dir "$base.$next.roll"
Move-Item -Path $Path -Destination $rolled -Force
New-Item -ItemType File -Path $Path | Out-Null
($([ordered]@{ timestamp=(Get-Date).ToString('o'); type='meta'; action='rotate'; from=$rolled; to=$Path; schema='loop-script-events-v1' }) | ConvertTo-Json -Compress) | Add-Content -Path $Path
if ($JsonLogMaxRolls -and $JsonLogMaxRolls -gt 0) {
$all = Get-ChildItem -Path $dir -Filter "$base.*.roll" | Sort-Object { $_.Name -replace '.*\\.(\d+)\.roll','$1' -as [int] }
if ($all.Count -gt $JsonLogMaxRolls) {
$remove = $all | Select-Object -First ($all.Count - $JsonLogMaxRolls)
foreach ($r in $remove) { Remove-Item -Path $r.FullName -Force -ErrorAction SilentlyContinue }
}
}
} catch {
Write-Detail "Log rotation failed: $($_.Exception.Message)" 'Error'
}
}
Write-Detail ("Resolved LogVerbosity=$LogVerbosity DryRun=$($DryRun.IsPresent) Simulate=$simulate") 'Debug'
Write-Detail ("Invocation parameters (pre-run):" )
Write-Detail (($invokeParams.Keys | Sort-Object | ForEach-Object { " $_ = $($invokeParams[$_])" }) -join [Environment]::NewLine) 'Debug'
if ($UseTestStandHarness -and $harnessPlan) {
Write-Detail ("TestStand harness path: $($harnessPlan.path)")
Write-Detail ("TestStand output root: $($harnessPlan.output)") 'Debug'
Write-Detail ("TestStand warmup mode: $($harnessPlan.warmup) renderReport=$($harnessPlan.renderReport) closeLabVIEW=$($harnessPlan.closeLabVIEW) closeLVCompare=$($harnessPlan.closeLVCompare) disableTimeout=$($harnessPlan.disableTimeout) timeout=$($harnessPlan.timeout)") 'Debug'
}
$planPayload = [ordered]@{
simulate = $simulate
dryRun = $DryRun.IsPresent
maxIterations = $MaxIterations
interval = $IntervalSeconds
diffSummaryFormat = $DiffSummaryFormat
harness = $UseTestStandHarness
}
if ($UseTestStandHarness -and $harnessPlan) {
$planPayload.harnessPath = $harnessPlan.path
$planPayload.harnessOutput = $harnessPlan.output
$planPayload.harnessWarmup = $harnessPlan.warmup
$planPayload.harnessRenderReport = $harnessPlan.renderReport
$planPayload.harnessRuntimeSurface = $harnessPlan.runtimeSurface
$planPayload.harnessProcessModelClass = $harnessPlan.processModelClass
$planPayload.harnessRequestedSimultaneous = $harnessPlan.requestedSimultaneous
$planPayload.executionTopology = [ordered]@{
runtimeSurface = $harnessPlan.runtimeSurface
processModelClass = $harnessPlan.processModelClass
windowsOnly = $harnessPlan.windowsOnly
requestedSimultaneous = $harnessPlan.requestedSimultaneous
cellClass = $harnessPlan.cellClass
executionCellLeasePath = $harnessPlan.executionCellLeasePath
executionCellId = $harnessPlan.executionCellId
executionCellLeaseId = $harnessPlan.executionCellLeaseId
harnessInstanceLeasePath = $harnessPlan.harnessInstanceLeasePath
harnessInstanceLeaseId = $harnessPlan.harnessInstanceLeaseId
harnessInstanceId = $harnessPlan.harnessInstanceId
}
}
Write-JsonEvent 'plan' $planPayload
if ($DryRun) {
Write-Detail 'Dry run requested; skipping Invoke-IntegrationCompareLoop execution.'
# Show inferred file outputs
if ($DiffSummaryPath) { Write-Detail "Would write diff summary to: $DiffSummaryPath" }
if ($MetricsSnapshotEvery -gt 0) { Write-Detail "Would emit snapshots to: $MetricsSnapshotPath every $MetricsSnapshotEvery iteration(s)" }
if ($RunSummaryJsonPath) { Write-Detail "Would write run summary JSON to: $RunSummaryJsonPath" }
if ($UseTestStandHarness -and $harnessPlan) {
Write-Detail ("Would invoke TestStand harness at $($harnessPlan.path) with output root $($harnessPlan.output)")
}
$dryRunPayload = @{ diffSummaryPath=$DiffSummaryPath; snapshots=$MetricsSnapshotPath; runSummary=$RunSummaryJsonPath; harness=$UseTestStandHarness }
if ($UseTestStandHarness -and $harnessPlan) {
$dryRunPayload.harnessPath = $harnessPlan.path
$dryRunPayload.harnessOutput = $harnessPlan.output
$dryRunPayload.harnessRuntimeSurface = $harnessPlan.runtimeSurface
$dryRunPayload.harnessProcessModelClass = $harnessPlan.processModelClass
$dryRunPayload.executionTopology = [ordered]@{
runtimeSurface = $harnessPlan.runtimeSurface
processModelClass = $harnessPlan.processModelClass
windowsOnly = $harnessPlan.windowsOnly
requestedSimultaneous = $harnessPlan.requestedSimultaneous
cellClass = $harnessPlan.cellClass
executionCellLeasePath = $harnessPlan.executionCellLeasePath
executionCellId = $harnessPlan.executionCellId
executionCellLeaseId = $harnessPlan.executionCellLeaseId
harnessInstanceLeasePath = $harnessPlan.harnessInstanceLeasePath
harnessInstanceLeaseId = $harnessPlan.harnessInstanceLeaseId
harnessInstanceId = $harnessPlan.harnessInstanceId
}
}
Write-JsonEvent 'dryRun' $dryRunPayload
Set-LoopExit 0
}
try {
$result = Invoke-IntegrationCompareLoop @invokeParams
} catch {
if ($shouldCloseLabVIEW) {
Invoke-LabVIEWCloser -Context 'invoke-exception'
}
throw
}
if ($UseTestStandHarness -and $harnessPlan -and $latestHarnessSessionMetadata.Value) {
if (-not [string]::IsNullOrWhiteSpace($latestHarnessSessionMetadata.Value.harnessInstanceId)) {
$harnessPlan.harnessInstanceId = $latestHarnessSessionMetadata.Value.harnessInstanceId
}
if (-not [string]::IsNullOrWhiteSpace($latestHarnessSessionMetadata.Value.harnessInstanceLeaseId)) {
$harnessPlan.harnessInstanceLeaseId = $latestHarnessSessionMetadata.Value.harnessInstanceLeaseId
}
if (-not [string]::IsNullOrWhiteSpace($latestHarnessSessionMetadata.Value.harnessInstanceLeasePath)) {
$harnessPlan.harnessInstanceLeasePath = $latestHarnessSessionMetadata.Value.harnessInstanceLeasePath
}
}
Write-JsonEvent 'result' (@{ iterations=$result.Iterations; diffs=$result.DiffCount; errors=$result.ErrorCount; succeeded=$result.Succeeded })
# Final status JSON emission (independent of run summary JSON produced by loop if that param was set)
if ($FinalStatusJsonPath) {
try {
$obj = [ordered]@{
schema = 'loop-final-status-v1'
timestamp = (Get-Date).ToString('o')
iterations = $result.Iterations
diffs = $result.DiffCount
errors = $result.ErrorCount
succeeded = $result.Succeeded
averageSeconds = $result.AverageSeconds
totalSeconds = $result.TotalSeconds
percentiles = $result.Percentiles
histogram = $result.Histogram
diffSummaryEmitted = [bool]$result.DiffSummary
basePath = $result.BasePath
headPath = $result.HeadPath
}
if ($UseTestStandHarness -and $harnessPlan) {
$obj.harness = [ordered]@{
path = $harnessPlan.path
output = $harnessPlan.output
suiteClass = $harnessPlan.suiteClass
runtimeSurface = $harnessPlan.runtimeSurface
processModelClass = $harnessPlan.processModelClass
windowsOnly = $harnessPlan.windowsOnly
requestedSimultaneous = $harnessPlan.requestedSimultaneous
cellClass = $harnessPlan.cellClass
operatorAuthorizationRef = $harnessPlan.operatorAuthorizationRef
premiumSaganMode = $harnessPlan.premiumSaganMode
executionCellLeasePath = $harnessPlan.executionCellLeasePath
executionCellId = $harnessPlan.executionCellId
executionCellLeaseId = $harnessPlan.executionCellLeaseId
harnessInstanceLeasePath = $harnessPlan.harnessInstanceLeasePath
harnessInstanceLeaseId = $harnessPlan.harnessInstanceLeaseId
harnessInstanceId = $harnessPlan.harnessInstanceId
}
}
$json = $obj | ConvertTo-Json -Depth 5
$finalDir = Split-Path -Parent $FinalStatusJsonPath
if ($finalDir -and -not (Test-Path $finalDir)) { New-Item -ItemType Directory -Path $finalDir | Out-Null }
Set-Content -Path $FinalStatusJsonPath -Value $json
Write-Detail "Final status JSON: $FinalStatusJsonPath" 'Debug'
Write-JsonEvent 'finalStatusEmitted' @{ path=$FinalStatusJsonPath }
} catch {
Write-Detail "Failed to write FinalStatusJsonPath: $($_.Exception.Message)" 'Error'
}
}
# Emit concise console summary
$summaryLines = @()
$summaryLines += '=== Integration Compare Loop Result ==='
$summaryLines += "Base: $($result.BasePath)"
$summaryLines += "Head: $($result.HeadPath)"
$summaryLines += "Harness: $(if ($UseTestStandHarness -and $harnessPlan) { 'TestStand (' + $harnessPlan.path + ')' } else { 'LVCompare CLI' })"
$summaryLines += "Iterations: $($result.Iterations) (Diffs=$($result.DiffCount) Errors=$($result.ErrorCount))"
if ($result.Percentiles) { $summaryLines += "Latency p50/p90/p99: $($result.Percentiles.p50)/$($result.Percentiles.p90)/$($result.Percentiles.p99) s" }
if ($result.DiffSummary) { $summaryLines += 'Diff summary fragment emitted.' }
if ($RunSummaryJsonPath -and (Test-Path $RunSummaryJsonPath)) { $summaryLines += "Run summary JSON: $RunSummaryJsonPath" }
if ($MetricsSnapshotEvery -gt 0 -and (Test-Path $MetricsSnapshotPath)) { $summaryLines += "Snapshots NDJSON: $MetricsSnapshotPath" }
if (-not $NoConsoleSummary) { $summaryLines | ForEach-Object { Write-Detail $_ } } else { Write-Detail 'Console summary suppressed (-NoConsoleSummary).' 'Debug' }
# Append diff summary fragment to GitHub step summary if running in Actions
if (-not $NoStepSummary -and $env:GITHUB_STEP_SUMMARY -and $result.DiffSummary) {
try { Add-Content -Path $env:GITHUB_STEP_SUMMARY -Value $result.DiffSummary; Write-JsonEvent 'stepSummaryAppended' @{ path=$env:GITHUB_STEP_SUMMARY } } catch { Write-Warning "Failed to append to GITHUB_STEP_SUMMARY: $($_.Exception.Message)" }
} elseif ($result.DiffSummary) {
Write-Detail 'Step summary append skipped (suppressed or not in Actions).' 'Debug'
}
if ($shouldCloseLabVIEW) {
Invoke-LabVIEWCloser -Context 'post-loop'
}
# Exit code semantics: 0 when succeeded (even if diffs unless FailOnDiff terminated early), 1 if any errors encountered
if (-not $result.Succeeded) { Set-LoopExit 1 }
if ($DiffExitCode -and $result.DiffCount -gt 0 -and $result.ErrorCount -eq 0) { Set-LoopExit $DiffExitCode }
Set-LoopExit 0
\