Skip to content

fix(virtualization): propagate LazyStack keySelector to row Element.Key (#326) - #635

Merged
Alexandre Zollinger Chohfi (azchohfi) merged 2 commits into
mainfrom
azchohfi-lazystack-keyselector-element-key
Jun 23, 2026
Merged

Alexandre Zollinger Chohfi (azchohfi) merged 2 commits into
mainfrom
azchohfi-lazystack-keyselector-element-key

Conversation

@azchohfi

Copy link
Copy Markdown
Collaborator

Summary

The post-#324 ItemsRepeater recycle path (ElementFactory<T>) reused a realized inner Component<T> across different logical items while scrolling, because each row's top-level Element.Key was null. Reconciler.CanUpdate then returned true for same-type rows, taking an in-place property diff that carried the row's UseState/UseEffect state from item A into item B — e.g. an inline editor's "dirty" flag for item 5 stayed dirty when its control was recycled for item 12. This matched WinUI RecyclingElementFactory behavior but is a footgun.

Fix: in the spec-042 ReactorRow path, propagate the author's keySelector projection onto the built row's Element.Key (ElementFactory<T>.ApplyItemIdentityKey). A different logical item now yields a different key → CanUpdate returns false → Reactor takes its keyed-replacement path (unmount + fresh mount) → per-item Component state resets cleanly. Same-item re-renders keep the same key and still diff in place (state preserved).

Design decision — always-on, explicit .WithKey wins (Q1 / Q2)

I chose always-on rather than an opt-in flag, with explicit author keys winning:

  • Always-on for the keyed list path. Per-item identity reset is the intuitive default; state carry-over across logical items is a footgun, not a feature. The perf data below shows no regression, so the opt-in fallback (resetStateOnRecycle:) the issue allows is unnecessary.
  • Explicit author .WithKey(...) always wins — the implicit key is only applied when the built row's Key is still null.
  • Legacy int-index path left unkeyed. On that path the "key" is the realized index, not item identity; keying it would force a control swap on every scroll and break the bounded-working-set fix(virtualization): proper ItemsRepeater recycling — stop leaking every realized container #324 fixtures. All live LazyVStack/LazyHStack/ItemsRepeater<T>/ItemsView<T> bind an ObservableCollection<ReactorRow> source (spec 042), so they all get the fix through the single central site.

Issue questions

  • Q3 (ListView/GridView): Not affected. TemplatedListLifecycle + HandleTemplatedContainerContentChanging already unmount container content on InRecycleQueue and mount fresh on realize, so per-item state already resets there. No change needed.
  • Q4 (does KeyedListDiff already key the realized row?): No. KeyedListDiff keys only the OC<ReactorRow> level (for move/insert/remove); the realized row's Element.Key was never set. The fix sets it at realization/refresh in ElementFactory<T>.

Perf check (Q5 — required)

Homogeneous-row scroll-recycle, StressPerf.VirtualList.Reactor --headless --count 5000 --duration 6, ARM64 Release, clean back-to-back A/B (core file reverted via git stash for BEFORE, identical platform/build):

Metric BEFORE AFTER Δ
Avg dt 16.64 ms 16.65 ms +0.01
P50 16.67 ms 16.67 ms 0.00
P95 17.81 ms 17.84 ms +0.03
P99 22.15 ms 22.30 ms +0.15
Max 25.36 ms 24.96 ms −0.40
WS 177 MB 182 MB +5 MB

No meaningful regression. The keyed reuse path swaps via ElementPool (the raw control is recycled on Unmount→Mount, not reallocated) and stays well within the 60fps frame budget; tail latency is unchanged. No swap-mitigation was needed.

Tests

  • Unit (tests/Reactor.Tests/ElementFactoryKeyPropagationTests.cs): null→key, explicit author key wins, distinct items get distinct keys, concrete record type preserved through the with copy.
  • SelfTest (tests/Reactor.AppTests.Host/SelfTest/Fixtures/ElementFactoryRecyclingFixtures.cs):
    • EFR_Factory_KeyChangeRecycle_ResetsRowComponentState — fresh component instance (ctor=2) + new effect mount + old effect cleanup on cross-key reuse.
    • EFR_Factory_SameItemReuse_PreservesRowComponentState — same instance (ctor=1), no extra mount/cleanup on same-key re-render.
  • Existing fix(virtualization): proper ItemsRepeater recycling — stop leaking every realized container #324 EFR, LazyStack, Keyed, VirtualList, ItemsRepeater, ItemsView fixtures stay green. Full dotnet test tests/Reactor.Tests = 9478 passed, 0 failed.

Docs

docs/guide/collections.md gains a "Per-item Component state resets on recycle" section documenting the default behavior and the explicit-.WithKey precedence (edited the docs/_pipeline/templates/collections.md.dt template and recompiled via mur docs compile).

Closes #326

…ey (#326)

The post-#324 ItemsRepeater recycle path (ElementFactory<T>) reused a realized
inner Component<T> across different logical items while scrolling, because the
row's top-level Element.Key was null. Reconciler.CanUpdate then returned true
for same-type rows, taking an in-place property diff that carried the row's
UseState/UseEffect state from item A into item B (e.g. an editor's "dirty"
flag for item 5 stayed dirty when its control was recycled for item 12).

Fix: in the spec-042 ReactorRow path, propagate the author's keySelector
projection onto the built row's Element.Key (ApplyItemIdentityKey). A different
logical item now yields a different key, flipping CanUpdate to false so Reactor
takes its keyed-replacement path (unmount + fresh mount) and resets per-item
Component state. Same-item re-renders keep the same key and still diff in place.

Design decision (always-on, explicit key wins):
- Always-on for the keyed list path: per-item identity reset is the intuitive
  default; carry-over across logical items is a footgun, not a feature.
- An explicit author .WithKey(...) on the row always wins (key is only applied
  when the built row's Key is still null).
- The legacy int-index path is left unkeyed (its "key" is the realized index,
  not item identity; keying it would force a swap on every scroll and break the
  bounded-working-set #324 fixtures).
- ListView<T>/GridView<T> are unaffected: TemplatedListLifecycle already
  unmounts container content on recycle and mounts fresh on realize.

Perf (homogeneous-row scroll, StressPerf.VirtualList, ARM64 Release, clean A/B):
  before  Avg 16.64ms  P95 17.81  P99 22.15  Max 25.36  WS 177MB
  after   Avg 16.65ms  P95 17.84  P99 22.30  Max 24.96  WS 182MB
No meaningful regression: the swap reuses pooled controls via ElementPool and
stays within the 60fps frame budget.

Tests:
- Unit: ElementFactoryKeyPropagationTests (null->key, explicit key wins, distinct
  items get distinct keys, concrete record type preserved).
- SelfTest: EFR_Factory_KeyChangeRecycle_ResetsRowComponentState (fresh component
  + effect remount on cross-key reuse) and EFR_Factory_SameItemReuse_Preserves
  RowComponentState (state preserved on same-key re-render). Existing #324 EFR /
  LazyStack / Keyed / VirtualList fixtures stay green.

Docs: collections.md "Per-item Component state resets on recycle" section
(template + regenerated guide).

Closes #326

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

This PR fixes a virtualization/recycling footgun in the spec-042 ItemsRepeater path by ensuring the author’s keySelector identity is propagated onto the realized row’s top-level Element.Key. With a stable per-item key present, Reconciler.CanUpdate correctly rejects cross-item reuse (same type, different logical item) and forces a remount so per-item Component hook state (UseState/UseEffect) does not leak between items during scroll recycling.

Changes:

  • Propagate spec-042 ReactorRow.Key (keySelector projection) to the built row’s Element.Key via ElementFactory<T>.ApplyItemIdentityKey on the keyed path only.
  • Add unit + selftest coverage to validate (a) implicit key assignment, (b) explicit .WithKey(...) precedence, and (c) cross-item recycle remount vs same-item in-place update.
  • Document the default “per-item component state resets on recycle” behavior (and explicit .WithKey override) in the collections guide (template + generated output).

Reviewed changes

Copilot reviewed 6 out of 6 changed files in this pull request and generated no comments.

Show a summary per file
File Description
src/Reactor/Core/ElementFactory.cs Applies item identity key to the realized row element on the spec-042 keyed path, influencing CanUpdate and recycle reconciliation behavior.
tests/Reactor.Tests/ElementFactoryKeyPropagationTests.cs Unit tests for ApplyItemIdentityKey semantics (null→key, derived record preservation, explicit key precedence).
tests/Reactor.AppTests.Host/SelfTest/Fixtures/ElementFactoryRecyclingFixtures.cs Selftests asserting cross-key reuse remounts (state reset) while same-key reuse diffs in place (state preserved).
tests/Reactor.AppTests.Host/SelfTest/SelfTestFixtureRegistry.cs Registers the two new selftest fixtures for discovery and construction.
docs/_pipeline/templates/collections.md.dt Source template documenting per-item state reset-on-recycle and explicit key override behavior.
docs/guide/collections.md Generated guide output reflecting the updated template content.

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

…ms (#326)

pr-review H1/L1/M1/L2 follow-up.

H1+L1: RefreshRealizedItems now handles Reconcile's replacement return value
(CanUpdate=false on a same-slot key change, e.g. the documented
.WithKey({id}:{rev}) revision-bump pattern). Because the WinUI ItemsRepeater
that owns realized rows is not a Panel, its children cannot be reparented from
managed code the way GetElement's framework return-channel allows. New
Reconciler.TryAdoptRealizedReplacement transplants the freshly-mounted component
subtree into the still-parented wrapper Border and migrates the _componentNodes
entry, so the old control is no longer orphaned (stale state stayed visible),
_lastElementByControl no longer mistracks, and the inner Component's UseState
resets end-to-end. Non-adoptable shapes (root type change) fall back to
tracking-only reconciliation. New live-repeater selftest
Factory_RefreshKeyChange_RemountsRealizedRow asserts the end-to-end state reset,
old-control removal, and tracking consistency.

M1: CHANGELOG [Unreleased] entry for the per-item-state-resets-on-recycle
behavior change.

L2: collections.md documents the constant-key / hoist-state opt-out for durable
carry-over across recycles.

Co-authored-by: Copilot <[email protected]>
@azchohfi
Alexandre Zollinger Chohfi (azchohfi) merged commit f7ecd23 into main Jun 23, 2026
17 checks passed
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.

Propagate LazyStack keySelector to row Element.Key so reused rows reset per-item Component state

2 participants