Skip to content

fix(Worklets): propagate lazy chunks to Worklet Runtimes in native code - #11764

Draft
tjzel wants to merge 8 commits into
mainfrom
@tjzel/worklets/lazy-chunk-propagation-memory
Draft

tjzel wants to merge 8 commits into
mainfrom
@tjzel/worklets/lazy-chunk-propagation-memory

Conversation

@tjzel

@tjzel tjzel commented Dec 4, 2026 •

Copy link
Copy Markdown
Collaborator

Note

This pull request was authored by AI on behalf of @tjzel.

Summary

Why

The Android Bundle Mode runtime tests run out of memory, and the app is killed during the lazy chunk tests. #11723 moved the kill to a later test but did not remove it.

The cause is in Worklets, not in the tests. In a development build with Bundle Mode, a lazy chunk that the React Native Runtime loads is also sent to the Worklet Runtimes. That propagation was done in JS, with a list of Worker Runtime ids that only ever grew. When the first chunk loaded, it was serialized once for every Worker Runtime created so far, including runtimes that were already destroyed. The Worklets runtime tests create hundreds of Worker Runtimes before they import a lazy chunk. Each copy of the 4.35 MB chunk stayed in native memory until the next garbage collection. An app that creates and destroys many Worker Runtimes has the same problem.

What

Lazy chunk propagation moves from JS to the native module. The native side keeps each loaded chunk once and evaluates it on the live Worklet Runtimes. Worker Runtimes created later get the kept chunks before their initializer runs. The JS registry of chunks and runtime ids is removed, together with the workaround that delayed the initializer of a runtime created after a chunk loaded. Behavior stays the same:

  1. Runtimes without a queue or without locking get only the chunks loaded before they were created.
  2. import() resolves when every runtime has evaluated the chunk.
  3. An aborted or destroyed runtime does not block import().

This only affects development builds with Bundle Mode.

How

The native runtime manager already tracks every live Worklet Runtime and already broadcasts in the same way, for custom serializables and for Fast Refresh updates. Propagation now uses this. While new runtimes are paused from becoming ready, the chunk is stored and the list of live runtimes is taken. The evaluation is then scheduled on each runtime's own queue, so the React Native thread never waits for a busy runtime. A shared completion object, held by every scheduled job, resolves the import() promise when the last job has run or has been dropped by an aborted or destroyed runtime.

A new Worker Runtime evaluates the stored chunks before its initializer runs. A chunk that the React Native Runtime loads while the initializer is still running would otherwise be missed, because it is sent only to runtimes that are already ready. So, just before the new runtime becomes ready, any such chunk is queued on it. Queuing never waits for the new runtime, so a timer that the initializer started cannot deadlock against the runtime that creates it.

The stored chunks and their evaluation live in a separate lazy bundle manager. The runtime manager only decides which runtimes are ready.

Like Fast Refresh updates, the native part is compiled only in debug native builds. A development bundle running on a release native build loads lazy chunks on the React Native Runtime only, as before #10961.

import() on the RN Runtime
  -> Metro loads the chunk on the RN Runtime, and JS fetches its source
  -> native: store the chunk once, take the live runtimes with a queue and locking
  -> schedule the evaluation on each runtime's queue
  -> last job done or dropped -> resolve or reject import()

createWorkletRuntime(...)
  -> native: evaluate the stored chunks -> initializer -> evaluate chunks that arrived meanwhile -> ready

Performance

Measured on an Android emulator (API 34), Debug build with Bundle Mode, sampling the app memory. Each case ran once, so there is no median or standard deviation. All runs include the per-test Worker Runtime cleanup from #11765.

The OOM reproduction runs the Worklets memory, runtimes and bundle mode core suites:

  1. Without a fix: the app was killed at the first lazy import, after the native heap reached 3182 MB (total PSS 3274 MB).
  2. With the first, JS-only version of this PR: 583 tests pass, with a peak native heap of 907 MB (total PSS 1050 MB).
  3. With the native version: 583 tests pass, with a peak native heap of 878 MB (total PSS 998 MB).

