Repository navigation
feat: add process-wide authenticated user id attribution - #31
Conversation
There was a problem hiding this comment.
Pull request overview
Adds a process-wide, runtime-mutable authenticated user identifier so all telemetry emitted by this package (Desktop, WASM, and FileTelemetry) can be attributed to a signed-in account via the native Application Insights ai.user.authUserId tag / user_AuthenticatedId column.
Changes:
- Introduces
TelemetryUserContext.AuthenticatedUserId(ambient, thread-safe) and wires it throughITelemetry.AuthenticatedUserIdacross implementations/adapters/DI. - Desktop: stamps per-item context via a new
AuthenticatedUserTelemetryInitializer; WASM: injectsai.user.authUserIdinto REST envelope tags; FileTelemetry: conditionally emits a top-levelAuthenticatedUserIdJSON field. - Adds unit + WASM runtime test coverage and updates specs/docs.
Reviewed changes
Copilot reviewed 18 out of 18 changed files in this pull request and generated 4 comments.
Show a summary per file
| File | Description |
|---|---|
| src/Uno.DevTools.Telemetry/WasmHttpSender.cs | Factors tag creation and conditionally emits ai.user.authUserId in WASM envelopes; exposes envelope builders for tests. |
| src/Uno.DevTools.Telemetry/TelemetryUserContext.cs | New ambient, process-wide authenticated user id store with env-var seeding + normalization. |
| src/Uno.DevTools.Telemetry/TelemetryServiceCollectionExtensions.cs | Ensures DI-open-generic telemetry wrapper delegates the new property. |
| src/Uno.DevTools.Telemetry/TelemetryAdapter.cs | Delegates the new property through the adapter. |
| src/Uno.DevTools.Telemetry/Telemetry.cs | Exposes the new property and registers a telemetry initializer to stamp items on desktop. |
| src/Uno.DevTools.Telemetry/ScopedTelemetry.cs | Delegates the new property through scoped telemetry. |
| src/Uno.DevTools.Telemetry/ITelemetry.cs | Adds AuthenticatedUserId to the public interface (breaking change). |
| src/Uno.DevTools.Telemetry/FileTelemetry.cs | Delegates property + conditionally emits AuthenticatedUserId field while preserving previous output when unset. |
| src/Uno.DevTools.Telemetry/AuthenticatedUserTelemetryInitializer.cs | New per-item initializer that stamps Context.User.AuthenticatedUserId from the ambient store. |
| src/Uno.DevTools.Telemetry.WasmTests/Uno.DevTools.Telemetry.WasmTests/TelemetryWasmTests.cs | Adds a WASM runtime test covering set → track → clear behavior. |
| src/Uno.DevTools.Telemetry.Tests/WasmHttpSenderAuthenticatedUserTests.cs | New unit tests asserting WASM REST tags include/omit ai.user.authUserId. |
| src/Uno.DevTools.Telemetry.Tests/TelemetryUserContextTests.cs | New unit tests for ambient store semantics and env-var seed helper. |
| src/Uno.DevTools.Telemetry.Tests/TelemetryGenericDiTests.cs | Adds DI end-to-end test verifying setting via ITelemetry<T> affects file output. |
| src/Uno.DevTools.Telemetry.Tests/FileTelemetryAuthenticatedUserTests.cs | New unit tests validating conditional JSON field emission and late-setting behavior. |
| src/Uno.DevTools.Telemetry.Tests/AuthenticatedUserTelemetryInitializerTests.cs | New unit tests for initializer stamping and value changes between items. |
| specs/002-authenticated-user-id/spec.md | New feature spec documenting requirements, edge cases, and success criteria. |
| docs/usage.md | Documents how to set/clear the authenticated user id and the env-var seed. |
| AGENTS.md | Updates WASM runtime test count and list to include the new test. |
💡 Add a code-review agent skill for context-aware, tailored reviews. Learn more in the docs.
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 18 out of 18 changed files in this pull request and generated no new comments.
Suppressed comments (2)
src/Uno.DevTools.Telemetry/ITelemetry.cs:26
- The remarks mention normalization for null/empty/whitespace, but the implementation also normalizes over-long values (>1024 chars) to null (see TelemetryUserContext.MaxAuthenticatedUserIdLength/Normalize). Please document the max-length normalization here as well so the interface contract matches behavior.
/// <remarks>
/// This value is process-wide ambient state: setting it through any <see cref="ITelemetry"/>
/// instance affects every instance in the process
/// (see <see cref="TelemetryUserContext.AuthenticatedUserId"/>).
/// Set it when a user signs in; set it to <see langword="null"/> when the user signs out.
/// Null, empty or whitespace values are normalized to <see langword="null"/>.
/// </remarks>
src/Uno.DevTools.Telemetry/ITelemetry.cs:28
- This PR adds a new member to ITelemetry (breaking change for external implementers). version.json currently targets the 1.x line ("1.4-dev..."), so merging/publishing without a major-version bump would ship an interface break in a minor version. Please coordinate a 2.0 bump (or explicitly document/accept the break for 1.x before release).
public interface ITelemetry
{
bool Enabled { get; }
/// <summary>
/// Gets or sets the authenticated user id attributed to telemetry emitted by this process.
/// </summary>
/// <remarks>
/// This value is process-wide ambient state: setting it through any <see cref="ITelemetry"/>
/// instance affects every instance in the process
/// (see <see cref="TelemetryUserContext.AuthenticatedUserId"/>).
/// Set it when a user signs in; set it to <see langword="null"/> when the user signs out.
/// Null, empty or whitespace values are normalized to <see langword="null"/>.
/// </remarks>
string? AuthenticatedUserId { get; set; }
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 18 out of 18 changed files in this pull request and generated no new comments.
Suppressed comments (1)
src/Uno.DevTools.Telemetry.Tests/TelemetryGenericDiTests.cs:53
- This test creates a temp file and a ServiceProvider but never disposes the provider or deletes the temp file. Disposing the provider and cleaning up the temp file in the finally block avoids leaking resources across the test run (and matches the intent of using temp files).
var tempFile = Path.GetTempFileName();
Environment.SetEnvironmentVariable("UNO_PLATFORM_TELEMETRY_FILE", tempFile);
try
{
IServiceCollection services = new ServiceCollection();
services.AddTelemetry();
var provider = services.BuildServiceProvider();
var telemetry = provider.GetRequiredService<ITelemetry<MyContext>>();
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 14 out of 14 changed files in this pull request and generated no new comments.
Suppressed comments (2)
src/Uno.DevTools.Telemetry/TelemetryUserContext.cs:85
- GetEnvironmentSeed() catch block calls LogDiagnostic(), but the preceding comment notes that a throwing Trace listener can poison the type initializer. If LogDiagnostic throws inside this catch, the exception will still escape and defeat the poisoning guard. Consider wrapping the diagnostic call in its own try/catch (or avoid Trace logging here) so GetEnvironmentSeed() cannot throw under any circumstances.
// exception (SecurityException from the env read, but also a throwing Trace listener
// in LogDiagnostic above) would poison the type forever — TypeInitializationException
// on every subsequent access, from inside consumer sign-in code. Degrade to unseeded.
LogDiagnostic($"Authenticated user id environment seed failed: {e.Message}");
return null;
specs/002-authenticated-user-id/spec.md:30
- This spec states the change is purely additive with no ITelemetry API change, but the PR description states ITelemetry gains a new member and is a breaking change. The current codebase also shows ITelemetry has no AuthenticatedUserId property. Please reconcile the PR description/spec so release/versioning decisions aren’t made on incorrect assumptions.
- **Purely additive public API** — no change to `ITelemetry` or any other existing public type, so
external implementers and callers are unaffected. (This deviates from the originating issue's
sketch, which suggested a member on `ITelemetry`; see Key Design Decisions.)
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 14 out of 14 changed files in this pull request and generated no new comments.
Suppressed comments (1)
Previously missed (1) — in code that hasn't changed since the last review.
src/Uno.DevTools.Telemetry/WasmHttpSender.cs:56
- The new try/catch blocks rely on LogFailure to record diagnostics, but LogFailure itself isn’t protected against exceptions from Debug/Trace listeners. A throwing TraceListener would make the catch block throw (undoing the “telemetry must never fault the app” guarantee) and could still produce unobserved task exceptions. Consider wrapping the Debug/Trace writes inside LogFailure in a try/catch (similar to TelemetryUserContext.LogDiagnostic) so logging is best-effort and never escapes.
catch (Exception ex)
{
LogFailure("WASM telemetry event envelope failed", ex);
}
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 14 out of 14 changed files in this pull request and generated no new comments.
Suppressed comments (2)
Previously missed (1) — in code that hasn't changed since the last review.
src/Uno.DevTools.Telemetry/WasmHttpSender.cs:56
- The new catch block calls LogFailure, but LogFailure itself isn’t exception-safe (it calls Debug/Trace directly). If a custom TraceListener throws, this catch can rethrow and you’re back to an unobserved exception in the fire-and-forget task, contradicting the “telemetry must never fault the app” policy. Consider wrapping the LogFailure call in a try/catch (or making LogFailure internally swallow listener failures, similar to TelemetryUserContext.LogDiagnostic).
This issue also appears on line 75 of the same file.
catch (Exception ex)
{
LogFailure("WASM telemetry event envelope failed", ex);
}
src/Uno.DevTools.Telemetry/WasmHttpSender.cs:78
- Same issue as SendEventAsync: this catch block calls LogFailure, but LogFailure isn’t guarded against exceptions from Trace/Debug listeners. A throwing listener would let an exception escape this catch and become unobserved in the discarded Task. Wrap the LogFailure call in a try/catch (or harden LogFailure) so the catch block can’t throw.
catch (Exception ex)
{
LogFailure("WASM telemetry exception envelope failed", ex);
}
🧑⚖️ Seven-agent review panelSeven independent reviewer lenses — architect, security, skeptic, quality, operability, contract, performance — were run against this PR. Consolidated below.
Verdict: fix-first (worst-case across the panel)
No blockers. The feature is well-reasoned, additive, and clean on the concurrency/perf front. The fix-first verdict rides on one under-tested correctness claim plus a cluster of test-coverage and maintainability gaps — all inexpensive to close. 🔴 HighH1 · Drain-time stamping (EC-1) is asserted by prose, not proven by any test — H2 · H3 · Env-seed "read once at type init" is a leaky, in-process-untestable abstraction — 🟠 MediumM1 · M2 · WASM runtime test verifies nothing about the envelope — M3 · Normalization boundary is UTF-16-code-unit based and only ASCII-tested — M4 · Exception-shape byte-identity is not snapshot-tested — M5 · M6 · Process-wide single-identity ceiling; no scoped/AsyncLocal escape hatch — 🟡 Low
ℹ️ Confirmed good
Recommended path to green
🤖 Generated with Claude Code — seven-agent review panel |
carldebilly
left a comment
There was a problem hiding this comment.
Review summary
Verdict: fix-first. No blockers. 2 high, 8 medium, 6 low, 3 style nits, plus 9 lower-confidence signals listed at the bottom.
This round worked from a local checkout of the branch, which settles several items the previous round could only assume:
- H1 (drain-time stamping): confirmed, and now demonstrable.
TelemetryClient.Initializeloops initializers synchronously, andTrackEventTaskcalls_client.TrackEventfrom inside the CAS-chained continuation, so stamping does happen at drain. A second mechanism makes it worse: the chain is rooted atTask.Run(InitializeTelemetry)(file I/O), so startup events drain after sign-in. See the comment onTelemetryUserContext.cs:23. - M1 (
LogFailure): the leak half is refuted.LogFailurelogsexception.Messageonly, never the envelope or the id, and no failure path onSendAsynccarries the id in its message. The throw half is still open, seeWasmHttpSender.cs:56. - M3 (surrogate pairs): false positive. The cap and the Application Insights limit are both expressed in UTF-16 code units, and an over-limit value normalizes to
nullrather than truncating, so no pair can be split. - H2 (duplicated tag literal): largely refuted, no action recommended.
ai.user.authUserIdappears exactly once in product code (WasmHttpSender.cs:170); the desktop path goes through the SDK typed property. The other occurrences are test assertions, which should hardcode the wire key rather than reference a constant they exist to pin. - The environment-variable question raised on
TelemetryUserContext.cs:63: settled on facts. EveryUNO_*variable read in this package was enumerated:OPTOUT,TELEMETRY_FILE,TELEMETRY_PROFILE, and the persistence-channel debug flag. There is no pre-existing user-id-via-environment debug affordance here, so the seed is a new contract rather than reuse of an existing one. Whether it is desirable is the open question, seeTelemetryUserContext.cs:26.
Two decisions, then mechanical work
Only two findings need a decision rather than a patch:
- The stated invariant and the actual behaviour disagree.
TelemetryUserContext.cs:21-23promises the failure direction is neverwrong user; drain-time stamping can attribute an in-flight event to whoever signed in before it drained. Capture-at-enqueue is the recommended direction because server-side join fidelity on the account id is the whole point of the feature, but it changes sender arities and contradicts theno arity changesclaim in the PR description. The alternative is to correct the comment and EC-1 and add the concurrency test. Either is defensible; shipping both the claim and the behaviour is not. - The fate of the environment seed. Removing it, gating it behind an explicit opt-in call, or consuming-and-clearing it are all coherent, but the choice should be made before the name is published, because this repo pushes a dev package to nuget.org on every push to
main.
Everything else is mechanical and costed in the individual comments, each of which names its knock-on edits so the work can be done in one pass.
Not anchored to a line
c24d5cf remains in the branch as feat!: with a BREAKING CHANGE: ITelemetry gains an AuthenticatedUserId property trailer, for a change e6f5349 and 3565cf1 fully reverted. History on main uses merge commits, the commit-format check validates shape only, and NerdBank.GitVersioning reads version.json and ignores commit messages, so main would silently carry a breaking-change record against a package that breaks nothing. Squash-merging with the current (correct) PR title resolves it, or reword the commit. Note that a force-push would invalidate the existing review-comment anchors.
Lower-confidence signals
Real enough to surface, not confident enough to carry as full findings. Informational; none of these gate the merge.
| Severity | Location | Signal |
|---|---|---|
| medium | Telemetry.cs:249-253 |
The stamped id reaches persisted transmission files under Path.GetTempPath(), which is world-shared /tmp on Linux and on macOS without TMPDIR; the directory is created without an explicit UnixFileMode. |
| medium | AuthenticatedUserTelemetryInitializer.cs:19 |
Three sinks read the static store directly, in a codebase that takes TimeProvider? and Func<bool?> precisely to avoid that shape. An internal provider defaulting to the static would also serve as the scoped escape hatch raised as M6 previously, and would let the four [DoNotParallelize] classes drop the attribute. Not urgent: it stays additive later. |
| medium | TelemetryUserContext.cs:28-32 |
Statics are per assembly load context. In MSBuild tasks, VS extensions and SDK plugins, sign-in code in one context stamps nothing in another, so the process-wide wording in FR-003 and the remarks overstates the reach. |
| medium | TelemetryUserContext.cs:43-57 |
The attribution path has no switch of its own: whitespace-defeating the seed does nothing to an in-code assignment, leaving only the full telemetry opt-out, whose blast radius exceeds the fault. |
| low | TelemetryWasmTests.cs:177-210 |
Still open from the previous round (M2): the runtime test asserts ambient-store round-trip and does-not-throw, never envelope tags. Worth stating before anyone reaches for the fix: CreateEventEnvelope is internal and the WASM test project has no InternalsVisibleTo, so closing this costs a second entry in the csproj or a stub endpoint. |
| low | spec.md:149-151 |
The claim that all tests setting the value are [DoNotParallelize] with resets around each test is not true of TelemetryWasmTests, which carries only [TestClass] and resets in a finally. |
| low | TelemetryUserContextTests.cs:23-24 |
The same two-line [TestInitialize] rationale is copied verbatim into four new test classes. Dissolves entirely if the environment seed goes, since those resets exist only for it. |
| info | TelemetryUserContext.cs:11 |
The new public type takes the same name as the downstream type the linked issue says the consumer keeps, so that consumer must fully qualify the package type at the very call site the acceptance criterion describes. Free to change while the symbol is unshipped. |
Suggested order, so nothing needs a second pass
- Answer the environment-seed question and, if it stays, decide the field's visibility. Removing the seed also dissolves
GetEnvironmentSeed, its two tests, the four[TestInitialize]resets, FR-009, P3,docs/usage.md:109-138including the table row, and the AGENTS.md counts. - Reconcile the invariant with the behaviour (capture-at-enqueue, or correct the comment plus EC-1 plus a concurrency test).
- Replace the parallel anonymous shapes with records, and add the exception-shape snapshot in the same commit; the snapshot is what proves the swap.
- Honour the opt-out at both
FileTelemetryselection sites; makeLogFailureexception-safe; log the full exception atTelemetry.cs:274and document theTrace.Listenersprerequisite; add the rollback note. - Pin
1024with a literal assertion and have the prose reference the constant; add the capturingTraceListenertest; extract the temp-file fixture helper; delete the vacuous test; single-source the WASM test count; qualify EC-1. - Style nits as one batch.
Confirmed good
The purely-additive claim survives verification: ITelemetry.cs is byte-identical to origin/main, every other production edit is internal or inside an unchanged signature, and no leftover of the reverted interface design remains in the sources or the spec. user_AuthenticatedId is the correct Log Analytics column. The exception shape is in fact byte-identical to main today. The spec follows the existing specs/001-wasm-compat/ structure section for section and its FR/EC/SC identifiers resolve and are cited from code, so it is convention rather than bloat. The length-only, never-the-id guarantee holds at every diagnostic call site. No lock, .Result, .Wait() or async void is introduced.
- new TelemetryUserContext ambient store (volatile, blank-normalizing, seeded once from UNO_PLATFORM_TELEMETRY_AUTHENTICATED_USER_ID) - ITelemetry gains a runtime-mutable AuthenticatedUserId property; all implementations delegate to the shared store - desktop stamps ai.user.authUserId per item via a telemetry initializer (per-item context, no shared client context mutation) - WebAssembly event and exception envelopes carry the same tag when set, omit it when unset - FileTelemetry emits a top-level AuthenticatedUserId field only when set; output unchanged otherwise - 22 new unit tests + 1 WASM runtime test Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_013VwiUTi8tF2JCa5yNiLDvW
- spec 002 (requirements, edge cases, success criteria) - usage.md: attribution section, env var, WASM tag, file output field - AGENTS.md: WASM runtime test count 8 -> 9 Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_013VwiUTi8tF2JCa5yNiLDvW
- normalize over-long ids (>1024, the AppInsights tag limit) to null, never a truncated prefix - guard the environment seed read against type-initializer poisoning - Debug/Trace diagnostics on seed pickup and normalization (length only) - wrap WASM sender bodies in try/catch (fire-and-forget callers discard the task, envelope failures were unobserved) - pre-size the WASM tags dictionary - guard the initializer pipeline registration with a test; snapshot-test the unset FileTelemetry line byte-for-byte with a pinned clock - deterministic test baselines via TestInitialize (env seed can make the startup value non-null) - spec: drain-time stamping semantics, unverified-attribution threat model, deferred-transmission risk, interface-break rationale - docs: child-process contract, operational suppression, trust warning Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_013VwiUTi8tF2JCa5yNiLDvW
- document the over-length normalization in the ITelemetry contract (doc parity with TelemetryUserContext) - state the telemetry-never-throws rationale on the deliberate generic catch clauses (type-initializer poisoning guard, fire-and-forget observation) flagged by static analysis - Path.Join over Path.Combine in the new tests Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_013VwiUTi8tF2JCa5yNiLDvW
eee96ae to
d1247a2
Compare
carldebilly
left a comment
There was a problem hiding this comment.
Approved
The rework answers the previous round in full. All 19 findings from the 2026-09-03 review are verified closed at their new locations, and so is the environment-variable question raised on the original TelemetryUserContext. The comments below are follow-ups, not conditions, with one exception I would like to see land: finding 1, the missing regression net on the WASM forwarding path.
What was verified, not taken on trust
- The "never wrong user" invariant now holds.
TelemetryUserContext.AuthenticatedUserIdis read in exactly five places in the whole production project, every one of them on the synchronous prologue of a tracking call. The queued continuations take a captured local or a parameter;WasmHttpSenderonly ever sees the parameter. Per-item stamping avoids the shared-client-context race, and the comment explaining why is accurate. The new capture tests drive a realTelemetryClientthrough an injected channel and mutate the ambient value between the call and the flush, so they exercise the race rather than restating the code; the mirror case would fail loudly against drain-time stamping. - The environment seed is genuinely gone from code, tests, docs and spec. The only environment variables the package reads are the opt-out, the file redirect, and two pre-existing ones unrelated to identity.
- The byte-identity snapshots are honest. The committed literals match the pre-record anonymous shapes on
origin/mainfield for field and in order, for both the event shape (Type, Timestamp, EventName, Properties, Measurements) and the exception shape (Type, Timestamp, Severity, Exception{Type, Message, StackTrace}, Properties, Measurements). A snapshot regenerated from the code it guards would have proved nothing; this one is the real thing, and both snapshots assert the whole line, so a rename or a reorder fails them. - The 1024 figure is now sourced.
ContextTagKeys.bondinmicrosoft/ApplicationInsights-dotnetdeclares[MaxStringLength("1024")]onUserAuthUserId, and128onUserId, exactly as the comment says. The previous round could not confirm that number against any vendor document. - The reverted
BREAKING CHANGEtrailer did not survive the rebase. Nofeat!header and no breaking-change footer remains on the branch, so nothing false lands onmain. - CI is green: Build, WASM Runtime Tests, CodeQL for both languages, conventional commits.
The one I would like to see land
Finding 1 is a coverage gap rather than a defect: nothing asserts that Telemetry's WASM branch actually forwards the captured id to the sender. machineId, sessionId and authenticatedUserId are three adjacent strings at two call sites, and a transposition or a hard-coded null at either one compiles with the whole suite green, then ships on the next push to main. The fix is small and stays internal.
Follow-ups
The other seven comments are cheap and batchable: a thin WASM failure log, one prose guarantee the test suite does not actually give, a new helper that does not own what its summary claims, hardcoded environment-variable names in tests, and two pieces of documentation bookkeeping that drifted within a single round.
Lower-confidence signals
Surfacing these without carrying them as findings; none is a merge condition.
| Severity | Location | Signal |
|---|---|---|
| medium | FileTelemetry.cs:156-162 |
The opt-out gates both sink-selection sites, but FileTelemetry itself has Enabled => true and no check in its write paths, so a directly constructed instance still writes the id. Nothing in the package constructs it outside the gate, so the code as composed is safe; the unqualified promise at docs/usage.md:120-121 is what is wider than the guarantee. Narrowing that sentence to the UNO_PLATFORM_TELEMETRY_FILE-selected lane is the cheapest resolution. Gating Enabled would be cleaner but changes a public member's behaviour. |
| medium | shared helper adoption | TelemetryDiagnostics is wired to the init and WASM paths but not to the remaining Debug-only diagnostic sites in FileTelemetry and Telemetry, which the Release package compiles out. The diff leaves two idioms where there was one, and the PR body's "all package diagnostics go through one shared helper" is broader than the code. |
| low | Telemetry.cs:353-354 |
Stamping identity onto persisted items raises the offline store under the shared temp directory from a pseudonymous machine hash to a directly identifying account id. Pre-existing location, correctly scoped out of this PR; one confidentiality sentence beside the existing rollback paragraph would close it. |
| low | docs/usage.md:161-164 |
The new paragraph describing the line format sits directly under an example that omits the Type field and uses a Z-suffixed timestamp the code cannot emit. Copying the literal now asserted in the snapshot test fixes it. |
Worth saying
This is the round where the design got simpler rather than more defended. An ITelemetryInitializer plus drain-time stamping became one captured local threaded as a parameter; a whole environment-variable mechanism was deleted rather than justified; six copies of a fixture collapsed onto one; and the anonymous shapes became records with the field order pinned by tests instead of by convention. The exotic decisions that remain each carry a comment explaining why.
|
Tick the box to add this pull request to the merge queue (same as
|
Closes unoplatform/studio.live#3337
What
Adds a runtime-mutable authenticated user id owned by the package, so downstream consumers can attribute telemetry to a signed-in account without wrapping the client:
TelemetryUserContext.AuthenticatedUserId: a process-wide ambient store (volatile, thread-safe) and the single entry point. Set it on sign-in, set it tonullon sign-out. NoITelemetryinstance is involved, so sign-in code has no dependency on telemetry resolution or lifetime. Once set, everyITelemetryinstance in the process stamps it, including typedITelemetry<T>instances resolved from DI that consumers never hold directly, and instances created after the value was set.TrackEventandTrackExceptionread the value when they are called and thread it through the queued track task, so each item carries the user that was signed in at that moment, not whoever is signed in when the asynchronous pipeline drains. An event tracked before sign-in is never attributed to a user who signs in while it is queued; an event tracked while signed in keeps that attribution if the user signs out before it is sent. The failure direction is "unattributed", never "wrong user".ai.user.authUserId(theuser_AuthenticatedIdcolumn) right before the item is handed to theTelemetryClient. Client-level context is deliberately not mutated: the lock-free track chaining does not fully serialize under contention, so per-event shared-context mutation would race.ai.user.authUserIdtag when set and omit it entirely when unset. The sender receives the captured id as an explicit parameter and never reads the ambient store itself.FileTelemetry: emits a top-levelAuthenticatedUserIdJSON field only while a value is set. Output is byte-identical to previous releases otherwise, for both the event and the exception shape (snapshot-tested with a pinned clock).null; the tag is then absent, never empty and never a truncated prefix. The cap is 1024 characters, theMaxStringLengththe Application InsightsContextTagKeysschema declares for this tag.UNO_PLATFORM_TELEMETRY_OPTOUT=truenow also disables theUNO_PLATFORM_TELEMETRY_FILEredirect, so the id is never written to disk while the opt-out is set.nullemits aTraceline carrying the value length only, never the id. All package diagnostics go through one shared helper that never throws, so a faulting consumerTraceListenercannot escape into sign-in code or a fire-and-forget task.Being a native context tag rather than a custom property, the id cannot be stripped or overridden through the per-event properties dictionary.
There is no environment-variable seed. The value starts as
nulland only changes when code sets it. A parent that launches child processes passes the id to them itself and the child assigns it at startup; the usage doc describes the pattern.Public API
Purely additive: one new public type (
TelemetryUserContext) with one property. No changes toITelemetryor any other existing public type. Consumers and external implementers compile unchanged, so no major-version bump is needed.This deviates deliberately from the originating issue's sketch of a member on
ITelemetry: stamping happens at the emitting sinks, which read the ambient store directly, so an interface member would be a capability-free pass-through that breaks every external implementer (netstandard2.0 rules out default interface members) and invites hand-written fakes to diverge from the process-global semantics. Rationale recorded inspecs/002-authenticated-user-id/spec.md.Tests
TraceListenerproving the diagnostic carries the length and never the value; a throwingTraceListenerproving neither the setter nor the shared diagnostics helper lets a listener fault escape.ThreadBlockingTrackEventpath, and that machine id, properties and metrics are unchanged.FileTelemetry: field presence and absence, byte-identity snapshots of the unset event and exception lines, and the field's position when set. The snapshots were captured against the previous anonymous-type shapes before the switch to records.[DoNotParallelize]and reset the value in[TestCleanup]. A sharedTempFilesfixture replaces six copies of the temp-file boilerplate.Docs
specs/002-authenticated-user-id/spec.md: requirements, edge cases (capture-at-call semantics, multi-product processes, no implicit seed, deferred transmission of persisted items), the assembly-load-context caveat, theTraceListenerprerequisite for diagnostics, threat model (the value is unverified client attribution, never to be used server-side for authorization, abuse, or billing decisions), success criteria, and key design decisions.docs/usage.md: new Authenticated User Attribution section with the process-wide semantics warning, the capture-at-call behaviour, the privacy note, child-process guidance, and an Operational suppression and diagnostics list covering the opt-out, the listener prerequisite, and a rollback note naming where the offline channel persists items.Out of scope
Per-instance ids, cross-process propagation of the id in either direction, and consent/PII policy (the consumer decides what identifier to send).
Two pre-existing items were noted during review and left as they are: the offline channel persists unsent items under the shared temp directory rather than a per-user location, and contended
TrackEvent/TrackExceptioncalls can leave orphaned continuations that emit duplicates. Neither is caused or worsened here.