Skip to content

Commit 1893237

Browse files
authored
Add copilot telemetry cross-correlation id (#12508)
1 parent 28a0412 commit 1893237

10 files changed

Lines changed: 420 additions & 9 deletions

File tree

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
# LLM context telemetry: research and decisions
2+
3+
## Contract
4+
5+
Add two common properties to the optional Microsoft.Testing.Extensions.Telemetry
6+
usage collector:
7+
8+
| Property | Value |
9+
| --- | --- |
10+
| `is llm` | Existing `LLMEnvironmentDetector` result as `true`/`false`; a heuristic, not proof of human/agent authorship. |
11+
| `CopilotAgentSessionId` | Normalized `COPILOT_AGENT_SESSION_ID`, or `not_present` when absent/empty. |
12+
13+
Match the SDK's `CopilotAgentSessionId`: preserve canonical UUID versions 1-8
14+
with RFC variant, plus the nil UUID, including original casing. Hash other
15+
values as lowercase SHA-256 of their original UTF-8 bytes, without trimming.
16+
A literal `not_present` input is hashed. A missing telemetry property means
17+
collection support is unknown.
18+
19+
The signals are independent. Snapshot them before queueing each event, without
20+
mutating caller dictionaries or accepting overrides. Preserve existing opt-outs,
21+
session/reporter IDs, runtime restrictions, cancellation, and transport.
22+
No new public API or dependency; no changes to console defaults, OpenTelemetry,
23+
or JSON-RPC `ServerTelemetry` forwarding, which operates independently of usage
24+
telemetry opt-out.
25+
26+
## Research and decision
27+
28+
[dotnet/sdk#57106](https://github.com/dotnet/sdk/pull/57106) adds cross-product
29+
Copilot correlation. Its pinned
30+
[normalization implementation](https://github.com/dotnet/sdk/blob/a436089fa916892516a2d1d4ed964c96d07380fa/src/Cli/dotnet/Telemetry/TelemetryCommonProperties.cs)
31+
was checked against the referenced Copilot runtime source on 2026-11-18.
32+
33+
Reuse TestFx's detector, previously used only for console defaults, and collect
34+
the fields in `AppInsightsProvider.LogEventAsync`. Construction-time capture was
35+
rejected because queued events could receive stale context. Keep normalization
36+
private: TestFx's existing hasher uppercases inputs and would break correlation;
37+
`Guid.TryParse` accepts UUID forms outside Copilot's contract. Collecting agent
38+
names/raw marker values or adding OpenTelemetry tags is outside scope.
39+
40+
Use the SDK's exact correlation key to simplify cross-product queries. Keep
41+
`is llm` distinct from SDK's `llm`, which contains agent names rather than a boolean.
42+
43+
## Test-value evidence
44+
45+
SDK-key alignment validated on 2026-11-18, Debug, SDK `12.0.100-alpha.1.26562.108`.
46+
Base: `53b0b9bd9df4f856498e18dec978ca86c9753cfc`.
47+
Behavioral `src`/`test` patch SHA-256:
48+
`c6abdb455adf3e0e0634e1dfedb99d8397ff21d98d640e8a7408618de3a41fbf`.
49+
This document is excluded from that patch identity.
50+
51+
| Contract | Tests |
52+
| --- | --- |
53+
| Detection and correlation | `LogEvent_ReportsLLMContext` (6 cases), `LogEvent_NormalizesCopilotSessionId` (17 cases: UUIDs, absence, casing, whitespace, malformed IDs, UTF-8). |
54+
| Queueing and ownership | `LogEvent_SnapshotsContextBeforeQueueingWithoutMutatingCallerProperties`: three distinguishable events, changing context, overrides, and dictionary reuse. |
55+
| Opt-outs | Packaged environment-variable and `TestApplicationOptions` tests with the real provider registered. |
56+
| Shipping boundary | `Telemetry_Context_IsIncludedInEveryUsageEvent`: four contexts per runtime; checks each event's fields, identity, and unchanged platform session ID. |
57+
58+
| Selection | Passed / executed | Result |
59+
| --- | --- | --- |
60+
| Provider tests: .NET 10 / 11 / Framework 4.6.2 / 4.7.2 | 57 / 57, 57 / 57, 54 / 54, 54 / 54 | Exit 0 |
61+
| Packaged acceptance: .NET 10 / 11 / Framework 4.6.2 | 15 / 15 | Exit 0 |
62+
63+
Current alignment: **222 unit and 15 acceptance cases passed**, no failures/skips.
64+
TRX/JUnit/CTRF counts were reconciled; method-level parallelization was preserved.
65+
The acceptance host runs on .NET 12. Its custom-framework children intentionally
66+
exit 8 (`ZeroTests`), exercising startup/shutdown telemetry rather than counting
67+
zero-test runs as regression tests.
68+
69+
**Executed regression check:** the same 17 `LogEvent_NormalizesCopilotSessionId`
70+
cases ran in an isolated output copy with the preserved pre-rename provider.
71+
All 17 failed specifically because `CopilotAgentSessionId` was missing (exit 2).
72+
Replacing only that DLL with the rebuilt provider yielded 17 passes (exit 0);
73+
test assembly bytes were unchanged. Both runs also checked report counts.
74+
The initial feature's separate field-removal check detected 24 failures before
75+
key alignment; its earlier reports remain archived.
76+
77+
Both changed `3.0.0-dev` packages packed successfully. All six executed consumer
78+
DLLs matched their NuGet payload hashes, using `netstandard2.0` assets on
79+
.NET Framework. Isolated restores and actual loaded assembly paths were checked.
80+
The packaged scenarios verified 24 usage events across 12 context-specific launches,
81+
including the SDK key's presence and the old space-separated key's absence.
82+
83+
## Validation notes and remaining work
84+
85+
CI exposed a Release-only failure: the namespace import for `RoslynString` was
86+
guarded by `#if DEBUG`. The import is now unconditional. Release packing passes
87+
for all three product TFMs, and 190 Release provider cases pass across .NET 10/11
88+
and Framework 4.6.2/4.7.2 (49/49/46/46). This fixes compilation, not runtime behavior.
89+
90+
Full commands, reports, patches, and DLL hashes remain in session artifacts under
91+
`sdk-key-alignment`: `validate.ps1`, `comparison-provenance.json`, and
92+
`consumer-provenance-complete\provenance.json`. Fixture-only packages were restored
93+
temporarily for acceptance and removed afterward; the isolated comparison output
94+
is also cleaned up. Final `.\eng\verify-nupkgs.ps1 -configuration Debug` passed.
95+
96+
This is nonvisual metadata; backend ingestion/dashboard queries were not verified.
97+
Before release, update the
98+
[public telemetry documentation](https://learn.microsoft.com/dotnet/core/testing/microsoft-testing-platform-telemetry)
99+
and complete any required telemetry governance review.

‎src/Platform/Microsoft.Testing.Extensions.Telemetry/AppInsightsProvider.cs‎

Lines changed: 51 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
11
// Copyright (c) Microsoft Corporation. All rights reserved.
22
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
33

4+
using System.Security.Cryptography;
5+
46
#if NETCOREAPP
57
using System.Threading.Channels;
68
#endif
79

8-
#if DEBUG
910
using Microsoft.Testing.Platform;
10-
#endif
1111
using Microsoft.Testing.Platform.Configurations;
1212
using Microsoft.Testing.Platform.Helpers;
1313
using Microsoft.Testing.Platform.Logging;
@@ -60,6 +60,7 @@ internal sealed partial class AppInsightsProvider :
6060
TelemetryProperties.VersionPropertyName,
6161
TelemetryProperties.ReporterIdPropertyName,
6262
TelemetryProperties.SessionId,
63+
TelemetryProperties.CopilotAgentSessionIdPropertyName,
6364
TelemetryProperties.HostProperties.TestingPlatformVersionPropertyName,
6465
TelemetryProperties.HostProperties.FrameworkDescriptionPropertyName,
6566
TelemetryProperties.HostProperties.OSDescriptionPropertyName,
@@ -310,6 +311,40 @@ private static double ToUnixTimeNanoseconds(DateTimeOffset value) =>
310311
// We multiply by 100 because Ticks are 100 ns, and we want to report ns.
311312
(value.UtcTicks - 621355968000000000L) * 100;
312313

314+
private static string NormalizeCopilotAgentSessionId(string? sessionId)
315+
{
316+
if (RoslynString.IsNullOrEmpty(sessionId))
317+
{
318+
return "not_present";
319+
}
320+
321+
if (GetCopilotSessionUuidPattern().IsMatch(sessionId))
322+
{
323+
return sessionId;
324+
}
325+
326+
// Unlike HashWithNormalizedCasing, Copilot hashes the original UTF-8 bytes.
327+
using var sha256 = SHA256.Create();
328+
byte[] hash = sha256.ComputeHash(Encoding.UTF8.GetBytes(sessionId));
329+
#if NET9_0_OR_GREATER
330+
return Convert.ToHexStringLower(hash);
331+
#else
332+
return BitConverter.ToString(hash).Replace("-", string.Empty).ToLowerInvariant();
333+
#endif
334+
}
335+
336+
// Match the SDK/Copilot contract: canonical UUID versions 1-8 with RFC variant, or nil.
337+
#if NET7_0_OR_GREATER
338+
[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",
339+
RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)]
340+
private static partial Regex GetCopilotSessionUuidPattern();
341+
#else
342+
private static Regex GetCopilotSessionUuidPattern()
343+
=> new(
344+
@"\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",
345+
RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
346+
#endif
347+
313348
#if DEBUG
314349
private static string AssertHashed(string key, string value)
315350
{
@@ -365,15 +400,25 @@ Task LogEventAsync(string eventName, IDictionary<string, object> paramsMap, Canc
365400
#endif
366401
}
367402

368-
#if NETCOREAPP
369-
await _payloads.Writer.WriteAsync((eventName, paramsMap), cancellationToken).ConfigureAwait(ContinueOnCapturedContext);
370-
#else
403+
#if !NETCOREAPP
371404
if (cancellationToken.IsCancellationRequested)
372405
{
373406
return Task.FromCanceled(cancellationToken);
374407
}
408+
#endif
409+
410+
// Capture context before queueing; the environment and caller's dictionary can change.
411+
var payload = new Dictionary<string, object>(paramsMap)
412+
{
413+
[TelemetryProperties.IsLLMPropertyName] = new LLMEnvironmentDetector(_environment).IsLLMEnvironment(),
414+
[TelemetryProperties.CopilotAgentSessionIdPropertyName] =
415+
NormalizeCopilotAgentSessionId(_environment.GetEnvironmentVariable("COPILOT_AGENT_SESSION_ID")),
416+
};
375417

376-
_payloads.Write((eventName, paramsMap));
418+
#if NETCOREAPP
419+
await _payloads.Writer.WriteAsync((eventName, payload), cancellationToken).ConfigureAwait(ContinueOnCapturedContext);
420+
#else
421+
_payloads.Write((eventName, payload));
377422
return Task.CompletedTask;
378423
#endif
379424
}

‎src/Platform/Microsoft.Testing.Extensions.Telemetry/PACKAGE.md‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,24 @@ This package extends Microsoft.Testing.Platform with:
2020

2121
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.
2222

23+
## AI-agent context
24+
25+
When telemetry is enabled, every usage event includes:
26+
27+
- `is llm`: `true` when the platform's existing environment detector recognizes
28+
an AI agent, otherwise `false`. Detection is heuristic; `false` does not prove
29+
a human invocation. Only the boolean is collected, not the marker values.
30+
- `CopilotAgentSessionId`: the nonempty `COPILOT_AGENT_SESSION_ID`, normalized
31+
to match the .NET SDK's `CopilotAgentSessionId` and Copilot telemetry.
32+
Canonical UUIDs (versions 1-8 with RFC variant, or the nil UUID) are preserved
33+
exactly. Other values become lowercase SHA-256 of their original UTF-8 bytes,
34+
without trimming or case normalization. Missing or empty values produce
35+
`not_present`; a missing telemetry property means collection support is unknown.
36+
37+
These are independent signals, captured for each event before asynchronous
38+
dispatch. Existing platform session IDs and telemetry opt-outs are unchanged.
39+
This does not add fields to application-configured OpenTelemetry traces.
40+
2341
## Documentation
2442

2543
For this extension, see <https://learn.microsoft.com/dotnet/core/testing/microsoft-testing-platform-telemetry>.

‎src/Platform/Microsoft.Testing.Platform/InternalAPI/InternalAPI.Unshipped.txt‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
#nullable enable
2+
const Microsoft.Testing.Platform.Telemetry.TelemetryProperties.IsLLMPropertyName = "is llm" -> string!
3+
const Microsoft.Testing.Platform.Telemetry.TelemetryProperties.CopilotAgentSessionIdPropertyName = "CopilotAgentSessionId" -> string!
24
Microsoft.Testing.Platform.TestHostControllers.TestHostControllersManager.AddDataConsumerWhenControllerStarts<T>(Microsoft.Testing.Platform.Extensions.CompositeExtensionFactory<T!>! compositeServiceFactory) -> void
35
Microsoft.Testing.Platform.TestHostControllers.TestHostControllersManager.AddEnvironmentVariableProviderWhenControllerStarts(System.Func<System.IServiceProvider!, Microsoft.Testing.Platform.Extensions.TestHostControllers.ITestHostEnvironmentVariableProvider!>! factory) -> void
46
*REMOVED*Microsoft.Testing.Platform.TestHostControllers.TestHostProcessInformation.HasExitedGracefully.get -> bool

‎src/Platform/Microsoft.Testing.Platform/Telemetry/TelemetryProperties.cs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@ internal static class TelemetryProperties
99
public const string SessionId = "session id";
1010
public const string ReporterIdPropertyName = "reporter id";
1111
public const string IsCIPropertyName = "is ci";
12+
public const string IsLLMPropertyName = "is llm";
13+
public const string CopilotAgentSessionIdPropertyName = "CopilotAgentSessionId";
1214

1315
public const string VersionValue = "20";
1416

‎test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/TelemetryDisabledTests.cs‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,9 @@ public async Task Telemetry_WhenEnableTelemetryIsFalse_WithTestApplicationOption
2929
.+ Microsoft.Testing.Platform.Telemetry.TelemetryManager DEBUG DOTNET_CLI_TELEMETRY_OPTOUT environment variable: ''
3030
.+ Microsoft.Testing.Platform.Telemetry.TelemetryManager DEBUG Telemetry is 'DISABLED'
3131
""";
32-
await AssertDiagnosticReportAsync(testHostResult, diagPathPattern, diagContentsPattern);
32+
string report = await AssertDiagnosticReportAsync(testHostResult, diagPathPattern, diagContentsPattern);
33+
string content = await File.ReadAllTextAsync(report, TestContext.CancellationToken);
34+
Assert.DoesNotContain("Send telemetry event:", content);
3335
}
3436

3537
private static async Task<string> AssertDiagnosticReportAsync(TestHostResult testHostResult, string diagPathPattern, string diagContentsPattern, string level = "Trace", string flushType = "async")
@@ -73,10 +75,12 @@ public sealed class TestAssetFixture() : TestAssetFixtureBase()
7375
7476
<ItemGroup>
7577
<PackageReference Include="Microsoft.Testing.Platform" Version="$MicrosoftTestingPlatformVersion$" />
78+
<PackageReference Include="Microsoft.Testing.Extensions.Telemetry" Version="$MicrosoftTestingPlatformVersion$" />
7679
</ItemGroup>
7780
</Project>
7881
7982
#file Program.cs
83+
using Microsoft.Testing.Extensions;
8084
using Microsoft.Testing.Platform.Builder;
8185
using Microsoft.Testing.Platform.Capabilities.TestFramework;
8286
using Microsoft.Testing.Platform.Extensions.TestFramework;
@@ -86,6 +90,7 @@ public class Program
8690
public static async Task<int> Main(string[] args)
8791
{
8892
ITestApplicationBuilder builder = await TestApplication.CreateBuilderAsync(args$TelemetryArg$);
93+
builder.AddAppInsightsTelemetryProvider();
8994
builder.RegisterTestFramework(_ => new TestFrameworkCapabilities(), (_,__) => new DummyTestFramework());
9095
using ITestApplication app = await builder.BuildAsync();
9196
return await app.RunAsync();

0 commit comments

Comments
 (0)