Skip to content

Fix #1090: don't arm echo suppression for a SelectedIndex write WinUI can't honor - #1091

Merged
Alexandre Zollinger Chohfi (azchohfi) merged 4 commits into
mainfrom
azchohfi-fix-listview-echo-suppression-strand
Aug 17, 2026
Merged

Alexandre Zollinger Chohfi (azchohfi) merged 4 commits into
mainfrom
azchohfi-fix-listview-echo-suppression-strand

Conversation

@azchohfi

@azchohfi Alexandre Zollinger Chohfi (azchohfi) commented Aug 13, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #1090.

Credit to kouhe3 (@kouhe3), who reproduced my counter-experiments, retracted their original theory, and supplied the corrected mechanism plus a minimal repro. That is what made this fix possible.

Root cause (confirmed)

Echo suppression arms one token per expected change event. The controlled SelectedIndex write was gated only on drift (control != requested), which is not sufficient: WinUI will not honor a selection past the end of its ItemsSource. The property stays put, no SelectionChanged is raised, and the armed token strands — later swallowing the user's next genuine selection.

The common trigger is an items array that is still empty on mount while its data loads — idiomatic for UseState<T[]>([]) plus a fetch.

Instrumented ledger on unfixed code, driving the repro with real mouse clicks against the installed runtime:

MOUNT  write: itemsCount=0 current=-1 -> 0
BEGIN  count=1
MOUNT  write done: readback=-1        // clamped - no event
UPDATE write: itemsCount=0 current=-1 -> 0
BEGIN  count=2
UPDATE write done: readback=-1        // clamped - no event
SHOULD consumed -> count=1            // items arrive: ONE coalesced event
...                                   // counter never returns to 0
SHOULD consumed -> count=0            // the user's first real click, eaten

Two clamped writes arm two tokens; the single coalesced materialization event consumes only one. The leftover eats the first real click. The counter never returns to 0 after startup - that is the signature.

The fix

A reachability guard: only write - and therefore only arm - when the requested index actually exists in the current source.

if (lv.SelectedIndex is { HasValue: true } mountIndex
    && listView.SelectedIndex != mountIndex.Value
    && IsReachable(mountIndex.Value, lv.Items.Length))
{
    ReactorBinding.WriteSuppressed(listView, () => listView.SelectedIndex = mountIndex.Value);
}

private static bool IsReachable(int index, int itemCount)
    => index < 0 || index < itemCount;

A write that cannot land is skipped; the later update that brings the items in performs it instead, where it lands and echoes normally. -1 stays always-reachable - it is the spec-050 force-clear sentinel and is meaningful against any source.

Keyed on reachability, not Items.Length == 0. Empty is just the common case: an index past the end of a short non-empty source has the same defect. Unguarded, that variant additionally throws ArgumentException from the setter - surfaced by its own fixture.

Applied identically to ListViewHandler and GridViewHandler (Mount + Update).

Verification

End to end, real mouse input. The reporter's repro as a framework-dependent unpackaged app binding the installed WindowsAppRuntime 2.3.1, clicks driven through the accessibility tree:

before after
click b after the combo switch row highlights, state index: 0 (callback never ran) row highlights, state index: 1, LISTVIEW CALLBACK #1: i=1

Mutation-checked. Removing just the two guard clauses makes all three new fixtures fail:

not ok Issue1090_EmptyMount_FirstRealSelectionFires
not ok Issue1090_GVEmptyMount_FirstRealSelectionFires
not ok Issue1090_ListView_IndexPastEndOfShortSource_FirstRealSelectionFires_CRASH - ArgumentException

Suites. 13288 unit tests pass; 1439 selftest fixtures pass (including all six Issue495_* render-storm guards and the ValueDiff_* / Issue464_* echo guards); Release builds of src/Reactor and the selftest host are clean.

About the first commit on this branch

12b500a8 addressed a different, unconfirmed hypothesis - that the ItemsSource swap could preserve a selection and strand a token. I could not reproduce that on any runtime; both WASDK 2.1 and 2.3.1 always reset the selection and always fire. That commit's BeginSuppressCancelable / EchoSuppressArm primitive is therefore hardening, not a fix, and is a no-op on observed behavior.

