Skip to content

Spec: Yield and Reacquire in out-of-process TaskHosts - #15624

Draft
baronfel wants to merge 7 commits into
mainfrom
baronfel-taskhost-yield-spec
Draft

baronfel wants to merge 7 commits into
mainfrom
baronfel-taskhost-yield-spec

Conversation

@baronfel

@baronfel baronfel commented Nov 20, 2026 •

Copy link
Copy Markdown
Member

Related issue(s):

None.

Context

CL and MIDL yield their node while an external compiler runs, so another project can use that capacity. In an out-of-process TaskHost, Yield and Reacquire are no-ops. The node stays reserved instead.

On a 104-project workload at -m:8, clean builds took 39.2 s in-process, 99.4 s with MSBuild.exe -mt, and about 103-104 s in the later yield-disabled comparison.

Start with the diagrams: in-process overlap versus current TaskHost behavior.

Changes Made

Documentation only. The spec explains why yielded-task lifetime, process state, routing, scheduler accounting, and memory need design decisions.

  • Option A diagram: reuse the node, but keep overlapping tasks in separate TaskHost processes.
  • Option B diagram: reuse the node and TaskHost, with task-ID routing and per-task cancellation.

The recommendation favors B only if its shared-state risk is acceptable. Tests and diagnostics cannot enforce isolation.

Review questions: accept that risk or choose A, provide per-task isolation, and decide whether balanced completion needs engine-level enforcement. The no-op differences remain unexplained.

The spec retains the existing-callback comparison, reacquire constraints, benchmark provenance, rebased prototype links, and links from the related threading specs.

Compatibility

No product behavior changes. The proposed implementations negotiate packet version 9, retain no-op behavior for older and CLR2 hosts, and provide a change wave 18.14 opt-out.

Testing

  • git diff --check - passed.
  • mmdc -i documentation\specs\multithreading\taskhost-yield.md -o "$env:TEMP\taskhost-yield-05c023a1-review.md" -e svg --quiet - passed. All four diagrams render and were visually checked.
  • Checked 13 relative links/anchors, both prototype branches, six linked commits, and preservation of benchmark table values.
  • No product build or unit tests run for this documentation-only change.

Local benchmark evidence, not committed:

  • C:\Users\chusk\.copilot\session-state\daf19032-ba4c-47ec-a9d5-50e049a6d4d7\files\native-cpp-yield\measure-141146-a42b7f (normal mode, four rounds)
  • C:\Users\chusk\.copilot\session-state\0d839b1c-0964-4ff4-a89f-5b16e337e413\files\native-cpp-yield-mt\measure-163107-c7fbd4 (-mt, two rounds)

Runs were sequential, not concurrent, with variant order varied. Sample counts are small.

Dependencies and Follow-up

Select the isolation design before an implementation PR. Both prototypes build on the CLR4 TaskHost support parent identified in the spec.

Compare process-level isolation and shared TaskHosts with task-ID routing
for forwarding IBuildEngine3.Yield/Reacquire from out-of-process TaskHosts,
and recommend the shared-host design with shared-state mitigations.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@baronfel baronfel added Area: C++ tasks and targets Related to C++ (vcxproj) builds, which are part of Visual Studio and not part of this repository. Area: TaskHost Area: Multithreaded labels Nov 20, 2026
baronfel and others added 3 commits November 20, 2026 10:01
Correct benchmark interpretation, process boundaries, and shared-state safeguards.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

## Open questions

- Should Option B allow a task to request a separate TaskHost when it cannot follow the shared-state rule?

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.

Don't we already differentiate between "explicit taskhost" and "sidecar taskhost"? The decision here could be whether you're sidecar.

The callback model does not cover explicit `Yield`:

- `IBuildEngine3.Yield()` and `Reacquire()` are no-ops in the TaskHost. A callback blocks the calling thread, although other threads created by the task can still run.
- A truly yielded task continues to run while another task is active in the same process. The yielded task can log or complete during that time.

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.

Isn't it always an error to complete while yielded? I thought we required Reacquire.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

The agent during implementation (and now during additional design review) found several cases where that check isn't done - if we strengthened those checks then some implementation cost/code size may shrink.

I've added a bit more detail about yielding today and the engine level checks to this doc to highlight the gaps and potential for strengthening the engine behaviors.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
baronfel and others added 2 commits November 23, 2026 11:25
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@JanProvaznik

Copy link
Copy Markdown
Member

Thanks for writing this up and building both prototypes — the C++ clean-build regression (~39 s → ~100–117 s) is clearly real, and having both prototypes makes the trade-offs much easier to evaluate.

High-level take / Scoping recommendation

Overall, enabling arbitrary TaskHost yielding by default introduces substantial risk (both shared-state corruption under Option B and subtle feature/lifetime interactions across the whole TaskHost surface). Before committing to general-purpose TaskHost yielding by default, we should seriously consider scoping this as opt-in only for known yielding, non-migrated tasks in the C++ scenario — if we verify that existing/older C++ tasks will actually be used with new MSBuild in this mode (rather than migrating/updating them) — instead of turning it on for all tasks by default.


