Skip to content

Commit ff42476

Browse files
authored
perf(runtime): load large file modules off the JS thread (#2177)
### Description Ports NativeScript/ios#622 to Android. Large `.mjs` files are read and compiled on the stream-compile pool instead of the JS thread, and code-cache creation moves out of the load path. 1. **Streamed compile off the JS thread.** `.mjs` files of 32 KiB or more without a fresh code cache are read and stream-compiled on the pool. The JS thread only finalizes the module. 2. **Off-thread cache consume.** Files of 256 KiB or more with a fresh cache consume it on the pool. 3. **Deferred cache creation.** Caches are created 0.5 s after the last one was queued, one per pass 16 ms apart. A background thread writes them and skips the write if the source's mtime changed meanwhile. Pending caches are created when the app's UI is hidden (`onTrimMemory(TRIM_MEMORY_UI_HIDDEN)` → `Runtime.flushScriptCaches()`). 4. **No code caches in debuggable builds** (create, write and read). Semantics kept from iOS: - `import()` of a large file returns before it is evaluated; a graph of small files still settles inside the call. Every file `import()` settles through `Evaluate()` (V8 reports `kEvaluated` while top-level await is pending). - Boot, Worker entries and `require()` of an ES module block until the graph is evaluated. While only file loads are outstanding, the wait sleeps on the pool's signal and runs only nestable V8 tasks with microtasks suppressed, so no timer, looper post, worker message or promise job runs inside `require()`. With an HTTP fetch outstanding it pumps the looper as before. - Graph walks started before the outermost synchronous load are parked until it ends, including its evaluation, then resume as nestable tasks. #### Android-specific decisions - The file-only wait is a new `EventLoop::PumpNestableV8TasksUntil` (2 ms poll on the pool's signal). The pump mode is re-chosen after each step. - Idle cache slices go through `PostInternalDelayed`. - The "app went to background" signal is `onTrimMemory(UI_HIDDEN)`, registered in `RuntimeHelper` only when `codeCache` is on and the app isn't debuggable. Only the main runtime flushes; workers keep their own queue and drop pending entries at teardown, as on iOS. - Caches stay beside the source (`.mcache` / `.cache`); freshness is the source's whole-second mtime, which extracted assets take from the APK entry. - Off-thread compiles follow the app's `--no-lazy` flag, like the HTTP path. - JS running off the runtime's thread (`enableMultithreadedJavascript`) neither starts nor waits for a background file load: it compiles inline, and a job that finishes later defers to the module it registered. Without this, a `require()` on another thread could attach to the main thread's in-flight `import()` and pump the main loop from the wrong thread (EventLoop home-thread check abort). #### Behaviour change Debuggable apps with `codeCache: true` no longer read or write code caches. Release builds are unchanged apart from the deferred creation. #### Measurements Boot-graph A/B with the same 8-library graph as the iOS PR (3.15 MB, a fresh copy per variant and rep). "Inline" is the same build with background loads switched off by a temporary hook, not in this PR. Emulator Pixel_3a_API_36 (Android 16, arm64-v8a, 4 vCPU) on an Apple M4 Pro. Median of 10 (min..max), ms: | Regime | `require()` inline → off | `import()` longest JS-thread stall inline → off | |---|---|---| | debug | 38.8 (34.5..43.3) → **24.0** (19.1..27.4) | 40.5 (37.0..43.2) → **8.0** (6.8..9.0) | | release, first launch | 40.9 (33.5..42.4) → **26.1** (22.5..31.9) | 40.6 (37.2..42.9) → **7.4** (6.9..8.1) | | release, warm caches | 15.3 (10.2..18.2) → **12.6** (8.8..18.1) | 13.8 (10.3..18.9) → **7.0** (3.5..9.6) | `import()` settle time: 40.5 → 27.3 (debug and release first launch), 13.8 → 11.9 (warm). Release first launch is about equal to debug here because the test app compiles lazily (iOS's release numbers came from `--no-lazy`). All 160 caches were checked fresh before each warm launch. Pressing HOME mid-run created the 99 queued caches in one pass about 1 s later. ### Does your commit message include the wording below to reference a specific issue in this repo? No. ### Related Pull Requests - NativeScript/ios#622 — the iOS change this ports. ### Does your pull request have [unit tests](https://github.com/NativeScript/NativeScript/blob/master/running-tests.md)? Yes. `tests/testFileModuleLoad.js` ports the iOS specs (async `import()`, no timers or promise jobs inside `require()`, parking, top-level await, concurrent imports, cache freshness and write skipping) and adds two Android specs: an off-thread `require()`, and an off-thread `require()` concurrent with a pending `import()` of the same large module. `testWorkerConcurrentStartup.js`'s cache-mtime spec is pending in debuggable builds and keeps its workers alive long enough for the deferred writes in release. - Full suite on an API 36 emulator: 2207/2207 passing (and 2206/2206 with `enableMultithreadedJavascript: false` before the last spec was added). - Each fix was removed in turn and its spec failed: microtask suppression, always calling `Evaluate()`, the file-only pump, parking, start-order parking, HTTP-site parking, background dispatch, and the off-thread attach gate. - Release APK, cache-related specs only: 30 specs, 0 failures (the HTTP spec is skipped because the release allowlist blocks loopback); caches carry the source's mtime and leave no temp files. Follow-up worth discussing: since the test app is debuggable, the standard suite no longer exercises code caches. A test-only override would bring that coverage back to CI. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **Improvements** * Large JavaScript modules support dynamic imports, top-level `await`, and loading through workers and other module-loading paths. * Script caches are created and refreshed in the background, with freshness checked against source changes. * Queued script caches are flushed when the app moves out of view, when caching is enabled. A runtime API is also available to flush queued caches. * Imports already in progress remain pending during synchronous ES-module `require()`. If the required module awaits an import, loading continues until the configured deadline. * **Tests** * Expanded coverage for large-module loading, concurrent startup, cache behavior, and worker loading. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
1 parent a80675d commit ff42476

15 files changed

Lines changed: 2131 additions & 314 deletions

‎docs/ns-builtin-modules.md‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -981,6 +981,14 @@ Call it from a task context instead — a native boundary, an event handler, a
981981
timer callback, or module evaluation itself. A **synchronous** graph needs no
982982
pumping and stays legal from anywhere, microtask turns included.
983983
984+
**An `import()` started before the require settles after it.** While a
985+
synchronous load runs (any `require()` of an ES module, pumping or not), a
986+
module graph that an earlier `import()` is loading is not evaluated, and that
987+
`import()`'s promise stays pending until the require returns. A graph that
988+
awaits such a promise cannot settle in-pump: it waits out `deadlineSeconds`,
989+
then follows `onTimeout`. An `import()` the graph starts itself, such as
990+
`await import("./x.mjs")` in its own code, is not held back.
991+
984992
### What an HTTP module response must be
985993

986994
A module fetched over `http(s)` is classified by status and MIME type before it

‎test-app/app/src/main/assets/app/mainpage.js‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,8 @@ require('./tests/testConcurrentProxyGeneration');
151151
require('./tests/testEsmHttpLoader');
152152
// What import() settles with, per importer kind and specifier shape
153153
require('./tests/testDynamicImport');
154+
// File modules large enough to load off the JS thread
155+
require('./tests/testFileModuleLoad');
154156
// Node-API addon surface
155157
require('./tests/NapiTests');
156158
require('./tests/NapiCoverageTests');
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
// Imports the module named by each message, reporting "loading" as soon as
2+
// import() has returned and the module's id and line count once it settles.
3+
onmessage = function (msg) {
4+
import(msg.data).then(function (mod) {
5+
postMessage("ok:" + mod.id + ":" + mod.count);
6+
}, function (error) {
7+
postMessage("error:" + String((error && error.message) || error));
8+
});
9+
postMessage("loading");
10+
};

0 commit comments

Comments
 (0)