It is retained here because it removes an unverified platform assumption from the same code path and carries 12 mutation-checked headless tests. If reviewers would rather keep this PR minimal, say so and I will drop that commit - the actual #1090 fix is entirely in 56988bc6 and stands alone.

Sibling audit

Every other BeginSuppress call site is drift-gated. Worth noting the same class of defect could exist wherever a suppressed write can be rejected or coerced by the control - this fix addresses the SelectedIndex/ItemsSource pair specifically.

One unrelated observation, recorded rather than changed: TemplatedListLifecycle.ApplyKeyedDiffOrFallback reassigns ItemsSource with no suppression on its bailout path. That is a potential leak, not a strand, and no fixture demonstrates a defect there.

…ollows

ListViewHandler.Update and GridViewHandler.Update armed
ChangeEchoSuppressor.BeginSuppress speculatively, immediately before
reassigning ItemsSource, on the assumption that WinUI always drops
SelectedIndex to -1 and fires SelectionChanged to consume it.

That assumption is version-dependent. The runtime bundled with WASDK
2.1.x does reset the selection, synchronously, even when the old index
is still valid in the new source. Newer runtimes can preserve a
still-valid selection and raise nothing at all -- and then the token is
never consumed, so ShouldSuppress eats the user's next genuine
SelectionChanged instead. That is the reported symptom: exactly one
selection is swallowed after a rebuild.

Arming unconditionally breaks on the second behaviour; not arming
reopens the #495 render storm on the first. So arm, then observe:
SelectedIndex reads back its post-swap value synchronously with the
assignment (and does not drift afterwards), so an unchanged index
proves no drop occurred and the token can be handed back. A deferred
drop still shows a changed index, so its token is correctly kept until
the queued event arrives. One code path, correct under all three.

- ChangeEchoSuppressor.BeginSuppressCancelable + EchoSuppressArm, a
  retractable counter token. CancelIfUnconsumed is baseline-guarded, so
  it is a safe no-op when the echo already fired and cannot cancel a
  token belonging to an unrelated pending write.
- EchoSuppressArmTests drives Reconciler.ReactorState directly to cover
  all three platform branches. This has to be headless: the selftest
  host is WindowsAppSDKSelfContained and pinned, so a live fixture can
  only ever observe whichever branch its bundled WinUI takes.
- Issue1090SelectionStrandFixtures adds live coverage for the rebuild
  round-trip plus the reporter's end-to-end repro, and a platform probe
  that asserts only the two version-independent properties the fix
  relies on (index stable across the dispatcher drain; index movement
  and event delivery agree) while logging which branch the host took.

Audited every other BeginSuppress call site: all are drift-gated
(`if (value != current)`), so their writes reliably fire and their
promises hold. These two ItemsSource sites were the only speculative
arms.

Fixes #1090

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 32bf22fb-ba60-47d3-a0c6-8f5c0079f10e
@github-actions

github-actions Bot commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

📦 Build metrics

Artifact sizes for 6c62d08 vs the base branch (58b0561).

Packages (compressed .nupkg)

Artifact base PR Δ
Microsoft.UI.Reactor.nupkg 1.61 MB 1.61 MB +1.51 KB (+0.09%) ⚠️
Microsoft.UI.Reactor.Advanced.nupkg 487.4 KB 487.4 KB +9 B (0.00%) ≈
Microsoft.UI.Reactor.Devtools.nupkg 278.2 KB 278.2 KB +5 B (0.00%) ≈

Assemblies in Microsoft.UI.Reactor

Artifact base PR Δ
Reactor.Analyzers.dll 356.0 KB 356.0 KB +0 B (0.00%) ≈
Reactor.dll 2.39 MB 2.39 MB +1.00 KB (+0.04%) ≈
Reactor.Localization.Generator.dll 16.0 KB 16.0 KB +0 B (0.00%) ≈
Reactor.Wrappers.Abstractions.dll 10.5 KB 10.5 KB +0 B (0.00%) ≈
Reactor.Wrappers.Generator.dll 99.5 KB 99.5 KB +0 B (0.00%) ≈

