Skip to content

fix(LayoutAnimations): deadlock in ReanimatedCommitHook surface initialization - #9903

Merged
bartlomiejbloniarz merged 4 commits into
mainfrom
fix-shadow-tree-registry-deadlock
Aug 13, 2026
Merged

bartlomiejbloniarz merged 4 commits into
mainfrom
fix-shadow-tree-registry-deadlock

Conversation

@bartlomiejbloniarz

Copy link
Copy Markdown
Member

Summary

Fixes #8579.

maybeInitializeLayoutAnimations enumerated the ShadowTreeRegistry from inside a commit hook. Commits usually execute inside ShadowTreeRegistry::visit, which already holds the registry's shared_mutex in shared mode, so the enumerate was a recursive shared acquisition. libc++ writers block new readers while draining existing ones, so a concurrent startSurface/stopSurface (a registry writer) on another thread turns that recursion into a permanent deadlock — the three-thread ANR in the issue (JS in enumerate, pool thread in startSurface, main in constraintLayout).

The registry is now read exactly once, at hook construction (module init — never a commit stack), to pick up surfaces that existed before Reanimated loaded (lazy init, brownfield). After that, the first commit of each new surface registers the mounting override delegate directly through the committing ShadowTree — no registry access on commit stacks at all. currentMaxSurfaceId_ becomes a seenSurfaces_ set, and a mount hook erases stopped surfaces from it. That last part is not hypothetical: a JS reload reuses the same surface id, so without the erase the recreated surface would never get the override delegate.

Test plan

fabric-example, iOS sim + Android emulator:

  • Layout animations run on the main surface (delegate registered via the commit-hook path) and on a LogBox surface created after init (the case a registry-free fix has to cover)
  • 5×/10× reload churn (surface stop + start + first commits racing) with layout animations between reloads: responsive throughout, zero ANRs, stable pid
  • Back-button surface stop + relaunch on Android, empty-root commits (render-null) — all clean
  • The emulator still had ANR traces from the unfixed binary with the 【Android ANR】RN 0.81.5 RCT_NEW_ARCH_ENABLED = true ReanimatedCommitHook::maybeInitializeLayoutAnimations #8579 signature; the fixed binary produced none under the same and heavier churn

@bartlomiejbloniarz
bartlomiejbloniarz force-pushed the fix-shadow-tree-registry-deadlock branch from c7685da to 5d9d63f Compare July 8, 2026 12:27
@donatoaguirre24

Copy link
Copy Markdown

It's worth noting that this PR also fixes #8344, for a reason unrelated to the ANR it's intended to address, so it would be great to merge it.

I discovered this because I was using Cursor's Debug mode with Opus 5 to debug an iOS crash, and it applied these changes as a patch over 4.3.3 to fix it.

In my case, the crash happened when using an entering animation inside a screen that also uses a custom component as top‑bar title. We use react‑native‑navigation and apparently a custom top-bar creates a new Fabric surface.

Here (collapsed to avoid a wall of text) are our findings, details about our environment, and repro details

The second bug in currentMaxSurfaceId_

maybeInitializeLayoutAnimations guards registration with a single high-water mark. It enumerates the registry and registers every surface above the mark, then sets the mark to the id of the committing surface, which can be lower than the highest id it just registered. Whenever two surfaces exist before either has committed, the higher-id surface gets registered twice. Captured on 4.3.3 (timestamp prefixes elided):

t=...187096 surface 101 commits, currentMaxSurfaceId_ = 91 -> enumeration registers surface 111, then surface 101 -> mark set to 101 t=...187098 surface 111 commits, 111 > 101 -> surface 111 registered a SECOND time

Since setMountingOverrideDelegate appends rather than replaces, LayoutAnimationsProxy_Legacy::pullTransaction then ran twice for every transaction on that surface — 84 occurrences in one session, only on the double-registered surface, with the second invocation receiving the first's output as its input.

This is the case #6841 was meant to prevent ("this would lead to us processing the same transaction multiple times"); the high-water mark just doesn't cover the ordering where enumeration outruns the mark.

Why the double pass is fatal rather than merely wasteful

Inside pullTransaction, addOngoingAnimations runs before handleRemovals, so a single pass emits Update then Delete, which is correct.

On the second pass the incoming Remove/Delete are consumed by parseRemoveMutations and re-emitted by handleRemovals, while the incoming Update is passed straight through by handleUpdatesAndEnterings — which runs after handleRemovals. So the second pass emits Delete(tag) followed by Update(tag). The mount layer recycles the view on the Delete, and the stale Update then queries it:

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'RCTComponentViewRegistry: Attempt to query unregistered component.'

