Skip to content

[iOS/MacCatalyst] Arm CollectionView anchor animations before reentrant UIKit callbacks - #40828

Merged
kubaflo merged 1 commit into
mainfrom
kubaflo-catalyst-scroll-anchor-late
Nov 30, 2026
Merged

kubaflo merged 1 commit into
mainfrom
kubaflo-catalyst-scroll-anchor-late

Conversation

@kubaflo

@kubaflo kubaflo commented Nov 29, 2026 •

Copy link
Copy Markdown
Contributor

Agent assessment

Self-reported assessment, not an independent review.

Assessed revision: 34743c3d66cdd5a00ce98ef5166238e6c13c5a48

Dimension Assessment Rationale
Change confidence 9/10 ↑ Both complete Catalyst fixtures passed; ten further full-family repetitions passed; PR CI Catalyst controls is green with 2190 passed and 0 failed; no public API change or new production allocation.
↓ Other platform results have not been exhaustively reviewed.
Diagnosis confidence 7/10 ↑ Real synchronous UIKit callbacks deterministically demonstrate the older Start call replacing a newer End marker; the repro fails with both pre-#40817 and merged-main product code.
↓ The exact CI Position 1090 case was not reproduced naturally locally; other family failures may have additional causes.
Evidence fit 9/10 ↑ Causal red/green/revert/restore from genuine native TRX, ten complete-family repetitions, and raw green Catalyst controls CI logs on macOS 27 for this head.
↓ The exact intermittent 1090 symptom was not naturally reproduced locally; local OS differs from CI.

Note

Are you waiting for the changes in this PR to be merged?
It would be very helpful if you could test the resulting artifacts from this PR and let us know in a comment if this change resolves your issue. Thank you!

Target Branch

This PR is for Initial base
New features, API changes, or .NET 12 work (including .NET 12 fixes) main
.NET 11 servicing fixes net11, for review
Older servicing, release integration, infrastructure, or documentation The branch designated for that work

For .NET 11 fixes, only a maintainer retargets the approved PR to the active
inflight lane and merges it after CI validates that final base. Do not merge
individual fixes directly into net11; agents must not retarget or merge.

Description of Change

Fix shared CollectionView scroll-anchor animation ownership, not individual test delays or assertion tolerances. This is a new branch from 6e6416eece627b26e7ac45a92a3c64427c3ded4b, after #40817 merged; its request-scoped completion fix is retained unchanged.

Root cause: CollectionViewScrollAnchor.ScrollToStart and ScrollToEnd assigned _edgeAnimation after calling UIKit. UIKit can synchronously raise Scrolled or an animation end before returning. If Scrolled starts a newer End request, the older Start call resumes and overwrites the newer marker with (Start, 0). Turning anchoring off then transfers the wrong completion correction. Diagnostic output on merged main showed requestedEnd=True marker=(Start, -0) offset=0, followed by failure to reach the measured end.

Fix: Arm the edge/target before calling SetContentOffset, and do not write it again afterward. A newer reentrant request—or synchronous completion clearing the marker—therefore survives. Publish the current tracker state rather than an unconditional anchored value.

Regression test: A private native test view detaches immediately before the native SetContentOffset, after the anchor has selected its animated branch. UIKit really jumps and reports callbacks synchronously; no delegate completion is fabricated. The app reattaches and requests End from Scrolled, then disables anchoring and grows the last row. The test waits for a real window and the grown native cell before checking the measured end. Both navigation variants run it. The helper exists only to make the window/callback interleaving deterministic; production code gains no test hook.

Baseline comparison

The exact reported case is:
An animated ScrollToStart or ScrollToEnd right after one to the other edge that doesn't animate wins(anchorMode: Start | End, edge: End, headerAndFooter: False).

Raw Catalyst logs show it ran without failure in both navigation variants in all five baseline builds:

Build Source Exact case Other Catalyst failure
1704369 main 9c4919b856 Passed Last item shrinks
1704308 main a16185b807 Passed None
1704250 #40806 Passed None
1704240 #40802 Passed ScrollToEnd from Scrolled
1704475 main cea39ee6e3 Passed Turning AnchorMode off timeout