Assemblies in Microsoft.UI.Reactor.Advanced

Artifact base PR Δ
Reactor.Advanced.dll 1021.5 KB 1021.5 KB +0 B (0.00%) ≈

Assemblies in Microsoft.UI.Reactor.Devtools

Artifact base PR Δ
Microsoft.UI.Reactor.Devtools.dll 777.5 KB 777.5 KB +0 B (0.00%) ≈

✅ smaller / ⚠️ larger / ≈ within noise. Sizes come from a Release dotnet pack on the CI runner: packages are the compressed .nupkg download size, assemblies the uncompressed DLL inside it.
workflow run.

@github-actions

github-actions Bot commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

🧪 Merged coverage

Coverage for 6c62d08 vs the base branch (58b0561) — unit + selftest merged.

Metric base PR Δ
Line 85.86% 85.90% +0.04 pp ≈
Branch 77.36% (902/1166) 77.44% (903/1166) +0.08 pp ≈

No coverage change beyond the noise floor. ✅

✅ higher / ⚠️ lower / ≈ within noise. Δ is in percentage points; coverage is unit + selftest merged (Debug x64) on the CI runner. Cobertura reports attached to the workflow run as artifacts.

@azchohfi Alexandre Zollinger Chohfi (azchohfi) changed the title Fix #1090: retract the ItemsSource echo-suppress token when no echo follows Harden the ItemsSource echo-suppress arm against a non-firing swap (refs #1090) Aug 13, 2026
… can't honor

Confirmed root cause, with credit to @kouhe3 who reproduced my counter-
experiments, retracted their original theory, and supplied the corrected
mechanism and a minimal repro.

Echo suppression arms one token per EXPECTED change event. The controlled
SelectedIndex write in ListViewHandler/GridViewHandler was gated only on
drift (control != requested), which is not sufficient: WinUI will not honor
a selection past the end of its ItemsSource. The property stays put, no
SelectionChanged is raised, and the armed token strands.

The common trigger is an items array that is still empty on mount while its
data loads -- idiomatic for UseState<T[]>([]) plus a fetch. Instrumented
ledger on the unfixed code, driving the reporter's repro with real clicks
against the installed runtime:

  MOUNT  write: itemsCount=0 current=-1 -> 0
  BEGIN  count=1
  MOUNT  write done: readback=-1        // clamped -- no event
  UPDATE write: itemsCount=0 current=-1 -> 0
  BEGIN  count=2
  UPDATE write done: readback=-1        // clamped -- no event
  SHOULD consumed -> count=1            // items arrive: ONE coalesced event
  ...                                   // counter never returns to 0
  SHOULD consumed -> count=0            // the user's first real click, eaten

The fix is a reachability guard: only write, and therefore only arm, when the
requested index actually exists in the current source. A write that cannot
land is skipped; the later update that brings the items in performs it
instead, where it lands and echoes normally. -1 stays always-reachable -- it
is the spec-050 force-clear sentinel and is meaningful on any source.

Deliberately keyed on reachability rather than Items.Length == 0. Empty is
just the common case; an index past the end of a short non-empty source has
the same defect, and is covered by its own fixture. Unguarded, that variant
additionally throws ArgumentException from the setter.

Fixtures (all three fail without the guard -- mutation-checked):
  Issue1090_ListView_EmptyMountThenItemsArrive_FirstRealSelectionFires
  Issue1090_GridView_EmptyMountThenItemsArrive_FirstRealSelectionFires
  Issue1090_ListView_IndexPastEndOfShortSource_FirstRealSelectionFires

Verified end to end: the reporter's repro, driven by real mouse clicks in a
framework-dependent app on the installed WindowsAppRuntime 2.3.1, now moves
state index 0 -> 1 on the first click (previously the row highlighted and the
callback never ran).

Fixes #1090

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 32bf22fb-ba60-47d3-a0c6-8f5c0079f10e
@azchohfi Alexandre Zollinger Chohfi (azchohfi) changed the title Harden the ItemsSource echo-suppress arm against a non-firing swap (refs #1090) Fix #1090: don't arm echo suppression for a SelectedIndex write WinUI can't honor Aug 14, 2026
@azchohfi
Alexandre Zollinger Chohfi (azchohfi) marked this pull request as ready for review August 14, 2026 18:45
github-code-quality flagged three static writes from an instance method in
ReproComponent (RenderCount++, StateIndex, SwitchSource).

The suggested remedies -- Interlocked counters, or a static "current instance"
tracker -- both keep the static mutable state and add machinery. They are not
needed here: the fixture constructs the component itself, so it can just hold
the reference and read plain instance fields.

That removes the shared mutable state entirely, along with the Reset()
ceremony it required, so a run cannot be contaminated by a previous one. The
Issue1090_Repro_InitialSelection check doubles as a positive control on the
identity: a stale or wrong reference leaves StateIndex at its -99 sentinel and
the assertion fails.

Scoped to the fixture this PR introduces. The older static-counter fixtures in
ListViewLoopReproFixtures.cs are untouched -- they are unrelated to #1090 and
not flagged here.

Selftests 1439/1439 green; Release build clean.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 32bf22fb-ba60-47d3-a0c6-8f5c0079f10e
@azchohfi

Copy link
Copy Markdown
Collaborator Author

Code-quality review comments addressed in 046f79c0 — all three threads replied to and resolved.

All three flagged the same thing: static fields written from an instance method in the ReproComponent test fixture. I took a different route from the suggested remedies (Interlocked counters / a static "current instance" tracker), because both keep the static mutable state and add machinery around it. The fixture constructs the component itself, so it can just hold the reference and read plain instance fields — which removes the shared state outright, along with the Reset() ceremony it needed. Details in the thread replies.


Note: Analyze (csharp) failure is a GitHub infrastructure flake, not a code problem

Please don't spend time re-investigating this one. From the job log, the analysis itself succeeded and only the results upload failed:

C# analysis with build-mode 'none' completed (1 result)
Uploading code quality results
##[warning]No server is currently available to service your request...
##[error]No server is currently available to service your request...
##[warning]An unexpected error occurred when sending a status report: No server is currently available...

That is GitHub's 503 during an incident window — I hit the identical error repeatedly from the CLI at the same time (gh api graphql -> HTTP 503: No server is currently available), including on one resolveReviewThread call that then succeeded on retry.

I could not re-trigger it: gh run rerun 32053730189 and the REST rerun-failed-jobs endpoint both return 403 This workflow run cannot be retried. It should clear on the next push to the branch, or a maintainer can re-run it.

Everything else is green — 18 successful checks, including Build solution, Unit Tests, Selftests, E2E Tests (winapp ui), Integration Tests, AOT Selftests, AOT Trim Proof, Merged coverage, and the other two CodeQL languages.

The "Analyze (csharp)" code-scanning job on 046f79c failed at the results
UPLOAD step, not during analysis:

  C# analysis with build-mode 'none' completed (1 result)
  Uploading code quality results
  ##[error]No server is currently available to service your request...

That was a GitHub incident, which also produced repeated HTTP 503s from the
CLI in the same window. Code Quality runs on other PRs have since gone green,
confirming the outage has passed.

The run is CodeQL default setup (path=dynamic/github-code-scanning/codeql,
event=dynamic), which the Actions API refuses to re-run -- both
`gh run rerun --failed` and the REST rerun-failed-jobs endpoint return
403 "This workflow run cannot be retried". Closing and reopening the PR did
not queue a fresh analysis either. A new head SHA is the only reliable
trigger, hence this empty commit.

No code change. Tree is identical to 046f79c.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 32bf22fb-ba60-47d3-a0c6-8f5c0079f10e
@azchohfi

Copy link
Copy Markdown
Collaborator Author

Update — resolved. CI is fully green.

Analyze (csharp) now reports success on 6c62d088, confirming the earlier failure was the GitHub outage and not a code problem.

Getting it re-run took some digging, recorded here in case anyone hits the same thing:

  • The run is CodeQL default setup (path=dynamic/github-code-scanning/codeql, event=dynamic) — GitHub-managed, with no workflow file in .github/workflows. Those runs cannot be re-run through the Actions API: gh run rerun --failed and the REST rerun-failed-jobs endpoint both return 403 This workflow run cannot be retried.
  • Closing and reopening the PR did not queue a fresh analysis either.
  • A new head SHA is the only reliable trigger, so 6c62d088 is an empty commit — git diff HEAD~1 HEAD is 0 lines, the tree is byte-identical to 046f79c0. It carries no code change and can be squashed away on merge.

Independent corroboration that it was an outage rather than this branch: Code Quality runs on other PRs (#1083, #1094) started passing again in the same window, and my CLI calls were returning HTTP 503 throughout it.

Final state: 19 checks passing, 0 failing, mergeStateStatus improved from UNSTABLE to CLEAN.

@azchohfi
Alexandre Zollinger Chohfi (azchohfi) merged commit 24c8414 into main Aug 17, 2026
21 checks passed
@azchohfi
Alexandre Zollinger Chohfi (azchohfi) deleted the azchohfi-fix-listview-echo-suppression-strand branch August 17, 2026 21:14
Alexandre Zollinger Chohfi (azchohfi) added a commit that referenced this pull request Aug 18, 2026
…dening (#1097)

* Complete the #1090 selection-write guard; drop the unreproducible hardening

Follow-up to #1091 (merged), addressing findings from a multi-dimensional
review of that branch. Every finding below was independently confirmed by a
second model.

1. The fix was incomplete: three more unguarded paths (HIGH)

   #1091 guarded only ListViewHandler and GridViewHandler. The same
   suppress-then-write shape exists in the templated (typed) list path, which
   #1091 never touched:

     - TemplatedListLifecycle: 6 sites (Mount/Update x ListView/GridView/FlipView)
     - TemplatedListViewDescriptor  (spec-047 Phase 3 descriptor variant)
     - TemplatedGridViewDescriptor

   The descriptor pair is worse than a swallowed event: with an unreachable
   index the WinUI setter throws ArgumentException. A new typed selftest
   crashed on it, which is how the path was found.

2. Removed the BeginSuppressCancelable / EchoSuppressArm hardening

   That primitive was written for a hypothesis that measurement disproved (an
   ItemsSource swap preserving a still-valid selection). It also carried a real
   defect: CancelIfUnconsumed is watermark-guarded, not identity-guarded, so
   with two overlapping arms on one control a delayed retraction cancels the
   wrong token -- unsuppressing a genuine engine echo. Its own XML doc claimed
   the opposite. Keeping buggy speculative code for an unobservable branch is
   not a good trade, so the arm-then-observe blocks revert to the plain
   drift-gated BeginSuppress that main used before, and the 12 headless tests
   that modelled the hypothetical branch are deleted.

3. Centralized the rule

   IsReachable was duplicated per handler. It is now
   SelectionWriteGuard.CanLand, used by all 10 write sites, so the typed and
   untyped families cannot drift.

4. Corrected an unsupported claim in shipped docs

   The threading guide asserted that ItemsSource reassignment "preserves the
   selection silently on some WinUI versions". No in-repo source establishes
   that -- the only support was this PR's own test comments, which is circular,
   and every runtime measured (WASDK 2.1 and 2.3.1) resets and fires. Replaced
   with the rule that is actually established: gate on reachability as well as
   drift, and skip the write entirely when it cannot land.

5. Closed the coverage gaps

   #1090's mutation check removed both guards at once, so it could not tell
   Mount from Update. Each guard is now pinned independently:

     ListView Mount guard removed   -> Issue1090_ListView_IndexPastEndOfShortSource
     ListView Update guard removed  -> Issue1090_ListView_ControlledIndexUnreachableAfterShrink
     GridView guards removed        -> Issue1090_GVEmptyMount + GridView_IndexPastEndOfShortSource
     Templated guards removed       -> Issue1090_TypedListView_ControlledIndexUnreachableAfterShrink

   New fixtures also cover multi-select empty mount via the OnSelectionChanged
   snapshot callback, and the GridView past-end case.

Verified: 1443 selftest fixtures pass (up from 1440); 13276 unit tests pass;
Release builds of src/Reactor and the selftest host are clean; docs recompiled
via `mur docs compile --topic threading-and-dispatch`.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 32bf22fb-ba60-47d3-a0c6-8f5c0079f10e

* Address review: single GetSelectedIndex call; correct the descriptor rationale

Review comment: `shouldWrite` called `el.GetSelectedIndex()` twice, which is
redundant and could disagree with itself if that ever normalizes. Capture it
once in a block-bodied lambda. Both descriptor sites.

Also corrects the comment on those two sites, which overstated what I had
established. TemplatedListViewDescriptor / TemplatedGridViewDescriptor are
"retained for isolated selftests" (TemplatedListHandler.cs) and are NOT
registered on the production path -- the TemplatedListHandler decorator
replaced the per-kind descriptor registrations. A probe injected into
shouldWrite confirms it is never invoked for ListView<T>.

I had claimed a new selftest crashed on this path. That was wrong: the crash
came from a stale binary left by an earlier mutation experiment that had
removed the TemplatedListLifecycle guards, and I attributed it to the
descriptor change that happened to land next. The guard stays for consistency
across the family -- the write shape is identical and would be a live defect
if those ports were ever re-registered -- but it is defensive, not a fix for
anything a fixture reaches.

The TemplatedListLifecycle finding is unaffected and remains proven: removing
just those 6 guards still reddens
Issue1090_TypedListView_ControlledIndexUnreachableAfterShrink with the
ArgumentException, re-verified after this change.

Selftests 1443/1443.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 32bf22fb-ba60-47d3-a0c6-8f5c0079f10e

---------

Co-authored-by: z <z@z.z>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 32bf22fb-ba60-47d3-a0c6-8f5c0079f10e
Alexandre Zollinger Chohfi (azchohfi) added a commit that referenced this pull request Sep 1, 2026
Audits every PR merged since v0.1.0-preview.13 (56 commits) for changelog
coverage, then cuts the release section per docs/contributing/release-runbook.md.

Only 9 of those PRs updated CHANGELOG.md. Nine user-facing changes were missing
an entry and are added here:

  Added   - declarative window icon: icon: on ReactorApp.Run plus
            Run(WindowSpec, ...) overloads (#1145, issue #1143)
  Changed - dotnet new reactorapp resolves the latest Windows App SDK (#1096)
  Fixed   - connected animations never played across a replaced subtree (#1124)
          - a controlled SelectedIndex WinUI cannot honor stranded an echo
            token and ate the next real selection (issue #1090, #1091, #1097)
          - legacy text-node TreeView rendered empty under NativeAOT (#1108)
          - devtools DP lookups found nothing, since CsWinRT projects
            DependencyProperty statics as properties (issue #1109)
          - the exe-icon fallback was dead code, and WindowIcon.FromResource
            silently applied a default icon in packaged apps (issue #1143)
          - an installed mur was frozen at first bootstrap, and mur check
            shipped without Roslyn (#1130)
          - mur loc/docs help printed the non-existent "duct" command (#1129)
          - a scaffolded project would not launch in Visual Studio 26 (#1084)

The three behaviour fixes were checked against v0.1.0-preview.13 rather than
assumed: the AOT skip for ControlUpdate_Collections, the
_pendingConnectedAnimationStarts list, and the drift-only SelectedIndex gates
all exist at the tag, so each shipped broken and none qualifies for the
introduced-and-fixed-in-window exemption.

Deliberately omitted: dependency bumps, docs-only and CI/test-infra work, and
#1099/#1102, whose product code was already correct (the defect was in a test
classifier and a text matcher respectively).

Bumps ReactorPublicVersion to 0.1.0-preview.14 and recompiles the guide, which
substitutes {{reactorVersion}} across 8 pages, satisfying the docs freshness gate.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
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.

[Bug] ListView swallows the first SelectionChanged after an ItemsSource rebuild when the selection survives the reassignment

1 participant