You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
fix(Worklets): propagate lazy chunks to Worklet Runtimes in native code - #11764
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:
Runtimes without a queue or without locking get only the chunks loaded before they were created.
import() resolves when every runtime has evaluated the chunk.
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:
Without a fix: the app was killed at the first lazy import, after the native heap reached 3182 MB (total PSS 3274 MB).
With the first, JS-only version of this PR: 583 tests pass, with a peak native heap of 907 MB (total PSS 1050 MB).
With the native version: 583 tests pass, with a peak native heap of 878 MB (total PSS 998 MB).
The full Worklets suite:
Without a fix: 1114 tests pass, with a peak total PSS of 2628 MB.
With the JS-only version: 1114 tests pass, with a peak of 1793 MB.
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
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.
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:
on an iOS simulator;
on an Android emulator, where the out-of-memory reproduction also passes.
These runs cover:
chunks on runtimes created before and after the load;
runtimes without a queue or without locking;
an aborted runtime;
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.
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.
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/WorkletsModule/workletsModuleProxy.ts: propagateLazyBundle declared and added to InternalMethods.
Tests and checks
__tests__/lazyBundles.native.test.ts (mocks serializable, runtimeKind, threads, getDevServer, fetch, __workletsModuleProxy): one native call per chunk with path and body, resolves on onEvaluated(), rejects with [Worklets] Could not evaluate the bundle "<path>" on the UI Runtime: boom, and concurrent imports of the same path share one propagation.
yarn run --top-level jest in packages/react-native-worklets: 239 passed (the new file also checks that import() resolves when propagateLazyBundle is missing). yarn workspace react-native-worklets type:check, lint:jsi-signatures, oxlint src: clean. clang++ -std=c++20 -fsyntax-only with and without -DNDEBUG for RuntimeManager.cpp and JSIWorkletsModuleProxy.cpp: clean. node_modules/.bin/clang-format applied.
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.
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
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.
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.
software-mansion/react-native-reanimated#10977: This PR documents runtime eligibility for lazy-chunk propagation. This change retains the queue and locking conditions while moving the implementation to native code.
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: 4
Check name
Status
Explanation
Title check
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
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
Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check
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.
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
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
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 4 remain after this review.
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 file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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:
import()resolves when every runtime has evaluated the chunk.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.
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,runtimesandbundle mode coresuites:The full Worklets suite:
The
memorysuite alone raised the native heap to 2141 MB at the lazy import, and theruntimessuite 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
runOnRNSync.Test plan
The Worklets runtime tests pass in Debug builds with Bundle Mode, together with the per-test runtime cleanup from #11765:
These runs cover:
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
yarn changelog:addfor each changed package, or this PR does not changereact-native-reanimatedorreact-native-worklets.Agent track
Details for agents
Cause (before this PR)
src/bundleMode/lazyBundles.native.tson main:registerWorkerRuntimeForLazyBundlesappends every Worker Runtime with a queue and locking toregistry.workerRuntimeIds(a Synchronizable); the only removal wasonDropped.evaluateOnWorkletRuntimesmapped[UI, ...workerRuntimeIds]and per id calledWorkletsModule.scheduleOnRuntimeWithId(runtimeId, createSerializable(() => { 'worklet'; evaluateLazyBundleJob(path, body, onEvaluated); }), ...). Each call serialized a new closure capturingbody(strings are not cached), so oneSerializableStringof the chunk per id, freed only when the RN Runtime collected the refs./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 ofRuntimeManager: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)(synchronousrunSyncevaluation,jsi::JSError→std::runtime_error("[Worklets] Failed to evaluate the lazy chunks on the <name> Runtime. Reason: ...")).scheduleEvaluation(runtimes, bundle, onEvaluated): for each runtime withhasQueue() && isLockingEnabled(),runtime->schedule(...); every job holds ashared_ptr<LazyBundlePropagation>.scheduleCatchUp(runtime, bundles): the same scheduling for one new runtime, without a completion callback (errors go through the debugscheduleerror reporting).globalThis.__workletsEvaluateLazyBundle(path, body)(installed byinstallLazyBundleLoader; it dedupes by URL, records module ids and marks the chunk root for HMR).WorkletRuntime/LazyBundlePropagation.{h,cpp}(debug only): its destructor resolvesonEvaluatedwithundefinedor the joinedon the <name> Runtime: <message>failures.scheduleImpldrops jobs on an aborted runtime and~WorkletRuntimecallsqueue_->abortPending, so dropped jobs also release it.RuntimeManager:propagateLazyBundle:lazyBundleManager_.store(...), thenwithRuntimeReadyPaused(getAllRuntimes()), thenscheduleEvaluation. 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: afterinitandloadModuleUpdates,lazyBundleManager_.loadBundlesAfter(runtime, 0)(before the initializer, nothing else runs on the runtime yet), then the initializer, thenonRuntimeReady(runtimeId, runtime, loadedSequence).onRuntimeReady(runtimeId, runtime, loadedSequence)(overload, documented in the header): in Debug, underruntimeReadyMutex_,scheduleCatchUp(runtime, getBundlesAfter(loadedSequence))andmarkRuntimeReady; in Release it forwards to the two-argument overload. It never waits for the new runtime's lock (CodeRabbit findings: a lock inversion withruntimeReadyMutex_, and a cycle with a timer on the new runtime callingrunOnRuntimeSyncinto the creating runtime).#ifndef NDEBUG, likepropagateModuleUpdate. JS declarespropagateLazyBundle?and resolvesimport()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: removedLazyBundleRegistry,getLazyBundleRegistry,registerWorkerRuntimeForLazyBundles,getLoadedLazyBundles,evaluateLazyBundles,evaluateOnWorkletRuntime,evaluateLazyBundleJoband theLazyBundletype.evaluateOnWorkletRuntimesnow wrapsglobalThis.__workletsModuleProxy.propagateLazyBundle(path, body, createSerializable(onEvaluated))in a promise.installLazyBundleRegistrartakes 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:propagateLazyBundledeclared and added toInternalMethods.Tests and checks
__tests__/lazyBundles.native.test.ts(mocksserializable,runtimeKind,threads,getDevServer,fetch,__workletsModuleProxy): one native call per chunk with path and body, resolves ononEvaluated(), rejects with[Worklets] Could not evaluate the bundle "<path>" on the UI Runtime: boom, and concurrent imports of the same path share one propagation.yarn run --top-level jestinpackages/react-native-worklets: 239 passed (the new file also checks thatimport()resolves whenpropagateLazyBundleis missing).yarn workspace react-native-worklets type:check,lint:jsi-signatures,oxlint src: clean.clang++ -std=c++20 -fsyntax-onlywith and without-DNDEBUGforRuntimeManager.cppandJSIWorkletsModuleProxy.cpp: clean.node_modules/.bin/clang-formatapplied.LazyBundleManager, scheduled catch-up), top of the stack incl. test(Worklets): create Worklet Runtimes per test and fail tests that leave one alive #11765 and test(Worklets): restore the lazy chunk and retained serialization coverage reduced for memory #11771, afterpod install: iOS--library workletspassed 1111, failed 0, skipped 5; Android--only "memory,runtimes,bundle mode core"passed 583, failed 0, peak PSS 1267 MB (with the larger fixtures restored by test(Worklets): restore the lazy chunk and retained serialization coverage reduced for memory #11771). Earlier, with the synchronous catch-up: full Androidworklets(incl. test(Worklets): restore the lazy chunk and retained serialization coverage reduced for memory #11771) passed 1114, failed 0, peak PSS 1264 MB.yarn workspace fabric-example runtime-tests --library worklets --platform ios: passed 1111, failed 0, skipped 5.Pixel_9_Agent_1(API 34, Debug, Bundle Mode, stack with test(Worklets): create Worklet Runtimes per test and fail tests that leave one alive #11765), samplerdumpsys meminfo com.fabricexample:--only "memory,runtimes,bundle mode core"lazy import()workletsworkletsworkletsIsolation runs without a fix:
bundle mode core911/757,reload,bundle mode core849/700,memory,bundle mode core2299/2141,runtimes,bundle mode core1481/1322 (PSS/native MB). A probe in the firstlazy import()test found only runtime ids 2 and 3 alive while the native heap grew about 300 MB/s.Job board: 70f5f426.