Skip to content

fix(reconciler): preserve Grid children on child type flip (#34) - #36

Merged
Chris Anderson (codemonkeychris) merged 2 commits into
mainfrom
fix/34-cell-loss-async-commit
Apr 19, 2026
Merged

Chris Anderson (codemonkeychris) merged 2 commits into
mainfrom
fix/34-cell-loss-async-commit

Conversation

@codemonkeychris

@codemonkeychris Chris Anderson (codemonkeychris) commented Apr 19, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

  • Fixes DataGrid cells lost from UIA tree after async commit triggers row state transition #34 — DataGrid cells disappearing from the UIA tree after async-commit state transitions, exposed by the Interactive_DataGrid_ClickEditTabCommit E2E test.
  • Root cause: ReconcileImperative called UnmountAndPool on the replaced control, which eagerly detached it from its parent via ElementPool.Return → DetachFromParent before the caller performed g.Children[i] = replacement. The detach shifted sibling indices; UpdateGrid's fast path then overwrote a sibling with the replacement and fell off the end of the loop at i >= g.Children.Count, dropping the trailing cell and leaving the retargeted sibling with a stale AutomationProperties.Name.
  • Fix: switched both UnmountAndPool calls in ReconcileImperative to plain Unmount, mirroring the pattern already used by ChildReconciler's ReplaceChildWithExitTransition. WinUI's indexer assignment handles parent bookkeeping cleanly.
  • Regression coverage: new DataGrid_CellTypeFlipPreservesTrailingCells selfhost fixture that mounts a 4-column Grid, flips its middle child between TextBlock and TextField, and asserts child count + per-cell AutomationProperties.Name survive the flip and the flip-back.

Test plan

  • Build: library + host test project compile clean (0 warnings, 0 errors).
  • Unit tests (dotnet test tests/Reactor.Tests): 4238/4238 pass, 0 failures.
  • Unit tests — Reconciler + Grid subset: 374/374 pass.
  • Selfhost tests (Reactor.AppTests.Host.exe --self-test): Total failures: 0. New fixture DataGrid_CellTypeFlipPreservesTrailingCells contributes 17 green assertions covering child count preservation and AutomationName integrity across a TextBlock↔TextBox flip cycle.
  • E2E (Interactive_DataGrid_ClickEditTabCommit): not run locally — WinAppDriver won't stay resident in this shell (requires an interactive desktop session / elevated context). CI or a manual run on a reviewer's machine is required to confirm the previously-failing test now passes.

🤖 Generated with Claude Code

… Grid children on type flip

When a child's element type changed during reconciliation (e.g. a DataGrid
cell entering or leaving inline-edit mode — TextBlock → TextBox → TextBlock),
ReconcileImperative called UnmountAndPool on the replaced control. The pool's
Return path invokes DetachFromParent, which synchronously removes the old
child from its parent collection before the caller gets a chance to perform
its own g.Children[i] = replacement assignment. The eager detach shifted
subsequent sibling indices down by one, after which the fast-path Grid update
loop in UpdateGrid overwrote a valid sibling and fell off the end via the
i >= g.Children.Count guard — dropping the trailing cell and leaving the
retargeted sibling carrying a stale AutomationProperties.Name.

Switch both UnmountAndPool calls in ReconcileImperative to Unmount so the
parent collection is left untouched; the caller's indexer assignment cleanly
replaces the old control and WinUI handles parent bookkeeping. This mirrors
the pattern already used by ChildReconciler's ReplaceChildWithExitTransition.

Fixes #34 — DataGrid cells disappearing from the
UIA tree after async-commit state transitions exposed by
Interactive_DataGrid_ClickEditTabCommit.

Adds a selfhost regression fixture DataGrid_CellTypeFlipPreservesTrailingCells
that mounts a 4-column Grid, flips its middle child between TextBlock and
TextField, and asserts the row's child count and per-cell AutomationName
survive the flip and flip-back.

Co-Authored-By: Claude Opus 4.7 (1M context) <[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

Fixes a reconciler edge case where flipping a Grid child’s element/control type (e.g., TextBlock ↔ TextBox) could corrupt sibling indices during reconciliation, causing trailing cells to disappear and UIA AutomationProperties.Name to become stale/missing (notably impacting DataGrid editing scenarios tied to #34).

Changes:

  • Updated ReconcileImperative to avoid pooling-detach behavior during replace/type-flip by using Unmount instead of UnmountAndPool.
  • Added a new selfhost regression fixture (DataGrid_CellTypeFlipPreservesTrailingCells) validating child-count stability and UIA naming across a flip and flip-back.
  • Registered the new fixture in the self-test registry.

Reviewed changes

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

File Description
src/Reactor/Core/Reconciler.cs Changes reconciliation unmount behavior on control replacement/type changes to prevent parent-child collection index corruption.
tests/Reactor.AppTests.Host/SelfTest/Fixtures/DataGridEditFixtures.cs Adds a regression selfhost fixture reproducing the Grid child type-flip scenario and asserting correctness post-fix.
tests/Reactor.AppTests.Host/SelfTest/SelfTestFixtureRegistry.cs Registers the new regression fixture so it runs in the self-test suite.

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

Comment thread src/Reactor/Core/Reconciler.cs Resolved
Comment thread src/Reactor/Core/Reconciler.cs Resolved
- Reconciler.cs: tighten the rationale comment block. DetachFromParent lives
  inside ElementPool.Return (called by UnmountAndPool), not inside
  UnmountAndPool directly. Also call out that the switch to Unmount means
  replaced controls are no longer returned to the pool — this is a deliberate
  correctness-over-perf trade-off (type flips are rare; a follow-up could
  reintroduce post-swap pool-return safely).
- DataGridEditFixtures.cs: strengthen the regression assertions for
  CellTypeFlipPreservesTrailingCells. Require AutomationProperties.Name to
  equal the visible text exactly rather than "empty OR match" — the #34 bug
  surfaces as either a cleared name (CleanElement) or a stale sibling name
  (shift corruption), both of which the weaker assertion would have silently
  accepted.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@codemonkeychris

Copy link
Copy Markdown
Collaborator Author

CI status note

The Unit Tests job has been failing on this PR with a TimeoutException in QueryCacheThreadingTests.Stress_1000_Keys_Mixed_Ops_Terminates_Without_Exceptions. Investigation:

  • The test is a pure threading stress test over QueryCache (no UI, no reconciler involvement — it does cache.Set/TryGet/Invalidate/Subscribe/Unsubscribe/EvictNow across 8 worker tasks for 500ms, then waits 10s for them to join).
  • It passes locally in 511ms on my machine against this branch.
  • It has zero code-path overlap with the diff in this PR (ReconcileImperative in src/Reactor/Core/Reconciler.cs).
  • The 10s WaitAsync deadline appears to be brittle under GitHub Actions runner load — workers spin on cache ops until cancellation, and when the runner is oversubscribed they can take longer than 10s to observe the token.

This looks like a pre-existing flake that this PR is unlucky enough to have hit twice in a row. Happy to either re-run CI one more time or file a separate issue to bump the timeout / StressThreads in QueryCacheThreadingTests.cs, but I don't believe it's blocking this fix.

@codemonkeychris
Chris Anderson (codemonkeychris) merged commit ce79ebb into main Apr 19, 2026
3 checks passed
@codemonkeychris
Chris Anderson (codemonkeychris) deleted the fix/34-cell-loss-async-commit branch May 28, 2026 19:11
Alexandre Zollinger Chohfi (azchohfi) added a commit that referenced this pull request Jun 26, 2026
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]>
Alexandre Zollinger Chohfi (azchohfi) added a commit that referenced this pull request Jun 27, 2026
…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]>
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.

DataGrid cells lost from UIA tree after async commit triggers row state transition

2 participants