diff --git a/Engine/ScriptAnalyzer.cs b/Engine/ScriptAnalyzer.cs index da324dfe5..a525fcf15 100644 --- a/Engine/ScriptAnalyzer.cs +++ b/Engine/ScriptAnalyzer.cs @@ -707,7 +707,7 @@ private void Initialize( #if CORECLR // For Full CLR logger is loaded via Composition // But for Core CLR we need to load it explicitly - this.Loggers = GetInterfaceImplementationsFromAssembly(); + this.Loggers = GetInterfaceImplementationsFromAssembly(typeof(ScriptAnalyzer).GetTypeInfo().Assembly); #endif #region Initializes Rules @@ -866,36 +866,12 @@ private List GetValidCustomRulePaths(string[] customizedRulePath, PathIn } - private IEnumerable GetInterfaceImplementationsFromAssembly() where T : class + private IEnumerable GetInterfaceImplementationsFromAssembly(Assembly assembly) where T : class { - string dirName = Path.GetDirectoryName(typeof(ScriptAnalyzer).GetTypeInfo().Assembly.Location); - var dllPaths = Directory.EnumerateFiles(dirName, "*.dll", SearchOption.TopDirectoryOnly); - var objects = new List(); - foreach (var dllPath in dllPaths) - { - outputWriter.WriteVerbose(string.Format("Found Assembly: {0}", dllPath)); - var objectsFromOneFile = GetInterfaceImplementationsFromAssembly(dllPath); - objects.AddRange(objectsFromOneFile); - } - return objects; - } - - private IEnumerable GetInterfaceImplementationsFromAssembly(string ruleDllPath) where T : class - { - string fileName = Path.GetFileNameWithoutExtension(ruleDllPath); - var assemblyName = new AssemblyName(fileName); - outputWriter.WriteVerbose(string.Format("Loading Assembly:{0}", assemblyName.FullName)); - - Assembly dll = Assembly.Load(assemblyName); - - if (dll == null) - { - outputWriter.WriteVerbose(string.Format("Cannot load {0}", ruleDllPath)); - return Enumerable.Empty(); - } + outputWriter.WriteVerbose(string.Format("Loading Assembly:{0}", assembly.FullName)); var rules = new List(); - foreach (Type type in dll.ExportedTypes) + foreach (Type type in assembly.ExportedTypes) { if (type.IsInterface || type.IsAbstract @@ -927,9 +903,13 @@ private void LoadRules(Dictionary> result, CommandInvocatio this.ExternalRules = null; #if CORECLR - this.ScriptRules = GetInterfaceImplementationsFromAssembly(); - this.TokenRules = GetInterfaceImplementationsFromAssembly(); - this.DSCResourceRules = GetInterfaceImplementationsFromAssembly(); + // Hosts can place the analyzer beside hundreds of unrelated assemblies. + // Built-in rules live in one known assembly; probing every adjacent DLL + // loads host code and can fail on dependencies that analysis never needs. + var builtInRules = Assembly.Load(new AssemblyName("Microsoft.Windows.PowerShell.ScriptAnalyzer.BuiltinRules")); + this.ScriptRules = GetInterfaceImplementationsFromAssembly(builtInRules); + this.TokenRules = GetInterfaceImplementationsFromAssembly(builtInRules); + this.DSCResourceRules = GetInterfaceImplementationsFromAssembly(builtInRules); #else // An aggregate catalog that combines multiple catalogs. using (AggregateCatalog catalog = new AggregateCatalog()) diff --git a/README.md b/README.md index 0e82f34be..1fffd3590 100644 --- a/README.md +++ b/README.md @@ -191,6 +191,23 @@ Get-TestFailures The documentation in this section can be found in [Using PSScriptAnalyzer](https://learn.microsoft.com/powershell/utility-modules/psscriptanalyzer/using-scriptanalyzer). +### Built-in assembly discovery in the Immense fork + +On PowerShell Core, built-in rules are loaded from +`Microsoft.Windows.PowerShell.ScriptAnalyzer.BuiltinRules` and loggers from the +analyzer engine assembly. Other DLLs beside the engine are not searched for rules +or loggers. This avoids loading unrelated host assemblies on every analysis and +prevents their missing dependencies from breaking analysis. + +`-IncludeRule` and `-ExcludeRule` select rules after discovery; they do not filter +DLLs. Explicit PowerShell custom rules still use `-CustomRulePath`, including its +existing wildcard and recursion support. Putting a custom compiled rule or logger +DLL beside the engine no longer implicitly registers it on PowerShell Core. This +change does not add compiled custom-rule support to the Core implementation. + +See [rule discovery measurements](docs/RuleDiscoveryPerformance.md) for a +reproducible before/after benchmark and its limits. + ## Contributions are welcome There are many ways to contribute: diff --git a/Tests/Engine/RuleAssemblyDiscovery.tests.ps1 b/Tests/Engine/RuleAssemblyDiscovery.tests.ps1 new file mode 100644 index 000000000..e3b8e564d --- /dev/null +++ b/Tests/Engine/RuleAssemblyDiscovery.tests.ps1 @@ -0,0 +1,77 @@ +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. + +Describe 'PowerShell Core built-in rule discovery' -Skip:($PSVersionTable.PSEdition -ne 'Core') { + BeforeAll { + $moduleRoot = (Get-Module PSScriptAnalyzer).ModuleBase + $powerShell = (Get-Process -Id $PID).Path + $childScript = Join-Path $TestDrive 'Test-Discovery.ps1' + @' +param($ModulePath, $CustomRulePath) +$ErrorActionPreference = 'Stop' +Import-Module $ModulePath +$rules = @(Get-ScriptAnalyzerRule) +$diagnostics = @(Invoke-ScriptAnalyzer -ScriptDefinition 'gci' -IncludeRule PSAvoidUsingCmdletAliases) +$custom = @(Invoke-ScriptAnalyzer -ScriptDefinition 'gci' -Settings @{ + CustomRulePath = $CustomRulePath + IncludeDefaultRules = $true + IncludeRules = @('PSAvoidUsingCmdletAliases', 'Measure-RequiresRunAsAdministrator') +}) +$customOnly = @(Invoke-ScriptAnalyzer -ScriptDefinition 'gci' -CustomRulePath $CustomRulePath) +$formatted = Invoke-Formatter -ScriptDefinition 'gci' +[pscustomobject]@{ + Rules = @($rules.RuleName) + Diagnostics = @($diagnostics.RuleName) + Custom = @($custom.RuleName) + CustomOnly = @($customOnly.RuleName) + Formatted = $formatted + UnrelatedLoaded = @([AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { + -not $_.IsDynamic -and [IO.Path]::GetFileName($_.Location) -eq 'Unrelated.Host.dll' + }).Count +} | ConvertTo-Json -Compress +'@ | Set-Content $childScript + + # Compile outside the child: loading it in the test runner must not hide + # whether discovery loads it in the fresh process. + $managedDll = Join-Path $TestDrive 'Unrelated.Host.dll' + Add-Type -TypeDefinition 'public class UnrelatedDiscoveryFixture {}' -OutputAssembly $managedDll + $dependencyDll = Join-Path $TestDrive 'MissingDependency.dll' + Add-Type -TypeDefinition 'public class MissingDiscoveryDependency {}' -OutputAssembly $dependencyDll + $missingDependencyDll = Join-Path $TestDrive 'MissingDependency.Host.dll' + Add-Type -TypeDefinition 'public class DerivedDiscoveryFixture : MissingDiscoveryDependency {}' ` + -ReferencedAssemblies $dependencyDll -OutputAssembly $missingDependencyDll + } + + It 'ignores an unrelated DLL and preserves built-in and explicit custom rules' -TestCases @( + @{ Kind = 'invalid' } + @{ Kind = 'managed' } + @{ Kind = 'missing dependency' } + ) { + param($Kind) + $copy = Join-Path $TestDrive $Kind + Copy-Item $moduleRoot $copy -Recurse + $adjacentDll = Join-Path $copy 'PSv7/Unrelated.Host.dll' + if ($Kind -eq 'invalid') { + Set-Content $adjacentDll 'Not a managed assembly' + } elseif ($Kind -eq 'missing dependency') { + Copy-Item $missingDependencyDll $adjacentDll + } else { + Copy-Item $managedDll $adjacentDll + } + + $output = & $powerShell -NoLogo -NoProfile -File $childScript ` + -ModulePath (Join-Path $copy 'PSScriptAnalyzer.psd1') ` + -CustomRulePath "$PSScriptRoot/samplerule/samplerule.psm1" 2>&1 + $LASTEXITCODE | Should -Be 0 -Because ($output | Out-String) + $result = $output | ConvertFrom-Json + $result.Rules.Count | Should -Be 69 + $result.Rules | Should -Contain 'PSAvoidUsingCmdletAliases' + $result.Rules | Should -Contain 'PSDSCUseIdenticalParametersForDSC' + $result.Diagnostics | Should -Be @('PSAvoidUsingCmdletAliases') + $result.Custom | Should -Contain 'PSAvoidUsingCmdletAliases' + $result.Custom | Should -Contain 'samplerule\Measure-RequiresRunAsAdministrator' + $result.CustomOnly | Should -Be @('samplerule\Measure-RequiresRunAsAdministrator') + $result.Formatted | Should -Be 'gci' + $result.UnrelatedLoaded | Should -Be 0 + } +} diff --git a/docs/RuleDiscoveryPerformance.md b/docs/RuleDiscoveryPerformance.md new file mode 100644 index 000000000..8ad40947f --- /dev/null +++ b/docs/RuleDiscoveryPerformance.md @@ -0,0 +1,141 @@ +# Built-in rule discovery performance + +## Why this changed + +[ImmyBot PR 11257](https://github.com/immense/immybot/pull/11257) exposed a +PowerShell Core discovery problem: PSScriptAnalyzer enumerated every `*.dll` +beside its engine, loaded each assembly, and walked its exported types four times +per invocation (loggers, script rules, token rules, DSC rules). In a host's output +directory, unrelated DLLs made analysis expensive and missing dependencies could +abort it entirely. Rule-name filters run too late to prevent this work. + +The engine now discovers loggers in its own assembly and rules in the known +`Microsoft.Windows.PowerShell.ScriptAnalyzer.BuiltinRules` assembly. It creates +fresh rule instances each time, preserving per-invocation configuration. No cache, +environment variable, or glob setting is required. Explicit PowerShell custom +rules still use `CustomRulePath`, including its wildcard/recursion support. + +Compatibility: adjacency alone no longer registers third-party compiled rules or +loggers on PowerShell Core. This change does not add Core support for compiled +custom-rule paths. The legacy full-framework MEF implementation is unchanged. + +## Measurements + +Measured November 17, 2026, on macOS 27.2 arm64, PowerShell 7.6.1 / .NET 10.0.7. +Both builds used SDK 10.0.400, `PSV7Release`, `net6`, and identical dependencies. +Baseline: `immybot-latest` commit `43c1fa343c2dbfc8ba9ec3b1641ab141087954d2`. +The fixed build differs only in `Engine/ScriptAnalyzer.cs`. + +The normal module directory contains six managed DLLs. The crowded fixture adds +410 unrelated managed DLLs, each exporting 100 empty classes. This is a synthetic +scaling experiment, not the actual ImmyBot application directory. + +Each build/layout/operation used five fresh processes. Each process records its +first call, makes five warm-up calls, then measures 30 calls. Build order alternates +between runs. Module import and fixture generation are outside the timings. +Numbers below are medians across the five processes; warm values are medians of +each process's 30 calls. Verbose inspection counts are collected separately. + +| Operation / layout | Before warm (ms) | After warm (ms) | Before first call (ms) | After first call (ms) | +| --- | ---: | ---: | ---: | ---: | +| Discovery, no extra DLLs | 0.479 | 0.276 | 45.848 | 44.336 | +| Analysis, no extra DLLs | 3.080 | 1.112 | 56.245 | 63.492 | +| Discovery, 410 extra DLLs | 15.685 | 0.252 | 118.493 | 25.831 | +| Analysis, 410 extra DLLs | 15.770 | 0.363 | 144.083 | 34.432 | + +Discovery is `Get-ScriptAnalyzerRule`: initialization and rule listing, without +script analysis. Analysis is a complete `Invoke-ScriptAnalyzer -ScriptDefinition +'gci' -IncludeRule PSAvoidUsingCmdletAliases` call, including initialization. This +small script and single rule isolate the discovery penalty; they do not represent +the cost of running every rule on a large script. + +With 410 extra DLLs, warm discovery was 62.2x faster and the full alias-analysis +call was 43.4x faster. Individual process warm medians ranged from 12.341–15.983 ms +before versus 0.251–0.288 ms after for discovery, and 14.702–29.902 ms before versus +0.339–0.482 ms after for analysis. + +| Crowded-layout metric | Before | After | +| --- | ---: | ---: | +| Assembly type inspections per call | 1,664 | 4 | +| Unrelated fixture assemblies loaded | 410 | 0 | +| Discovery allocated bytes per warm call | 3,937,252 | 190,920 | +| Analysis allocated bytes per warm call | 3,929,312 | 182,481 | +| Discovery first-call working-set increase | 28.59 MiB | 2.52 MiB | +| Analysis first-call working-set increase | 28.11 MiB | 2.34 MiB | + +All 40 processes returned identical results within each operation: the same 69 +built-in rule names, or the same single alias diagnostic. The deterministic +assembly counts corroborate the timing result. Working set and timings are noisy +on a shared machine; the clean-layout cold analysis did not improve. These numbers +are not an editor keystroke latency claim, do not measure PSES's debounce, and do +not establish how much of ImmyBot's historical slowness this accounts for. + +## Reproduce + +Build separate durable checkouts of the baseline commit and the PR head with the +same SDK and dependencies. From a directory using the selected SDK (the checkout's +`global.json` pins 6.0.403), run for each checkout: + +```powershell +dotnet build "$source/Rules/Rules.csproj" -c PSV7Release -f net6 -m:1 ` + -p:BuildInParallel=false -p:ImportDirectoryBuildProps=false ` + -p:ImportDirectoryBuildTargets=false -p:ManagePackageVersionsCentrally=false +if ($LASTEXITCODE) { throw 'Build failed' } +``` + +The last three properties isolate these independent checkouts from a containing +repository's MSBuild configuration. They were identical in both measured builds. +On shared ImmyBot development machines, also apply the machine's load check and +build lock. + +Prepare a module directory for each build, with `PSScriptAnalyzer.psd1`, +`PSScriptAnalyzer.psm1`, `ScriptAnalyzer.types.ps1xml`, and +`ScriptAnalyzer.format.ps1xml` from `Engine`; `Engine/Settings` as `Settings`; and +`PSCompatibilityCollector/profiles` as `compatibility_profiles`. Put these six +DLLs from `Rules/bin/PSV7Release/net6` in its `PSv7` subdirectory: + +- `Microsoft.Windows.PowerShell.ScriptAnalyzer.dll` +- `Microsoft.Windows.PowerShell.ScriptAnalyzer.BuiltinRules.dll` +- `Microsoft.PowerShell.CrossCompatibility.dll` +- `Pluralize.NET.dll` +- `Microsoft.VisualStudio.Threading.dll` +- `Microsoft.VisualStudio.Validation.dll` + +The threading dependencies are necessary for this fork even though the old +`build.ps1` copy list omits them. Use the same non-analyzer assets for both builds. +The recorded run used these assets from ImmyBot's installed private 1.21.0 package +and replaced the six DLLs with the respective source build outputs. + +Run the harness from the PR checkout in PowerShell Core: + +```powershell +$results = ./tools/Measure-RuleDiscovery.ps1 ` + -BeforeModulePath $beforeModule -AfterModulePath $afterModule ` + -Runs 5 -Iterations 30 -AdjacentAssemblyCount 410 -TypesPerAssembly 100 +$results | ConvertTo-Json -Depth 5 | Set-Content $resultsPath +``` + +Use temporary directories for modules/results. The harness creates and removes +its own fixture directory. It emits raw samples, rule names, assembly inspection +and load counts, allocated bytes, working-set deltas, and runtime version. Each +child process fails if the expected built-in rule count or alias diagnostic changes. + +## Regression validation + +`Tests/Engine/RuleAssemblyDiscovery.tests.ps1` copies the real module into an +isolated directory and invokes a fresh PowerShell process for each of three cases: +an invalid DLL, an unrelated managed DLL, and a managed DLL with a missing base-type +dependency. All three fail on the baseline and pass on the fixed build. Each case +also checks built-in rule listing/diagnostics, formatting, a custom PowerShell rule +selected through settings with built-ins, and custom-only analysis. + +The final focused discovery/custom-rule/settings/formatter suite passed 138 tests +with 2 skips, including all three new regression cases. The broader engine/rule +suite passed 1,276 tests with 148 skips and +10 failures, all reproduced on the unchanged baseline in the same environment: +2 attempts to write outside the sandbox, 3 help-description checks for the newer +`ProgressAction` common parameter, and 5 existing compatibility-profile assertions. +Both source builds succeeded with the same four existing warnings. + +This PR does not publish a new package or change ImmyBot's package reference. Those +steps and verification in an actual editor process remain integration work. diff --git a/tools/Measure-RuleDiscovery.ps1 b/tools/Measure-RuleDiscovery.ps1 new file mode 100644 index 000000000..82825c450 --- /dev/null +++ b/tools/Measure-RuleDiscovery.ps1 @@ -0,0 +1,145 @@ +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. + +<# +.SYNOPSIS +Compares two built module directories in isolated PowerShell processes. +.DESCRIPTION +Generates unrelated managed DLLs in a temporary directory, copies each module, +and measures discovery separately from a complete alias-analysis invocation. +Outputs one object per process. Preparation and import are outside the timings. +The crowded layout is synthetic, not an ImmyBot/editor end-to-end benchmark. +#> +[CmdletBinding(DefaultParameterSetName = 'Compare')] +param( + [Parameter(Mandatory, ParameterSetName = 'Compare')] + [string] $BeforeModulePath, + [Parameter(Mandatory, ParameterSetName = 'Compare')] + [string] $AfterModulePath, + [Parameter(ParameterSetName = 'Compare')] + [ValidateRange(1, 100)] + [int] $Runs = 5, + [Parameter(ParameterSetName = 'Compare')] + [ValidateRange(1, 1000)] + [int] $AdjacentAssemblyCount = 410, + [Parameter(ParameterSetName = 'Compare')] + [ValidateRange(1, 1000)] + [int] $TypesPerAssembly = 100, + [ValidateRange(1, 10000)] + [int] $Iterations = 30, + [Parameter(Mandatory, ParameterSetName = 'Worker')] + [string] $ModulePath, + [Parameter(Mandatory, ParameterSetName = 'Worker')] + [ValidateSet('Discovery', 'Analysis')] + [string] $Mode +) + +$ErrorActionPreference = 'Stop' +Set-StrictMode -Version Latest + +if ($PSCmdlet.ParameterSetName -eq 'Worker') { + Import-Module (Join-Path $ModulePath 'PSScriptAnalyzer.psd1') + $operation = if ($Mode -eq 'Discovery') { + { Get-ScriptAnalyzerRule } + } else { + { Invoke-ScriptAnalyzer -ScriptDefinition 'gci' -IncludeRule PSAvoidUsingCmdletAliases } + } + [GC]::Collect() + [GC]::WaitForPendingFinalizers() + $memoryBefore = [Environment]::WorkingSet + $assembliesBefore = [AppDomain]::CurrentDomain.GetAssemblies().Count + $watch = [Diagnostics.Stopwatch]::StartNew() + $first = @(& $operation) + $watch.Stop() + $coldMs = $watch.Elapsed.TotalMilliseconds + $memoryDelta = [Environment]::WorkingSet - $memoryBefore + $assembliesDelta = [AppDomain]::CurrentDomain.GetAssemblies().Count - $assembliesBefore + $ruleNames = @($first.RuleName | Sort-Object) + if ($Mode -eq 'Discovery' -and $ruleNames.Count -ne 69) { + throw "Expected 69 built-in rules, got $($ruleNames.Count)" + } + if ($Mode -eq 'Analysis' -and ($ruleNames.Count -ne 1 -or $ruleNames[0] -ne 'PSAvoidUsingCmdletAliases')) { + throw 'Alias diagnostic changed' + } + # Warm JIT and rule dependencies before steady-state samples. + 1..5 | ForEach-Object { $null = & $operation } + $samples = [Collections.Generic.List[double]]::new() + $allocatedBefore = [GC]::GetTotalAllocatedBytes($true) + for ($i = 0; $i -lt $Iterations; $i++) { + $watch.Restart() + $null = & $operation + $watch.Stop() + $samples.Add($watch.Elapsed.TotalMilliseconds) + } + $allocated = [GC]::GetTotalAllocatedBytes($true) - $allocatedBefore + $ordered = @($samples | Sort-Object) + # Verbose capture is deliberately outside timed/allocation samples. + $trace = if ($Mode -eq 'Discovery') { + @(Get-ScriptAnalyzerRule -Verbose 4>&1) + } else { + @(Invoke-ScriptAnalyzer -ScriptDefinition 'gci' -IncludeRule PSAvoidUsingCmdletAliases -Verbose 4>&1) + } + [pscustomobject]@{ + Mode = $Mode + PowerShell = $PSVersionTable.PSVersion.ToString() + Runtime = [Runtime.InteropServices.RuntimeInformation]::FrameworkDescription + ColdMs = $coldMs + WarmMedianMs = $ordered[[int][Math]::Floor($Iterations / 2)] + WarmP95Ms = $ordered[[int][Math]::Ceiling($Iterations * 0.95) - 1] + AllocatedBytesPerCall = $allocated / $Iterations + ColdWorkingSetDeltaBytes = $memoryDelta + ColdLoadedAssemblies = $assembliesDelta + AdjacentLoadedAssemblies = @([AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { + -not $_.IsDynamic -and [IO.Path]::GetFileName($_.Location) -like 'DiscoveryFixture*.dll' + }).Count + AssemblyInspectionsPerCall = @($trace | Where-Object { + $_ -is [System.Management.Automation.VerboseRecord] -and $_.Message -like 'Loading Assembly:*' + }).Count + RuleNames = $ruleNames + WarmSamplesMs = @($samples) + } | ConvertTo-Json -Depth 4 -Compress + return +} + +$before = (Resolve-Path $BeforeModulePath).Path +$after = (Resolve-Path $AfterModulePath).Path +$scratch = Join-Path ([IO.Path]::GetTempPath()) ('PssaDiscovery-' + [Guid]::NewGuid()) +$powerShell = (Get-Process -Id $PID).Path +try { + $fixtures = New-Item (Join-Path $scratch 'fixtures') -ItemType Directory -Force + for ($i = 0; $i -lt $AdjacentAssemblyCount; $i++) { + $classes = (0..($TypesPerAssembly - 1) | ForEach-Object { "public class Type$_ {}" }) -join "`n" + Add-Type -TypeDefinition "namespace DiscoveryFixture$i { $classes }" ` + -OutputAssembly (Join-Path $fixtures.FullName "DiscoveryFixture$i.dll") + } + foreach ($count in @(0, $AdjacentAssemblyCount)) { + foreach ($variant in @('Before', 'After')) { + $source = if ($variant -eq 'Before') { $before } else { $after } + $destination = Join-Path $scratch "$variant-$count" + Copy-Item $source $destination -Recurse + if ($count -gt 0) { + Copy-Item "$($fixtures.FullName)/*.dll" (Join-Path $destination 'PSv7') + } + } + for ($run = 1; $run -le $Runs; $run++) { + # Alternate build order to reduce systematic warm-cache/time bias. + $variants = if ($run % 2) { @('Before', 'After') } else { @('After', 'Before') } + foreach ($modeName in @('Discovery', 'Analysis')) { + foreach ($variant in $variants) { + $output = & $powerShell -NoLogo -NoProfile -File $PSCommandPath ` + -ModulePath (Join-Path $scratch "$variant-$count") ` + -Mode $modeName -Iterations $Iterations + if ($LASTEXITCODE -ne 0) { throw "Benchmark child failed: $variant/$count/$modeName" } + $result = $output | ConvertFrom-Json + $result | Add-Member -NotePropertyMembers @{ + Variant = $variant; Run = $run; AdjacentAssemblies = $count + TypesPerAssembly = $TypesPerAssembly; Iterations = $Iterations + } + $result + } + } + } + } +} finally { + if (Test-Path $scratch) { Remove-Item $scratch -Recurse -Force } +}