Skip to content

Honor multithreadable attributes on inline task classes - #15128

Merged
JanProvaznik merged 6 commits into
dotnet:mainfrom
JanProvaznik:janprovaznik-inline-task-attribute-routing
Oct 5, 2026
Merged

JanProvaznik merged 6 commits into
dotnet:mainfrom
JanProvaznik:janprovaznik-inline-task-attribute-routing

Conversation

@JanProvaznik

@JanProvaznik JanProvaznik commented Sep 24, 2026 •

Copy link
Copy Markdown
Member

Related issue(s): #14138 (partial)

Context

Roslyn inline task classes run in a TaskHost during multithreaded builds even when marked [MSBuildMultiThreadableTask].

Changes Made

Respect the concrete task class's attribute when routing tasks from supported factories. Keep dependency resolvers available across repeated and overlapping invocations, including compiled-assembly cache hits. Add focused C# regressions and document class-based opt-in.

Compatibility

Unannotated tasks and generated Fragment/Method tasks remain isolated. Unsupported custom factories remain rejected, and forced isolation still takes precedence. No public API changes.

Testing

Full build passed. Roslyn factory tests passed: 68 on .NET and 66 on .NET Framework 4.7.2. The reviewer's delayed-dependency repro now passes. PID routing and unsupported-factory regressions passed on both target frameworks. Earlier full-suite validation had one desktop test fail because msbuild was missing from PATH; its isolated retry passed with Visual Studio MSBuild on PATH.

Dependencies and Follow-up

Possible follow-up: support TaskEnvironment constructor injection for Roslyn task classes. Pass the invocation's environment through the internal factory context and reuse the existing environment-constructor/parameterless-constructor selection. Also avoid creating a throwaway task in the parent on the sidecar path; use the factory's task type for metadata, preserving cleanup responsibilities. This PR retains the public parameterless-constructor requirement.

Fragment/Method authoring support is deferred.

Fixes: #14138

JanProvaznik and others added 4 commits September 24, 2026 15:37
Keep the supported-factory gate and forced-isolation precedence while honoring the existing task attribute. Add routing and factory-rejection regressions and document class-mode support.

Co-authored-by: Copilot App <[email protected]>
Compare inline and assembly task PIDs in one C# MT test. Remove the VB fixture and mode matrix, and focus custom-factory coverage on rejection before task creation.

Co-authored-by: Copilot App <[email protected]>
Copilot AI lite review requested due to automatic review settings September 24, 2026 15:43
@JanProvaznik
JanProvaznik requested a review from a team as a code owner September 24, 2026 15:43

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.

Copilot review overview

🔵 Needs a closer look

Preserve explicit MSBuildRuntime and MSBuildArchitecture parameters when routing attributed inline tasks.

Review effort: Lite
Findings: None

What changed in this PR

Updates MSBuild routing so attributed Roslyn inline task classes can run in-process during multithreaded builds.

Changes:

  • Routes supported factories using the concrete task’s multithreadable attribute.
  • Adds inline-task and unsupported-factory regression tests.
  • Documents inline class opt-in and focused test guidance.
File Summary
src/​Tasks.UnitTests/​RoslynCodeTaskFactory_Tests.cs Adds PID-based inline routing regression coverage.
src/​Build/​BackEnd/​TaskExecutionHost/​TaskExecutionHost.cs Applies attribute-aware routing while preserving forced isolation; explicit identity parameters require correction.
src/​Build.UnitTests/​BackEnd/​TaskExecutionHost_Tests.cs Verifies unsupported factories remain rejected.
documentation/​specs/​multithreading/​thread-safe-tasks.md Documents inline task opt-in.
.github/​instructions/​tests.instructions.md Adds focused routing-test guidance.

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

@github-actions github-actions Bot 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.

# Dimension Verdict
22 Correctness & Edge Cases 🔴 1 BLOCKING

✅ 23/24 dimensions clean.

  • Correctness — repeated in-process Roslyn inline-task invocation can lose its external-assembly resolver after the first cleanup

Warning

Firewall blocked 3 domains

The following domains were blocked by the firewall during workflow execution:

  • api.github.com
  • github.com
  • patchdiff.githubusercontent.com

[!TIP]
api.github.com is blocked because GitHub API access uses the built-in GitHub tools by default. Instead of adding api.github.com to network.allowed, use tools.github.mode: gh-proxy for direct pre-authenticated GitHub CLI access without requiring network access to api.github.com:

tools:
  github:
    mode: gh-proxy

See GitHub Tools for more information on gh-proxy mode.

To allow these domains, add them to the network.allowed list in your workflow frontmatter:

network:
  allowed:
    - defaults
    - "api.github.com"
    - "github.com"
    - "patchdiff.githubusercontent.com"

See Network Configuration for more information.

Generated by Expert Code Review (on open) for #15128 · copilot · gpt56 · 941.4 AIC · ⌖ 6.96 AIC · ⊞ 17.8K

Cache the resolver with the compiled assembly and balance subscriptions per task instance, preserving initialization-time resolution and overlapping invocations. Ignore TaskHost wrapper cleanup and release subscriptions on failed initialization or construction.

Co-authored-by: Copilot App <[email protected]>
@ViktorHofer

Copy link
Copy Markdown
Member

MSBuild code review

Scope: c32fc908ce..217fda432f — 5 commits, 6 files. Both changed product assemblies build clean for .NET Framework and modern .NET.

Assessment: request changes. No blocking correctness defect was identified. Backward compatibility checks out, and no ChangeWave is needed: /mt is opt-in, the attribute is explicit, and no new warnings are introduced. The new routing call does not encounter MetadataLoadContext types.

Must fix

Finding Issue
H1 — Documentation documentation/specs/multithreading/thread-safe-tasks.md:111-120 removed the forced-isolation override, unsupported-factory restriction, thread-safety disclaimer, and Code Source clarification. Restore these statements so the documentation describes the implemented contract.
H2 — Negative routing coverage src/Tasks.UnitTests/RoslynCodeTaskFactory_Tests.cs:1149 proves attributed inline classes run in-process, but not that unattributed classes remain isolated. Add an unattributed-class PID-differs case; also cover forced isolation of an attributed class.
H3 — Resolver lifetime contract src/Tasks/RoslynCodeTaskFactory/RoslynCodeTaskFactory.cs:113-155,231 relies on one resolver subscription per successful CreateTask, with the first task inheriting the initialization subscription. Document and test this invariant, including the inner-task cleanup at TaskExecutionHost.cs:2246 before wrapper cleanup.
M5 — Resolver regression determinism RoslynCodeTaskFactory_Tests.cs:1255-1287: successful execution can mask missing resolver registration if the dependency is already loaded. Assert subscription balance directly and ensure process-global state is restored on assertion failures.
M7 — Test instructions .github/instructions/tests.instructions.md:50 encodes PR-specific history (“compiler-launcher infrastructure”) as a repository-wide rule. Keep the general focused-regression guidance and positive PID-comparison technique; remove the historical counterexample.

Recommended in this PR

  • M6 — Cache retention: TaskRouter.cs:31 now receives runtime-compiled inline-task types in its static ConcurrentDictionary<Type, bool>. Consider weak-key caching to avoid retaining these types independently of their existing owners.
  • M3 — Factory coverage: TaskExecutionHost.cs:1307-1308 also applies to CodeTaskFactory and XamlTaskFactory, while the documentation and new execution tests cover Roslyn only. Clarify the scope and cover the legacy class-body path.
  • L1 — Test artifacts: remove unused /bl:routing.binlog and /bl:15.binlog switches unless their output is intentionally retained for diagnostics.

Follow-up considerations

  • M1 — Initialization failures: a user task's BuildEngine or HostObject setter can throw before CleanupForBatch is protected by a finally. Per-task subscriptions can then accumulate. Review exception-safe resolver ownership across that boundary.
  • M2 — Resolver isolation: CreateAssemblyResolver ignores RequestingAssembly and loads dependency bytes without caching. Longer-lived overlapping registrations under /mt amplify cross-task resolution risks; consider request scoping and assembly caching.
  • M4 — Declared versus instantiated type: routing uses ITaskFactory.TaskType, while the out-of-process wrapper uses innerTask.GetType(). Document the factory contract where those differ.

What's good

The routing fix is minimal and preserves the unsupported-factory gate before attribute routing. The resolver-lifetime bug being addressed is real, happy-path registration accounting balances, and concurrent first-task handoff uses Interlocked correctly.

Include initialization in batch cleanup, preserve assembly-load tracking through cleanup, and cover a throwing BuildEngine setter. Protect resolver test cleanup on assertion failures and remove PR-specific test guidance.

Co-authored-by: Copilot App <[email protected]>
@JanProvaznik

Copy link
Copy Markdown
Member Author

Thanks @ViktorHofer. Addressed the cleanup issues in dda9b94:

  • M1: initialization is now inside the batch-cleanup finally boundary, so throwing BuildEngine/HostObject setters no longer bypass factory cleanup. Added a focused throwing-setter regression that verifies cleanup happens exactly once. Assembly-load tracking still spans cleanup.
  • M5: moved the resolver test's cleanup protection ahead of task creation and assertions. Keeping behavioral coverage rather than inspecting private AppDomain event state; the delayed-dependency regression runs in a fresh process.
  • M7: removed the PR-specific historical wording from the test instructions.

H2: not adding more PID/isolation end-to-end cases. The negative routing and forced-isolation paths are covered elsewhere; duplicating those runs adds flakiness without useful additional coverage for this change.

For the remaining points: the short documentation is intentional (H1), and the subscription ownership comments plus inner-task/wrapper cleanup sequence are already covered (H3). Binlogs are intentional diagnostics (L1). M3/M4: supported factories instantiate their declared task type; CodeTaskFactory already has a persistent resolver, and generated XAML tasks remain unattributed. M6: a weak routing cache would not make these statically cached, noncollectible assemblies unloadable, so I am leaving that redesign out. M2 is worth separate investigation, rather than expanding this PR into a dependency-loader redesign.

Full build passed. TaskBuilder and Roslyn factory tests passed on both .NET and .NET Framework (185 tests total, none skipped).

@JanProvaznik
JanProvaznik merged commit 31c668b into dotnet:main Oct 5, 2026
14 checks passed
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.

support declaring RoslynCodeTaskFactory tasks multithreadable

3 participants