Skip to content

Commit 97b3c62

Browse files
authored
Drain ResizeObserver callback microtasks before rendering (#60436)
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 Pull Request resolved: #60436
1 parent ee2d411 commit 97b3c62

12 files changed

Lines changed: 839 additions & 69 deletions

File tree

‎packages/react-native/ReactCommon/react/renderer/observers/resize/ResizeObserverManager.cpp‎

Lines changed: 44 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -251,7 +251,9 @@ void ResizeObserverManager::shadowTreeDidCommit(
251251

252252
#pragma mark - RuntimeSchedulerResizeObserverDelegate
253253

254-
void ResizeObserverManager::runResizeObservations(jsi::Runtime& runtime) {
254+
void ResizeObserverManager::runResizeObservations(
255+
jsi::Runtime& runtime,
256+
const CallbackInvoker& invokeCallback) {
255257
TraceSection s{"ResizeObserverManager::runResizeObservations"};
256258

257259
// The broadcast below runs JS, which may commit synchronously and re-enter
@@ -288,8 +290,8 @@ void ResizeObserverManager::runResizeObservations(jsi::Runtime& runtime) {
288290
break;
289291
}
290292

291-
auto shallowest =
292-
broadcastActiveResizeObservations(runtime, gathered.activeObservations);
293+
auto shallowest = broadcastActiveResizeObservations(
294+
runtime, gathered.activeObservations, invokeCallback);
293295
if (!shallowest.has_value()) {
294296
break;
295297
}
@@ -299,7 +301,7 @@ void ResizeObserverManager::runResizeObservations(jsi::Runtime& runtime) {
299301

300302
// https://w3c.github.io/csswg-drafts/resize-observer/#deliver-resize-loop-error
301303
if (hasSkippedObservations) {
302-
notifyResizeObservers(runtime, true);
304+
invokeCallback([&]() { notifyResizeObservers(runtime, true); });
303305
}
304306
}
305307

@@ -425,7 +427,8 @@ ResizeObserverManager::gatherActiveResizeObservations(size_t depth) {
425427

426428
std::optional<size_t> ResizeObserverManager::broadcastActiveResizeObservations(
427429
jsi::Runtime& runtime,
428-
std::vector<ActiveObservation>& active) {
430+
std::vector<ActiveObservation>& active,
431+
const CallbackInvoker& invokeCallback) {
429432
TraceSection s{"ResizeObserverManager::broadcastActiveResizeObservations"};
430433

431434
if (active.empty() || notifyResizeObserversFunction_ == nullptr) {
@@ -445,41 +448,61 @@ std::optional<size_t> ResizeObserverManager::broadcastActiveResizeObservations(
445448
});
446449

447450
std::optional<size_t> shallowestDepth;
448-
{
449-
std::unique_lock lock(pendingEntriesMutex_);
450-
pendingEntries_.reserve(pendingEntries_.size() + active.size());
451-
for (auto& observation : active) {
452-
observation.observer->markAsReported(observation.result);
453-
shallowestDepth = shallowestDepth.has_value()
454-
? std::min(shallowestDepth.value(), observation.result.targetDepth)
455-
: observation.result.targetDepth;
456-
pendingEntries_.push_back(std::move(*observation.result.entry));
457-
}
451+
std::vector<ResizeObserverEntry> entries;
452+
// Instance handles are weak; root their JS identities across checkpoints.
453+
std::vector<jsi::Value> targetInstanceHandles;
454+
entries.reserve(active.size());
455+
targetInstanceHandles.reserve(active.size());
456+
for (auto& observation : active) {
457+
targetInstanceHandles.push_back(
458+
observation.result.entry->shadowNodeFamily->getInstanceHandle(runtime));
459+
observation.observer->markAsReported(observation.result);
460+
shallowestDepth = shallowestDepth.has_value()
461+
? std::min(shallowestDepth.value(), observation.result.targetDepth)
462+
: observation.result.targetDepth;
463+
entries.push_back(std::move(*observation.result.entry));
458464
}
459465

460-
if (!notifyResizeObservers(runtime, false)) {
461-
return std::nullopt;
466+
// Snapshot every entry before invoking JS, which can remove any observer.
467+
active.clear();
468+
auto entry = entries.begin();
469+
while (entry != entries.end() && notifyResizeObserversFunction_ != nullptr) {
470+
const auto observerId = entry->resizeObserverId;
471+
{
472+
std::unique_lock lock(pendingEntriesMutex_);
473+
do {
474+
pendingEntries_.push_back(std::move(*entry));
475+
++entry;
476+
} while (entry != entries.end() && entry->resizeObserverId == observerId);
477+
}
478+
479+
invokeCallback([&]() { notifyResizeObservers(runtime, false); });
462480
}
463481

464482
return shallowestDepth;
465483
}
466484

467-
bool ResizeObserverManager::notifyResizeObservers(
485+
void ResizeObserverManager::notifyResizeObservers(
468486
jsi::Runtime& runtime,
469487
bool hasResizeLoopError) {
470488
// Copy the callable: the notification runs JS, and a callback may
471489
// `disconnect()` the last observer, which clears the member while we are
472490
// still executing it.
473491
auto notifyResizeObserversFunction = notifyResizeObserversFunction_;
474492
if (notifyResizeObserversFunction == nullptr) {
475-
return false;
493+
return;
476494
}
477495

478496
// No lock may be held here. JS pulls the entries with `takeRecords` and the
479497
// callbacks it then invokes can re-enter `observe`/`unobserve`/`disconnect`,
480498
// or commit synchronously (which re-enters the commit hook on this thread).
481-
notifyResizeObserversFunction(runtime, hasResizeLoopError);
482-
return true;
499+
try {
500+
notifyResizeObserversFunction(runtime, hasResizeLoopError);
501+
} catch (...) {
502+
std::unique_lock lock(pendingEntriesMutex_);
503+
pendingEntries_.clear();
504+
throw;
505+
}
483506
}
484507

485508
} // namespace facebook::react

‎packages/react-native/ReactCommon/react/renderer/observers/resize/ResizeObserverManager.h‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ class ResizeObserverManager final : public UIManagerCommitHook, public RuntimeSc
5353

5454
#pragma mark - RuntimeSchedulerResizeObserverDelegate
5555

56-
void runResizeObservations(jsi::Runtime &runtime) override;
56+
void runResizeObservations(jsi::Runtime &runtime, const CallbackInvoker &invokeCallback) override;
5757

5858
#pragma mark - UIManagerCommitHook
5959

@@ -140,10 +140,11 @@ class ResizeObserverManager final : public UIManagerCommitHook, public RuntimeSc
140140
// was delivered.
141141
std::optional<size_t> broadcastActiveResizeObservations(
142142
jsi::Runtime &runtime,
143-
std::vector<ActiveObservation> &active);
143+
std::vector<ActiveObservation> &active,
144+
const CallbackInvoker &invokeCallback);
144145

145-
// Calls into JS. Returns false if there is nothing connected to notify.
146-
bool notifyResizeObservers(jsi::Runtime &runtime, bool hasResizeLoopError);
146+
// Calls into JS.
147+
void notifyResizeObservers(jsi::Runtime &runtime, bool hasResizeLoopError);
147148
};
148149

149150
} // namespace facebook::react

‎packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeSchedulerResizeObserverDelegate.h‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,14 +10,19 @@
1010
#include <react/cxxstableapi/FrameworksGuard.h>
1111

1212
#include <jsi/jsi.h>
13+
#include <functional>
1314

1415
namespace facebook::react {
1516

1617
class RuntimeSchedulerResizeObserverDelegate {
1718
public:
19+
using CallbackInvoker = std::function<void(const std::function<void()> &)>;
20+
1821
virtual ~RuntimeSchedulerResizeObserverDelegate() = default;
1922

20-
virtual void runResizeObservations(jsi::Runtime &runtime) = 0;
23+
// Invocations are synchronous and include callback cleanup. Do not retain
24+
// the invoker or use it before the previous author callback has returned.
25+
virtual void runResizeObservations(jsi::Runtime &runtime, const CallbackInvoker &invokeCallback) = 0;
2126
};
2227

2328
} // namespace facebook::react

‎packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeScheduler_Modern.cpp‎

Lines changed: 25 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,12 @@ int64_t durationToMilliseconds(HighResDuration duration) {
3030
return duration.toNanoseconds() / static_cast<int64_t>(1e6);
3131
}
3232

33+
[[noreturn]] void rethrowMicrotaskError(
34+
jsi::Runtime& /*unused*/,
35+
jsi::JSError& error) {
36+
throw error;
37+
}
38+
3339
} // namespace
3440

3541
#pragma mark - Public
@@ -334,7 +340,10 @@ void RuntimeScheduler_Modern::runEventLoopTick(
334340
executeTask(runtime, task, didUserCallbackTimeout);
335341

336342
// "Perform a microtask checkpoint" step.
337-
performMicrotaskCheckpoint(runtime);
343+
performMicrotaskCheckpoint(
344+
runtime, [this](jsi::Runtime& runtime, jsi::JSError& error) {
345+
handleTaskError(runtime, error);
346+
});
338347

339348
auto taskEndTime = now_();
340349
markYieldingOpportunity(taskEndTime);
@@ -369,20 +378,22 @@ void RuntimeScheduler_Modern::updateRendering(
369378
// The delegate runs the spec's depth-bounded gather/broadcast loop
370379
// internally; this call site stays a single invocation per tick.
371380
if (resizeObserverDelegate_ != nullptr) {
372-
// This delivers the observations to JS synchronously, so it is outside the
373-
// error boundary of `executeTask`. Report the error without going through
374-
// `handleTaskError`: we are already inside the "update the rendering" step,
375-
// so clearing the queues here would drop the pending rendering updates this
376-
// step is about to drain, and a throwing observer callback would abort the
377-
// remaining steps below.
381+
// Uncaught errors must unwind the observer pass before fatal handling can
382+
// tear down delegates referenced by pending rendering callbacks.
378383
try {
379-
resizeObserverDelegate_->runResizeObservations(runtime);
384+
resizeObserverDelegate_->runResizeObservations(
385+
runtime, [&](const std::function<void()>& callback) {
386+
callback();
387+
performMicrotaskCheckpoint(runtime, rethrowMicrotaskError);
388+
});
380389
} catch (jsi::JSError& error) {
381-
onTaskError_(runtime, error);
390+
handleTaskError(runtime, error);
391+
return;
382392
} catch (std::exception& ex) {
383393
jsi::JSError error(
384394
runtime, std::string("Non-JS exception: ") + ex.what());
385-
onTaskError_(runtime, error);
395+
handleTaskError(runtime, error);
396+
return;
386397
}
387398
}
388399

@@ -441,7 +452,8 @@ void RuntimeScheduler_Modern::executeTask(
441452
* Iterates on \c drainMicrotasks until it completes or hits the retries bound.
442453
*/
443454
void RuntimeScheduler_Modern::performMicrotaskCheckpoint(
444-
jsi::Runtime& runtime) {
455+
jsi::Runtime& runtime,
456+
const RuntimeSchedulerTaskErrorHandler& onMicrotaskError) {
445457
if (performingMicrotaskCheckpoint_) {
446458
return;
447459
}
@@ -465,11 +477,11 @@ void RuntimeScheduler_Modern::performMicrotaskCheckpoint(
465477
break;
466478
}
467479
} catch (jsi::JSError& error) {
468-
handleTaskError(runtime, error);
480+
onMicrotaskError(runtime, error);
469481
} catch (std::exception& ex) {
470482
jsi::JSError error(
471483
runtime, std::string("Non-JS exception: ") + ex.what());
472-
handleTaskError(runtime, error);
484+
onMicrotaskError(runtime, error);
473485
}
474486
retries++;
475487
}

‎packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeScheduler_Modern.h‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -203,7 +203,7 @@ class RuntimeScheduler_Modern final : public RuntimeSchedulerBase {
203203
void clearQueues();
204204

205205
bool performingMicrotaskCheckpoint_{false};
206-
void performMicrotaskCheckpoint(jsi::Runtime &runtime);
206+
void performMicrotaskCheckpoint(jsi::Runtime &runtime, const RuntimeSchedulerTaskErrorHandler &onMicrotaskError);
207207

208208
void reportLongTasks(const Task &task, HighResTimeStamp startTime, HighResTimeStamp endTime);
209209

0 commit comments

Comments
 (0)