Skip to content

Migrate ResolveTargetingPackAssets to IMultiThreadableTask - #53944

Merged
AlesProkop merged 6 commits into
dotnet:mainfrom
SimaTian:migrate-resolve-targeting-pack-assets
Jun 2, 2026
Merged

AlesProkop merged 6 commits into
dotnet:mainfrom
SimaTian:migrate-resolve-targeting-pack-assets

Conversation

@SimaTian

@SimaTian SimaTian commented Apr 17, 2026 •

Copy link
Copy Markdown
Contributor

Fixes dotnet/msbuild#13776

Migrate ResolveTargetingPackAssets to IMultiThreadableTask

Migrates ResolveTargetingPackAssets to support multi-threaded MSBuild execution.

Why

From OrchardCore build profiling (see gist):

Metric Value
Invocations 191
Cold-build time 222 ms
Incremental-build time 59 ms

Supersedes the earlier exploratory branch at SimaTian#49.

What changed

  • Task carries [MSBuildMultiThreadableTask] and implements IMultiThreadableTask with TaskEnvironment property.
  • Path resolution and file I/O routed through TaskEnvironment.GetAbsolutePath + AbsolutePath.Value.
  • Output properties preserve relativity via AbsolutePath.OriginalValue.
  • Also tightens RuntimeFramework.CacheKey to hash all item metadata (sorted), not just Name/FrameworkName/Version. The old key was incomplete vs the cached output (rf.Item); the multithreaded cache lifetime makes that latent collision more reachable

Tests

  • New GivenAResolveTargetingPackAssetsMultiThreading.cs behavioural tests: decoy-CWD resolution, multi-process parity, output relativity, concurrent execution.
  • Existing GivenAResolveTargetingPackAssetsTask.cs updated: InitializeTask() now sets TaskEnvironment for correctness.
  • All existing tests passing.

Review status

Internally reviewed via 3-round playbook (merge-group-review → expert-review-msbuild-migration → opus-4.7 adversarial). All rounds PASS after test-strengthening fixes.