1. Principled protocol & handshake design first

Both prototypes end up adding stateful prefix packets (TaskHostYieldConfiguration in A, TaskHostTaskIdentity in B) immediately before TaskHostConfiguration because CLR4 TaskHosts still read TaskHostConfiguration without an extended header / packet version.

We should figure out the principled handshake and protocol-versioning story first — alongside the type-safe MSBuild node handshakes proposal and the CLR4 cross-version issues raised on #15586 — before locking in PacketVersion 9 callback specifics. Solving extended headers / version negotiation cleanly once avoids baking stateful two-packet prefix hacks into the protocol permanently.


2. Task-ID routing, Option A vs. B, and isolation boundaries


3. Feature interactions at risk (needs explicit tracing & design)

Whichever design (or opt-in scope) we pick, these existing MSBuild features interact directly with TaskHost yielding and are currently at risk in the prototypes:

Feature / Subsystem Risk / Gap
ReportFileAccesses (BuildXL Detours) High concern — needs thorough verification. ReportFileAccesses isn't allowed with -mt, but it is supported in normal OOP builds using TaskHosts (explicit TaskHostFactory, cross-runtime CLR4/NET, cross-arch). FileAccessManager attributes accesses by nodeId assuming one active request per node, which is why in-proc TaskHost.Yield() is a no-op when ReportFileAccesses == true. Neither prototype gates yieldEnabled on !BuildParameters.ReportFileAccesses, so Option B transitions the child into Yielded state even when the parent's Yield() is a no-op — and any concurrent/nested execution in a detoured TaskHost risks misattributing file accesses across projects.
MSBuild-internal process-global state (Option B) The shared-state risk isn't limited to user tasks: (1) On any thread where AsyncLocal doesn't flow (native/FileTracker/COM/UnsafeQueueUserWorkItem), GetCurrentTaskContext() is null → EffectiveConfiguration falls back to _currentConfiguration (Task B's!) and WrapForParentRouting sends an unwrapped LogMessage, silently misattributing Project A's errors/warnings to Project B (or hitting #15612). (2) TaskLoader.s_resolverLoadedType / RemoveAssemblyResolver() mutates process-global AppDomain.AssemblyResolve. (3) _updateEnvironment, _debugCommunications, _updateEnvironmentAndLog are still shared instance fields overwritten by Task B (same class of bug T-Gro caught on WarningsAsErrors in #13350).
Orphaned logs & Reacquire packet-loop blocking (1) Neither prototype includes #15622's Window A fix (if (taskFinished) break;), so a ToolTask's async stdout/stderr log arriving behind TaskHostTaskComplete resets taskFinished = false and hangs TaskHostTask.Execute(). (2) HandleYieldRequest(reacquire: true) blocks TaskHostTask's only packet-pumping thread synchronously in Reacquire(): incoming LogMessages, NodeShutdown (host crash), or a background thread calling ReleaseCores()/IsRunningMultipleNodes are stalled (and ReleaseCores can deadlock) until the scheduler grants the node back.
BuildProjectFile while yielded In-proc SchedulableRequest.BlockByRequest rejects Yielding (MSB0001). Option B's auto-reacquire/re-yield workaround doesn't validate YieldThreadId (bypassing the #15331/#15338 thread check if called off-thread) and its finally { YieldContext(...); } attempts to re-yield even after BuildProjectFile fails with BuildAbortedException/cancellation.
Sidecar ownership & overflow lifetime (#14584) Under Option A, HostSlot > 0 hosts stay alive as retained sidecars across builds in MSBuild Server instead of retiring on EndBuild(). Under Option B, HandleNodeBuildComplete asserts _activeTaskCount == 0 without checking _yieldedTaskCount == 0.
GetRegisteredTaskObject & static caches Option A breaks process-affinity assumptions for tasks that share state via GetRegisteredTaskObject or static fields across invocations in a build.
Cancellation & BuildAbortedException type Option A omits InitializeSerializationContract() (crashes packet pump on cancelled Reacquire). Option B maps BuildAbortedException to GenericBuildTransferredException — even though src/MSBuild/MSBuild.csproj directly references Microsoft.Build.csproj, so real BuildAbortedException can be registered and preserved for tasks catching it. Also note HandleShutdown() still calls unbounded ExecutingThread?.Join() (flagged in #13350).
Console redirection (-mt node 1) ConsoleWritePacket is process-wide and unwrapped; overlapping tasks in Option B interleave stdout/stderr with no attribution.
Environment delta & skip-apply/restore cache Must verify _forwardEnvironmentBaseline / _lastAppliedConfigEnvironment and UpdateEnvironmentForMainNode when Task A completes while yielded and Task B has mutated or skipped applying the environment.
Core accounting (IBuildEngine9) TaskHost.Reacquire() calls ReleaseAllCores() automatically; verify interaction when a hosted task acquires cores before/during yield and another task runs in the meantime.

4. Additional Requirement: ETW Instrumentation

Please add ETW events to the common requirements (consistent with ExecuteTaskYieldStart/Stop, ExecuteTaskReacquireStart/Stop, TaskHostBuildProjectFileStart/Stop, and TaskHostDispatchStart/Stop in MSBuildEventSource.cs). At minimum we should be able to observe in traces:

  • TaskHost yield/reacquire IPC round-trip and wait duration (distinguishing scheduler reacquire wait vs. IPC overhead),
  • TaskHost overlap / slot count (how many tasks are concurrently yielded in a host or overflow slots created),
  • Unbalanced yield completions (parent-side forced reacquire).

5. Checklist of Invariants to Validate in the Final Implementation

Before any implementation PR merges, it should validate all of the following:

  • Scoping & isolation: Explicit TaskFactory="TaskHostFactory" tasks never share a process with other tasks and still exit/unlock assemblies as before. If scoped to opt-in/known tasks, non-opted-in tasks keep no-op behavior with zero overhead.
  • No packet-routing misattribution: Every task-scoped packet (LogMessage, callbacks, completion) from a yielded or active task reaches only its owning TaskHostTask — including logs emitted from background/native/non-AsyncLocal threads, or such logs are safely handled without leaking to another task or crashing (#15612/#15622 Window A & B).
  • No TaskHostTask deadlock while waiting in Reacquire(): A host crash (NodeShutdown), cancellation, or background-thread callback (ReleaseCores, logging) while blocked in Reacquire() unblocks cleanly without hanging.
  • Balanced scheduler state on all exit paths: Normal return, exception, cancellation, host crash, and unbalanced task exit (omitted Reacquire, wrong-thread Reacquire, double Yield) never strand a request in Yielding or trigger MSB0001.
  • Exact exception semantics on cancel: Cancellation during Reacquire delivers BuildAbortedException (not a packet-pump crash or GenericBuildTransferredException), and in Option B cancels only the targeted task without disturbing sibling tasks.
  • ReportFileAccesses safety: When BuildParameters.ReportFileAccesses is enabled, TaskHost yielding is disabled (yieldEnabled == false) and file-access attribution is verified in tests.
  • Sidecar & server lifecycle (Own sidecar TaskHosts so they cannot outlive their owner #14584): EndBuild() / PrepareForNextBuild() cleanly resets per-task/yield state; NodeBuildComplete never runs with active or yielded tasks still in flight; no overflow TaskHosts leak across builds in MSBuild Server; ShutdownAllNodes() cleans up all spawned hosts.
  • Process-global state safety (if Option B): Per-task isolation of _updateEnvironment, _debugCommunications, WarningsAs*, FileAccessData, and TaskLoader assembly resolver — plus synchronized shared-state guard tests (including CL/MIDL).
  • Protocol & mixed-version compatibility: Clean negotiation with older hosts (v8 and earlier) and CLR2 (no-op fallback), ChangeWave opt-out respected on reused hosts without relying on fragile stateful prefix packets, and aligned with the principled handshake/extended-header contract.
  • Performance & ETW: -mt microbenchmarks and real-world/C++ builds confirm task-ID envelope routing does not regress non-yielding -mt TaskHost throughput/allocations, no-op delta is explained and bounded, and ETW events emit properly paired start/stop traces.

6. Open Questions to Resolve in the Spec

  1. Opt-in scope vs. default-on: Can we confirm whether old/unmigrated C++ tasks (CL/MIDL) actually need to run in TaskHost with new MSBuild, and if so, should we gate TaskHost yielding to an explicit opt-in (e.g., for known yielding C++ tasks) rather than enabling it globally by default?
  2. Protocol ordering: Should we land the principled handshake / CLR4 extended-header protocol work (gist + Run .NET Framework (CLR4 and CLR2) tasks from .NET MSBuild in a Visual Studio task host #15586) first so TaskId / YieldEnabled live cleanly in TaskHostConfiguration instead of prefix packets?
  3. True cost of Option A: What do Option A's process count, RSS, and -mt no-op time look like once the per-node slot accumulation and global _hostAcquisitionLock around CreateNode() are fixed?
  4. Non-AsyncLocal threads & MSBuild-internal globals under Option B: How will Option B prevent misrouted logs when GetCurrentTaskContext() is null, and prevent collisions in TaskLoader.s_resolverLoadedType and OutOfProcTaskHostNode instance fields?
  5. Synchronous Reacquire() in TaskHostTask: How should TaskHostTask keep draining LogMessage / NodeShutdown / ReleaseCores packets while its request thread is blocked inside IBuildEngine3.Reacquire()?
  6. Engine-level balanced-yield enforcement: Should we fix unbalanced-yield handling consistently at the TaskBuilder/TaskHost layer (so OOP doesn't silently mask bugs like TarDirectory task produces MSBUILD : error MSB1025: An internal failure occurred while running MSBuild #15331 that crash in-proc), or keep it TaskHost-only?

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Area: C++ tasks and targets Related to C++ (vcxproj) builds, which are part of Visual Studio and not part of this repository. Area: Multithreaded Area: TaskHost

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants