Repository navigation
Avoid full link-target resolution for ordinary Windows directories - #15282
Conversation
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]>
There was a problem hiding this comment.
🔵 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.
Co-authored-by: Copilot App <[email protected]>
Co-authored-by: Copilot App <[email protected]>
Co-authored-by: Copilot App <[email protected]>
MSBuild Code Review — 24-dimension passVerdict: 🟡 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: 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. 🔴 MajorM1 — The new tests cannot fail if the optimization is removedI deleted the production hunk ( All 7 tests pass without the change. The reason is structural — every assertion in FileMatcher.ShouldSkipRecursiveDirectory(path).ShouldBe(OriginalShouldSkip(path), path);and Suggested:
M2 — The enumerator already has the attributes; this re-stats and allocates
string directory = entry.ToFullPath(); // string allocation per directory
if (ShouldSkipRecursiveDirectory(directory)) // → File.GetAttributes syscall
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
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 🟡 ModerateMo1 — The legacy path duplicates the logic and is left behind
Mo2 — ChangeWave decision is unstatedAnalysis suggests no new wave is required: the guard only short-circuits when 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; Mo3 — Dead weight on the hot path
Likewise if (directory.Length > 2 && directory[1] == Path.VolumeSeparatorChar && FileUtilities.IsSlash(directory[2]))Mo4 — Comment documents the what, not the why
Mo5 — Failure paths now throw twice
Careful with the fix: 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
|
| # | 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.IsWindowsshort-circuits the whole block, and the block is additionally compiled out fornetstandard2.0by#if NET(needed, sinceNetCoreBuild— and thereforeFEATURE_SYMLINK_TARGET— covers.NETStandardtoo). No hardcoded separators;root.Replace('\\','/')is covered in the tests. - Concurrency / caching —
ShouldSkipRecursiveDirectoryis a pure static with no shared mutable state, safe under theParallel.ForEachatFileMatcher.cs:1143and the optimized enumerator's parallel subdirectory walk. It queries the live filesystem on every call and touches neither_cachedGlobExpansionsnor theConcurrentDictionarycache, so the Prevent FileMatcher test cache state leak #15177 class of cross-test cache leakage does not apply;RepeatedObservationsSeeDirectoryChangedToAndFromLinklocks that in.src/Shared/UnitTests/xunit.runner.jsonsetsparallelizeTestCollections: false, so theSetCurrentDirectorymutations 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
- Replace the probe at
ShouldRecurseIntoEntrywithentry.Attributes(M2) and reorder it after the match checks (M3) — this likely subsumes the Windows-only fast path entirely. - Make the tests capable of failing (M1), and add junction / parent-symlink / mapped-drive cases.
- Drop or rename the unrelated
Build.UnitTestsfile (Scope). - Fold in Mo1/Mo3/Mo4/Mo5 and the nits.
- Record the ChangeWave rationale in the PR description (Mo2).
Co-authored-by: Copilot App <[email protected]>
|
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 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. |
|
@rainersigwald maybe you can also take another look |
Microbenchmark comparisonCompared pinned Times are mean ± SD across launches; negative change means faster.
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. |
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:
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
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.