Depends on polyfills infrastructure (already in main via #52909).

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.

Pull request overview

Migrates ResolveTargetingPackAssets to participate in MSBuild’s multi-threaded task execution model by implementing IMultiThreadableTask and introducing TaskEnvironment-based behavior, with accompanying unit test updates/additions.

Changes:

  • Mark ResolveTargetingPackAssets as [MSBuildMultiThreadableTask] and implement IMultiThreadableTask with a TaskEnvironment property.
  • Make targeting-pack caching behavior depend on TaskEnvironment (instead of a static, process-environment lookup) and thread the decision through resolve helpers.
  • Update/add unit tests to set/exercise TaskEnvironment and validate basic concurrency/caching behavior.

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated 3 comments.

File Description
src/Tasks/Microsoft.NET.Build.Tasks/ResolveTargetingPackAssets.cs Implements IMultiThreadableTask, introduces TaskEnvironment, and refactors caching toggle/calls to be task-environment driven.
src/Tasks/Microsoft.NET.Build.Tasks.UnitTests/GivenAResolveTargetingPackAssetsTask.cs Updates task initialization to set TaskEnvironment; adjusts hashing test to ignore TaskEnvironment.
src/Tasks/Microsoft.NET.Build.Tasks.UnitTests/GivenAResolveTargetingPackAssetsMultiThreading.cs Adds new tests covering TaskEnvironment-controlled caching and basic concurrent execution behavior.
Comments suppressed due to low confidence (1)

src/Tasks/Microsoft.NET.Build.Tasks/ResolveTargetingPackAssets.cs:331

  • AddItemsFromFrameworkList populates analyzerItems/referenceItems from a cached FrameworkList, but then continues to load and parse FrameworkList.xml anyway. This defeats the purpose of caching and may also re-register the same task object / add duplicates when a framework-list cache hit occurs without an overall cache hit. After a cache hit, return early to avoid extra I/O and duplicate work.
            if (allowCacheLookup &&
                buildEngine4?.GetRegisteredTaskObject(
                  frameworkListKey,
                  RegisteredTaskObjectLifetime.AppDomain)
                is FrameworkList cacheEntry)
            {
                // As above, we are not even checking timestamps here
                // and instead assuming that the targeting pack folder
                // is fully immutable.

                analyzerItems.AddRange(cacheEntry.Analyzers);
                referenceItems.AddRange(cacheEntry.References);
            }

            XDocument frameworkListDoc = XDocument.Load(definition.FrameworkListPath);

@SimaTian

Copy link
Copy Markdown
Contributor Author

Friendly ping — the dotnet-sdk-public-ci pipeline is in action_required state (Azure Pipelines requires first-time-contributor approval for fork PRs). Could a maintainer please approve the pipeline run so CI can execute? Thanks!

SimaTian and others added 2 commits May 13, 2026 12:15
Replace static Environment.GetEnvironmentVariable with instance-level
TaskEnvironment.GetEnvironmentVariable for thread-safe environment
variable access. Add [MSBuildMultiThreadableTask] attribute and implement
IMultiThreadableTask interface. Thread allowCacheLookup parameter through
static helper methods.

Co-authored-by: Copilot <[email protected]>
@AlesProkop
AlesProkop marked this pull request as ready for review May 19, 2026 11:42

@OvesN OvesN 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.

So I think after deleting of unnecessary lock and potentially addressing this comment #53944 (comment) it is good to go.

@ViktorHofer

Copy link
Copy Markdown
Member

/review

@ViktorHofer ViktorHofer left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Expert MSBuild review — IMultiThreadableTask migration of ResolveTargetingPackAssets

Reviewed the 5-commit range across ResolveTargetingPackAssets.cs and GivenAResolveTargetingPackAssetsTask.cs against the 24 review dimensions plus the multithreaded-task-migration "6 deadly compatibility sins" checklist. I traced the full post-migration source and the supporting framework types (AbsolutePath, both TaskEnvironment drivers).

The migration itself is faithful and well-tested:

  • Value/OriginalValue split is applied correctly — file I/O uses absolute Value (Directory.Exists/GetFiles, File.Exists), [Output] itemspecs use relative OriginalValue. No output contamination (Sin 1) or error-message inflation (Sin 2).
  • default(AbsolutePath).Value == null, so empty Path metadata preserves the missing-targeting-pack error branch bit-for-bit — no NRE, no swallowed exception (Sins 3 & 6 clean).
  • No canonicalization regression (Sin 5): pre-migration code never called Path.GetFullPath either, so cache/dedup keys see the same non-canonical strings.
  • Per-key locking is deadlock-free: lock order is always top-level → framework-list (a leaf), key namespaces are disjoint by class-name prefix, so no cycle is constructible.
  • Moving allowCacheLookup from a process-static field to a per-Execute TaskEnvironment.GetEnvironmentVariable read actually fixes a latent multithreading bug.
  • The shared-TaskItem[]-on-cache-hit behavior is pre-existing (AppDomain cache + node reuse), not introduced here.
# Dimension Verdict
3 Performance & Allocation 🟢 1 NIT (s_cacheLocks unbounded growth)
10 / 20 Design / Scope 🟡 1 MODERATE (RuntimeFramework.CacheKey rewrite — unrelated cache-correctness change)

✅ 21/24 dimensions clean — all 6 compatibility sins clean, concurrency clean, cache-key isolation test-proven.

  • Scope — call out (or split) the RuntimeFramework.CacheKey change
  • Performance (NIT) — note intentional process-lifetime growth of s_cacheLocks

Verdict: COMMENT — nothing blocks merge. The only substantive ask is to surface the RuntimeFramework.CacheKey change so it gets reviewed on its own merits.

@AlesProkop
AlesProkop enabled auto-merge (squash) June 2, 2026 12:11
@AlesProkop
AlesProkop merged commit 6579d35 into dotnet:main Jun 2, 2026
25 checks passed
@dotnet-milestone-bot dotnet-milestone-bot Bot added this to the 11.0-preview6 milestone Jun 3, 2026
rainersigwald added a commit to rainersigwald/sdk that referenced this pull request Jun 26, 2026
Copilot analysis of an allocation regression when inserting .NET SDK 11
into Visual Studio and building OrchardCore pointed to a 43× increase
in `Slot[TaskItem][]` allocations in `ResolveTargetingPackAssets`.

The cache key introduced in dotnet#53944 added _all_ metadata to the cache
identity. That includes the computed metadatum `DefiningProjectFullPath`
that's distinct for every project, which caused spurious cache
invalidation.

Just reverting it didn't look quite right as another possibly-relevant
metadatum was added in dotnet#39402. Added that and put comments in both
places to hopefully avoid future drift.
rainersigwald added a commit that referenced this pull request Jun 29, 2026
Copilot analysis of an allocation regression when inserting .NET SDK 11
into Visual Studio and building OrchardCore pointed to a 43× increase
in `Slot[TaskItem][]` allocations in `ResolveTargetingPackAssets`.

The cache key change in #53944 added _all_ metadata to the cache
identity. That includes the computed metadatum `DefiningProjectFullPath`
that's distinct for every project, which caused spurious cache
invalidation.

Just reverting it didn't look quite right as another possibly-relevant
metadatum was added in #39402. Added that and put comments in both
places to hopefully avoid future drift.
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.

[Multithreaded] Migrate ResolveTargetingPackAssets in SDK

6 participants