Skip to content

Log MSBuild Server lifecycle (spawn/reuse/not-used) to the build log - #14156

Merged
JanProvaznik merged 11 commits into
dotnet:mainfrom
JanProvaznik:dev/janprovaznik/server-lifecycle-binlog-messages
Jul 14, 2026
Merged

JanProvaznik merged 11 commits into
dotnet:mainfrom
JanProvaznik:dev/janprovaznik/server-lifecycle-binlog-messages

Conversation

@JanProvaznik

@JanProvaznik JanProvaznik commented Jun 24, 2026 •

Copy link
Copy Markdown
Member

Context

It is currently hard to tell from a binary log whether a build used MSBuild Server, whether the server process was freshly spawned or reused, or why the server was not used when it was requested. This adds a dedicated, structured build event capturing that lifecycle, including the server process ID.

Changes

A single low-importance event is deferred to the start of each build (so it appears in a binary log and at -v:diag, without changing default console output). It is a dedicated, versionable MSBuildServerLifecycleEventArgs (its own binary-log record kind) rather than an ad-hoc message, so tooling can recognize and render it structurally while old viewers/consoles still show the human-readable text.

The event reports one of:

  • Server spawned — a freshly started server node serving its first build: MSBuild Server node started for this build (process ID N).
  • Server spawned (short-lived) — a /mt build with node reuse off, which uses a fresh server (for Server GC) that tears itself down afterward: MSBuild Server node started for this build only; it will shut down afterward (process ID N).
  • Server reused — an already-running server node reused for this build: Reusing the running MSBuild Server node for this build (process ID N).
  • Server not used — the server was requested but the build ran in-process: MSBuild Server was requested but not used for this build: {reason}. Reasons cover the server being busy, unreachable, crashed on launch, its state unknown, node reuse being disabled, the MSBUILDENSURESTDOUTFORTASKPROCESSES escape hatch, an incompatible invocation, or a command-line parse error.

Ordinary builds that never request the server log nothing.

MSBuildServerLifecycleEventArgs exposes structured fields so third-party loggers and log viewers can branch without parsing localized text:

  • Kind — Spawned / Reused / NotUsed (MSBuildServerLifecycleKind).
  • ProcessId — the server node's PID (0 for NotUsed).
  • ShortLived — true for a spawned server that shuts down after the build.
  • Reason — the localized, human-readable fall-back reason (for NotUsed).
  • ReasonCode — a stable, non-localized code for the fall-back cause (e.g. node-reuse-disabled, server-busy, server-crashed), for NotUsed.

Implementation notes

  • New event type Microsoft.Build.Framework.MSBuildServerLifecycleEventArgs (+ the MSBuildServerLifecycleKind enum), deriving from BuildMessageEventArgs.
  • Binary log: new BinaryLogRecordKind.MSBuildServerLifecycle with matching writer/reader; FileFormatVersion bumped 26 → 27. MinimumReaderVersion is unchanged: this is an additive, forward-compatible record, so readers that predate it skip it via the length-prefixed record framing.
  • Node transfer: LoggingEventType.MSBuildServerLifecycleEvent is registered so the event can travel from the out-of-proc server node to the client over the existing node-packet channel.
  • Deferred path: BuildManager.DeferredBuildMessage can carry a pre-built BuildEventArgs; LogDeferredMessages raises it as-is (via ILoggingService.LogBuildEvent) so it is recorded under its own event type. XMake.GetMessagesToLogInBuildLoggers builds the event in TryCreateServerLifecycleEvent().
  • Spawn vs. reuse is distinguished by a per-build counter in the server process (builds are serialized behind the busy mutex). The "not used" reason/reasonCode is recorded by the client (MSBuildClientApp) or by Main when a requested server is precluded locally, and paired in a single ServerNotUsedReason so the localized text and stable code cannot drift.
  • New localized resources (with .xlf regenerated via UpdateXlf).

Tooling

The MSBuild Structured Log Viewer / msbuildlog.com support for the v27 record is in KirillOsenkov/MSBuildStructuredLog#955, which renders the event as a dedicated node. Verified end-to-end: a locally built server MSBuild emits v27 binlogs for the spawned / reused / short-lived / not-used cases, and both a current in-repo reader and the #955 StructuredLogger reconstruct the event with all structured fields.

Why this is not a breaking change

The event is MessageImportance.Low, exactly like the sibling Process / CommandLine / LongPaths deferred messages. It only appears in binary logs and at diagnostic verbosity; default output is unchanged and no new warning/error is introduced. A plain (non-server) build emits nothing. The binary-log format bump is additive: existing readers skip the unknown record.