Logs inspected: 835, 849, 769, 783, and 849 respectively. #40806 changes iOS simulator provisioning; #40802's change is Windows-only. Neither changes the Catalyst scroll-anchor implementation.

1704445, #40817 merge 78e680c543, is the first observed failure of this exact case in the inspected set: log 784, Position: 1090.

Attribution boundary: The exact 1090 failure did not reproduce naturally locally. Repeated full-fixture runs and width probes (320/800/1200/6650) did reproduce a related native reentrant End failure. The controlled window interleaving then proved this shared marker bug on both pre-#40817 and merged-main code. This establishes a pre-existing ownership defect, not a proven introduction of the exact CI symptom by #40817. No per-test assertion was weakened.

Causal local validation

macOS 26.7.3, Xcode 27.2, pinned SDK 12.0.100-alpha.1.26523.103 from the existing fallback SDK directory. The installed Xcode is newer than the workload's requested 27.1, so -SkipXcodeVersionCheck was used. All execution was in-process Mac Catalyst; no physical devices or host XCTest UI automation.

The following exact command was used with the fix and again with only CollectionViewScrollAnchor.cs restored to merged main:

pwsh .github/skills/run-device-tests/scripts/Run-DeviceTests.ps1 \
  -Project Controls -Platform maccatalyst \
  -DotnetPath /Users/kubaflo/Projects/copilot-worktrees/maui/kubaflo-catalyst-cascade/.dotnet/dotnet \
  -SkipXcodeVersionCheck -Rebuild \
  -IncludeClasses Microsoft.Maui.DeviceTests.CollectionViewTests,Microsoft.Maui.DeviceTests.CollectionViewNavigationHandlerTests \
  -IncludeMethods TurningAnchorModeOffAfterAReentrantAnimatedScrollToEndKeepsTheEndRequest,AnAnimatedScrollToAnEdgeRightAfterAJumpToTheOtherEdgeWins,ScrollToEndFromScrolledWhileADetachedScrollToStartFinishesReachesTheEnd \
  -OutputDirectory artifacts/scroll-anchor/prearmed-fixed -Timeout 00:15:00
pwsh .github/skills/run-device-tests/scripts/Run-DeviceTests.ps1 \
  -Project Controls -Platform maccatalyst \
  -DotnetPath /Users/kubaflo/Projects/copilot-worktrees/maui/kubaflo-catalyst-cascade/.dotnet/dotnet \
  -SkipXcodeVersionCheck -Rebuild \
  -IncludeClasses Microsoft.Maui.DeviceTests.CollectionViewTests,Microsoft.Maui.DeviceTests.CollectionViewNavigationHandlerTests \
  -OutputDirectory artifacts/scroll-anchor/prearmed-restored-full -Timeout 00:15:00

422 passed, 0 failed, 8 existing skips (430 total), verified from genuine testResults.trx.

Additional checks:

  • dotnet build Microsoft.Maui.BuildTasks.slnf --nologo -v:q: passed, 0 warnings/errors.
  • dotnet format whitespace Microsoft.Maui.sln --no-restore --exclude Templates/src --include src/Controls/src/Core/Handlers/Items2/iOS/CollectionViewScrollAnchor.cs src/Controls/tests/DeviceTests/Elements/CollectionView/CollectionViewTests.ScrollAnchor.cs: passed; workspace-loading warnings.
  • git diff --check: passed.

Ten further complete-family repetitions passed on committed revision 34743c3d66cdd5a00ce98ef5166238e6c13c5a48: 211 passed, 0 failed, 4 existing skips per run; aggregate 2110 passed, 0 failed, 40 skips. Each run includes the entire scroll-anchor family in CollectionViewNavigationHandlerTests, not just the newly added test. All ten fresh TRX files were checked.

for i in $(seq 1 10); do
  pwsh .github/skills/run-device-tests/scripts/Run-DeviceTests.ps1 \
    -Project Controls -Platform maccatalyst \
    -DotnetPath /Users/kubaflo/Projects/copilot-worktrees/maui/kubaflo-catalyst-cascade/.dotnet/dotnet \
    -SkipXcodeVersionCheck \
    -IncludeClasses Microsoft.Maui.DeviceTests.CollectionViewNavigationHandlerTests \
    -OutputDirectory artifacts/scroll-anchor/validated-family-$i -Timeout 00:15:00
done

PR CI Catalyst controls is green: build 1704506, job Catalyst controls CoreCLR macos27, completed/succeeded. Raw test-task log 778 reports 2190 passed, 0 failed, 42 skipped (2232 total). Both new regression variants appear in that log. The required real-TRX validation step also succeeded.

CI tested merge 1f4954e3e5896dfc92b2e2c3380d123ea98a4d4b, whose parents are main 3507ea53b79eee7d2452c2ba4609b05a98e6b0f4 and this PR head 34743c3d66cdd5a00ce98ef5166238e6c13c5a48. The newer main changes do not touch the scroll-anchor implementation.

Post-#40817 main comparison: 1704496 at 6e6416eece completed Catalyst tests with 2186 passed, 1 failed, 42 skipped (raw task log 813). The entire scroll-anchor family, including the exact 1090 variant, passed. Its only failure was the unrelated PageTransitions test A root replacement started from the assignment's PropertyChanging animates once its own page lands (UIKit) (“The queued replacement swapped the root without animating”). That main Catalyst job is therefore not called green; no unrelated product code was changed here.

Issues Fixed

No standalone GitHub issue was supplied. Investigates the Catalyst scroll-anchor failures linked above; fixes the reproduced pre-existing marker-ownership race. Related to #40211 and merged #40817.

Let AI finish this PR

  • Let the MAUI agent address review feedback and fix remaining issues on this PR. Maintainers still decide whether it is merged. For PRs from forks, the agent opens a follow-up PR that keeps your commits.

Arm the edge and target before UIKit can synchronously raise Scrolled or an animation end, so an older call cannot overwrite the marker of a newer request.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings November 29, 2026 21:41
@kubaflo

kubaflo commented Nov 29, 2026

Copy link
Copy Markdown
Contributor Author

@dalexsoto stamp

@kubaflo

This comment has been minimized.

@kubaflo
kubaflo temporarily deployed to copilot-pat-pool November 29, 2026 21:41 — with GitHub Actions Inactive
@github-actions

This comment has been minimized.

@azure-pipelines

This comment has been minimized.

@azure-pipelines

This comment has been minimized.

@kubaflo

This comment has been minimized.

@azure-pipelines

This comment has been minimized.

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.

🔵 Needs a closer look

The UIKit callback-ordering fix still needs native iOS and configured macOS 27 CI validation, since reported testing covers only local Catalyst.

No open issues 🎉

What changed in this PR

This PR fixes scroll-anchor animation ownership in the iOS/Mac Catalyst CollectionView handler. It complements #40817 by recording animation state before UIKit callbacks can synchronously start or complete another request.

Changes:

  • Set start/end animation markers before calling UIKit, preserving newer requests made during callbacks.
  • Publish the tracker’s current anchored state instead of an unconditional value.
  • Add a deterministic native regression test covering a reentrant End request followed by disabling anchoring and growing the last row.
File Description
src/​Controls/​tests/​DeviceTests/​Elements/​CollectionView/​CollectionViewTests.ScrollAnchor.cs Adds the regression test and private native helpers that trigger synchronous callbacks.
src/​Controls/​src/​Core/​Handlers/​Items2/​iOS/​CollectionViewScrollAnchor.cs Records animation ownership before native scrolling and publishes current anchor state.

Review effort: Balanced

@dalexsoto dalexsoto left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Stamping as requested by @kubaflo; no code review performed.

@kubaflo
kubaflo merged commit 0a98fde into main Nov 30, 2026
51 of 55 checks passed
@kubaflo
kubaflo deleted the kubaflo-catalyst-scroll-anchor-late branch November 30, 2026 11:37
kubaflo added a commit that referenced this pull request Nov 30, 2026
…nimates the view back as it lays it out (#40854)

<!-- copilot-assessment:v1 -->
### Agent assessment

Self-reported assessment, not an independent review.

Assessed revision: `06dd7c47b0c2d9b0c41cb5aafc4e57fc09571b75`

| Dimension | Assessment | Rationale |
|---|---|---|
| Change confidence | 8.5/10 | ↑ The new test fails without the fix in
every local run (Mac Catalyst 40/40, iOS 27 simulator 42/42) and passes
with it (iOS 27 42/42, Mac Catalyst 39/40; the one miss timed out in the
harness window setup before the test body ran).<br>↑ Whole
CollectionView device-test family with the fix: Mac Catalyst 422 passed,
0 failed, 8 skipped in two runs; iOS 27 418 passed, 0 failed, 8
skipped.<br>↑ Acts only on a scroll animation UIKit starts inside a
layout pass while the view follows an edge; animations the app or the
anchor started, drags and decelerations are excluded. No public API
change. Merges cleanly with #40828.<br>↓ No PR CI: the device-test
pipelines are disabled. The local host runs macOS 26.7.3; CI runs macOS
27.2. |
| Diagnosis confidence | 8.5/10 | ↑ Native stack of the animation start:
-[UICollectionView layoutSubviews] →
_setContentSize:skipContentOffsetAdjustment: →
performWhileAnimatingAutomaticContentOffsetAdjustments: →
_adjustContentOffsetIfNecessary → setContentOffset:animated:YES (850 →
760).<br>↑ Anchor trace: ScrollAnimating turns true in that layout pass,
the anchor counts it as user scrolling, and it switches from End to None
once the re-targeted animation is 10 points above the end.<br>↓ When
UIKit animates this adjustment rather than applying it at once is
inferred from private method names. |
| Evidence fit | 4/10 | ↑ Same signature as the Mac Catalyst CI failures
in builds 1704369 and 1704494: the list stops following its end and
stays a fixed distance above it (370 in both).<br>↓ The flaky test's own
shrink step doesn't start this animation on macOS 26.7.3 or the iOS 27
simulator (100+ local runs pass before and after the fix), so it isn't
confirmed that macOS 27 takes this path; CI is disabled. |
<!-- /copilot-assessment -->

<!-- Please let the below note in for people that find this PR -->
> [!NOTE]
> Are you waiting for the changes in this PR to be merged?
> It would be very helpful if you could [test the resulting
artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!

<!--
Open .NET 11 fix PRs against net11 for review; target main for
next-major features.
After approval, a maintainer manually retargets the fix PR to the active
inflight
branch and merges it directly there. Do not merge individual fixes into
net11.
Bots must not retarget or merge. Candidate integration into net11 and
release/*
changes are separate, explicitly coordinated release work.
-->

### Target Branch

| This PR is for | Initial base |
| --- | --- |
| New features, API changes, or .NET 12 work (including .NET 12 fixes) |
`main` |
| .NET 11 servicing fixes | `net11`, for review |
| Older servicing, release integration, infrastructure, or documentation
| The branch designated for that work |

- [x] I selected the applicable base branch using the [contribution
guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting).

For .NET 11 fixes, only a maintainer retargets the approved PR to the
active
inflight lane and merges it after CI validates that final base. Do not
merge
individual fixes directly into `net11`; agents must not retarget or
merge.

### Description of Change

<!-- Enter description of the fix in this section -->

This investigates the intermittent Mac Catalyst device-test failure
`[CollectionView] Back at the end after a ScrollTo away, the list keeps
the end in view as the last item shrinks` on `main` ("Following the end,
the list should keep the end in view as the last item shrinks. Distance
to the end: 370."). It fixes a deterministic `ScrollAnchorMode` (#40211)
defect on iOS and Mac Catalyst that leaves the list in the same failed
state.

**Root cause.** When the content of a `UICollectionView` shrinks under
its content offset during a layout pass, UIKit animates the view back
within the content. Native stack captured locally on Mac Catalyst:

```
-[UICollectionView setContentOffset:animated:]       animated: YES, 850 → 760
-[UICollectionView _applyAutomaticAdjustedContentOffset:]
-[UIScrollView _adjustContentOffsetIfNecessary]
-[UIScrollView setContentSize:]
-[UICollectionView setContentSize:]
-[UIScrollView performWhileAnimatingAutomaticContentOffsetAdjustments:]
-[UICollectionView _setContentSize:skipContentOffsetAdjustment:]
-[UICollectionView _updateVisibleCellsNow:]
-[UICollectionView layoutSubviews]
```

`CollectionViewScrollAnchor` treats every scroll animation it didn't
start as a fling (`ScrollAnimating`), and stops correcting until it
ends. On its way, UIKit measures the rows the animation brings into view
and re-targets it, so the view ends up above where the end settles. The
anchor sees the view move more than its threshold away from the end and
stops following it (`End → None`), and the view stays there.

This happens whenever rows are shorter than UIKit's 30-point estimate
(`LayoutFactory2` uses
`NSCollectionLayoutDimension.CreateEstimated(30)`). The anchor goes to
the end as estimated, UIKit measures the rows there shorter, the content
shrinks under the view, and UIKit animates back.

**Fix.** `CollectionViewScrollAnchor.LayoutStarting` now notes whether a
scroll animation is running when an outermost layout pass starts. In
`LayoutFinished`, if one is running that wasn't before, and neither the
anchor nor the app started one (no edge animation, no animated request,
no drag or deceleration), UIKit started it while laying the view out. A
view that follows an edge stops it where it starts with
`SetContentOffset(ContentOffset, false)`, the idiom the controller
already uses to stop animations. The usual post-layout look then scrolls
to the edge. Views that don't follow an edge keep UIKit's animation. The
three `LayoutStarting` call sites in `ItemsViewController2` now pass the
collection view.

**Regression test.** `AnchorMode End shows and follows the end of rows
shorter than UIKit estimates them` (iOS and Mac Catalyst): 40 rows of 20
points must open at their end, and the list must keep following its end
when 20 more arrive.

| Local run | Without the fix | With the fix |
|---|---|---|
| Mac Catalyst (macOS 26.7.3), new test ×20 per navigation variant |
40/40 failed: 32 didn't open at the end (45 to 89.5 above it), 8 lost it
after the batch (up to 486 above) | 39/40 passed; the other timed out in
the harness window setup (`OnLoadedAsync`) before the test body ran |
| iOS 27.0 simulator, new test ×21 per navigation variant | 42/42
failed: 40 didn't open at the end (40 above it), 2 lost it after the
batch | 42/42 passed |
| Mac Catalyst, whole CollectionView family (both variants) | — | 422
passed, 0 failed, 8 skipped (two runs) |
| iOS 27.0 simulator, whole CollectionView family | — | 418 passed, 0
failed, 8 skipped |

The repeated runs used a temporary local theory that called the new
test; it isn't part of this PR. The flaky test also passed 40/40 locally
with the fix, and its assertions are unchanged.

**Relationship to the Mac Catalyst CI failure.** Both observed failures
end with the list no longer following its end and a stable 370 points
above it: build 1704369 on main `9c4919b856` (`[NavigationViewHandler]`)
and build 1704494 (`[NavigationRenderer]`). That's the state this defect
leaves the view in. Locally, though, the flaky test's shrink step
doesn't take this path. On macOS 26.7.3 and on the iOS 27 simulator,
UIKit re-estimates the rows above and moves the offset in that layout
pass before it shrinks the content, so it never animates. More than 100
local runs of that test passed, with and without this change, including
in the full family. CI runs macOS 27.2, which I couldn't run locally. So
this PR fixes a real, deterministic anchor defect with the same failure
signature, and it's the most likely explanation I found, but it doesn't
prove that the macOS 27 run took this path.

Other findings, not changed here:
- With macOS keyboard navigation enabled, the focus engine asks the
collection view for `preferredFocusedView`. UIKit then sizes that cell
outside a layout pass
(`_endReusableViewCreationAndSelfSizingOutsideVisibleCellsUpdate`), and
applies the compositional layout's content-offset adjustment at once. It
reports the move to `scrollViewDidScroll` before it updates the content
size, and the anchor judges it as a scroll. With rows taller than the
estimate, as in the flaky test, the move is toward the end and harmless.
With shorter rows it briefly un-anchors the list. A possible follow-up
is to treat offset changes made inside
`CustomUICollectionViewCompositionalLayout.InvalidateLayout(context)` as
layout.
- #40828 changes the animated `ScrollToStart`/`ScrollToEnd` branches;
this PR changes `LayoutStarting`/`LayoutFinished`. Their hunks don't
overlap, and a trial merge is clean. #40817 is unaffected.

**CI.** `maui-pr`, `maui-pr-uitests` and `maui-pr-devicetests` have been
disabled since 2026-11-29 23:22 UTC, so CI hasn't run on this PR. It's
pending until the pipelines are re-enabled; the validation above is
local.

Validation, with the pinned SDK `12.0.100-alpha.1.26523.103` and Xcode
27.2 (hence `-SkipXcodeVersionCheck`):

```bash
pwsh .github/skills/run-device-tests/scripts/Run-DeviceTests.ps1 -Project Controls -Platform maccatalyst \
  -DotnetPath "$PWD/.dotnet/dotnet" -SkipXcodeVersionCheck \
  -IncludeClasses Microsoft.Maui.DeviceTests.CollectionViewTests,Microsoft.Maui.DeviceTests.CollectionViewNavigationHandlerTests
# passed: 422 passed, 0 failed, 8 skipped (430 total), in two runs

pwsh .github/skills/run-device-tests/scripts/Run-DeviceTests.ps1 -Project Controls -Platform ios -iOSVersion 27 \
  -DotnetPath "$PWD/.dotnet/dotnet" -SkipXcodeVersionCheck \
  -IncludeClasses Microsoft.Maui.DeviceTests.CollectionViewTests,Microsoft.Maui.DeviceTests.CollectionViewNavigationHandlerTests
# passed: 418 passed, 0 failed, 8 skipped (426 total)

pwsh .github/skills/run-device-tests/scripts/Run-DeviceTests.ps1 -Project Controls -Platform maccatalyst \
  -DotnetPath "$PWD/.dotnet/dotnet" -SkipXcodeVersionCheck \
  -IncludeClasses Microsoft.Maui.DeviceTests.CollectionViewTests,Microsoft.Maui.DeviceTests.CollectionViewNavigationHandlerTests \
  -IncludeMethods AnchorModeEndShowsAndFollowsTheEndOfRowsShorterThanEstimated
# without the product change: 0 passed, 2 failed (distances 67.5 and 490); with it: 2 passed

dotnet format whitespace Microsoft.Maui.sln --no-restore --exclude Templates/src --include <the three changed files>
# passed, no changes
```

### Issues Fixed

<!-- Please make sure that there is a bug logged for the issue being
fixed. The bug should describe the problem and how to reproduce it. -->

No standalone issue. Related to #40211 (ScrollAnchorMode), the
intermittent Mac Catalyst failure above, #40828 and #40817.

### Let AI finish this PR

- [ ] **Let the MAUI agent address review feedback and fix remaining
issues on this PR.** Maintainers still decide whether it is merged. For
PRs from forks, keep "Allow edits by maintainers" on so the agent can
push to your branch; otherwise it opens a follow-up PR that keeps your
commits.

<!--
Verify the target branch follows the release workflow in
docs/ReleaseBranchWorkflow.md.
Infrastructure and documentation changes should target the branch where
they apply.
-->

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>

This branch was previously deployed

1 inactive deployment
copilot-pat-pool — 34743c3d Deployed Nov 29, 2026 by kubaflo via conclusion #3484
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.

3 participants