Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
99 changes: 99 additions & 0 deletions docs/decisions/llm-context-telemetry.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
# 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. |
| `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
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.

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

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:
`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 | 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 |
| Packaged acceptance: .NET 10 / 11 / Framework 4.6.2 | 15 / 15 | Exit 0 |

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 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,
including the SDK key's presence and the old space-separated key's absence.

## Validation notes and remaining work

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
`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
[public telemetry documentation](https://learn.microsoft.com/dotnet/core/testing/microsoft-testing-platform-telemetry)
and complete any required telemetry governance review.
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
// 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

#if DEBUG
using Microsoft.Testing.Platform;
#endif
using Microsoft.Testing.Platform.Configurations;
using Microsoft.Testing.Platform.Helpers;
using Microsoft.Testing.Platform.Logging;
Expand Down Expand Up @@ -60,6 +60,7 @@ internal sealed partial class AppInsightsProvider :
TelemetryProperties.VersionPropertyName,
TelemetryProperties.ReporterIdPropertyName,
TelemetryProperties.SessionId,
TelemetryProperties.CopilotAgentSessionIdPropertyName,
TelemetryProperties.HostProperties.TestingPlatformVersionPropertyName,
TelemetryProperties.HostProperties.FrameworkDescriptionPropertyName,
TelemetryProperties.HostProperties.OSDescriptionPropertyName,
Expand Down Expand Up @@ -310,6 +311,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)
{
Expand Down Expand Up @@ -365,15 +400,25 @@ Task LogEventAsync(string eventName, IDictionary<string, object> 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<string, object>(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
}
Expand Down
18 changes: 18 additions & 0 deletions src/Platform/Microsoft.Testing.Extensions.Telemetry/PACKAGE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
- `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,
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 <https://learn.microsoft.com/dotnet/core/testing/microsoft-testing-platform-telemetry>.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
#nullable enable
const Microsoft.Testing.Platform.Telemetry.TelemetryProperties.IsLLMPropertyName = "is llm" -> string!
const Microsoft.Testing.Platform.Telemetry.TelemetryProperties.CopilotAgentSessionIdPropertyName = "CopilotAgentSessionId" -> string!
Microsoft.Testing.Platform.TestHostControllers.TestHostControllersManager.AddDataConsumerWhenControllerStarts<T>(Microsoft.Testing.Platform.Extensions.CompositeExtensionFactory<T!>! compositeServiceFactory) -> void
Microsoft.Testing.Platform.TestHostControllers.TestHostControllersManager.AddEnvironmentVariableProviderWhenControllerStarts(System.Func<System.IServiceProvider!, Microsoft.Testing.Platform.Extensions.TestHostControllers.ITestHostEnvironmentVariableProvider!>! factory) -> void
*REMOVED*Microsoft.Testing.Platform.TestHostControllers.TestHostProcessInformation.HasExitedGracefully.get -> bool
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 = "CopilotAgentSessionId";

public const string VersionValue = "20";

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<string> AssertDiagnosticReportAsync(TestHostResult testHostResult, string diagPathPattern, string diagContentsPattern, string level = "Trace", string flushType = "async")
Expand Down Expand Up @@ -73,10 +75,12 @@ public sealed class TestAssetFixture() : TestAssetFixtureBase()
<ItemGroup>
<PackageReference Include="Microsoft.Testing.Platform" Version="$MicrosoftTestingPlatformVersion$" />
<PackageReference Include="Microsoft.Testing.Extensions.Telemetry" Version="$MicrosoftTestingPlatformVersion$" />
</ItemGroup>
</Project>
#file Program.cs
using Microsoft.Testing.Extensions;
using Microsoft.Testing.Platform.Builder;
using Microsoft.Testing.Platform.Capabilities.TestFramework;
using Microsoft.Testing.Platform.Extensions.TestFramework;
Expand All @@ -86,6 +90,7 @@ public class Program
public static async Task<int> 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();
Expand Down
Loading
Loading