Skip to content

feat: add process-wide authenticated user id attribution - #31

Merged
rajamatt merged 12 commits into
mainfrom
dev/mara/global-userid
Sep 14, 2026
Merged

rajamatt merged 12 commits into
mainfrom
dev/mara/global-userid

Conversation

@rajamatt

@rajamatt rajamatt commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

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 to null on sign-out. No ITelemetry instance is involved, so sign-in code has no dependency on telemetry resolution or lifetime. Once set, every ITelemetry instance in the process stamps it, including typed ITelemetry<T> instances resolved from DI that consumers never hold directly, and instances created after the value was set.
  • Captured at the tracking call. TrackEvent and TrackException read 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".
  • Desktop: the captured id is stamped onto each item's own context as ai.user.authUserId (the user_AuthenticatedId column) right before the item is handed to the TelemetryClient. 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.
  • WebAssembly: both the event and exception REST envelopes carry the same ai.user.authUserId tag 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-level AuthenticatedUserId JSON 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).
  • Normalization: null, empty, whitespace, or over-long values normalize to null; the tag is then absent, never empty and never a truncated prefix. The cap is 1024 characters, the MaxStringLength the Application Insights ContextTagKeys schema declares for this tag.
  • Opt-out covers every lane: UNO_PLATFORM_TELEMETRY_OPTOUT=true now also disables the UNO_PLATFORM_TELEMETRY_FILE redirect, so the id is never written to disk while the opt-out is set.
  • Diagnostics: an assignment that normalizes to null emits a Trace line carrying the value length only, never the id. All package diagnostics go through one shared helper that never throws, so a faulting consumer TraceListener cannot 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 null and 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 to ITelemetry or 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 in specs/002-authenticated-user-id/spec.md.

Tests

  • Ambient store: set, clear, overwrite; blank and over-length normalization with the literal 1024 boundary and a dedicated test pinning the constant; a capturing TraceListener proving the diagnostic carries the length and never the value; a throwing TraceListener proving neither the setter nor the shared diagnostics helper lets a listener fault escape.
  • Desktop capture-at-call: five tests drive the real track queue through an injected in-process channel, covering sign-out-then-sign-in and sign-in-after-track while the item is queued, the synchronous ThreadBlockingTrackEvent path, and that machine id, properties and metrics are unchanged.
  • WASM envelope tags: set and unset, event and exception, plus a check that the sender ignores the ambient store at envelope time.
  • 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.
  • DI: open-generic end-to-end proving instances the consumer never holds stamp the id, and opt-out coverage for both sink-selection sites.
  • All ambient-mutating test classes are [DoNotParallelize] and reset the value in [TestCleanup]. A shared TempFiles fixture replaces six copies of the temp-file boilerplate.
  • One WASM runtime test (set, track, clear round-trip), listed in AGENTS.md.
  • Full suite: 76/76 passing locally; library builds clean on netstandard2.0, net8.0 and net9.0. CI green: Build, WASM Runtime Tests, CodeQL, conventional commits.

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, the TraceListener prerequisite 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/TrackException calls can leave orphaned continuations that emit duplicates. Neither is caused or worsened here.

Copilot AI lite review requested due to automatic review settings August 20, 2026 19:30

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 through ITelemetry.AuthenticatedUserId across implementations/adapters/DI.
  • Desktop: stamps per-item context via a new AuthenticatedUserTelemetryInitializer; WASM: injects ai.user.authUserId into REST envelope tags; FileTelemetry: conditionally emits a top-level AuthenticatedUserId JSON 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.

Copilot AI review requested due to automatic review settings August 20, 2026 20:19

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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; }

Copilot AI review requested due to automatic review settings August 20, 2026 21:46

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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>>();

@rajamatt rajamatt self-assigned this Aug 21, 2026
Copilot AI review requested due to automatic review settings August 21, 2026 14:17
@rajamatt rajamatt changed the title feat!: add process-wide authenticated user id attribution feat: add process-wide authenticated user id attribution Aug 21, 2026

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.)

Copilot AI review requested due to automatic review settings August 21, 2026 14:56

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 15 out of 15 changed files in this pull request and generated 1 comment.

Copilot AI review requested due to automatic review settings August 21, 2026 15:14

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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);
			}

Copilot AI review requested due to automatic review settings August 21, 2026 15:18

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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);
			}

@nickrandolph

Copy link
Copy Markdown
Contributor

🧑‍⚖️ Seven-agent review panel

Seven independent reviewer lenses — architect, security, skeptic, quality, operability, contract, performance — were run against this PR. Consolidated below.

⚠️ Reviewers worked from the fetched diff only (no local checkout), so any finding depending on unseen code — notably LogFailure / SendAsync bodies — is flagged as an assumption, not a confirmed defect.

Verdict: fix-first (worst-case across the panel)

Reviewer Verdict
skeptic fix-first
security fix-before-merge (only to confirm LogFailure)
architect approve-with-changes
quality approve-with-changes
operability approve-with-changes
contract approve
performance approve

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.


🔴 High

H1 · Drain-time stamping (EC-1) is asserted by prose, not proven by any test — Telemetry.cs (initializer registration) + AuthenticatedUserTelemetryInitializer.cs
The initializer reads the ambient store when the AI SDK calls Initialize (at task drain), not at the TrackEvent() call site. Counterexample: thread A signs in user-X and calls TrackEvent; before drain, thread B signs in user-Y; the item drains stamped user-Y. The spec's letter holds ("never a value that wasn't legitimately set"), but the event the developer attributed to X now reports Y. No test exercises a concurrent set-during-drain — Given_AuthenticatedUserIdChangedBetweenItems is single-threaded and calls Initialize directly, proving nothing about real drain timing or the queue gate. → add a concurrency test exercising identity-switch-during-flight; confirm the SDK invokes initializers at drain vs enqueue.

H2 · "ai.user.authUserId" tag name is a duplicated magic string — WasmHttpSender.cs (CreateTags)
WASM hard-codes the tag inline; desktop stamps it via the SDK's Context.User.AuthenticatedUserId. Two representations of the same wire contract can drift silently — a WASM key typo would pass every desktop test. → hoist to an internal const (e.g. TelemetryUserContext.AuthenticatedUserIdTag) and reference it from the WASM builder.

H3 · Env-seed "read once at type init" is a leaky, in-process-untestable abstraction — TelemetryUserContext.cs
_authenticatedUserId = GetEnvironmentSeed() runs at type init, which fires on first access to any member, so "read once per process" (EC-5) silently depends on when the type is first touched. The generic catch guarding against TypeInitializationException poisoning is exemplary — but the semantics are enforced by nothing, and the field-initializer seed is only reachable via a child-process integration test (author accepts this gap). → document the first-touch dependency explicitly; consider a child-process integration test if the seed contract matters.


🟠 Medium

M1 · LogFailure is out of diff — the fire-and-forget hardening depends on it not throwing (and not echoing the id) — WasmHttpSender.cs
The new generic catch → LogFailure is what makes the discarded tasks safe; if LogFailure itself throws, it re-introduces the unobserved fault it was meant to close. Security also could not confirm LogFailure doesn't serialize the envelope/exception (which could contain the id). This is the single item gating the security verdict. → confirm LogFailure has an internal try/catch and logs message text only, never the serialized envelope.

M2 · WASM runtime test verifies nothing about the envelope — TelemetryWasmTests.cs
The sole new WASM runtime test asserts only property round-trip + DoesNotThrow; it never inspects the actual envelope tags on the real single-threaded Mono path (FR-007). The desktop WasmHttpSenderAuthenticatedUserTests run on desktop CLR. → assert tag presence/absence in the runtime harness, or caveat the gap explicitly.

M3 · Normalization boundary is UTF-16-code-unit based and only ASCII-tested — TelemetryUserContext.cs (Normalize)
.Length counts UTF-16 units. 512 surrogate-pair chars (.Length == 1024) passes the cap but may still exceed AI's serialized tag budget — a silent server-side drop, the opposite of the "never truncated" guarantee. Boundary tests use only ASCII 'a'. → add a surrogate-pair/unicode boundary test; decide whether the cap should count runes/bytes.

M4 · Exception-shape byte-identity is not snapshot-tested — FileTelemetryAuthenticatedUserTests.cs
The byte-identity snapshot covers only the event shape; the exception shape asserts only TryGetProperty…BeFalse. FR-008/SC-004 claim exception parity, but a stray field-ordering change in the exception anonymous type would pass current tests. → add a pinned-clock byte-identity snapshot for the unset exception line.

M5 · FileTelemetry two-anonymous-shape branches duplicated for event and exception — FileTelemetry.cs
~40 lines of parallel structure (4 near-identical object literals) that must be edited in lockstep. Acceptable to preserve byte-identity, but the hazard is real. → extract a shared base-fields helper, or add a comment stating anonymous-type property-order pinning forbids refactoring.

M6 · Process-wide single-identity ceiling; no scoped/AsyncLocal escape hatch — TelemetryUserContext.cs
Ambient static is the correct reach for FR-003 (per-instance can't satisfy it), but it bakes in "one process = one user"; a future multi-session/server host (one process, many users) cannot use this correctly. → while the API is still additive, consider backing the store with a swappable resolver (Func<string?> / internal IAuthenticatedUserIdProvider with a static-backed default) so a multi-session host can substitute AsyncLocal without an API break later. Worth a deliberate decision now — cheap while additive, expensive later.


🟡 Low

  • L1 · PII — the id is emitted raw; the 1024 cap is an AI tag limit, not a PII/opaqueness guard. FileTelemetry writes it cleartext at rest, and that lane is not governed by UNO_PLATFORM_TELEMETRY_OPTOUT. Documented as consumer responsibility; consider a docs note that the file lane writes the id in cleartext.
  • L2 · Default-behavior surprise on upgrade — an inherited/global env var silently stamps user_AuthenticatedId on a process that never opted in via code. Ensure the seed Trace line fires in Release so an operator can spot an unexpected id source.
  • L3 · Init-failure diagnostic logs e.Message only (Telemetry.cs) — often can't distinguish a bad key from a channel/disk fault. Add e.GetType().Name/e.ToString() (library's own exception, no PII concern).
  • L4 · Normalize redundancy — the Length: > 0 sub-clause is subsumed by the IsNullOrWhiteSpace check.
  • L5 · Public field vs read-only property for the env-var name — field-over-const is correctly justified, but a get-only property would be a stronger contract than a reflection-mutable field.
  • L6 · Test-only production surface — CreateEventEnvelope/CreateExceptionEnvelope widened private→internal and TelemetryConfigurationInternal added purely for test observation. Acceptable (stops at internal).
  • L7 · Adjacent scope — the WASM fire-and-forget hardening and Trace-on-init-failure are real robustness wins but sit outside the stated FR set; defensible and documented.

ℹ️ Confirmed good

  • Contract: purely-additive claim confirmed. No member added/removed/renamed on ITelemetry or any existing public type; SendEventAsync/SendExceptionAsync arities unchanged; the initial feat!/BREAKING-CHANGE approach was fully reverted with no leftover references. FileTelemetry JSON field and AI/WASM tags are additive/optional. (External-caller enumeration would be needed to fully rule out reflective coupling.)
  • Performance: clean. No lock/Monitor/SemaphoreSlim.Wait/.Result/.Wait()/async void introduced. volatile store is WASM-mono-thread safe. Emit-path allocation is neutral: FileTelemetry boxing to object adds nothing (reference types don't box), WASM dict is pre-sized to 5, desktop initializer allocates zero when unset.
  • Security: the "length only, never the id" claim holds across all audited diagnostic call sites. The static-field-initializer generic catch correctly avoids type-init poisoning.
  • Quality: comment hygiene is good — dense but overwhelmingly WHY/invariant/rationale, not code-restatement; XML docs present on public members. FR 1–14 and SC 1–5 map to shipped code.

Recommended path to green

  1. H1 / M2 / M4 — the drain-time correctness claim and two coverage gaps (WASM envelope, exception byte-identity) are the real content of the fix-first verdict. Add the tests; confirm the SDK drain-timing assumption.
  2. M1 — a 2-minute check: does LogFailure throw or echo the envelope? This alone clears security.
  3. H2 / M3 — extract the tag constant; add a unicode boundary test.
  4. Everything else is discretionary polish — M6 is the one worth deciding now while the API is still additive.

🤖 Generated with Claude Code — seven-agent review panel

@carldebilly carldebilly left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.Initialize loops initializers synchronously, and TrackEventTask calls _client.TrackEvent from inside the CAS-chained continuation, so stamping does happen at drain. A second mechanism makes it worse: the chain is rooted at Task.Run(InitializeTelemetry) (file I/O), so startup events drain after sign-in. See the comment on TelemetryUserContext.cs:23.
  • M1 (LogFailure): the leak half is refuted. LogFailure logs exception.Message only, never the envelope or the id, and no failure path on SendAsync carries the id in its message. The throw half is still open, see WasmHttpSender.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 null rather than truncating, so no pair can be split.
  • H2 (duplicated tag literal): largely refuted, no action recommended. ai.user.authUserId appears 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. Every UNO_* 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, see TelemetryUserContext.cs:26.

Two decisions, then mechanical work

Only two findings need a decision rather than a patch:

  1. The stated invariant and the actual behaviour disagree. TelemetryUserContext.cs:21-23 promises the failure direction is never wrong 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 the no arity changes claim 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.
  2. 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

  1. 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-138 including the table row, and the AGENTS.md counts.
  2. Reconcile the invariant with the behaviour (capture-at-enqueue, or correct the comment plus EC-1 plus a concurrency test).
  3. Replace the parallel anonymous shapes with records, and add the exception-shape snapshot in the same commit; the snapshot is what proves the swap.
  4. Honour the opt-out at both FileTelemetry selection sites; make LogFailure exception-safe; log the full exception at Telemetry.cs:274 and document the Trace.Listeners prerequisite; add the rollback note.
  5. Pin 1024 with a literal assertion and have the prose reference the constant; add the capturing TraceListener test; extract the temp-file fixture helper; delete the vacuous test; single-source the WASM test count; qualify EC-1.
  6. 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.

Comment thread docs/usage.md Resolved
Comment thread specs/002-authenticated-user-id/spec.md Resolved
rajamatt and others added 11 commits September 9, 2026 11:03
- 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

@carldebilly carldebilly left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.AuthenticatedUserId is 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; WasmHttpSender only 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 real TelemetryClient through 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/main field 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.bond in microsoft/ApplicationInsights-dotnet declares [MaxStringLength("1024")] on UserAuthUserId, and 128 on UserId, exactly as the comment says. The previous round could not confirm that number against any vendor document.
  • The reverted BREAKING CHANGE trailer did not survive the rebase. No feat! header and no breaking-change footer remains on the branch, so nothing false lands on main.
  • 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.

Comment thread src/Uno.DevTools.Telemetry/Telemetry.cs Resolved
Comment thread specs/002-authenticated-user-id/spec.md Resolved
@mergify

mergify Bot commented Sep 14, 2026

Copy link
Copy Markdown

Tick the box to add this pull request to the merge queue (same as @mergifyio queue).

  • Queue this pull request

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants