Skip to content

Clear RuntimeScheduler queues on error - #56892

Closed
sammy-SC wants to merge 2 commits into
react:mainfrom
sammy-SC:export-D105696366
Closed

sammy-SC wants to merge 2 commits into
react:mainfrom
sammy-SC:export-D105696366

Conversation

@sammy-SC

Copy link
Copy Markdown
Contributor

Summary:
changelog: [internal]

Add enableRuntimeSchedulerQueueClearingOnError and use it in RuntimeScheduler_Modern to clear pending tasks, pending rendering updates, and pending surface IDs before forwarding task or microtask errors to onTaskError. Update SchedulerDelegateInvalidationTest so enableSchedulerDelegateInvalidation can be disabled while the new queue-clearing flag is enabled, proving that stale rendering updates and queued follow-up tasks are dropped after an error.

Differential Revision: D105696366

sammy-SC added 2 commits May 19, 2026 08:02
Summary:
changelog: [internal]

this is a sensible change to follow the pattern established in the class and avoid passing in `this` into lambda.

Reviewed By: javache

Differential Revision: D105696365
Summary:
changelog: [internal]

Add `enableRuntimeSchedulerQueueClearingOnError` and use it in `RuntimeScheduler_Modern` to clear pending tasks, pending rendering updates, and pending surface IDs before forwarding task or microtask errors to `onTaskError`. Update `SchedulerDelegateInvalidationTest` so `enableSchedulerDelegateInvalidation` can be disabled while the new queue-clearing flag is enabled, proving that stale rendering updates and queued follow-up tasks are dropped after an error.

Differential Revision: D105696366
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. label May 19, 2026
@meta-codesync

meta-codesync Bot commented May 19, 2026

Copy link
Copy Markdown

@sammy-SC has exported this pull request. If you are a Meta employee, you can view the originating Diff in D105696366.

@meta-codesync meta-codesync Bot closed this in 9cbddbd May 20, 2026
@facebook-github-tools facebook-github-tools Bot added the Merged This PR has been merged. label May 20, 2026
@meta-codesync

meta-codesync Bot commented May 20, 2026

Copy link
Copy Markdown

This pull request has been merged in 9cbddbd.

Flewp added a commit to discord/react-native that referenced this pull request Aug 31, 2026
Flip the flag's defaultValue to true and regenerate the feature-flag
boilerplate with `yarn featureflags --update`. The config's own metadata
already declared expectedReleaseValue: true.

Both app-side providers inherit this default, so one change covers both
platforms: ReactNativeNewArchitectureFeatureFlagsDefaults (Android) and
ReactNativeFeatureFlagsOverridesOSSStable (iOS) neither override the flag,
and nothing in the monorepo sets it.

Why: deferred rendering-update lambdas queued from
Scheduler::uiManagerDidFinishTransaction and uiManagerDidDispatchCommand
capture SchedulerDelegate* by raw pointer. Under RuntimeScheduler_Modern the
lambda runs asynchronously, so a delegate destroyed before
updateRendering() drains pendingRenderingUpdates_ leaves the lambda
dereferencing freed memory -- a garbage vtable load and a wild branch.
Upstream added the guard in react#56678/react#56680 defaulted off; at that default it
never runs, which is the state this branch shipped in.

