Repository navigation
feat(trace): ETW provider for correlated Reactor + WinUI profiling - #37
Conversation
a79fa26 to
0bc7516
Compare
There was a problem hiding this comment.
Pull request overview
Adds first-class ETW instrumentation to Reactor so reconcile/render/state/effects/MCP activity can be correlated with WinUI (Microsoft-Windows-XAML) events in a single trace, and promotes reconcile volume counters to be available in Release builds.
Changes:
- Introduces a new
Microsoft-UI-ReactorEventSourcewith start/stop events for reconcile, component render, effects flush, child reconcile, MCP calls, plus state-change/lifecycle/error events. - Wires tracing into
Reconciler,RenderContexthooks, and Devtools MCP dispatch; makes reconcile counters always-on (not DEBUG-only) and surfaces them viaRenderStats. - Documents the ETW capture workflow (xperf) for correlated Reactor + WinUI traces.
Reviewed changes
Copilot reviewed 11 out of 11 changed files in this pull request and generated 8 comments.
Show a summary per file
| File | Description |
|---|---|
| src/Reactor/Core/Diagnostics/ReactorEventSource.cs | New ETW/EventPipe provider defining Reactor trace events/keywords/tasks. |
| src/Reactor/Core/Reconciler.cs | Emits reconcile/render/effects/child-reconcile/unmount/error events; adds trace depth tracking. |
| src/Reactor/Core/RenderContext.cs | Emits state-change events from UseState/UseReducer setters. |
| src/Reactor/Hosting/Devtools/McpDispatcher.cs | Emits MCP call start/stop events around tool invocation. |
| src/Reactor/Hosting/Devtools/README.md | Adds xperf-based capture instructions and provider/keyword details. |
| src/Reactor/Core/Reconciler.Update.cs | Makes diff/skip/modified counters update in Release builds. |
| src/Reactor/Core/Reconciler.Mount.cs | Makes created counter update in Release builds. |
| src/Reactor/Core/ChildReconciler.cs | Makes skipped counter update in Release builds in positional reconcile. |
| src/Reactor/Hosting/RenderStats.cs | Promotes LastDiffed/Skipped/Created/Modified to always exist (no #if DEBUG). |
| src/Reactor/Hosting/ReactorHost.cs | Always populates RenderStats with reconcile counters. |
| src/Reactor/Hosting/ReactorHostControl.cs | Always populates RenderStats with reconcile counters. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| void Setter(T newValue) | ||
| { | ||
| var h = (ValueHookState<T>)_hooks[currentIndex]; | ||
| bool changed; | ||
| if (h.ThreadSafe) | ||
| { | ||
| bool changed; | ||
| lock (h.Lock) | ||
| { | ||
| changed = !EqualityComparer<T>.Default.Equals(h.Value, newValue); | ||
| if (changed) h.Value = newValue; | ||
| } | ||
| Diagnostics.ReactorEventSource.Log.StateChange("UseState", typeof(T).Name, changed); | ||
| if (changed) _requestRerender?.Invoke(); | ||
| } | ||
| else | ||
| { | ||
| AssertUIThread("UseState"); | ||
| if (!EqualityComparer<T>.Default.Equals(h.Value, newValue)) | ||
| { | ||
| h.Value = newValue; | ||
| _requestRerender?.Invoke(); | ||
| } | ||
| changed = !EqualityComparer<T>.Default.Equals(h.Value, newValue); | ||
| if (changed) h.Value = newValue; | ||
| Diagnostics.ReactorEventSource.Log.StateChange("UseState", typeof(T).Name, changed); | ||
| if (changed) _requestRerender?.Invoke(); |
There was a problem hiding this comment.
StateChange is called unconditionally on every UseState/UseReducer write; even though the EventSource method checks IsEnabled, the call-site still evaluates typeof(T).Name and does the extra call on the hot path. Consider a call-site IsEnabled(EventLevel.Verbose, Keywords.State) guard (or an overload taking a Type and resolving .Name only when enabled) to keep the disabled path minimal as described in the docs.
| (see `Core/Diagnostics/ReactorEventSource.cs`). Events are zero-cost when no | ||
| listener is attached and cover reconcile passes, component render start/stop | ||
| with trigger (self/parent), state writes, unmounts, render errors, and MCP | ||
| call start/stop. |
There was a problem hiding this comment.
This section states “Events are zero-cost when no listener is attached”, but the current emit sites do non-trivial work even when disabled (e.g., starting Stopwatches / reading timestamps and computing argument strings before the EventSource’s internal IsEnabled check). Either add call-site IsEnabled guards to make the statement true, or soften the wording to reflect the remaining overhead.
| (see `Core/Diagnostics/ReactorEventSource.cs`). Events are zero-cost when no | |
| listener is attached and cover reconcile passes, component render start/stop | |
| with trigger (self/parent), state writes, unmounts, render errors, and MCP | |
| call start/stop. | |
| (see `Core/Diagnostics/ReactorEventSource.cs`). When no listener is attached, | |
| EventSource delivery is effectively disabled, though some emit sites may still | |
| pay small call-site overhead unless they are explicitly guarded with | |
| `IsEnabled`. Events cover reconcile passes, component render start/stop with | |
| trigger (self/parent), state writes, unmounts, render errors, and MCP call | |
| start/stop. |
| // Trace only top-level reconcile passes (depth == 0) to avoid flooding | ||
| // the provider with per-subtree entries; nested Reconcile() calls during | ||
| // the same pass don't emit their own start/stop. | ||
| bool emitTrace = _reconcileTraceDepth++ == 0; | ||
| if (emitTrace) | ||
| { | ||
| Diagnostics.ReactorEventSource.Log.ReconcileStart( | ||
| newElement?.GetType().Name ?? "null"); | ||
| } |
There was a problem hiding this comment.
Reconcile tracing currently increments _reconcileTraceDepth and calls ReconcileStart/Stop every pass regardless of whether the provider/keyword is enabled. If the goal is near-zero overhead when tracing is off, consider first checking ReactorEventSource.Log.IsEnabled(EventLevel.Informational, Keywords.Reconcile) (or similar) and only then updating the trace-depth and emitting start/stop.
…ctor + WinUI profiling
Emits a TraceLogging-style EventSource (provider: Microsoft-UI-Reactor,
GUID 2BA6BC23-ABF9-56DE-3922-8CC701F16EDE) so a classic ETW session
can capture Reactor reconcile / render / state events alongside
Microsoft-Windows-XAML frame / layout / input events and see the full
pipeline on one timeline.
Emit sites (all IsEnabled()-guarded, zero-cost when no listener):
- Reconciler.Reconcile: ReconcileStart/Stop at top-level passes,
carrying elementsDiffed / elementsSkipped / uiElementsCreated /
uiElementsModified counters as event payload.
- Reconciler.ReconcileComponent: ComponentRenderStart/Stop with
component name, trigger (self/parent), and elapsed microseconds;
RenderError on caught exceptions.
- Reconciler.(Unmount)Recursive / UnmountAndCollect: ComponentUnmount
when a component node cleans up.
- FlushEffectsTraced helper: EffectsFlushStart/Stop around UseEffect
flush per component.
- ReconcileChildren / ReconcileItemsChildren: ChildReconcileStart/Stop
around keyed-LIS child diff with oldCount / newCount payload.
- RenderContext.UseState setter + UseReducer updater: StateChange with
hook kind, value type, and whether the write actually changed.
- McpDispatcher.Invoke: McpCallStart/Stop with tool, selector, success,
result code, elapsed ms.
Reconciler counters (DebugElementsDiffed/Skipped, DebugUIElementsCreated/
Modified) and RenderStats.Last* fields promoted from #if DEBUG to
always-on so Release traces carry the data. A/B stress test (50% /
7s / 5 runs) shows +2% reconcile time vs. pre-instrumentation — within
one stdev, indistinguishable from noise.
Capture recipe documented in Hosting/Devtools/README.md (xperf, not
dotnet-trace: EventPipe cannot surface the native Microsoft-Windows-XAML
provider). Full mask: 0x3F at Verbose. Viewing: .etl opens natively in
PerfView and WPA; a Chromium-JSON converter for web viewers is tracked
separately.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
0bc7516 to
310a299
Compare
|
Addressed all 8 Copilot review comments in Core fix — the theme across all comments was that emit sites were doing pre-work (Stopwatch,
Docs fixed:
Tests green: |
Hot keyed list-diff path (grid steady state) allocated heavily and missed fast-paths even when keys were unchanged. Eliminate per-diff allocations and add the missing fast-path, preserving diff behavior exactly. ChildReconciler.cs: - Keyed prefix/suffix loops now take the Element.CanSkipUpdate early-exit that the positional path has, so stable keyed rows no longer re-diff every tick (#30); cache children.Count once instead of re-reading the COM IVector.get_Size per suffix iteration (#37). - Replace HashSet-returning ComputeLIS with allocation-free ComputeLISInto filling a pooled bool mask; pool tails/tailIndices/predecessors from ArrayPool (#31/#32). Keep a thin ComputeLIS(int[]) wrapper for tests. - Pool ReconcileKeyedMiddle's working arrays (ArrayPool) and the two key->index maps (re-entrancy-safe ThreadStatic dict pool); buffers cleared and returned on every exit (#33). - Filter: count-pass + single Element[] fill, no List+ToArray (#36). - GetKey: cache Type.Name via ConcurrentDictionary (#38). KeyedListDiff.cs: - Rent newKeys from ArrayPool<string>, threading explicit newCount (rented array may be larger); returned clearArray:true in a finally (#2). - Move the no-op (SequenceEqual) + empty/empty fast paths ABOVE the duplicate scan so the steady-state grid case never allocates/scans a dup set (#1). - Fold the churn-bailout decision into ApplyGeneral, computed from the same post-prefix/suffix scratch map the general walk builds (diff-range churn == full-range churn), removing the O(2n) null-marker pre-pass (#34). - Pool the doomed ReactorRow[] (ArrayPool, descending IComparer sort over [0,removes), cleared+returned) (#3). - Lazy-allocate movedRows only on an actual move under an ambient (#35). - In-place SyncLastKeysToSource instead of LastKeys Clear()+Add (#10). - HasDuplicates reuses state.Scratch (TryAdd) for 4+ keys instead of a fresh HashSet (#11); cached null-key diagnostic sample (#41). Tests: add pooling non-corruption coverage (rented-buffer-larger-than-count, interleaved independent states, randomized stress vs oracle with survivor identity, pooled doomed removes, churn with shared prefix+suffix, Scratch reuse for the dup scan) and ComputeLISInto bool-mask coverage. Full Reactor.Tests suite green (9693 passed); core lib Release build is warning-clean (AOT/trim). Closes #653 Co-authored-by: Copilot <[email protected]>
…ff (#657) * perf: eliminate per-diff allocations in ChildReconciler + KeyedListDiff Hot keyed list-diff path (grid steady state) allocated heavily and missed fast-paths even when keys were unchanged. Eliminate per-diff allocations and add the missing fast-path, preserving diff behavior exactly. ChildReconciler.cs: - Keyed prefix/suffix loops now take the Element.CanSkipUpdate early-exit that the positional path has, so stable keyed rows no longer re-diff every tick (#30); cache children.Count once instead of re-reading the COM IVector.get_Size per suffix iteration (#37). - Replace HashSet-returning ComputeLIS with allocation-free ComputeLISInto filling a pooled bool mask; pool tails/tailIndices/predecessors from ArrayPool (#31/#32). Keep a thin ComputeLIS(int[]) wrapper for tests. - Pool ReconcileKeyedMiddle's working arrays (ArrayPool) and the two key->index maps (re-entrancy-safe ThreadStatic dict pool); buffers cleared and returned on every exit (#33). - Filter: count-pass + single Element[] fill, no List+ToArray (#36). - GetKey: cache Type.Name via ConcurrentDictionary (#38). KeyedListDiff.cs: - Rent newKeys from ArrayPool<string>, threading explicit newCount (rented array may be larger); returned clearArray:true in a finally (#2). - Move the no-op (SequenceEqual) + empty/empty fast paths ABOVE the duplicate scan so the steady-state grid case never allocates/scans a dup set (#1). - Fold the churn-bailout decision into ApplyGeneral, computed from the same post-prefix/suffix scratch map the general walk builds (diff-range churn == full-range churn), removing the O(2n) null-marker pre-pass (#34). - Pool the doomed ReactorRow[] (ArrayPool, descending IComparer sort over [0,removes), cleared+returned) (#3). - Lazy-allocate movedRows only on an actual move under an ambient (#35). - In-place SyncLastKeysToSource instead of LastKeys Clear()+Add (#10). - HasDuplicates reuses state.Scratch (TryAdd) for 4+ keys instead of a fresh HashSet (#11); cached null-key diagnostic sample (#41). Tests: add pooling non-corruption coverage (rented-buffer-larger-than-count, interleaved independent states, randomized stress vs oracle with survivor identity, pooled doomed removes, churn with shared prefix+suffix, Scratch reuse for the dup scan) and ComputeLISInto bool-mask coverage. Full Reactor.Tests suite green (9693 passed); core lib Release build is warning-clean (AOT/trim). Closes #653 Co-authored-by: Copilot <[email protected]> * perf: address PR review on keyed-diff allocation fixes Review follow-ups on #657 (keyed list-diff allocation work): - ChildReconciler.ReconcileKeyedMiddle: return the pooled matched and inLis bool[] buffers with clearArray:false instead of true (Copilot review). Both are value-typed (no reference pinning) and have their used range fully (re)initialized before any read - matched via the Array.Clear on rent, inLis via ComputeLISInto leading clear - so the full-array wipe on return was avoidable O(rented-capacity) work on the hot path. Matches how the int[] newToOld already returns. Reference-typed pooled buffers (string[]/ReactorRow[] in KeyedListDiff) still clear. - Tests (ChildReconcilerLisIntoTests): replace the circular oracle that compared ComputeLISInto against ComputeLIS (now a thin wrapper over it) with an independent brute-force LIS-length DP that honors the -1 unmapped sentinel, asserting the mask marks a valid strictly-increasing subsequence of maximal length. - Tests (ChildReconcilerKeyedSkipTests, new): cover the #30 keyed CanSkipUpdate fast path - an identical keyed list skips every row with no ops and no child-control access, across repeated stable frames. Co-authored-by: Copilot <[email protected]> * fix: correct keyed-middle reorder identity (C1/H1) + reorder & alloc tests The keyed-middle reconciliation in ChildReconciler patched surviving controls by their FINAL panel index while the panel was only partially rearranged, so on reorders a survivor was patched against the wrong control (C1, CRITICAL): e.g. rotation [a,b,c,d]->[b,c,d,a] rendered "c" at slot 0 and scrambled keyed identity (focus/animation/state landed on the wrong row). A related stale keyToIndex (only the moved key was rewritten) left shifted siblings mis-indexed after an insert/move (H1). Fix: extract the index logic into RunKeyedMiddleCore<TSink> behind a struct-generic IKeyedMiddleSink seam (devirtualized, AOT-clean) and replace the left-to-right loop with the canonical right-to-left LIS walk. Each item is positioned immediately before its already-placed right neighbour; LIS members stay put and only out-of-LIS movers relocate (minimal moves). Every survivor is patched at its CURRENT live position, resolved from a pooled oldRelToPanel int[] that is mutated in lock-step with every Insert/Move so it stays exact -- fixing C1 and H1 together. The production RealKeyedMiddleSink drives the identical Mount/Move/ UpdateChild/Unmount/Replace + ambient enter/move behaviour as before. oldRelToPanel replaces the second pooled key->index dict (one fewer rented dict per call). Tests: - ChildReconcilerKeyedMiddleCoreTests (new): a headless SimKeyedMiddleSink drives the SAME RunKeyedMiddleCore over identity cells (exact production parity, no live-WinUI selftest wall), with a 4-invariant oracle (length, prefix/suffix untouched, per-slot identity+content, every patch hits its claimed survivor) across rotation, full reverse, scramble, block-swap, inserts/removes/duplicates and prefix/suffix offsets. A faithful pre-fix reproduction proves the rotation regression test has teeth (the buggy walk corrupts content[0] and mis-patches; the real core is clean). - KeyedListDiffPoolingTests: two GC.GetAllocatedBytesForCurrentThread budgets guarding the #1/#2/#11 pooling -- no-op steady-state diff is 0 B/iter and a 128-key reorder is 72 B/diff; reverting the pooling (a new string[128] + a 128-entry HashSet per diff) fails them. Diff correctness preserved; pooled buffers returned on every exit. Co-authored-by: Copilot <[email protected]> * fix: gate keyed no-op fast path on duplicate-free state + test hardening Address Copilot re-review of e664f9f. KeyedListDiff: the no-op fast path runs above the duplicate scan (#1), so an UNCHANGED list that already holds duplicate keys -- the state a prior duplicate bailout leaves behind, since ReactorListState.Reset preserves the dups in Source/LastKeys but collapses ByKey to first occurrences -- would match LastKeys and return Empty, silently skipping the duplicate bailout/diagnostic and leaving the diff in an invalid duplicate state. Gate the fast path on `state.ByKey.Count == oldCount`: true exactly for the duplicate-free steady state (allocation-free path preserved), false when dups were collapsed (re-takes the bailout). The check is O(1) and short-circuits before the O(n) SequenceEqualOrdinal, so the common unique-key path pays nothing. No-op steady-state allocation stays 0 B/iter. Tests: - KeyedListDiffTests: new Apply_Unchanged_Duplicate_List_Re_Bails_Instead_ Of_NoOp_FastPath -- proves an unchanged duplicate list re-bails; verified to FAIL without the guard (takes the no-op path and returns Empty). - ChildReconcilerLisIntoTests: strengthen the LIS oracle to assert selected indices are never the unmapped -1 sentinel (a buggy impl could swap a real member for a -1 and still satisfy strictly-increasing + length). - KeyedListDiffPoolingTests: drop the unused `using System.Buffers;` (fully-qualify the one ArrayPool cref) flagged by the reviewer. Co-authored-by: Copilot <[email protected]> --------- Co-authored-by: Copilot <[email protected]>
Summary
Adds a
Microsoft-UI-ReactorTraceLoggingEventSource(provider GUID2BA6BC23-ABF9-56DE-3922-8CC701F16EDE) so an ETW session can capture Reactor's reconcile / render / state / effects / child-diff / MCP events on the same timeline asMicrosoft-Windows-XAMLframe / layout / input / compositor events.The result: a single trace that shows state change → reconcile → ComponentRender → ChildReconcile → layout → arrange → render → frame present end-to-end, with element counts as span args.
What's in the event stream
Reconcile(Start/Stop)Reconcile=0x1elementsDiffed,elementsSkipped,uiElementsCreated,uiElementsModifiedComponentRender(Start/Stop)Render=0x2componentName,trigger(self/parent),elapsedUsEffectsFlush(Start/Stop)Render=0x2componentName,elapsedUsChildReconcile(Start/Stop)Reconcile=0x1oldCount,newCountStateChangeState=0x4hookKind,valueType,changedComponentUnmountLifecycle=0x10componentNameMcpCall(Start/Stop)Mcp=0x8toolName,selector,success,resultCode,elapsedMsRenderErrorErrors=0x20componentName,exceptionType,messageFull keyword mask:
0x3F. Every site isIsEnabled()-guarded — emits zero cost when no listener is attached.Always-on counters
Reconciler.DebugElementsDiffed/Skipped/UIElementsCreated/ModifiedandRenderStats.LastDiffed/Skipped/Created/Modifiedwere DEBUG-only. Promoted to always-on so Release-build traces can answer "how many elements were created / modified per reconcile?" A/B stress test (50% update rate, 7s, 4 warm runs each):All deltas are within one standard deviation — indistinguishable from run-to-run noise.
Capture recipe (xperf, not dotnet-trace)
dotnet-traceuses EventPipe and can't surface native ETW providers, soMicrosoft-Windows-XAMLgets dropped and you end up with a Reactor-only trace. Documented the xperf path insrc/Reactor/Hosting/Devtools/README.md:.etlopens natively in PerfView / WPA. A Chromium-JSON converter for web-based viewers (Perfetto, Firefox Profiler, Speedscope) is tracked as follow-up work.Test plan
dotnet build Reactor.sln -c Debug— 0 errorsdotnet test tests/Reactor.Tests— 3859 passed, 0 faileddotnet build samples/apps/headtrax -c Release -r win-arm64— cleanReactor.Reconcileargs show realuiElementsCreated / uiElementsModifiedcounters (verified: 73 created on mount pass, 90 modified / 18 skipped on steady-state)🤖 Generated with Claude Code