From 53b0b9bd9df4f856498e18dec978ca86c9753cfc Mon Sep 17 00:00:00 2001 From: Jan Krivanek Date: Wed, 18 Nov 2026 11:30:36 +0100 Subject: [PATCH 1/3] Add copilot telemetry cross-correlation id --- docs/decisions/llm-context-telemetry.md | 98 ++++++++++++ .../AppInsightsProvider.cs | 55 ++++++- .../PACKAGE.md | 18 +++ .../InternalAPI/InternalAPI.Unshipped.txt | 2 + .../Telemetry/TelemetryProperties.cs | 2 + .../TelemetryDisabledTests.cs | 7 +- .../TelemetryTests.cs | 69 ++++++++- .../AppInsightsProviderTests.cs | 141 ++++++++++++++++++ .../Telemetry/TelemetryManagerTests.cs | 31 ++++ .../WellKnownEnvironmentVariables.cs | 1 + 10 files changed, 417 insertions(+), 7 deletions(-) create mode 100644 docs/decisions/llm-context-telemetry.md diff --git a/docs/decisions/llm-context-telemetry.md b/docs/decisions/llm-context-telemetry.md new file mode 100644 index 00000000000..4bdfdda5fac --- /dev/null +++ b/docs/decisions/llm-context-telemetry.md @@ -0,0 +1,98 @@ +# LLM context telemetry: research and decisions + +## Contract + +Add two common properties to the optional Microsoft.Testing.Extensions.Telemetry +usage collector: + +| Property | Value | +| --- | --- | +| `is llm` | Existing `LLMEnvironmentDetector` result as `true`/`false`; a heuristic, not proof of human/agent authorship. | +| `copilot agent session id` | Normalized `COPILOT_AGENT_SESSION_ID`, or `not_present` when absent/empty. | + +Match the SDK's `CopilotAgentSessionId`: preserve canonical UUID versions 1-8 +with RFC variant, plus the nil UUID, including original casing. Hash other +values as lowercase SHA-256 of their original UTF-8 bytes, without trimming. +A literal `not_present` input is hashed. A missing telemetry property means +collection support is unknown. + +The signals are independent. Snapshot them before queueing each event, without +mutating caller dictionaries or accepting overrides. Preserve existing opt-outs, +session/reporter IDs, runtime restrictions, cancellation, and transport. +No new public API or dependency; no changes to console defaults, OpenTelemetry, +or JSON-RPC `ServerTelemetry` forwarding, which operates independently of usage +telemetry opt-out. + +## Research and decision + +[dotnet/sdk#57106](https://github.com/dotnet/sdk/pull/57106) adds cross-product +Copilot correlation. Its pinned +[normalization implementation](https://github.com/dotnet/sdk/blob/a436089fa916892516a2d1d4ed964c96d07380fa/src/Cli/dotnet/Telemetry/TelemetryCommonProperties.cs) +was checked against the referenced Copilot runtime source on 2026-11-18. + +Reuse TestFx's detector, previously used only for console defaults, and collect +the fields in `AppInsightsProvider.LogEventAsync`. Construction-time capture was +rejected because queued events could receive stale context. Keep normalization +private: TestFx's existing hasher uppercases inputs and would break correlation; +`Guid.TryParse` accepts UUID forms outside Copilot's contract. Collecting agent +names/raw marker values or adding OpenTelemetry tags is outside scope. + +## Test-value evidence + +Validated on 2026-11-18 with SDK `12.0.100-alpha.1.26562.108`, Debug builds. +Base: `28c534d9fd47856682e8d1c14f54a10a1b4a08bf`. +Behavioral `src`/`test` patch SHA-256: +`51bb4966e403e758b6f4c331080004821ae2c87cfde414f892c915dd0f906044`. +This document is excluded from that patch identity. + +| Contract | Tests | +| --- | --- | +| Detection and correlation | `LogEvent_ReportsLLMContext` (6 cases), `LogEvent_NormalizesCopilotSessionId` (17 cases: UUIDs, absence, casing, whitespace, malformed IDs, UTF-8). | +| Queueing and ownership | `LogEvent_SnapshotsContextBeforeQueueingWithoutMutatingCallerProperties`: three distinguishable events, changing context, overrides, and dictionary reuse. | +| Opt-outs | `TelemetryManager_WhenDisabled_DoesNotCreateContextCollector`, plus packaged tests with the real provider registered. | +| Shipping boundary | `Telemetry_Context_IsIncludedInEveryUsageEvent`: four contexts per runtime; checks each event's fields, identity, and unchanged platform session ID. | + +| Selection | Passed / executed | Result | +| --- | --- | --- | +| Provider tests: .NET 10 / 11 / Framework 4.6.2 / 4.7.2 | 57 / 57, 57 / 57, 54 / 54, 54 / 54 | Exit 0 | +| Manager/detector tests: .NET 10 / 11 / Framework 4.6.2 | 30 / 30 on each | Exit 0 | +| Packaged acceptance: .NET 10 / 11 / Framework 4.6.2 | 15 / 15 | Exit 0 | + +Total: **312 unit and 15 acceptance cases passed**, no failures/skips. +TRX/JUnit/CTRF counts were reconciled; method-level parallelization was preserved. +The acceptance host runs on .NET 12. Its custom-framework children intentionally +exit 8 (`ZeroTests`), exercising startup/shutdown telemetry rather than counting +zero-test runs as regression tests. + +**Executed counterfactual:** removing both fields before enqueueing, with the +same tests retained, produced 24 intended assertion failures and 33 passes on +.NET 10 (exit 2). Restoring the provider and forcing a rebuild recovered to +57 passes (exit 0). This is feature-removal evidence, not a pristine-base run. +Mutation patch SHA-256: +`15d8df8a7812dc2fd699e6aa4e5c294e0666b50a17280a38ba111a7235058d20`. + +Both changed `3.0.0-dev` packages packed successfully. All six executed consumer +DLLs matched their NuGet payload hashes, using `netstandard2.0` assets on +.NET Framework. Isolated restores and actual loaded assembly paths were checked. +The packaged scenarios verified 24 usage events across 12 context-specific launches. + +## Validation notes and remaining work + +The default build could not find Visual Studio 18.12; supported +`-msbuildEngine dotnet` builds passed instead. Fixture package prerequisites were +packed separately. Tests use an explicit diagnostic directory because agent-aware +banner suppression hides the diagnostic-file announcement. A stale comparison +DLL after copying older source was identified by hashes and corrected with +`-t:Rebuild`; setup/build failures were not counted as behavioral evidence. + +Full commands, reports, patches, binlogs, and DLL hashes remain in session +artifacts, including `run-unit-validation.ps1` and +`consumer-provenance-complete\provenance.json`. The temporary comparison export +was removed. Fixture-only MSTest packages are retained under `fixture-packages`; +copy them to `artifacts\packages\Debug\Shipping` before a local acceptance rerun +without a full pack. Final `.\eng\verify-nupkgs.ps1 -configuration Debug` passed. + +This is nonvisual metadata; backend ingestion/dashboard queries were not verified. +Before release, update the +[public telemetry documentation](https://learn.microsoft.com/dotnet/core/testing/microsoft-testing-platform-telemetry) +and complete any required telemetry governance review. diff --git a/src/Platform/Microsoft.Testing.Extensions.Telemetry/AppInsightsProvider.cs b/src/Platform/Microsoft.Testing.Extensions.Telemetry/AppInsightsProvider.cs index 9491dc3eac5..1b072224bfa 100644 --- a/src/Platform/Microsoft.Testing.Extensions.Telemetry/AppInsightsProvider.cs +++ b/src/Platform/Microsoft.Testing.Extensions.Telemetry/AppInsightsProvider.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using System.Security.Cryptography; + #if NETCOREAPP using System.Threading.Channels; #endif @@ -60,6 +62,7 @@ internal sealed partial class AppInsightsProvider : TelemetryProperties.VersionPropertyName, TelemetryProperties.ReporterIdPropertyName, TelemetryProperties.SessionId, + TelemetryProperties.CopilotAgentSessionIdPropertyName, TelemetryProperties.HostProperties.TestingPlatformVersionPropertyName, TelemetryProperties.HostProperties.FrameworkDescriptionPropertyName, TelemetryProperties.HostProperties.OSDescriptionPropertyName, @@ -310,6 +313,40 @@ private static double ToUnixTimeNanoseconds(DateTimeOffset value) => // We multiply by 100 because Ticks are 100 ns, and we want to report ns. (value.UtcTicks - 621355968000000000L) * 100; + private static string NormalizeCopilotAgentSessionId(string? sessionId) + { + if (RoslynString.IsNullOrEmpty(sessionId)) + { + return "not_present"; + } + + if (GetCopilotSessionUuidPattern().IsMatch(sessionId)) + { + return sessionId; + } + + // Unlike HashWithNormalizedCasing, Copilot hashes the original UTF-8 bytes. + using var sha256 = SHA256.Create(); + byte[] hash = sha256.ComputeHash(Encoding.UTF8.GetBytes(sessionId)); +#if NET9_0_OR_GREATER + return Convert.ToHexStringLower(hash); +#else + return BitConverter.ToString(hash).Replace("-", string.Empty).ToLowerInvariant(); +#endif + } + + // Match the SDK/Copilot contract: canonical UUID versions 1-8 with RFC variant, or nil. +#if NET7_0_OR_GREATER + [GeneratedRegex(@"\A(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)\z", + RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)] + private static partial Regex GetCopilotSessionUuidPattern(); +#else + private static Regex GetCopilotSessionUuidPattern() + => new( + @"\A(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)\z", + RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); +#endif + #if DEBUG private static string AssertHashed(string key, string value) { @@ -365,15 +402,25 @@ Task LogEventAsync(string eventName, IDictionary paramsMap, Canc #endif } -#if NETCOREAPP - await _payloads.Writer.WriteAsync((eventName, paramsMap), cancellationToken).ConfigureAwait(ContinueOnCapturedContext); -#else +#if !NETCOREAPP if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled(cancellationToken); } +#endif + + // Capture context before queueing; the environment and caller's dictionary can change. + var payload = new Dictionary(paramsMap) + { + [TelemetryProperties.IsLLMPropertyName] = new LLMEnvironmentDetector(_environment).IsLLMEnvironment(), + [TelemetryProperties.CopilotAgentSessionIdPropertyName] = + NormalizeCopilotAgentSessionId(_environment.GetEnvironmentVariable("COPILOT_AGENT_SESSION_ID")), + }; - _payloads.Write((eventName, paramsMap)); +#if NETCOREAPP + await _payloads.Writer.WriteAsync((eventName, payload), cancellationToken).ConfigureAwait(ContinueOnCapturedContext); +#else + _payloads.Write((eventName, payload)); return Task.CompletedTask; #endif } diff --git a/src/Platform/Microsoft.Testing.Extensions.Telemetry/PACKAGE.md b/src/Platform/Microsoft.Testing.Extensions.Telemetry/PACKAGE.md index c9016f78743..b2df77341e7 100644 --- a/src/Platform/Microsoft.Testing.Extensions.Telemetry/PACKAGE.md +++ b/src/Platform/Microsoft.Testing.Extensions.Telemetry/PACKAGE.md @@ -20,6 +20,24 @@ This package extends Microsoft.Testing.Platform with: This package is an optional, opt-in extension. To enable telemetry when using Microsoft.Testing.Platform (including when running tests with [MSTest](https://www.nuget.org/packages/MSTest)), you must explicitly reference the `Microsoft.Testing.Extensions.Telemetry` package from your test project or from your own test framework or tooling package. +## AI-agent context + +When telemetry is enabled, every usage event includes: + +- `is llm`: `true` when the platform's existing environment detector recognizes + an AI agent, otherwise `false`. Detection is heuristic; `false` does not prove + a human invocation. Only the boolean is collected, not the marker values. +- `copilot agent session id`: the nonempty `COPILOT_AGENT_SESSION_ID`, normalized + to match the .NET SDK's `CopilotAgentSessionId` and Copilot telemetry. + Canonical UUIDs (versions 1-8 with RFC variant, or the nil UUID) are preserved + exactly. Other values become lowercase SHA-256 of their original UTF-8 bytes, + without trimming or case normalization. Missing or empty values produce + `not_present`; a missing telemetry property means collection support is unknown. + +These are independent signals, captured for each event before asynchronous +dispatch. Existing platform session IDs and telemetry opt-outs are unchanged. +This does not add fields to application-configured OpenTelemetry traces. + ## Documentation For this extension, see . diff --git a/src/Platform/Microsoft.Testing.Platform/InternalAPI/InternalAPI.Unshipped.txt b/src/Platform/Microsoft.Testing.Platform/InternalAPI/InternalAPI.Unshipped.txt index 2f09a4aab2e..71e56af29ad 100644 --- a/src/Platform/Microsoft.Testing.Platform/InternalAPI/InternalAPI.Unshipped.txt +++ b/src/Platform/Microsoft.Testing.Platform/InternalAPI/InternalAPI.Unshipped.txt @@ -1,4 +1,6 @@ #nullable enable +const Microsoft.Testing.Platform.Telemetry.TelemetryProperties.IsLLMPropertyName = "is llm" -> string! +const Microsoft.Testing.Platform.Telemetry.TelemetryProperties.CopilotAgentSessionIdPropertyName = "copilot agent session id" -> string! Microsoft.Testing.Platform.TestHostControllers.TestHostControllersManager.AddDataConsumerWhenControllerStarts(Microsoft.Testing.Platform.Extensions.CompositeExtensionFactory! compositeServiceFactory) -> void Microsoft.Testing.Platform.TestHostControllers.TestHostControllersManager.AddEnvironmentVariableProviderWhenControllerStarts(System.Func! factory) -> void *REMOVED*Microsoft.Testing.Platform.TestHostControllers.TestHostProcessInformation.HasExitedGracefully.get -> bool diff --git a/src/Platform/Microsoft.Testing.Platform/Telemetry/TelemetryProperties.cs b/src/Platform/Microsoft.Testing.Platform/Telemetry/TelemetryProperties.cs index 523040b09bd..359959de7e2 100644 --- a/src/Platform/Microsoft.Testing.Platform/Telemetry/TelemetryProperties.cs +++ b/src/Platform/Microsoft.Testing.Platform/Telemetry/TelemetryProperties.cs @@ -9,6 +9,8 @@ internal static class TelemetryProperties public const string SessionId = "session id"; public const string ReporterIdPropertyName = "reporter id"; public const string IsCIPropertyName = "is ci"; + public const string IsLLMPropertyName = "is llm"; + public const string CopilotAgentSessionIdPropertyName = "copilot agent session id"; public const string VersionValue = "20"; diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/TelemetryDisabledTests.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/TelemetryDisabledTests.cs index f4707cbb6c8..db115d81958 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/TelemetryDisabledTests.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/TelemetryDisabledTests.cs @@ -29,7 +29,9 @@ public async Task Telemetry_WhenEnableTelemetryIsFalse_WithTestApplicationOption .+ Microsoft.Testing.Platform.Telemetry.TelemetryManager DEBUG DOTNET_CLI_TELEMETRY_OPTOUT environment variable: '' .+ Microsoft.Testing.Platform.Telemetry.TelemetryManager DEBUG Telemetry is 'DISABLED' """; - await AssertDiagnosticReportAsync(testHostResult, diagPathPattern, diagContentsPattern); + string report = await AssertDiagnosticReportAsync(testHostResult, diagPathPattern, diagContentsPattern); + string content = await File.ReadAllTextAsync(report, TestContext.CancellationToken); + Assert.DoesNotContain("Send telemetry event:", content); } private static async Task AssertDiagnosticReportAsync(TestHostResult testHostResult, string diagPathPattern, string diagContentsPattern, string level = "Trace", string flushType = "async") @@ -73,10 +75,12 @@ public sealed class TestAssetFixture() : TestAssetFixtureBase() + #file Program.cs +using Microsoft.Testing.Extensions; using Microsoft.Testing.Platform.Builder; using Microsoft.Testing.Platform.Capabilities.TestFramework; using Microsoft.Testing.Platform.Extensions.TestFramework; @@ -86,6 +90,7 @@ public class Program public static async Task Main(string[] args) { ITestApplicationBuilder builder = await TestApplication.CreateBuilderAsync(args$TelemetryArg$); + builder.AddAppInsightsTelemetryProvider(); builder.RegisterTestFramework(_ => new TestFrameworkCapabilities(), (_,__) => new DummyTestFramework()); using ITestApplication app = await builder.BuildAsync(); return await app.RunAsync(); diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/TelemetryTests.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/TelemetryTests.cs index 4a2acbceb2b..96191d1aa55 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/TelemetryTests.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/TelemetryTests.cs @@ -10,6 +10,57 @@ public class TelemetryTests : AcceptanceTestBase + { + ["AI_AGENT"] = context.Agent, + ["COPILOT_AGENT_SESSION_ID"] = context.SessionId, + ["TESTINGPLATFORM_APPINSIGHTS_SESSIONID"] = "11111111-2222-4333-8444-555555555555", + }, + disableTelemetry: false, + cancellationToken: TestContext.CancellationToken); + + result.AssertExitCodeIs(ExitCode.ZeroTests); + result.AssertOutputContains($"TelemetryAssemblyPath: {Path.Combine(testHost.DirectoryName, "Microsoft.Testing.Extensions.Telemetry.dll")}"); + result.AssertOutputContains($"PlatformAssemblyPath: {Path.Combine(testHost.DirectoryName, "Microsoft.Testing.Platform.dll")}"); + string[] reports = Directory.GetFiles(diagnostics.Path, "*.diag"); + Assert.HasCount(1, reports); + TestContext.WriteLine($"Telemetry diagnostics: {reports[0]}"); + string content = await File.ReadAllTextAsync(reports[0], TestContext.CancellationToken); + MatchCollection events = Regex.Matches(content, @"Send telemetry event: (?[^\r\n]+)\r?\n(?(?: [^\r\n]*\r?\n)+)"); + Assert.HasCount(Regex.Matches(content, "Send telemetry event:").Count, events); + Assert.Contains("dotnet/testingplatform/host/testhostbuilt", events.Select(e => e.Groups["name"].Value)); + Assert.Contains("dotnet/testingplatform/host/consoletesthostexit", events.Select(e => e.Groups["name"].Value)); + foreach (Match telemetryEvent in events) + { + var properties = Regex.Matches(telemetryEvent.Groups["properties"].Value, @"(?m)^ (?[^:\r\n]+): (?[^\r\n]*)") + .ToDictionary(m => m.Groups["key"].Value, m => m.Groups["value"].Value); + Assert.Contains("is llm", properties.Keys, telemetryEvent.Value); + Assert.AreEqual(context.ExpectedLLM, properties["is llm"], telemetryEvent.Value); + Assert.Contains("copilot agent session id", properties.Keys, telemetryEvent.Value); + Assert.AreEqual(context.ExpectedSessionId, properties["copilot agent session id"], telemetryEvent.Value); + Assert.AreEqual("11111111-2222-4333-8444-555555555555", properties["session id"], telemetryEvent.Value); + } + } + } + [DynamicData(nameof(TargetFrameworks.AllForDynamicData), typeof(TargetFrameworks))] [TestMethod] public async Task Telemetry_ByDefault_TelemetryIsEnabled(string tfm) @@ -45,6 +96,7 @@ public async Task Telemetry_WhenOptingOutTelemetry_WithEnvironmentVariable_Telem new Dictionary { { EnvironmentVariableConstants.TESTINGPLATFORM_TELEMETRY_OPTOUT, "1" }, + { "COPILOT_AGENT_SESSION_ID", "build-investigation-42" }, }, disableTelemetry: false, cancellationToken: TestContext.CancellationToken); @@ -58,7 +110,9 @@ public async Task Telemetry_WhenOptingOutTelemetry_WithEnvironmentVariable_Telem .+ Microsoft.Testing.Platform.Telemetry.TelemetryManager DEBUG DOTNET_CLI_TELEMETRY_OPTOUT environment variable: '' .+ Microsoft.Testing.Platform.Telemetry.TelemetryManager DEBUG Telemetry is 'DISABLED' """; - await AssertDiagnosticReportAsync(testHostResult, diagPathPattern, diagContentsPattern); + string report = await AssertDiagnosticReportAsync(testHostResult, diagPathPattern, diagContentsPattern); + string content = await File.ReadAllTextAsync(report, TestContext.CancellationToken); + Assert.DoesNotContain("Send telemetry event:", content); } [DynamicData(nameof(TargetFrameworks.AllForDynamicData), typeof(TargetFrameworks))] @@ -74,6 +128,7 @@ public async Task Telemetry_WhenOptingOutTelemetry_With_DOTNET_CLI_EnvironmentVa new Dictionary { { EnvironmentVariableConstants.DOTNET_CLI_TELEMETRY_OPTOUT, "1" }, + { "COPILOT_AGENT_SESSION_ID", "build-investigation-42" }, }, disableTelemetry: false, cancellationToken: TestContext.CancellationToken); @@ -87,7 +142,9 @@ public async Task Telemetry_WhenOptingOutTelemetry_With_DOTNET_CLI_EnvironmentVa .+ Microsoft.Testing.Platform.Telemetry.TelemetryManager DEBUG DOTNET_CLI_TELEMETRY_OPTOUT environment variable: '1' .+ Microsoft.Testing.Platform.Telemetry.TelemetryManager DEBUG Telemetry is 'DISABLED' """; - await AssertDiagnosticReportAsync(testHostResult, diagPathPattern, diagContentsPattern); + string report = await AssertDiagnosticReportAsync(testHostResult, diagPathPattern, diagContentsPattern); + string content = await File.ReadAllTextAsync(report, TestContext.CancellationToken); + Assert.DoesNotContain("Send telemetry event:", content); } private static async Task AssertDiagnosticReportAsync(TestHostResult testHostResult, string diagPathPattern, string diagContentsPattern, string level = "Trace", string flushType = "async") @@ -131,10 +188,12 @@ public sealed class TestAssetFixture() : TestAssetFixtureBase() + #file Program.cs +using Microsoft.Testing.Extensions; using Microsoft.Testing.Platform.Builder; using Microsoft.Testing.Platform.Capabilities.TestFramework; using Microsoft.Testing.Platform.Extensions.TestFramework; @@ -143,7 +202,10 @@ public class Program { public static async Task Main(string[] args) { + Console.WriteLine($"TelemetryAssemblyPath: {typeof(AppInsightsTelemetryProviderExtensions).Assembly.Location}"); + Console.WriteLine($"PlatformAssemblyPath: {typeof(ITestApplicationBuilder).Assembly.Location}"); ITestApplicationBuilder builder = await TestApplication.CreateBuilderAsync(args$TelemetryArg$); + builder.AddAppInsightsTelemetryProvider(); builder.RegisterTestFramework(_ => new TestFrameworkCapabilities(), (_,__) => new DummyTestFramework()); using ITestApplication app = await builder.BuildAsync(); return await app.RunAsync(); @@ -174,6 +236,9 @@ public Task ExecuteRequestAsync(ExecuteRequestContext context) public string TargetAssetPath => GetAssetPath(WithTelemetry); + // This custom framework has no MSTest metadata for the source generator to process. + protected override IReadOnlyList SourceGenMetadataModes => []; + public override (string ID, string Name, string Code) GetAssetsToGenerate() => (WithTelemetry, AssetName, TestCode .PatchTargetFrameworks(TargetFrameworks.All) diff --git a/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/AppInsightsProviderTests.cs b/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/AppInsightsProviderTests.cs index 7fc768cffee..8e3532753e6 100644 --- a/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/AppInsightsProviderTests.cs +++ b/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/AppInsightsProviderTests.cs @@ -307,6 +307,147 @@ public async Task LogEvent_AddsCommonProperties() Assert.AreEqual(TelemetryProperties.False, properties[TelemetryProperties.IsCIPropertyName]); } + [TestMethod] + [DataRow("COPILOT_CLI", "1", "true")] + [DataRow("CLAUDECODE", "1", "true")] + [DataRow("AI_AGENT", "github_copilot_app_agent", "true")] + [DataRow("AI_AGENT", "unknown", "false")] + [DataRow("COPILOT_CLI", "", "false")] + [DataRow("COPILOT_CLI", null, "false")] + public async Task LogEvent_ReportsLLMContext(string variable, string? value, string expected) + { + Mock environment = new(); + environment.Setup(x => x.GetEnvironmentVariable(variable)).Returns(value); + + (Dictionary properties, _) = await TrackEventAsync( + new Dictionary(), + environment: environment.Object); + + Assert.ContainsEntry("is llm", expected, properties); + Assert.ContainsEntry("copilot agent session id", "not_present", properties); + } + + [TestMethod] + [DataRow(null, "not_present")] + [DataRow("", "not_present")] + [DataRow("aBCDEfAB-1234-1567-8ABC-DEFaBCDEF012", "aBCDEfAB-1234-1567-8ABC-DEFaBCDEF012")] + [DataRow("aBCDEfAB-1234-4567-9ABC-DEFaBCDEF012", "aBCDEfAB-1234-4567-9ABC-DEFaBCDEF012")] + [DataRow("aBCDEfAB-1234-8567-bABC-DEFaBCDEF012", "aBCDEfAB-1234-8567-bABC-DEFaBCDEF012")] + [DataRow("00000000-0000-0000-0000-000000000000", "00000000-0000-0000-0000-000000000000")] + [DataRow("build-investigation-42", "a5b5273cea99d1a7df8e81f234369666daf7d810c64d852df129ae276d5167b2")] + [DataRow("BUILD-INVESTIGATION-42", "8495a77b0853a7baf0eaccc4f2cb4b53bd36872da0f13744527a2f8c4142a30f")] + [DataRow(" build-investigation-42 ", "d7bdcf1b188a689f9649ea46a5257b1e5310a1780ce5e884752643cad50ad9f5")] + [DataRow(" ", "36a9e7f1c95b82ffb99743e0c5c4ce95d83c9a430aac59f84ef3cbfab6145068")] + [DataRow("not_present", "edcc84b8e36c26b675c1b102b0e42f3507eee0afe5fbda7c203e9cbb758390e3")] + [DataRow("aBCDEfAB-1234-9567-8ABC-DEFaBCDEF012", "3409b6c07099e67716e185a5c8269e3548739d63d5e29e140b91654768e95708")] + [DataRow("aBCDEfAB-1234-4567-CABC-DEFaBCDEF012", "114b0c8fb3a916f8d4ec944818aade5fa3b6ff70a8f03af7f348508ca1683920")] + [DataRow("aBCDEfAB-1234-0567-8ABC-DEFaBCDEF012", "c31e983f514112a8db5f7badc6a10bd62fec9b8c6b8c4a4697996d5374c7b0fb")] + [DataRow("{aBCDEfAB-1234-4567-8ABC-DEFaBCDEF012}", "3c8cd2ea1393a621bec3d2bc462291191a0a67b1c20c4a599ea545ea1ed69eb7")] + [DataRow("aBCDEfAB-1234-4567-8ABC-DEFaBCDEF012\n", "de43912d6c54f9f27884ba6f98e7cd82f11eded3fd0551bfc48b471e41ade046", DisplayName = "Copilot UUID with trailing newline")] + [DataRow("caf\u00e9", "850f7dc43910ff890f8879c0ed26fe697c93a067ad93a7d50f466a7028a9bf4e")] + public async Task LogEvent_NormalizesCopilotSessionId(string? sessionId, string expected) + { + Mock environment = new(); + environment.Setup(x => x.GetEnvironmentVariable("COPILOT_AGENT_SESSION_ID")).Returns(sessionId); + + (Dictionary properties, _) = await TrackEventAsync( + new Dictionary(), + environment: environment.Object); + + Assert.ContainsEntry("copilot agent session id", expected, properties); + Assert.ContainsEntry("session id", "sessionId", properties); + Assert.ContainsEntry("is llm", "false", properties); + } + + [TestMethod] + public async Task LogEvent_SnapshotsContextBeforeQueueingWithoutMutatingCallerProperties() + { + TaskCompletionSource startConsumer = new(TaskCreationOptions.RunContinuationsAsynchronously); + TaskCompletionSource allEventsTracked = new(TaskCreationOptions.RunContinuationsAsynchronously); + Mock task = new(); +#if NETCOREAPP + task.Setup(x => x.Run(It.IsAny>(), It.IsAny())) + .Returns((Func loop, CancellationToken _) => RunConsumerAsync(loop)); +#else + task.Setup(x => x.RunLongRunning(It.IsAny>(), It.IsAny(), It.IsAny())) + .Returns((Func loop, string _, CancellationToken _) => RunConsumerAsync(loop)); +#endif + + List<(string Name, Dictionary Properties)> events = []; + Mock client = new(); + client.Setup(x => x.TrackEvent(It.IsAny(), It.IsAny>(), It.IsAny>())) + .Callback((string name, Dictionary properties, Dictionary _) => + { + events.Add((name, properties)); + if (events.Count == 3) + { + allEventsTracked.TrySetResult(true); + } + }); + Mock factory = new(); + factory.Setup(x => x.Create(It.IsAny(), It.IsAny())).Returns(client.Object); + Mock environment = new(); + string? currentId = "build-investigation-42"; + string? currentAgent = "github_copilot_app_agent"; + environment.Setup(x => x.GetEnvironmentVariable("COPILOT_AGENT_SESSION_ID")).Returns(() => currentId); + environment.Setup(x => x.GetEnvironmentVariable("AI_AGENT")).Returns(() => currentAgent); + + AppInsightsProvider provider = CreateProvider(factory, environment: environment.Object, task: task.Object); + Dictionary callerProperties = new() + { + ["is llm"] = false, + ["copilot agent session id"] = "caller-supplied", + }; + + try + { + await provider.LogEventAsync("first", callerProperties, CancellationToken.None); + currentId = "aBCDEfAB-1234-4567-8ABC-DEFaBCDEF012"; + currentAgent = null; + await provider.LogEventAsync("second", callerProperties, CancellationToken.None); + currentId = null; + await provider.LogEventAsync("third", callerProperties, CancellationToken.None); + currentId = "later-context"; + currentAgent = "github_copilot_app_agent"; + + Assert.HasCount(2, callerProperties); + Assert.IsFalse((bool)callerProperties["is llm"]); + Assert.AreEqual("caller-supplied", callerProperties["copilot agent session id"]); + callerProperties.Clear(); + startConsumer.SetResult(true); + await WaitForSignalAsync(allEventsTracked.Task, "Telemetry consumer did not track the three queued events."); + } + finally + { + startConsumer.TrySetResult(true); +#if NETCOREAPP + await provider.DisposeAsync(); +#else + provider.Dispose(); +#endif + } + + Assert.HasCount(3, events); + Assert.AreEqual("first", events[0].Name); + Assert.AreEqual("second", events[1].Name); + Assert.AreEqual("third", events[2].Name); + Assert.ContainsEntry("is llm", "true", events[0].Properties); + Assert.ContainsEntry("copilot agent session id", "a5b5273cea99d1a7df8e81f234369666daf7d810c64d852df129ae276d5167b2", events[0].Properties); + Assert.ContainsEntry("is llm", "false", events[1].Properties); + Assert.ContainsEntry("copilot agent session id", "aBCDEfAB-1234-4567-8ABC-DEFaBCDEF012", events[1].Properties); + Assert.ContainsEntry("is llm", "false", events[2].Properties); + Assert.ContainsEntry("copilot agent session id", "not_present", events[2].Properties); + + Task RunConsumerAsync(Func loop) + => Task.Run( + async () => + { + await startConsumer.Task; + await loop(); + }, + TestContext.CancellationToken); + } + [TestMethod] [DataRow(false)] [DataRow(true)] diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Telemetry/TelemetryManagerTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Telemetry/TelemetryManagerTests.cs index 6208f9baa1c..74ae0087cd9 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Telemetry/TelemetryManagerTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Telemetry/TelemetryManagerTests.cs @@ -16,6 +16,37 @@ namespace Microsoft.Testing.Platform.UnitTests; [TestClass] public sealed class TelemetryManagerTests { + [TestMethod] + [DataRow(null, false)] + [DataRow(EnvironmentVariableConstants.TESTINGPLATFORM_TELEMETRY_OPTOUT, true)] + [DataRow(EnvironmentVariableConstants.DOTNET_CLI_TELEMETRY_OPTOUT, true)] + public async Task TelemetryManager_WhenDisabled_DoesNotCreateContextCollector(string? optOutVariable, bool enableTelemetry) + { + Mock environment = new(); + if (optOutVariable is not null) + { + environment.Setup(x => x.GetEnvironmentVariable(optOutVariable)).Returns("1"); + } + + ServiceProvider serviceProvider = new(); + serviceProvider.AddService(environment.Object); + Mock loggerFactory = new(); + loggerFactory.Setup(x => x.CreateLogger(It.IsAny())).Returns(new Mock().Object); + bool collectorCreated = false; + TelemetryManager manager = new(); + manager.AddTelemetryCollectorProvider(_ => + { + collectorCreated = true; + return new NopTelemetryService(false); + }); + + await manager.BuildTelemetryAsync(serviceProvider, loggerFactory.Object, new TestApplicationOptions { EnableTelemetry = enableTelemetry }); + + Assert.IsFalse(collectorCreated); + Assert.IsFalse(serviceProvider.GetRequiredService().IsEnabled); + environment.Verify(x => x.GetEnvironmentVariable("COPILOT_AGENT_SESSION_ID"), Times.Never); + } + // When set to 1 or true it should suppress the message. [DataRow(EnvironmentVariableConstants.TESTINGPLATFORM_NOBANNER, "1")] [DataRow(EnvironmentVariableConstants.TESTINGPLATFORM_NOBANNER, "true")] diff --git a/test/Utilities/Microsoft.Testing.TestInfrastructure/WellKnownEnvironmentVariables.cs b/test/Utilities/Microsoft.Testing.TestInfrastructure/WellKnownEnvironmentVariables.cs index f9d1956cf73..3f0d039241b 100644 --- a/test/Utilities/Microsoft.Testing.TestInfrastructure/WellKnownEnvironmentVariables.cs +++ b/test/Utilities/Microsoft.Testing.TestInfrastructure/WellKnownEnvironmentVariables.cs @@ -86,6 +86,7 @@ public static class WellKnownEnvironmentVariables "TESTINGPLATFORM_TELEMETRY_OPTOUT", "DOTNET_NOLOGO", "TESTINGPLATFORM_NOBANNER", + "COPILOT_AGENT_SESSION_ID", // Azure DevOps output device opt-out. Tests inject this explicitly when needed, so we // keep the parent process value from bleeding into child test hosts. From de5d2bb4b700c74e0bbf1021d00e57ab65a3f22d Mon Sep 17 00:00:00 2001 From: Jan Krivanek Date: Wed, 18 Nov 2026 11:49:16 +0100 Subject: [PATCH 2/3] Update the property name --- docs/decisions/llm-context-telemetry.md | 55 ++++++++++--------- .../PACKAGE.md | 2 +- .../InternalAPI/InternalAPI.Unshipped.txt | 2 +- .../Telemetry/TelemetryProperties.cs | 2 +- .../TelemetryTests.cs | 5 +- .../AppInsightsProviderTests.cs | 15 ++--- 6 files changed, 42 insertions(+), 39 deletions(-) diff --git a/docs/decisions/llm-context-telemetry.md b/docs/decisions/llm-context-telemetry.md index 4bdfdda5fac..e43413ef97e 100644 --- a/docs/decisions/llm-context-telemetry.md +++ b/docs/decisions/llm-context-telemetry.md @@ -8,7 +8,7 @@ usage collector: | Property | Value | | --- | --- | | `is llm` | Existing `LLMEnvironmentDetector` result as `true`/`false`; a heuristic, not proof of human/agent authorship. | -| `copilot agent session id` | Normalized `COPILOT_AGENT_SESSION_ID`, or `not_present` when absent/empty. | +| `CopilotAgentSessionId` | Normalized `COPILOT_AGENT_SESSION_ID`, or `not_present` when absent/empty. | Match the SDK's `CopilotAgentSessionId`: preserve canonical UUID versions 1-8 with RFC variant, plus the nil UUID, including original casing. Hash other @@ -37,60 +37,61 @@ private: TestFx's existing hasher uppercases inputs and would break correlation; `Guid.TryParse` accepts UUID forms outside Copilot's contract. Collecting agent names/raw marker values or adding OpenTelemetry tags is outside scope. +Use the SDK's exact correlation key to simplify cross-product queries. Keep +`is llm` distinct from SDK's `llm`, which contains agent names rather than a boolean. + ## Test-value evidence -Validated on 2026-11-18 with SDK `12.0.100-alpha.1.26562.108`, Debug builds. -Base: `28c534d9fd47856682e8d1c14f54a10a1b4a08bf`. +SDK-key alignment validated on 2026-11-18, Debug, SDK `12.0.100-alpha.1.26562.108`. +Base: `53b0b9bd9df4f856498e18dec978ca86c9753cfc`. Behavioral `src`/`test` patch SHA-256: -`51bb4966e403e758b6f4c331080004821ae2c87cfde414f892c915dd0f906044`. +`c6abdb455adf3e0e0634e1dfedb99d8397ff21d98d640e8a7408618de3a41fbf`. This document is excluded from that patch identity. | Contract | Tests | | --- | --- | | Detection and correlation | `LogEvent_ReportsLLMContext` (6 cases), `LogEvent_NormalizesCopilotSessionId` (17 cases: UUIDs, absence, casing, whitespace, malformed IDs, UTF-8). | | Queueing and ownership | `LogEvent_SnapshotsContextBeforeQueueingWithoutMutatingCallerProperties`: three distinguishable events, changing context, overrides, and dictionary reuse. | -| Opt-outs | `TelemetryManager_WhenDisabled_DoesNotCreateContextCollector`, plus packaged tests with the real provider registered. | +| Opt-outs | Packaged environment-variable and `TestApplicationOptions` tests with the real provider registered. | | Shipping boundary | `Telemetry_Context_IsIncludedInEveryUsageEvent`: four contexts per runtime; checks each event's fields, identity, and unchanged platform session ID. | | Selection | Passed / executed | Result | | --- | --- | --- | | Provider tests: .NET 10 / 11 / Framework 4.6.2 / 4.7.2 | 57 / 57, 57 / 57, 54 / 54, 54 / 54 | Exit 0 | -| Manager/detector tests: .NET 10 / 11 / Framework 4.6.2 | 30 / 30 on each | Exit 0 | | Packaged acceptance: .NET 10 / 11 / Framework 4.6.2 | 15 / 15 | Exit 0 | -Total: **312 unit and 15 acceptance cases passed**, no failures/skips. +Current alignment: **222 unit and 15 acceptance cases passed**, no failures/skips. TRX/JUnit/CTRF counts were reconciled; method-level parallelization was preserved. The acceptance host runs on .NET 12. Its custom-framework children intentionally exit 8 (`ZeroTests`), exercising startup/shutdown telemetry rather than counting zero-test runs as regression tests. -**Executed counterfactual:** removing both fields before enqueueing, with the -same tests retained, produced 24 intended assertion failures and 33 passes on -.NET 10 (exit 2). Restoring the provider and forcing a rebuild recovered to -57 passes (exit 0). This is feature-removal evidence, not a pristine-base run. -Mutation patch SHA-256: -`15d8df8a7812dc2fd699e6aa4e5c294e0666b50a17280a38ba111a7235058d20`. +**Executed regression check:** the same 17 `LogEvent_NormalizesCopilotSessionId` +cases ran in an isolated output copy with the preserved pre-rename provider. +All 17 failed specifically because `CopilotAgentSessionId` was missing (exit 2). +Replacing only that DLL with the rebuilt provider yielded 17 passes (exit 0); +test assembly bytes were unchanged. Both runs also checked report counts. +The initial feature's separate field-removal check detected 24 failures before +key alignment; its earlier reports remain archived. Both changed `3.0.0-dev` packages packed successfully. All six executed consumer DLLs matched their NuGet payload hashes, using `netstandard2.0` assets on .NET Framework. Isolated restores and actual loaded assembly paths were checked. -The packaged scenarios verified 24 usage events across 12 context-specific launches. +The packaged scenarios verified 24 usage events across 12 context-specific launches, +including the SDK key's presence and the old space-separated key's absence. ## Validation notes and remaining work -The default build could not find Visual Studio 18.12; supported -`-msbuildEngine dotnet` builds passed instead. Fixture package prerequisites were -packed separately. Tests use an explicit diagnostic directory because agent-aware -banner suppression hides the diagnostic-file announcement. A stale comparison -DLL after copying older source was identified by hashes and corrected with -`-t:Rebuild`; setup/build failures were not counted as behavioral evidence. - -Full commands, reports, patches, binlogs, and DLL hashes remain in session -artifacts, including `run-unit-validation.ps1` and -`consumer-provenance-complete\provenance.json`. The temporary comparison export -was removed. Fixture-only MSTest packages are retained under `fixture-packages`; -copy them to `artifacts\packages\Debug\Shipping` before a local acceptance rerun -without a full pack. Final `.\eng\verify-nupkgs.ps1 -configuration Debug` passed. +Initial setup required `-msbuildEngine dotnet` (VS18.12 unavailable), fixture +packages, and explicit diagnostic directories for banner-suppressed runs. +Restoring older source needed `-t:Rebuild` to avoid a stale DLL; these setup +failures were not counted as behavioral evidence. + +Full commands, reports, patches, and DLL hashes remain in session artifacts under +`sdk-key-alignment`: `validate.ps1`, `comparison-provenance.json`, and +`consumer-provenance-complete\provenance.json`. Fixture-only packages were restored +temporarily for acceptance and removed afterward; the isolated comparison output +is also cleaned up. Final `.\eng\verify-nupkgs.ps1 -configuration Debug` passed. This is nonvisual metadata; backend ingestion/dashboard queries were not verified. Before release, update the diff --git a/src/Platform/Microsoft.Testing.Extensions.Telemetry/PACKAGE.md b/src/Platform/Microsoft.Testing.Extensions.Telemetry/PACKAGE.md index b2df77341e7..57e7c3a5457 100644 --- a/src/Platform/Microsoft.Testing.Extensions.Telemetry/PACKAGE.md +++ b/src/Platform/Microsoft.Testing.Extensions.Telemetry/PACKAGE.md @@ -27,7 +27,7 @@ When telemetry is enabled, every usage event includes: - `is llm`: `true` when the platform's existing environment detector recognizes an AI agent, otherwise `false`. Detection is heuristic; `false` does not prove a human invocation. Only the boolean is collected, not the marker values. -- `copilot agent session id`: the nonempty `COPILOT_AGENT_SESSION_ID`, normalized +- `CopilotAgentSessionId`: the nonempty `COPILOT_AGENT_SESSION_ID`, normalized to match the .NET SDK's `CopilotAgentSessionId` and Copilot telemetry. Canonical UUIDs (versions 1-8 with RFC variant, or the nil UUID) are preserved exactly. Other values become lowercase SHA-256 of their original UTF-8 bytes, diff --git a/src/Platform/Microsoft.Testing.Platform/InternalAPI/InternalAPI.Unshipped.txt b/src/Platform/Microsoft.Testing.Platform/InternalAPI/InternalAPI.Unshipped.txt index 71e56af29ad..d63c4dfaa31 100644 --- a/src/Platform/Microsoft.Testing.Platform/InternalAPI/InternalAPI.Unshipped.txt +++ b/src/Platform/Microsoft.Testing.Platform/InternalAPI/InternalAPI.Unshipped.txt @@ -1,6 +1,6 @@ #nullable enable const Microsoft.Testing.Platform.Telemetry.TelemetryProperties.IsLLMPropertyName = "is llm" -> string! -const Microsoft.Testing.Platform.Telemetry.TelemetryProperties.CopilotAgentSessionIdPropertyName = "copilot agent session id" -> string! +const Microsoft.Testing.Platform.Telemetry.TelemetryProperties.CopilotAgentSessionIdPropertyName = "CopilotAgentSessionId" -> string! Microsoft.Testing.Platform.TestHostControllers.TestHostControllersManager.AddDataConsumerWhenControllerStarts(Microsoft.Testing.Platform.Extensions.CompositeExtensionFactory! compositeServiceFactory) -> void Microsoft.Testing.Platform.TestHostControllers.TestHostControllersManager.AddEnvironmentVariableProviderWhenControllerStarts(System.Func! factory) -> void *REMOVED*Microsoft.Testing.Platform.TestHostControllers.TestHostProcessInformation.HasExitedGracefully.get -> bool diff --git a/src/Platform/Microsoft.Testing.Platform/Telemetry/TelemetryProperties.cs b/src/Platform/Microsoft.Testing.Platform/Telemetry/TelemetryProperties.cs index 359959de7e2..910d3e829a4 100644 --- a/src/Platform/Microsoft.Testing.Platform/Telemetry/TelemetryProperties.cs +++ b/src/Platform/Microsoft.Testing.Platform/Telemetry/TelemetryProperties.cs @@ -10,7 +10,7 @@ internal static class TelemetryProperties public const string ReporterIdPropertyName = "reporter id"; public const string IsCIPropertyName = "is ci"; public const string IsLLMPropertyName = "is llm"; - public const string CopilotAgentSessionIdPropertyName = "copilot agent session id"; + public const string CopilotAgentSessionIdPropertyName = "CopilotAgentSessionId"; public const string VersionValue = "20"; diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/TelemetryTests.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/TelemetryTests.cs index 96191d1aa55..af768293f5b 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/TelemetryTests.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/TelemetryTests.cs @@ -54,8 +54,9 @@ public async Task Telemetry_Context_IsIncludedInEveryUsageEvent(string tfm) .ToDictionary(m => m.Groups["key"].Value, m => m.Groups["value"].Value); Assert.Contains("is llm", properties.Keys, telemetryEvent.Value); Assert.AreEqual(context.ExpectedLLM, properties["is llm"], telemetryEvent.Value); - Assert.Contains("copilot agent session id", properties.Keys, telemetryEvent.Value); - Assert.AreEqual(context.ExpectedSessionId, properties["copilot agent session id"], telemetryEvent.Value); + Assert.Contains("CopilotAgentSessionId", properties.Keys, telemetryEvent.Value); + Assert.AreEqual(context.ExpectedSessionId, properties["CopilotAgentSessionId"], telemetryEvent.Value); + Assert.DoesNotContain("copilot agent session id", properties.Keys, telemetryEvent.Value); Assert.AreEqual("11111111-2222-4333-8444-555555555555", properties["session id"], telemetryEvent.Value); } } diff --git a/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/AppInsightsProviderTests.cs b/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/AppInsightsProviderTests.cs index 8e3532753e6..9d80b1ec660 100644 --- a/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/AppInsightsProviderTests.cs +++ b/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/AppInsightsProviderTests.cs @@ -324,7 +324,7 @@ public async Task LogEvent_ReportsLLMContext(string variable, string? value, str environment: environment.Object); Assert.ContainsEntry("is llm", expected, properties); - Assert.ContainsEntry("copilot agent session id", "not_present", properties); + Assert.ContainsEntry("CopilotAgentSessionId", "not_present", properties); } [TestMethod] @@ -354,7 +354,8 @@ public async Task LogEvent_NormalizesCopilotSessionId(string? sessionId, string new Dictionary(), environment: environment.Object); - Assert.ContainsEntry("copilot agent session id", expected, properties); + Assert.ContainsEntry("CopilotAgentSessionId", expected, properties); + Assert.DoesNotContain("copilot agent session id", properties.Keys); Assert.ContainsEntry("session id", "sessionId", properties); Assert.ContainsEntry("is llm", "false", properties); } @@ -396,7 +397,7 @@ public async Task LogEvent_SnapshotsContextBeforeQueueingWithoutMutatingCallerPr Dictionary callerProperties = new() { ["is llm"] = false, - ["copilot agent session id"] = "caller-supplied", + ["CopilotAgentSessionId"] = "caller-supplied", }; try @@ -412,7 +413,7 @@ public async Task LogEvent_SnapshotsContextBeforeQueueingWithoutMutatingCallerPr Assert.HasCount(2, callerProperties); Assert.IsFalse((bool)callerProperties["is llm"]); - Assert.AreEqual("caller-supplied", callerProperties["copilot agent session id"]); + Assert.AreEqual("caller-supplied", callerProperties["CopilotAgentSessionId"]); callerProperties.Clear(); startConsumer.SetResult(true); await WaitForSignalAsync(allEventsTracked.Task, "Telemetry consumer did not track the three queued events."); @@ -432,11 +433,11 @@ public async Task LogEvent_SnapshotsContextBeforeQueueingWithoutMutatingCallerPr Assert.AreEqual("second", events[1].Name); Assert.AreEqual("third", events[2].Name); Assert.ContainsEntry("is llm", "true", events[0].Properties); - Assert.ContainsEntry("copilot agent session id", "a5b5273cea99d1a7df8e81f234369666daf7d810c64d852df129ae276d5167b2", events[0].Properties); + Assert.ContainsEntry("CopilotAgentSessionId", "a5b5273cea99d1a7df8e81f234369666daf7d810c64d852df129ae276d5167b2", events[0].Properties); Assert.ContainsEntry("is llm", "false", events[1].Properties); - Assert.ContainsEntry("copilot agent session id", "aBCDEfAB-1234-4567-8ABC-DEFaBCDEF012", events[1].Properties); + Assert.ContainsEntry("CopilotAgentSessionId", "aBCDEfAB-1234-4567-8ABC-DEFaBCDEF012", events[1].Properties); Assert.ContainsEntry("is llm", "false", events[2].Properties); - Assert.ContainsEntry("copilot agent session id", "not_present", events[2].Properties); + Assert.ContainsEntry("CopilotAgentSessionId", "not_present", events[2].Properties); Task RunConsumerAsync(Func loop) => Task.Run( From 692f9011f32db541b4cf46fb0fe0eb4293fb25ff Mon Sep 17 00:00:00 2001 From: Jan Krivanek Date: Wed, 18 Nov 2026 12:17:31 +0100 Subject: [PATCH 3/3] Fix Release compilation of Copilot telemetry Import Microsoft.Testing.Platform in all configurations so RoslynString resolves during Release builds. Verified Release packing and 190 provider test cases. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- docs/decisions/llm-context-telemetry.md | 8 ++++---- .../AppInsightsProvider.cs | 2 -- 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/docs/decisions/llm-context-telemetry.md b/docs/decisions/llm-context-telemetry.md index e43413ef97e..0e8ef8fed35 100644 --- a/docs/decisions/llm-context-telemetry.md +++ b/docs/decisions/llm-context-telemetry.md @@ -82,10 +82,10 @@ including the SDK key's presence and the old space-separated key's absence. ## Validation notes and remaining work -Initial setup required `-msbuildEngine dotnet` (VS18.12 unavailable), fixture -packages, and explicit diagnostic directories for banner-suppressed runs. -Restoring older source needed `-t:Rebuild` to avoid a stale DLL; these setup -failures were not counted as behavioral evidence. +CI exposed a Release-only failure: the namespace import for `RoslynString` was +guarded by `#if DEBUG`. The import is now unconditional. Release packing passes +for all three product TFMs, and 190 Release provider cases pass across .NET 10/11 +and Framework 4.6.2/4.7.2 (49/49/46/46). This fixes compilation, not runtime behavior. Full commands, reports, patches, and DLL hashes remain in session artifacts under `sdk-key-alignment`: `validate.ps1`, `comparison-provenance.json`, and diff --git a/src/Platform/Microsoft.Testing.Extensions.Telemetry/AppInsightsProvider.cs b/src/Platform/Microsoft.Testing.Extensions.Telemetry/AppInsightsProvider.cs index 1b072224bfa..d4c540094b1 100644 --- a/src/Platform/Microsoft.Testing.Extensions.Telemetry/AppInsightsProvider.cs +++ b/src/Platform/Microsoft.Testing.Extensions.Telemetry/AppInsightsProvider.cs @@ -7,9 +7,7 @@ using System.Threading.Channels; #endif -#if DEBUG using Microsoft.Testing.Platform; -#endif using Microsoft.Testing.Platform.Configurations; using Microsoft.Testing.Platform.Helpers; using Microsoft.Testing.Platform.Logging;