RCTComponentViewRegistry.mm:76, reached from the Update branch of RCTPerformMountInstructions. Traced end to end for tag 3790 in transaction 34: endLayoutAnimation(3790, shouldRemove=true), pass 1 emits the final Update(3790), pass 2 emits no update of its own (proving its Update is a pass-through duplicate), and the mount layer logs the Delete of 3790 immediately followed by the failing Update.

This contradicts the current theory on #8344

#8344 currently reads as cross-surface deadNodes leakage. Our evidence points elsewhere:

  • A probe flagging any emitted mutation whose view belonged to a surface other than the transaction's never fired, and the failing mutation had surfaceMismatch: false. The view belonged to the same surface as the transaction.
  • entering alone reproduces it. No exiting animation, no modal, no screen pop, so no surface teardown is involved.
  • The per-surface work already in 4.3.3 (per-surface deadNodes via surfaceContext_, stopSurface/surfacesToRemove_, reconcileContradictedRemovals) does not help, because the duplicate registration happens upstream of all of it in the commit hook.

That may also account for the reports on #8344 where the crash appears with an entering animation and no modal dismissal, which the teardown-based theory doesn't obviously predict.

The second surface is incidental to the repro rather than causal: ours comes from react-native-navigation giving each custom topBar.title.component its own RCTFabricSurface. A plain text nav title doesn't reproduce it, because then there is only one surface.

Verification of this PR's change

We backported 5d9d63fe1098fd69ff8df4293caa6083b4624165 onto 4.3.3 and re-ran the identical probes. Replacing the high-water mark with seenSurfaces_ and registering only the committing surface makes registration idempotent, and the crash goes with it.

Before: 84 duplicated pullTransaction passes, and the crash.
After, across four launches: 0 duplicated passes, 0 duplicate registrations, 0 mount-registry misses, 12 correct shadowTreeDidUnmount cleanups — and 1109 layout-animation update mutations still flowing, so animations still work rather than merely having stopped crashing.

The ordering race itself still happens after the fix (in later launches surface 111 registered before 101). It is just harmless now.

Environment and caveats

reanimated 4.3.3, react-native 0.81.6, react-native-navigation 8.8.10, new architecture / Fabric, Hermes, iOS simulator. Legacy proxy active (LayoutAnimationsProxy_Legacy, ENABLE_SHARED_ELEMENT_TRANSITIONS false).

We verified on iOS only. The duplicate registration is platform-independent, so we'd expect the same double pass on Android, where the symptom would surface differently in the mount layer — plausibly the RetryableMountingLayerException: Unable to find viewState for tag reported on #8344. We have not confirmed that, so please treat it as a hypothesis.

currentMaxSurfaceId_ is still present on main, 4.5.3 and 4.3.3, so this affects current releases.

cc @bartlomiejbloniarz @gosha212

@coderabbitai

coderabbitai Bot commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 2d02e44a-afb2-4816-8345-5f07a7f34fc2

📥 Commits

Reviewing files that changed from the base of the PR and between 976be30 and d80ee22.

📒 Files selected for processing (2)
  • packages/react-native-reanimated/Common/cpp/reanimated/Fabric/ReanimatedCommitHook.cpp
  • packages/react-native-reanimated/Common/cpp/reanimated/NativeModules/ReanimatedModuleProxy.cpp

📝 Walkthrough

Summary by CodeRabbit

  • Bug Fixes
    • Improved layout animation setup for surfaces that already exist when the feature is enabled.
    • Ensured layout animations initialize only once for each active surface.
    • Improved animation consistency while mounting and committing updates.
    • Correctly cleans up unmounted surfaces, allowing surface identifiers to be reused safely.
    • Improved behavior across supported rendering configurations.
    • Reduced the risk of missed or duplicate animation initialization during surface lifecycle changes.

Walkthrough

initializeFabric now shares one thread-safe ReanimatedSurfaceTracker with both Fabric hooks. ReanimatedCommitHook initializes layout animations from ShadowTree instances without nested registry access. ReanimatedMountHook removes surfaces during unmount.

Changes

Fabric surface lifecycle

Layer / File(s) Summary
Surface tracking contract
packages/react-native-reanimated/Common/cpp/reanimated/Fabric/ReanimatedSurfaceTracker.h
Adds mutex-protected, idempotent surface insertion and removal.
Mount hook lifecycle integration
packages/react-native-reanimated/Common/cpp/reanimated/Fabric/ReanimatedMountHook.h, packages/react-native-reanimated/Common/cpp/reanimated/Fabric/ReanimatedMountHook.cpp
Passes the shared tracker to ReanimatedMountHook, skips mount processing when USE_ANIMATION_BACKEND is enabled, and removes surfaces during unmount.
ShadowTree commit initialization
packages/react-native-reanimated/Common/cpp/reanimated/Fabric/ReanimatedCommitHook.h, packages/react-native-reanimated/Common/cpp/reanimated/Fabric/ReanimatedCommitHook.cpp
Initializes layout animations once per surface from existing and committed ShadowTree instances. Removes the previous surface-ID threshold, mutex, and registry-wide initialization logic.
Fabric hook wiring and proxy setup
packages/react-native-reanimated/Common/cpp/reanimated/NativeModules/ReanimatedModuleProxy.cpp
Creates one tracker for initializeFabric, passes it to both hooks, always installs ReanimatedMountHook, and requires the component descriptor registry for layout-animation proxy creation.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Mergeability Score: 🔵 Low · up to d80ee

The change reroutes layout-animation delegate initialization for newly created surfaces; if reused surface IDs are not serialized through registration, reload churn could skip or misapply layout animations. The PR is mergeable with explicit owner awareness to verify that the tracker keeps initialization protected until registration completes.

Sequence Diagram(s)

sequenceDiagram
  participant ReanimatedModuleProxy
  participant ReanimatedCommitHook
  participant ReanimatedSurfaceTracker
  participant ShadowTree
  participant ReanimatedMountHook
  ReanimatedModuleProxy->>ReanimatedCommitHook: initializeFabric with ShadowTree
  ReanimatedCommitHook->>ReanimatedSurfaceTracker: add(surfaceId)
  ReanimatedCommitHook->>ShadowTree: start and configure layout animations
  ReanimatedCommitHook->>ReanimatedCommitHook: handle committed ShadowTree
  ReanimatedCommitHook->>ReanimatedSurfaceTracker: skip tracked surface
  ReanimatedMountHook->>ReanimatedSurfaceTracker: remove(unmounted surfaceId)
Loading

Possibly related issues

  • #8579: Replaces mutex- and registry-based initialization in ReanimatedCommitHook, matching the reported commit-time blocking path.
  • #9907: Updates surface initialization and mount lifecycle handling for layout-animation surfaces.

Possibly related PRs

Suggested reviewers: matipl01, tomekzaw, tjzel

🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the main change: fixing the surface-initialization deadlock in ReanimatedCommitHook.
Description check ✅ Passed The description explains the deadlock cause, implementation changes, and validation performed for the related surface scenarios.
Linked Issues check ✅ Passed The changes address #8579 by removing registry access from commit stacks while supporting existing, new, stopped, and reused Fabric surfaces.
Out of Scope Changes check ✅ Passed The changes remain focused on surface tracking, delegate registration, and deadlock prevention required by the linked issue.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix-shadow-tree-registry-deadlock

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In
`@packages/react-native-reanimated/Common/cpp/reanimated/Fabric/ReanimatedCommitHook.cpp`:
- Around line 35-48: Serialize the entire initialization sequence in
ReanimatedCommitHook::maybeInitializeLayoutAnimations with surface unmount
handling, keeping mutex_ held from recording the SurfaceId through startSurface
and setMountingOverrideDelegate. Update the corresponding shadowTreeDidUnmount
path to use the same synchronization so a reused SurfaceId cannot begin
initialization until the prior call completes.
- Around line 23-27: Reorder hook registration in the Reanimated initialization
flow so the mount hook is registered before the commit hook, ensuring
commit-created surface IDs can always be removed by unmount handling. Update the
relevant UIManager registration calls in the surrounding constructor or
initialization method, while preserving the existing shadow-tree enumeration and
maybeInitializeLayoutAnimations behavior.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 3c9ac5fd-c395-43a4-836f-6beebc73564b

📥 Commits

Reviewing files that changed from the base of the PR and between fb9cb55 and d175703.

📒 Files selected for processing (2)
  • packages/react-native-reanimated/Common/cpp/reanimated/Fabric/ReanimatedCommitHook.cpp
  • packages/react-native-reanimated/Common/cpp/reanimated/Fabric/ReanimatedCommitHook.h

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In
`@packages/react-native-reanimated/Common/cpp/reanimated/Fabric/ReanimatedMountHook.cpp`:
- Around line 33-36: Update the USE_ANIMATION_BACKEND branch in the Reanimated
mount hook so it does not bypass handleNodeRemovals without addressing retained
removed nodes. Implement the required cleanup before returning, or explicitly
gate this path behind a tracked issue until cleanup is available.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 518e3d7f-db2f-4d40-ac61-0d4e2bf4c044

📥 Commits

Reviewing files that changed from the base of the PR and between d175703 and 3144d22.

📒 Files selected for processing (6)
  • packages/react-native-reanimated/Common/cpp/reanimated/Fabric/ReanimatedCommitHook.cpp
  • packages/react-native-reanimated/Common/cpp/reanimated/Fabric/ReanimatedCommitHook.h
  • packages/react-native-reanimated/Common/cpp/reanimated/Fabric/ReanimatedMountHook.cpp
  • packages/react-native-reanimated/Common/cpp/reanimated/Fabric/ReanimatedMountHook.h
  • packages/react-native-reanimated/Common/cpp/reanimated/Fabric/ReanimatedSurfaceTracker.h
  • packages/react-native-reanimated/Common/cpp/reanimated/NativeModules/ReanimatedModuleProxy.cpp

@bartlomiejbloniarz
bartlomiejbloniarz force-pushed the fix-shadow-tree-registry-deadlock branch 2 times, most recently from 3c81105 to 976be30 Compare August 11, 2026 10:34
@bartlomiejbloniarz
bartlomiejbloniarz marked this pull request as ready for review August 11, 2026 10:39
…alization

maybeInitializeLayoutAnimations enumerated the ShadowTreeRegistry from
inside a commit hook. Commits usually execute inside
ShadowTreeRegistry::visit, which already holds the registry's
shared_mutex in shared mode, so the enumerate was a recursive shared
acquisition. libc++ writers block new readers while draining existing
ones, so a concurrent startSurface/stopSurface (a registry writer) on
another thread turns that recursion into a permanent deadlock - reported
as production ANRs in #8579.

The registry is now read exactly once, at hook construction (module
init, never a commit stack), to pick up surfaces that existed before
Reanimated loaded. After that, the first commit of each new surface
registers the mounting override delegate directly through the committing
ShadowTree - no registry access on commit stacks at all.
currentMaxSurfaceId_ becomes a seenSurfaces_ set, and a mount hook
erases stopped surfaces from it so surface id reuse cannot leave a new
surface unregistered.

Fixes #8579
Move the seen-surfaces bookkeeping out of ReanimatedCommitHook into a small
shared ReanimatedSurfaceTracker. The commit hook adds surfaces (registering
the LA mounting override delegate on a surface's first commit) and
ReanimatedMountHook removes them in shadowTreeDidUnmount, so a reused
surface id registers again. This keeps the existing commit-hook/mount-hook
separation instead of making the commit hook implement both interfaces.

The mount hook is now also registered with USE_ANIMATION_BACKEND enabled,
with its shadowTreeDidMount work compiled out - it only tracks surface
unmounts there.
- register the mount hook before the commit hook, so a commit-tracked
  surface can always be forgotten on unmount
- guard against a null layoutAnimationsProxy_ (the ComponentDescriptorRegistry
  lookup can fail, leaving the proxy unset)
@bartlomiejbloniarz
bartlomiejbloniarz merged commit e2b9310 into main Aug 13, 2026
13 checks passed
@bartlomiejbloniarz
bartlomiejbloniarz deleted the fix-shadow-tree-registry-deadlock branch August 13, 2026 15:37
bartlomiejbloniarz added a commit that referenced this pull request Aug 18, 2026
…hread (#10265)

## Summary

Extracted from #9901 per review feedback: the legacy layout-animations
proxy checked `std::this_thread::get_id() != uiThreadId_` with a lazily
captured thread id, and `AndroidUIScheduler` kept its own private
`thread_local` flag for the same purpose.

This promotes the existing tls mechanism into a shared helper:
`UIScheduler::isOnUIThread()`, with the flag set in the base
`UIScheduler::triggerUI()` (the single funnel all platforms' UI jobs run
through). The Android wrapper drops its private flag and its
now-redundant `triggerUI` override; the legacy proxy drops `uiThreadId_`
and its three lazy assignments.

Being a static on `UIScheduler` in worklets, the helper is available
globally (e.g. for the CDP profiler).

Semantics are preserved: the tls is marked at least as early as
`uiThreadId_` was ever assigned, a thread-local read needs no locking,
and an unmarked thread still means "not the UI thread".

## Test plan

Covered by the existing layout-animation flows exercised in #9901/#9903
test plans; the check sites are unchanged apart from the helper call.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

【Android ANR】RN 0.81.5 RCT_NEW_ARCH_ENABLED = true ReanimatedCommitHook::maybeInitializeLayoutAnimations

4 participants