Skip to content

Make telemetry initialization and disposal best-effort so it can never fail a build - #14554

Merged
AlesProkop merged 5 commits into
mainfrom
copilot/nre-crash-fix
Aug 18, 2026
Merged

AlesProkop merged 5 commits into
mainfrom
copilot/nre-crash-fix

Conversation

Copilot AI commented Jul 28, 2026 •

Copy link
Copy Markdown
Contributor

Context

MSBuild 18.8.2 on .NET Framework fails builds with MSBUILD : error MSB1025 when a NullReferenceException escapes VsTelemetryInitializer.Dispose(). Two independent defects combine here:

  1. TelemetryManager swallowed the wrong exceptions. Both init and dispose used a filtered catch (FileNotFoundException/FileLoadException/TypeLoadException), which doesn't match an NRE thrown from inside the VS telemetry stack. The exception propagated up through BuildManager.Dispose() to MSBuildApp.Execute and failed the build.

  2. BuildManager disposed a session it doesn't own. The telemetry session is process-wide, created by the entry point (XMake.Main) or the host (VS). MSBuildApp.BuildProject's finally disposes BuildManager.DefaultBuildManager, so the session was torn down while the process was still running — leaving CrashTelemetryRecorder.PostFaultEvent posting to a disposed session, which is the second stack trace in the report.

Telemetry is best-effort infrastructure; no failure inside it should be observable by a build.

Changes Made

src/Framework/Telemetry/TelemetryManager.cs

  • TryInitializeTelemetry and Dispose now use a catch-all instead of a type-filtered catch. Comments record which exceptions are expected and why the filter isn't sufficient.
  • s_disposed is set before the teardown work, and DefaultActivitySource is cleared, so nothing can emit through a source backed by a disposed session.
  • VsTelemetryInitializer.Initialize no longer dereferences the session unconditionally. CreateAndGetDefaultSession can return null (e.g. telemetry disabled machine-wide), so UseVsIsOptedIn()/Start() and ownership are only taken when a session actually exists:
session = TelemetryService.CreateAndGetDefaultSession(CollectorApiKey);

if (session is not null)
{
    session.UseVsIsOptedIn();
    session.Start();
    s_ownsSession = true;
}
  • VsTelemetryInitializer.Dispose snapshots and clears the static state before disposing, so a throwing Dispose() can't leave a stale session behind and a repeat call is a no-op.
  • Dropped using System; / using System.IO;, now unused (IDE0005 is warning-as-error in official builds).

src/Build/BackEnd/BuildManager/BuildManager.cs

  • Removed TelemetryManager.Instance.Dispose() from Dispose(bool). This is a no-op change for hosts, which initialize with isStandalone: false and therefore never owned the session; XMake.Main and MSBuild.Coordinator/Program.cs already pair their own Initialize/Dispose, and on .NET Core Dispose() has no body.

Testing

  • New src/Framework.UnitTests/TelemetryManager_Tests.cs: disposal without initialization doesn't throw, disposal is idempotent, ResetForTest clears state.
  • New BuildManagerDisposeDoesNotDisposeProcessWideTelemetry in src/Build.UnitTests/Telemetry/Telemetry_Tests.cs, verified to fail when the removed TelemetryManager.Instance.Dispose() call is restored.

Notes

This is defensive. The underlying reason TelemetrySession.Dispose() NREs in the reporter's environment (Windows Server 2022, VS 2026 + VS 2022 side-by-side, VS_TELEMETRY_OPT_OUT=1) is in the closed-source VS Telemetry SDK and is not addressed here — but no failure mode inside it can fail a build anymore.

Worth a look during review: BuildManager.EndBuildTelemetry() calls StartActivity without a guard. Left alone as out of scope, but it's adjacent.

Fixes the MSB1025 build failure caused by a NullReferenceException escaping
VsTelemetryInitializer.Dispose(), and stops BuildManager.Dispose() from tearing
down the process-wide telemetry session it does not own.

Co-authored-by: AlesProkop <[email protected]>
Copilot AI changed the title [WIP] Fix unhandled exception in VsTelemetryInitializer.Dispose Make telemetry initialization and disposal best-effort so it can never fail a build Jul 28, 2026
Copilot AI requested a review from AlesProkop July 28, 2026 14:02
AlesProkop and others added 2 commits August 14, 2026 13:00
Address three review findings on the telemetry best-effort change.

Do not swallow critical exceptions. Both the initialization and disposal
handlers used a bare catch, which also absorbed OutOfMemoryException,
AccessViolationException and InternalErrorException. MSBuild classifies
those as critical in ExceptionHandling.IsCriticalException, so the build
could report success while the process was already unrecoverable. Both
handlers now filter on !IsCriticalException; NullReferenceException is
deliberately not critical, so the MSB1025 fix is unaffected.

Do not leak a partially initialized session. Ownership was recorded only
after UseVsIsOptedIn() and Start() had both succeeded, so a session that
was created and then failed to start was never tracked and never
disposed - it stayed referenced by the telemetry SDK for the lifetime of
the process. Ownership is now recorded immediately after creation, so
shutdown cleans up regardless of where initialization failed.

Cover the reported crash. The existing tests never disposed an owned
TelemetrySession, so they passed against the old type-filtered catch and
could not detect a regression of the reported failure. The new net472
test poisons the session with an uninitialized instance whose Dispose()
throws NullReferenceException, then asserts that disposal is contained
and that session and ownership state are cleared. Verified to fail with
the previous filter, reproducing the exact NullReferenceException from
the issue, while the other telemetry tests still passed.

Co-authored-by: Copilot <[email protected]>
Copilot-Session: fbd1a9a9-a7e3-4f3a-ae4c-cfe365e7addf
@AlesProkop
AlesProkop marked this pull request as ready for review August 14, 2026 12:04
Copilot AI lite review requested due to automatic review settings August 14, 2026 12:04

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

This PR hardens MSBuild’s telemetry lifecycle so that failures inside the VS telemetry stack (especially on .NET Framework) cannot surface as build failures, and ensures process-wide telemetry isn’t torn down by BuildManager instances that don’t own it.

Changes:

  • Make telemetry initialization and disposal best-effort by swallowing all non-critical exceptions and clearing activity state before teardown.
  • Fix VS telemetry session initialization to handle CreateAndGetDefaultSession(...) returning null, and make disposal idempotent by clearing static state before calling into the SDK.
  • Stop BuildManager.Dispose() from disposing the process-wide telemetry manager; add unit tests covering idempotent/best-effort disposal and ownership boundaries.

Reviewed changes

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

File Description
src/Framework/Telemetry/TelemetryManager.cs Catch-all best-effort init/dispose; clear activity source and make VS session init/dispose safer.
src/Framework.UnitTests/TelemetryManager_Tests.cs New unit tests validating best-effort disposal, idempotency, and reset behavior.
src/Build/BackEnd/BuildManager/BuildManager.cs Remove telemetry teardown from BuildManager disposal (ownership fix).
src/Build.UnitTests/Telemetry/Telemetry_Tests.cs New test ensuring disposing BuildManager does not dispose process-wide telemetry.

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

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

Looks reasonable but raises the specter of "now something is failing which has killed 100% of our telemetry". What are we doing to keep track of that--should we add a release task at build promotion time to validate that we see telemetry from the prerel version?

@AlesProkop
AlesProkop merged commit 9145389 into main Aug 18, 2026
10 checks passed
@AlesProkop
AlesProkop deleted the copilot/nre-crash-fix branch August 18, 2026 06:33
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.

[Unhandled Exception]: VsTelemetryInitializer.Dispose(): System.NullReferenceException: Object reference not set to an instance of an object.

4 participants