From c37016cf6dcaf2813b46b5f4a4b1b8ad3231c2df Mon Sep 17 00:00:00 2001 From: Noah Gilson Date: Fri, 30 Oct 2026 14:22:05 -0700 Subject: [PATCH] Do not delay exit waiting for telemetry Resolves https://github.com/dotnet/sdk/issues/56815#issuecomment-6483765498 The initial fix was made in INTERNAL on dotnet/dotnet 11.0.100 for GA. https://login.microsoftonline.com/72f988bf-86f1-41af-91ab-2d7cd011db47/oauth2/authorize?client_id=499b84ac-1321-427f-aa17-267ca6975798&site_id=501454&response_mode=form_post&response_type=code+id_token&redirect_uri=https%3A%2F%2Fspsprodcus3.vssps.visualstudio.com%2F_signedin&nonce=6e955c3b-2d8e-4b63-a9e6-27ed4d3332c6&state=realm%3Ddev.azure.com%26reply_to%3Dhttps%253A%252F%252Fdev.azure.com%252Fdnceng%252Finternal%252F_git%252Fdotnet-dotnet%252Fpullrequest%252F67911%26ht%3D2%26protocol%3Dentra.web.3%26hid%3Db55de4ed-4b5a-4215-a8e4-0a0a5f71e7d8%26nonce%3D6e955c3b-2d8e-4b63-a9e6-27ed4d3332c6%26lltid%3D221510f4-2b26-40d5-988a-08b05ea44407&resource=499b84ac-1321-427f-aa17-267ca6975798&cid=6e955c3b-2d8e-4b63-a9e6-27ed4d3332c6&wsucxt=1&instance_aware=true Scenario Pre-patch Post-patch --version, default NativeAOT path 2.11 s 0.21 s No-op build, managed CLI + MSBuild logger 8.76 s 4.52 s Build telemetry overhead versus opt-out 5.05 s 0.91 s The tracerProvider often get blocked on pending HTTP requests from recent Azure Monitor Exporter changes. It is supposed to be a minimal shutdown delay. Pending requests often take 3-5 seconds to complete, which results in extreme exit delay. The MS Build logger telemetry client calls ForceFlush, which is why the additional change is needed. The defaultTimeout remains as 5 seconds, because it informs network timeout for HTTP requests in options.Retry.NetworkTimeout - since telemetry POST completion time is often around 3-5 seconds, setting this lower would drop telemetry. -- The DIFFERENCE between this PR and what went into GA: - Fixed a test only in dotnet/sdk - I went from 10 to 100 ms because 10ms may not give enough time to write blob storage on slower disks for short lived commands When merging, prefer these changes. --- documentation/project-docs/telemetry.md | 10 +++--- src/Cli/dotnet/Telemetry/TelemetryClient.cs | 12 +++++-- .../AzureExporterLifecycleTests.cs | 32 +++++++++++++++++++ .../TelemetryTests/TelemetryClientTests.cs | 2 +- 4 files changed, 48 insertions(+), 8 deletions(-) diff --git a/documentation/project-docs/telemetry.md b/documentation/project-docs/telemetry.md index e44a855ce010..0ab7216fa8bc 100644 --- a/documentation/project-docs/telemetry.md +++ b/documentation/project-docs/telemetry.md @@ -90,8 +90,10 @@ and delivery. [TelemetryClient](../../src/Cli/dotnet/Telemetry/TelemetryClient.c use a separate 300-ms trace allowance in each runtime; there is no cross-runtime deadline coordination. Normal exports before shutdown remain network-first; this is not synchronous persistence of every ended span, and abrupt termination can lose queued spans. An upload already in flight - can still delay shutdown. Successful local shutdown waits for the batch processor to finish rather than - applying the old 10-ms timeout to persistence. Failed-command persistence is subject to the 300-ms timeout. + can still delay shutdown. Successful local shutdown gives the trace batch processor 100 ms to finalize + persistence; the zero drain budget prevents waiting for the subsequent upload. This is long enough for a cold + exporter to complete its atomic file write without reintroducing an unbounded exit delay. Failed-command + persistence is subject to the 300-ms timeout. 2. **Subsequent invocations.** Azure schedules an eager background drain after a 50-ms startup delay; actual start time also depends on thread scheduling and storage work. The two-minute periodic retry timer remains. Accepted payloads are deleted; retryable failures remain for later attempts. Storage partitioning, retention, @@ -113,8 +115,8 @@ and delivery. [TelemetryClient](../../src/Cli/dotnet/Telemetry/TelemetryClient.c be persisted, and a timeout can leave telemetry undelivered. 4. **Persistent MSBuild hosts.** A logger finishes a build request with nonterminal `ForceFlush`, allowing the same provider to handle later builds. Locally the SDK enables - `Azure.Monitor.OpenTelemetry.Exporter.PersistOnForceFlush`; process exit uses `Shutdown`. CI uses a bounded - network-first flush. A force-flush result is not an ingestion acknowledgment. + `Azure.Monitor.OpenTelemetry.Exporter.PersistOnForceFlush` and gives trace persistence 100 ms; process exit uses + `Shutdown`. CI uses a bounded network-first flush. A force-flush result is not an ingestion acknowledgment. These Azure settings are process-wide. OTLP-enabled invocations retain bounded provider shutdown, and the trace and metric providers share the configured wait budget. This bounds provider waits, not all process-exit work. Azure's diff --git a/src/Cli/dotnet/Telemetry/TelemetryClient.cs b/src/Cli/dotnet/Telemetry/TelemetryClient.cs index 3faa17d8f0a4..32f80710a622 100644 --- a/src/Cli/dotnet/Telemetry/TelemetryClient.cs +++ b/src/Cli/dotnet/Telemetry/TelemetryClient.cs @@ -19,6 +19,8 @@ namespace Microsoft.DotNet.Cli.Telemetry; public class TelemetryClient : ITelemetryClient { + private const int LocalTracePersistenceTimeoutMilliseconds = 100; + private static FrozenDictionary s_commonProperties = []; private Task? _trackEventTask; @@ -280,17 +282,21 @@ internal static void FlushProviders(int exitCode) } else { - s_tracerProvider?.Shutdown(); + // This timeout includes batch serialization and the atomic storage write. Ten milliseconds can + // interrupt the write before its temporary file is finalized, leaving nothing a later run can drain. + s_tracerProvider?.Shutdown(LocalTracePersistenceTimeoutMilliseconds); s_metricsProvider?.Shutdown(timeoutMilliseconds: 10); } } internal static void ForceFlushProviders() { - int timeout = s_isCIEnvironment || s_enableOtlpExporter ? s_shutdownTimeoutMs : Timeout.Infinite; + int timeout = s_isCIEnvironment || s_enableOtlpExporter + ? s_shutdownTimeoutMs + : LocalTracePersistenceTimeoutMilliseconds; long started = Stopwatch.GetTimestamp(); s_tracerProvider?.ForceFlush(timeout); - int remaining = timeout == Timeout.Infinite ? 10 : Math.Max(0, timeout - (int)Stopwatch.GetElapsedTime(started).TotalMilliseconds); + int remaining = Math.Max(0, timeout - (int)Stopwatch.GetElapsedTime(started).TotalMilliseconds); s_metricsProvider?.ForceFlush(remaining); } diff --git a/test/Microsoft.DotNet.Cli.Telemetry.Tests/AzureExporterLifecycleTests.cs b/test/Microsoft.DotNet.Cli.Telemetry.Tests/AzureExporterLifecycleTests.cs index e2cdd9c7e554..4ac4a4b7f2c9 100644 --- a/test/Microsoft.DotNet.Cli.Telemetry.Tests/AzureExporterLifecycleTests.cs +++ b/test/Microsoft.DotNet.Cli.Telemetry.Tests/AzureExporterLifecycleTests.cs @@ -41,6 +41,38 @@ public void LocalShutdownPersistsQueuedActivitiesBeforeReturning(int activityCou .Should().BeEquivalentTo(Enumerable.Range(0, activityCount).Select(index => $"session-{index}")); } + [TestMethod] + public void LocalShutdownPersistsQueuedActivitiesWithinCliBudget() + { + using var settings = new ExporterSettingsScope(ci: false); + using var scope = new AzureExporterTestScope(); + using var handler = new RecordingHandler(); + using var provider = scope.CreateProvider(handler); + using var activity = scope.Emit("cli-budget"); + + provider.Shutdown(100).Should().BeTrue(); + + handler.Payloads.Should().BeEmpty(); + scope.StoredFiles().Select(File.ReadAllText) + .Should().Contain(payload => payload.Contains("cli-budget", StringComparison.Ordinal)); + } + + [TestMethod] + public void LocalForceFlushPersistsQueuedActivitiesWithinCliBudget() + { + using var settings = new ExporterSettingsScope(ci: false); + using var scope = new AzureExporterTestScope(); + using var handler = new RecordingHandler(); + using var provider = scope.CreateProvider(handler); + using var activity = scope.Emit("cli-force-flush-budget"); + + provider.ForceFlush(100).Should().BeTrue(); + + handler.Payloads.Should().BeEmpty(); + scope.StoredFiles().Select(File.ReadAllText) + .Should().Contain(payload => payload.Contains("cli-force-flush-budget", StringComparison.Ordinal)); + } + [TestMethod] public async Task LocalShutdownDoesNotWaitForItsBackgroundUpload() { diff --git a/test/dotnet.Tests/TelemetryTests/TelemetryClientTests.cs b/test/dotnet.Tests/TelemetryTests/TelemetryClientTests.cs index fe4ec0be9db5..cdaa9885a725 100644 --- a/test/dotnet.Tests/TelemetryTests/TelemetryClientTests.cs +++ b/test/dotnet.Tests/TelemetryTests/TelemetryClientTests.cs @@ -46,7 +46,7 @@ public void ShutdownUsesExitCodeAndRestoresDrainSetting(int exitCode, bool throw AppContext.SetData(drainBudgetName, 17); Action shutdown = () => TelemetryClient.FlushProviders(exitCode); shutdown.Should().NotThrow(); - processor.Timeout.Should().Be(boundedExport ? boundedTimeout : exitCode == 0 ? Timeout.Infinite : 300); + processor.Timeout.Should().Be(boundedExport ? boundedTimeout : exitCode == 0 ? 100 : 300); processor.DrainBudget.Should().Be(boundedExport || exitCode == 0 ? 17 : 300); AppContext.GetData(drainBudgetName).Should().Be(17); }