Repository navigation
Fix MSBuild coordinator deadlock for nested MSBuild processes - #14224
Conversation
Encapsulate the coordinator pipe, reader, writer, connection ID, handshake, and server capabilities in a nested Connection helper. This makes ownership transfer to CoordinatorClient explicit and keeps message I/O details out of grant negotiation.
Move the WaitMessage response flow into a dedicated WaitForDeferredGrant helper. This keeps TryNegotiate focused on the initial coordinator response and scopes heartbeat pumping to the deferred-grant path.
Rename ClientConnection to ConnectedClient and introduce a server-side Connection helper for initial handshake ownership. This separates handshake/request setup from the accepted client lifecycle and keeps pipe reader/writer ownership encapsulated.
There was a problem hiding this comment.
Pull request overview
This PR addresses coordinator deadlocks in nested MSBuild scenarios (for example, NuGet static-graph restore launching an MSBuild-based child process) by adding a capability-gated “nested grants” protocol so child processes can join an existing root grant instead of waiting for additional global budget.
Changes:
- Introduces the
nested-grantscapability and new protocol messages (JoinGrantMessage,NodeGrantWithIdMessage) plus grant-token flow viaMSBUILDCOORDINATORGRANTID. - Refactors coordinator server/client connection ownership to separate handshake/request negotiation from the post-grant lifecycle, and improves trace formatting.
- Expands unit + integration test coverage for nested grant behavior, and updates coordinator documentation.
Reviewed changes
Copilot reviewed 34 out of 34 changed files in this pull request and generated 3 comments.
Show a summary per file
| File | Description |
|---|---|
| src/UnitTests.Shared/TestEnvironment.cs | Includes coordinator/debug-path trace files in invariant output and scans the framework debug path for MSBuild logs. |
| src/UnitTests.Shared/RunnerUtilities.cs | Adds reusable bootstrap MSBuild path/command helpers and simplifies bootstrapped execution. |
| src/MSBuild.Coordinator/NodeBudgetManager.cs | Prevents nested grants from consuming/releasing global node budget. |
| src/MSBuild.Coordinator/CoordinatorTelemetry.cs | Adds grant-id and nested/non-nested tags to coordinator telemetry activities. |
| src/MSBuild.Coordinator/CoordinatorServer.DefaultDebugOutput.cs | Improves timestamp/thread formatting for coordinator trace output. |
| src/MSBuild.Coordinator/CoordinatorServer.cs | Implements nested-grant join handling, refactors client lifecycle, and adds grant-id tracking for root grants. |
| src/MSBuild.Coordinator/CoordinatorServer.Connection.cs | New: encapsulates server-side handshake and initial request negotiation over the pipe. |
| src/MSBuild.Coordinator/CoordinatorServer.ConnectedClient.cs | New: encapsulates accepted client state + pipe ownership during the grant lifecycle. |
| src/MSBuild.Coordinator/ClientConnection.cs | Removed in favor of the new Connection/ConnectedClient split. |
| src/MSBuild.Coordinator/BuildGrant.cs | Adds GrantId and IsNested to represent root vs nested grants. |
| src/MSBuild.Coordinator.UnitTests/NodeBudgetManager_Tests.cs | Adds coverage for nested-grant release not returning root budget. |
| src/MSBuild.Coordinator.UnitTests/Message_Tests.cs | Adds round-trip coverage for JoinGrantMessage and NodeGrantWithIdMessage. |
| src/MSBuild.Coordinator.UnitTests/CoordinatorTelemetry_Tests.cs | Verifies new telemetry tags, including nested-grant tagging. |
| src/MSBuild.Coordinator.UnitTests/CoordinatorServer_Tests.cs | Adds protocol/capability tests and verifies nested join doesn’t consume additional budget. |
| src/MSBuild.Coordinator.UnitTests/CoordinatorIntegration_Tests.cs | Adds end-to-end integration coverage for nested MSBuild and NuGet static-graph restore scenarios. |
| src/MSBuild.Coordinator.UnitTests/CoordinatorClient_Tests.cs | Adds tests for grant-id environment flow and nested join behavior. |
| src/Framework/Coordinator/Messages/ServerMessageType.cs | Adds a new server message type for node grants carrying a grant token. |
| src/Framework/Coordinator/Messages/ServerMessage.cs | Extends deserialization to handle NodeGrantWithIdMessage. |
| src/Framework/Coordinator/Messages/NodeGrantWithIdMessage.cs | New: server response that includes both grant-id and granted node count. |
| src/Framework/Coordinator/Messages/NodeGrantMessage.cs | Implements a common grant interface (INodeGrantMessage) with an empty grant-id. |
| src/Framework/Coordinator/Messages/JoinGrantMessage.cs | New: client request to join an existing root grant by id. |
| src/Framework/Coordinator/Messages/INodeGrantMessage.cs | New: shared contract for node-grant messages (legacy + with-id). |
| src/Framework/Coordinator/Messages/ClientMessageType.cs | Adds JoinGrant message type and updates payload documentation. |
| src/Framework/Coordinator/Messages/ClientMessage.cs | Extends deserialization to handle JoinGrantMessage. |
| src/Framework/Coordinator/Constants.cs | Adds the MSBUILDCOORDINATORGRANTID environment variable name constant. |
| src/Framework/Coordinator/Capabilities.cs | Defines the nested-grants capability string. |
| src/Framework/BackEnd/CommunicationsUtilities.cs | Aligns comm trace formatting with coordinator trace formatting. |
| src/Build/Microsoft.Build.csproj | Includes new CoordinatorClient partial files in the Build project. |
| src/Build/BackEnd/BuildManager/CoordinatorClient.GrantOwnership.cs | New: models root vs nested grant ownership semantics for env-var flow/restore. |
| src/Build/BackEnd/BuildManager/CoordinatorClient.cs | Implements nested join behavior, grant-id environment flow/restore, and refactors negotiation logic. |
| src/Build/BackEnd/BuildManager/CoordinatorClient.Connection.cs | New: encapsulates client-side handshake and request negotiation over the pipe. |
| src/Build/BackEnd/BuildManager/BuildParameters.cs | Adds helper to update the frozen build-process environment map. |
| src/Build/BackEnd/BuildManager/BuildManager.cs | Flows coordinator grant-id into the build process environment for child processes. |
| documentation/MSBuild-Coordinator.md | Documents nested grants, updated protocol message set, and the new grant-id environment variable. |
There was a problem hiding this comment.
Caution
agentic threat detected
Threat detection flagged this output in warn mode. Manual review is REQUIRED before any follow-up automation.
Code Review — PR #14224 (Fix MSBuild coordinator deadlock for nested MSBuild processes)
20/24 dimensions clean. Four findings, no blocking issues.
Findings
[MAJOR] Concurrency — SetInheritedGrantId/RestoreInheritedGrantId are not thread-safe
CoordinatorClient.cs lines ~139–159. The two static helpers perform a GetEnvironmentVariable / SetEnvironmentVariable pair with no lock. In scenarios where two BuildManager instances coexist in the same process (VS hosts multiple), two concurrent root grants will corrupt each other's saved/restored env state: Thread B reads the env var as null before Thread A sets it, stores the wrong _previousGrantId, and the env var is never restored correctly after both clients dispose. Inline comment on line 152.
[MODERATE] Correctness — RedirectStandardOutput = true / RedirectStandardError = true without a reader
CoordinatorClient.cs lines 562–563 (dll branch) and 575–576 (exe branch). No code ever drains these streams. The coordinator is a headless daemon — CreateNoWindow = true already suppresses console windows. The concrete risk: if the coordinator fails to start and the dotnet host writes a structured framework-mismatch error to stderr, the coordinator process blocks on write once the OS pipe buffer fills and is orphaned until MSBuild exits. Additionally, startup-failure reasons become invisible (MSBuild sees only "failed to connect"). Inline comment on line 563.
[MAJOR] Test Coverage — Release_NestedGrant_DoesNotReturnRootBudget does not exercise DrainWaitQueue
NodeBudgetManager_Tests.cs line ~165. The test has no waiting grant in the queue, so DrainWaitQueue_NoLock (which is always called from Release) has nothing to drain and the crucial invariant — "releasing a nested grant must not unblock root-budget waiters" — is not asserted. A refactor that accidentally removes the if (grant.IsNested) guard in NodeBudgetManager.Release would not be caught at the unit-test level. Inline comment on line 165.
[NIT] Naming — TryReadGrantRequest understates its responsibility
CoordinatorServer.cs. The method validates, sends error replies, looks up root grants, and constructs BuildGrant objects — it's grant negotiation, not just reading. Suggest TryNegotiateGrant to match the vocabulary used in CoordinatorClient.TryNegotiate. Inline comment on line 253.
Clean dimensions (20/24)
Backwards Compatibility, ChangeWave Discipline, Performance & Allocation, Error Message Quality, String Comparison Correctness, API Surface Discipline, MSBuild Target Authoring, Design Before Implementation, Cross-Platform Correctness, Code Simplification, SDK Integration Boundaries, Idiomatic C# Patterns, File I/O & Path Handling, Documentation Accuracy, Build Infrastructure Care, Scope & PR Discipline, Evaluation Model Integrity, Dependency Management, Security Awareness, and the protocol correctness of the nested-grant TOCTOU (correctly sequenced under ReaderWriterLockSlim).
The feature design itself is solid: capability gating, environment-variable inheritance, server-side validation at join time, and the INodeGrantMessage interface for transparent grant-type dispatch are all well-executed. The integration test covering the NuGet static graph restore scenario directly validates the reported issue fix.
Generated by Expert Code Review (on open) for #14224 · 4.5K AIC · ⊞ 30.3K
4148730 to
9051ca8
Compare
Extract grant request parsing and accepted-client setup from HandleClientAsync. Centralize connected-client cleanup and make post-grant protocol errors release grants consistently.
Add JoinGrantMessage for clients joining an existing coordinator grant and NodeGrantWithIdMessage for returning grant tokens to capable clients. Keep the original NodeGrantMessage wire shape for compatibility and add shared grant-message handling through INodeGrantMessage.
Teach CoordinatorClient to advertise nested-grants support, flow root grant IDs through the environment, and join inherited grants when available. Track root versus nested grant ownership so only root grants manage the ambient grant token, and handle both legacy and grant-ID node grant responses through the shared grant message contract. In addition, when a root coordinator grant is received, add its grant ID to BuildParameters.BuildProcessEnvironment so tasks and child MSBuild processes inherit the coordinator grant. Add a helper for updating the captured build process environment consistently.
Teach the coordinator server to accept JoinGrant requests from capable clients and validate them against active root grant tokens. Track active root grants, return grant IDs to nested-grant-capable clients, and ensure nested grants borrow root budget without consuming or releasing global node budget.
Tag coordinator telemetry activities with the grant ID and whether the grant is nested so root and joined grants can be distinguished in diagnostics.
Direct coordinator integration test debug logs to a test-controlled path and teach the build failure log invariant to inspect FrameworkDebugUtils.DebugPath and look for coordinator logs. Also, improve communication trace formatting and prevent the launched coordinator process from inheriting redirected MSBuild output handles.
Cover nested coordinator grant behavior across client, server, telemetry, and integration paths. Add tests for grant ID environment flow, inherited grant joins, legacy capability fallback, nested grant server responses, and nested grant release accounting. Add integration coverage for coordinated child MSBuild invocations and the NuGet static graph restore scenario from dotnet#14170. Configure coordinator debug logs to use a test-owned path, shorten coordinator shutdown for integration tests, disable shared compilation in launched builds to avoid compiler-server file locks, and expose a shared RunnerUtilities bootstrap MSBuild command helper for cross-platform test execution.
9051ca8 to
3a63b7f
Compare
Update the coordinator architecture document with nested grant protocol flow, grant ID propagation, capability gating, and limitations around root/nested concurrency. Also refresh server component names and environment variable documentation.
3a63b7f to
3b81288
Compare
AR-May
left a comment
There was a problem hiding this comment.
LGTM, I have only a minor comment and one discussion point.
|
@DustinCampbell happy to merge after you addressed the comments |
Move server message payload deserialization into the corresponding message types so ClientMessage and ServerMessage dispatch only by message kind. This keeps coordinator wire-format read logic co-located with each message payload. For readability, avoid performing reads in message constructor calls.
Update the nested grants example to describe NuGet static-graph restore as launching a nested process that uses MSBuild APIs during an already-coordinated build.
Add NodeBudgetManager coverage for issuing nested grants to verify they return their assigned node count without increasing allocated nodes or active root grant accounting.
Introduce a shared Message<TMessageType> base for coordinator wire framing and factory-based dispatch for client and server messages. Move message type storage into the base type and centralize payload creation through per-direction factory tables.
Extend the coordinator message wire framing with an optional extended-fields byte, indicated by the high bit of the message type byte. Add factory metadata for supported extension masks and validate unsupported marker usage, reserved type bits, and unknown extension bits before payload parsing. Add tests that reject extended-field markers on message types that do not support extensions.
Fold the nested-grant token into NodeGrantMessage as an optional extended field instead of using a separate NodeGrantWithIdMessage type. Remove the extra server message type and INodeGrantMessage abstraction so node grants use one semantic message with capability-gated payload data. Update coordinator client/server handling, tests, and documentation for the new NodeGrantMessage wire shape.
|
@rainersigwald and @AR-May: I think I've addressed your feedback and I added three more commits that refactor the coordinator message infrastructure to allow messages to be extended with optional fields. That should avoid a multi-dimensional explosion as further capabilities are added. I decided to add that feature to this PR since "nested-grants" is the first capability added. |
Track accepted client connections from pipe acceptance through negotiation and grant lifetime, and include those connections in the server idle check. This prevents the auto-shutdown timer from stopping the coordinator while a client is between handshake and grant registration. Restart the shutdown timer when the last active connection exits and the server is otherwise idle.
|
@DustinCampbell & @rainersigwald I see this new capability fixes immediate deadlock and keeps things simple and backward-compatible, but isn't there still a room for improvement? I can think of an example where parent process would have all resources and child even though not waiting, still does not have resources, thus performance degrades. I also think it might be a burden on root build logic to self-coordinate as it is not transparent to users. I generally like this nested-grant idea, but maybe it would be good to create some issues about improving it? So that we don't lose and re-discover it again later when we try to optimize stuff? Just asking |
I suspect that #14241 might to do more to address these issues as well. That's waiting on this PR though. |
Oh yes! My hope is that nested grants are not often used, and we can let this functionality stay suboptimal and focus on other areas. I actually think dynamically-requested cores (as we would want to use them) might be another way out of this--then the parent might not be using the full capacity when the child comes along and requests some. That's definitely the case in static-graph restore, when the parent build has only had to use one node. |
…MSTest PR #14224 (coordinator deadlock fix) landed on main adding new xUnit [Fact] tests in MSBuild.Coordinator.UnitTests. Merged main and converted the new/conflicting tests to MSTest ([Fact]->[MSBuildTestMethod]), and fixed the CoordinatorTestHelper ctor param from ITestOutputHelper to TestContext. All 73 coordinator tests pass on net10. Co-authored-by: Copilot App <[email protected]> Copilot-Session: 49f1ea15-de87-41f9-b4c0-62ddf5ecd47f
Build 1509649: 7/8 legs fully green (all net472 + Linux + Source-Build). Only macOS Core failed on flaky shared-infra invariant BuildFailureLogInvariant (TestEnvironment.cs debug/failure-log file-count race, extended by main PR #14224 for coordinator traces) in Tasks CopyWithDuplicatesUsingFiles, plus a macOS coordinator test-host crash (no TRX). Both pass on Linux + Windows; classic macOS process/pipe timing flakiness, not a migration defect. Re-running to confirm. Co-authored-by: Copilot App <[email protected]> Copilot-Session: 49f1ea15-de87-41f9-b4c0-62ddf5ecd47f
### Context This PR hardens coordinator client/server lifecycle handling on top of #14224. Coordinator client writes can come from multiple lifecycle paths: regular heartbeat timers, deferred-wait heartbeat pumps, and `Dispose` releasing a grant. Those paths need to avoid overlapping `BinaryWriter` writes and timer callbacks racing with connection ownership changes or disposal. ### Changes Made - Keep coordinator client transport ownership centered on `CoordinatorClient.Connection`. - Serialize client message writes inside `Connection`, so heartbeats, deferred-wait heartbeats, and release messages share one write path. - Drain deferred-wait and client heartbeat timers before the associated connection can be disposed. - Track accepted coordinator server connections while they are negotiating so idle shutdown does not race an in-progress client. - Make deferred grant notification resilient when a waiting client disconnects while being granted nodes. - Make connected-client disposal idempotent. - Add targeted regression tests for client disposal, deferred-wait heartbeats, accepted-client shutdown timing, and disconnected deferred waiters. ### Testing - `.\build.cmd -v quiet` - `dotnet msbuild src\Build\Microsoft.Build.csproj -p:Configuration=Release -v:q` - `dotnet msbuild src\MSBuild.Coordinator\MSBuild.Coordinator.csproj -p:Configuration=Release -v:q` - `dotnet test src\MSBuild.Coordinator.UnitTests\MSBuild.Coordinator.UnitTests.csproj -c Release`
Arcade sets MSBUILDDEBUGPATH once per build (eng/common/tools.ps1) to $LogDir/MsbuildDebugLogs. Since dotnet#14224 BuildFailureLogInvariant also scans FrameworkDebugUtils.DebugPath, which resolves to that single shared folder in every test process. Test assemblies run in parallel, and the invariant deletes the files it considers new, so parallel processes saw and destroyed each other's MSBuild_*.txt files - producing flaky failures in both directions. Give each test process its own subfolder, nested under the Arcade path so the logs are still published as a CI artifact. Co-authored-by: Copilot App <[email protected]>
Related issue(s): ### Context `BuildFailureLogInvariant` flakes in `msbuild-pr` CI, in both directions (`Expected: 1, Actual: 2` and `Expected: 2, Actual: 1`). It scans three directories for `MSBuild_*.txt`. Two are process-private; the third — `FrameworkDebugUtils.DebugPath`, added by #14224 — resolves to the single build-wide folder Arcade sets via `MSBUILDDEBUGPATH`. Test assemblies run in parallel as separate processes, and `AssertInvariant` deletes files it considers new *before* applying its benign-file filters, so they destroy each other's files. ### Changes Made Give each test process a `test_<pid>` subfolder, applying the isolation pattern already used for the temp path just below it. Nested under the Arcade path so the logs are still published as a CI artifact. No-op when the variable is unset. `BuildFailureLogInvariant` is deliberately unchanged: once all three scanned directories are process-private, its existing logic is correct as written. --------- Co-authored-by: Copilot App <[email protected]> Co-authored-by: Copilot Autofix powered by AI <[email protected]>
Fixes #14170
Tip
I recommend reviewing commit-by-commit. Each commit tells a story and helps separate refactoring from new behavior.
CoordinatorClientandCoordinatorServerto prepare for new behavior. (9c465c8, 9c092a7, 53ab0a2, 59aa4b7)Summary
Fixes coordinator deadlocks when a build launches nested MSBuild-based work, such as NuGet static graph restore, while the root build is already holding a coordinator node grant.
nested-grantscapabilityJoinGrantMessageNodeGrantWithIdMessageMSBUILDCOORDINATORGRANTIDinternal grant tokenNodeGrantMessagewire shape for clients that do not advertisenested-grants.Important behavior
Nested grants:
The root build remains responsible for coordinating its own nested work to avoid over-subscription within the root grant.
Validation
Added unit coverage for:
Added integration coverage for:
Coordinator integration tests now use a test-controlled debug path for trace capture.