Repository navigation
fix(virtualization): propagate LazyStack keySelector to row Element.Key (#326) - #635
Merged
Alexandre Zollinger Chohfi (azchohfi) merged 2 commits intoJun 23, 2026
Conversation
…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]>
Alexandre Zollinger Chohfi (azchohfi)
requested a review
from Chris Anderson (codemonkeychris)
as a code owner
June 23, 2026 01:15
Contributor
There was a problem hiding this comment.
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’sElement.KeyviaElementFactory<T>.ApplyItemIdentityKeyon 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
.WithKeyoverride) 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]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
The post-#324
ItemsRepeaterrecycle path (ElementFactory<T>) reused a realized innerComponent<T>across different logical items while scrolling, because each row's top-levelElement.Keywasnull.Reconciler.CanUpdatethen returnedtruefor same-type rows, taking an in-place property diff that carried the row'sUseState/UseEffectstate 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 WinUIRecyclingElementFactorybehavior but is a footgun.Fix: in the spec-042
ReactorRowpath, propagate the author'skeySelectorprojection onto the built row'sElement.Key(ElementFactory<T>.ApplyItemIdentityKey). A different logical item now yields a different key →CanUpdatereturnsfalse→ 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
.WithKeywins (Q1 / Q2)I chose always-on rather than an opt-in flag, with explicit author keys winning:
resetStateOnRecycle:) the issue allows is unnecessary..WithKey(...)always wins — the implicit key is only applied when the built row'sKeyis stillnull.LazyVStack/LazyHStack/ItemsRepeater<T>/ItemsView<T>bind anObservableCollection<ReactorRow>source (spec 042), so they all get the fix through the single central site.Issue questions
TemplatedListLifecycle+HandleTemplatedContainerContentChangingalready unmount container content onInRecycleQueueand mount fresh on realize, so per-item state already resets there. No change needed.KeyedListDiffkeys only theOC<ReactorRow>level (for move/insert/remove); the realized row'sElement.Keywas never set. The fix sets it at realization/refresh inElementFactory<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 viagit stashfor BEFORE, identical platform/build):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
tests/Reactor.Tests/ElementFactoryKeyPropagationTests.cs): null→key, explicit author key wins, distinct items get distinct keys, concrete record type preserved through thewithcopy.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.dotnet test tests/Reactor.Tests= 9478 passed, 0 failed.Docs
docs/guide/collections.mdgains a "Per-item Component state resets on recycle" section documenting the default behavior and the explicit-.WithKeyprecedence (edited thedocs/_pipeline/templates/collections.md.dttemplate and recompiled viamur docs compile).Closes #326