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
21 changes: 21 additions & 0 deletions documentation/project-docs/telemetry.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
- [How to Control Telemetry](#how-to-control-telemetry)
- [CLI Activity Duration Metrics](#cli-activity-duration-metrics)
- [Common Properties Collected](#common-properties-collected)
- [Copilot session correlation](#copilot-session-correlation)
- [Telemetry Events](#telemetry-events)
- [Core CLI Events](#core-cli-events)
- [Test Events](#test-events)
Expand Down Expand Up @@ -197,6 +198,26 @@ Every telemetry event automatically includes these common properties:
| **Libc Release** | Libc release information | Libc release version |
| **Libc Version** | Libc version information | Libc version number |
| **SessionId** | Unique session identifier | GUID or CI-specific correlation identifier |
| **CopilotAgentSessionId** | Executing Copilot session ID, normalized to match Copilot telemetry, or `not_present` when unavailable | UUID, 64-character lowercase SHA-256 digest, or `not_present` |

### Copilot session correlation

When telemetry is enabled, `CopilotAgentSessionId` records the nonempty
`COPILOT_AGENT_SESSION_ID` using
[Copilot's normalization](https://github.com/github/copilot-agent-runtime/blob/1fc45d2c2a0a978ebbd068e0eec79715cf5dd417/src/native/primitives/crypto_helpers.rs#L23-L62):
recognized UUIDs are preserved exactly; other values become lowercase SHA-256 hex
of the original UTF-8 bytes, without trimming or case normalization.

`TelemetryCommonProperties` collects and normalizes the value. The sender merges
common, event, and context properties into a snapshot before queueing each event,
without modifying the caller's properties, so reused MSBuild hosts pick up
the current request's ID without recollecting machine-level properties.
Missing/empty environment values produce `not_present`
rather than null, which exporters can drop. A missing telemetry field means collection
support is unknown (for example, an older SDK); `not_present` means no Copilot context
was observed, not proof of a human invocation. A literal `not_present` environment
value is hashed like any other custom ID. Existing telemetry opt-out settings and
.NET's own `SessionId` remain unchanged.

### Microsoft-internal user classification

Expand Down
56 changes: 35 additions & 21 deletions src/Cli/dotnet/Telemetry/TelemetryClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ namespace Microsoft.DotNet.Cli.Telemetry;
public class TelemetryClient : ITelemetryClient
{
private static FrozenDictionary<string, string?> s_commonProperties = [];
private readonly TelemetryCommonProperties _commonPropertiesCollector;
private Task? _trackEventTask;

private static readonly MeterProviderBuilder s_metricsProviderBuilder;
Expand Down Expand Up @@ -162,6 +163,9 @@ public TelemetryClient() : this(null) { }

public TelemetryClient(string? sessionId, IEnvironmentProvider? environmentProvider = null)
{
environmentProvider ??= new EnvironmentProvider();
_commonPropertiesCollector = new TelemetryCommonProperties(environmentProvider: environmentProvider);

// This is some kind of special condition for MSBuild-related tests.
if (DisabledForTests)
{
Expand All @@ -171,7 +175,6 @@ public TelemetryClient(string? sessionId, IEnvironmentProvider? environmentProvi
Instance = this;
IsInitialized = true;

environmentProvider ??= new EnvironmentProvider();
Enabled = !environmentProvider.GetEnvironmentVariableAsBool(EnvironmentVariableNames.TELEMETRY_OPTOUT,
// When building in the official CI pipeline, this makes the complier enable telemetry by default. Otherwise, it is disabled.
// It is the reason tests don't send telemetry, because we don't run tests in the official CI pipeline.
Expand Down Expand Up @@ -201,7 +204,7 @@ public TelemetryClient(string? sessionId, IEnvironmentProvider? environmentProvi
: environmentProvider.GetEnvironmentVariable(EnvironmentVariableNames.DOTNET_CLI_TELEMETRY_SESSIONID);

CurrentSessionId ??= !string.IsNullOrEmpty(initialSessionId) ? initialSessionId : Guid.NewGuid().ToString();
s_commonProperties = new TelemetryCommonProperties().GetTelemetryCommonProperties(CurrentSessionId);
s_commonProperties = _commonPropertiesCollector.GetTelemetryCommonProperties(CurrentSessionId);
}

/// <summary>
Expand Down Expand Up @@ -350,10 +353,12 @@ public void TrackEvent(string eventName, IDictionary<string, string?>? propertie
return;
}

var tags = MakeTags(properties); // Capture before queueing: a later request can change the environment.

// Continue the task in different threads.
_trackEventTask = _trackEventTask == null
? Task.Run(() => TrackEventTask(eventName, properties))
: _trackEventTask.ContinueWith(_ => TrackEventTask(eventName, properties));
? Task.Run(() => TrackEventTask(eventName, tags))
: _trackEventTask.ContinueWith(_ => TrackEventTask(eventName, tags));
}

public void ThreadBlockingTrackEvent(string eventName, IDictionary<string, string?>? properties)
Expand All @@ -363,7 +368,7 @@ public void ThreadBlockingTrackEvent(string eventName, IDictionary<string, strin
return;
}

TrackEventTask(eventName, properties);
TrackEventTask(eventName, MakeTags(properties));
}

internal void WaitForPendingEvents()
Expand All @@ -374,29 +379,38 @@ internal void WaitForPendingEvents()
internal static void WaitForInternalMicrosoftDetection() =>
s_internalMicrosoftTelemetry.WaitForCompletion();

private static void TrackEventTask(string eventName, IDictionary<string, string?>? properties)
private static void TrackEventTask(string eventName, ActivityTagsCollection? tags)
{
try
if (tags is not null)
{
properties ??= new Dictionary<string, string?>();
properties.Add("event id", Guid.NewGuid().ToString());
var @event = new ActivityEvent($"dotnet/cli/{eventName}", tags: MakeTags(properties));
var @event = new ActivityEvent($"dotnet/cli/{eventName}", tags: tags);
Activity.Current?.AddEvent(@event);
}
}

private ActivityTagsCollection? MakeTags(IDictionary<string, string?>? eventProperties)
{
try
{
// Snapshot before queueing: callers and reused MSBuild hosts can change their properties or environment.
var contextProperties = _commonPropertiesCollector.GetTelemetryContextProperties();
var common = s_commonProperties
.Where(p => !contextProperties.ContainsKey(p.Key))
.Select(p => new KeyValuePair<string, object?>(p.Key, p.Value));
var properties = (eventProperties ?? new Dictionary<string, string?>())
.Where(p => p.Value is not null && !contextProperties.ContainsKey(p.Key))
.Select(p => new KeyValuePair<string, object?>(p.Key, p.Value))
.OrderBy(p => p.Key);
var context = contextProperties
.Select(p => new KeyValuePair<string, object?>(p.Key, p.Value));
ActivityTagsCollection tags = [.. common, .. properties, .. context];
tags.Add("event id", Guid.NewGuid().ToString());
return tags;
}
catch (Exception e)
{
Debug.Fail(e.ToString());
return null;
}
}

private static ActivityTagsCollection MakeTags(IDictionary<string, string?> eventProperties)
{
var common = s_commonProperties
.Select(p => new KeyValuePair<string, object?>(p.Key, p.Value));
var properties = eventProperties
.Where(p => p.Value is not null)
.Select(p => new KeyValuePair<string, object?>(p.Key, p.Value))
.OrderBy(p => p.Key);
return [.. common, .. properties];
}
}
33 changes: 31 additions & 2 deletions src/Cli/dotnet/Telemetry/TelemetryCommonProperties.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

using System.Collections.Frozen;
using System.Net.NetworkInformation;
using System.Text.RegularExpressions;
using Microsoft.DotNet.Cli.Utils;
using Microsoft.DotNet.Configurer;
using Microsoft.DotNet.Utilities;
Expand All @@ -11,16 +12,18 @@

namespace Microsoft.DotNet.Cli.Telemetry;

internal class TelemetryCommonProperties(
internal partial class TelemetryCommonProperties(
Func<string>? getCurrentDirectory = null,
Func<string, string>? hasher = null,
Func<string?>? getMACAddress = null,
Func<string>? getDeviceId = null,
IDockerContainerDetector? dockerContainerDetector = null,
IUserLevelCacheWriter? userLevelCacheWriter = null,
ICIEnvironmentDetector? ciEnvironmentDetector = null,
ILLMEnvironmentDetector? llmEnvironmentDetector = null)
ILLMEnvironmentDetector? llmEnvironmentDetector = null,
IEnvironmentProvider? environmentProvider = null)
{
private readonly IEnvironmentProvider _environmentProvider = environmentProvider ?? new EnvironmentProvider();
private readonly IDockerContainerDetector _dockerContainerDetector = dockerContainerDetector ?? new DockerContainerDetectorForTelemetry();
private readonly ICIEnvironmentDetector _ciEnvironmentDetector = ciEnvironmentDetector ?? new CIEnvironmentDetectorForTelemetry();
private readonly ILLMEnvironmentDetector _llmEnvironmentDetector = llmEnvironmentDetector ?? new LLMEnvironmentDetectorForTelemetry(environmentProvider: null);
Expand Down Expand Up @@ -48,6 +51,7 @@ internal class TelemetryCommonProperties(
private const string LibcRelease = "Libc Release";
private const string LibcVersion = "Libc Version";
private const string SessionId = "SessionId";
private const string CopilotAgentSessionId = "CopilotAgentSessionId";
private const string CI = "Continuous Integration";
private const string LLM = "llm";
private const string TelemetryProfileEnvironmentVariable = "DOTNET_CLI_TELEMETRY_PROFILE";
Expand Down Expand Up @@ -78,8 +82,33 @@ internal class TelemetryCommonProperties(
{ LibcRelease, ExternalTelemetryProperties.GetLibcRelease() },
{ LibcVersion, ExternalTelemetryProperties.GetLibcVersion() },
{ SessionId, currentSessionId }
}.Concat(GetTelemetryContextProperties()).ToFrozenDictionary(StringComparer.OrdinalIgnoreCase);

/// <summary>
/// Captures common properties that can change between events in a reused host,
/// without recollecting the cached machine-level properties.
/// </summary>
public FrozenDictionary<string, string?> GetTelemetryContextProperties() => new Dictionary<string, string?>
{
{ CopilotAgentSessionId, GetCopilotAgentSessionId() }
}.ToFrozenDictionary(StringComparer.OrdinalIgnoreCase);

private string GetCopilotAgentSessionId()
{
string? sessionId = _environmentProvider.GetEnvironmentVariable(EnvironmentVariableNames.COPILOT_AGENT_SESSION_ID);
if (string.IsNullOrEmpty(sessionId))
{
return "not_present";
}

return CopilotSessionUuidPattern().IsMatch(sessionId) ? sessionId : _hasher(sessionId);
}

// Match Copilot's hash_string_if_not_uuid: canonical UUID versions 1-8 with RFC variant, or nil.
[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 CopilotSessionUuidPattern();

private string GetMachineId()
{
try
Expand Down
1 change: 1 addition & 0 deletions src/Common/EnvironmentVariableNames.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ internal static class EnvironmentVariableNames
public static readonly string DOTNET_SKIP_WORKLOAD_INTEGRITY_CHECK = nameof(DOTNET_SKIP_WORKLOAD_INTEGRITY_CHECK);
public static readonly string DOTNET_CLI_ENABLEAOT = nameof(DOTNET_CLI_ENABLEAOT);
public static readonly string DOTNET_CLI_TELEMETRY_SESSIONID = nameof(DOTNET_CLI_TELEMETRY_SESSIONID);
public static readonly string COPILOT_AGENT_SESSION_ID = nameof(COPILOT_AGENT_SESSION_ID);
public static readonly string DOTNET_CLI_CONSOLE_USE_DEFAULT_ENCODING = nameof(DOTNET_CLI_CONSOLE_USE_DEFAULT_ENCODING);
// Telemetry logging/debug/testing.
public static readonly string DOTNET_CLI_TELEMETRY_STORAGE_PATH = nameof(DOTNET_CLI_TELEMETRY_STORAGE_PATH);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,9 @@ public void ItUsesSeededTelemetrySessionId()
environmentProvider
.Setup(p => p.GetEnvironmentVariable(EnvironmentVariableNames.DOTNET_CLI_TELEMETRY_SESSIONID))
.Returns(sessionId);
environmentProvider
.Setup(p => p.GetEnvironmentVariable(EnvironmentVariableNames.COPILOT_AGENT_SESSION_ID))
.Returns((string)null);

_ = new TelemetryClient(sessionId: null, environmentProvider: environmentProvider.Object);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,9 @@ bool telemetrySecondRunShouldBeEnabled
_environmentProvider
.Setup(p => p.GetEnvironmentVariableAsBool("DOTNET_CLI_TELEMETRY_OPTOUT", It.IsAny<bool>()))
.Returns(DOTNET_CLI_TELEMETRY_OPTOUT);
_environmentProvider
.Setup(p => p.GetEnvironmentVariable("COPILOT_AGENT_SESSION_ID"))
.Returns((string)null);
_environmentProvider
.Setup(p => p.GetEnvironmentVariableAsBool("DOTNET_NOLOGO", It.IsAny<bool>()))
.Returns(DOTNET_NOLOGO);
Expand Down
Loading
Loading