Testing

  • Serialization round-trips: the binary-log writer/reader round-trip covers Spawned (short-lived) and, separately, NotUsed (with non-null Reason/ReasonCode) and Reused; a Framework.UnitTests test covers the node-packet WriteToStream/CreateFromStream path. The dedicated record kind (not Message) is asserted.
  • Deferred-message glue: a BinaryLogger_Tests case logs a DeferredBuildMessage backed by the event through BeginBuild and reads the typed event back from the binlog.
  • End-to-end MSBuildServer_Tests: spawn+reuse logging (matching PIDs), the short-lived /mt message, the not-used reason on fall-back, and absence on a plain build. Assertions resolve the exact localized strings from the MSBuild resources to stay locale-independent.
  • Repo build is clean (0 warnings).

Add low-importance deferred build messages so a binary log (and -v:diag
output) records how each build relates to MSBuild Server:

- "MSBuild Server node started for this build (process ID N)." when a
  freshly spawned server node serves its first build.
- "Reusing the running MSBuild Server node for this build (process ID N)."
  when an already-running node is reused for a subsequent build.
- "MSBuild Server was requested but not used for this build: {reason}."
  when a desired server falls back to an in-process build (server busy,
  unreachable, crashed on launch, or the invocation is incompatible).

The server process distinguishes spawn from reuse via a per-build counter;
the client records the fall-back reason. Messages are MessageImportance.Low,
so default console output is unchanged and ordinary builds that never request
the server emit nothing. Adds localized resources (+ xlf) and unit tests.

Co-authored-by: Copilot <[email protected]>
Copilot AI review requested due to automatic review settings June 24, 2026 14:24

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

Adds low-importance deferred build-log messages that record whether MSBuild Server was spawned, reused, or requested-but-not-used (with a localized reason), so this information is visible in binlogs and at -v:diag without changing default console output.

Changes:

  • Log MSBuild Server lifecycle status (spawn/reuse/not-used + PID/reason) via deferred build messages in XMake.
  • Plumb localized “not used” reasons from the client fallback path (MSBuildClientApp) into the in-proc build log.
  • Add localized resources + unit tests validating spawn/reuse/not-used messaging, and document the new diagnostics behavior.

Reviewed changes

Copilot reviewed 18 out of 18 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
src/MSBuild/XMake.cs Records server lifecycle as low-importance deferred build messages; tracks per-server build count; captures “server requested but precluded” reason for in-proc builds.
src/MSBuild/MSBuildClientApp.cs On fallback, records a localized “server not used” detail for the in-proc build log (and adds a busy-specific detail).
src/MSBuild.UnitTests/MSBuildServer_Tests.cs Adds tests asserting spawned/reused/not-used messages (and absence on plain builds) using localized resources.
src/MSBuild/Resources/Strings.resx Adds new localized string resources for lifecycle and “not used” reasons.
src/MSBuild/Resources/xlf/Strings.zh-Hant.xlf Adds new localization entries for MSBuild Server lifecycle/reason strings.
src/MSBuild/Resources/xlf/Strings.zh-Hans.xlf Adds new localization entries for MSBuild Server lifecycle/reason strings.
src/MSBuild/Resources/xlf/Strings.tr.xlf Adds new localization entries for MSBuild Server lifecycle/reason strings.
src/MSBuild/Resources/xlf/Strings.ru.xlf Adds new localization entries for MSBuild Server lifecycle/reason strings.
src/MSBuild/Resources/xlf/Strings.pt-BR.xlf Adds new localization entries for MSBuild Server lifecycle/reason strings.
src/MSBuild/Resources/xlf/Strings.pl.xlf Adds new localization entries for MSBuild Server lifecycle/reason strings.
src/MSBuild/Resources/xlf/Strings.ko.xlf Adds new localization entries for MSBuild Server lifecycle/reason strings.
src/MSBuild/Resources/xlf/Strings.ja.xlf Adds new localization entries for MSBuild Server lifecycle/reason strings.
src/MSBuild/Resources/xlf/Strings.it.xlf Adds new localization entries for MSBuild Server lifecycle/reason strings.
src/MSBuild/Resources/xlf/Strings.fr.xlf Adds new localization entries for MSBuild Server lifecycle/reason strings.
src/MSBuild/Resources/xlf/Strings.es.xlf Adds new localization entries for MSBuild Server lifecycle/reason strings.
src/MSBuild/Resources/xlf/Strings.de.xlf Adds new localization entries for MSBuild Server lifecycle/reason strings.
src/MSBuild/Resources/xlf/Strings.cs.xlf Adds new localization entries for MSBuild Server lifecycle/reason strings.
documentation/MSBuild-Server.md Documents the new per-build MSBuild Server lifecycle messages under a Diagnostics section.

