Skip to content

fix(runtime): release async module-graph loads without V8 state off the isolate thread - #619

Open
edusperoni wants to merge 2 commits into
mainfrom
fix/async-graph-load-offthread-release
Open

edusperoni wants to merge 2 commits into
mainfrom
fix/async-graph-load-offthread-release

Conversation

@edusperoni

@edusperoni edusperoni commented Dec 2, 2026 •

Copy link
Copy Markdown
Collaborator

What

An async module-graph load (AsyncGraphLoad in ModuleInternalCallbacks.mm) owns a v8::Global<v8::Context>. Background threads keep references to it:

  • a stream compile job on the StreamCompilePool (large bodies) captures the load, the ticket, the fetch result and the completion, and the pool thread kept the job's closure until the job function returned, after it had posted the completion and after Leave() on the compile gate;
  • the fetch completion given to FetchModuleBodyAsync captures the load and lives until the NSURLSession thread deletes it, after calling it.

When the isolate thread ran the posted completion to the end of the walk first, the background thread dropped the last reference to a completed load, and ~v8::Global ran on that thread without a Locker while the isolate could be running JS.

This PR:

  • Resets the context Global when a load completes, on the isolate thread, in AsyncGraphMaybeComplete, before onComplete is called, so no way out of the callback (a C++ exception included) skips it. The callback receives the context as a v8::Local from the caller's handle scope and never reads the load's Global. A completed load then owns no V8 state, so it does not matter which thread drops it last. Teardown (KillAsyncGraphLoadsForIsolate) already did the same for loads still in flight.
  • Releases everything a stream compile job holds before Leave() on the compile gate, which is all teardown waits on. The job moves its load, ticket, result and completion into an inner scope that ends before Leave(). The captures are init-captures: the load, ticket and result are const& parameters, and a plain by-copy capture of them is a const member that std::move copies instead of releasing.
  • Rewrites the ~AsyncGraphLoad comment, which said the destructor runs on the JS thread on the normal path. It may run on any thread; completion and teardown leave it nothing to release there.

Nothing JS-visible changes.

Why

~v8::Global returns its slot to the isolate's global handle table. Doing that from a thread that does not hold the isolate's lock could race with the isolate thread's own use of that table. This is reasoning from what ~Global does, not an observed failure: the runs below observed the unlocked destruction itself, and no crash or test failure came with it.

How it was verified

The window is a few instructions wide, so a passing suite says nothing either way. The check used temporary instrumentation that is not part of this PR:

  • ~AsyncGraphLoad logged a line when it ran with a non-empty context Global on a thread other than the isolate's own thread (the thread id recorded when the isolate thread starts a load or runs one of its fetch completions), and recorded whether that thread held the isolate's Locker (v8::Locker::IsLocked). Lines were classified as the stream compile pool path or the transport path by a thread-local flag set on pool threads.
  • An optional 30 ms sleep widened the window: on the pool thread after the job function returned, and on the NSURLSession thread after it called the fetch completion and before deleting it. In the fixed build, another 30 ms sleep sat inside the job, after it posted the completion and before the release scope ended.
  • A temporary spec imported 60 distinct large modules (/esm/big.mjs, streamed) and then 60 distinct small modules (/esm/query.mjs) one after another, on top of the full suite, which includes the large-module specs ("survives workers terminated while their large modules compile" among them).

Counts are full-suite runs on an iOS 26.3 simulator. "Unlocked" means a non-empty Global destroyed on a thread that was neither the isolate's thread nor holding its Locker.

Build Sleeps Unlocked, pool path Unlocked, transport path
main none 0 0
main after the job, after the fetch completion 64 182
main + job release only (no reset on completion) after the job, after the fetch completion 0 246
this PR after the job, inside the job after posting, after the fetch completion 0 0

The pool zero in the release-only row holds because that run had no sleep inside the job; the release narrows the pool window to the instructions between posting and the end of the release scope, it does not close it. Every unlocked destruction logged on main was of a completed load (completed=1, dead=0); none was of a load still in flight.

All of these runs passed the suite, including the ones with 246 unlocked destructions.

The instrumented "this PR" run had the reset right after onComplete returned. It now comes right before the call, which only makes the load inert sooner; the instrumented runs were not repeated for that change.

In the fixed run with sleeps, 57 completed loads were still dropped last on a pool thread and 190 on a transport thread, all with an empty Global: the window was still hit, and was harmless. The run with only the job release shows that the release alone moves the last drop from the pool thread to the transport thread; resetting on completion is what removes it.

On main without sleeps, nothing unlocked was logged: the defect could occur there, but these runs did not hit it. Every run without the reset on completion also logged one destruction on a background thread that held the Locker: an import() from a GCD thread whose disk-only graph completes inline on that thread, which is not this defect. The runs with the reset logged none.

Without the instrumentation:

  • Full suite: 2339 cases, 0 failures, 13 skipped.
  • Full suite under AddressSanitizer: 2339 cases, 0 failures, 18 skipped.
  • Release build of the NativeScript framework (-Wall -Werror, iOS Simulator arm64 and x86_64): succeeded.

Not covered

  • No spec is added. The race shows only with a widened window, and pinning it would need a test-only hook in the runtime.
  • HasPendingAsyncModuleGraphWork still counts a load until its last reference is dropped, which can be on a background thread shortly after the load completed. Its only reader, the boot pump in runMainApplication, pumps 10 ms run loop slices under a deadline, so a late decrement costs at most one extra slice and is never early. Left as it is.
  • The transport keeps its own references to the load and the event loop until it deletes the completion, and nothing waits for that. With the reset on completion and the reset at teardown this holds no V8 state, and ~EventLoop already allows a last drop after shutdown on another thread.

Summary by CodeRabbit

  • Bug Fixes
    • Improved reliability of streamed module loading and completion during runtime teardown. Completion callbacks now run after the load context has been reset, helping avoid stale context during asynchronous work. Cleanup of resources associated with streamed compilation is coordinated with ongoing compile jobs, reducing the risk of premature release while work is in progress.
…he isolate thread

An async module-graph load owns a v8::Global for its context. Stream
compile pool threads and NSURLSession threads keep references to the
load after posting its fetch completion to the isolate thread. When the
isolate thread ran that completion to the end of the walk first, the
background thread dropped the last reference, and the Global was
destroyed off the isolate thread without a Locker while the isolate
could be running JS.

A load now resets its context Global on the isolate thread as soon as
it completes, so it holds no V8 state whichever thread drops it last.
Teardown already did the same for loads still in flight.

A stream compile job also releases the load, ticket, fetch result and
completion it holds before leaving the compile gate, which is all
teardown waits on.
The context Global of a completed module-graph load was reset after its
completion callback returned, so a C++ exception escaping the callback
would leave a completed load holding V8 state for another thread to
release. The callback receives the context as a Local from the caller's
handle scope and never reads the load's Global, so the reset now comes
first.
@coderabbitai

coderabbitai Bot commented Dec 2, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

The async graph load now resets its context before invoking the completion callback. Streamed compile jobs move captured references into job-local owners and release them before leaving the compile gate.

Changes: Async graph load lifecycle

Layer / File(s) Summary
Context and job reference cleanup
NativeScript/runtime/ModuleInternalCallbacks.mm
The destructor comment states that completion or teardown resets the context on the isolate thread. Completion resets the context before the callback. The streamed compile job releases its local owners before leaving the compile gate.

Estimated code review effort: 2 (Simple) | ~10 minutes

Change: Bug fix

Possibly related PRs

  • NativeScript/ios#587: Adds background-thread stream compilation for large HTTP modules. This change updates the lifetime of objects held by that compile job.

Suggested reviewers: nathanwalker

Merge Risk: Minimal · up to 31993

This change fixes a possible race when an async module-graph load's V8 context handle is destroyed off the isolate thread. JavaScript-visible behavior does not change. No blocking risk is identified, so it looks ready to merge.

Pre-merge checks: Passed 4

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title names the main change: releasing async module-graph load state (the V8 Global context) off the isolate thread, which the PR fixes by resetting the context on the isolate thread and reorderin…
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: releasing async module-graph load state (the V8 Global context) off the isolate thread, which the PR fixes by resetting the context on the isolate thread and reordering job-local releases. It is specific, concise, and matches the summary and objectives. The title uses the conventional commit prefix, which is acceptable.

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

A rabbit checks the context clean
Before the callback takes the scene
The stream job lets its owners go
Before the gate says “time to flow”
Ears up, the load is tidy now

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: 7cff9966-92a4-4c83-a293-ed9f7d2b45f7
Commits

Reviewing files that changed from the base of the PR and between fed7867 and 31993bc.

Files selected for processing: 1

  • NativeScript/runtime/ModuleInternalCallbacks.mm

Included review availability: This review used your included allowance. Your plan provides up to 2 included reviews per hour; 0 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

1 participant