Skip to content

Commit 79f01ac

Browse files
JanKrivanekCopilot
andcommitted
Moving the logic from telemetry client to telemetry properties - based on suggestion by @baronfel
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
1 parent a0b6629 commit 79f01ac

5 files changed

Lines changed: 160 additions & 86 deletions

File tree

‎documentation/project-docs/telemetry.md‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -208,8 +208,11 @@ When telemetry is enabled, `CopilotAgentSessionId` records the nonempty
208208
recognized UUIDs are preserved exactly; other values become lowercase SHA-256 hex
209209
of the original UTF-8 bytes, without trimming or case normalization.
210210

211-
The value is captured before each event is queued, so reused MSBuild hosts pick up
212-
the current request's ID. Missing/empty environment values produce `not_present`
211+
`TelemetryCommonProperties` collects and normalizes the value. The sender merges
212+
common, event, and context properties into a snapshot before queueing each event,
213+
without modifying the caller's properties, so reused MSBuild hosts pick up
214+
the current request's ID without recollecting machine-level properties.
215+
Missing/empty environment values produce `not_present`
213216
rather than null, which exporters can drop. A missing telemetry field means collection
214217
support is unknown (for example, an older SDK); `not_present` means no Copilot context
215218
was observed, not proof of a human invocation. A literal `not_present` environment

‎src/Cli/dotnet/Telemetry/TelemetryClient.cs‎

Lines changed: 31 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,9 @@
33

44
using System.Collections.Frozen;
55
using System.Diagnostics;
6-
using System.Text.RegularExpressions;
76
using Microsoft.DotNet.Cli.InternalMicrosoft;
87
using Microsoft.DotNet.Cli.Utils;
98
using Microsoft.DotNet.Configurer;
10-
using Microsoft.DotNet.Utilities;
119

1210
#if MICROSOFT_ENABLE_TELEMETRY_AZURE_MONITOR
1311
using Azure.Monitor.OpenTelemetry.Exporter;
@@ -20,11 +18,10 @@
2018

2119
namespace Microsoft.DotNet.Cli.Telemetry;
2220

23-
public partial class TelemetryClient : ITelemetryClient
21+
public class TelemetryClient : ITelemetryClient
2422
{
25-
private const string CopilotAgentSessionIdPropertyName = "CopilotAgentSessionId";
2623
private static FrozenDictionary<string, string?> s_commonProperties = [];
27-
private readonly IEnvironmentProvider _environmentProvider;
24+
private readonly TelemetryCommonProperties _commonPropertiesCollector;
2825
private Task? _trackEventTask;
2926

3027
private static readonly MeterProviderBuilder s_metricsProviderBuilder;
@@ -166,7 +163,8 @@ public TelemetryClient() : this(null) { }
166163

167164
public TelemetryClient(string? sessionId, IEnvironmentProvider? environmentProvider = null)
168165
{
169-
_environmentProvider = environmentProvider ?? new EnvironmentProvider();
166+
environmentProvider ??= new EnvironmentProvider();
167+
_commonPropertiesCollector = new TelemetryCommonProperties(environmentProvider: environmentProvider);
170168

171169
// This is some kind of special condition for MSBuild-related tests.
172170
if (DisabledForTests)
@@ -177,7 +175,7 @@ public TelemetryClient(string? sessionId, IEnvironmentProvider? environmentProvi
177175
Instance = this;
178176
IsInitialized = true;
179177

180-
Enabled = !_environmentProvider.GetEnvironmentVariableAsBool(EnvironmentVariableNames.TELEMETRY_OPTOUT,
178+
Enabled = !environmentProvider.GetEnvironmentVariableAsBool(EnvironmentVariableNames.TELEMETRY_OPTOUT,
181179
// When building in the official CI pipeline, this makes the complier enable telemetry by default. Otherwise, it is disabled.
182180
// It is the reason tests don't send telemetry, because we don't run tests in the official CI pipeline.
183181
defaultValue: CompileOptions.TelemetryOptOutDefault);
@@ -203,10 +201,10 @@ public TelemetryClient(string? sessionId, IEnvironmentProvider? environmentProvi
203201

204202
var initialSessionId = !string.IsNullOrEmpty(sessionId)
205203
? sessionId
206-
: _environmentProvider.GetEnvironmentVariable(EnvironmentVariableNames.DOTNET_CLI_TELEMETRY_SESSIONID);
204+
: environmentProvider.GetEnvironmentVariable(EnvironmentVariableNames.DOTNET_CLI_TELEMETRY_SESSIONID);
207205

208206
CurrentSessionId ??= !string.IsNullOrEmpty(initialSessionId) ? initialSessionId : Guid.NewGuid().ToString();
209-
s_commonProperties = new TelemetryCommonProperties().GetTelemetryCommonProperties(CurrentSessionId);
207+
s_commonProperties = _commonPropertiesCollector.GetTelemetryCommonProperties(CurrentSessionId);
210208
}
211209

212210
/// <summary>
@@ -350,28 +348,25 @@ public static void WriteLogIfNecessary()
350348

351349
public void TrackEvent(string eventName, IDictionary<string, string?>? properties)
352350
{
353-
if (!Enabled)
351+
if (!Enabled || MakeTags(properties) is not { } tags)
354352
{
355353
return;
356354
}
357355

358-
// Capture before queueing: a reused MSBuild host can change its environment for the next request.
359-
string copilotAgentSessionId = GetCopilotAgentSessionId();
360-
361356
// Continue the task in different threads.
362357
_trackEventTask = _trackEventTask == null
363-
? Task.Run(() => TrackEventTask(eventName, properties, copilotAgentSessionId))
364-
: _trackEventTask.ContinueWith(_ => TrackEventTask(eventName, properties, copilotAgentSessionId));
358+
? Task.Run(() => TrackEventTask(eventName, tags))
359+
: _trackEventTask.ContinueWith(_ => TrackEventTask(eventName, tags));
365360
}
366361

367362
public void ThreadBlockingTrackEvent(string eventName, IDictionary<string, string?>? properties)
368363
{
369-
if (!Enabled)
364+
if (!Enabled || MakeTags(properties) is not { } tags)
370365
{
371366
return;
372367
}
373368

374-
TrackEventTask(eventName, properties, GetCopilotAgentSessionId());
369+
TrackEventTask(eventName, tags);
375370
}
376371

377372
internal void WaitForPendingEvents()
@@ -382,48 +377,35 @@ internal void WaitForPendingEvents()
382377
internal static void WaitForInternalMicrosoftDetection() =>
383378
s_internalMicrosoftTelemetry.WaitForCompletion();
384379

385-
private string GetCopilotAgentSessionId()
380+
private static void TrackEventTask(string eventName, ActivityTagsCollection tags)
386381
{
387-
string? sessionId = _environmentProvider.GetEnvironmentVariable(EnvironmentVariableNames.COPILOT_AGENT_SESSION_ID);
388-
if (string.IsNullOrEmpty(sessionId))
389-
{
390-
return "not_present";
391-
}
392-
393-
return CopilotSessionUuidPattern().IsMatch(sessionId) ? sessionId : Sha256Hasher.Hash(sessionId);
382+
var @event = new ActivityEvent($"dotnet/cli/{eventName}", tags: tags);
383+
Activity.Current?.AddEvent(@event);
394384
}
395385

396-
// Match Copilot's hash_string_if_not_uuid: canonical UUID versions 1-8 with RFC variant, or nil.
397-
[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",
398-
RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)]
399-
private static partial Regex CopilotSessionUuidPattern();
400-
401-
private static void TrackEventTask(string eventName, IDictionary<string, string?>? properties, string copilotAgentSessionId)
386+
private ActivityTagsCollection? MakeTags(IDictionary<string, string?>? eventProperties)
402387
{
403388
try
404389
{
405-
properties ??= new Dictionary<string, string?>();
406-
properties.Add("event id", Guid.NewGuid().ToString());
407-
var @event = new ActivityEvent($"dotnet/cli/{eventName}", tags: MakeTags(properties, copilotAgentSessionId));
408-
Activity.Current?.AddEvent(@event);
390+
// Snapshot before queueing: callers and reused MSBuild hosts can change their properties or environment.
391+
var contextProperties = _commonPropertiesCollector.GetTelemetryContextProperties();
392+
var common = s_commonProperties
393+
.Where(p => !contextProperties.ContainsKey(p.Key))
394+
.Select(p => new KeyValuePair<string, object?>(p.Key, p.Value));
395+
var properties = (eventProperties ?? new Dictionary<string, string?>())
396+
.Where(p => p.Value is not null && !contextProperties.ContainsKey(p.Key))
397+
.Select(p => new KeyValuePair<string, object?>(p.Key, p.Value))
398+
.OrderBy(p => p.Key);
399+
var context = contextProperties
400+
.Select(p => new KeyValuePair<string, object?>(p.Key, p.Value));
401+
ActivityTagsCollection tags = [.. common, .. properties, .. context];
402+
tags.Add("event id", Guid.NewGuid().ToString());
403+
return tags;
409404
}
410405
catch (Exception e)
411406
{
412407
Debug.Fail(e.ToString());
408+
return null;
413409
}
414410
}
415-
416-
private static ActivityTagsCollection MakeTags(IDictionary<string, string?> eventProperties, string copilotAgentSessionId)
417-
{
418-
var common = s_commonProperties
419-
.Select(p => new KeyValuePair<string, object?>(p.Key, p.Value));
420-
var properties = eventProperties
421-
.Where(p => p.Value is not null && p.Key != CopilotAgentSessionIdPropertyName)
422-
.Select(p => new KeyValuePair<string, object?>(p.Key, p.Value))
423-
.OrderBy(p => p.Key);
424-
ActivityTagsCollection tags = [.. common, .. properties];
425-
tags.Add(CopilotAgentSessionIdPropertyName, copilotAgentSessionId);
426-
427-
return tags;
428-
}
429411
}

‎src/Cli/dotnet/Telemetry/TelemetryCommonProperties.cs‎

Lines changed: 31 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
using System.Collections.Frozen;
55
using System.Net.NetworkInformation;
6+
using System.Text.RegularExpressions;
67
using Microsoft.DotNet.Cli.Utils;
78
using Microsoft.DotNet.Configurer;
89
using Microsoft.DotNet.Utilities;
@@ -11,16 +12,18 @@
1112

1213
namespace Microsoft.DotNet.Cli.Telemetry;
1314

14-
internal class TelemetryCommonProperties(
15+
internal partial class TelemetryCommonProperties(
1516
Func<string>? getCurrentDirectory = null,
1617
Func<string, string>? hasher = null,
1718
Func<string?>? getMACAddress = null,
1819
Func<string>? getDeviceId = null,
1920
IDockerContainerDetector? dockerContainerDetector = null,
2021
IUserLevelCacheWriter? userLevelCacheWriter = null,
2122
ICIEnvironmentDetector? ciEnvironmentDetector = null,
22-
ILLMEnvironmentDetector? llmEnvironmentDetector = null)
23+
ILLMEnvironmentDetector? llmEnvironmentDetector = null,
24+
IEnvironmentProvider? environmentProvider = null)
2325
{
26+
private readonly IEnvironmentProvider _environmentProvider = environmentProvider ?? new EnvironmentProvider();
2427
private readonly IDockerContainerDetector _dockerContainerDetector = dockerContainerDetector ?? new DockerContainerDetectorForTelemetry();
2528
private readonly ICIEnvironmentDetector _ciEnvironmentDetector = ciEnvironmentDetector ?? new CIEnvironmentDetectorForTelemetry();
2629
private readonly ILLMEnvironmentDetector _llmEnvironmentDetector = llmEnvironmentDetector ?? new LLMEnvironmentDetectorForTelemetry(environmentProvider: null);
@@ -48,6 +51,7 @@ internal class TelemetryCommonProperties(
4851
private const string LibcRelease = "Libc Release";
4952
private const string LibcVersion = "Libc Version";
5053
private const string SessionId = "SessionId";
54+
private const string CopilotAgentSessionId = "CopilotAgentSessionId";
5155
private const string CI = "Continuous Integration";
5256
private const string LLM = "llm";
5357
private const string TelemetryProfileEnvironmentVariable = "DOTNET_CLI_TELEMETRY_PROFILE";
@@ -78,8 +82,33 @@ internal class TelemetryCommonProperties(
7882
{ LibcRelease, ExternalTelemetryProperties.GetLibcRelease() },
7983
{ LibcVersion, ExternalTelemetryProperties.GetLibcVersion() },
8084
{ SessionId, currentSessionId }
85+
}.Concat(GetTelemetryContextProperties()).ToFrozenDictionary(StringComparer.OrdinalIgnoreCase);
86+
87+
/// <summary>
88+
/// Captures common properties that can change between events in a reused host,
89+
/// without recollecting the cached machine-level properties.
90+
/// </summary>
91+
public FrozenDictionary<string, string?> GetTelemetryContextProperties() => new Dictionary<string, string?>
92+
{
93+
{ CopilotAgentSessionId, GetCopilotAgentSessionId() }
8194
}.ToFrozenDictionary(StringComparer.OrdinalIgnoreCase);
8295

96+
private string GetCopilotAgentSessionId()
97+
{
98+
string? sessionId = _environmentProvider.GetEnvironmentVariable(EnvironmentVariableNames.COPILOT_AGENT_SESSION_ID);
99+
if (string.IsNullOrEmpty(sessionId))
100+
{
101+
return "not_present";
102+
}
103+
104+
return CopilotSessionUuidPattern().IsMatch(sessionId) ? sessionId : _hasher(sessionId);
105+
}
106+
107+
// Match Copilot's hash_string_if_not_uuid: canonical UUID versions 1-8 with RFC variant, or nil.
108+
[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",
109+
RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)]
110+
private static partial Regex CopilotSessionUuidPattern();
111+
83112
private string GetMachineId()
84113
{
85114
try

0 commit comments

Comments
 (0)