Repository navigation
Enable Pester 6 Run.Parallel via full C# migration of domain types - #115
Open
HeyItsGilbert wants to merge 8 commits into
Open
HeyItsGilbert wants to merge 8 commits into
HeyItsGilbert wants to merge 8 commits into
Conversation
…clude parallel is architecturally not viable
…el now fully viable Full port, not just the Condition spike: Effect, Operator, GatekeeperPath, Condition, PropertyValidation, Property, PropertySet, Rule, FeatureFlag, and all three ArgumentTransformationAttribute classes are now compiled once via Add-Type (Classes/CompiledTypes.ps1), replacing every PowerShell `class`/`enum` definition that previously caused cross-runspace type- identity failures under Pester 6 Run.Parallel. Non-obvious pitfalls hit and fixed along the way: - ScriptsToProcess ordering: the compile/accelerator-registration step must run before Property.ps1/FeatureFlag.ps1 (now near-empty pointer comments), which still run via ScriptsToProcess ahead of RootModule. - Module-private functions (ConvertFrom-JsonToHashtable) aren't resolvable via RunspaceMode.CurrentRunspace when a C#-compiled static method is invoked directly from outside module scope (e.g. a test calling [PropertySet]::FromFile(...) directly) - switched to the public ConvertFrom-Json -AsHashtable cmdlet instead. - PSObject unwrapping: a raw C# `is IDictionary`/`is Condition` check does not see through a PSObject wrapper the way PowerShell's own `-is` operator does; all three Transform() methods now unwrap explicitly. - Write-Warning from a nested PowerShell.Create(RunspaceMode.CurrentRunspace) call writes straight to the host, bypassing the caller's own 3>&1 redirection (confirmed empirically). Property.Validate is now split into a C# ValidateCore (decides pass/fail, records the message) plus a real PowerShell ScriptMethod "Validate" (registered via Update-TypeData) that calls it and emits the actual Write-Warning from genuine script context. - Calling a C#-compiled static method that throws, directly from PowerShell script (e.g. [FeatureFlag]::FromFile(...)), gets wrapped in a MethodInvocationException - Read-FeatureFlag.ps1/Read-PropertySet.ps1 now unwrap it to preserve the original error-message contract. - Missed the Condition(string connective, Condition[] conditions) constructor (used only by New-ConditionGroup, which has no test coverage) on the first pass; added and smoke-tested directly. - Architecture.tests.ps1's 'Class pattern consistency' and 'Effect enum matches configuration' tests grepped Classes/*.ps1 and Enums/Effect.ps1 text for PowerShell `class`/`enum` syntax that no longer exists there; rewritten to use reflection against the compiled types instead, same intent (every primary type exposes FromJson/FromFile; Effect matches Configuration.psd1's Logging keys). - Fixed a separate BuildHelpers module-discovery race in Pester.BeforeContainer.ps1 (Get-Module -ListAvailable transiently found nothing under 17-way concurrency) with the same Monitor-lock pattern. Verified: sequential Test task 399/0/5 (several runs). Full 17-file parallel suite: 399/0/5 across 3 consecutive fresh-session runs after the BuildHelpers fix (zero type-identity failures, zero flakes). psakeFile.ps1's TestParallel task description/comment updated from 'NOT VIABLE' to reflect the resolved state.
…reflection-based assertions The 'Class pattern consistency' and 'Effect enum matches configuration' contexts resolve [Effect]/'FeatureFlag' -as [type] via reflection against the compiled module types - unlike the original text-grepping version of this file, which never needed the module imported at all. The file 'passed' in the full suite only because some other file (or the build's own GenerateMarkdown/BuildHelp steps, which import the module to generate docs) had already imported Gatekeeper earlier in the same process, making the type accelerators resolvable incidentally. Running this file alone would have failed. Added the same explicit Import-Module every other test file already uses; verified passing standalone (4/4) and unchanged in the full suite (sequential 399/0/5, parallel 399/0/5).
- The original PowerShell `class Condition` declared `[Operator]$Operator`, so an invalid operator value threw immediately at construction time via PowerShell's own enum coercion. The C# port kept Operator as a plain string with no validation while its sibling Rule.Effect *was* correctly ported with Enum.Parse validation (ParseEffect) - an asymmetric, silent regression caught by code review, not by any test (no test constructs a Condition with a bad Operator directly). - Added Condition.ParseOperator, mirroring Rule.ParseEffect exactly, and applied it when assigning Operator from a Hashtable. Fully-qualified Gatekeeper.Operator in the helper since the bare name would otherwise resolve to the instance field (string) of the same name. - Verified: invalid operator now throws at construction time (matching original contract); valid operators still accepted case-insensitively. Sequential 399/0/5, parallel 399/0/5, PSScriptAnalyzer clean.
…dation The previous fix (5d42193) had no test guarding it - exactly how the original regression shipped unnoticed. Added two tests to Classes.tests.ps1: - an invalid Operator throws at construction time (not deferred to Test-Condition's evaluation-time switch) - a valid Operator is accepted case-insensitively and normalized to its canonical enum name Verified: sequential 401/0/5, parallel 401/0/5 (both files/counts went 399 -> 401 for the two new tests, zero failures).
Test Results 3 files 414 suites 5s ⏱️ Results for commit 522c8e5. |
Contributor
There was a problem hiding this comment.
🟡 Changes recommended
Unresolved critical regressions break PowerShell 5.1 imports and clean-checkout test discovery, allow empty conditions to enable features, and let saves return successfully without updating files.
14 open issues
Preserve PowerShell 5.1 compatibility or raise the minimum version · New Make nested write and rename errors terminating · New Reject empty AllOf and Not groups during conversion · New Skip accelerator updates when the type is already registered · New Build module artifacts before Pester discovery · New Compare file extensions case-insensitively · New Restore the enum-typed Condition.Operator API · New Reject undefined numeric Condition.Operator values · New Preserve scalar Enum values as single-element arrays · New Normalize New-Property type before validation switches · New Use case-insensitive Hashtables in both PropertySet constructors · New Reject undefined numeric rule and default effects · New Treat scalar string tags as a single tag · New Register the original GatekeeperPath and PropertyValidation type names · New
What changed in this PR
This PR migrates Gatekeeper’s domain types from PowerShell definitions to shared C# types, aiming to eliminate type-identity collisions during Pester 6 parallel testing.
Changes:
- Centralizes domain types, argument transformations, and type registration in a guarded compilation step.
- Adds parallel test execution and per-worker environment initialization.
- Updates architecture tests, operator-validation coverage, test isolation, and file-loading error handling.
| File | Description |
|---|---|
tests/Test-FeatureFlag.tests.ps1 |
Removes the local build fallback. |
tests/Test-Condition.tests.ps1 |
Removes two misleading comments. |
tests/NewFiles.tests.ps1 |
Removes configuration mocks and global test configuration. |
tests/Meta.tests.ps1 |
Removes the Unicode-file count assertion. |
tests/Import-GatekeeperConfig.tests.ps1 |
Makes the cache test independent of test order. |
tests/Classes.tests.ps1 |
Adds operator-validation tests and removes the build fallback. |
tests/Architecture.tests.ps1 |
Uses reflection to inspect compiled types. |
psakeFile.ps1 |
Adds the Pester 6 TestParallel task. |
Pester.BeforeContainer.ps1 |
Adds serialized test-environment initialization. |
Gatekeeper/Private/Read-PropertySet.ps1 |
Unwraps file-loading exception messages. |
Gatekeeper/Private/Read-FeatureFlag.ps1 |
Unwraps file-loading exception messages. |
Gatekeeper/Gatekeeper.psm1 |
Removes module-level accelerator registration and cleanup. |
Gatekeeper/Gatekeeper.psd1 |
Loads compiled types before other initialization scripts. |
Gatekeeper/Enums/Effect.ps1 |
Replaces the enum definition with a migration pointer comment. |
Gatekeeper/Classes/Property.ps1 |
Replaces property-type definitions with pointer comments. |
Gatekeeper/Classes/FeatureFlag.ps1 |
Replaces feature-flag-related definitions with pointer comments. |
Gatekeeper/Classes/CompiledTypes.ps1 |
Implements shared C# types, PowerShell interoperation, and registration. |
Review effort: Balanced
| [System.Threading.Monitor]::Enter($TypeAcceleratorsClass) | ||
| try { | ||
| if (-not ('Gatekeeper.FeatureFlag' -as [type])) { | ||
| Add-Type -Language CSharp -ReferencedAssemblies 'System.Management.Automation', 'System.Linq', 'System.Collections', 'System.Text.RegularExpressions' -TypeDefinition @' |
Comment on lines
+208
to
+218
| ps.AddCommand("Set-Content").AddParameter("Path", path).AddParameter("Value", value); | ||
| ps.Invoke(); | ||
| } | ||
| } | ||
|
|
||
| public static void MoveItemForce(string path, string destination) | ||
| { | ||
| using (var ps = NewPS()) | ||
| { | ||
| ps.AddCommand("Move-Item").AddParameter("Path", path).AddParameter("Destination", destination).AddParameter("Force"); | ||
| ps.Invoke(); |
| { | ||
| result.Add(item is Condition c ? c : new Condition((Hashtable)item)); | ||
| } | ||
| return result; |
Comment on lines
+969
to
+970
| [void]$TypeAcceleratorsClass::Remove($name) | ||
| $TypeAcceleratorsClass::Add($name, $acceleratorTypes[$name]) |
| throw 'BuildHelpers module is required to bootstrap the build environment for tests.' | ||
| } | ||
| Import-Module -Name BuildHelpers -Force -Verbose:$false | ||
| BuildHelpers\Set-BuildEnvironment -Path $PSScriptRoot -Force -ErrorAction Stop |
| { | ||
| LastValidationWarning = null; | ||
| if (Validation == null) { return true; } | ||
| switch (Type) |
Comment on lines
+643
to
+648
| Properties = new Hashtable(); | ||
| } | ||
|
|
||
| public PropertySet(Hashtable rawData) | ||
| { | ||
| Properties = new Hashtable(); |
Comment on lines
+783
to
+784
| if (value is Effect e) { return e; } | ||
| return (Effect)System.Enum.Parse(typeof(Effect), value.ToString(), true); |
| if (source == null) { return null; } | ||
| if (source is string[] arr) { return arr; } | ||
| var list = new List<string>(); | ||
| foreach (var item in (IEnumerable)source) { list.Add(item?.ToString()); } |
| 'Property' = [Gatekeeper.Property] | ||
| 'PropertySet' = [Gatekeeper.PropertySet] | ||
| 'Rule' = [Gatekeeper.Rule] | ||
| 'FeatureFlag' = [Gatekeeper.FeatureFlag] |
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.


Summary
Gatekeeper's domain types (
Condition,Property,PropertySet,Rule,FeatureFlag,Effect,Operator,GatekeeperPath, and the threeArgumentTransformationAttributeclasses) were PowerShellclass/enumdefinitions, re-compiled fresh on every module import. Under Pester 6's experimentalRun.Parallel(multiple test-file workers, one runspace each, sharing a single process and its process-wideTypeAcceleratorstable), the last worker to import always wins the shared accelerator slot — every other worker's already-built objects then fail identity checks (-is,Should -BeOfType, argument transforms) against a same-named-but-unrelated compiled type.Validated with a narrow spike first (convert only
Condition, prove the theory on a 2-file bisection) before committing to the full port — see commit history for the incremental trail, including two real bugs caught along the way that had zero prior test coverage (a missingCondition(string, object[])constructor used only byNew-ConditionGroup, andOperatorsilently skipping the enum validation its siblingEffectfield got).Evidence
"Cannot convert type to FeatureFlag: FeatureFlag","Expected type [Rule] ... but got Rule with type [Rule]"(type-identity collisions). SequentialTesttask: 399/0/5 passed (parallel was simply unusable, not a correctness issue in the sequential path).Test: 401/0/5 passed. Full parallel suite: 401/0/5 passed, confirmed across 3+ consecutive fresh-session runs.PSScriptAnalyzer: clean.Merge Danger
Door: Two-way. Every changed production file (
CompiledTypes.ps1+ the gutted stub files) can be reverted in one commit with no data migration — there's no persisted format change, only how the types are compiled in-process.Blast Radius: Internal implementation detail, not a public API change.
[Condition],[FeatureFlag], etc. still resolve identically for any external consumer of this module (same accelerator names, same public fields/methods). The one observable behavior change: calling a C#-compiled static method directly that throws (e.g.[FeatureFlag]::FromFile(...)) now wraps the exception inMethodInvocationExceptionunless unwrapped — already handled at the two call sites that mattered (Read-FeatureFlag.ps1,Read-PropertySet.ps1); any other direct caller of these static methods outside this module would see the wrapped exception type (same message, different type/stack shape).