This restores protection that 0.81.4-discord carried unconditionally.
v0.86.0 was cut between upstream's guard (react#56680, 2026-05-04) and the
queue-clearing fix that superseded it (react#56892, 2026-05-20), so this tree has
the guard but not RuntimeScheduler_Modern::clearQueues.

Note for future upgrades: upstream removed both flag and guard in react#58138
because clearQueues closes the dominant path. Do not mirror that removal
here until react#56892 is backported, or this tree ends up with neither.
douglowder added a commit to expo/expo that referenced this pull request Oct 26, 2026
…#51880)

# Why

On iOS, a fatal JS error in a React Native scheduler task can freeze the
app instead of crashing it. The error never reaches the JS error
handlers, so expo-app-metrics does not record it, and expo-updates error
recovery does not run.

The root cause is in React Native. After a JS error in a task,
`RuntimeScheduler_Modern::clearQueues()` destroys the queued tasks while
it holds `schedulingMutex_`. A task destructor that schedules work then
calls `RuntimeScheduler_Modern::scheduleTask`, which waits for the same
non-recursive mutex, and the JS thread deadlocks. The main thread then
also waits for that mutex. This is reported upstream in
react/react-native#59204.

- react/react-native#56892 added the queue clearing behind a flag.
- react/react-native#58129 and #58132 made it the default in React
Native 0.88. `0.87-stable` does not have it.

In Expo, the destructors that schedule work are the `deinit`s of
`JavaScriptPromise` and `JavaScriptCallback`, which schedule the release
of their state (#47521).

# How

This PR is part of a stack:

1. #51880 [jsi] Fix an iOS deadlock when a JS error clears the scheduler
queues
2. #51881 [updates] Use millisecond log timestamps and correct error
recovery codes
3. #51882 [observe] Add an expo-updates integration
4. #51883 [updates] Add a log entry listener registry
5. #51884 [observe] Report expo-updates log entries as they are logged

This is PR 1. It is independent of the other PRs in the stack. The stack
depends on it, because the end-to-end test of expo-updates error
recovery on iOS freezes without it.

This PR is a workaround in expo-modules-jsi until a React Native release
fixes `clearQueues()`.

When a promise or callback `deinit` runs on the JS thread,
`Scheduler.scheduleRelease` no longer schedules from that thread:

- It adds the release to a batch that a lock protects.
- When the batch was empty, a private serial queue takes the batch and
schedules one task that runs all its releases. That thread waits for the
scheduler mutex until `clearQueues()` releases it, so no deadlock
happens. Because the queue is serial, at most one thread waits for the
mutex, and a batch needs one `scheduleTask` call instead of one for each
value.
- The batch is taken before its task is scheduled. So each release runs
after a `resolve` or `reject` that was queued before its value was
dropped, and the promise still finds its resolve and reject functions.
Releasing the state at once on the JS thread would break this order.

On other threads, and when the runtime has no host scheduler, the
behavior does not change.

Performance: a drop on the JS thread now adds the release to the batch,
and the release thread wakes to schedule it. In a benchmark that drops
about a million values per second on a runtime with a host scheduler, a
drop costs about 0.5–0.8 µs more than on `main` (see the Test Plan).
`DispatchQueue.global` was cheaper per drop, but it can start one thread
for each blocked block during `clearQueues()`.

The diff changes:

- `JavaScriptRuntimeScheduler.swift`: `scheduleRelease`, the batch, and
the release queue.
- `JavaScriptPromise.swift` and `JavaScriptCallback.swift`: `deinit`
uses `scheduleRelease`.
- `TestRuntimeScheduler.swift`: test dispatch functions. One acts like
React Native's mutex and counts a dispatch from the thread that holds
the lock, which would deadlock. One counts the dispatches.
- `SchedulerReentrancyTests.swift`: the new tests.
- `Benchmarks/ReleaseBenchmarks.swift`: benchmarks with a host
scheduler. The existing benchmarks use a standalone runtime, which never
takes the new path.
- A changeset for `expo-modules-jsi`.

# Test Plan

- `pnpm test:integration` in `packages/expo-modules-jsi`: 834 tests
pass. The new tests:
- A promise and a callback that are dropped on the JS thread while the
emulated scheduler lock is held do not dispatch from that thread, and
their state is released later. Both tests fail with the `deinit` code
from `main`.
- A promise that is resolved and then dropped on the JS thread still
settles, and 100 such promises all settle.
- 100 promises dropped together share release tasks. This test fails
when each release has its own task.
- `pnpm swift:lint` passes.
- Benchmarks, Release, Mac Catalyst, median ns per operation:

  | Case | `main` | this PR (two runs) |
  |---|---|---|
| `JavaScriptPromise(runtime)`: create deferred (standalone runtime) |
351.8 | 349.6, 359.8 |
| `JavaScriptCallback.decode()`: create and drop (standalone runtime) |
149.3 | 153.5, 155.1 |
  | host scheduler: promise create and drop | 716.3 | 1554.0, 1438.9 |
| host scheduler: promise create, resolve, and drop | 847.0 | 1494.2,
1353.3 |
  | host scheduler: callback decode and drop | 224.3 | 1220.4, 738.8 |

The other promise and callback benchmarks match `main` within noise. The
host scheduler cases drop their tasks, so they measure only the work on
the JS thread. They differ by up to 40% between runs.
- Release build of `apps/observe-tester` on the iPhone 17 simulator (iOS
26.5), with the integration from #51882. A sample throws a JS error in a
`setTimeout` callback soon after launch.
- Without a fix, the app froze. A `sample` of the process showed the JS
thread in `RuntimeScheduler_Modern::clearQueues()`, then
`JavaScriptPromise.deinit`, then
`RuntimeScheduler_Modern::scheduleTask`, waiting for the mutex.
- With an earlier version of this fix (one background dispatch per
release, before batching), the app crashed. On the next launch,
expo-app-metrics recorded the fatal `js.exception`, and the expo-updates
log had the error recovery entry. I did not run this end-to-end test
again with the batched version. The unit tests use an emulated lock, so
this manual run is the only check against the real scheduler.
- Android is not affected, because the change is Swift only.

# Screenshots

No UI change.

# Checklist

- [x] I added a changeset and followed [this short
guide](https://github.com/expo/expo/blob/main/CONTRIBUTING.md#-before-submitting)
- [ ] This diff will work correctly for `npx expo prebuild` & EAS Build
(eg: updated a module plugin).
- [ ] Conforms with the [Documentation Writing Style
Guide](https://github.com/expo/expo/blob/main/guides/Expo%20Documentation%20Writing%20Style%20Guide.md)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
tsapeta pushed a commit to expo/expo that referenced this pull request Oct 28, 2026
…#51880)

# Why

On iOS, a fatal JS error in a React Native scheduler task can freeze the
app instead of crashing it. The error never reaches the JS error
handlers, so expo-app-metrics does not record it, and expo-updates error
recovery does not run.

The root cause is in React Native. After a JS error in a task,
`RuntimeScheduler_Modern::clearQueues()` destroys the queued tasks while
it holds `schedulingMutex_`. A task destructor that schedules work then
calls `RuntimeScheduler_Modern::scheduleTask`, which waits for the same
non-recursive mutex, and the JS thread deadlocks. The main thread then
also waits for that mutex. This is reported upstream in
react/react-native#59204.

- react/react-native#56892 added the queue clearing behind a flag.
- react/react-native#58129 and #58132 made it the default in React
Native 0.88. `0.87-stable` does not have it.

In Expo, the destructors that schedule work are the `deinit`s of
`JavaScriptPromise` and `JavaScriptCallback`, which schedule the release
of their state (#47521).

# How

This PR is part of a stack:

1. #51880 [jsi] Fix an iOS deadlock when a JS error clears the scheduler
queues
2. #51881 [updates] Use millisecond log timestamps and correct error
recovery codes
3. #51882 [observe] Add an expo-updates integration
4. #51883 [updates] Add a log entry listener registry
5. #51884 [observe] Report expo-updates log entries as they are logged

This is PR 1. It is independent of the other PRs in the stack. The stack
depends on it, because the end-to-end test of expo-updates error
recovery on iOS freezes without it.

This PR is a workaround in expo-modules-jsi until a React Native release
fixes `clearQueues()`.

When a promise or callback `deinit` runs on the JS thread,
`Scheduler.scheduleRelease` no longer schedules from that thread:

- It adds the release to a batch that a lock protects.
- When the batch was empty, a private serial queue takes the batch and
schedules one task that runs all its releases. That thread waits for the
scheduler mutex until `clearQueues()` releases it, so no deadlock
happens. Because the queue is serial, at most one thread waits for the
mutex, and a batch needs one `scheduleTask` call instead of one for each
value.
- The batch is taken before its task is scheduled. So each release runs
after a `resolve` or `reject` that was queued before its value was
dropped, and the promise still finds its resolve and reject functions.
Releasing the state at once on the JS thread would break this order.

On other threads, and when the runtime has no host scheduler, the
behavior does not change.

Performance: a drop on the JS thread now adds the release to the batch,
and the release thread wakes to schedule it. In a benchmark that drops
about a million values per second on a runtime with a host scheduler, a
drop costs about 0.5–0.8 µs more than on `main` (see the Test Plan).
`DispatchQueue.global` was cheaper per drop, but it can start one thread
for each blocked block during `clearQueues()`.

The diff changes:

- `JavaScriptRuntimeScheduler.swift`: `scheduleRelease`, the batch, and
the release queue.
- `JavaScriptPromise.swift` and `JavaScriptCallback.swift`: `deinit`
uses `scheduleRelease`.
- `TestRuntimeScheduler.swift`: test dispatch functions. One acts like
React Native's mutex and counts a dispatch from the thread that holds
the lock, which would deadlock. One counts the dispatches.
- `SchedulerReentrancyTests.swift`: the new tests.
- `Benchmarks/ReleaseBenchmarks.swift`: benchmarks with a host
scheduler. The existing benchmarks use a standalone runtime, which never
takes the new path.
- A changeset for `expo-modules-jsi`.

# Test Plan

- `pnpm test:integration` in `packages/expo-modules-jsi`: 834 tests
pass. The new tests:
- A promise and a callback that are dropped on the JS thread while the
emulated scheduler lock is held do not dispatch from that thread, and
their state is released later. Both tests fail with the `deinit` code
from `main`.
- A promise that is resolved and then dropped on the JS thread still
settles, and 100 such promises all settle.
- 100 promises dropped together share release tasks. This test fails
when each release has its own task.
- `pnpm swift:lint` passes.
- Benchmarks, Release, Mac Catalyst, median ns per operation:

  | Case | `main` | this PR (two runs) |
  |---|---|---|
| `JavaScriptPromise(runtime)`: create deferred (standalone runtime) |
351.8 | 349.6, 359.8 |
| `JavaScriptCallback.decode()`: create and drop (standalone runtime) |
149.3 | 153.5, 155.1 |
  | host scheduler: promise create and drop | 716.3 | 1554.0, 1438.9 |
| host scheduler: promise create, resolve, and drop | 847.0 | 1494.2,
1353.3 |
  | host scheduler: callback decode and drop | 224.3 | 1220.4, 738.8 |

The other promise and callback benchmarks match `main` within noise. The
host scheduler cases drop their tasks, so they measure only the work on
the JS thread. They differ by up to 40% between runs.
- Release build of `apps/observe-tester` on the iPhone 17 simulator (iOS
26.5), with the integration from #51882. A sample throws a JS error in a
`setTimeout` callback soon after launch.
- Without a fix, the app froze. A `sample` of the process showed the JS
thread in `RuntimeScheduler_Modern::clearQueues()`, then
`JavaScriptPromise.deinit`, then
`RuntimeScheduler_Modern::scheduleTask`, waiting for the mutex.
- With an earlier version of this fix (one background dispatch per
release, before batching), the app crashed. On the next launch,
expo-app-metrics recorded the fatal `js.exception`, and the expo-updates
log had the error recovery entry. I did not run this end-to-end test
again with the batched version. The unit tests use an emulated lock, so
this manual run is the only check against the real scheduler.
- Android is not affected, because the change is Swift only.

# Screenshots

No UI change.

# Checklist

- [x] I added a changeset and followed [this short
guide](https://github.com/expo/expo/blob/main/CONTRIBUTING.md#-before-submitting)
- [ ] This diff will work correctly for `npx expo prebuild` & EAS Build
(eg: updated a module plugin).
- [ ] Conforms with the [Documentation Writing Style
Guide](https://github.com/expo/expo/blob/main/guides/Expo%20Documentation%20Writing%20Style%20Guide.md)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 5599fba)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. fb-exported Merged This PR has been merged. meta-exported p: Facebook Partner: Facebook Partner

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant