Skip to content

test(Worklets): create Worklet Runtimes per test and fail tests that leave one alive - #11765

Draft
tjzel wants to merge 6 commits into
@tjzel/worklets/lazy-chunk-propagation-memoryfrom
@tjzel/runtime-tests/worklets-runtime-memory
Draft

tjzel wants to merge 6 commits into
@tjzel/worklets/lazy-chunk-propagation-memoryfrom
@tjzel/runtime-tests/worklets-runtime-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 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:

  1. 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.
  2. One reload test kept a runtime in a module variable between tests. The two tests that used it are merged into one.
  3. 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

  1. 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.
  2. 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.
  • ReJest/types.ts: WorkletRuntimeUser = { count; assign }; TestSuite gains parent and workletRuntimeUsers.
  • 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.
  • Self-tests FailureSummary.test.ts, TestsOfTestingFramework.test.tsx: literal suites gained parent: null, workletRuntimeUsers: [].

Runs (Debug, Bundle Mode, base ee3d2ca045)

@tjzel
tjzel added this pull request to stack #11766 December 4, 2026 14:46
@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

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.

Possibly related PRs

Suggested labels: lib: Worklets

Change: Other

Merge Risk: Low · previous review 57729

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: Passed 4

Check name Status Explanation
Title check Passed 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 Passed 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 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: 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.

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: 2bfac1a5-34f9-4c93-9780-64e90cf95597
Commits

Reviewing files that changed from the base of the PR and between 637a069 and 57729c9.

Files selected for processing: 2

  • apps/common-app/runtime-tests/self-tests/suites.ts
  • apps/common-app/runtime-tests/self-tests/tests/WorkletRuntimeTracker.test.ts

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

Major 2
  1. A test that leaves a running worklet can hang the whole test run.
  2. A failed cleanup can leave a stale shared runtime for the next test.
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: 12d228f0-b3c6-48c2-849f-89cfeab0b5a8
Commits

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

Files selected for processing: 49

  • apps/common-app/runtime-tests/ReJest/RuntimeTestsApi.ts
  • apps/common-app/runtime-tests/ReJest/TestRunner/TestRunner.ts
  • apps/common-app/runtime-tests/ReJest/TestRunner/TestSuiteBuilder.ts
  • apps/common-app/runtime-tests/ReJest/TestRunner/WorkletRuntimePool.ts
  • apps/common-app/runtime-tests/ReJest/TestRunner/WorkletRuntimeTracker.ts
  • apps/common-app/runtime-tests/ReJest/types.ts
  • apps/common-app/runtime-tests/self-tests/tests/FailureSummary.test.ts
  • apps/common-app/runtime-tests/self-tests/tests/TestsOfTestingFramework.test.tsx
  • apps/common-app/runtime-tests/worklets/tests/memory/createSerializable.test.tsx
  • apps/common-app/runtime-tests/worklets/tests/memory/createSerializableOnUI.test.tsx
  • apps/common-app/runtime-tests/worklets/tests/memory/createSerializableTyped.test.tsx
  • apps/common-app/runtime-tests/worklets/tests/memory/customSerializable.test.tsx
  • apps/common-app/runtime-tests/worklets/tests/memory/hybridObjectSupport.test.tsx
  • apps/common-app/runtime-tests/worklets/tests/memory/isSerializableRef.test.tsx
  • apps/common-app/runtime-tests/worklets/tests/memory/retainingSerializable.test.tsx
  • apps/common-app/runtime-tests/worklets/tests/memory/retainingSerializableConcurrency.test.tsx
  • apps/common-app/runtime-tests/worklets/tests/memory/serializableMapping.test.tsx
  • apps/common-app/runtime-tests/worklets/tests/memory/shareable.test.tsx
  • apps/common-app/runtime-tests/worklets/tests/memory/synchronizable.test.tsx
  • apps/common-app/runtime-tests/worklets/tests/networking/api.test.ts
  • apps/common-app/runtime-tests/worklets/tests/plugin/closureFree.test.ts
  • apps/common-app/runtime-tests/worklets/tests/plugin/closures.test.ts
  • apps/common-app/runtime-tests/worklets/tests/reload/oldInstanceValues.test.tsx
  • apps/common-app/runtime-tests/worklets/tests/runLoop/dispatchWorklet.ts
  • apps/common-app/runtime-tests/worklets/tests/runLoop/executionOrder.test.tsx
  • apps/common-app/runtime-tests/worklets/tests/runLoop/finalizers.test.tsx
  • apps/common-app/runtime-tests/worklets/tests/runLoop/timerErrors.test.tsx
  • apps/common-app/runtime-tests/worklets/tests/runtimes/abortWorkletRuntime.test.ts
  • apps/common-app/runtime-tests/worklets/tests/runtimes/deserializationErrors.test.tsx
  • apps/common-app/runtime-tests/worklets/tests/runtimes/errorTraces.test.tsx
  • apps/common-app/runtime-tests/worklets/tests/runtimes/getCurrentThreadId.test.tsx
  • apps/common-app/runtime-tests/worklets/tests/runtimes/microtaskDrains.test.tsx
  • apps/common-app/runtime-tests/worklets/tests/runtimes/microtaskErrors.test.tsx
  • apps/common-app/runtime-tests/worklets/tests/runtimes/nativeErrorBoundaries.test.ts
  • apps/common-app/runtime-tests/worklets/tests/runtimes/performanceNow.test.tsx
  • apps/common-app/runtime-tests/worklets/tests/runtimes/reactNativeImportShim.test.ts
  • apps/common-app/runtime-tests/worklets/tests/runtimes/runOnRNSync.test.ts
  • apps/common-app/runtime-tests/worklets/tests/runtimes/runOnRuntimeAsync.test.tsx
  • apps/common-app/runtime-tests/worklets/tests/runtimes/runOnRuntimeAsyncWithId.test.tsx
  • apps/common-app/runtime-tests/worklets/tests/runtimes/runOnRuntimeSync.test.tsx
  • apps/common-app/runtime-tests/worklets/tests/runtimes/runOnRuntimeSyncWithId.test.tsx
  • apps/common-app/runtime-tests/worklets/tests/runtimes/runOnUIAsync.test.tsx
  • apps/common-app/runtime-tests/worklets/tests/runtimes/runOnUISync.test.tsx
  • apps/common-app/runtime-tests/worklets/tests/runtimes/scheduleOnRN.test.tsx
  • apps/common-app/runtime-tests/worklets/tests/runtimes/scheduleOnRuntime.test.tsx
  • apps/common-app/runtime-tests/worklets/tests/runtimes/scheduleOnRuntimeWithId.test.tsx
  • apps/common-app/runtime-tests/worklets/tests/runtimes/scheduleOnUI.test.tsx
  • apps/common-app/runtime-tests/worklets/tests/runtimes/syncCallCrossRuntimeError.test.tsx
  • apps/common-app/runtime-tests/worklets/tests/runtimes/weakRef.test.tsx
Files with no reviewable changes: 1

  • apps/common-app/runtime-tests/ReJest/TestRunner/WorkletRuntimePool.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 7 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. Leak check cannot see runtimes created inside a worklet.
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: 56671503-4452-458d-b354-99f7cabccd15
Commits

Reviewing files that changed from the base of the PR and between b7f68e1 and 0042fa9.

Files selected for processing: 2

  • apps/common-app/runtime-tests/ReJest/TestRunner/TestRunner.ts
  • apps/common-app/runtime-tests/ReJest/TestRunner/WorkletRuntimeTracker.ts

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

const proxy = getProxy();
const originalCreate = proxy.createWorkletRuntime;
const tracked: TrackedWorkletRuntime[] = [];
proxy.createWorkletRuntime = (...args: unknown[]) => {

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.

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.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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.

@tjzel
tjzel force-pushed the @tjzel/runtime-tests/worklets-runtime-memory branch from 0042fa9 to e5bf4e1 Compare December 4, 2026 15:35
@tjzel
tjzel force-pushed the @tjzel/runtime-tests/worklets-runtime-memory branch from e5bf4e1 to 637a069 Compare December 4, 2026 16:37
@tjzel
tjzel force-pushed the @tjzel/runtime-tests/worklets-runtime-memory branch 2 times, most recently from 25f7bce to 6c95237 Compare December 4, 2026 17:04
@tjzel
tjzel force-pushed the @tjzel/runtime-tests/worklets-runtime-memory branch from 57729c9 to d4a9165 Compare December 4, 2026 17:42

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