Repository navigation
perf(runtime): compile large HTTP modules off the JS thread - #2170
Draft
edusperoni wants to merge 3 commits into
Draft
edusperoni wants to merge 3 commits into
edusperoni wants to merge 3 commits into
Conversation
|
Important Draft PR not reviewedDraft PRs are not automatically reviewed by default.
To automatically review draft PRs, update your CodeRabbit configuration: reviews:
auto_review:
drafts: true
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. |
This was referenced Dec 2, 2026
edusperoni
added a commit
that referenced
this pull request
Dec 2, 2026
…er URL (#2168) ### Description A module loaded over `http(s)` now resolves the specifiers it imports the way a browser does, for static `import` and `import()` alike, and it can no longer reach the app's filesystem implicitly. **Resolution follows the HTML module-specifier rules, through the WHATWG URL parser** (ada, the parser behind `new URL()`): - Only `/`, `./` and `../` prefixes are relative (`//host/x` is a `/` form). Anything else is an absolute URL if it parses as one, and a bare specifier otherwise. So `.x`, `.` and `..` are bare. - Dot segments and `\` resolve as in a browser, and the scheme is lowercased, so `HTTP://host/x` is an http URL. - The authority (userinfo, host, port) keeps the spelling the importer's URL, or the specifier, wrote. Dev tooling compares the module URLs the runtime reports against the origin it was configured with, verbatim. - The query is kept: `import('./x.js?v=1')` and `import('./x.js?v=2')` are two modules, as they are for a static import. **No implicit filesystem fallback from an HTTP module.** The shared resolver (graph walk, static resolve callback, `import()` callback) refuses these before anything is fetched or probed on disk: - a relative, root-relative or scheme-relative specifier that does not form an `http(s)` URL against the importer's URL; - an unmapped bare specifier, instead of falling back to `<app root>/<spec>`; - `~/x`. The errors name the specifier, the importer and what to use instead, e.g.: ``` Cannot resolve module specifier "lodash" imported from http://host/src/app.js: it is not in the import map (bare specifiers from an HTTP module must be mapped). ``` An unmapped specifier with another scheme (`data:`, `foo:bar`, `file:/x`) fails as `Cannot find module` without a disk lookup. Still allowed from an HTTP module: `ns:`/`node:` builtins, absolute `http(s)` URLs, an explicit `file:///…` URL, `blob:nativescript/…` URLs, and anything the import map maps. A mapped target is never refused, and a relative or root-relative target resolves against the importer's URL. `createRequire(<file path>)` stays the explicit way for an HTTP module to reach on-disk modules. **An import-map entry keyed by a module's own URL** never changes how that module's imports resolve. An HTTP module mapped to a file stays an HTTP importer, and a file module whose `file:///app/…` URL (or a prefix of it) is a map key stays a file importer. `docs/ns-builtin-modules.md` gains a "Specifier resolution" section for HTTP importers. #### Notes for review - **Import-map lookup of a query, from a file module.** On Android, a file module's static `import 'pkg?x'` and its `import('pkg?x')` both look `pkg?x` up in the map as written. The map is consulted before the query is dropped for the on-disk path, which is already how `main` works. A new spec pins it, and the docs state it. On iOS after NativeScript/ios#586, `import()` from a file module drops the query before the lookup, while a static import does not. The two platforms therefore differ for `import()` from a file module. This is one of the cross-platform decisions tracked in #2020; this PR doesn't change it. Note that #2020's description of the Android side predates this check. - File modules resolve exactly as before. ### Does your commit message include the wording below to reference a specific issue in this repo? No issue. ### Related Pull Requests Mirrors NativeScript/ios#586 (code, specs and the docs section). Part of a stack of six; each PR targets the branch below it: 1. #2168 `fix/http-importer-specifiers`: specifier resolution from HTTP importers (**this PR**, base `main`) 2. #2169 `refactor/module-url-parse`: one URL parse for every http(s) entry point 3. #2170 `perf/http-module-streaming-compile`: compile large HTTP modules off the JS thread 4. #2171 `fix/http-module-fetch-budget`: bound fetches by the graph walk's deadline 5. #2172 `perf/http-module-transport`: persistent connections, per-host-class caps, OkHttp transport 6. #2173 `feat/http-module-cache-controls`: HTTP module cache controls ### Does your pull request have [unit tests](https://github.com/NativeScript/NativeScript/blob/master/running-tests.md)? Yes. 21 new specs in `testEsmHttpLoader.js`, served by new `ModuleTestServer` routes and `esm/http-importer/`, `esm/self-mapped-*/` and `esm/query-map/` fixtures: - `./`, `../`, root- and scheme-relative `import()` load the URLs a browser computes, and the query is part of the module's identity. - Unmapped static and dynamic bare imports, `~/` and an other-scheme `import()` are refused. Same-named fixtures exist on disk, and an evaluation flag in each proves nothing was read. - Builtins, an explicit `file://` URL, import-map entries (any target form, including a relative one) and `blob:nativescript` URLs still load. - A module whose own URL is a map key (HTTP mapped to a file; a file module's exact and prefix entries) keeps its importer kind. - `.x`, `.` and `..` are refused as bare, statically and from `import()`. - Every spelling of one URL is one module, from `import()` and from a static import. Dot segments, `\` and an uppercase scheme normalize as the URL parser does. An importer served from a non-canonically spelled origin keeps that spelling in what it resolves. - A file module looks a static import's and an `import()`'s query up in the map as written. Full suite on the top of the stack (`./gradlew runtestsAndVerifyResults`): 2074 specs, 2068 passed, 0 failed, 6 skipped (the usual GC, native-module and environment skips), on an API 36 arm64 emulator with OkHttp in the test app, at `feat/http-module-cache-controls` 21f87a8. This stays a draft until the stack has been run against a real Vite dev session on Android, which has not happened yet. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **New Features** * HTTP(S) modules now resolve relative and root-absolute imports against their URL, while import maps can rewrite specifiers and provide URL-relative targets. * Import resolution now handles built-in modules, file and blob URLs, and URL normalization consistently. * **Bug Fixes** * Unmapped bare and `~/` imports from HTTP modules are rejected with clearer errors instead of being treated as file paths. * File-based modules retain file-based resolution when their own URL is mapped. * **Documentation** * Clarified import-map behavior and documented HTTP module specifier resolution. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
… terminated Five workers each start a dynamic import() of a 2 s delayed HTTP module and are terminated as soon as the fetch is in flight. The main isolate then imports a module delayed past every worker response and must still resolve. Android quiesces a worker's async graph loads in DestroyRuntime while the runtime's state is still reachable, so the completions that land later find their loads dead and touch nothing. The spec pins that. ModuleTestServer gains the /esm/slow/ routes (leaf, child, parent) that answer after `delayMs`, matching the iOS test server.
…S thread An async graph load's context Global was Reset only by isolate teardown. A fetch thread keeps its reference to the load until its completion callback is destroyed, after the completion was posted, so when the JS thread finished the walk first the fetch thread dropped the last reference and destroyed the Global without the isolate's Locker. The walk now Resets the Global as soon as it completes. No completion can arrive after that, so whichever thread drops the last reference destroys no V8 state.
ES modules fetched over HTTP by the async graph walk whose JavaScript body is 32 KiB or larger are parsed and compiled to bytecode on a background thread through V8's streaming API; the JS thread only finalizes the result. Smaller bodies, JSON, failed fetches and the synchronous fallback compile as before. Nothing JS-visible changes. - A StreamedModuleCompile is started at fetch issue, parked in the isolate's ModuleLoaderState, fed the body once the transport completes, run on a dedicated pool, and finalized with ScriptCompiler::CompileModule(context, StreamedSource*, ...). Registration, request walking and error reporting are shared with the synchronous path through CompileAndRegisterModule; a key registered meanwhile (two walks fetching one URL) is reused and the streamed compile discarded. - Pure-ASCII bodies become external one-byte source strings, charged to the isolate through v8::ExternalMemoryAccounter and released in the resource's Unaccount(). - The pool is at most min(4, cores - 1) detached pthreads, started on demand, with a 2 MB stack: V8's background parser checks for overflow against --stack-size (984 KB) below the point where Run() starts, and a default bionic thread (~1 MB) leaves almost no margin above that. With a 512 KB stack the deep-nesting spec crashes the process with a stack overflow on the pool thread instead of rejecting with a RangeError. The threads are not attached to the JVM. If no pool thread can start, the module compiles on the JS thread. - When the app's v8Flags turn lazy compilation off, streamed compiles pass kEagerCompile, since streaming follows --lazy-streaming, not --lazy. V8 has no public flag getter, so InitializeV8 reads the flag string it applies, the way SetFlagsFromString reads a bool flag. - Bodies starting with a UTF-8 BOM are not streamed, because the stream drops the BOM while the source string keeps it. - Isolate teardown (QuiesceModuleLoadsForIsolate, workers included) closes a gate, waits out running compiles while running the event loop's nestable V8 tasks, where a background compile's GC request lands, and destroys unfinalized compiles before the event loop stops. That wait runs with microtasks suppressed and JS execution disallowed: a worker terminated mid-JS can still hold microtasks, and the runtime is half torn down by then. - Debug builds expose process-wide counts of the paths large bodies took through ns:module's streamedCompileStats() (finalized, discarded, fellBack, running, teardownWaits). Specs cover dynamic, static and pumped require() loads, non-ASCII sources, syntax errors, pathologically deep nesting, concurrent imports of one module and workers terminated mid-compile, against /esm/big.mjs and /esm/big-parent.mjs routes added to ModuleTestServer. Each asserts the counters, so a module that silently compiles on the JS thread fails it. The worker sweep waits for each worker's thread to end and sizes itself from a wall-clock budget. A worker terminated while spinning, with a microtask that would import a probe module and a fetch completion queued, checks that its teardown wait runs no JavaScript.
edusperoni
force-pushed
the
perf/http-module-streaming-compile
branch
from
December 2, 2026 17:36
bd7b74b to
5bb37af
Compare
NathanWalker
reviewed
Dec 2, 2026
| } | ||
|
|
||
| private: | ||
| static constexpr size_t kStackBytes = 2 * 1024 * 1024; |
Contributor
There was a problem hiding this comment.
Minor risk: the parser's overflow limit is --stack-size below where Run() starts, but this stack is fixed at 2 MB. An app whose v8Flags raise --stack-size past ~1.9 MB (fine on the ~8 MB main thread today) could segfault here on a deeply nested ≥32 KiB module instead of getting a RangeError. Maybe size the threads from the parsed --stack-size + margin in NoteAppliedV8Flags, or skip streaming when it's too large?
This branch has not been deployed
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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
Description
ES modules that the async graph walk fetches over HTTP are now parsed and compiled to bytecode on a background thread through V8's streaming API when their JavaScript body is 32 KiB or larger. The JS thread only finalizes the result. Smaller bodies, JSON modules, failed fetches and the synchronous fallback compile as before. Nothing JS-visible changes: module identity, evaluation order, error texts and positions all stay the same.
During a dev-server load the JS thread compiled every fetched module itself, one after another, while other fetches had already completed. Large modules dominate that time, for example bundles and modules carrying inline source maps.
How it works
StreamedModuleCompileis started when the fetch is issued (ScriptCompiler::StartStreaming(..., kModule, ...)) and parked in the isolate'sModuleLoaderState. The transport carries only a ticket and owns no V8 state.ScriptStreamingTask::Run). Only then is the completion posted to the isolate's event loop.ScriptCompiler::CompileModule(context, StreamedSource*, ...)finalizes the compile. Registration, request walking and error reporting are shared with the synchronous path throughCompileAndRegisterModule. If two walks fetched one URL and the key was registered in the meantime, the existing module is reused and the streamed compile is discarded.v8::ExternalMemoryAccounterand released in the resource'sUnaccount(). Anything else usesNewFromUtf8as before.min(4, cores - 1)detached pthreads, started on demand, each with a 2 MB stack. V8's background parser checks for overflow at--stack-size(984 KB) below whereRun()starts, so a default ~1 MB bionic thread leaves almost no margin. With a 512 KB stack, the deep-nesting spec crashed the process with a stack overflow on the pool thread instead of rejecting with aRangeError. The threads are not attached to the JVM. If no pool thread can start, the module compiles on the JS thread.kEagerCompile. Streaming follows--lazy-streaming, not--lazy. So when the app'sv8Flagsturn lazy compilation off, streamed compiles passkEagerCompile. V8 has no public flag getter, soInitializeV8reads the flag string it applies.QuiesceModuleLoadsForIsolate(workers included) closes a gate and waits out running compiles. While it waits, it runs the event loop's nestable V8 tasks, which is where a background compile's GC request lands. It then destroys unfinalized compiles before the event loop stops. The wait runs with microtasks suppressed and JS execution disallowed, because a worker terminated mid-JS can still hold microtasks and the runtime is half torn down by then.Debug builds expose process-wide counters through
ns:module.streamedCompileStats():finalized,discarded,fellBack,runningandteardownWaits.An Android-only fix in the same PR: release a finished graph walk's context on the JS thread. An async graph load's
v8::Global<v8::Context>was reset only by isolate teardown. A fetch thread holds a reference to the load until its completion callback is destroyed, which happens after the completion is posted. So when the JS thread finished the walk first, the fetch thread dropped the last reference and destroyed theGlobalwithout the isolate'sLocker. The walk now resets theGlobalas soon as it completes. No completion can arrive after that, so whichever thread drops the last reference destroys no V8 state. This is not part of NativeScript/ios#587 or NativeScript/ios#584.Notes for review
DestroyRuntimewhile the runtime's state is still reachable. Only the fix(runtime): quiesce in-flight http module loads when a worker terminates ios#584 spec is ported, as a guard.StartStreamingcall when it is issued. The body size is unknown until the response arrives.scriptParsed, breakpoints);kEagerCompilebranch, which only an app whosev8Flagsturn lazy compilation off reaches (the test app's flags are--expose_gconly);Does your commit message include the wording below to reference a specific issue in this repo?
No issue.
Related Pull Requests
Mirrors NativeScript/ios#587. It also ports the worker-teardown spec of NativeScript/ios#584, on which NativeScript/ios#587 builds; the NativeScript/ios#584 code change has no Android counterpart (see above). Android-specific: the pool threads are not attached to the JVM, the teardown wait runs no JavaScript (microtasks suppressed, JS execution disallowed), and debug builds expose the
streamedCompileStats()counters.Part of a stack of six; each PR targets the branch below it:
fix/http-importer-specifiers: specifier resolution from HTTP importersrefactor/module-url-parse: one URL parse for every http(s) entry pointperf/http-module-streaming-compile: compile large HTTP modules off the JS thread (this PR)fix/http-module-fetch-budget: bound fetches by the graph walk's deadlineperf/http-module-transport: persistent connections, per-host-class caps, OkHttp transportfeat/http-module-cache-controls: HTTP module cache controlsDoes your pull request have unit tests?
Yes.
ModuleTestServergains these routes:/esm/big.mjs, a generated module above the threshold, with options for non-ASCII literals, a trailing syntax error, deep nesting and a delay;/esm/big-parent.mjs;/esm/slow/(leaf,child,parent), which answer afterdelayMs, matching the iOS test server.New specs in
testEsmHttpLoader.js:import()of a 2 s delayed module and are terminated while the fetch is in flight. The main isolate then imports a module delayed past every worker response, and that import must resolve.streamedCompileStats()counters, so a module that silently compiles on the JS thread fails it. They cover:import(), through a static import, and during a pumpedrequire();RangeErroras a small module is;Full suite on the top of the stack (
./gradlew runtestsAndVerifyResults): 2074 specs, 2068 passed, 0 failed, 6 skipped (the usual GC, native-module and environment skips), on an API 36 arm64 emulator with OkHttp in the test app, atfeat/http-module-cache-controls21f87a8.This stays a draft until the stack has been run against a real Vite dev session on Android, which has not happened yet.