Comment thread documentation/MSBuild-Server.md Resolved
@JanProvaznik

Copy link
Copy Markdown
Member Author

E2E validation attestation

Captured from real .binlog files (written with -bl, then read back via MSBuild.exe <file>.binlog -v:diag), using MSBuild.exe with MSBUILDUSESERVER=1. The messages sit in the standard build-startup message group (alongside MSBuild executable path, Command line arguments, MSBuild version, ...).

Scenario 1 — server spawned (cold start):

MSBuild executable path = "...\MSBuild.exe"
MSBuild version = "18.9.0-dev-26324-01+104b0f716"
MSBuild Server node started for this build (process ID 3852).

Scenario 2 — server reused (next build, same process):

MSBuild executable path = "...\MSBuild.exe"
MSBuild version = "18.9.0-dev-26324-01+104b0f716"
Reusing the running MSBuild Server node for this build (process ID 3852).

Note the process ID (3852) matches scenario 1, confirming the same long-lived server node was reused.

Scenario 3 — server requested but not used (-nr:false makes the invocation incompatible):

MSBuild executable path = "...\MSBuild.exe"
MSBuild version = "18.9.0-dev-26324-01+104b0f716"
MSBuild Server was requested but not used for this build: this invocation is not compatible with MSBuild Server.

Other not-used reasons (server busy with another build, crashed on launch, could not be reached) are produced by the same path with their respective localized sub-messages.

All messages are MessageImportance.Low: they appear in the binary log and at -v:diag, and are absent at default verbosity and from builds that never request the server (covered by the new unit tests).

Comment thread documentation/MSBuild-Server.md Resolved
@baronfel

Copy link
Copy Markdown
Member

@JanProvaznik design question - I'm not sure we should be creating a new bespoke Messages for this kind of data. Because the binary log format is now forward-compatible, I think we should instead create specific message types to carry the data we want, which we can then version as needed. This also helps tooling in general - today the Terminal Logger is very strict with Message payloads because they are overused for all kinds of ad-hoc data, but in an ideal world we'd be able to let all Messages flow because system/build-relevant data wasn't being communicated through them.

- Report the specific cause when a requested server is precluded locally:
  "node reuse is disabled (-nodeReuse:false or MSBUILDDISABLENODEREUSE=1)"
  and "the MSBUILDENSURESTDOUTFORTASKPROCESSES escape hatch is enabled",
  with a generic fallback for the remaining (non-surfacing) cases.
  CanRunServerBasedOnCommandLineSwitches now outputs the localized reason.
- Remove the verbose LOCALIZATION <comment> notes from the new resources.
- Update tests to assert the node-reuse-disabled reason.

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

Copy link
Copy Markdown
Member Author

Update: the "server not used" reason is now specific (and the verbose LOCALIZATION comments were dropped from the new resources). Captured from real .binlog files:

# msbuild ... -nr:false           (or MSBUILDDISABLENODEREUSE=1)
MSBuild Server was requested but not used for this build: node reuse is disabled (-nodeReuse:false or MSBUILDDISABLENODEREUSE=1).

# MSBUILDENSURESTDOUTFORTASKPROCESSES=1
MSBuild Server was requested but not used for this build: the MSBUILDENSURESTDOUTFORTASKPROCESSES escape hatch is enabled.

The client-side fall-backs remain specific too (server busy with another build / crashed on launch / could not be reached). A generic "this invocation is not compatible with MSBuild Server" only backs the remaining cases that never reach a build log anyway (-help/-version/-nodemode/binlog replay/parse error).

