Skip to content

Batch setNativeProps commits within a task - #60355

Open
robhogan wants to merge 8 commits into
mainfrom
robhogan/batch-set-native-props
Open

robhogan wants to merge 8 commits into
mainfrom
robhogan/batch-set-native-props

Conversation

@robhogan

@robhogan robhogan commented Nov 27, 2026 •

Copy link
Copy Markdown
Collaborator

Summary:

Currently, every setNativeProps call commits the shadow tree:

shadowTreeRegistry_.visit(
family.getSurfaceId(), [&](const ShadowTree& shadowTree) {
// The lambda passed to `commit` may be executed multiple times.
// We need to create fresh copy of the `RawProps` object each time.
auto ancestorShadowNode =
shadowTree.getCurrentRevision().rootShadowNode;
shadowTree.commit(
[&](const RootShadowNode& oldRootShadowNode) {
auto rootNode = oldRootShadowNode.cloneTree(
family, [&](const ShadowNode& oldShadowNode) {
auto& componentDescriptor =
componentDescriptorRegistry_->at(
shadowNode->getComponentHandle());
PropsParserContext propsParserContext{
family.getSurfaceId(), *contextContainer_};
auto props = componentDescriptor.cloneProps(
propsParserContext,
getShadowNodeInSubtree(*shadowNode, ancestorShadowNode)
->getProps(),
RawProps(rawProps));
return oldShadowNode.clone({.props = props});
});
return std::static_pointer_cast<RootShadowNode>(rootNode);
},
{/* default commit options */});
});

That commit clones the node's ancestors, and cloning a parent with a new child list also clones each of its other children (YogaLayoutableShadowNode::adoptYogaChild). While enableAccumulatedUpdatesInRawPropsAndroid is off, Android also diffs each commit on the JS thread. So moving N sibling views with one call each per frame, as JS-driven animations do, is O(N²) per frame.

This adds enableSetNativePropsBatching. With it on, setNativeProps still records its props in nativeProps_DEPRECATED straight away, but queues the node, and the first call in a task queues a microtask that commits every queued node in one cloneMultiple commit per surface, applying the props the batch set on it. Committing in a microtask keeps these commits ahead of observers and the mount later in the task, as they are today. With enableFabricCommitBranching, a React commit earlier in the task replaces the main branch when it's merged, so then the batch goes on top of React's revision instead. It's bridgeless only, because bridge mode doesn't drain microtasks.

JS reads of the shadow tree (NativeDOM, the measure methods, findNodeAtPoint, getRelativeLayoutMetrics) commit the queue first, and so do accessibility events and LayoutAnimation.configureNext, which would otherwise reach the platform ahead of the props. Calls made in ResizeObserver callbacks, which run after the task's microtasks, are committed as each round of callbacks returns. Each batch also refreshes the tree that JS reads see for the rest of the task, as a React commit does, so a read sees the props even after an earlier read in the same task.

A few things change with the flag on:

  • Native code that reads the tree directly, rather than through JS, sees the new props once the batch commits rather than after each call. With commit branching and a React revision pending, the batch mounts at the merge, so an accessibility event or LayoutAnimation.configureNext in that window still reaches the platform first, as it does for React's own changes.
  • With commit branching, findNodeAtPoint and getRelativeLayoutMetrics read the main branch, so they don't see a batch on React's revision until the merge, as with React's own changes.
  • A prop that fails to convert throws from whatever commits the batch first rather than from the call, and the rest of that batch is lost. From a ResizeObserver callback, that error is reported as fatal rather than logged. With the flag off the bad value stays in nativeProps_DEPRECATED too, so later commits that clone the node or its siblings throw either way.
  • A ResizeObserver callback that resizes a target at its own depth or shallower gets the spec's loop error, and that target isn't notified again until the surface next commits. With the flag off it isn't notified at all.

A bouncing-ball stress test in RNTester's Playground (N sibling views, each moved with setNativeProps every frame), release builds of main and this PR side by side:

android-main-vs-pr-public.mp4
ios-main-vs-pr-public.mp4
Device Views main This PR
Galaxy A16 200 5.0 fps 49.5 fps (~10x)
iPhone 12 mini 200 28.5 fps 60 fps (display cap)
iPhone 12 mini 400 8 fps 60 fps (display cap)

Changelog:

[Internal]

Test Plan:

New Fantom test, run with the flag and enableFabricCommitBranching each on and off:

yarn fantom packages/react-native/src/private/renderer/mounting/__tests__/SetNativeProps-itest.js

68 tests pass. Its ResizeObserver and throwing-task tests fail against a version that commits in the rendering update instead of a microtask. With commit branching on, its test for a React update before the call fails without the commit on top of React's revision. Its test with a native-driven animation fails against a version that reapplies every prop ever set through setNativeProps, which reverts the animated value. Its tests for reads after an earlier read and in a layout effect, calls from ResizeObserver callbacks (including one that disconnects), accessibility events and LayoutAnimation, the root node, and React overriding the props with its update first each fail without the change they cover.

The existing Mounting, ReactNativeElement, Animated, ResizeObserver and IntersectionObserver suites pass (945 tests).

Benchmark (AI-driven): RNTester release builds at main (3b49389) and this branch with the flag defaulted on, installed side by side, Playground running N absolutely positioned sibling views and one setNativeProps per view per frame from requestAnimationFrame. 200-view figures are medians of 6 interleaved cold launches each, from the app's own 500 ms frame counter after a 6 s warm-up. The iPhone 400-view figures are read from the app's on-screen frame counter in a screen recording (WebDriverAgent, about 18 fps), with capture running. The builds are from an earlier revision of this branch, which applied all of a view's stored native props in each batch rather than only the ones the batch set. Here every call sets all of them, so the work is the same. The changes since add one revision refresh per surface per batch.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. label Nov 27, 2026
@github-actions github-actions Bot added the Meta Review Required This PR is considered risky and requires Meta to import it to do more testing before merging. label Nov 27, 2026
@facebook-github-tools facebook-github-tools Bot added the Shared with Meta Applied via automation to indicate that an Issue or Pull Request has been shared with the team. label Nov 28, 2026
@robhogan
robhogan force-pushed the robhogan/batch-set-native-props branch 4 times, most recently from 7156d8f to 5a7beb5 Compare November 28, 2026 02:03
Every `setNativeProps` call commits the shadow tree. The commit clones the node's ancestors, and cloning a parent with a new child list also clones each of its other children (`YogaLayoutableShadowNode::adoptYogaChild`). While `enableAccumulatedUpdatesInRawPropsAndroid` is off, the default, Android also diffs each commit on the JS thread. So updating N siblings with one call each, as JS-driven animations do every frame, costs O(N²) per frame.

With `enableSetNativePropsBatching`, `setNativeProps` from JS still records its props in `nativeProps_DEPRECATED` straight away, but queues the node instead of committing it. The first call in a task queues a microtask that commits every queued node in one `cloneMultiple` commit per surface, applying the props the batch set on it at their current values. Committing in a microtask keeps these commits ahead of the observers and mount that follow in the task, as they are when each call commits, and the microtask still runs when the task throws. With `enableFabricCommitBranching`, a React commit earlier in the task replaces the main branch when it's merged, so then the batch is committed on top of React's revision instead.

JS reads of the shadow tree commit the queue first. `getShadowTreeRevisionProvider()` returns a provider that does this, which covers `NativeDOM`, the measure methods, `ResizeObserver` and view transitions, and `findNodeAtPoint` and `getRelativeLayoutMetrics` in `UIManagerBinding` do the same.

Queueing a microtask needs the `jsi::Runtime`, so the JS callers use a new `setNativeProps_DEPRECATED` overload that takes it. The existing overload is unchanged. Batching is bridgeless only, because bridge mode doesn't drain microtasks (Hermes has no microtask queue there), so with `enableBridgelessArchitecture` off every call still commits. The flag is off by default.

Changelog: [Internal]
@robhogan
robhogan force-pushed the robhogan/batch-set-native-props branch from 5a7beb5 to 694ee42 Compare November 28, 2026 02:17

@ccheever ccheever 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.

Review by Claude (Fable 5.2). From reading the source at 694ee42; I did not build or run the Fantom tests.

The design holds up. Recording the props immediately, queueing only the prop names, and reading their current values at flush time means the batch always lands on the newest tree, so a React commit between the call and the microtask can't be clobbered and can still override the value. I traced these and found no problem:

  • Commit branching. Choosing the React branch when a React revision exists is right, and the check-then-commit race with a merge on the main thread is benign: if the merge resets currentReactRevision_ in between, tryCommit starts a new React revision from the merged main branch.
  • Unmounted nodes. A queued family that has left the tree makes cloneMultiple either return nullptr (commit cancelled) or clone some ancestors needlessly; it can't crash.
  • props.at(name). Nothing ever removes a key from nativeProps_DEPRECATED or resets it, so the lookup can't throw.
  • Threading. Every caller of the revision provider is on the JS thread, so the flush always clones there and runtime shadow node references stay up to date.

Two things inline: one behaviour change with the flag on (setNativeProps from a ResizeObserver callback), and one gap that exists on main too but that the new read tests don't cover.

if (isFirstInBatch) {
// Committing in a microtask keeps these calls ahead of the observers and
// mount that follow them in the task.
runtime.queueMicrotask(

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.

setNativeProps from a ResizeObserver callback isn't committed until some later task runs

The batch depends on a microtask checkpoint following the call. The only one is in RuntimeScheduler_Modern::runEventLoopTick, after executeTask and before updateRendering. ResizeObserver callbacks run inside updateRendering (runResizeObservations → notifyResizeObservers calls into JS synchronously), and nothing drains microtasks after them.

So with the flag on:

new ResizeObserver(() => {
  other.setNativeProps({style: {height: 50}});
}).observe(target);

The props are stored and the node is queued, but the commit waits for the checkpoint of the next task, whenever one is scheduled. If the JS thread is otherwise idle, the view stays as it was until an unrelated task runs.

With the flag off, the same call commits immediately: the commit asks for a mount straight away (mountSynchronously is true), and the next gather round of the same runResizeObservations loop sees the surface as committed. With the flag on the gather loop doesn't rescue it, because gatherActiveResizeObservations returns before it reaches the revision provider when no surface has committed.

Two ways to fix it: commit the pending props after delivering resize observations (before the intersection observer step), or perform a microtask checkpoint after runResizeObservations, which is also closer to the HTML spec's "clean up after running a callback".

The existing ResizeObserver test only calls setNativeProps from a task. A test that calls it from inside the observer callback and asserts the rendered output without running another task would cover this.

RootShadowNode::Shared getCurrentRevision(SurfaceId surfaceId) override {
uiManager_.commitPendingNativeProps();
return uiManager_.lazyShadowTreeRevisionConsistencyManager_
->getCurrentRevision(surfaceId);

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.

The flush doesn't make the props visible if the task has already read this surface (same on main, so not a regression)

runEventLoopTick holds a ScopedShadowTreeRevisionLock for the whole tick. Once LazyShadowTreeRevisionConsistencyManager has captured a root for a surface, getCurrentRevision keeps returning it until updateCurrentRevision is called, and only completeSurface calls that. So:

el.getBoundingClientRect();                 // captures the root
el.setNativeProps({style: {width: 100}});
el.getBoundingClientRect().width;           // commits the queue, then returns the captured root: old width

The unbatched path has the same result, since its commit doesn't refresh the captured revision either. But the tests under "is visible to reads later in the task" only cover set → read, so they pass without this case working, and the ResizeObserver gather step reads through the same provider and gets the same captured root.

Calling lazyShadowTreeRevisionConsistencyManager_->updateCurrentRevision(surfaceId) for each surface that commitPendingNativeProps commits, as completeSurface does, would make the batched path do what the PR description says. A read → set → read test would pin it down.

@ccheever ccheever 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.

Review by Grok 4.7 (xhigh reasoning). Run against a checkout of 694ee42 with the same brief as the other reviewers; it read the source and did not build or run tests. The findings are the model's own, and the verification notes are from Claude.

The batching design is coherent for a task that never snapshots the shadow tree before the flush, and the new tests only cover that shape: one write, then a read, with rendered output checked after the tick. With the bridgeless scheduler the revision lock stays held across the task, microtasks, and rendering, and the flush does not replace the snapshot that lock already captured, so later JS reads and ResizeObserver keep the pre-batch root. With commit branching on, the batch is also committed onto the React branch while findNodeAtPoint and getRelativeLayoutMetrics still read the main revision.

Findings

  1. Flushing pending setNativeProps leaves the locked revision snapshot stale (rated high). Same issue as this thread, so not repeated inline. Grok adds a more common trigger than read → set → read: in a layout effect, React's own commit has already refreshed the snapshot through completeSurface, so setNativeProps followed by getBoundingClientRect() returns the old value there too. It also says ResizeObserver then never delivers the new size, because the commit's dirty mark is consumed against the stale root.
    Verification note (Claude): the snapshot behaviour is confirmed, and it is the same with the flag off, so the rating reflects the read guarantee in the PR description, not a regression. I did not verify the claim that the resize is never delivered.
  2. Hit-testing and relative metrics miss a batch committed onto the React branch (rated medium). Inline.

validateArgumentCount(runtime, methodName, paramCount, count);

if (UIManager::isSetNativePropsBatchingEnabled()) {
uiManager->commitPendingNativeProps();

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.

Hit-testing and relative metrics miss a batch committed onto the React branch (medium)

When enableFabricCommitBranching is on and ShadowTree::getCurrentReactRevision() is set, commitPendingNativeProps commits with CommitSource::React and mountSynchronously: false. tryCommit then writes currentReactRevision_ and does not update currentRevision_.

getRelativeLayoutMetrics (this flush) and findNodeAtPoint (UIManagerBinding.cpp around the new flush at line 323) then read the main revision only: UIManager::getRelativeLayoutMetrics and getNewestCloneOfShadowNode both use shadowTree.getCurrentRevision(). The flush landed on the other branch.

Concrete case, both flags on. A discrete setState commits in the microtask checkpoint (completeRoot uses CommitSource::React and sets currentReactRevision). Layout effects run after that mutation phase, still in the same locked turn:

useLayoutEffect(() => {
  child.setNativeProps({style: {width: 100}});
  width = UIManager.getRelativeLayoutMetrics(childNode, parentNode).width;
}, [dep]);

getRelativeLayoutMetrics flushes immediately, sees the React revision, and commits the width onto that branch. The metrics call then measures the main tree, which still has the old width. findNodeAtPoint misses the same update, so a point that the new layout should hit still resolves to the old target.

Promotion and merge run later, in updateRendering, after these reads. The existing tests call these APIs with no React revision in the turn, and the React-update tests only check output after the merge.

Resolve the root the way LazyShadowTreeRevisionConsistencyManager::updateCurrentRevision does (React revision when one exists, otherwise main) after the flush, or route both methods through getShadowTreeRevisionProvider() once that provider returns the post-commit root.


Verification note (Claude): confirmed. getNewestCloneOfShadowNode and the null-ancestor path of getRelativeLayoutMetrics read shadowTree.getCurrentRevision(), the main branch. With the flag off the call commits to the main branch, so these two reads do see it; with both flags on and a React revision present they don't.

@ccheever ccheever 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.

Review by Gemini 4 Neon (xhigh). Run against a checkout of 694ee42 with the same brief as the other reviewers; it read the source and did not build or run tests. The findings are the model's own, and the verification notes are from Claude.

The overall design—recording native props immediately, coalescing per-surface commits via cloneMultiple in a microtask, and flushing on JS shadow-tree reads—addresses the O(N^2) sibling-cloning problem cleanly on the happy path. However, there are several verified correctness bugs around microtask scheduling outside executeTask (notably ResizeObserver callbacks during updateRendering), stale revision reads through LazyShadowTreeRevisionConsistencyManager, commit-branching reads in findNodeAtPoint / getRelativeLayoutMetrics, and exception safety when rawProps is not an object. Additionally, SetNativeProps-itest.js misses these edge cases and its React-override test does not actually exercise React updating nativeProps_DEPRECATED between queueing and flushing.

Findings

  1. setNativeProps called from ResizeObserver callbacks is never committed in the same tick and can stall indefinitely (rated high). Same issue as this thread, not repeated inline.
  2. PendingNativePropsRevisionProvider returns a stale cached revision if a read or React commit already occurred earlier in the same task (rated high). Same issue as this thread, not repeated inline. Neon notes the unbatched path lacks the refresh as well.
  3. With enableFabricCommitBranching, findNodeAtPoint and getRelativeLayoutMetrics flush to the React branch but read from the main branch (rated high). Same issue as this thread, not repeated inline. Neon's suggested fix is to resolve the root for these two handlers through getShadowTreeRevisionProvider() and leave getCurrentRevision() on the main branch for native callers.
  4. Three more findings inline: a non-object payload leaving the queue stuck, a gap in the "lets React override the props" test, and the root node losing its layout constraints.

isFirstInBatch = pendingNativeProps_.empty();
auto& pendingNames = pendingNativeProps_[family.getSurfaceId()]
[shadowNode->getFamilyShared()];
for (const auto& name : props.keys()) {

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.

Non-object rawProps (or an exception before queueMicrotask) permanently wedges batching by leaving pendingNativeProps_ non-empty without a microtask (high)

In UIManager::setNativeProps_DEPRECATED(jsi::Runtime&, ...) (UIManager.cpp:561-588), pendingNativeProps_[family.getSurfaceId()][shadowNode->getFamilyShared()] is inserted before iterating props.keys() and before calling runtime.queueMicrotask(...).

Neither UIManagerBinding.cpp:612 (nativeFabricUIManager.setNativeProps) nor NativeDOM.cpp:486 (NativeDOM.setNativeProps) verifies that the JS payload is a plain object. In RawProps::RawProps(jsi::Runtime&, const jsi::Value&) (RawProps.cpp:20), value.isNull() returns false for undefined, arrays, and primitives, so (folly::dynamic)rawProps invokes jsi::dynamicFromValue (JSIDynamic.cpp:157-173) and yields a non-object folly::dynamic (NULLT, ARRAY, DOUBLE, BOOL, or STRING).

Scenario:

  1. pendingNativeProps_ is empty.
  2. JS calls nativeFabricUIManager.setNativeProps(node, undefined) (or NativeDOM.setNativeProps(node, undefined), or passes an array/primitive) inside a try/catch or error boundary.
  3. Line 568 sets isFirstInBatch = true, and line 569 inserts an empty entry into pendingNativeProps_, making pendingNativeProps_.empty() false.
  4. Line 571 calls props.keys(), which throws folly::TypeError because !props.isObject().
  5. Line 578 (runtime.queueMicrotask(...)) is never reached, yet pendingNativeProps_ remains non-empty.
  6. Every subsequent valid setNativeProps call across all surfaces sees pendingNativeProps_.empty() == false, sets isFirstInBatch = false, and never queues a microtask—silently stalling all future batched setNativeProps commits until some unrelated JS shadow-tree read happens to flush commitPendingNativeProps(). (The same stall happens if runtime.queueMicrotask(...) itself throws.)

Suggested fix: Check if (!props.isObject() || props.empty()) { return; } right after auto props = (folly::dynamic)rawProps; (before updateNativeProps and before modifying pendingNativeProps_, which also avoids queueing empty no-op commits and prevents storing non-object values in family.nativeProps_DEPRECATED->props), and guard runtime.queueMicrotask(...) so that if it throws, the batch state / scheduled flag is rolled back rather than left permanently stuck.


Verification note (Claude): confirmed by reading: the map entry is inserted before props.keys() can throw, and nothing later queues a microtask while the map is non-empty. The public setNativeProps on host instances only passes an object payload, so reaching this takes a direct call to the internal API with undefined, an array or a primitive. I'd rate it low, but ordering the insert after the checks is cheap.

});
}

test('lets React override the props', () => {

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.

lets React override the props never exercises React overriding a queued setNativeProps batch (medium)

Fantom renders with useConcurrentRoot: true (RendererImplementation.js:32, so root.tag === 1). In ReactFabric-dev.js, batchedUpdatesImpl (lines 20384-20395) only flushes legacy roots synchronously (flushSyncWorkAcrossRoots_impl(0, true)), while discrete-event setState calls on a concurrent root schedule processRootScheduleInMicrotask via scheduleMicrotask (lines 3748-3749, 3956-3963).

Scenario in the test:

  1. In test('lets React override the props') (lines 295-312), setNativeProps({testID: 'native'}) is called before setLabel('second') inside onClick.
  2. setNativeProps enqueues commitPendingNativeProps as microtask nil #1; setLabel('second') then enqueues React's processRootScheduleInMicrotask as microtask pthread.h not found #2.
  3. Microtask nil #1 commits and drains pendingNativeProps_ before React even starts rendering.
  4. As a result, the test only verifies the pre-existing behavior of UIManager::cloneNode overriding an already-committed setNativeProps, and never exercises the batched reconciliation path in UIManager.cpp:614-631 (where React calls cloneNode and updates family.nativeProps_DEPRECATED between queueing in setNativeProps_DEPRECATED and committing in commitPendingNativeProps). Similarly, in lines 256-293 with updateFirst = false, commitPendingNativeProps runs before React renders rather than with an active React revision.

Suggested fix: Force React to commit between setNativeProps and commitPendingNativeProps (e.g., via flushSync(() => setLabel('second')), or by scheduling a React update before setNativeProps so React's microtask executes ahead of commitPendingNativeProps while also updating testID). Also add test cases for: (1) JS reads and ResizeObserver after a prior read or React commit in the same task, (2) findNodeAtPoint / getRelativeLayoutMetrics after a React commit with enableFabricCommitBranching on, and (3) setNativeProps called from inside a ResizeObserver callback.


Verification note (Claude): the microtask order matches my reading: Fantom renders a concurrent root, and the batch's microtask is queued before React's. I did not check the ReactFabric-dev.js line numbers cited above.

shadowTree.commit(
[&](const RootShadowNode& oldRootShadowNode) {
return std::static_pointer_cast<RootShadowNode>(
oldRootShadowNode.cloneMultiple(

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.

Passing a RootShadowNode to batched setNativeProps wipes root layoutConstraints and layoutContext (low)

Unbatched setNativeProps_DEPRECATED uses oldRootShadowNode.cloneTree(family, ...) (UIManager.cpp:530), which calls family.getAncestors(oldRootShadowNode) (ShadowNode.cpp:391). When family is the root node's own family, getAncestors returns an empty list (ShadowNodeFamily.cpp:122-129), cloneTree returns nullptr, and the commit is cleanly cancelled.

With batching, oldRootShadowNode.cloneMultiple(families, ...) (ShadowNode.cpp:469, 489) puts the root tag into childrenCount, so childrenCount.contains(getTag()) is true and cloneMultipleRecursive calls propsWithPendingProps(oldRootShadowNode) -> RootComponentDescriptor::cloneProps(...) (UIManager.cpp:632-635). That invokes the 3-argument constructor RootProps::RootProps(context, sourceProps, rawProps) (RootProps.cpp:18-22), which does not copy sourceProps.layoutConstraints or sourceProps.layoutContext, resetting both to {} (zeroed pointScaleFactor and empty constraints).

Scenario: JS retrieves the root shadow node (exposed via NativeDOM::linkRootNode) and passes it to NativeDOM.setNativeProps(rootNode, {testID: 'x'}) or nativeFabricUIManager.setNativeProps(rootNode, {testID: 'x'}). Under batching, the surface's RootProps loses its layoutConstraints and layoutContext on commit.

Suggested fix: Ignore root shadow nodes (e.g., skip nodes with ShadowNodeTraits::Trait::RootNodeKind matching oldRootShadowNode, or return ShadowNodeFragment::propsPlaceholder() when ShadowNode::sameFamily(oldShadowNode, oldRootShadowNode) and omit the root family from families) to match unbatched cloneTree.


Verification note (Claude): confirmed mechanically: RootProps' three-argument constructor doesn't copy layoutConstraints or layoutContext, and cloneTree cancels for the root family where cloneMultiple doesn't. It is only reachable by passing the root node to the internal API directly.

@ccheever ccheever 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.

Review by GPT-6.2 Astra (max reasoning). Run against a checkout of 694ee42 with the same brief as the other reviewers; it read the source and did not build or run tests. The findings are the model's own, and the verification notes are from Claude.

I would request changes before enabling the flag. Same-task reads can return stale layout, and the batch can publish props from a React render that never commits. The Fantom tests exercise synchronous writes on one surface, but miss reads from an already captured revision, writes during ResizeObserver delivery, and errors after a batch reaches the React branch. I reviewed commit 694ee42d99 from source only.

Findings that match existing threads (not repeated inline)

  • Refresh the task's cached revision after a batch commits (rated high): thread.
  • Hit testing and relative measurement read the wrong branch after flushing (rated high): thread.
  • Writes from a ResizeObserver callback miss the rendering step (rated high): thread.
  • An invalid first payload can prevent subsequent batches from being scheduled (rated medium): thread.

New findings, inline: a discarded React render overwriting a queued value, a later throwing microtask dropping the promotion, one conversion error discarding the batch, an accessibility event overtaking the props on Android, and a queued write consuming a LayoutAnimation.

Smaller points, not inline

  • JS tag lookups still return pre-batch shadow nodes (rated medium). FabricUIManager.findShadowNodeByTag_DEPRECATED enumerates the main trees directly and wraps the node it finds. For example, resize a native ScrollView, look it up by tag, and pass that handle to NativeFantom.enqueueScrollEvent in the same task. The emitted event uses the old container width because the consumer reads layout directly from the returned node. NativeViewTransition.findPseudoElementShadowNodeByTag also enumerates main directly. Flush before these JS lookups and search the JS-visible revisions.
    Verification note (Claude): it's true that findShadowNodeByTag_DEPRECATED doesn't flush. The callers I know of pass the returned node to the measure methods, which flush and resolve the newest clone, so I'd rate it low.
  • Combining prop names changes which style alias wins (rated medium). On iOS, set style.backgroundSize to '20px' and then style.experimental_backgroundSize to '40px' on the same view. Separate calls leave the background size at 40px. The batch passes both names to the classic BaseViewProps constructor together, where backgroundSize takes precedence over its alias, leaving 20px. Preserve call order when applying patches to typed props, or normalize aliases before coalescing them. The ordering test only repeats an identical key.
    Verification note (Claude): the precedence in BaseViewProps is as described (backgroundSize wins when both keys are in one payload). Niche.
  • A JS microtask can produce a second commit on the same surface in one tick (rated medium). Call a.setNativeProps(...), then queueMicrotask(() => b.setNativeProps(...)) for a sibling, with no intervening read. The first native flush runs ahead of the JS microtask. The second setter sees an empty queue and schedules another commit before the same rendering step. The revision assertion here covers two synchronous calls on one surface. To guarantee one commit per surface per scheduler tick, flush after the microtask checkpoint and before observers, and count commits on each of two surfaces with a write made from a JS microtask.
    Verification note (Claude): this follows from committing in a microtask and is a cost observation, not a correctness problem; the PR only promises one commit for the calls made before the flush.

const auto& family = *it->first;
std::lock_guard<std::mutex> lock(family.nativePropsMutex);
for (const auto& name : it->second) {
currentProps[name] = family.nativeProps_DEPRECATED->props.at(name);

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.

A discarded React clone can overwrite a queued imperative value (high)

After setNativeProps({testID: 'native'}), let Fabric call cloneNodeWithNewProps for the same node with testID: 'draft' and discard the clone before completeRoot. UIManager::cloneNode has already written 'draft' into family.nativeProps_DEPRECATED. The flush reads that value here and publishes it to the mounted tree, even though the render never committed. Retain the imperative value in the batch and reconcile later React overrides against a successfully committed revision. The current override test only exercises a render that commits.


Verification note (Claude): confirmed that UIManager::cloneNode writes React's value into nativeProps_DEPRECATED at clone time, before completeRoot, and that the flush reads from there, so a render that is thrown away leaves its value to be published. The window is narrow: the discarded render has to run between the setNativeProps call and the microtask of the same task, for example a synchronous re-render that suspends. With the flag off the call commits its own value, although the stored value is overwritten the same way. I'd rate it low to medium.

if (shadowTree.getCurrentReactRevision().has_value()) {
commitOptions = {
.mountSynchronously = false,
.source = ShadowTree::CommitSource::React};

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.

A later throwing microtask can strand an already flushed batch (medium)

With a pending React revision, have a layout effect call setNativeProps and then queue a microtask that throws. The native-props microtask runs first, empties the batch, and schedules React revision promotion. The later exception makes RuntimeScheduler_Modern::clearQueues discard the promotion from pendingRenderingUpdates_. The change never reaches main unless later work promotes that surface. Preserve or reschedule promotion for a committed batch during error recovery, and test an exception after the flush as well as one before it.


Verification note (Claude): confirmed: handleTaskError calls clearQueues, which empties pendingRenderingUpdates_, where the promotion was queued. React's own commit loses its promotion the same way if a later microtask throws, so this is an existing hazard of commit branching that batched props now share whenever a React revision is present.

decltype(pendingNativeProps_) pendingNativeProps;
{
std::lock_guard<std::mutex> lock(pendingNativePropsMutex_);
pendingNativeProps.swap(pendingNativeProps_);

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.

One prop conversion error discards earlier valid writes (medium)

Queue a valid width change on one view and then pass a numeric accessibilityRole to another view on the same surface. The classic AccessibilityProps constructor reads the role as a string, which throws when parsing the stored numeric value. Both setters have already returned. The exception aborts the surface transaction and destroys the swapped-out batch, including the valid width change and any surfaces still awaiting processing. Validate failing patches at the setter boundary or isolate them so earlier valid work still commits.


Verification note (Claude): confirmed for this example: AccessibilityProps converts accessibilityRole with a bare fromRawValue (AccessibilityProps.cpp:185), outside the try/catch in convertRawProp, so a number throws. Most other props go through convertRawProp and fall back to a default. With the flag off the exception reaches the caller of that one setNativeProps and nothing else is lost.

}
}

void UIManager::sendAccessibilityEvent(

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.

An Android accessibility event can overtake creation of its target (medium)

On a flattened Android View, call setNativeProps({accessible: true}) and then AccessibilityInfo.sendAccessibilityEvent(view, 'focus'). Setting accessible makes the shadow node form a native view, but its creation now waits for the microtask. The accessibility event goes straight onto the Android mount-item queue first. SurfaceMountingManager.sendAccessibilityEvent finds no native view and drops the event. Order the event after the pending props have mounted.


Verification note (Claude): confirmed the Android side: the event goes on the same mount-item queue (addMountItem), and SurfaceMountingManager.sendAccessibilityEvent logs a soft exception and returns when the view doesn't exist. More generally, anything sent to the mounting layer later in the same task now goes ahead of the props, where the unbatched commit asked for a mount at the call (mountSynchronously). I expect that includes dispatchCommand, but I didn't trace it per platform.

void commitPendingNativeProps() const;

/**
* Configure a LayoutAnimation to happen on the next commit.

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.

A pending write can consume a subsequently configured LayoutAnimation (medium)

On Android with Fabric layout animations enabled and the default per-commit transaction pulling, change a mounted view's width via setNativeProps, then call LayoutAnimation.configureNext for a later React update. The earlier width change now commits after configuration. Its nonempty transaction consumes and clears LayoutAnimationKeyFrameManager::currentAnimation_, so the intended React update gets no animation. Flush preceding imperative writes before arming the next layout animation.


Verification note (Claude): confirmed that LayoutAnimationKeyFrameManager::pullTransaction takes and clears currentAnimation_ for the next transaction it sees. I did not trace the Android pull timing myself; it rests on each commit being pulled on the JS thread, as the PR description says.

@robhogan

robhogan commented Nov 29, 2026 •

Copy link
Copy Markdown
Collaborator Author

Thanks @ccheever! I fed this and @kitten's offline feedback ("handover" below) back for another few rounds of iteration.


setNativeProps in a ResizeObserver callback

#60355 (comment) (and the handover's P3)

Fixed in 30c8319. The callable that NativeResizeObserver hands to ResizeObserverManager now commits pending props as soon as the JS callbacks return, so the change mounts in the same rendering update, and the next gather round sees it. The manager copies that callable before invoking it, so a callback that disconnects the last observer still gets its props committed. A microtask checkpoint after observer callbacks is the spec-shaped fix, but it changes every microtask queued in those callbacks, so I'd rather do that separately.

Together with the refresh below, a nested observer now sees the change in the same update (the handover's reproduction B). With the flag off it's still lost, which is pre-existing. Reproduction C passed because an initial delivery leaves the surface pending for one more gather round, which reads through the flushing provider.

One behaviour change with the flag on, which I think is expected, and which is now in the description: a callback that resizes a target at its own depth or shallower gets the spec's loop error. It's logged with console.error, so it shows in LogBox in dev. That target then isn't notified again until the surface next commits, because ResizeObserverManager only re-gathers a skipped observation on a commit. That part is pre-existing: with the flag off the target is never notified at all. I'll look at re-gathering skipped observations separately.

Reads after an earlier read in the task

#60355 (comment)

Fixed for the batched path in 33c72aa: a batch now refreshes the surface's captured revision, as completeSurface does. That covers Grok's layout effect case too, and its point about ResizeObserver, which holds with the flag off: the observer never sees the change there. New tests cover read → set → read, and setNativeProps then getBoundingClientRect in a layout effect, on mount and on an update that commits. With the flag off these reads still see the tree from the task's first read or React commit, which is pre-existing, and I've left that path as it is on main.

Hit-testing and relative metrics with commit branching

#60355 (comment) (and the handover's P2)

Not changed. This is a regression with the flag on, but only with enableFabricCommitBranching on too, and only while a React revision is pending: with the flag off, both reads see the new value at once. They already miss React's own revision in that window, which is pre-existing, and with the flag off the merge then drops the setNativeProps value, so the flag-off path isn't correct there either. Neon's suggestion of resolving through the revision provider needs JS-only variants of both methods, because Android's native code calls UIManager::getRelativeLayoutMetrics too, and it changes flag-off reads as well. I think it belongs with the branching work. The description lists it.

With enableFabricCommitBranchingMergeOnMainThread, a React revision lasts until the main thread merges it, so this window isn't limited to layout effects, and batches in later tasks go onto React's branch and mount at the merge. That's a delay rather than a regression: with the flag off, those calls go onto the main branch and the merge drops them. That's from reading only, since Fantom merges synchronously.

Accessibility events and LayoutAnimation

#60355 (comment)
#60355 (comment)

Fixed in 6eae363: the binding commits pending props before sendAccessibilityEvent and configureNextLayoutAnimation. dispatchCommand doesn't need it, because the scheduler already defers commands to the rendering update, after the mount:

void Scheduler::uiManagerDidDispatchCommand(
const std::shared_ptr<const ShadowNode>& shadowNode,
const std::string& commandName,
const folly::dynamic& args) {
TraceSection s(
"Scheduler::uiManagerDispatchCommand", "commandName", commandName);
if (delegate_ != nullptr) {
auto shadowView = ShadowView(*shadowNode);
runtimeScheduler_->scheduleRenderingUpdate(
shadowNode->getSurfaceId(),
[delegate = delegate_,
shadowView = std::move(shadowView),
commandName,
args]() {
delegate->schedulerDidDispatchCommand(shadowView, commandName, args);
});
}
}

What's left, all regressions with the flag on:

  • With commit branching on and a React revision pending, the batch goes onto React's branch and mounts at the merge, so the event still goes out first. That's the same ordering React's own view changes get in that window, and with the flag off the props mount first but the merge then drops them. The description lists it.
  • TurboModule calls that act on a view tag, like iOS's deprecated setAccessibilityFocus, don't commit the queue first, so they can still overtake the props.
  • setIsJSResponder also goes straight to the mounting layer, so in principle it's the same. But React sets the responder during event extraction, before any handler runs, so I don't see a way for a handler's setNativeProps to come first.

Non-object payloads and the root node

#60355 (comment)
#60355 (comment)

Fixed in ddff3b7 and f0c4251: both take the unbatched path now. There's no test for the payload one, because that path aborts the debug tester on undefined or an array with the flag off too:

react_native_assert(rawProps.value_.isObject());

The root check is the root component handle rather than RootNodeKind, which <Modal> and InputAccessoryView carry too, so calls on those are still batched. The unbatched path still stores the props, and the next commit that clones the root applies them, which zeroes its layout constraints. That's pre-existing: main does the same with the flag on or off. I'll fix it for both paths separately.

The override test

#60355 (comment)

Right - with React's update after the call, the batch's microtask runs before React renders. aa6ac72 also runs it with the update before the call, where React commits first and the batch has to take React's value from nativeProps_DEPRECATED. That order fails if the batch applies each call's own values.

A discarded React render

#60355 (comment) (and the handover's P1)

Not changed. This is a regression with the flag on, with a narrow trigger: a render of the same node with the same prop, after the call and before the microtask in the same task, which React then throws away. With the flag off, the call commits its own value first. The underlying problem is pre-existing, though: cloneNode writes the speculative value into nativeProps_DEPRECATED with the flag off too, and reading the code, it then reaches the tree at the node's next clone. Storing each call's values instead breaks React winning when it commits after the call, which the reordered override test now pins down. Fixing it properly means reconciling against committed revisions, which is a bigger change than this PR.

A prop that fails to convert

#60355 (comment)

Not changed. Part of this is a regression with the flag on and part is pre-existing.

The regression: the other calls made earlier in that task are lost, the caller can't catch the error because it comes from whatever commits the batch first, and from a ResizeObserver callback it reaches onTaskError_ instead of being logged. The description now says so.

Pre-existing: with the flag off the bad value is stored too, and every later commit that clones that node or a sibling throws, so the app is broken from that point either way. That's also why I couldn't isolate the failing node. I tried leaving it unchanged, but ShadowNode::clone re-applies a node's whole nativeProps_DEPRECATED whenever it's cloned with placeholder props, so the bad value throws again in the same commit:

std::shared_ptr<ShadowNode> ShadowNode::clone(
const ShadowNodeFragment& fragment) const {
const auto& family = *family_;
const auto& componentDescriptor = family.componentDescriptor_;
std::shared_ptr<const Props> props;
{
std::lock_guard<std::mutex> lock(family.nativePropsMutex);
const auto& nativeProps = family.nativeProps_DEPRECATED;
if (nativeProps != nullptr) {
if (fragment.props == ShadowNodeFragment::propsPlaceholder()) {
// Props that already include `nativeProps_DEPRECATED` don't need
// them applied again.
if (nativeProps->appliedProps != props_) {
// Clone existing `props_` with `family.nativeProps_DEPRECATED` to
// apply previously set props via `setNativeProps` API.
auto propsParserContext =
PropsParserContext{family_->getSurfaceId(), {}};
props = componentDescriptor.cloneProps(
propsParserContext, props_, RawProps(nativeProps->props));
nativeProps->appliedProps = props;
}
} else {
// TODO: We might need to merge fragment.props with
// `family.nativeProps_DEPRECATED`.
}
}
}

A later microtask that throws

#60355 (comment)

Not changed. This is a regression with the flag on, but only with commit branching on too, when the batch goes onto React's branch: with the flag off the call is committed and mounted at once, so clearQueues can't drop it. It comes from a pre-existing branching hazard, since React's own commit loses its promotion the same way when clearQueues empties pendingRenderingUpdates_, so I think the fix belongs in RuntimeScheduler_Modern's error recovery rather than here.

Smaller points

  • findShadowNodeByTag_DEPRECATED doesn't commit the queue, so with the flag on it can return the node from before the batch. That's a difference that I'd call expected, because the callers I know of pass the node on to the measure methods, which commit the queue and resolve the newest clone first.
  • With backgroundSize and experimental_backgroundSize set by separate calls in one batch, backgroundSize wins regardless of order, where separate commits let the last call win. That's a regression with the flag on, and niche enough that I've left it.
  • A setNativeProps from a JS microtask can make a second commit on the surface in the same tick. That's expected, since only the calls made before the flush share a commit, and nothing is lost.
  • db56967 is a small refactor: commitPendingNativeProps checks the flag itself, so the new call sites don't each need a guard.

The handover's other notes

  • Teardown: Not a problem. The microtask holds a raw UIManager pointer, but the UIManagerBinding installed on the runtime owns the UIManager, and every binding host function captures the same pointer.
  • Commit hooks that check source == React: Expected, and only with commit branching on. They run for a batch only when it goes onto React's branch, and then behave as they do for React's own commit (eg AnimationBackendCommitHook reapplies animated props over it). Not tested at runtime.
  • Other JS after the microtask checkpoint: Not a problem. Event Timing queues PerformanceObserver callbacks as separate tasks, so the ResizeObserver step is the only JS in updateRendering.
  • A native-driven animation and an imperative update on the same node (0 batched, 50 unbatched): A behaviour change with the flag on that I think is expected. The batch commits after React's update, so the imperative value, set after the update, wins until the animation's next frame.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. Meta Review Required This PR is considered risky and requires Meta to import it to do more testing before merging. Shared with Meta Applied via automation to indicate that an Issue or Pull Request has been shared with the team.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants