From ea612acd9160b906ff910a46e32bde1935bb35c3 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Tue, 1 Dec 2026 23:25:27 -0300 Subject: [PATCH 1/3] test(runtime): cover HTTP module fetches that land after their worker 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. --- .../app/tests/httpImportTerminateWorker.js | 6 +++ .../assets/app/tests/testEsmHttpLoader.js | 51 +++++++++++++++++++ .../java/com/tns/tests/ModuleTestServer.java | 49 ++++++++++++++++++ 3 files changed, 106 insertions(+) create mode 100644 test-app/app/src/main/assets/app/tests/httpImportTerminateWorker.js diff --git a/test-app/app/src/main/assets/app/tests/httpImportTerminateWorker.js b/test-app/app/src/main/assets/app/tests/httpImportTerminateWorker.js new file mode 100644 index 000000000..5df1330cc --- /dev/null +++ b/test-app/app/src/main/assets/app/tests/httpImportTerminateWorker.js @@ -0,0 +1,6 @@ +// Starts an HTTP dynamic import and reports as soon as its fetch is in flight, +// without waiting for it to settle. +onmessage = function (msg) { + import(msg.data).catch(function () {}); + postMessage("fetching"); +}; diff --git a/test-app/app/src/main/assets/app/tests/testEsmHttpLoader.js b/test-app/app/src/main/assets/app/tests/testEsmHttpLoader.js index f031593e6..f148d1a96 100644 --- a/test-app/app/src/main/assets/app/tests/testEsmHttpLoader.js +++ b/test-app/app/src/main/assets/app/tests/testEsmHttpLoader.js @@ -829,6 +829,57 @@ describe("HTTP ESM Loader", function () { }); }); + describe("worker teardown", function () { + var originalTimeout; + beforeEach(function () { + originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL; + jasmine.DEFAULT_TIMEOUT_INTERVAL = 30000; + }); + afterEach(function () { + jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout; + }); + + it("survives HTTP module fetches that land after their worker terminated", + function (done) { + var workerDelayMs = 2000; + var workerCount = 5; + var remaining = workerCount; + + // Delayed past every worker response, so by the time it + // settles all of them have arrived at their torn-down loaders. + function importOnMain() { + import(origin + "/esm/slow/leaf.mjs?k=wt-main&delayMs=" + (workerDelayMs + 1000)) + .then(function (mod) { + expect(mod.value).toBe(42); + done(); + }).catch(function (error) { + reportRejection(error, done); + }); + } + + function settle(worker) { + worker.terminate(); + if (--remaining === 0) { + importOnMain(); + } + } + + for (var i = 0; i < workerCount; i++) { + (function (worker, k) { + worker.onmessage = function () { + settle(worker); + }; + worker.onerror = function (error) { + fail("worker " + k + " errored: " + formatError(error)); + settle(worker); + }; + worker.postMessage(origin + "/esm/slow/leaf.mjs?k=" + k + + "&delayMs=" + workerDelayMs); + })(new Worker("./httpImportTerminateWorker.js"), "wt" + i); + } + }); + }); + // Each present configureLoader section replaces its state wholesale, so // an empty array is explicit policy — "nothing is volatile any more" — // not a no-op. diff --git a/test-app/app/src/main/java/com/tns/tests/ModuleTestServer.java b/test-app/app/src/main/java/com/tns/tests/ModuleTestServer.java index fb1413804..64ae896d4 100644 --- a/test-app/app/src/main/java/com/tns/tests/ModuleTestServer.java +++ b/test-app/app/src/main/java/com/tns/tests/ModuleTestServer.java @@ -286,6 +286,29 @@ private static void route(Socket socket, String path, String query) throws IOExc return; } + // Simulates a dev server answering a cold module transform in + // `delayMs`. The parent re-exports the child, a transitive HTTP edge + // the graph walk discovers after the slow fetch lands. + if (path.startsWith("/esm/slow/")) { + int delayMs = intParam(query, "delayMs=", "/esm/slow/child.mjs".equals(path) ? 0 : 7000); + String key = param(query, "k="); + if (key == null) { + key = "slow"; + } + String body; + if ("/esm/slow/parent.mjs".equals(path)) { + body = "export { value } from \"./child.mjs?from=" + key + "\";\n" + + "export const parent = \"" + key + "\";\n"; + } else { + body = "export const value = 42; export const name = \"" + key + "\";\n"; + } + if (!sleepFor(delayMs)) { + return; + } + respond(socket, "200 OK", JS_MIME, body.getBytes(UTF8)); + return; + } + if ("/esm/timeout.mjs".equals(path)) { int delayMs = 12000; String raw = param(query, "delayMs="); @@ -351,6 +374,32 @@ private static String param(String query, String prefix) { return null; } + private static int intParam(String query, String prefix, int fallback) { + String raw = param(query, prefix); + if (raw == null) { + return fallback; + } + try { + return Integer.parseInt(raw); + } catch (NumberFormatException e) { + return fallback; + } + } + + /** False when the connection thread was interrupted (the server is stopping). */ + private static boolean sleepFor(int delayMs) { + if (delayMs <= 0) { + return true; + } + try { + Thread.sleep(delayMs); + return true; + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return false; + } + } + private static String jsStringLiteral(String s) { return s.replace("\\", "\\\\") .replace("\"", "\\\"") From ff75692c717a4f93f5fdedfb16f3de291cfb35bf Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Tue, 1 Dec 2026 23:59:47 -0300 Subject: [PATCH 2/3] fix(runtime): release a finished module graph walk's context on the JS 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. --- .../runtime/src/main/cpp/ModuleInternalCallbacks.cpp | 5 +++++ .../runtime/src/main/cpp/ModuleInternalCallbacks.h | 10 +++++----- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp b/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp index bb540e50d..ec199b978 100644 --- a/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp +++ b/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp @@ -1415,6 +1415,8 @@ static uint64_t MonotonicUs() { namespace { struct AsyncGraphLoad { v8::Isolate* isolate = nullptr; + // Reset on the JS thread when the walk completes or teardown kills it: the + // last reference to a load may drop on a transport or compile thread. v8::Global context; std::string rootKey; // canonical registry key of the root robin_hood::unordered_set visited; // canonical keys (JS thread only) @@ -1562,6 +1564,9 @@ static void AsyncGraphMaybeComplete(const std::shared_ptr& load, v8::Local context) { if (load->completed || load->pendingFetches > 0) return; load->completed = true; + // No completion can arrive for this load any more, while transport and + // compile threads may still hold references to it and drop the last one. + load->context.Reset(); if (LogCategoryEnabled(LogCategory::Esm)) { const uint64_t endUs = MonotonicUs(); const uint64_t ms = endUs > load->startUs ? (endUs - load->startUs) / 1000ull : 0ull; diff --git a/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.h b/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.h index cdb869fdc..b6c97316c 100644 --- a/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.h +++ b/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.h @@ -166,11 +166,11 @@ v8::MaybeLocal LoadHttpModuleForUrl( // path) to report with its own message, so the walk introduces no new failure // modes and steals no error text. // -// `onComplete` must capture only trivially destructible state. A background -// fetch completion can drop the last reference to a load whose isolate is -// already quiesced — QuiesceModuleLoadsForIsolate Resets the load's context -// Global but nothing else — so the closure is destroyed on whichever thread -// gets there last, and a captured v8 handle would be destroyed off-thread. +// `onComplete` must capture only trivially destructible state. The last +// reference to a load can drop on a background thread, possibly after the +// isolate is gone; the load's own context Global is Reset on the JS thread +// when the walk completes or teardown quiesces it, but nothing else is, so a +// captured v8 handle would be destroyed off-thread. void StartModuleGraphLoad( v8::Isolate* isolate, v8::Local context, const std::string& root, From 5bb37af3f999063b35bd200b2984225e1fa37007 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Tue, 1 Dec 2026 23:25:41 -0300 Subject: [PATCH 3/3] perf(runtime): compile large HTTP modules off the JS thread 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. --- docs/ns-builtin-modules.md | 7 +- .../main/assets/app/esm/mixed/big-entry.mjs | 4 + .../app/tests/httpImportDrainProbeWorker.js | 12 + .../app/tests/httpImportSettleWorker.js | 10 + .../assets/app/tests/testEsmHttpLoader.js | 375 ++++++++++++ .../src/main/assets/app/tests/testNsModule.js | 3 +- .../java/com/tns/tests/ModuleTestServer.java | 82 +++ .../src/main/cpp/ModuleInternalCallbacks.cpp | 579 +++++++++++++++++- .../src/main/cpp/ModuleInternalCallbacks.h | 7 + test-app/runtime/src/main/cpp/Runtime.cpp | 1 + test-app/runtime/src/main/cpp/js/ns-module.js | 7 +- 11 files changed, 1060 insertions(+), 27 deletions(-) create mode 100644 test-app/app/src/main/assets/app/esm/mixed/big-entry.mjs create mode 100644 test-app/app/src/main/assets/app/tests/httpImportDrainProbeWorker.js create mode 100644 test-app/app/src/main/assets/app/tests/httpImportSettleWorker.js diff --git a/docs/ns-builtin-modules.md b/docs/ns-builtin-modules.md index ee1b5ad23..e0d8dc8e2 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -511,7 +511,12 @@ diagnostic that takes a string and throws build with `allowRemoteModules` on would fetch `url` under a `security.remoteModuleAllowlist` of `entries` (`true` for `[]`) and throws `remoteUrlMatchesAllowlist expects a URL string and an array of strings` -otherwise; release builds omit both. Missing members are simply absent — never +otherwise, and `streamedCompileStats()`, which returns process-wide counts of +how HTTP module bodies large enough for a background compile were compiled +(`finalized`, `discarded` after another walk registered the same key first, +`fellBack` to the JS thread), the background compiles `running` now, and the +isolate teardowns that waited one out (`teardownWaits`); release builds omit +all three. Missing members are simply absent — never present-but-throwing — so feature checks work. The module is registered in every build: the security boundary for remote module loading sits at the network layer (`security.allowRemoteModules` in nativescript.config, enforced diff --git a/test-app/app/src/main/assets/app/esm/mixed/big-entry.mjs b/test-app/app/src/main/assets/app/esm/mixed/big-entry.mjs new file mode 100644 index 000000000..5d046e292 --- /dev/null +++ b/test-app/app/src/main/assets/app/esm/mixed/big-entry.mjs @@ -0,0 +1,4 @@ +// Local root whose only edge is "ns-big-leaf", a bare specifier the spec's +// import map points at a generated ModuleTestServer module above the +// streaming-compile threshold. +export * as leaf from "ns-big-leaf"; diff --git a/test-app/app/src/main/assets/app/tests/httpImportDrainProbeWorker.js b/test-app/app/src/main/assets/app/tests/httpImportDrainProbeWorker.js new file mode 100644 index 000000000..29aebcf91 --- /dev/null +++ b/test-app/app/src/main/assets/app/tests/httpImportDrainProbeWorker.js @@ -0,0 +1,12 @@ +// Starts a small and a large HTTP import, queues a microtask that imports +// `probe`, reports "spinning" and spins until terminated: the small import's +// fetch completion and the microtask are still pending when it is. +onmessage = function (msg) { + import(msg.data.small); + import(msg.data.big); + Promise.resolve().then(function () { + import(msg.data.probe); + }); + postMessage("spinning"); + for (;;) {} +}; diff --git a/test-app/app/src/main/assets/app/tests/httpImportSettleWorker.js b/test-app/app/src/main/assets/app/tests/httpImportSettleWorker.js new file mode 100644 index 000000000..02072141f --- /dev/null +++ b/test-app/app/src/main/assets/app/tests/httpImportSettleWorker.js @@ -0,0 +1,10 @@ +// Starts an HTTP dynamic import, reports "fetching" as soon as it is issued +// and "settled" once it resolves or rejects. A terminated worker never sends +// "settled". +onmessage = function (msg) { + function settled() { + postMessage("settled"); + } + import(msg.data).then(settled, settled); + postMessage("fetching"); +}; diff --git a/test-app/app/src/main/assets/app/tests/testEsmHttpLoader.js b/test-app/app/src/main/assets/app/tests/testEsmHttpLoader.js index f148d1a96..5b9540c5e 100644 --- a/test-app/app/src/main/assets/app/tests/testEsmHttpLoader.js +++ b/test-app/app/src/main/assets/app/tests/testEsmHttpLoader.js @@ -880,6 +880,381 @@ describe("HTTP ESM Loader", function () { }); }); + // Bodies of 32 KiB or more compile off the JS thread. Every module + // here comes from ModuleTestServer's /esm/big.mjs generator, has its + // own `k` (modules evaluate once per process) and asserts `bytes` so + // it is above that threshold by construction. + describe("large modules", function () { + var STREAMING_THRESHOLD = 32 * 1024; + var LINES = 1500; + var originalTimeout; + beforeEach(function () { + originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL; + jasmine.DEFAULT_TIMEOUT_INTERVAL = 30000; + }); + afterEach(function () { + jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout; + }); + + function bigQuery(k, lines, extra) { + return "k=" + k + "&lines=" + lines + (extra || ""); + } + + // Process-wide counts of the paths large bodies took (debug builds). + function streamStats() { + return require("ns:module").streamedCompileStats(); + } + + function streamedSince(before) { + var now = streamStats(); + return { + finalized: now.finalized - before.finalized, + discarded: now.discarded - before.discarded, + fellBack: now.fellBack - before.fellBack, + teardownWaits: now.teardownWaits - before.teardownWaits, + }; + } + + // `finalized` large bodies since `before`, all compiled off the JS + // thread. + function expectStreamed(before, finalized) { + var delta = streamedSince(before); + expect(delta.finalized).toBe(finalized); + expect(delta.discarded).toBe(0); + expect(delta.fellBack).toBe(0); + } + + function requestCount(target) { + return import(origin + "/esm/request-stats.json?target=" + + encodeURIComponent(target) + "&n=" + (++requestStatsQueries)) + .then(function (m) { + return m.default.count; + }); + } + + function bigUrl(k, lines, extra) { + return origin + "/esm/big.mjs?" + bigQuery(k, lines, extra); + } + + function expectWholeBody(mod, k, lines) { + var total = 0; + for (var i = 0; i < lines; i++) { + total += (i * 3 + i) % 1000; + } + expect(mod.id).toBe(k); + expect(mod.count).toBe(lines); + expect(mod.total).toBe(total); + expect(mod.bytes).toBeGreaterThan(STREAMING_THRESHOLD); + expect(globalThis.__nsBigModuleEvaluations[k]).toBe(1); + } + + function rejectionOf(url) { + return import(url).then(function () { + return "resolved"; + }, function (error) { + return formatError(error); + }); + } + + // The rejection names the module and the error position; strip the + // URL so a small and a large module's texts compare equal. + function withoutUrl(message, url) { + return message.split(url).join(""); + } + + it("evaluates one loaded with import()", function (done) { + var before = streamStats(); + import(bigUrl("big-dynamic", LINES)).then(function (mod) { + expectWholeBody(mod, "big-dynamic", LINES); + expectStreamed(before, 1); + done(); + }).catch(function (error) { + reportRejection(error, done); + }); + }); + + it("evaluates one reached through a static import", function (done) { + var before = streamStats(); + var child = encodeURIComponent(bigQuery("big-static", LINES)); + import(origin + "/esm/big-parent.mjs?k=big-static-parent&child=" + child) + .then(function (mod) { + expect(mod.parent).toBe("big-static-parent"); + expectWholeBody(mod.child, "big-static", LINES); + expectStreamed(before, 1); + done(); + }).catch(function (error) { + reportRejection(error, done); + }); + }); + + it("evaluates one reached during a pumped require()", function () { + var nsModule = require("ns:module"); + nsModule.configureLoader({ + importMap: { + imports: { "ns-big-leaf": bigUrl("big-require", LINES) }, + }, + }); + try { + var before = streamStats(); + var req = nsModule.createRequire(appRoot + "/anything.js"); + var mod = req("./esm/mixed/big-entry.mjs"); + expectWholeBody(mod.leaf, "big-require", LINES); + expectStreamed(before, 1); + } finally { + nsModule.configureLoader({ importMap: { imports: {} } }); + } + }); + + it("evaluates non-ASCII string literals to the right values", function (done) { + var before = streamStats(); + import(bigUrl("big-unicode", LINES, "&unicode=1")).then(function (mod) { + expectWholeBody(mod, "big-unicode", LINES); + expectStreamed(before, 1); + var joinedLength = 0; + for (var i = 0; i < LINES; i++) { + joinedLength += ("café 日本語 😀 " + i).length; + } + expect(mod.first).toBe("café 日本語 😀 0"); + expect(mod.last).toBe("café 日本語 😀 " + (LINES - 1)); + expect(mod.joinedLength).toBe(joinedLength); + done(); + }).catch(function (error) { + reportRejection(error, done); + }); + }); + + it("rejects a syntax error with the text a small module produces", function (done) { + var smallUrl = bigUrl("small-syntax", 0, "&error=1"); + var largeUrl = bigUrl("big-syntax", LINES, "&error=1"); + var before = streamStats(); + Promise.all([rejectionOf(smallUrl), rejectionOf(largeUrl)]).then(function (texts) { + expectStreamed(before, 1); + var position = /\(line (\d+):(\d+)\)/; + var small = withoutUrl(texts[0], smallUrl); + var large = withoutUrl(texts[1], largeUrl); + expect(small).toContain("SyntaxError"); + // The error sits on the line after the filler declarations. + expect(small.match(position)[1]).toBe("3"); + expect(large.match(position)[1]).toBe(String(LINES + 3)); + expect(large.replace(position, "")).toBe(small.replace(position, "")); + expect(large.match(position)[2]).toBe(small.match(position)[2]); + done(); + }).catch(function (error) { + reportRejection(error, done); + }); + }); + + it("rejects pathologically deep nesting like a small module does", function (done) { + // 20 KB of brackets: below the threshold on its own, above it + // with the filler declarations. + var smallUrl = bigUrl("small-deep", 0, "&nest=10000"); + var largeUrl = bigUrl("big-deep", 600, "&nest=10000"); + var before = streamStats(); + Promise.all([rejectionOf(smallUrl), rejectionOf(largeUrl)]).then(function (texts) { + expectStreamed(before, 1); + var position = /\s*\(line \d+:\d+\)/; + var small = withoutUrl(texts[0], smallUrl).replace(position, ""); + var large = withoutUrl(texts[1], largeUrl).replace(position, ""); + expect(small).toContain("Maximum call stack size exceeded"); + expect(large).toBe(small); + done(); + }).catch(function (error) { + reportRejection(error, done); + }); + }); + + it("resolves one module for concurrent imports from several call sites", + function (done) { + var query = bigQuery("big-shared", LINES); + var url = origin + "/esm/big.mjs?" + query; + var parent = origin + "/esm/big-parent.mjs?child=" + encodeURIComponent(query) + + "&k="; + var before = streamStats(); + Promise.all([ + import(url), + import(parent + "big-shared-a"), + import(url), + import(parent + "big-shared-b"), + ]).then(function (mods) { + expectWholeBody(mods[0], "big-shared", LINES); + expect(mods[2]).toBe(mods[0]); + expect(mods[1].child).toBe(mods[0]); + expect(mods[3].child).toBe(mods[0]); + // Each walk that found the module unregistered fetched and + // compiled it; the first to finish registered its result. + var delta = streamedSince(before); + expect(delta.finalized).toBe(1); + expect(delta.discarded).toBeLessThan(3); + expect(delta.fellBack).toBe(0); + done(); + }).catch(function (error) { + reportRejection(error, done); + }); + }); + + it("survives workers terminated while their large modules compile", + function (done) { + var MODULE_LINES = 40000; + // The sweep terminates its workers at evenly spaced points from + // 0 to LAST_POINT of a calibrated import's duration. The + // background compile occupies only part of that duration, and + // where it starts depends on the machine, so the points cover + // all of it. As many points as fit in SWEEP_BUDGET_MS, which + // leaves the calibration and the final import room under the + // spec's timeout. + var LAST_POINT = 1.1; + var MAX_STEPS = 23; + var SWEEP_BUDGET_MS = 25000; + + function importOnMain() { + var before = streamStats(); + import(bigUrl("big-after-workers", LINES)).then(function (mod) { + expectWholeBody(mod, "big-after-workers", LINES); + expectStreamed(before, 1); + done(); + }).catch(function (error) { + reportRejection(error, done); + }); + } + + // Calls onFetching when the worker's import is issued and + // onSettled when it settles, each at most once (a worker that + // errors counts as settled), and onEnded once its thread has + // torn its runtime down. + function startWorker(k, onFetching, onSettled, onEnded) { + var worker = new Worker("./httpImportSettleWorker.js"); + var fetching = false; + var settled = false; + function settle() { + if (!settled) { + settled = true; + onSettled(worker); + } + } + worker.addEventListener("nsworkerended", onEnded); + worker.onmessage = function (msg) { + if (msg.data === "fetching" && !fetching) { + fetching = true; + onFetching(worker); + } else if (msg.data === "settled") { + settle(); + } + }; + worker.onerror = function (error) { + fail("worker " + k + " errored: " + formatError(error)); + settle(); + }; + worker.postMessage(bigUrl(k, MODULE_LINES)); + } + + // One worker at a time, so each compile has the pool to itself + // as the calibration import did. A worker is terminated at its + // point or when it settles, whichever comes first, and the next + // one starts only once its thread has ended: a teardown that + // never finishes fails the spec by its timeout. Steps slower + // than calibrated end the sweep early. + function sweep(plan, step) { + if (step === plan.steps || Date.now() - plan.startedAt > SWEEP_BUDGET_MS) { + importOnMain(); + return; + } + var stopped = false; + function stop(worker) { + if (!stopped) { + stopped = true; + worker.terminate(); + } + } + startWorker("big-worker-" + step, function (worker) { + setTimeout(function () { + stop(worker); + }, plan.durationMs * plan.spacing * step); + }, stop, function () { + sweep(plan, step + 1); + }); + } + + var before = streamStats(); + var createdAt = Date.now(); + var fetchingAt = 0; + var settledAt = 0; + startWorker("big-worker-calibration", function () { + fetchingAt = Date.now(); + }, function (worker) { + settledAt = Date.now(); + worker.terminate(); + }, function () { + if (fetchingAt === 0) { + importOnMain(); + return; + } + expectStreamed(before, 1); + var durationMs = settledAt - fetchingAt; + // A terminated worker's teardown can wait out up to the + // rest of its compile, so a step costs up to a whole + // import on top of starting and ending a worker. + var stepMs = (fetchingAt - createdAt) + (Date.now() - settledAt) + durationMs; + var steps = Math.max(2, Math.min(MAX_STEPS, + Math.floor(SWEEP_BUDGET_MS / stepMs))); + sweep({ + durationMs: durationMs, + steps: steps, + spacing: LAST_POINT / (steps - 1), + startedAt: Date.now(), + }, 0); + }); + }, 60000); + + it("runs no JavaScript in a terminated worker's teardown while its compile finishes", + function (done) { + // Terminated mid-spin, the worker leaves a microtask pending + // and a small module's fetch completion queued; its teardown + // then waits for the large module's background compile and + // runs queued V8 tasks meanwhile. The microtask would import + // `probe`. + var stamp = Date.now(); + var probeTarget = "/esm/query.mjs?drain-probe=" + stamp; + var before = streamStats(); + var deadline = Date.now() + 20000; + var worker = new Worker("./httpImportDrainProbeWorker.js"); + worker.addEventListener("nsworkerended", function () { + expect(streamedSince(before).teardownWaits).toBe(1); + // Time for a request the teardown issued to reach the server. + setTimeout(function () { + requestCount(probeTarget).then(function (count) { + expect(count).toBe(0); + done(); + }).catch(function (error) { + reportRejection(error, done); + }); + }, 1000); + }); + worker.onerror = function (error) { + fail("worker errored: " + formatError(error)); + }; + worker.onmessage = function (msg) { + if (msg.data !== "spinning") { + return; + } + (function terminateOnceCompiling() { + if (streamStats().running > 0) { + worker.terminate(); + } else if (Date.now() > deadline) { + fail("the worker's large module never started compiling"); + worker.terminate(); + } else { + setTimeout(terminateOnceCompiling, 1); + } + })(); + }; + worker.postMessage({ + small: origin + "/esm/query.mjs?drain-small=" + stamp, + big: bigUrl("big-drain-probe", 100000), + probe: origin + probeTarget, + }); + }, 60000); + }); + // Each present configureLoader section replaces its state wholesale, so // an empty array is explicit policy — "nothing is volatile any more" — // not a no-op. diff --git a/test-app/app/src/main/assets/app/tests/testNsModule.js b/test-app/app/src/main/assets/app/tests/testNsModule.js index e74d98be2..cdc1552ca 100644 --- a/test-app/app/src/main/assets/app/tests/testNsModule.js +++ b/test-app/app/src/main/assets/app/tests/testNsModule.js @@ -16,7 +16,8 @@ describe("ns:module", function () { var expected = ["configureLoader", "createPumpingRequire", "createRequire", "getLoadedModuleUrls", "invalidateModules"]; if (typeof nsModule.canonicalizeHttpUrlKey === "function") { - expected.push("canonicalizeHttpUrlKey", "remoteUrlMatchesAllowlist"); + expected.push("canonicalizeHttpUrlKey", "remoteUrlMatchesAllowlist", + "streamedCompileStats"); } expect(Object.keys(nsModule).sort()).toEqual(expected.sort()); }); diff --git a/test-app/app/src/main/java/com/tns/tests/ModuleTestServer.java b/test-app/app/src/main/java/com/tns/tests/ModuleTestServer.java index 64ae896d4..9fcee0c20 100644 --- a/test-app/app/src/main/java/com/tns/tests/ModuleTestServer.java +++ b/test-app/app/src/main/java/com/tns/tests/ModuleTestServer.java @@ -309,6 +309,76 @@ private static void route(Socket socket, String path, String query) throws IOExc return; } + // Generated modules of a requested size. + // /esm/big.mjs: `lines` real declarations whose evaluation folds into + // `total`, so a value depends on the whole body. + // k module id (also the evaluation counter's key) + // unicode 1 adds non-ASCII string literals (strs/first/last) + // error 1 ends the body with a syntax error at line lines+3 + // nest appends an array literal nested `nest` deep + // delayMs answers after a delay + // /esm/big-parent.mjs?k=…&child= statically + // imports that big.mjs and re-exports it as `child`. + if ("/esm/big.mjs".equals(path) || "/esm/big-parent.mjs".equals(path)) { + String rawKey = decodedParam(query, "k="); + StringBuilder keyBuilder = new StringBuilder(); + for (char c : (rawKey == null ? "x" : rawKey).toCharArray()) { + if (Character.isLetterOrDigit(c) || c == '-') { + keyBuilder.append(c); + } + } + String key = keyBuilder.toString(); + int delayMs = intParam(query, "delayMs=", 0); + StringBuilder body = new StringBuilder(); + if ("/esm/big-parent.mjs".equals(path)) { + String child = decodedParam(query, "child="); + child = child == null ? "" : child.replace("\"", ""); + body.append("export * as child from \"./big.mjs?").append(child).append("\";\n") + .append("export const parent = \"").append(key).append("\";\n"); + } else { + int lines = intParam(query, "lines=", 0); + boolean unicode = "1".equals(param(query, "unicode=")); + body.append("let acc = 0;\nconst strs = [];\n"); + for (int i = 0; i < lines; i++) { + body.append("function f").append(i).append("(x) { return (x * 3 + ").append(i) + .append(") % 1000; } acc += f").append(i).append("(").append(i).append(");"); + if (unicode) { + body.append(" strs.push(\"café 日本語 😀 ") + .append(i).append("\");"); + } + body.append("\n"); + } + int depth = intParam(query, "nest=", 0); + if (depth > 0) { + body.append("export const deep = "); + for (int i = 0; i < depth; i++) { + body.append('['); + } + for (int i = 0; i < depth; i++) { + body.append(']'); + } + body.append(";\n"); + } + if ("1".equals(param(query, "error="))) { + body.append("export const broken = ;\n"); + } + body.append("const evaluations = globalThis.__nsBigModuleEvaluations || (globalThis.__nsBigModuleEvaluations = {});\n") + .append("evaluations[\"").append(key).append("\"] = (evaluations[\"").append(key).append("\"] || 0) + 1;\n") + .append("export const id = \"").append(key).append("\";\n") + .append("export const count = ").append(lines).append(";\n") + .append("export const total = acc;\n") + .append("export const first = strs[0];\n") + .append("export const last = strs[strs.length - 1];\n") + .append("export const joinedLength = strs.join(\"\").length;\n"); + body.append("export const bytes = ").append(body.toString().getBytes(UTF8).length).append(";\n"); + } + if (!sleepFor(delayMs)) { + return; + } + respond(socket, "200 OK", JS_MIME, body.toString().getBytes(UTF8)); + return; + } + if ("/esm/timeout.mjs".equals(path)) { int delayMs = 12000; String raw = param(query, "delayMs="); @@ -374,6 +444,18 @@ private static String param(String query, String prefix) { return null; } + private static String decodedParam(String query, String prefix) { + String raw = param(query, prefix); + if (raw == null) { + return null; + } + try { + return URLDecoder.decode(raw, "UTF-8"); + } catch (Exception e) { + return raw; + } + } + private static int intParam(String query, String prefix, int fallback) { String raw = param(query, prefix); if (raw == null) { diff --git a/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp b/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp index ec199b978..a7b585768 100644 --- a/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp +++ b/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp @@ -1,19 +1,25 @@ // ModuleInternalCallbacks.cpp #include "ModuleInternalCallbacks.h" +#include #include #include #include +#include #include #include #include +#include #include #include +#include +#include #include #include #include #include +#include #include #include @@ -155,6 +161,7 @@ static std::string FileURLToPath(const std::string& url) { // Forward declarations for helpers referenced before their definitions. static const char* ModuleStatusToString(v8::Module::Status status); static void KillAsyncGraphLoadsForIsolate(v8::Isolate* isolate); +static void DrainStreamedCompilesForIsolate(v8::Isolate* isolate); static v8::MaybeLocal CompileJsonTextAsEsModule( v8::Isolate* isolate, v8::Local context, const std::string& jsonText, const std::string& registryAbsPath, @@ -173,6 +180,119 @@ struct RequireFacadeEntry { v8::Global facade; }; +// ───────────────────────────────────────────────────────────── +// Off-thread compile of large HTTP module bodies +// +// ScriptStreamingTask::Run() works on the isolate's heap from another thread +// (it opens a LocalIsolate), so the isolate must outlive every Run() and a +// task that has run must be destroyed before the isolate is disposed. Hence: +// - StreamedModuleCompile (StreamedSource + task) is owned by the isolate's +// ModuleLoaderState and created, finalized and destroyed under the +// isolate's Locker only; +// - background threads hold a StreamTicket, which never owns V8 state; +// - StreamCompileGate counts Run() calls in flight; teardown closes it and +// waits for zero before the event loop stops and the state is destroyed. + +// The whole body in one chunk. Feed() and the GetMoreData() calls Run() makes +// happen on the same thread, Feed() first. V8 takes ownership of the chunk +// and delete[]s it. +class BodySourceStream : public v8::ScriptCompiler::ExternalSourceStream { + public: + void Feed(std::unique_ptr chunk, size_t length) { + chunk_ = std::move(chunk); + length_ = length; + } + + size_t GetMoreData(const uint8_t** src) override { + if (chunk_ == nullptr) return 0; + *src = chunk_.release(); + return length_; + } + + private: + std::unique_ptr chunk_; + size_t length_ = 0; +}; + +class StreamCompileGate { + public: + // False once closed: no Run() may start after teardown began. + bool TryEnter() { + std::lock_guard lock(mutex_); + if (closed_) return false; + inFlight_++; + return true; + } + + void Leave() { + std::lock_guard lock(mutex_); + if (--inFlight_ == 0) { + cv_.notify_all(); + } + } + + // Under the isolate's Locker. A Run() that needs a GC parks until the + // isolate's thread performs it (CollectionBarrier::AwaitCollectionBackground), + // and the waiting thread is not parked itself, so a plain wait could + // deadlock: `serviceGcRequests` runs between short waits to let that GC + // happen. True when a Run() was in flight. + bool CloseAndDrain(const std::function& serviceGcRequests) { + std::unique_lock lock(mutex_); + closed_ = true; + const bool waited = inFlight_ > 0; + while (inFlight_ > 0) { + if (cv_.wait_for(lock, std::chrono::milliseconds(2), + [this] { return inFlight_ == 0; })) { + break; + } + lock.unlock(); + serviceGcRequests(); + lock.lock(); + } + return waited; + } + + private: + std::mutex mutex_; + std::condition_variable cv_; + int inFlight_ = 0; + bool closed_ = false; +}; + +// The background threads' view of one streamed compile. `stream` and `task` +// are owned by the isolate-side StreamedModuleCompile and may be used only +// between a successful gate->TryEnter() and the matching Leave(). `ran` and +// `ascii` are written before the completion task is posted and read after it +// runs. +struct StreamTicket { + uint64_t id = 0; + std::shared_ptr gate; + BodySourceStream* stream = nullptr; + v8::ScriptCompiler::ScriptStreamingTask* task = nullptr; + bool ran = false; + bool ascii = false; +}; + +struct StreamedModuleCompile { + // Declared before `task`, which points into it. + std::unique_ptr source; + std::unique_ptr task; +}; + +// Which path each streamable body took, across all isolates. Read by the +// debug-only `ns:module` streamedCompileStats() diagnostic. +struct StreamedCompileCounters { + std::atomic finalized{0}; // background compile finalized + std::atomic discarded{0}; // background compile ran, key registered meanwhile + std::atomic fellBack{0}; // compiled on the JS thread instead + std::atomic running{0}; // Run() calls in progress + std::atomic teardownWaits{0}; // isolate teardowns that waited out a Run() +}; +static StreamedCompileCounters g_streamedCompileCounters; + +// Set by NoteAppliedV8Flags before any isolate exists. +static bool g_eagerStreamedCompiles = false; + // ───────────────────────────────────────────────────────────── // Per-isolate module-loader state // @@ -232,6 +352,14 @@ struct ModuleLoaderState { // Holds the facade target across that facade's InstantiateModule and nothing // else — the facade's resolve callback is the only reader. v8::Global pendingFacadeTarget; + + // Streamed compiles issued and not yet finalized or discarded, by ticket id. + // QuiesceModuleLoadsForIsolate drains the gate before any of these die. + std::shared_ptr streamGate = + std::make_shared(); + robin_hood::unordered_map> + streamedCompiles; + uint64_t nextStreamedCompileId = 1; }; // This isolate's loader state, or null once teardown has begun — callers must @@ -506,9 +634,15 @@ static std::string DescribeCaughtError(v8::Isolate* isolate, // which nothing downstream can reconstruct. A caller that cannot let it // propagate must consume it through its own TryCatch and route the text into // its own failure channel — never drop it. -static v8::MaybeLocal CompileModuleForResolveRegisterOnly( +// +// `compile` produces the module for `origin`; it is not called when the key is +// already registered. +using ModuleCompileStep = + std::function(const v8::ScriptOrigin& origin)>; + +static v8::MaybeLocal CompileAndRegisterModule( v8::Isolate* isolate, v8::Local context, - const std::string& code, const std::string& urlStr) { + const std::string& urlStr, const ModuleCompileStep& compile) { v8::EscapableHandleScope hs(isolate); auto* moduleState = ModuleLoaderStateFor(isolate); if (moduleState == nullptr) { @@ -527,8 +661,6 @@ static v8::MaybeLocal CompileModuleForResolveRegisterOnly( } } - v8::Local sourceText = - ArgConverter::ConvertToV8String(isolate, code); v8::Local urlV8; if (!v8::String::NewFromUtf8(isolate, urlStr.c_str(), v8::NewStringType::kNormal) @@ -537,11 +669,10 @@ static v8::MaybeLocal CompileModuleForResolveRegisterOnly( } v8::ScriptOrigin origin(urlV8, 0, 0, false, -1, v8::Local(), false, false, true /* is_module */); - v8::ScriptCompiler::Source src(sourceText, origin); v8::Local mod; { v8::TryCatch tcCompile(isolate); - if (!v8::ScriptCompiler::CompileModule(isolate, &src).ToLocal(&mod)) { + if (!compile(origin).ToLocal(&mod)) { TNS_DEBUG(Esm, "[http-esm][compile][fail] %s %s", urlStr.c_str(), DescribeCaughtError(isolate, context, tcCompile).c_str()); tcCompile.ReThrow(); @@ -554,6 +685,86 @@ static v8::MaybeLocal CompileModuleForResolveRegisterOnly( return hs.Escape(mod); } +static v8::MaybeLocal CompileModuleForResolveRegisterOnly( + v8::Isolate* isolate, v8::Local context, + const std::string& code, const std::string& urlStr) { + return CompileAndRegisterModule( + isolate, context, urlStr, + [isolate, &code](const v8::ScriptOrigin& origin) { + v8::ScriptCompiler::Source src( + ArgConverter::ConvertToV8String(isolate, code), origin); + return v8::ScriptCompiler::CompileModule(isolate, &src); + }); +} + +// A module body the isolate keeps as an external one-byte string. Valid only +// for pure-ASCII bodies: a one-byte string is Latin-1, which matches the +// UTF-8 bytes the streamed compile parsed only below 0x80. The bytes live +// outside the V8 heap, so they are charged as external memory for as long as +// the string holds them. +class OwnedAsciiSource : public v8::String::ExternalOneByteStringResource { + public: + OwnedAsciiSource(std::string body, v8::Isolate* isolate) + : body_(std::move(body)), isolate_(isolate) {} + const char* data() const override { return body_.data(); } + size_t length() const override { return body_.size(); } + + // Under the isolate's Locker, with the string held by a handle: the + // increase can run a collection before it returns. + void Charge() { + accounter_.Increase(isolate_, body_.size()); + charged_ = true; + } + + // V8 calls this right before Dispose(), possibly on a GC worker thread or + // during heap teardown; the decrease is a single atomic update. + void Unaccount(v8::Isolate* isolate) override { + if (charged_) { + accounter_.Decrease(isolate, body_.size()); + charged_ = false; + } + } + + private: + std::string body_; + v8::Isolate* isolate_; + v8::ExternalMemoryAccounter accounter_; + bool charged_ = false; +}; + +// Finalizes a streamed compile whose ScriptStreamingTask::Run() has returned. +// `body` must be the exact bytes the stream was fed. The compile is discarded +// unfinalized when `urlStr` is registered already. +static v8::MaybeLocal CompileStreamedModuleRegisterOnly( + v8::Isolate* isolate, v8::Local context, + StreamedModuleCompile& streamed, std::string body, bool ascii, + const std::string& urlStr) { + bool finalized = false; + v8::MaybeLocal mod = CompileAndRegisterModule( + isolate, context, urlStr, + [isolate, context, &streamed, &body, ascii, + &finalized](const v8::ScriptOrigin& origin) { + finalized = true; + v8::Local sourceText; + if (ascii) { + auto* resource = new OwnedAsciiSource(std::move(body), isolate); + if (!v8::String::NewExternalOneByte(isolate, resource).ToLocal(&sourceText)) { + delete resource; + return v8::MaybeLocal(); + } + resource->Charge(); + } else { + sourceText = ArgConverter::ConvertToV8String(isolate, body); + } + return v8::ScriptCompiler::CompileModule(context, streamed.source.get(), + sourceText, origin); + }); + (finalized ? g_streamedCompileCounters.finalized + : g_streamedCompileCounters.discarded) + .fetch_add(1, std::memory_order_relaxed); + return mod; +} + // Returns null once teardown has begun. ModuleHandleMap* ModuleRegistryFor(v8::Isolate* isolate) { auto* state = ModuleLoaderStateFor(isolate); @@ -562,10 +773,12 @@ ModuleHandleMap* ModuleRegistryFor(v8::Isolate* isolate) { // Neutralize any in-flight async graph loads for `isolate`: their fetch // completions check the dead flag before touching V8, and their context -// Globals are Reset here, while the isolate is still alive. The rest of the -// loader state is destroyed with the isolate's RuntimeState. +// Globals are Reset here, while the isolate is still alive. Background compiles +// are waited out for the same reason. The rest of the loader state is +// destroyed with the isolate's RuntimeState. void QuiesceModuleLoadsForIsolate(v8::Isolate* isolate) { KillAsyncGraphLoadsForIsolate(isolate); + DrainStreamedCompilesForIsolate(isolate); } // The calling isolate's vocabulary, or null once teardown has begun. @@ -1400,17 +1613,21 @@ static uint64_t MonotonicUs() { // Enqueue(root) // → local: CompileFileEsModule + register under the canonical key // → http: FetchModuleBodyAsync (background thread — see HttpLoader.cpp) +// → JavaScript bodies of kStreamingCompileThresholdBytes or +// more: parse + bytecode generation on a StreamCompilePool +// thread (V8 streaming) // → back to the isolate's own event loop as a nestable v8 task -// → CompileModuleForResolveRegisterOnly (registers under the -// canonical URL key — the exact entry the resolver looks up) +// → CompileModuleForResolveRegisterOnly, or the streamed +// compile's finalization (registers under the canonical URL +// key — the exact entry the resolver looks up) // → GetModuleRequests() → ResolveSpecifierToPath → Enqueue(…) // → when pendingFetches drains, onComplete fires on the JS thread. // // Thread discipline: `visited`, `pendingFetches`, `failed`, `completed` are // touched ONLY on the isolate's JS thread (every fetch completion hops there -// first). Only raw I/O runs off-thread. The one crossing signal is `dead`, -// an atomic set by isolate teardown so in-flight completions become no-ops -// instead of touching a disposed isolate. +// first). Off-thread work is the I/O and ScriptStreamingTask::Run(). The one +// crossing signal is `dead`, an atomic set by isolate teardown so in-flight +// completions become no-ops instead of touching a disposed isolate. namespace { struct AsyncGraphLoad { @@ -1469,8 +1686,233 @@ void RegisterAsyncGraphLoad(v8::Isolate* isolate, loads.end()); loads.push_back(load); } + +// Smaller JavaScript bodies compile on the isolate thread: for them the round +// trip through a background thread costs more than the compile it moves. +constexpr size_t kStreamingCompileThresholdBytes = 32 * 1024; + +// Threads that run ScriptStreamingTask::Run(). The background parser checks +// for stack overflow against V8's --stack-size (984 KB on arm64) below the +// stack pointer at which Run() starts, so a thread with less stack than that +// overflows for real before the parser can report a RangeError. Bionic's +// default thread stack is just under 1 MB, hence dedicated threads with a +// larger one. Run() needs no JNI, so the threads are not attached to the JVM. +class StreamCompilePool { + public: + static StreamCompilePool& Shared() { + // Never destroyed: its threads wait on its members for the life of the + // process. + static StreamCompilePool* pool = new StreamCompilePool(); + return *pool; + } + + // False when no thread could be started to run `job`, which is then + // dropped without running. + bool Post(std::function job) { + { + std::lock_guard lock(mutex_); + if (jobs_.size() >= idle_ && threads_ < maxThreads_ && StartThreadLocked()) { + threads_++; + } + if (threads_ == 0) return false; + jobs_.push_back(std::move(job)); + } + cv_.notify_one(); + return true; + } + + private: + static constexpr size_t kStackBytes = 2 * 1024 * 1024; + + StreamCompilePool() { + const unsigned cpus = std::thread::hardware_concurrency(); + maxThreads_ = std::clamp(cpus > 1 ? cpus - 1 : 1u, 1u, 4u); + } + + bool StartThreadLocked() { + pthread_attr_t attr; + if (pthread_attr_init(&attr) != 0) return false; + pthread_attr_setstacksize(&attr, kStackBytes); + pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); + pthread_t thread; + const bool started = pthread_create(&thread, &attr, &ThreadMain, this) == 0; + pthread_attr_destroy(&attr); + return started; + } + + static void* ThreadMain(void* arg) { + pthread_setname_np(pthread_self(), "ns-esm-compile"); + auto* pool = static_cast(arg); + for (;;) { + std::function job; + { + std::unique_lock lock(pool->mutex_); + pool->idle_++; + pool->cv_.wait(lock, [pool] { return !pool->jobs_.empty(); }); + pool->idle_--; + job = std::move(pool->jobs_.front()); + pool->jobs_.pop_front(); + } + job(); + } + return nullptr; + } + + std::mutex mutex_; + std::condition_variable cv_; + std::deque> jobs_; + size_t idle_ = 0; + unsigned threads_ = 0; + unsigned maxThreads_ = 1; +}; + +// Whether `flags` turn lazy compilation off, read the way V8's +// SetFlagsFromString reads a bool flag: whitespace-separated, an optional +// second dash, a "no"/"no-" negation, `_` and `-` alike, the last occurrence +// winning, nothing after a bare "--". V8 has no public flag getter. +bool FlagsDisableLazyCompile(const std::string& flags) { + static constexpr const char* kSpace = " \t\n\v\f\r"; + bool lazy = true; + size_t pos = 0; + while (pos < flags.size()) { + const size_t start = flags.find_first_not_of(kSpace, pos); + if (start == std::string::npos) break; + size_t end = flags.find_first_of(kSpace, start); + if (end == std::string::npos) end = flags.size(); + pos = end; + std::string arg = flags.substr(start, end - start); + if (arg == "--") break; + if (arg.size() < 2 || arg[0] != '-') continue; + std::replace(arg.begin(), arg.end(), '_', '-'); + size_t name = arg[1] == '-' ? 2 : 1; + bool negated = false; + if (arg.compare(name, 2, "no") == 0) { + name += 2; + if (name < arg.size() && arg[name] == '-') name++; + negated = true; + } + if (arg.compare(name, std::string::npos, "lazy") == 0 || + arg.compare(name, 5, "lazy=") == 0) { + lazy = !negated; + } + } + return !lazy; +} + +// Isolate's Locker, at fetch issue. Null when V8 declines to stream; otherwise +// the compile is parked in the loader state, its stream empty until the +// transport feeds it. +std::shared_ptr BeginStreamedCompile(v8::Isolate* isolate, + ModuleLoaderState& state) { + auto compile = std::make_unique(); + auto stream = std::make_unique(); + BodySourceStream* streamPtr = stream.get(); + compile->source = std::make_unique( + std::move(stream), v8::ScriptCompiler::StreamedSource::UTF8); + // Streaming follows --lazy-streaming, not --lazy, so an app's --no-lazy has + // to be passed explicitly. + const auto options = g_eagerStreamedCompiles ? v8::ScriptCompiler::kEagerCompile + : v8::ScriptCompiler::kNoCompileOptions; + compile->task.reset(v8::ScriptCompiler::StartStreaming( + isolate, compile->source.get(), v8::ScriptType::kModule, options)); + if (compile->task == nullptr) return nullptr; + auto ticket = std::make_shared(); + ticket->id = state.nextStreamedCompileId++; + ticket->gate = state.streamGate; + ticket->stream = streamPtr; + ticket->task = compile->task.get(); + state.streamedCompiles.emplace(ticket->id, std::move(compile)); + return ticket; +} + +// The issuing isolate's compile for `ticket`, now owned by the caller. +// Isolate's Locker only. +std::unique_ptr TakeStreamedCompile( + v8::Isolate* isolate, const StreamTicket* ticket) { + auto* state = ticket != nullptr ? ModuleLoaderStateFor(isolate) : nullptr; + if (state == nullptr) return nullptr; + auto it = state->streamedCompiles.find(ticket->id); + if (it == state->streamedCompiles.end()) return nullptr; + std::unique_ptr compile = std::move(it->second); + state->streamedCompiles.erase(it); + return compile; +} + +bool IsAscii(const std::string& bytes) { + const unsigned char* p = reinterpret_cast(bytes.data()); + const size_t n = bytes.size(); + size_t i = 0; + for (; i + sizeof(uint64_t) <= n; i += sizeof(uint64_t)) { + uint64_t word; + memcpy(&word, p + i, sizeof(word)); + if (word & 0x8080808080808080ull) return false; + } + for (; i < n; i++) { + if (p[i] & 0x80) return false; + } + return true; +} + +bool IsStreamableBody(const ModuleFetchResult& result) { + // The stream skips a leading UTF-8 BOM that the full source string would + // keep, which would shift every position the finalized script reports. + return result.ok && result.kind == ModuleResponseKind::kJavaScript && + result.body.size() >= kStreamingCompileThresholdBytes && + !StartsWith(result.body, "\xEF\xBB\xBF"); +} + +// Transport thread. Feeds `result` to the ticket's stream and runs the compile +// on the StreamCompilePool, which calls `postCompletion` once Run() has +// returned. Returns false, without running anything, when the body is not to +// be streamed; the caller then posts the completion itself. +bool DispatchStreamedCompile(const std::shared_ptr& load, + const std::shared_ptr& ticket, + const std::shared_ptr& result, + std::function postCompletion) { + if (!IsStreamableBody(*result)) return false; + if (!ticket->gate->TryEnter()) return false; + if (load->dead.load(std::memory_order_acquire)) { + ticket->gate->Leave(); + return false; + } + const bool posted = StreamCompilePool::Shared().Post( + [load = load, ticket = ticket, result = result, + postCompletion = std::move(postCompletion)]() mutable { + if (!load->dead.load(std::memory_order_acquire)) { + const std::string& body = result->body; + std::unique_ptr chunk(new uint8_t[body.size()]); + memcpy(chunk.get(), body.data(), body.size()); + ticket->ascii = IsAscii(body); + ticket->stream->Feed(std::move(chunk), body.size()); + g_streamedCompileCounters.running.fetch_add(1, std::memory_order_relaxed); + ticket->task->Run(); + g_streamedCompileCounters.running.fetch_sub(1, std::memory_order_relaxed); + ticket->ran = true; + // Posted before Leave(): teardown stops the event loop only after + // the gate drains, so this post cannot be dropped off the isolate + // thread. + postCompletion(); + } + // Released before Leave(): once the gate drains, teardown may drop the + // runtime's own references, and the last one to the event loop must + // not be released on this thread. + postCompletion = nullptr; + load.reset(); + result.reset(); + ticket->gate->Leave(); + }); + if (!posted) { + ticket->gate->Leave(); + return false; + } + return true; +} } // namespace +void NoteAppliedV8Flags(const std::string& flags) { + g_eagerStreamedCompiles = FlagsDisableLazyCompile(flags); +} + bool HasPendingAsyncModuleGraphWork() { return AsyncGraphLoad::g_asyncGraphLoadsInFlightCounter().load( std::memory_order_acquire) > 0; @@ -1494,6 +1936,41 @@ static void KillAsyncGraphLoadsForIsolate(v8::Isolate* isolate) { state->asyncGraphLoads.clear(); } +// Isolate-teardown hook, after KillAsyncGraphLoadsForIsolate and before the +// event loop stops: closes the streaming gate, waits out every Run() in flight +// and destroys the compiles that will never be finalized, all while the +// isolate is alive and locked. A Run() parked on a GC request is released by +// running the loop's nestable v8 tasks, where V8 posted the request; that +// drain reads the loop's queues directly and never polls the looper, so it is +// safe from inside a looper callback. +// +// No JS may run in that drain: the runtime is half torn down (Java side +// detached, child workers terminated, loads killed). A terminated isolate can +// still hold microtasks, which the per-task checkpoint would run, so they are +// suppressed; a V8 task that calls into JS directly (a wasm start function +// run by an async instantiate) gets an exception instead. +static void DrainStreamedCompilesForIsolate(v8::Isolate* isolate) { + auto* state = ModuleLoaderStateFor(isolate); + if (state == nullptr) return; + Runtime* runtime = Runtime::TryGetRuntime(isolate); + std::shared_ptr loop = + runtime != nullptr ? runtime->GetEventLoop() : nullptr; + { + v8::Isolate::SuppressMicrotaskExecutionScope noMicrotasks(isolate); + v8::Isolate::DisallowJavascriptExecutionScope noJs( + isolate, v8::Isolate::DisallowJavascriptExecutionScope::THROW_ON_FAILURE); + const bool waited = state->streamGate->CloseAndDrain([&loop]() { + if (loop != nullptr) { + loop->RunNestableV8Tasks(); + } + }); + if (waited) { + g_streamedCompileCounters.teardownWaits.fetch_add(1, std::memory_order_relaxed); + } + } + state->streamedCompiles.clear(); +} + static void AsyncGraphEnqueue(const std::shared_ptr& load, const ModuleResolution& resolution); @@ -1591,7 +2068,9 @@ static void AsyncGraphMaybeComplete(const std::shared_ptr& load, // isolate the same way other cross-thread callbacks do. static void AsyncGraphOnFetchCompleted( const std::shared_ptr& load, const std::string& url, - const std::shared_ptr& fetched) { + const std::shared_ptr& fetched, + const std::shared_ptr& ticket) { + // Dead loads leave their streamed compile to DrainStreamedCompilesForIsolate. if (load->dead.load(std::memory_order_acquire)) return; v8::Isolate* isolate = load->isolate; if (Runtime::TryGetRuntime(isolate) == nullptr) return; @@ -1599,6 +2078,9 @@ static void AsyncGraphOnFetchCompleted( v8::Locker locker(isolate); v8::Isolate::Scope isolate_scope(isolate); v8::HandleScope handle_scope(isolate); + std::unique_ptr streamed = + TakeStreamedCompile(isolate, ticket.get()); + const bool streamedRan = streamed != nullptr && ticket->ran; v8::Local context = load->context.Get(isolate); if (context.IsEmpty()) return; v8::Context::Scope context_scope(context); @@ -1648,9 +2130,20 @@ static void AsyncGraphOnFetchCompleted( // compile exception must be consumed here rather than left pending; its // text goes into the load's own failure channel instead. v8::TryCatch tcCompile(isolate); - compiled = CompileModuleForResolveRegisterOnly(isolate, context, - fetched->body, key) - .ToLocal(&mod); + if (streamedRan) { + compiled = CompileStreamedModuleRegisterOnly( + isolate, context, *streamed, std::move(fetched->body), + ticket->ascii, key) + .ToLocal(&mod); + streamed.reset(); + } else { + if (IsStreamableBody(*fetched)) { + g_streamedCompileCounters.fellBack.fetch_add(1, std::memory_order_relaxed); + } + compiled = CompileModuleForResolveRegisterOnly(isolate, context, + fetched->body, key) + .ToLocal(&mod); + } if (!compiled) { compileError = DescribeCaughtError(isolate, context, tcCompile); } @@ -1762,9 +2255,10 @@ static void AsyncGraphEnqueue(const std::shared_ptr& load, load->pendingFetches++; std::shared_ptr loadRef = load; const std::string url = target; + std::shared_ptr ticket = BeginStreamedCompile(isolate, *moduleState); // The canonical key is computed here, on the isolate's thread; the fetch // carries it so background threads never touch per-isolate vocabulary. - FetchModuleBodyAsync(url, key, [loadRef, url](ModuleFetchResult result) { + FetchModuleBodyAsync(url, key, [loadRef, url, ticket](ModuleFetchResult result) { // Arbitrary thread. Hop to the isolate's home thread as a nestable v8 // foreground task — delivery is a property of the isolate, not of the // thread that started the fetch, and the pumped walk's @@ -1779,11 +2273,18 @@ static void AsyncGraphEnqueue(const std::shared_ptr& load, : nullptr; if (loop == nullptr) return; auto resultPtr = std::make_shared(std::move(result)); - loop->PostV8Task( - std::make_unique([loadRef, url, resultPtr]() { - AsyncGraphOnFetchCompleted(loadRef, url, resultPtr); - }), - /*nestable=*/true, /*delaySeconds=*/0); + auto postCompletion = [loop, loadRef, url, resultPtr, ticket]() { + loop->PostV8Task( + std::make_unique([loadRef, url, resultPtr, ticket]() { + AsyncGraphOnFetchCompleted(loadRef, url, resultPtr, ticket); + }), + /*nestable=*/true, /*delaySeconds=*/0); + }; + if (ticket != nullptr && + DispatchStreamedCompile(loadRef, ticket, resultPtr, postCompletion)) { + return; + } + postCompletion(); }); } @@ -3898,6 +4399,38 @@ bool BuildNsModuleBinding(v8::Local context, v8::Local .FromMaybe(false)) { return false; } + + auto statsCb = [](const v8::FunctionCallbackInfo& info) { + v8::Isolate* iso = info.GetIsolate(); + v8::Local ctx = iso->GetCurrentContext(); + const std::pair fields[] = { + {"finalized", (double) g_streamedCompileCounters.finalized.load()}, + {"discarded", (double) g_streamedCompileCounters.discarded.load()}, + {"fellBack", (double) g_streamedCompileCounters.fellBack.load()}, + {"running", (double) g_streamedCompileCounters.running.load()}, + {"teardownWaits", (double) g_streamedCompileCounters.teardownWaits.load()}, + }; + v8::Local stats = v8::Object::New(iso); + for (const auto& field : fields) { + if (!stats->CreateDataProperty(ctx, ToV8String(iso, field.first), + v8::Number::New(iso, field.second)) + .FromMaybe(false)) { + return; + } + } + info.GetReturnValue().Set(stats); + }; + v8::Local statsFn; + if (!v8::Function::New(context, statsCb).ToLocal(&statsFn)) { + return false; + } + statsFn->SetName(ToV8String(isolate, "streamedCompileStats")); + if (!binding + ->CreateDataProperty(context, ToV8String(isolate, "streamedCompileStats"), + statsFn) + .FromMaybe(false)) { + return false; + } } return true; diff --git a/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.h b/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.h index b6c97316c..91b777a50 100644 --- a/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.h +++ b/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.h @@ -91,6 +91,10 @@ ModuleHandleMap* ModuleRegistryFor(v8::Isolate* isolate); // is destroyed with the isolate's RuntimeState. void QuiesceModuleLoadsForIsolate(v8::Isolate* isolate); +// The v8Flags string V8 was initialized with. Called once, before any isolate +// exists. +void NoteAppliedV8Flags(const std::string& flags); + // Utility to drop modules from the registry when compilation/instantiation // fails. Call on `isolate`'s own JS thread. void RemoveModuleFromRegistry(v8::Isolate* isolate, @@ -273,6 +277,9 @@ void SetCanonicalizationConfig(CanonicalizationConfig config); // - canonicalizeHttpUrlKey(url) (debug builds only; test diagnostic) // - remoteUrlMatchesAllowlist(url, entries) // (debug builds only; test diagnostic) +// - streamedCompileStats() (debug builds only; test diagnostic: +// process-wide counts of the paths large +// HTTP module bodies took) // // Worker teardown across HMR cycles is userland: the dev client intercepts // the global `Worker` constructor and terminates tracked instances diff --git a/test-app/runtime/src/main/cpp/Runtime.cpp b/test-app/runtime/src/main/cpp/Runtime.cpp index fdf465610..c45763ee1 100644 --- a/test-app/runtime/src/main/cpp/Runtime.cpp +++ b/test-app/runtime/src/main/cpp/Runtime.cpp @@ -849,6 +849,7 @@ static void InitializeV8() { // per isolate. Runtime::Init has already read them out of the Java config. V8::SetFlagsFromString(Constants::V8_STARTUP_FLAGS.c_str(), Constants::V8_STARTUP_FLAGS.size()); + tns::NoteAppliedV8Flags(Constants::V8_STARTUP_FLAGS); // wrap the default platform so foreground tasks ride each runtime thread's // Java Looper instead of sitting in never-pumped libplatform queues Runtime::platform = diff --git a/test-app/runtime/src/main/cpp/js/ns-module.js b/test-app/runtime/src/main/cpp/js/ns-module.js index 9d57e30ea..e92aba504 100644 --- a/test-app/runtime/src/main/cpp/js/ns-module.js +++ b/test-app/runtime/src/main/cpp/js/ns-module.js @@ -6,8 +6,8 @@ // and freezes the exports. // // Membership varies by build: -// - `canonicalizeHttpUrlKey` and `remoteUrlMatchesAllowlist` exist only in -// debug builds (test diagnostics). +// - `canonicalizeHttpUrlKey`, `remoteUrlMatchesAllowlist` and +// `streamedCompileStats` exist only in debug builds (test diagnostics). // Missing members are simply absent — never present-but-throwing — so // feature checks work. @@ -183,5 +183,8 @@ if (binding.canonicalizeHttpUrlKey !== undefined) { if (binding.remoteUrlMatchesAllowlist !== undefined) { surface.remoteUrlMatchesAllowlist = binding.remoteUrlMatchesAllowlist; } +if (binding.streamedCompileStats !== undefined) { + surface.streamedCompileStats = binding.streamedCompileStats; +} module.exports = ObjectFreeze(surface);