@JanProvaznik
JanProvaznik marked this pull request as draft June 24, 2026 16:55
JanProvaznik and others added 6 commits July 3, 2026 14:27
Addresses review feedback (dotnet#14156): instead of bespoke plain Messages, the
server lifecycle (spawn/reuse/not-used) is logged as ExtendedBuildMessageEventArgs
with ExtendedType="msbuild-server" and structured ExtendedMetadata
(kind/processId/reason).

On the wire this is still an ordinary BinaryLogRecordKind.Message record (the
extended payload rides in an optional field), so older binary-log viewers and the
-v:diag console still surface the human-readable text as a message, while new
tooling (e.g. msbuildlog.com) can recognize the type and render the structured
data. This is the recommended, versionable channel for custom event data.

- BuildManager.DeferredBuildMessage gains optional ExtendedType/ExtendedMetadata;
  LogDeferredMessages emits an ExtendedBuildMessageEventArgs via LogBuildEvent
  when they are set (plain-message path otherwise unchanged).
- XMake builds the three messages with metadata; the localized .Message text is
  unchanged so console/old-viewer output is identical.
- New serialization test asserts the wire record kind is Message and the
  round-tripped event keeps ExtendedType/metadata (forward compatibility).
- Documents the extended-event contract in MSBuild-Server.md.

Co-authored-by: Copilot <[email protected]>
Follow-up to review feedback on the extended-message approach:

- MODERATE: the "not-used" reason was only localized. Add a stable,
  non-localized "reasonCode" extended-metadata value (node-reuse-disabled,
  stdout-redirected, incompatible-invocation, command-line-parse-error,
  server-busy, server-crashed, server-state-unknown, server-unreachable) so
  tooling can branch on the cause without parsing localized text. Threaded from
  CanRunServerBasedOnCommandLineSwitches and the MSBuildClientApp fallback.
- MINOR: add DeferredExtendedBuildMessageIsWrittenToBinlogWithMetadata, which
  logs a DeferredBuildMessage(..., ExtendedType, metadata) through
  BuildManager.BeginBuild + a real BinaryLogger and reads the metadata back,
  covering the LogDeferredMessages glue end-to-end.
- Document the reasonCode values in MSBuild-Server.md.

Co-authored-by: Copilot <[email protected]>
Supersedes the extended-message approach: per review discussion, use a specific,
versionable event type recorded under its own binary-log record kind rather than
communicating server/system data through a (extended) Message. Old binlog viewers
skip the unknown record via the forward-compatible, length-prefixed framing.

- New MSBuildServerLifecycleEventArgs (Framework) with Kind/ProcessId/Reason/
  ReasonCode + WriteToStream/CreateFromStream.
- New BinaryLogRecordKind.MSBuildServerLifecycle + writer/reader; FileFormatVersion
  bumped 26 -> 27.
- LoggingEventType.MSBuildServerLifecycleEvent registered for node-packet transfer.
- BuildManager.DeferredBuildMessage can carry a pre-built BuildEventArgs (raised via
  LogBuildEvent with an Invalid context); XMake emits the typed event. The extended-
  type/metadata plumbing is removed.
- Tests: RoundtripMSBuildServerLifecycleEventArgs asserts the distinct record kind and
  field round-trip; DeferredMSBuildServerLifecycleEventIsWrittenToBinlog covers the
  deferred-message glue end-to-end.
- Docs updated (typed-event contract + graceful-skip note).

Verified: the unpatched msbuildlog.com reader (format v25) reads a v27 binlog and
skips the unknown record gracefully; MSBuild round-trips the typed event.

Co-authored-by: Copilot <[email protected]>
Resolves conflicts with dotnet#14248 ("Don't disable the MSBuild server for /mt
builds when node reuse is off"), which introduced the short-lived server
(a /mt build with node reuse off uses the server for Server GC but tears it
down after the build via ServerNodeBuildCommand.ShutdownAfterBuild).

- CanRunServerBasedOnCommandLineSwitches: integrate dotnet#14248's shutdownServerAfterBuild
  and the new node-reuse gate (nodeReuseDisqualifies = !nodeReuse && !multiThreaded)
  with my serverDisabledReason/reasonCode outputs. The node-reuse-disabled reason now
  only fires for non-/mt builds (a /mt build uses a short-lived server instead).
- MSBuildServerLifecycleEventArgs gains a ShortLived flag (serialized in the v27 record
  and node packets). XMake sets it for a spawned server that will shut down afterward,
  and logs a distinct "spawned (short-lived)" message. The flag is surfaced from
  OutOfProcServerNode.CurrentBuildShutsDownServerNode (additive; the public BuildCallback
  delegate is left unchanged to avoid an API break).
- New MSBuildServerNodeSpawnedShortLived resource (+ xlf); docs updated.
- Tests: round-trip covers ShortLived; new e2e ServerShortLivedForMultithreadedWhenNodeReuseOff.

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

Copy link
Copy Markdown
Member Author

@baronfel is this is how you'd imagine it?

@baronfel

baronfel commented Jul 9, 2026

Copy link
Copy Markdown
Member

Yeah! A lot of the comments are redundant (LLMs love to be verbose here) but this looks exactly like what I was thinking.

@JanProvaznik

Copy link
Copy Markdown
Member Author

/review

@KirillOsenkov

Copy link
Copy Markdown
Member

@baronfel are you sure we want a new structured event here? isn't it overkill to churn the format just for this info? Even though the format is forward-compatible there are still pains in the ecosystem every time it bumps (e.g. Fake etc).

How many of these events do we expect? Where will they appear in the viewers tree?

Not against this per se but I'd just want to make sure it's worth revving the format for this.

@baronfel

baronfel commented Jul 9, 2026

Copy link
Copy Markdown
Member

IMO yes - any smuggling of data in unstructured Messages is a sin. We should be very very rev happy now that we're forward-compatible.

@KirillOsenkov

Copy link
Copy Markdown
Member

okay then!

…es, tests

Applies the multi-agent maintainability review of dotnet#14156:

- API surface: make the MSBuildServerLifecycleEventArgs deserialization ctor
  and BuildManager.DeferredBuildMessage.BuildEvent internal; keep the event
  type/enum/properties public (third-party loggers depend on them). File-scoped
  namespace for the new file (per review).
- Reason/reasonCode: replace the parallel s_serverNotUsedReason/Code statics and
  the two lockstep MSBuildClientApp switches with a single ServerNotUsedReason
  (Message, Code) record produced in one place; collapse CanRunServerBasedOn-
  CommandLineSwitches reason out-params into it. Reset the reason after it is
  logged so it cannot leak into a later in-process build.
- DeferredBuildMessage: drop the dead importance parameter on the event-backed
  ctor (importance is taken from the event); set the event's Invalid context at
  construction so LogDeferredMessages no longer mutates a caller event.
- Serialization: add cross-reference "keep in sync" comments at the four
  serializer sites (node-packet WriteToStream/CreateFromStream and the binlog
  writer/reader); document that Write(int)/ReadInt32 are 7-bit encoded.
- Tests: cover NotUsed (non-null Reason/ReasonCode) and Reused round-trips in the
  binlog serializer, and add a Framework node-packet WriteToStream/CreateFromStream
  round-trip (the previously untested IPC path).
- Rename the two inconsistent resources to MSBuildServerReason*; fix the
  self-contradictory MSBuild-Server.md diagnostics wording ("requested").
- Regenerate xlf.

Verified end-to-end: a freshly built server MSBuild emits v27 binlogs for the
spawned/reused/short-lived/not-used cases, and the msbuildlog StructuredLogger
(PR KirillOsenkov/MSBuildStructuredLog#955) reads them and reconstructs the
MSBuildServerNode with Kind/ShortLived/ProcessId/Reason/ReasonCode.

Co-authored-by: Copilot <[email protected]>
Copilot-Session: f723b717-4837-4d3b-bfb1-6929d7d3b94a
- XMake: extract the inline server-lifecycle block from the large
  GetMessagesToLogInBuildLoggers into TryCreateServerLifecycleEvent(), removing
  the duplicated event construction (shared local factory sets the Invalid
  context) and replacing the nested ternary with a tuple switch.
- Trim comments that narrated implementation/review history down to forward-
  looking notes on non-obvious behavior (masking, short-lived status, the
  Invalid context, clearing the not-used reason, the counter's thread-safety).

Co-authored-by: Copilot <[email protected]>
Copilot-Session: f723b717-4837-4d3b-bfb1-6929d7d3b94a
@JanProvaznik
JanProvaznik requested a review from baronfel July 13, 2026 19:07
KirillOsenkov pushed a commit to KirillOsenkov/MSBuildStructuredLog that referenced this pull request Jul 13, 2026
Companion to dotnet/msbuild#14156, which records how each build relates to the
MSBuild Server node as a dedicated MSBuildServerLifecycleEventArgs under its own
BinaryLogRecordKind (binlog format v27).

- Read the new MSBuildServerLifecycle record and render it as a dedicated
  MSBuildServerNode under a "MSBuild Server" folder, with a distinct icon
  (WPF Generic.xaml + Avalonia). The node exposes Kind (Spawned/Reused/NotUsed),
  ShortLived, ProcessId, Reason and ReasonCode.
- Also read the LoggersRegistered record (binlog format v26) so v26/v27 logs no
  longer report "Skipped some data unknown to this version of Viewer" for it.

Co-authored-by: Copilot <[email protected]>
@JanProvaznik
JanProvaznik merged commit aa5bbaf into dotnet:main Jul 14, 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.

4 participants