The full Worklets suite:

  1. Without a fix: 1114 tests pass, with a peak total PSS of 2628 MB.
  2. With the JS-only version: 1114 tests pass, with a peak of 1793 MB.
  3. With the native version: 1114 tests pass, with a peak of 1208 MB.

The memory suite alone raised the native heap to 2141 MB at the lazy import, and the runtimes suite alone to 1322 MB. These numbers match one 4.35 MB copy of the chunk for each Worker Runtime that the suites had created.

Alternatives

  1. Keep the propagation in JS, skip destroyed runtimes and serialize the chunk once. This was the first version of this PR, and it also removes the out-of-memory kill. It keeps a second, JS-side list of runtimes next to the native one, and needs the delayed-initializer workaround for runtimes created after a chunk loaded.
  2. Evaluate the chunk synchronously on every runtime from the React Native thread, as Fast Refresh updates do. The React Native thread would wait for every busy runtime, and could deadlock against a runtime that is waiting for runOnRNSync.

Test plan

The Worklets runtime tests pass in Debug builds with Bundle Mode, together with the per-test runtime cleanup from #11765:

  1. on an iOS simulator;
  2. on an Android emulator, where the out-of-memory reproduction also passes.

These runs cover:

  1. chunks on runtimes created before and after the load;
  2. runtimes without a queue or without locking;
  3. an aborted runtime;
  4. a runtime created inside a worklet.

New unit tests check that the JS side hands each chunk to the native module once, and resolves or rejects with the result it reports. No automated test checks the memory use. The C++ compiles in Debug and Release syntax checks. The Worklets unit tests, type check, JSI signature check and lint pass. A Release build was not run, because lazy chunks are a development-only feature.

Changelog

  • I added a changelog fragment with yarn changelog:add for each changed package, or this PR does not change react-native-reanimated or react-native-worklets.

Agent track

Details for agents

Cause (before this PR)

  • src/bundleMode/lazyBundles.native.ts on main: registerWorkerRuntimeForLazyBundles appends every Worker Runtime with a queue and locking to registry.workerRuntimeIds (a Synchronizable); the only removal was onDropped.
  • evaluateOnWorkletRuntimes mapped [UI, ...workerRuntimeIds] and per id called WorkletsModule.scheduleOnRuntimeWithId(runtimeId, createSerializable(() => { 'worklet'; evaluateLazyBundleJob(path, body, onEvaluated); }), ...). Each call serialized a new closure capturing body (strings are not cached), so one SerializableString of the chunk per id, freed only when the RN Runtime collected the refs.
  • Chunk: /runtime-tests/lazyImportModule.ts.bundle?platform=android&dev=true&lazy=true&modulesOnly=true&runModule=false&... = 4 350 094 bytes, 733 __d( modules.

Native change

  • WorkletRuntime/LazyBundleManager.{h,cpp} (debug only), a member of RuntimeManager:
    • store(path, std::string &&body): under its own mutex, replaces a chunk with the same path and appends {sequence, path, shared_ptr<const std::string> body}.
    • getBundlesAfter(sequence), loadBundlesAfter(runtime, sequence) (synchronous runSync evaluation, jsi::JSError → std::runtime_error("[Worklets] Failed to evaluate the lazy chunks on the <name> Runtime. Reason: ...")).
    • scheduleEvaluation(runtimes, bundle, onEvaluated): for each runtime with hasQueue() && isLockingEnabled(), runtime->schedule(...); every job holds a shared_ptr<LazyBundlePropagation>.
    • scheduleCatchUp(runtime, bundles): the same scheduling for one new runtime, without a completion callback (errors go through the debug schedule error reporting).
    • The job calls globalThis.__workletsEvaluateLazyBundle(path, body) (installed by installLazyBundleLoader; it dedupes by URL, records module ids and marks the chunk root for HMR).
  • WorkletRuntime/LazyBundlePropagation.{h,cpp} (debug only): its destructor resolves onEvaluated with undefined or the joined on the <name> Runtime: <message> failures. scheduleImpl drops jobs on an aborted runtime and ~WorkletRuntime calls queue_->abortPending, so dropped jobs also release it.
  • RuntimeManager:
    • propagateLazyBundle: lazyBundleManager_.store(...), then withRuntimeReadyPaused(getAllRuntimes()), then scheduleEvaluation. Storing before taking the list under the readiness lock is what makes the catch-up complete: a runtime marked ready before the list is taken is in it, otherwise its catch-up sees the chunk.
    • createWorkletRuntime: after init and loadModuleUpdates, lazyBundleManager_.loadBundlesAfter(runtime, 0) (before the initializer, nothing else runs on the runtime yet), then the initializer, then onRuntimeReady(runtimeId, runtime, loadedSequence).
    • onRuntimeReady(runtimeId, runtime, loadedSequence) (overload, documented in the header): in Debug, under runtimeReadyMutex_, scheduleCatchUp(runtime, getBundlesAfter(loadedSequence)) and markRuntimeReady; in Release it forwards to the two-argument overload. It never waits for the new runtime's lock (CodeRabbit findings: a lock inversion with runtimeReadyMutex_, and a cycle with a timer on the new runtime calling runOnRuntimeSync into the creating runtime).
    • All lazy chunk code is #ifndef NDEBUG, like propagateModuleUpdate. JS declares propagateLazyBundle? and resolves import() without propagation when it is missing.
  • WorkletRuntime/WorkletRuntime.h: hasQueue().
  • NativeModules/JSIWorkletsModuleProxy.cpp: propagateLazyBundle(const std::string &, std::string &&, const std::shared_ptr<SerializableRemoteFunction> &) (debug only).

JS change

  • src/bundleMode/lazyBundles.native.ts: removed LazyBundleRegistry, getLazyBundleRegistry, registerWorkerRuntimeForLazyBundles, getLoadedLazyBundles, evaluateLazyBundles, evaluateOnWorkletRuntime, evaluateLazyBundleJob and the LazyBundle type. evaluateOnWorkletRuntimes now wraps globalThis.__workletsModuleProxy.propagateLazyBundle(path, body, createSerializable(onEvaluated)) in a promise. installLazyBundleRegistrar takes only the registrar.
  • src/runtimes.native.ts: no lazy bundle list, no deferred initializer, no registration after creation.
  • src/initializers/initializers.native.ts, src/privateGlobals.d.ts: registry removed.
  • src/WorkletsModule/workletsModuleProxy.ts: propagateLazyBundle declared and added to InternalMethods.

Tests and checks

Run Version Result Peak PSS (MB) Peak native HeapAlloc (MB)
--only "memory,runtimes,bundle mode core" no fix killed at lazy import() 3274 3182
same JS-only fix (dc30adf) 583 passed 1050 907
same native (this PR) 583 passed 998 878
full worklets no fix 1114 passed 2628 2427
full worklets JS-only fix 1114 passed 1793 1638
full worklets native (this PR) 1114 passed 1208 1097

Isolation runs without a fix: bundle mode core 911/757, reload,bundle mode core 849/700, memory,bundle mode core 2299/2141, runtimes,bundle mode core 1481/1322 (PSS/native MB). A probe in the first lazy import() test found only runtime ids 2 and 3 alive while the native heap grew about 300 MB/s.

Job board: 70f5f426.

@tjzel
tjzel added this pull request to stack #11766 December 4, 2026 14:46
@tjzel tjzel changed the title @tjzel/worklets/lazy chunk propagation memory fix(Worklets): serialize a lazy chunk once and skip destroyed Worker Runtimes Dec 4, 2026
@coderabbitai

coderabbitai Bot commented Dec 4, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • Resume reviews
  • Trigger review

No actionable comments were generated in the recent review.

Walkthrough

Lazy-bundle propagation now sends fetched chunks to the native runtime manager instead of using a shared JavaScript registry and per-runtime evaluation jobs. The native manager stores chunks and schedules evaluation on eligible runtimes. New Worker Runtimes load stored chunks before becoming ready. Native tests cover successful propagation, errors, concurrent loads, and missing native support.

Possibly related PRs

Change: Bug fix

Merge Risk: Minimal · up to 72954

This change moves lazy chunk propagation to the native side in development builds with Bundle Mode. Each chunk is now sent once to live Worklet Runtimes, which removes the memory growth behind the Android out-of-memory kills. The deadlock concern during runtime creation was addressed by scheduling catch-up instead of running it synchronously. No open issues remain that should block merging.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title names the main change: lazy chunks are now propagated to Worklet Runtimes from native code. This matches the changeset, which moves lazy bundle storage and propagation from JS into a native …
Description check Passed The description states the problem (Android Bundle Mode OOM from JS propagation to destroyed runtimes), the native fix, the alternatives considered, and the test plan. It matches the changed files: la…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Title check

Explanation

The title names the main change: lazy chunks are now propagated to Worklet Runtimes from native code. This matches the changeset, which moves lazy bundle storage and propagation from JS into a native LazyBundleManager and RuntimeManager. The title is specific and uses the conventional fix(Worklets) prefix.

Full details: Description check

Explanation

The description states the problem (Android Bundle Mode OOM from JS propagation to destroyed runtimes), the native fix, the alternatives considered, and the test plan. It matches the changed files: lazyBundles.native.ts, RuntimeManager, LazyBundleManager, and the removed JS registry. It is detailed and on-topic.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 40a05dcd-2392-4f29-8a62-4a15b71bfc3a
Commits

Reviewing files that changed from the base of the PR and between 4bdc9f7 and 729547e.

Files selected for processing: 4

  • packages/react-native-worklets/Common/cpp/worklets/WorkletRuntime/LazyBundleManager.cpp
  • packages/react-native-worklets/Common/cpp/worklets/WorkletRuntime/LazyBundleManager.h
  • packages/react-native-worklets/Common/cpp/worklets/WorkletRuntime/RuntimeManager.cpp
  • packages/react-native-worklets/Common/cpp/worklets/WorkletRuntime/RuntimeManager.h

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 5 remain after this review.

@tjzel tjzel changed the title fix(Worklets): serialize a lazy chunk once and skip destroyed Worker Runtimes fix(Worklets): propagate lazy chunks to Worklet Runtimes in native code Dec 4, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments

Major 1
  1. Avoid the runtime-lock inversion during catch-up.
Review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 09bc9bc4-1f8b-4aa4-8dd4-6f1b113b7afc
Commits

Reviewing files that changed from the base of the PR and between dc30adf and 50faa72.

Files selected for processing: 11

  • packages/react-native-worklets/Common/cpp/worklets/NativeModules/JSIWorkletsModuleProxy.cpp
  • packages/react-native-worklets/Common/cpp/worklets/WorkletRuntime/RuntimeManager.cpp
  • packages/react-native-worklets/Common/cpp/worklets/WorkletRuntime/RuntimeManager.h
  • packages/react-native-worklets/Common/cpp/worklets/WorkletRuntime/WorkletRuntime.h
  • packages/react-native-worklets/__tests__/lazyBundles.native.test.ts
  • packages/react-native-worklets/changelog/lazy-chunk-propagation-memory.fix.md
  • packages/react-native-worklets/src/WorkletsModule/workletsModuleProxy.ts
  • packages/react-native-worklets/src/bundleMode/lazyBundles.native.ts
  • packages/react-native-worklets/src/initializers/initializers.native.ts
  • packages/react-native-worklets/src/privateGlobals.d.ts
  • packages/react-native-worklets/src/runtimes.native.ts
Files skipped from review as they are similar to previous changes: 1

  • packages/react-native-worklets/changelog/lazy-chunk-propagation-memory.fix.md

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 4 remain after this review.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments

Minor 1
  1. Creation can deadlock when a timer on the new runtime calls back into the creator.
Review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 5c0750ca-5141-4c36-805f-38aabf008ccc
Commits

Reviewing files that changed from the base of the PR and between 3d395a1 and 4bdc9f7.

Files selected for processing: 4

  • packages/react-native-worklets/Common/cpp/worklets/WorkletRuntime/LazyBundlePropagation.cpp
  • packages/react-native-worklets/Common/cpp/worklets/WorkletRuntime/LazyBundlePropagation.h
  • packages/react-native-worklets/Common/cpp/worklets/WorkletRuntime/RuntimeManager.cpp
  • packages/react-native-worklets/Common/cpp/worklets/WorkletRuntime/RuntimeManager.h

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 3 remain after this review.

This branch has not been deployed

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants