Skip to content

Enable Pester 6 Run.Parallel via full C# migration of domain types - #115

Open
HeyItsGilbert wants to merge 8 commits into
mainfrom
feat/pester6-parallel-csharp-migration
Open

HeyItsGilbert wants to merge 8 commits into
mainfrom
feat/pester6-parallel-csharp-migration

Conversation

@HeyItsGilbert

Copy link
Copy Markdown
Owner

Summary

Gatekeeper's domain types (Condition, Property, PropertySet, Rule, FeatureFlag, Effect, Operator, GatekeeperPath, and the three ArgumentTransformationAttribute classes) were PowerShell class/enum definitions, re-compiled fresh on every module import. Under Pester 6's experimental Run.Parallel (multiple test-file workers, one runspace each, sharing a single process and its process-wide TypeAccelerators table), 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.

Before (PowerShell `class`, one compiled type per runspace)
  Worker A: Import-Module -> compiles Condition_A -> registers accelerator "Condition" -> Condition_A
  Worker B: Import-Module -> compiles Condition_B -> registers accelerator "Condition" -> Condition_B  (overwrites A's slot)
  Worker A: $obj -is [Condition]   # resolves via the now-shared slot -> Condition_B -> FAILS, $obj was built from Condition_A

After (C#, Add-Type, compiled once per process)
  Worker A: ScriptsToProcess -> Add-Type already compiled? no -> compile Condition -> register accelerator "Condition" -> Condition
  Worker B: ScriptsToProcess -> Add-Type already compiled? yes (same AppDomain) -> re-register same Type (no-op)
  Worker A: $obj -is [Condition]   # same Type everywhere -> PASSES
Gatekeeper/
├── Classes/
│   ├── CompiledTypes.ps1      # new: every domain type, one guarded Add-Type call
│   ├── FeatureFlag.ps1        # gutted to a pointer comment
│   └── Property.ps1           # gutted to a pointer comment
├── Enums/Effect.ps1            # gutted to a pointer comment
├── Gatekeeper.psd1             # ScriptsToProcess: CompiledTypes.ps1 now first
├── Gatekeeper.psm1             # dead per-import TypeAccelerators loop removed
├── Private/Read-FeatureFlag.ps1   # unwraps MethodInvocationException from direct static calls
├── Private/Read-PropertySet.ps1   # same
Pester.BeforeContainer.ps1        # new: per-worker env bootstrap (+ a BuildHelpers discovery-race fix)
psakeFile.ps1                     # new TestParallel task
tests/Classes.tests.ps1           # +Operator validation regression coverage
tests/Architecture.tests.ps1      # rewritten: reflection against compiled types, not file-text grep

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 missing Condition(string, object[]) constructor used only by New-ConditionGroup, and Operator silently skipping the enum validation its sibling Effect field got).

Evidence

  • Before: full 17-file parallel suite: 143 passed / 38 failed — "Cannot convert type to FeatureFlag: FeatureFlag", "Expected type [Rule] ... but got Rule with type [Rule]" (type-identity collisions). Sequential Test task: 399/0/5 passed (parallel was simply unusable, not a correctness issue in the sequential path).
  • After: sequential 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 in MethodInvocationException unless 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).

…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).
Copilot AI balanced review requested due to automatic review settings November 25, 2026 22:18
@github-actions

Copy link
Copy Markdown

Test Results

    3 files    414 suites   5s ⏱️
  409 tests   404 ✅  5 💤 0 ❌
1 218 runs  1 203 ✅ 15 💤 0 ❌

Results for commit 522c8e5.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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
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

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants