Skip to content

perf: devirtualize per-prop diff dispatch in V1 descriptor - #656

Closed
Alexandre Zollinger Chohfi (azchohfi) wants to merge 6 commits into
mainfrom
azchohfi-perf-descriptor-diff-dispatch
Closed

Alexandre Zollinger Chohfi (azchohfi) wants to merge 6 commits into
mainfrom
azchohfi-perf-descriptor-diff-dispatch

Conversation

@azchohfi

Copy link
Copy Markdown
Collaborator

Closes #655

What

Devirtualizes the V1 descriptor per-prop diff dispatch — the machinery that runs hundreds of thousands of comparisons/sec on the data-grid stress workload. Scope is the two diff-machinery files plus tests; behavior is preserved exactly for every descriptor-based control.

# Fix
#115 Value comparers stored nullable (null = default); all compares routed through an AggressiveInlining PropValueComparison.ValuesEqual helper that calls EqualityComparer<T>.Default.Equals directly (JIT devirtualizes + inlines for value types). Custom comparers still honored via the interface call.
#114 New PropEntry.Subscribes discriminator; handler partitions entries into _updateEntries (all) + _subscribeEntries (small subset). Per-Update subscribe pass visits only the subset and skips BindFor + the loop entirely when empty (the OneWay-only grid-cell case).
#117 Properties snapshotted into concrete PropEntry[] arrays in the handler ctor; Mount/Update iterate the arrays (no interface-indexer dispatch).
#119 [ThreadStatic] cleared-on-use scratch HashSets in CollectionDiffControlledPropEntry.Update (−2 allocs/update).
#120 ReferenceListPropEntry moved into the subscribe subset; [ThreadStatic] scratch cells list removes its per-Update allocation.

#118 is deferred — its fix needs ControlDescriptor.cs/Element.cs (out of scope); the entry still gets the #115 devirtualization.

Behavior preservation

The reference entries deliberately re-evaluate EnsureSubscribed every Update (ref add/remove/reorder detection), so a "skip after first wire" flag would be unsafe — only the empty-subset skip is used. Skipping BindFor when there are no subscribers is safe: its sole side effect (resetting the reference-slot thread-static) is consumed exclusively by reference entries, which are themselves subscribers. Scratch state is [ThreadStatic] (not instance fields) because entries are process-wide singletons shared across controls and Reactor supports multiple UI threads/windows.

Validation

  • dotnet build src/Reactor (Release) — clean, 0 warnings/0 errors.
  • dotnet test tests/Reactor.Tests (Release) — 9683 passed, 0 failed, incl. 13 new PropEntryDiffDispatchTests (write-on-change / skip-on-equal for default + custom comparer; comparer helper vs EqualityComparer<T>.Default; Subscribes discriminator + a reflection invariant guarding "overrides EnsureSubscribed ⇔ overrides Subscribes"; handler _updateEntries/_subscribeEntries partitioning; collection-diff scratch reuse across updates).
  • Live WinUI selftests: ToggleSwitch controlled family (echo suppression, value-diff, subscription wire/fire) and the RealRef reference-edge torture suite (scalar/list refs, keyed reorder a11y ordering, pool-reuse wire-exactly-once, no subscriber leaks) — 0 failures.

Perf numbers will be confirmed via /perf once that workflow merges. The two reactor.api.txt files are regenerated by the build's API-index tool to include the new public PropEntry.Subscribes member.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

Optimizes the V1 descriptor diff/update hot path by reducing per-prop virtual dispatch and per-update subscription overhead, targeting high-frequency workloads (e.g., stress-perf data grid) while aiming to preserve existing descriptor behavior.

Changes:

  • Introduces PropValueComparison.ValuesEqual and stores per-entry comparers as nullable to enable JIT-friendly default comparisons.
  • Adds PropEntry.Subscribes and updates DescriptorHandler to pre-snapshot properties into arrays and to run EnsureSubscribed only for the subscribing subset (skipping BindFor entirely when empty).
  • Adds targeted unit tests validating comparer behavior, handler partitioning, and scratch reuse; regenerates API reference snapshots to include Subscribes.

Reviewed changes

Copilot reviewed 5 out of 5 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
tests/Reactor.Tests/PropEntryDiffDispatchTests.cs New unit tests covering the new dispatch/comparer/subscription partition invariants.
src/Reactor/Core/V1Protocol/Descriptor/PropEntry.cs Nullable comparer storage + ValuesEqual helper; new Subscribes discriminator; thread-static scratch reuse for specific entries.
src/Reactor/Core/V1Protocol/Descriptor/DescriptorHandler.cs Snapshots descriptor properties into arrays and partitions subscribing entries to reduce update overhead.
skills/reactor.api.txt API snapshot updated to include PropEntry.Subscribes.
plugins/reactor/skills/reactor-dsl/references/reactor.api.txt DSL skill API snapshot updated to include PropEntry.Subscribes.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

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 5 out of 5 changed files in this pull request and generated 3 comments.

Alexandre Zollinger Chohfi (azchohfi) added a commit that referenced this pull request Jun 25, 2026
Review pass on PR #656 (pr-review skill + multi-model cross-check):

- CollectionDiff scratch: add a [ThreadStatic] s_scratchComparer sentinel so two
  entries of the same closed generic that carry different key comparers each diff
  with their own comparer (the reused scratch previously bound to whichever entry
  ran first). Drain both sets in a finally so reuse always starts clean.
- ReferenceList scratch: drain the cells buffer in a finally so it never retains
  FrameworkElement references between EnsureSubscribed calls.
- Tests: add a comparer-mismatch guard for the CollectionDiff sentinel and a
  handler-level Update test proving OneWay entries still write when the subscribe
  subset is empty (BindFor skipped).

No behavior change for the default-comparer path (the default comparer is the
shared EqualityComparer<TKey>.Default singleton, so the sentinel never rebuilds).

Co-authored-by: Copilot <[email protected]>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

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 5 out of 5 changed files in this pull request and generated no new comments.

@azchohfi

Copy link
Copy Markdown
Collaborator Author

/perf

@github-actions

github-actions Bot commented Jun 25, 2026 •

Copy link
Copy Markdown
Contributor

⚡ Reactor perf comparison

Workload: StressPerf.ReactorOptimized StocksGrid · --percent 50 --duration 10 · x64 Release · median of 12 paired runs (2 warmup dropped); Δ is the mean change with a 95% CI · PR head and main built and run interleaved on the same runner.

Regression vs main baseline

Metric main (baseline) This PR Δ (95% CI) Status
Renders/sec ↑ 2.71 2.52 -2.0% 95% CI [-8.0, +4.1] ≈ within noise
Avg Reconcile (ms) ↓ 134.0 131.1 -2.4% 95% CI [-4.4, -0.5] ✅ improvement
Avg Diff (ms) ↓ 121.0 118.1 -2.1% 95% CI [-4.9, +0.6] ≈ within noise
Avg Memory (MB) ↓ 286.9 283.3 -0.6% 95% CI [-1.4, +0.2] ≈ within noise

Low-mutation skip-floor (--percent 0)

At --percent 0 the workload mutates few cells per tick (always at least one), so reconcile/diff isolate the O(n) per-tick child skip-walk floor that higher mutation rates dilute — ChildReconciler re-walks every child each tick even when nothing moved. The closer --percent is to 0, the more this floor is the signal, so a structural-skip optimization shows up cleanly where the headline table above buries it. Δ is the mean paired change with a 95% CI.

Metric main (baseline) This PR Δ (95% CI) Status
Renders/sec ↑ 15.99 16.66 +7.2% 95% CI [+1.3, +13.1] ✅ improvement
Avg Reconcile (ms) ↓ 35.9 36.2 +0.2% 95% CI [-8.6, +8.9] ≈ within noise
Avg Diff (ms) ↓ 33.8 33.8 +1.5% 95% CI [-7.4, +10.4] ≈ within noise
Avg Memory (MB) ↓ 266.7 267.5 +0.3% 95% CI [0.0, +0.7] ⚠️ regression

Allocation (Reactor) — lower is better

Metric main (baseline) This PR Δ (95% CI) Status
Alloc bytes/render ↓ 5767426 5791952 +0.3% 95% CI [-1.0, +1.6] ≈ within noise
Gen0 GC / 1k renders ↓ 226.50 250.32 +8.7% 95% CI [-2.9, +20.3] ≈ within noise

Keyed-list workload (StressPerf.KeyedList, --percent 50)

A separate macro workload: a ~500-row stably keyed list whose rows are reordered / inserted / removed each tick. Because every child carries a key, the child reconciler takes its keyed arm (ReconcileKeyed → ReconcileKeyedMiddle, the LIS-based minimal-move pass) instead of the positional re-walk the StocksGrid tables above measure — so this is the sensitive macro signal for keyed-diff work the positional cells can never reach. Same interleaved paired-Δ 95% CI as the headline table.

Metric main (baseline) This PR Δ (95% CI) Status
Renders/sec ↑ 19.37 19.41 +7.0% 95% CI [-6.6, +20.6] ≈ within noise
Avg Reconcile (ms) ↓ 17.3 16.8 -3.7% 95% CI [-9.4, +1.9] ≈ within noise
Avg Diff (ms) ↓ 17.0 16.6 -3.7% 95% CI [-9.3, +1.9] ≈ within noise
Avg Memory (MB) ↓ 168.3 168.5 +0.3% 95% CI [-0.5, +1.2] ≈ within noise

Allocation (keyed-list) — lower is better

Metric main (baseline) This PR Δ (95% CI) Status
Alloc bytes/render ↓ 313374 313526 0.0% 95% CI [-0.4, +0.3] ≈ within noise
Gen0 GC / 1k renders ↓ 15.83 15.19 -2.8% 95% CI [-13.2, +7.5] ≈ within noise

Reconciler micro-benchmarks (PerfBench.ControlModel)

Production --variant Reactor control-model path, ns-resolution and WinUI-undiluted (spec-047 M1–M13) — ↓ lower is better. Status tracks allocated bytes/op, the authoritative signal here; it is deterministic for structurally-fixed benches, while dispatcher / background-thread benches carry a small process-to-process offset, so a bench is flagged only when its 95% CI clears a ±3% minimum-effect band (real structural alloc changes are several percent to many-x). ns/op is shown for context but is not auto-flagged (its paired CI is rep-interleaved but the flag remains dormant pending a real-CI identical-binary band calibration). Δ is the mean paired change with a 95% CI.

Bench main ns/op Δ ns (95% CI) main B/op Δ alloc (95% CI) Status
M1 Mount_Leaf_NoCallback 149730.5 -1.5% 95% CI [-3.0, -0.1] 1140.9 +0.1% 95% CI [-0.1, +0.2] ≈ within noise
M2 Mount_Leaf_OneCallback 110736.8 -2.7% 95% CI [-6.2, +0.9] 3383.3 0.0% 95% CI [0.0, 0.0] ≈ within noise
M3 Mount_Leaf_ThreeCallbacks 224983.3 -0.6% 95% CI [-4.1, +3.0] 8439.9 +0.6% 95% CI [-1.4, +2.6] ≈ within noise
M4 Dispatch_Switch_Cold 111041.2 -3.2% 95% CI [-5.4, -1.0] 1767.8 0.0% 95% CI [0.0, 0.0] ≈ within noise
M5 Dispatch_Switch_Warm 110078.2 +7.9% 95% CI [-1.2, +17.0] 1766.0 0.0% 95% CI [-1.2, +1.3] ≈ within noise
M6 Dispatch_ExternalType 90702.3 +3.2% 95% CI [-2.2, +8.7] 987.6 +0.1% 95% CI [-2.1, +2.2] ≈ within noise
M7 Update_NoChange 55300.4 -0.9% 95% CI [-1.5, -0.3] 452.1 +0.4% 95% CI [-5.1, +5.8] ≈ within noise
M8 Update_OneLeafChanged 42082.1 -1.6% 95% CI [-2.9, -0.3] 536.0 0.0% 95% CI [0.0, 0.0] ≈ within noise
M9 Update_AllChanged 2851829.6 -0.5% 95% CI [-2.8, +1.8] 184278.1 0.0% 95% CI [0.0, 0.0] ≈ within noise
M10 EventHandlerState_Alloc 88419.4 +0.2% 95% CI [-3.2, +3.6] 3095.2 0.0% 95% CI [0.0, 0.0] ≈ within noise
M11 ModifierEHS_Frequency 47109.0 +0.5% 95% CI [-4.4, +5.4] 638.9 0.0% 95% CI [+0.1, +0.1] ≈ within noise
M12 Pool_Rent_HotPath 118099.3 +0.5% 95% CI [-0.5, +1.5] 1099.9 0.0% 95% CI [0.0, 0.0] ≈ within noise
M13 Setters_Suppression_Scope 113.3 +3.0% 95% CI [-20.0, +26.1] 26.7 +0.2% 95% CI [+0.2, +0.2] ≈ within noise
M14 Dsl_Rebuild_Cascade 1559255.9 +0.2% 95% CI [-2.1, +2.4] 2231828.9 0.0% 95% CI [0.0, 0.0] ≈ within noise
C207 ChangeHandler_DpRead_Coalesce 1329.3 +3.1% 95% CI [-13.8, +20.1] 0.6 0.0% 95% CI [0.0, 0.0] ≈ within noise
OAlloc Optional_Element_Alloc 212.7 +2.6% 95% CI [-2.1, +7.2] 528.0 0.0% 95% CI [0.0, 0.0] ≈ within noise
OUpdate Optional_Reconciler_Update 12212.7 +0.3% 95% CI [-2.4, +2.9] 2772.3 0.0% 95% CI [0.0, 0.0] ≈ within noise

Cross-framework reference (same StocksGrid workload)

Metric vanilla WinUI3¹ Rust windows-reactor² Reactor (this PR)
Renders/sec ↑ 3.21 4.80 2.52
Avg Reconcile (ms) ↓ n/a 20.5 131.1
Avg Diff (ms) ↓ n/a 18.5 118.1
Avg Memory (MB) ↓ 263.7 198.4 283.3

↑ higher is better · ↓ lower is better. Within noise = the 95% confidence interval of the paired Δ includes 0 (no change resolvable at this sample size); ✅ improvement / ⚠️ regression require the CI to exclude 0.
Allocation metrics (alloc bytes/render, Gen0 GC) are the sensitive signal for allocation-reduction work, where the mean-ms / memory figures are largely flat. They read n/a for a harness built from a revision that predates them (rebase the PR onto main to populate them).
Reconciler micro-benchmarks run PerfBench.ControlModel --variant Reactor (M1–M13) as a headless loop bracketed by per-thread alloc + GC counters — ns-resolution and free of WinUI render / working-set dilution, so they resolve Core/Reconciler allocation deltas the macro StocksGrid workload cannot. main and PR each link their own src/Reactor build and are rep-interleaved (a fresh alternated process per rep); Δ is the paired 95% CI over per-rep means. The Status column tracks allocated bytes/op (deterministic for identical code); ns/op is informational — its paired CI is now unbiased but the flag stays dormant pending a real-CI identical-binary band calibration.
¹ vanilla WinUI3 = StressPerf.Direct (imperative; no virtual-DOM, so it has no reconcile/diff phase — those cells read n/a). Measured live on this runner.
² Rust = test_reactor_perf from microsoft/windows-rs — a port of this harness (same StocksGrid, same --percent/--duration CLI). Built from source and measured live on this runner.
Absolute numbers are runner-dependent — trust the Δ vs main, not the absolute values. Memory (working set) is the noisiest metric.
Runner: CPU: AMD EPYC 7763 64-Core Processor · 4 logical cores · 16 GB RAM · runner: GitHub Actions 1043003943.
Generated by .github/workflows/perf-compare.yml · PR 0904910 vs main e8572a0 · 2026-06-27T06:29:03Z · run log.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

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 5 out of 5 changed files in this pull request and generated 1 comment.

@azchohfi

Copy link
Copy Markdown
Collaborator Author

/perf

@azchohfi

Copy link
Copy Markdown
Collaborator Author

/perf

@azchohfi

Copy link
Copy Markdown
Collaborator Author

/perf

1 similar comment
@azchohfi

Copy link
Copy Markdown
Collaborator Author

/perf

@azchohfi

Copy link
Copy Markdown
Collaborator Author

/perf

Optimizes the descriptor diff machinery shared by all descriptor-based
controls. Behavior is preserved exactly (same props written, same
subscriptions fire, controlled/echo semantics unchanged) and the path
stays AOT/trim-clean.

#115: store value comparers as nullable (null = default) and route all
compares through an AggressiveInlining PropValueComparison.ValuesEqual
helper that calls EqualityComparer<T>.Default.Equals directly, which the
JIT devirtualizes + inlines for value-type props. Custom comparers are
still honored through the interface call.

#114/#117: add a Subscribes discriminator on PropEntry and snapshot the
descriptor Properties into concrete PropEntry[] arrays in the handler
ctor. Mount/Update iterate the concrete arrays (no interface-indexer
dispatch) and the per-Update subscribe pass visits only the small
_subscribeEntries subset, skipping BindFor entirely when it is empty
(the dominant OneWay-only grid-cell case). Reference entries must
re-evaluate every Update, so only the empty-subset skip is used (no
"wired" flag).

#119: reusable [ThreadStatic] cleared-on-use scratch HashSets in
CollectionDiffControlledPropEntry.Update, removing 2 allocs/update.

#120: ReferenceListPropEntry now lives in the subscribe subset and uses
a [ThreadStatic] scratch cells list, removing its per-Update allocation.

Adds PropEntryDiffDispatchTests covering write-on-change/skip-on-equal
(default + custom comparer), the comparer helper, the Subscribes
discriminator (with a reflection invariant guard), handler partitioning,
and collection-diff scratch reuse. The reactor.api.txt files are
regenerated by the build to include the new public PropEntry.Subscribes
member.

Co-authored-by: Copilot <[email protected]>
The #115 comparer-devirtualization change made the per-entry _comparer
field nullable (null = use EqualityComparer<TValue>.Default). The
controlled echo-arm path assigned this nullable field straight onto
payload.EchoComparer, so the default case now stored null instead of the
concrete EqualityComparer<TValue>.Default instance it held before.

Echo *suppression* still worked (every consumer reads EchoComparer ??
Default), but the observable payload field changed, regressing selftest
PropEntryOptional_Controlled_Update_HasValueChange_ArmsEcho which asserts
ReferenceEquals(EchoComparer, EqualityComparer<int>.Default).

Resolve the null to the default at the arming site, restoring the exact
prior observable value. Verified: full selftest suite 5181/0.

Co-authored-by: Copilot <[email protected]>
Review pass on PR #656 (pr-review skill + multi-model cross-check):

- CollectionDiff scratch: add a [ThreadStatic] s_scratchComparer sentinel so two
  entries of the same closed generic that carry different key comparers each diff
  with their own comparer (the reused scratch previously bound to whichever entry
  ran first). Drain both sets in a finally so reuse always starts clean.
- ReferenceList scratch: drain the cells buffer in a finally so it never retains
  FrameworkElement references between EnsureSubscribed calls.
- Tests: add a comparer-mismatch guard for the CollectionDiff sentinel and a
  handler-level Update test proving OneWay entries still write when the subscribe
  subset is empty (BindFor skipped).

No behavior change for the default-comparer path (the default comparer is the
shared EqualityComparer<TKey>.Default singleton, so the sentinel never rebuilds).

Co-authored-by: Copilot <[email protected]>
- Route the [ThreadStatic] scratch writes through private static helpers
  (RentScratchCells / RentScratchSets) so the lazy-init no longer writes a
  static field from an instance method body (CodeQL cs/static-field-written-by-
  instance). Behavior is identical and the per-thread reuse (the #119/#120 perf
  win) is preserved — using method-local sets, as the analyzer alternatively
  suggested, would reintroduce the exact per-update allocations these buffers
  exist to remove.
- Fix the XML doc on PropEntry.Subscribes to reference the real guard test
  (PropEntryDiffDispatchTests.Subscribes_OverrideMatches_EnsureSubscribedOverride_ForEveryEntry).

The Copilot comparer-mismatch finding on the CollectionDiff scratch is resolved
by the s_scratchComparer sentinel added in the previous commit.

Co-authored-by: Copilot <[email protected]>
The pr-review pass (correctness dimension, confirmed by a gpt-5.4 multi-model
cross-check) flagged that the [ThreadStatic] scratch reuse added in #119/#120
is not reentrancy-safe, unlike origin/main which allocated fresh per-call
HashSets/Lists. A CollectionDiff mutation (e.g. CalendarView.SelectedDates) can
echo synchronously -> user callback -> inline rerender -> nested Update on the
same thread + closed generic while the shared scratch is still populated,
corrupting the in-flight outer diff.

Fix: add a [ThreadStatic] in-use flag to both entries. Rent returns the shared
scratch (allocation-free fast path) only when not already in use; a nested call
gets fresh per-call collections (the pre-#119/#120 behavior) without touching
the shared scratch or comparer sentinel. Return clears + releases the shared
scratch in a finally only when it owned it. All [ThreadStatic] writes stay in
the static Rent/Return helpers (CodeQL cs/static-field-written-by-instance).

Also strengthen the PropEntry.Subscribes XML doc with an explicit warning that
external subclassers overriding EnsureSubscribed must also override Subscribes.

Tests (tests/Reactor.Tests, headless):
- CollectionDiff_ScratchDrainedAfterException_NoStaleKeyLeak: a throwing diff
  must still drain the shared scratch so the next diff is clean.
- CollectionDiff_NestedReentrantUpdate_DoesNotCorruptOuterDiff: a nested diff
  on a second entry of the same closed generic must not corrupt or over-churn
  the outer diff (asserts via a mutation-counting IList).

Co-authored-by: Copilot <[email protected]>
@azchohfi

Copy link
Copy Markdown
Collaborator Author

/perf

@azchohfi
Alexandre Zollinger Chohfi (azchohfi) force-pushed the azchohfi-perf-descriptor-diff-dispatch branch from 0df2ced to eb14f88 Compare June 26, 2026 07:33
@azchohfi

Copy link
Copy Markdown
Collaborator Author

/perf

@azchohfi

Copy link
Copy Markdown
Collaborator Author

/perf

@azchohfi

Copy link
Copy Markdown
Collaborator Author

Closing per the re-validation sweep on current main. This descriptor-dispatch change shows a small, real, mechanism-aligned TIME win - macro reconcile -2.4% [-4.4,-0.5] + diff -2.1%, and dispatch micros M4 -3.2% / M7 -0.9% / M8 -1.6% (all CIs exclude 0) - but no allocation component and a small magnitude. With four substantial wins now shipped, this is below the bar that justifies a full review+merge cycle. The win is real if revisited - reopen if the per-prop-diff-dispatch path becomes a bigger latency factor.

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.

perf: devirtualize per-prop diff dispatch in V1 descriptor

2 participants