Skip to content

Avoid full link-target resolution for ordinary Windows directories - #15282

Merged
AlesProkop merged 5 commits into
mainfrom
alesprokop-live-link-guard-perf
Oct 30, 2026
Merged

AlesProkop merged 5 commits into
mainfrom
alesprokop-live-link-guard-perf

Conversation

@AlesProkop

@AlesProkop AlesProkop commented Oct 14, 2026 •

Copy link
Copy Markdown
Member

Related issue(s): N/A

Context

MSBuild resolves directory link targets while walking globs, even for ordinary directories.

Changes Made

On Windows, check live file attributes first so normal directories can avoid full target resolution. Reparse points and inconclusive checks still use the existing resolver. Nothing is cached.

Compatibility

Other paths and platforms keep the old route. No changes to defaults, diagnostics or public APIs are intended. Reparse points and failed probes can pay an extra file-system query.

Testing

Windows Orchard MT-warm, five samples per side. Median time changes; negative is faster:

Metric Lab: guard vs parent Offline local: guard + globber vs globber alone (#15276)
Items (pass 3) -31.5% -22.4%
Total evaluation -2.7% -8.5%
Build wall time +0.08% (unchanged) -6.3%
Properties/imports (pass 1) +11.3% +3.6%

Lab property/import means are nearly identical (81.7s vs 81.8s), with substantial variation; no overall build speedup is established. Both lab runs use measured SDK 11.0.100-rtm.26480.113, wrapper SDK 10.0.402 and runtime 10.0.13.

Offline results are one ordered, unrepeated local pair, not versus stock main or included in the hosted comparisons. Mean build time improved 5.4%. This PR contains only the guard.

PerfStar comparisons: candidate 15680990 versus fresh parent 15682616, for the same selected Windows Orchard runs:

Includes path, link and evaluation-observer regression coverage. This unchanged PR head passed the original targeted Windows tests: 677 passed, 0 failed and 46 expected platform skips across .NET 11 and .NET Framework. Separately, the combined tree's Release focused tests passed: 939 passed, 0 failed and 48 expected platform/TODO skips; all seven modern Windows link tests ran and passed. Linux execution, actual access-denied behavior and the full test suite still need broader validation.

Scoped test commands and results for this PR head
# Passed: 295 tests, 23 platform skips
artifacts\bin\Microsoft.Build.Framework.UnitTests\Release\net11.0\Microsoft.Build.Framework.UnitTests.exe --filter-class '*FileMatcherLiveLinkProbe_Tests' '*FileMatcherOptimized_Tests' '*MSBuildPathMatcher_Tests' '*FileMatcherTest' --report-trx --report-trx-filename framework-net11.0.trx --results-directory D:\Evaluations\experiments\publication18\validation --no-progress
# Passed: 288 tests, 23 platform skips
artifacts\bin\Microsoft.Build.Framework.UnitTests\Release\net472\Microsoft.Build.Framework.UnitTests.exe --filter-class '*FileMatcherLiveLinkProbe_Tests' '*FileMatcherOptimized_Tests' '*MSBuildPathMatcher_Tests' '*FileMatcherTest' --report-trx --report-trx-filename framework-net472.trx --results-directory D:\Evaluations\experiments\publication18\validation --no-progress
# Passed: 47 tests
artifacts\bin\Microsoft.Build.Engine.UnitTests\Release\net11.0\Microsoft.Build.Engine.UnitTests.exe --filter-method '*LiveLinkProbeEvaluation_Tests*' '*FileMatcherCulture_Tests*' '*ItemGlobs_Tests*' '*ExcludeSeesIntermediaryState*' '*DifferentExcludesOnSameWildcard*' '*RemoveShouldPreserveIntermediaryReferences*' '*LazyWildcardExpansionDoesNotEvaluateWildCardsIfNotReferenced*' --report-trx --report-trx-filename evaluation-net11.0.trx --results-directory D:\Evaluations\experiments\publication18\validation --no-progress
# Passed: 47 tests
artifacts\bin\Microsoft.Build.Engine.UnitTests\Release\net472\Microsoft.Build.Engine.UnitTests.exe --filter-method '*LiveLinkProbeEvaluation_Tests*' '*FileMatcherCulture_Tests*' '*ItemGlobs_Tests*' '*ExcludeSeesIntermediaryState*' '*DifferentExcludesOnSameWildcard*' '*RemoveShouldPreserveIntermediaryReferences*' '*LazyWildcardExpansionDoesNotEvaluateWildCardsIfNotReferenced*' --report-trx --report-trx-filename evaluation-net472.trx --results-directory D:\Evaluations\experiments\publication18\validation --no-progress

Dependencies and Follow-up

No companion changes. This stays a draft while the property/import increase is understood and the remaining platform/access-control coverage is checked.

Probe current file attributes at each existing optimized recursion guard. Preserve full target resolution for reparse points, failed probes and ineligible paths. Add differential path/link and evaluator observer coverage.

Co-authored-by: Copilot App <[email protected]>
@AlesProkop
AlesProkop marked this pull request as ready for review October 15, 2026 11:29
Copilot AI balanced review requested due to automatic review settings October 15, 2026 11:29

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.

🔵 Needs a closer look

Access-control and broader platform validation remain pending, along with investigation of the property/import timing increase.

0 open findings

What changed in this PR

Optimizes Windows glob traversal by avoiding full link-target resolution for ordinary directories, while preserving the existing fallback.

Changes:

  • Adds an uncached live-attribute check for eligible Windows paths.
  • Adds regression tests for paths, links, glob results, and evaluation behavior.
File Description
src/​Framework/​Utilities/​FileMatcher.cs Adds the Windows attribute-check fast path.
src/​Framework.UnitTests/​Globbing/​FileMatcherLiveLinkProbe_Tests.cs Tests path compatibility, link behavior, and glob results.
src/​Build.UnitTests/​Evaluation/​LiveLinkProbeEvaluation_Tests.cs Tests item observers, metadata, and removal across evaluation models.

🧠 Review effort: Balanced


💡 Add a code-review agent skill for context-aware, tailored reviews. Learn more in the docs.

Comment thread src/Framework/Utilities/FileMatcher.cs Resolved
Comment thread src/Framework/Utilities/FileMatcher.cs Resolved
Comment thread src/Framework/Utilities/FileMatcher.cs Resolved
@ViktorHofer

Copy link
Copy Markdown
Member

MSBuild Code Review — 24-dimension pass

Verdict: 🟡 COMMENT — no blockers, but the test suite does not currently test the change (demonstrated below), and there is a strictly better, cross-platform, zero-syscall alternative already available at the main call site.

15/24 dimensions clean. Findings in: Performance, Test Coverage, Design, Simplification, Naming, Documentation, Scope, Correctness, ChangeWave.

Verified locally: build.cmd -projects src\Framework.UnitTests → 0 warnings, 0 errors on net11.0 and net472; the 7 new Framework tests pass.

A separate security-focused pass over this diff found no security vulnerabilities — the short circuit fires only when the entry is provably not a reparse point, so symlink-cycle protection and traversal guarantees are unchanged.


🔴 Major

M1 — The new tests cannot fail if the optimization is removed

I deleted the production hunk (FileMatcher.cs:3436-3454), rebuilt, and reran:

Test run summary: Passed!  total: 7  failed: 0  succeeded: 7

All 7 tests pass without the change. The reason is structural — every assertion in FileMatcherLiveLinkProbe_Tests.cs is:

FileMatcher.ShouldSkipRecursiveDirectory(path).ShouldBe(OriginalShouldSkip(path), path);

and OriginalShouldSkip (FileMatcherLiveLinkProbe_Tests.cs:182-196) is a verbatim copy of the pre-change implementation. These are oracle/differential tests — genuinely valuable as a regression net, but they prove nothing about the feature. The only thing that fails without the production change is compilation (the private → internal widening).

Suggested:

  1. Add a test that proves the fast path is actually taken. Cheapest seam: internal static Func<string, FileAttributes> s_getAttributes = File.GetAttributes; plus a test that swaps in a counting delegate and asserts ResolveLinkTarget is not reached.
  2. Add cases that would break if the attribute equivalence were wrong — none exist today:
    • a junction (mklink /J) — a reparse point that is not a symlink;
    • a real directory reached through a parent symlink (C:\linkToRoot\realChild) — the case where "does GetAttributes follow links?" actually matters;
    • a path on a mapped network drive (Z:\), which passes the directory[1] == ':' guard but is remote.

M2 — The enumerator already has the attributes; this re-stats and allocates

src/Framework/Utilities/FileMatcher.cs:3568-3575

string directory = entry.ToFullPath();          // string allocation per directory
if (ShouldSkipRecursiveDirectory(directory))    // → File.GetAttributes syscall

DirectFileSystemEntry is System.IO.Enumeration.FileSystemEntry / Microsoft.IO.Enumeration.FileSystemEntry (aliased at FileMatcher.cs:17-20), which exposes Attributes, populated directly from the enumeration record — zero extra syscalls on Windows, and already-cached lstat/d_type data on Unix.

if ((entry.Attributes & FileAttributes.ReparsePoint) != 0
    && ShouldSkipRecursiveDirectory(directory))
{
    return false;
}

This is strictly better than the current approach: it eliminates the syscall entirely for the overwhelmingly common non-reparse case, works on Linux and macOS too (the PR as written gives those platforms nothing), and makes the Windows-drive-path-shape guard unnecessary at the hot call site. This is the recursion predicate for the optimized direct enumerator — i.e. the dominant caller.

M3 — The probe runs before the cheap pattern checks

FileMatcher.cs:3570-3596. In ShouldRecurseIntoEntry, every branch returns false:

ShouldSkipRecursiveDirectory → false                 ← filesystem probe, runs first
TryGetRelativeDirectory / MatchesDirectory → false   ← pure string work
exclude matchers → false                             ← pure string work

Moving the probe after the include/exclude matching appears behavior-identical (same return value, no side effects in the matchers) and skips the probe entirely for directories that are about to be pruned — a large fraction of them with **/obj/**-style excludes. Worth verifying and reordering; it likely beats the attribute fast path on its own.


🟡 Moderate

Mo1 — The legacy path duplicates the logic and is left behind

FileMatcher.cs:957-967 inlines the identical probe in GetFilesRecursive instead of calling ShouldSkipRecursiveDirectory. Two copies of the same semantic will drift, and users who opt out of Wave 18.11 get none of the win. Suggest replacing with a call to the shared helper.

Mo2 — ChangeWave decision is unstated

Analysis suggests no new wave is required: the guard only short-circuits when ReparsePoint is definitively absent, and Win32 GetFileAttributes reports FILE_ATTRIBUTE_REPARSE_POINT for the link itself without following it — so "no flag" implies ResolveLinkTarget would have returned null. Non-symlink reparse points (OneDrive/cloud placeholders, dedup, AppExecLink, junctions) all keep the flag and fall through to the existing resolver. Failure paths fall through too.

However, the three affected call sites (3108, 3155, 3572) live in the optimized implementation gated by Wave 18.11, which is already mid-rotation and will expire while this code lives on; FileMatcherImplementation.Optimized can also be forced. Please state the reasoning in the PR description, and if the team is uneasy about SMB/DFS mapped drives, consider gating on the current wave (18.13) rather than inheriting 18.11's opt-out.

Mo3 — Dead weight on the hot path

FileMatcher.cs:3442: directory.AsSpan().IndexOfAny('*', '?'). GetFileAttributesEx never expands wildcards — C:\dir\* fails with ERROR_INVALID_NAME → IOException → the inner catch → fall-through, which is exactly the outcome the guard hand-rolls. More to the point, callers only pass enumerated directory names and state.BaseDirectory (the fixed, wildcard-free part of the spec, FileMatcher.cs:2329), so wildcards can't reach here. Suggest removing it, or documenting why it's needed.

Likewise Path.IsPathFullyQualified(directory) && directory[1] == Path.VolumeSeparatorChar (3440-3441) validates the prefix twice. A single check is cheaper and clearer:

if (directory.Length > 2 && directory[1] == Path.VolumeSeparatorChar && FileUtilities.IsSlash(directory[2]))

Mo4 — Comment documents the what, not the why

FileMatcher.cs:3437-3438 doesn't explain why UNC (\\server\share) and device (\\?\) paths are excluded — a future maintainer can't tell whether that was a correctness constraint or conservatism, and UNC-rooted enterprise builds silently get no benefit. Most importantly, the comment omits the invariant the whole change rests on:

GetFileAttributes returns the attributes of the reparse point itself and does not follow it, so the absence of FILE_ATTRIBUTE_REPARSE_POINT proves ResolveLinkTarget(..., returnFinalTarget: true) would return null.

Mo5 — Failure paths now throw twice

FileMatcher.cs:3452 → 3456. When a directory disappears mid-enumeration (routine during real builds), File.GetAttributes throws, is swallowed, and ResolveLinkTarget immediately throws the same exception again — two first-chance exceptions where there was one.

Careful with the fix: ExceptionHandling.IsIoRelatedException also matches NotSupportedException and SecurityException, which the outer catches (3460-3462) do not handle — today those propagate to IsIoRelatedExceptionOrAggregate at 3139 and surface as a glob failure. So narrow the inner handler rather than returning false from the broad filter:

catch (IOException) { return false; }
catch (UnauthorizedAccessException) { return false; }

Both are equivalent to the current outer-catch outcome and avoid the second throw.

Mo6 — Second direct bypass of the injected IFileSystem

FileMatcher carries _fileSystem (MSBuildFileSystemBase, used e.g. at 2264 _fileSystem.DirectoryExists), but ShouldSkipRecursiveDirectory is static and calls File.*/Directory.* directly. Pre-existing — the comment at FileMatcher.cs:966 ("This fails in tests with the MockFileSystem") acknowledges it — but this PR adds a second such call, widening the layering gap that VS's in-memory file system has to tolerate. Worth an issue if not fixed here.


🔵 Nits

# File:Line Finding
N1 FileMatcher.cs:3439 Inside #if NET, prefer OperatingSystem.IsWindows() — a JIT intrinsic that constant-folds and removes the entire block on non-Windows. NativeMethods.IsWindows is a bool? static property with a null check on every call, on the hot path.
N2 FileMatcherLiveLinkProbe_Tests.cs:22-26 Reflection binding of private FileMatcher.IsSubdirectoryOf by string name; a rename breaks tests with an opaque NRE from the !. You already widened ShouldSkipRecursiveDirectory to internal — consider doing the same for IsSubdirectoryOf (FileMatcher.cs:4030) and deleting the reflection.
N3 FileMatcher.cs:3431 private → internal purely for tests. Fine given the IVT in src/Framework/Properties/AssemblyInfo.cs:39, but add // internal for unit testing so it isn't widened further later.
N4 both test files Test names don't follow MethodUnderTest_Scenario_ExpectedResult: BothModelsPreserveGlobObserversMetadataAndRemoval, CallbackAndDirectGlobsPreserveFilesAndFailures. Prefer e.g. ShouldSkipRecursiveDirectory_NonReparsePointDirectory_ReturnsFalse. Also LiveLinkProbeEvaluation_Tests uses a primary-ctor parameter output instead of the _output field required by .github/instructions/tests.instructions.md § Capturing Output.
N5 FileMatcherLiveLinkProbe_Tests.cs:205-215 LinkCleanup.Revert catches only DirectoryNotFoundException; an IOException/UnauthorizedAccessException during cleanup fails the test from Dispose. Also TransientTestFolder already deletes the tree, and Directory.Delete on a directory symlink removes the link rather than the target — so LinkCleanup may be redundant. If it is needed, worth saying why.
N6 Microsoft.Build.Framework.UnitTests.csproj:4 The assembly also targets net472, where FEATURE_SYMLINK_TARGET is undefined (src/Directory.BeforeCommon.targets:81-88 scopes it to NetCoreBuild), so ShouldSkipRecursiveDirectory is a constant false and every differential assertion is trivially satisfied on that leg. Not wrong — just be aware the coverage is .NET-Core-only.
N7 FileMatcher.cs:3441 directory[1] is safe only because Path.IsPathFullyQualified guarantees Length >= 2. True today, undocumented, and becomes an IndexOutOfRangeException if the clause order is ever edited. The Length > 2 clause suggested in Mo3 both documents and hardens it for free.
N8 FileMatcher.cs:3431 The method sits at 4-space indentation while its siblings use 8 (pre-existing; the PR partially fixes the body at 3456). Optional cleanup while you're here.

Scope

src/Build.UnitTests/Evaluation/LiveLinkProbeEvaluation_Tests.cs (+78) contains no symlink, no reparse point, and no FileMatcher reference. It is a Project-vs-ProjectInstance parity test for item metadata, Update, and Remove with globs, and it passes identically before and after this change. The filename and class name (LiveLinkProbe…) are actively misleading. Suggest either dropping it from this PR, or renaming it (e.g. GlobItemOperations_ProjectAndInstanceParity_Tests) and landing it separately as the item-evaluation test it actually is.


Explicitly confirmed clean

  • Cross-platform — non-Windows behavior is byte-for-byte unchanged: NativeMethods.IsWindows short-circuits the whole block, and the block is additionally compiled out for netstandard2.0 by #if NET (needed, since NetCoreBuild — and therefore FEATURE_SYMLINK_TARGET — covers .NETStandard too). No hardcoded separators; root.Replace('\\','/') is covered in the tests.
  • Concurrency / caching — ShouldSkipRecursiveDirectory is a pure static with no shared mutable state, safe under the Parallel.ForEach at FileMatcher.cs:1143 and the optimized enumerator's parallel subdirectory walk. It queries the live filesystem on every call and touches neither _cachedGlobExpansions nor the ConcurrentDictionary cache, so the Prevent FileMatcher test cache state leak #15177 class of cross-test cache leakage does not apply; RepeatedObservationsSeeDirectoryChangedToAndFromLink locks that in. src/Shared/UnitTests/xunit.runner.json sets parallelizeTestCollections: false, so the SetCurrentDirectory mutations in the new tests are safe.
  • Security — strictly conservative. The short circuit fires only when the entry is provably not a reparse point, so symlink-cycle protection and traversal guarantees are unchanged. No new trust boundary.
  • Backwards compatibility, error messages, logging/binlog, string comparison, public API, target authoring, SDK boundary, file I/O helpers, dependencies, build infrastructure — no findings.

Suggested order of work

  1. Replace the probe at ShouldRecurseIntoEntry with entry.Attributes (M2) and reorder it after the match checks (M3) — this likely subsumes the Windows-only fast path entirely.
  2. Make the tests capable of failing (M1), and add junction / parent-symlink / mapped-drive cases.
  3. Drop or rename the unrelated Build.UnitTests file (Scope).
  4. Fold in Mo1/Mo3/Mo4/Mo5 and the nits.
  5. Record the ChangeWave rationale in the PR description (Mo2).

@AlesProkop

AlesProkop commented Oct 30, 2026 •

Copy link
Copy Markdown
Member Author

Addressed M1 with activation/fallback tests (the activation test fails without the optimization), plus parent-symlink coverage. Added the invariant, conservative path-scope and ChangeWave rationale for Mo2/Mo4, and fixed _output usage.

The rest of the issues are not proven to actually help the PR, so I deferred them not to bloat this PR. They may be addressed in a follow-up.

@AlesProkop
AlesProkop enabled auto-merge (squash) October 30, 2026 15:57
@ViktorHofer

Copy link
Copy Markdown
Member

@rainersigwald maybe you can also take another look

@AlesProkop
AlesProkop merged commit eb53291 into main Oct 30, 2026
13 checks passed
@AlesProkop
AlesProkop deleted the alesprokop-live-link-guard-perf branch October 30, 2026 17:05
@AlesProkop

Copy link
Copy Markdown
Member Author

Microbenchmark comparison

Compared pinned main (c749ea658a08) with the same snapshot with only this PR reverted. Existing BenchmarkDotNet benchmarks, Windows x64 / .NET 11 RC2, 28 cases and three independent launches per side.

Times are mean ± SD across launches; negative change means faster.

Benchmark Without fix With fix Raw time change
Recursive glob, 512 files 4.551 ± 0.179 ms 3.375 ± 0.488 ms −25.8%
Default-exclude glob, 512 files 2.744 ± 0.024 ms 2.042 ± 0.282 ms −25.6%
Isolated evaluation, 128 dirs / 8 nonmatching files per dir 11.162 ± 0.777 ms 3.849 ± 0.436 ms −65.5%
Shared cached evaluation, 32 dirs / 8 nonmatching files per dir 0.352 ± 0.017 ms 0.393 ± 0.092 ms +11.7%

Direct globbing was faster in all three pairs, but the exact percentage is uncertain: unaffected legacy controls also shifted −25.3% to +12.5%, indicating substantial machine/run drift. Shared cached evaluation had no consistent direction across the matrix. These are warmed-filesystem microbenchmark observations, not established full-build gains.

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.

5 participants