From f0653b99efdba77ae88c7fc4d17495e873b1408b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rub=C3=A9n=20Norte?= Date: Wed, 2 Dec 2026 02:58:41 -0800 Subject: [PATCH] Drain `ResizeObserver` callback microtasks before rendering (#60436) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Summary: ## Context `ResizeObserver` callbacks run during the rendering phase, after the task's normal microtask checkpoint. Jobs queued by those callbacks were left pending until another task arrived, so a later observer or native rendering could run before those jobs. On the Web, [broadcast active resize observations, ยง3.4.5 step 2.4](https://drafts.csswg.org/resize-observer/#broadcast-active-resize-observations) invokes each observer's callback individually using [Web IDL's callback invocation algorithm](https://webidl.spec.whatwg.org/#invoke-a-callback-function). Its step 13.2 performs [HTML script cleanup](https://html.spec.whatwg.org/multipage/webappapis.html#clean-up-after-running-script), which triggers a [microtask checkpoint](https://html.spec.whatwg.org/multipage/webappapis.html#perform-a-microtask-checkpoint) when the JavaScript execution-context stack becomes empty. For top-level rendering-phase delivery, that checkpoint drains queued jobs before the invocation returns and the broadcast continues. [HTML's rendering algorithm](https://html.spec.whatwg.org/multipage/webappapis.html#update-the-rendering) places the ResizeObserver loop before the final UI update. ## Changes Deliver each observer's native notification separately through a scheduler-owned callback invoker. The invoker calls the notification, performs callback cleanup (including its microtask checkpoint), and then returns to the manager. The manager has no raw microtask-draining capability. Snapshot entries and root their JavaScript identities for the whole broadcast so observer removal and garbage collection cannot invalidate later deliveries. The task checkpoint keeps its original error-handling policy. Uncaught observer checkpoint and notification errors unwind the observer machinery before clearing queued work and invoking the host fatal handler, then stop the rendering step. This prevents pending callbacks from accessing delegates destroyed during teardown. Handled observer exceptions continue normally. Keep the existing microtask-checkpoint reentry protection, without adding task/rendering-phase state or redundant entry guards. Add public-behavior integration coverage for FIFO promise/await/nested jobs, inter-observer ordering, pre-mount execution, deeper-target observations, nested measure callbacks, cancellation and error recovery. Update existing state-update tests to distinguish a real later rendering task from jobs that were previously stuck until an arbitrary wake. Changelog: [General][Fixed] - Run ResizeObserver callback microtasks before later observers and native rendering. Reviewed By: christophpurrer Differential Revision: D135358311 --- .../resize/ResizeObserverManager.cpp | 65 +- .../observers/resize/ResizeObserverManager.h | 9 +- .../RuntimeSchedulerResizeObserverDelegate.h | 7 +- .../RuntimeScheduler_Modern.cpp | 38 +- .../RuntimeScheduler_Modern.h | 2 +- .../tests/RuntimeSchedulerTest.cpp | 105 +++- .../SchedulerDelegateInvalidationTest.cpp | 70 ++- .../webapis/resizeobserver/__docs__/README.md | 22 +- .../__tests__/ResizeObserver-itest.js | 581 +++++++++++++++++- .../ReactAndroidFrameworksCxx.api | 3 +- .../api-snapshots/ReactAppleFrameworksCxx.api | 3 +- .../ReactCommonFrameworksCxx.api | 3 +- 12 files changed, 839 insertions(+), 69 deletions(-) diff --git a/packages/react-native/ReactCommon/react/renderer/observers/resize/ResizeObserverManager.cpp b/packages/react-native/ReactCommon/react/renderer/observers/resize/ResizeObserverManager.cpp index 74014199a3ef..085ada27ac93 100644 --- a/packages/react-native/ReactCommon/react/renderer/observers/resize/ResizeObserverManager.cpp +++ b/packages/react-native/ReactCommon/react/renderer/observers/resize/ResizeObserverManager.cpp @@ -251,7 +251,9 @@ void ResizeObserverManager::shadowTreeDidCommit( #pragma mark - RuntimeSchedulerResizeObserverDelegate -void ResizeObserverManager::runResizeObservations(jsi::Runtime& runtime) { +void ResizeObserverManager::runResizeObservations( + jsi::Runtime& runtime, + const CallbackInvoker& invokeCallback) { TraceSection s{"ResizeObserverManager::runResizeObservations"}; // The broadcast below runs JS, which may commit synchronously and re-enter @@ -288,8 +290,8 @@ void ResizeObserverManager::runResizeObservations(jsi::Runtime& runtime) { break; } - auto shallowest = - broadcastActiveResizeObservations(runtime, gathered.activeObservations); + auto shallowest = broadcastActiveResizeObservations( + runtime, gathered.activeObservations, invokeCallback); if (!shallowest.has_value()) { break; } @@ -299,7 +301,7 @@ void ResizeObserverManager::runResizeObservations(jsi::Runtime& runtime) { // https://w3c.github.io/csswg-drafts/resize-observer/#deliver-resize-loop-error if (hasSkippedObservations) { - notifyResizeObservers(runtime, true); + invokeCallback([&]() { notifyResizeObservers(runtime, true); }); } } @@ -425,7 +427,8 @@ ResizeObserverManager::gatherActiveResizeObservations(size_t depth) { std::optional ResizeObserverManager::broadcastActiveResizeObservations( jsi::Runtime& runtime, - std::vector& active) { + std::vector& active, + const CallbackInvoker& invokeCallback) { TraceSection s{"ResizeObserverManager::broadcastActiveResizeObservations"}; if (active.empty() || notifyResizeObserversFunction_ == nullptr) { @@ -445,26 +448,41 @@ std::optional ResizeObserverManager::broadcastActiveResizeObservations( }); std::optional shallowestDepth; - { - std::unique_lock lock(pendingEntriesMutex_); - pendingEntries_.reserve(pendingEntries_.size() + active.size()); - for (auto& observation : active) { - observation.observer->markAsReported(observation.result); - shallowestDepth = shallowestDepth.has_value() - ? std::min(shallowestDepth.value(), observation.result.targetDepth) - : observation.result.targetDepth; - pendingEntries_.push_back(std::move(*observation.result.entry)); - } + std::vector entries; + // Instance handles are weak; root their JS identities across checkpoints. + std::vector targetInstanceHandles; + entries.reserve(active.size()); + targetInstanceHandles.reserve(active.size()); + for (auto& observation : active) { + targetInstanceHandles.push_back( + observation.result.entry->shadowNodeFamily->getInstanceHandle(runtime)); + observation.observer->markAsReported(observation.result); + shallowestDepth = shallowestDepth.has_value() + ? std::min(shallowestDepth.value(), observation.result.targetDepth) + : observation.result.targetDepth; + entries.push_back(std::move(*observation.result.entry)); } - if (!notifyResizeObservers(runtime, false)) { - return std::nullopt; + // Snapshot every entry before invoking JS, which can remove any observer. + active.clear(); + auto entry = entries.begin(); + while (entry != entries.end() && notifyResizeObserversFunction_ != nullptr) { + const auto observerId = entry->resizeObserverId; + { + std::unique_lock lock(pendingEntriesMutex_); + do { + pendingEntries_.push_back(std::move(*entry)); + ++entry; + } while (entry != entries.end() && entry->resizeObserverId == observerId); + } + + invokeCallback([&]() { notifyResizeObservers(runtime, false); }); } return shallowestDepth; } -bool ResizeObserverManager::notifyResizeObservers( +void ResizeObserverManager::notifyResizeObservers( jsi::Runtime& runtime, bool hasResizeLoopError) { // Copy the callable: the notification runs JS, and a callback may @@ -472,14 +490,19 @@ bool ResizeObserverManager::notifyResizeObservers( // still executing it. auto notifyResizeObserversFunction = notifyResizeObserversFunction_; if (notifyResizeObserversFunction == nullptr) { - return false; + return; } // No lock may be held here. JS pulls the entries with `takeRecords` and the // callbacks it then invokes can re-enter `observe`/`unobserve`/`disconnect`, // or commit synchronously (which re-enters the commit hook on this thread). - notifyResizeObserversFunction(runtime, hasResizeLoopError); - return true; + try { + notifyResizeObserversFunction(runtime, hasResizeLoopError); + } catch (...) { + std::unique_lock lock(pendingEntriesMutex_); + pendingEntries_.clear(); + throw; + } } } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/observers/resize/ResizeObserverManager.h b/packages/react-native/ReactCommon/react/renderer/observers/resize/ResizeObserverManager.h index 990af7c7d6e3..c63140f277c3 100644 --- a/packages/react-native/ReactCommon/react/renderer/observers/resize/ResizeObserverManager.h +++ b/packages/react-native/ReactCommon/react/renderer/observers/resize/ResizeObserverManager.h @@ -53,7 +53,7 @@ class ResizeObserverManager final : public UIManagerCommitHook, public RuntimeSc #pragma mark - RuntimeSchedulerResizeObserverDelegate - void runResizeObservations(jsi::Runtime &runtime) override; + void runResizeObservations(jsi::Runtime &runtime, const CallbackInvoker &invokeCallback) override; #pragma mark - UIManagerCommitHook @@ -140,10 +140,11 @@ class ResizeObserverManager final : public UIManagerCommitHook, public RuntimeSc // was delivered. std::optional broadcastActiveResizeObservations( jsi::Runtime &runtime, - std::vector &active); + std::vector &active, + const CallbackInvoker &invokeCallback); - // Calls into JS. Returns false if there is nothing connected to notify. - bool notifyResizeObservers(jsi::Runtime &runtime, bool hasResizeLoopError); + // Calls into JS. + void notifyResizeObservers(jsi::Runtime &runtime, bool hasResizeLoopError); }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeSchedulerResizeObserverDelegate.h b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeSchedulerResizeObserverDelegate.h index 2a74c9a2e873..13d97e9e2482 100644 --- a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeSchedulerResizeObserverDelegate.h +++ b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeSchedulerResizeObserverDelegate.h @@ -10,14 +10,19 @@ #include #include +#include namespace facebook::react { class RuntimeSchedulerResizeObserverDelegate { public: + using CallbackInvoker = std::function &)>; + virtual ~RuntimeSchedulerResizeObserverDelegate() = default; - virtual void runResizeObservations(jsi::Runtime &runtime) = 0; + // Invocations are synchronous and include callback cleanup. Do not retain + // the invoker or use it before the previous author callback has returned. + virtual void runResizeObservations(jsi::Runtime &runtime, const CallbackInvoker &invokeCallback) = 0; }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeScheduler_Modern.cpp b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeScheduler_Modern.cpp index 2e57e23b0ce2..45785c4b5f71 100644 --- a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeScheduler_Modern.cpp +++ b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeScheduler_Modern.cpp @@ -30,6 +30,12 @@ int64_t durationToMilliseconds(HighResDuration duration) { return duration.toNanoseconds() / static_cast(1e6); } +[[noreturn]] void rethrowMicrotaskError( + jsi::Runtime& /*unused*/, + jsi::JSError& error) { + throw error; +} + } // namespace #pragma mark - Public @@ -334,7 +340,10 @@ void RuntimeScheduler_Modern::runEventLoopTick( executeTask(runtime, task, didUserCallbackTimeout); // "Perform a microtask checkpoint" step. - performMicrotaskCheckpoint(runtime); + performMicrotaskCheckpoint( + runtime, [this](jsi::Runtime& runtime, jsi::JSError& error) { + handleTaskError(runtime, error); + }); auto taskEndTime = now_(); markYieldingOpportunity(taskEndTime); @@ -369,20 +378,22 @@ void RuntimeScheduler_Modern::updateRendering( // The delegate runs the spec's depth-bounded gather/broadcast loop // internally; this call site stays a single invocation per tick. if (resizeObserverDelegate_ != nullptr) { - // This delivers the observations to JS synchronously, so it is outside the - // error boundary of `executeTask`. Report the error without going through - // `handleTaskError`: we are already inside the "update the rendering" step, - // so clearing the queues here would drop the pending rendering updates this - // step is about to drain, and a throwing observer callback would abort the - // remaining steps below. + // Uncaught errors must unwind the observer pass before fatal handling can + // tear down delegates referenced by pending rendering callbacks. try { - resizeObserverDelegate_->runResizeObservations(runtime); + resizeObserverDelegate_->runResizeObservations( + runtime, [&](const std::function& callback) { + callback(); + performMicrotaskCheckpoint(runtime, rethrowMicrotaskError); + }); } catch (jsi::JSError& error) { - onTaskError_(runtime, error); + handleTaskError(runtime, error); + return; } catch (std::exception& ex) { jsi::JSError error( runtime, std::string("Non-JS exception: ") + ex.what()); - onTaskError_(runtime, error); + handleTaskError(runtime, error); + return; } } @@ -441,7 +452,8 @@ void RuntimeScheduler_Modern::executeTask( * Iterates on \c drainMicrotasks until it completes or hits the retries bound. */ void RuntimeScheduler_Modern::performMicrotaskCheckpoint( - jsi::Runtime& runtime) { + jsi::Runtime& runtime, + const RuntimeSchedulerTaskErrorHandler& onMicrotaskError) { if (performingMicrotaskCheckpoint_) { return; } @@ -465,11 +477,11 @@ void RuntimeScheduler_Modern::performMicrotaskCheckpoint( break; } } catch (jsi::JSError& error) { - handleTaskError(runtime, error); + onMicrotaskError(runtime, error); } catch (std::exception& ex) { jsi::JSError error( runtime, std::string("Non-JS exception: ") + ex.what()); - handleTaskError(runtime, error); + onMicrotaskError(runtime, error); } retries++; } diff --git a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeScheduler_Modern.h b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeScheduler_Modern.h index 9054157d3b9c..2cb40c78d8e5 100644 --- a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeScheduler_Modern.h +++ b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeScheduler_Modern.h @@ -203,7 +203,7 @@ class RuntimeScheduler_Modern final : public RuntimeSchedulerBase { void clearQueues(); bool performingMicrotaskCheckpoint_{false}; - void performMicrotaskCheckpoint(jsi::Runtime &runtime); + void performMicrotaskCheckpoint(jsi::Runtime &runtime, const RuntimeSchedulerTaskErrorHandler &onMicrotaskError); void reportLongTasks(const Task &task, HighResTimeStamp startTime, HighResTimeStamp endTime); diff --git a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/tests/RuntimeSchedulerTest.cpp b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/tests/RuntimeSchedulerTest.cpp index 5d1d3499804d..9534fa2968fb 100644 --- a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/tests/RuntimeSchedulerTest.cpp +++ b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/tests/RuntimeSchedulerTest.cpp @@ -19,9 +19,11 @@ #include #include #include +#include #include #include #include +#include #include "StubClock.h" #include "StubErrorUtils.h" @@ -111,6 +113,20 @@ class RuntimeSchedulerTest : public testing::TestWithParam { }); } + void enqueueMicrotask(std::function callback) { + auto microtask = jsi::Function::createFromHostFunction( + *runtime_, + jsi::PropNameID::forAscii(*runtime_, "testMicrotask"), + 0, + [callback = std::move(callback)]( + jsi::Runtime& runtime, const jsi::Value&, const jsi::Value*, size_t) + -> jsi::Value { + callback(runtime); + return jsi::Value::undefined(); + }); + runtime_->queueMicrotask(microtask); + } + uint hostFunctionCallCount_{}; std::unique_ptr runtime_; @@ -1499,7 +1515,9 @@ TEST_P(RuntimeSchedulerTest, reportsLongTasksWithYielding) { class StubResizeObserverDelegate : public RuntimeSchedulerResizeObserverDelegate { public: - void runResizeObservations(jsi::Runtime& runtime) override { + void runResizeObservations( + jsi::Runtime& runtime, + const CallbackInvoker& invokeCallback) override { callCount++; lastRuntime = &runtime; @@ -1511,7 +1529,7 @@ class StubResizeObserverDelegate OnScopeExit onExit([this]() { concurrentInvocationCount--; }); if (onRunResizeObservations != nullptr) { - onRunResizeObservations(runtime); + invokeCallback([&]() { onRunResizeObservations(runtime); }); } } @@ -1849,7 +1867,78 @@ TEST_P(RuntimeSchedulerTest, resizeObservationsSchedulingWorkDoesNotReenter) { EXPECT_EQ(secondResizeObservationsPosition, 4); } -TEST_P(RuntimeSchedulerTest, errorInResizeObservationsDoesNotStopUpdate) { +TEST_P( + RuntimeSchedulerTest, + resizeObserverMicrotasksRunBeforeRenderingUpdates) { + if (!GetParam()) { + return; + } + + std::vector events; + StubResizeObserverDelegate resizeObserverDelegate; + resizeObserverDelegate.onRunResizeObservations = [&](jsi::Runtime&) { + events.emplace_back("callback:start"); + enqueueMicrotask([&](jsi::Runtime&) { events.emplace_back("microtask"); }); + events.emplace_back("callback:end"); + }; + runtimeScheduler_->setResizeObserverDelegate(&resizeObserverDelegate); + runtimeScheduler_->scheduleTask( + SchedulerPriority::NormalPriority, [&](jsi::Runtime&) { + events.emplace_back("task"); + runtimeScheduler_->scheduleRenderingUpdate( + 0, [&]() { events.emplace_back("rendering update"); }); + }); + + stubQueue_->tick(); + + const std::vector expected{ + "task", + "callback:start", + "callback:end", + "microtask", + "rendering update"}; + EXPECT_EQ(events, expected); + EXPECT_EQ(stubQueue_->size(), 0); +} + +TEST_P(RuntimeSchedulerTest, fatalResizeObserverMicrotasksDiscardPendingWork) { + if (!GetParam()) { + return; + } + + std::vector events; + StubResizeObserverDelegate resizeObserverDelegate; + resizeObserverDelegate.onRunResizeObservations = [&](jsi::Runtime&) { + if (resizeObserverDelegate.callCount > 1) { + return; + } + events.emplace_back("callback"); + enqueueMicrotask([&](jsi::Runtime& runtime) { + events.emplace_back("throwing microtask"); + throw jsi::JSError(runtime, "ResizeObserver microtask error"); + }); + enqueueMicrotask( + [&](jsi::Runtime&) { events.emplace_back("later microtask"); }); + runtimeScheduler_->scheduleTask( + SchedulerPriority::NormalPriority, + [&](jsi::Runtime&) { events.emplace_back("later task"); }); + }; + runtimeScheduler_->setResizeObserverDelegate(&resizeObserverDelegate); + runtimeScheduler_->scheduleTask( + SchedulerPriority::NormalPriority, [&](jsi::Runtime&) { + runtimeScheduler_->scheduleRenderingUpdate( + 0, [&]() { events.emplace_back("rendering update"); }); + }); + + stubQueue_->tick(); + + const std::vector expected{"callback", "throwing microtask"}; + EXPECT_EQ(events, expected); + EXPECT_EQ(stubErrorUtils_->getReportFatalCallCount(), 1); + EXPECT_EQ(stubQueue_->size(), 0); +} + +TEST_P(RuntimeSchedulerTest, fatalErrorInResizeObservationsStopsRendering) { // Only for event loop if (!GetParam()) { return; @@ -1875,15 +1964,11 @@ TEST_P(RuntimeSchedulerTest, errorInResizeObservationsDoesNotStopUpdate) { stubQueue_->tick(); - // Delivering observations to JS synchronously happens outside the error - // boundary of the task, so the step handles the error itself and carries on. - // In particular the error must not be routed through `handleTaskError`: - // that clears the pending rendering updates this same step is about to - // drain, and `didRunRenderingUpdate` below would be false. + // Fatal handling can destroy delegates; no later rendering phase may run. EXPECT_EQ(stubErrorUtils_->getReportFatalCallCount(), 1); EXPECT_EQ(resizeObserverDelegate.callCount, 1); - EXPECT_EQ(intersectionObserverDelegate.callCount, 1); - EXPECT_TRUE(didRunRenderingUpdate); + EXPECT_EQ(intersectionObserverDelegate.callCount, 0); + EXPECT_FALSE(didRunRenderingUpdate); EXPECT_EQ(stubQueue_->size(), 0); } diff --git a/packages/react-native/ReactCommon/react/renderer/scheduler/tests/SchedulerDelegateInvalidationTest.cpp b/packages/react-native/ReactCommon/react/renderer/scheduler/tests/SchedulerDelegateInvalidationTest.cpp index 9005250d6063..cb48e66836d0 100644 --- a/packages/react-native/ReactCommon/react/renderer/scheduler/tests/SchedulerDelegateInvalidationTest.cpp +++ b/packages/react-native/ReactCommon/react/renderer/scheduler/tests/SchedulerDelegateInvalidationTest.cpp @@ -279,7 +279,9 @@ class SchedulerDelegateInvalidationTest : public ::testing::Test { if (scheduler_) { scheduler_->setDelegate(nullptr); } - delegate_.reset(); + if (!retainDelegateForAssertions_) { + delegate_.reset(); + } }; runtimeScheduler_ = std::make_shared( @@ -400,6 +402,59 @@ class SchedulerDelegateInvalidationTest : public ::testing::Test { [this](jsi::Runtime& /*runtime*/) { postErrorTaskRan_ = true; }); } + void verifyResizeObserverFatalCleanup(bool fromMicrotask) { + class ThrowingResizeObserverDelegate final + : public RuntimeSchedulerResizeObserverDelegate { + public: + explicit ThrowingResizeObserverDelegate(bool fromMicrotask) + : fromMicrotask_(fromMicrotask) {} + + void runResizeObservations( + jsi::Runtime& runtime, + const CallbackInvoker& invokeCallback) override { + invokeCallback([&]() { + if (!fromMicrotask_) { + throw jsi::JSError( + runtime, "simulated fatal observer notification"); + } + auto callback = jsi::Function::createFromHostFunction( + runtime, + jsi::PropNameID::forAscii(runtime, "throwObserverMicrotask"), + 0, + throwObserverMicrotask); + runtime.queueMicrotask(callback); + }); + } + + private: + [[noreturn]] static jsi::Value throwObserverMicrotask( + jsi::Runtime& runtime, + const jsi::Value& /*unused*/, + const jsi::Value* /*unused*/, + size_t /*unused*/) { + throw jsi::JSError(runtime, "simulated fatal observer microtask"); + } + + bool fromMicrotask_; + } resizeObserverDelegate(fromMicrotask); + + setUp(); + // Keep the detached delegate alive to detect stale calls without invoking + // UB. + retainDelegateForAssertions_ = true; + runtimeScheduler_->setResizeObserverDelegate(&resizeObserverDelegate); + scheduler_->uiManagerDidFinishTransaction(coordinator_, false); + runtimeScheduler_->scheduleWork([](jsi::Runtime&) {}); + schedulePostErrorTask(); + executorQueue_->flush(); + + EXPECT_TRUE(jsThrowObserved_); + EXPECT_EQ(scheduler_->getDelegate(), nullptr); + EXPECT_EQ(delegate_->shouldRenderTransactionsCount(), 0); + EXPECT_FALSE(postErrorTaskRan_); + runtimeScheduler_->setResizeObserverDelegate(nullptr); + } + std::unique_ptr runtime_; std::unique_ptr executorQueue_; std::shared_ptr runtimeScheduler_; @@ -411,6 +466,7 @@ class SchedulerDelegateInvalidationTest : public ::testing::Test { std::shared_ptr rootShadowNode_; bool jsThrowObserved_{false}; bool postErrorTaskRan_{false}; + bool retainDelegateForAssertions_{false}; }; } // namespace @@ -456,6 +512,18 @@ TEST_F( // before running onTaskError, so by (d) there is no stale delegate lambda // left to drain. The post-error task is dropped by the same clearing. // --------------------------------------------------------------------------- +TEST_F( + SchedulerDelegateInvalidationTest, + ResizeObserverMicrotaskFatalErrorDiscardsStaleRenderingUpdates) { + verifyResizeObserverFatalCleanup(true); +} + +TEST_F( + SchedulerDelegateInvalidationTest, + ResizeObserverNotificationFatalErrorDiscardsStaleRenderingUpdates) { + verifyResizeObserverFatalCleanup(false); +} + TEST_F(SchedulerDelegateInvalidationTest, JSThrowInitiatedTeardownIsSafe) { setUp(); diff --git a/packages/react-native/src/private/webapis/resizeobserver/__docs__/README.md b/packages/react-native/src/private/webapis/resizeobserver/__docs__/README.md index 097fc5cd569f..85b21042e05b 100644 --- a/packages/react-native/src/private/webapis/resizeobserver/__docs__/README.md +++ b/packages/react-native/src/private/webapis/resizeobserver/__docs__/README.md @@ -25,7 +25,27 @@ dedicated step in the Event Loop (as specified in the Web spec, via `RuntimeSchedulerResizeObserverDelegate`) then runs resize observations against the latest committed tree and notifies JavaScript when there are pending entries. JavaScript pulls those entries via `takeRecords` and dispatches them to -the right observers. +one observer at a time. The manager passes each notification to the scheduler's +callback invoker. The invoker calls it synchronously and performs callback +cleanup, including a microtask checkpoint, before returning. This matches the +[Web IDL callback invocation boundary](https://webidl.spec.whatwg.org/#invoke-a-callback-function): +the next observer or gather round runs only after that invocation completes. +Microtasks queued by a callback, including promise reactions and nested jobs, +therefore run before that rendering step mounts its updates. + +The callback invoker belongs to the rendering step, is synchronous, and must not +be retained beyond `runResizeObservations`. The manager does not receive a raw +microtask-draining capability. Ordinary synchronous native callbacks nested +inside author JavaScript do not perform a checkpoint. Nested synchronous +scheduler accesses execute only the callback; the outer event loop tick performs +its checkpoint and rendering phases after the callback returns. Ordinary +observer callback exceptions are caught and reported by the JavaScript +dispatcher, without aborting the broadcast. Uncaught checkpoint or notification +errors follow React Native's fatal-error policy: the observer/checkpoint stack +unwinds, queued tasks and rendering updates are cleared before the fatal handler +can tear down delegates, and the rendering step stops. This intentionally +preserves native teardown safety rather than applying the browser's nonfatal +error semantics to uncaught runtime failures. Unlike layout events (`onLayout`), `ResizeObserver` lets callers choose which box to observe (`content-box`, `border-box`, or `device-pixel-content-box`) and diff --git a/packages/react-native/src/private/webapis/resizeobserver/__tests__/ResizeObserver-itest.js b/packages/react-native/src/private/webapis/resizeobserver/__tests__/ResizeObserver-itest.js index 929cb39d0a5d..d43bb25277fe 100644 --- a/packages/react-native/src/private/webapis/resizeobserver/__tests__/ResizeObserver-itest.js +++ b/packages/react-native/src/private/webapis/resizeobserver/__tests__/ResizeObserver-itest.js @@ -1982,6 +1982,440 @@ describe('ResizeObserver', () => { expect(events).toEqual(['callback', 'task']); }); + it('should drain callback microtasks without requiring another task', () => { + const nodeRef = createRef(); + const root = Fantom.createRoot(); + const events: Array = []; + + Fantom.runTask(() => { + root.render(); + }); + + Fantom.runTask(() => { + observer = new ResizeObserver(async () => { + events.push('callback:start'); + queueMicrotask(() => { + events.push('microtask'); + queueMicrotask(() => events.push('nested microtask')); + }); + const reaction = Promise.resolve().then(() => { + events.push('promise reaction'); + }); + events.push('callback:end'); + await Promise.resolve(); + events.push('await continuation'); + await reaction; + }); + observer.observe(nullthrows(nodeRef.current)); + }); + + expect(events).toEqual([ + 'callback:start', + 'callback:end', + 'microtask', + 'promise reaction', + 'await continuation', + 'nested microtask', + ]); + }); + + it('should drain microtasks between observer callbacks in the same broadcast', () => { + const nodeRef = createRef(); + const root = Fantom.createRoot(); + const events: Array = []; + + Fantom.runTask(() => { + root.render(); + }); + + observer = new ResizeObserver(() => { + events.push('first callback'); + queueMicrotask(() => events.push('microtask')); + return Promise.resolve().then(() => { + events.push('promise reaction'); + }); + }); + const secondObserver = new ResizeObserver(() => { + events.push('second callback'); + }); + + try { + Fantom.runTask(() => { + const node = nullthrows(nodeRef.current); + observer.observe(node); + secondObserver.observe(node); + Fantom.scheduleTask(() => { + events.push('task'); + }); + }); + + expect(events).toEqual([ + 'first callback', + 'microtask', + 'promise reaction', + 'second callback', + 'task', + ]); + } finally { + Fantom.runTask(() => secondObserver.disconnect()); + } + }); + + it('should not drain microtasks inside a synchronous measure callback', () => { + const nodeRef = createRef(); + const root = Fantom.createRoot(); + const events: Array = []; + Fantom.runTask(() => { + root.render(); + }); + + Fantom.runTask(() => { + events.push('task:start'); + queueMicrotask(() => events.push('task microtask')); + nullthrows(nodeRef.current).measure(() => { + events.push('measure callback'); + queueMicrotask(() => events.push('measure microtask')); + }); + events.push('task:end'); + }); + + expect(events).toEqual([ + 'task:start', + 'measure callback', + 'task:end', + 'task microtask', + 'measure microtask', + ]); + }); + + it('should finish nested native callbacks and the current microtask before draining more jobs', () => { + const nodeRef = createRef(); + const root = Fantom.createRoot(); + const events: Array = []; + Fantom.runTask(() => { + root.render(); + }); + const node = nullthrows(nodeRef.current); + + observer = new ResizeObserver(() => { + events.push('observer:start'); + queueMicrotask(() => { + events.push('first microtask:start'); + node.measure(() => { + events.push('microtask measure callback'); + queueMicrotask(() => events.push('nested microtask')); + }); + events.push('first microtask:end'); + }); + node.measure(() => { + events.push('observer measure callback'); + queueMicrotask(() => events.push('second microtask')); + }); + events.push('observer:end'); + }); + const secondObserver = new ResizeObserver(() => { + events.push('second observer'); + }); + + try { + Fantom.runTask(() => { + observer.observe(node); + secondObserver.observe(node); + }); + expect(events).toEqual([ + 'observer:start', + 'observer measure callback', + 'observer:end', + 'first microtask:start', + 'microtask measure callback', + 'first microtask:end', + 'second microtask', + 'nested microtask', + 'second observer', + ]); + } finally { + Fantom.runTask(() => secondObserver.disconnect()); + } + }); + + it('should let a microtask disconnect a later observer before its callback', () => { + const nodeRef = createRef(); + const root = Fantom.createRoot(); + const events: Array = []; + Fantom.runTask(() => { + root.render(); + }); + + observer = new ResizeObserver(() => { + events.push('first observer'); + queueMicrotask(() => { + events.push('disconnect'); + secondObserver.disconnect(); + }); + }); + const secondObserver = new ResizeObserver(() => { + events.push('second observer'); + }); + try { + Fantom.runTask(() => { + const node = nullthrows(nodeRef.current); + observer.observe(node); + secondObserver.observe(node); + }); + expect(events).toEqual(['first observer', 'disconnect']); + } finally { + Fantom.runTask(() => secondObserver.disconnect()); + } + }); + + it('should retain a later observer target across removal and garbage collection in a checkpoint', () => { + const firstRef = createRef(); + const removedRef = createRef(); + const remainingRef = createRef(); + const root = Fantom.createRoot(); + const events: Array = []; + Fantom.runTask(() => { + root.render( + <> + + + + , + ); + }); + let removedTarget: ?HostInstance = nullthrows(removedRef.current); + let weakTarget: ?WeakRef = null; + let deliveredTarget: ?HostInstance = null; + observer = new ResizeObserver(entries => { + if (entries[0].contentRect.width === 0) { + events.push('first observer'); + secondObserver.unobserve(nullthrows(removedTarget)); + removedTarget = null; + queueMicrotask(() => { + global.gc(); + events.push('gc'); + }); + } + }); + const secondObserver = new ResizeObserver(entries => { + if (entries[0].contentRect.width === 0) { + events.push('second observer'); + expect(entries).toHaveLength(1); + deliveredTarget = entries[0].target; + } + }); + + try { + Fantom.runTask(() => { + weakTarget = new WeakRef(nullthrows(removedTarget)); + observer.observe(nullthrows(firstRef.current)); + secondObserver.observe(nullthrows(removedTarget)); + secondObserver.observe(nullthrows(remainingRef.current)); + }); + Fantom.runTask(() => { + root.render( + , + ); + }); + expect(events).toEqual(['first observer', 'gc', 'second observer']); + Fantom.runTask(() => { + expect(deliveredTarget).toBe( + nullthrows(nullthrows(weakTarget).deref()), + ); + }); + expect(nullthrows(deliveredTarget).isConnected).toBe(false); + } finally { + Fantom.runTask(() => secondObserver.disconnect()); + } + }); + + it('should retain fatal cleanup for an uncaught observer microtask error', () => { + const nodeRef = createRef(); + const root = Fantom.createRoot(); + const events: Array = []; + Fantom.runTask(() => { + root.render( + , + ); + }); + + observer = new ResizeObserver(entries => { + if (entries[0].contentRect.width === 200) { + events.push('first observer'); + queueMicrotask(() => { + events.push('throwing microtask'); + throw new Error('resize microtask failed'); + }); + queueMicrotask(() => events.push('later microtask')); + Fantom.scheduleTask(() => { + events.push('later task'); + }); + } + }); + const secondObserver = new ResizeObserver(entries => { + if (entries[0].contentRect.width === 200) { + events.push('second observer'); + } + }); + + try { + Fantom.runTask(() => { + const node = nullthrows(nodeRef.current); + observer.observe(node); + secondObserver.observe(node); + }); + expect(() => { + Fantom.runTask(() => { + root.render( + , + ); + }); + }).toThrow('resize microtask failed'); + expect(events).toEqual(['first observer', 'throwing microtask']); + expect( + root + .getRenderedOutput({ + includeLayoutMetrics: true, + props: ['layoutMetrics-frame'], + }) + .toJSX(), + ).toEqual( + , + ); + } finally { + Fantom.runTask(() => secondObserver.disconnect()); + } + }); + + it('should run callback microtasks before mounting the reported resize', () => { + const nodeRef = createRef(); + const root = Fantom.createRoot(); + const events: Array<[string, React.Node]> = []; + const readMountedOutput = () => + root + .getRenderedOutput({ + includeLayoutMetrics: true, + props: ['layoutMetrics-frame'], + }) + .toJSX(); + + Fantom.runTask(() => { + root.render( + , + ); + }); + Fantom.runTask(() => { + observer = new ResizeObserver(entries => { + if (entries[0].contentRect.width !== 200) { + return; + } + events.push(['callback', readMountedOutput()]); + queueMicrotask(() => { + events.push(['microtask', readMountedOutput()]); + }); + Fantom.scheduleTask(() => { + events.push(['task', readMountedOutput()]); + }); + }); + observer.observe(nullthrows(nodeRef.current)); + }); + + Fantom.runTask(() => { + root.render( + , + ); + }); + + // Fantom exposes mounting, not a physical display's paint boundary. + expect(events).toEqual([ + [ + 'callback', + , + ], + [ + 'microtask', + , + ], + [ + 'task', + , + ], + ]); + expect(readMountedOutput()).toEqual( + , + ); + }); + + it('should gather a deeper target observed in a microtask before the next task', () => { + const parentRef = createRef(); + const childRef = createRef(); + const root = Fantom.createRoot(); + const events: Array = []; + + Fantom.runTask(() => { + root.render( + + + , + ); + }); + + Fantom.runTask(() => { + const parent = nullthrows(parentRef.current); + const child = nullthrows(childRef.current); + observer = new ResizeObserver(entries => { + if (entries[0].target === parent) { + events.push('parent callback'); + queueMicrotask(() => { + events.push('microtask'); + observer.observe(child); + }); + } else { + events.push('child callback'); + } + }); + observer.observe(parent); + Fantom.scheduleTask(() => { + events.push('task'); + }); + }); + + expect(events).toEqual([ + 'parent callback', + 'microtask', + 'child callback', + 'task', + ]); + }); + it('should let a callback read the committed layout it is reporting on', () => { const nodeRef = createRef(); const root = Fantom.createRoot(); @@ -2027,10 +2461,13 @@ describe('ResizeObserver', () => { }); const node = nullthrows(nodeRef.current); + const events: Array = []; const callback1: ResizeObserverMockCallback = jest.fn(() => { + events.push('throwing observer'); + queueMicrotask(() => events.push('microtask')); throw new Error('observer 1 failed'); }); - const callback2 = jest.fn(); + const callback2 = jest.fn(() => events.push('second observer')); let observer1: ResizeObserver; let observer2: ResizeObserver; @@ -2049,6 +2486,11 @@ describe('ResizeObserver', () => { expect(callback1).toHaveBeenCalledTimes(1); expect(callback2).toHaveBeenCalledTimes(1); + expect(events).toEqual([ + 'throwing observer', + 'microtask', + 'second observer', + ]); expect(errorSpy).toHaveBeenCalled(); } finally { // $FlowExpectedError[cannot-write] @@ -2060,6 +2502,108 @@ describe('ResizeObserver', () => { } }); + it('should abort pending work when reporting an observer error throws', () => { + const firstRef = createRef(); + const childRef = createRef(); + const secondRef = createRef(); + const root = Fantom.createRoot(); + const events: Array = []; + + component Boxes(width: number) { + return ( + <> + + + + + + ); + } + + Fantom.runTask(() => root.render()); + const child = nullthrows(childRef.current); + observer = new ResizeObserver(entries => { + const entry = entries[0]; + if (entry.target === child) { + events.push('child delivery'); + return; + } + if (entry.contentRect.width !== 200) { + return; + } + events.push('first observer'); + queueMicrotask(() => { + events.push('microtask'); + observer.observe(child); + }); + Fantom.scheduleTask(() => { + events.push('later task'); + }); + throw new Error('observer callback failed'); + }); + const secondObserver = new ResizeObserver(entries => { + if (entries[0].contentRect.width === 200) { + events.push('second observer'); + } + }); + const originalConsoleError = console.error; + try { + Fantom.runTask(() => { + observer.observe(nullthrows(firstRef.current)); + secondObserver.observe(nullthrows(secondRef.current)); + }); + Object.defineProperty(console, 'error', { + value: () => { + throw new Error('observer error reporter failed'); + }, + }); + + expect(() => { + Fantom.runTask(() => root.render()); + }).toThrow('observer error reporter failed'); + expect(events).toEqual(['first observer']); + expect( + root + .getRenderedOutput({ + includeLayoutMetrics: true, + props: ['layoutMetrics-frame'], + }) + .toJSON(), + ).toEqual([ + { + type: 'View', + props: {'layoutMetrics-frame': '{x:0,y:0,width:100,height:50}'}, + children: [ + { + type: 'View', + props: {'layoutMetrics-frame': '{x:0,y:0,width:40,height:20}'}, + children: [], + }, + ], + }, + { + type: 'View', + props: {'layoutMetrics-frame': '{x:0,y:50,width:100,height:50}'}, + children: [], + }, + ]); + } finally { + Object.defineProperty(console, 'error', {value: originalConsoleError}); + Fantom.runTask(() => secondObserver.disconnect()); + } + }); + it('should keep delivering later resizes to an observer whose callback always throws', () => { const nodeRef = createRef(); const root = Fantom.createRoot(); @@ -2466,6 +3010,11 @@ describe('ResizeObserver', () => { setWidth(200); } events.push('afterSetState'); + if (entries[0].contentRect.width === 100) { + Fantom.scheduleTask(() => { + events.push('task before React render'); + }); + } }); Fantom.runTask(() => { @@ -2473,7 +3022,7 @@ describe('ResizeObserver', () => { observer.observe(node); }); - expect(callback).toHaveBeenCalledTimes(1); + expect(callback).toHaveBeenCalledTimes(2); expect(callback.mock.calls[0][0][0].contentRect.width).toBe(100); Fantom.runTask(() => {}); @@ -2487,6 +3036,10 @@ describe('ResizeObserver', () => { expect(events.indexOf('afterSetState')).toBeLessThan( events.indexOf('render:200'), ); + expect(events).toContain('task before React render'); + expect(events.indexOf('task before React render')).toBeLessThan( + events.indexOf('render:200'), + ); }); // Without `flushSync` the update is not visible to the callback that @@ -2557,18 +3110,17 @@ describe('ResizeObserver', () => { } }); + const renderCountBeforeObserving = renderCount; Fantom.runTask(() => { observer = new ResizeObserver(callback); observer.observe(node); }); - const renderCountAfterInitialDelivery = renderCount; - Fantom.runTask(() => {}); // One extra render for both updates, and one extra delivery reporting the // final size. - expect(renderCount).toBe(renderCountAfterInitialDelivery + 1); + expect(renderCount).toBe(renderCountBeforeObserving + 1); expect(callback).toHaveBeenCalledTimes(2); expectEntrySizes(callback.mock.lastCall[0][0], { contentWidth: 200, @@ -2621,6 +3173,7 @@ describe('ResizeObserver', () => { let observerA: ResizeObserver; let observerB: ResizeObserver; + const renderCountBeforeObserving = renderCount; Fantom.runTask(() => { observerA = new ResizeObserver(callbackA); observerB = new ResizeObserver(callbackB); @@ -2628,13 +3181,10 @@ describe('ResizeObserver', () => { observerB.observe(nodeB); }); - const renderCountAfterInitialDelivery = renderCount; - Fantom.runTask(() => {}); - // Both callbacks scheduled an update in the same tick, so React renders - // once for both. - expect(renderCount).toBe(renderCountAfterInitialDelivery + 1); + // Both callbacks schedule default-priority work before React renders. + expect(renderCount).toBe(renderCountBeforeObserving + 1); expect(callbackA).toHaveBeenCalledTimes(2); expect(callbackB).toHaveBeenCalledTimes(2); @@ -2687,7 +3237,7 @@ describe('ResizeObserver', () => { }); expect(callbackA).toHaveBeenCalledTimes(1); - expect(callbackB).toHaveBeenCalledTimes(1); + expect(callbackB).toHaveBeenCalledTimes(2); Fantom.runTask(() => { sizesRef.a = 110; @@ -2732,7 +3282,7 @@ describe('ResizeObserver', () => { const callbackA: ResizeObserverMockCallback = jest.fn(() => { deliveryOrder.push('A'); - sizesRef.b = 90; + sizesRef.b = sizesRef.a - 10; root.render(); }); const callbackB: ResizeObserverMockCallback = jest.fn(() => { @@ -2756,6 +3306,7 @@ describe('ResizeObserver', () => { }); expect(deliveryOrder).toEqual(['A', 'B']); + expect(callbackB.mock.lastCall[0][0].contentRect.width).toBe(100); Fantom.runTask(() => { observerA.disconnect(); @@ -2816,14 +3367,14 @@ describe('ResizeObserver', () => { }); expect(callbackA).toHaveBeenCalledTimes(1); - expect(callbackB).toHaveBeenCalledTimes(1); + expect(callbackB).toHaveBeenCalledTimes(2); Fantom.runTask(() => { sizesRef.a = 110; root.render(); }); - // A is notified once more for its own resize; B twice more as it follows A + // A is notified once more for its own resize; B once more as it follows A // up to 110. Then neither side has anything left to change, so the cycle // ends with both boxes at 110 rather than growing forever. expect(callbackA).toHaveBeenCalledTimes(2); @@ -3247,6 +3798,8 @@ describe('ResizeObserver', () => { for (const target of targets) { observer.observe(target); } + // Same-depth observations are delivered in a later rendering tick. + Fantom.scheduleTask(() => {}); } }); for (const target of targets) { diff --git a/scripts/cxx-api/api-snapshots/ReactAndroidFrameworksCxx.api b/scripts/cxx-api/api-snapshots/ReactAndroidFrameworksCxx.api index 3c35ec2ee54e..d1e5af7fc33a 100644 --- a/scripts/cxx-api/api-snapshots/ReactAndroidFrameworksCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAndroidFrameworksCxx.api @@ -3511,7 +3511,8 @@ class facebook::react::RuntimeSchedulerIntersectionObserverDelegate { } class facebook::react::RuntimeSchedulerResizeObserverDelegate { - public virtual void runResizeObservations(facebook::jsi::Runtime& runtime) = 0; + public using CallbackInvoker = std::function&)>; + public virtual void runResizeObservations(facebook::jsi::Runtime& runtime, const facebook::react::RuntimeSchedulerResizeObserverDelegate::CallbackInvoker& invokeCallback) = 0; public virtual ~RuntimeSchedulerResizeObserverDelegate() = default; } diff --git a/scripts/cxx-api/api-snapshots/ReactAppleFrameworksCxx.api b/scripts/cxx-api/api-snapshots/ReactAppleFrameworksCxx.api index b99068078b5b..6377be522a58 100644 --- a/scripts/cxx-api/api-snapshots/ReactAppleFrameworksCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAppleFrameworksCxx.api @@ -5694,7 +5694,8 @@ class facebook::react::RuntimeSchedulerIntersectionObserverDelegate { } class facebook::react::RuntimeSchedulerResizeObserverDelegate { - public virtual void runResizeObservations(facebook::jsi::Runtime& runtime) = 0; + public using CallbackInvoker = std::function&)>; + public virtual void runResizeObservations(facebook::jsi::Runtime& runtime, const facebook::react::RuntimeSchedulerResizeObserverDelegate::CallbackInvoker& invokeCallback) = 0; public virtual ~RuntimeSchedulerResizeObserverDelegate() = default; } diff --git a/scripts/cxx-api/api-snapshots/ReactCommonFrameworksCxx.api b/scripts/cxx-api/api-snapshots/ReactCommonFrameworksCxx.api index f5bab50c02f9..2d393d8344ea 100644 --- a/scripts/cxx-api/api-snapshots/ReactCommonFrameworksCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactCommonFrameworksCxx.api @@ -2107,7 +2107,8 @@ class facebook::react::RuntimeSchedulerIntersectionObserverDelegate { } class facebook::react::RuntimeSchedulerResizeObserverDelegate { - public virtual void runResizeObservations(facebook::jsi::Runtime& runtime) = 0; + public using CallbackInvoker = std::function&)>; + public virtual void runResizeObservations(facebook::jsi::Runtime& runtime, const facebook::react::RuntimeSchedulerResizeObserverDelegate::CallbackInvoker& invokeCallback) = 0; public virtual ~RuntimeSchedulerResizeObserverDelegate() = default; }