Repository navigation
Conversation
7156d8f to
5a7beb5
Compare
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]
5a7beb5 to
694ee42
Compare
ccheever
left a comment
There was a problem hiding this comment.
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,tryCommitstarts a new React revision from the merged main branch. - Unmounted nodes. A queued family that has left the tree makes
cloneMultipleeither returnnullptr(commit cancelled) or clone some ancestors needlessly; it can't crash. props.at(name). Nothing ever removes a key fromnativeProps_DEPRECATEDor 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( |
There was a problem hiding this comment.
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); |
There was a problem hiding this comment.
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 widthThe 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
left a comment
There was a problem hiding this comment.
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
- 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, sosetNativePropsfollowed bygetBoundingClientRect()returns the old value there too. It also saysResizeObserverthen 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. - 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(); |
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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
setNativePropscalled fromResizeObservercallbacks is never committed in the same tick and can stall indefinitely (rated high). Same issue as this thread, not repeated inline.PendingNativePropsRevisionProviderreturns 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.- With
enableFabricCommitBranching,findNodeAtPointandgetRelativeLayoutMetricsflush 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 throughgetShadowTreeRevisionProvider()and leavegetCurrentRevision()on the main branch for native callers. - 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()) { |
There was a problem hiding this comment.
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:
pendingNativeProps_is empty.- JS calls
nativeFabricUIManager.setNativeProps(node, undefined)(orNativeDOM.setNativeProps(node, undefined), or passes an array/primitive) inside atry/catchor error boundary. - Line 568 sets
isFirstInBatch = true, and line 569 inserts an empty entry intopendingNativeProps_, makingpendingNativeProps_.empty()false. - Line 571 calls
props.keys(), which throwsfolly::TypeErrorbecause!props.isObject(). - Line 578 (
runtime.queueMicrotask(...)) is never reached, yetpendingNativeProps_remains non-empty. - Every subsequent valid
setNativePropscall across all surfaces seespendingNativeProps_.empty() == false, setsisFirstInBatch = false, and never queues a microtask—silently stalling all future batchedsetNativePropscommits until some unrelated JS shadow-tree read happens to flushcommitPendingNativeProps(). (The same stall happens ifruntime.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', () => { |
There was a problem hiding this comment.
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:
- In
test('lets React override the props')(lines 295-312),setNativeProps({testID: 'native'})is called beforesetLabel('second')insideonClick. setNativePropsenqueuescommitPendingNativePropsas microtask nil #1;setLabel('second')then enqueues React'sprocessRootScheduleInMicrotaskas microtaskpthread.hnot found #2.- Microtask nil #1 commits and drains
pendingNativeProps_before React even starts rendering. - As a result, the test only verifies the pre-existing behavior of
UIManager::cloneNodeoverriding an already-committedsetNativeProps, and never exercises the batched reconciliation path inUIManager.cpp:614-631(where React callscloneNodeand updatesfamily.nativeProps_DEPRECATEDbetween queueing insetNativeProps_DEPRECATEDand committing incommitPendingNativeProps). Similarly, in lines 256-293 withupdateFirst = false,commitPendingNativePropsruns 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( |
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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_DEPRECATEDenumerates 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 toNativeFantom.enqueueScrollEventin the same task. The emitted event uses the old container width because the consumer reads layout directly from the returned node.NativeViewTransition.findPseudoElementShadowNodeByTagalso enumerates main directly. Flush before these JS lookups and search the JS-visible revisions.
Verification note (Claude): it's true thatfindShadowNodeByTag_DEPRECATEDdoesn'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.backgroundSizeto'20px'and thenstyle.experimental_backgroundSizeto'40px'on the same view. Separate calls leave the background size at 40px. The batch passes both names to the classicBaseViewPropsconstructor together, wherebackgroundSizetakes 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 inBaseViewPropsis as described (backgroundSizewins 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(...), thenqueueMicrotask(() => 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); |
There was a problem hiding this comment.
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}; |
There was a problem hiding this comment.
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_); |
There was a problem hiding this comment.
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( |
There was a problem hiding this comment.
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. |
There was a problem hiding this comment.
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.
|
Thanks @ccheever! I fed this and @kitten's offline feedback ("handover" below) back for another few rounds of iteration.
|
Summary:
Currently, every
setNativePropscall commits the shadow tree:react-native/packages/react-native/ReactCommon/react/renderer/uimanager/UIManager.cpp
Lines 487 to 514 in 3b49389
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). WhileenableAccumulatedUpdatesInRawPropsAndroidis 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,setNativePropsstill records its props innativeProps_DEPRECATEDstraight away, but queues the node, and the first call in a task queues a microtask that commits every queued node in onecloneMultiplecommit 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. WithenableFabricCommitBranching, 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 andLayoutAnimation.configureNext, which would otherwise reach the platform ahead of the props. Calls made inResizeObservercallbacks, 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:
LayoutAnimation.configureNextin that window still reaches the platform first, as it does for React's own changes.findNodeAtPointandgetRelativeLayoutMetricsread the main branch, so they don't see a batch on React's revision until the merge, as with React's own changes.ResizeObservercallback, that error is reported as fatal rather than logged. With the flag off the bad value stays innativeProps_DEPRECATEDtoo, so later commits that clone the node or its siblings throw either way.ResizeObservercallback 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
setNativePropsevery frame), release builds ofmainand this PR side by side:android-main-vs-pr-public.mp4
ios-main-vs-pr-public.mp4
mainChangelog:
[Internal]
Test Plan:
New Fantom test, run with the flag and
enableFabricCommitBranchingeach on and off:68 tests pass. Its
ResizeObserverand 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 throughsetNativeProps, which reverts the animated value. Its tests for reads after an earlier read and in a layout effect, calls fromResizeObservercallbacks (including one that disconnects), accessibility events andLayoutAnimation, the root node, and React overriding the props with its update first each fail without the change they cover.The existing Mounting,
ReactNativeElement, Animated,ResizeObserverandIntersectionObserversuites 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 onesetNativePropsper view per frame fromrequestAnimationFrame. 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.