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
test(Worklets): create Worklet Runtimes per test and fail tests that leave one alive - #11765
This pull request was authored by AI on behalf of @tjzel.
Summary
Why
The Worklets runtime tests shared a pool of Worker Runtimes across tests, and some tests created extra runtimes that stayed alive after the test ended. Nothing checked that a runtime was ever destroyed. In a development build with Bundle Mode each Worker Runtime evaluates the whole bundle, so a runtime that a test keeps alive costs a lot of memory, and on Android the suite ran out of memory. This PR makes the cleanup a guarantee that the test runner enforces.
Requires #11764, which fixes the lazy chunk memory growth that caused the out-of-memory kill. That fix is in the PR below this one in the stack.
What
The pool of shared Worker Runtimes is removed. Every test now gets new Worker Runtimes, and after each test the runner checks that every Worker Runtime the test created was destroyed. A runtime that is still alive fails the test and is reported by name.
The check found 14 leaked runtimes in the existing tests, which are fixed:
In ten tests, a worklet running on a runtime captured that same runtime. The runner now also collects garbage on each Worker Runtime that is still alive, which releases these runtimes.
One reload test kept a runtime in a module variable between tests. The two tests that used it are merged into one.
Three abort tests capture their own aborted runtime. An aborted runtime runs no more JS, so it can never collect its own garbage and stays alive forever. This is a product bug, reported in Aborted Worklet Runtime that captured itself is never destroyed #11763. The tests now capture the runtime id and use the *WithId functions, so they test the same behavior without the leak.
How
Before each test, the runner wraps runtime creation and records every Worker Runtime created during the test. Describe blocks request runtimes through useWorkletRuntimes, which assigns new runtimes before each test and clears the references after it. Tests can also call getWorkletRuntimes directly. After the test, even if its cleanup throws, the runner clears these references and collects garbage on the React Native Runtime, the UI Runtime and every recorded Worker Runtime that is still alive and has a queue. Garbage collection on a Worker Runtime is scheduled on its queue, so a busy runtime cannot block the run. Runtimes without a queue are only polled. The runner repeats this until all of them are destroyed, or for at most five seconds, and then fails the test for each runtime still alive.
The check only sees runtimes created on the React Native Runtime. A runtime created inside a worklet goes through its creator's module proxy and is not tracked. The one test that does this waits for its nested runtime on its own.
Performance
Measured on an Android emulator (API 34), Debug build with Bundle Mode, one full Worklets run with the fix from #11764, sampling every 3 seconds. Each case ran once, so there is no median or standard deviation. Peak total PSS was 2628 MB without the lazy chunk fix and 1208 MB with it, and memory at the end of the suite is about 1000 MB. Each run loop or networking test that creates a Worker Runtime still adds about 300 to 400 MB of native memory, which is freed after the test, so the peak now depends on the largest single test instead of on the whole suite.
The iOS Worklets run takes about 9 minutes, because each test creates its own runtimes.
Alternatives
Keep the pool and only add the leak check. Pool runtimes stay alive for the whole run, so their memory and the state left by earlier tests would remain.
Warn about leaked runtimes instead of failing. A warning is easy to miss, and a leak shows up later as an out-of-memory kill in an unrelated test.
Test plan
The Worklets runtime tests and the ReJest self-tests pass on an iOS simulator and the Worklets runtime tests pass on an Android emulator, in Debug builds with Bundle Mode, with no leaked runtimes. These runs used main ee3d2ca045, not the current base. The common app type check and lint pass.
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
Harness
New apps/common-app/runtime-tests/ReJest/TestRunner/WorkletRuntimeTracker.ts:
startTracking() wraps __workletsModuleProxy.createWorkletRuntime and records { runtimeId, name }.
createRuntimes(count, namePrefix) throws outside a test; names are <test name> #<i>.
stopTrackingAndFindAlive() restores the original, then loops: RN gc(), UI gc() via runOnUISync, RN gc(); filters with isRuntimeAlive; runs gc() on each alive runtime via runOnRuntimeSyncWithId (throws on aborted runtimes, caught); retries every 20 ms up to 5000 ms.
Removed ReJest/TestRunner/WorkletRuntimePool.ts, workletRuntimePool and getWorkletRuntimesFromPool.
TestSuiteBuilder.useWorkletRuntimes(count, assign) registers on the current describe; describe() sets parent.
TestRunner.runTestCase: startTracking(), then for each WorkletRuntimeUser in the parent chain (outermost first) assign(createRuntimes(...)) before beforeEach; after render(null): assign([]), reset the shared test runtime, stopTrackingAndFindAlive(), and push [leaked runtime] Worklet Runtime "<name>" (id <id>) is still alive after the test. per survivor.
RuntimeTestsApi.ts exports useWorkletRuntimes, getWorkletRuntimes, getSharedTestWorkletRuntime (used by runLoop/dispatchWorklet.ts).
Call sites
About 40 test files: describe-level const [a] = getWorkletRuntimesFromPool(n) became let a!: WorkletRuntime; useWorkletRuntimes(n, (runtimes) => { [a] = runtimes; }); in-test calls became getWorkletRuntimes(n).
Describe-level eager reads of a runtime (crashed buildTests with Cannot read property 'name' of undefined) became getters: createSerializable.test.tsx (getRuntimeName, and the Worker scheduleOnTarget lost its 'worklet' directive so it does not capture the runtime at describe time), serializableMapping.test.tsx and runtimes/weakRef.test.tsx (getRuntimeId).
synchronizable.test.tsx: module-level runtime with useSynchronizableTestRuntime() in each top-level describe.
retainingSerializableConcurrency.test.tsx: runRound(runtimes, ...); runtimes are created once per test, so cachedAcrossCalls still sees the same runtimes (with per-round runtimes it got 320 instead of 800).
reload/oldInstanceValues.test.tsx: run an old cached worklet on a new Worker Runtime with the same id and unpack an old Worker Runtime Remote Function as a guard on a new Worker Runtime with the same id merged into run an old cached worklet and unpack an old Worker Runtime Remote Function as a guard on a new Worker Runtime with the same id; module variable sameIdWorker removed.
runtimes/abortWorkletRuntime.test.ts: abort-reschedule uses scheduleOnRuntimeWithId, abort-sync-self uses runOnRuntimeSyncWithId, abort-self-queued uses runOnRuntimeAsyncWithId, all with a captured runtimeId. Cause: WorkletRuntimeHolder holds a strong shared_ptr<WorkletRuntime> (Common/cpp/worklets/Compat/Holders.h), scheduleImpl drops jobs after abort and runOnRuntimeSyncWithId throws for aborted runtimes (JSIWorkletsModuleProxy.cpp), so the self-reference is never collected. Issue Aborted Worklet Runtime that captured itself is never destroyed #11763.
iOS simulator, first run before the fixes: passed 1097, failed 15 (14 [leaked runtime] + the cachedAcrossCalls 320 vs 800).
After the per-runtime gc(): --only reload,memory,runtimes passed 563, failed 4 (3 abort, 1 reload).
Full worklets after the reload fix: passed 1108, failed 3 (the abort tests, run started before their fix); then --only runtimes: passed 220, failed 0. --library self-tests: passed 43, failed 0, skipped 2.
Review fixes: releaseWorkletRuntimes runs in finally; queued runtimes get gc() via runOnRuntimeAsyncWithId with one pending request per runtime; queueless runtimes are only polled. After them, iOS --only memory,runtimes,bundle mode core passed 583, and the full iOS worklets suite on the native fix(Worklets): propagate lazy chunks to Worklet Runtimes in native code #11764 passed 1111, failed 0, skipped 5; Android --only memory,runtimes,bundle mode core passed 583.
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
The runtime test framework replaces its cached runtime pool with per-test runtime creation and tracking. Test suites can declare runtime users, and the runner assigns them runtimes and reports any that remain alive during cleanup. Worklet tests use the new runtime APIs. Selected abort-runtime tests use ID-based scheduling and execution functions.
This change only affects the runtime test harness. The leak check does not cover runtimes created inside worklets, and the busy-runtime cleanup handling is only partly confirmed by tests. Neither affects shipped behavior, so the risk of merging is low.
Pre-merge checks: 4
Check name
Status
Explanation
Title check
The title names the main change: Worklets tests now create Worker Runtimes per test, and tests that leave a runtime alive now fail. The raw summary confirms the runner tracks runtimes, clears referenc…
Description check
The description states the motivation (leaked Worker Runtimes and out-of-memory failures on Android), the design (per-test runtimes, a leak check that fails tests), the 14 leaks fixed, performance mea…
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: Worklets tests now create Worker Runtimes per test, and tests that leave a runtime alive now fail. The raw summary confirms the runner tracks runtimes, clears references, and reports survivors, and that the shared pool is removed. The title's 'test(Worklets)' prefix is a conventional commit type and scope, which does not affect the match.
Full details: Description check
Explanation
The description states the motivation (leaked Worker Runtimes and out-of-memory failures on Android), the design (per-test runtimes, a leak check that fails tests), the 14 leaks fixed, performance measurements, alternatives considered, and test-plan results. It matches the changeset closely.
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; 4 remain after this review.
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 7 remain after this review.
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 6 remain after this review.
The reason will be displayed to describe this comment to others. Learn more.
Minor · Functional Correctness · Heavy lift
Leak check cannot see runtimes created inside a worklet.
WorkletRuntimeTracker.startTracking wraps createWorkletRuntime only on the RN Runtime's __workletsModuleProxy. A Worker Runtime created inside a UI worklet goes through the UI Runtime's own proxy, so it is never added to the tracked list. The test at lazyChunkWorklets.test.ts:297-306 does this. Its nested runtime is therefore invisible to stopTrackingAndFindAlive, which returns [] and passes.
Each Worker Runtime in Bundle Mode adds a large native memory cost. A survivor from this path would therefore not be reported, even though the runner is meant to report every runtime a test creates.
Runtimes created on the UI Runtime must be included in the survivor check. RN-created runtimes must stay tracked as they are now.
The reason will be displayed to describe this comment to others. Learn more.
Hi, Bruce here. Model: Claude Opus 5.5 (claude-opus-5-5) · Session: owner session Arlo II @jsi-codegen
Confirmed. The tracker wraps createWorkletRuntime only on the RN Runtime's proxy, so a runtime created inside a worklet goes through its creator's proxy and isn't tracked. Today the only such test is the nested lazy chunk test, and it waits explicitly for its nested runtime to be destroyed. How to cover this in general (a debug-only native list of live runtimes, compared before and after each test, or JS wrappers on every proxy) is a design choice for you, @tjzel. This thread stays open until you decide.
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 Worklets runtime tests shared a pool of Worker Runtimes across tests, and some tests created extra runtimes that stayed alive after the test ended. Nothing checked that a runtime was ever destroyed. In a development build with Bundle Mode each Worker Runtime evaluates the whole bundle, so a runtime that a test keeps alive costs a lot of memory, and on Android the suite ran out of memory. This PR makes the cleanup a guarantee that the test runner enforces.
Requires #11764, which fixes the lazy chunk memory growth that caused the out-of-memory kill. That fix is in the PR below this one in the stack.
What
The pool of shared Worker Runtimes is removed. Every test now gets new Worker Runtimes, and after each test the runner checks that every Worker Runtime the test created was destroyed. A runtime that is still alive fails the test and is reported by name.
The check found 14 leaked runtimes in the existing tests, which are fixed:
*WithIdfunctions, so they test the same behavior without the leak.How
Before each test, the runner wraps runtime creation and records every Worker Runtime created during the test. Describe blocks request runtimes through
useWorkletRuntimes, which assigns new runtimes before each test and clears the references after it. Tests can also callgetWorkletRuntimesdirectly. After the test, even if its cleanup throws, the runner clears these references and collects garbage on the React Native Runtime, the UI Runtime and every recorded Worker Runtime that is still alive and has a queue. Garbage collection on a Worker Runtime is scheduled on its queue, so a busy runtime cannot block the run. Runtimes without a queue are only polled. The runner repeats this until all of them are destroyed, or for at most five seconds, and then fails the test for each runtime still alive.The check only sees runtimes created on the React Native Runtime. A runtime created inside a worklet goes through its creator's module proxy and is not tracked. The one test that does this waits for its nested runtime on its own.
Performance
Measured on an Android emulator (API 34), Debug build with Bundle Mode, one full Worklets run with the fix from #11764, sampling every 3 seconds. Each case ran once, so there is no median or standard deviation. Peak total PSS was 2628 MB without the lazy chunk fix and 1208 MB with it, and memory at the end of the suite is about 1000 MB. Each run loop or networking test that creates a Worker Runtime still adds about 300 to 400 MB of native memory, which is freed after the test, so the peak now depends on the largest single test instead of on the whole suite.
The iOS Worklets run takes about 9 minutes, because each test creates its own runtimes.
Alternatives
Test plan
The Worklets runtime tests and the ReJest self-tests pass on an iOS simulator and the Worklets runtime tests pass on an Android emulator, in Debug builds with Bundle Mode, with no leaked runtimes. These runs used main
ee3d2ca045, not the current base. The common app type check and lint pass.Changelog
yarn changelog:addfor each changed package, or this PR does not changereact-native-reanimatedorreact-native-worklets.Agent track
Details for agents
Harness
apps/common-app/runtime-tests/ReJest/TestRunner/WorkletRuntimeTracker.ts:startTracking()wraps__workletsModuleProxy.createWorkletRuntimeand records{ runtimeId, name }.createRuntimes(count, namePrefix)throws outside a test; names are<test name> #<i>.stopTrackingAndFindAlive()restores the original, then loops: RNgc(), UIgc()viarunOnUISync, RNgc(); filters withisRuntimeAlive; runsgc()on each alive runtime viarunOnRuntimeSyncWithId(throws on aborted runtimes, caught); retries every 20 ms up to 5000 ms.ReJest/TestRunner/WorkletRuntimePool.ts,workletRuntimePoolandgetWorkletRuntimesFromPool.ReJest/types.ts:WorkletRuntimeUser = { count; assign };TestSuitegainsparentandworkletRuntimeUsers.TestSuiteBuilder.useWorkletRuntimes(count, assign)registers on the current describe;describe()setsparent.TestRunner.runTestCase:startTracking(), then for eachWorkletRuntimeUserin the parent chain (outermost first)assign(createRuntimes(...))beforebeforeEach; afterrender(null):assign([]), reset the shared test runtime,stopTrackingAndFindAlive(), and push[leaked runtime] Worklet Runtime "<name>" (id <id>) is still alive after the test.per survivor.RuntimeTestsApi.tsexportsuseWorkletRuntimes,getWorkletRuntimes,getSharedTestWorkletRuntime(used byrunLoop/dispatchWorklet.ts).Call sites
const [a] = getWorkletRuntimesFromPool(n)becamelet a!: WorkletRuntime; useWorkletRuntimes(n, (runtimes) => { [a] = runtimes; }); in-test calls becamegetWorkletRuntimes(n).buildTestswithCannot read property 'name' of undefined) became getters:createSerializable.test.tsx(getRuntimeName, and the WorkerscheduleOnTargetlost its'worklet'directive so it does not capture the runtime at describe time),serializableMapping.test.tsxandruntimes/weakRef.test.tsx(getRuntimeId).synchronizable.test.tsx: module-level runtime withuseSynchronizableTestRuntime()in each top-level describe.retainingSerializableConcurrency.test.tsx:runRound(runtimes, ...); runtimes are created once per test, socachedAcrossCallsstill sees the same runtimes (with per-round runtimes it got 320 instead of 800).reload/oldInstanceValues.test.tsx:run an old cached worklet on a new Worker Runtime with the same idandunpack an old Worker Runtime Remote Function as a guard on a new Worker Runtime with the same idmerged intorun an old cached worklet and unpack an old Worker Runtime Remote Function as a guard on a new Worker Runtime with the same id; module variablesameIdWorkerremoved.runtimes/abortWorkletRuntime.test.ts:abort-rescheduleusesscheduleOnRuntimeWithId,abort-sync-selfusesrunOnRuntimeSyncWithId,abort-self-queuedusesrunOnRuntimeAsyncWithId, all with a capturedruntimeId. Cause:WorkletRuntimeHolderholds a strongshared_ptr<WorkletRuntime>(Common/cpp/worklets/Compat/Holders.h),scheduleImpldrops jobs after abort andrunOnRuntimeSyncWithIdthrows for aborted runtimes (JSIWorkletsModuleProxy.cpp), so the self-reference is never collected. Issue Aborted Worklet Runtime that captured itself is never destroyed #11763.FailureSummary.test.ts,TestsOfTestingFramework.test.tsx: literal suites gainedparent: null, workletRuntimeUsers: [].Runs (Debug, Bundle Mode, base
ee3d2ca045)[leaked runtime]+ thecachedAcrossCalls320 vs 800).gc():--only reload,memory,runtimespassed 563, failed 4 (3 abort, 1 reload).--only runtimes: passed 220, failed 0.--library self-tests: passed 43, failed 0, skipped 2.Pixel_9_Agent_1(API 34), with the native fix(Worklets): propagate lazy chunks to Worklet Runtimes in native code #11764: full worklets passed 1114, failed 0, skipped 2; peak PSS 1208 MB, peak native HeapAlloc 1097 MB, last PSS 1008 MB. With the earlier JS-only fix(Worklets): propagate lazy chunks to Worklet Runtimes in native code #11764: peak PSS 1793 MB. Without fix(Worklets): propagate lazy chunks to Worklet Runtimes in native code #11764: passed 1114, peak PSS 2628 MB, peak native 2427 MB.releaseWorkletRuntimesruns infinally; queued runtimes getgc()viarunOnRuntimeAsyncWithIdwith one pending request per runtime; queueless runtimes are only polled. After them, iOS--only memory,runtimes,bundle mode corepassed 583, and the full iOS worklets suite on the native fix(Worklets): propagate lazy chunks to Worklet Runtimes in native code #11764 passed 1111, failed 0, skipped 5; Android--only memory,runtimes,bundle mode corepassed 583.yarn workspace common-app type:check: passed.oxlint apps/common-app/runtime-tests: clean.