From 70320909450887be5983d36eb03500029d38dd0e Mon Sep 17 00:00:00 2001 From: Max schwenk Date: Thu, 12 Nov 2026 12:08:33 -0500 Subject: [PATCH] module: produce the compile cache after execution The module compile cache serializes the V8 code cache of a module right after compiling it, before it runs. V8 compiles functions lazily, so that cache only holds the top-level code, and every function the module calls is compiled again from source in each process that loads it from the cache. For a CommonJS or ES module that missed the cache, keep the compiled wrapper function or module script, and serialize the cache again when it is written at exit or by module.flushCompileCache(), when it also holds the functions that ran. The cache produced at compilation is kept if it is larger: V8 flushes the bytecode of functions that have not run for a while, so a long-running process can lose eagerly compiled functions from the later one. Since the content of a cache now depends on what ran, a cache file for the same code is only replaced by a larger one, unless V8 rejected it. Refs: https://github.com/nodejs/node/issues/52696 --- doc/api/module.md | 6 +- src/compile_cache.cc | 103 +++++++++++- src/compile_cache.h | 22 ++- .../fixtures/compile-cache-after-execution.js | 40 +++++ .../compile-cache-after-execution.mjs | 22 +++ .../test-compile-cache-after-execution.js | 155 ++++++++++++++++++ 6 files changed, 340 insertions(+), 8 deletions(-) create mode 100644 test/fixtures/compile-cache-after-execution.js create mode 100644 test/fixtures/compile-cache-after-execution.mjs create mode 100644 test/parallel/test-compile-cache-after-execution.js diff --git a/doc/api/module.md b/doc/api/module.md index f86167e8d44f..5278a7cd52cc 100644 --- a/doc/api/module.md +++ b/doc/api/module.md @@ -392,7 +392,11 @@ undesired behaviors (e.g. less precise test coverage). At the moment, when the compile cache is enabled and a module is loaded afresh, the code cache is generated from the compiled code immediately, but will only be written -to disk when the Node.js instance is about to exit. This is subject to change. The +to disk when the Node.js instance is about to exit. For CommonJS and ECMAScript modules, +the code cache is generated again when it is written, so that it also contains the +functions that have run by then, which V8 would otherwise compile again in every process +that loads the module, and the larger of the two is written. A cache file for the same +code is only replaced by a larger one, unless V8 rejected it. This is subject to change. The [`module.flushCompileCache()`][] method can be used to ensure the accumulated code cache is flushed to disk in case the application wants to spawn other Node.js instances and let them share the cache long before the parent exits. diff --git a/src/compile_cache.cc b/src/compile_cache.cc index 90ed63f448ae..03b94928ebcf 100644 --- a/src/compile_cache.cc +++ b/src/compile_cache.cc @@ -19,6 +19,7 @@ namespace node { using v8::Function; +using v8::HandleScope; using v8::Local; using v8::Module; using v8::ScriptCompiler; @@ -232,6 +233,35 @@ void CompileCacheHandler::ReadCacheFile(CompileCacheEntry* entry) { Debug(" success, size=%d\n", total_read); } +uint32_t CompileCacheHandler::ReadCacheSizeOnDisk( + const CompileCacheEntry* entry) { + uv_fs_t req; + auto defer_req_cleanup = OnScopeLeave([&req]() { uv_fs_req_cleanup(&req); }); + uv_file file = uv_fs_open( + nullptr, &req, entry->cache_filename.c_str(), O_RDONLY, 0, nullptr); + if (req.result < 0) { + return 0; + } + uv_fs_req_cleanup(&req); + auto defer_close = OnScopeLeave([file]() { + uv_fs_t close_req; + CHECK_EQ(0, uv_fs_close(nullptr, &close_req, file, nullptr)); + uv_fs_req_cleanup(&close_req); + }); + + uint32_t headers[kHeaderCount]; + uv_buf_t headers_buf = + uv_buf_init(reinterpret_cast(headers), sizeof(headers)); + const int r = uv_fs_read(nullptr, &req, file, &headers_buf, 1, 0, nullptr); + if (r != static_cast(headers_buf.len) || + headers[kMagicNumberOffset] != kCacheMagicNumber || + headers[kCodeSizeOffset] != entry->code_size || + headers[kCodeHashOffset] != entry->code_hash) { + return 0; + } + return headers[kCacheSizeOffset]; +} + static std::string GetRelativePath(std::string_view path, std::string_view base) { // On Windows, the native encoding is UTF-16, so we need to convert @@ -315,6 +345,11 @@ CompileCacheEntry* CompileCacheHandler::GetOrInsert(const uint8_t* code, result->source_filename = filename_utf8.ToString(); result->cache = nullptr; result->type = type; + // An existing entry is reused for changed code, so drop the code compiled + // from the old one. + result->rejected = false; + result->function.Reset(); + result->module_script.Reset(); // TODO(joyeecheung): if we fail enough times, stop trying for any future // files. @@ -344,7 +379,7 @@ ScriptCompiler::CachedData* SerializeCodeCache(Local mod) { } template -void CompileCacheHandler::MaybeSaveImpl(CompileCacheEntry* entry, +bool CompileCacheHandler::MaybeSaveImpl(CompileCacheEntry* entry, Local func_or_mod, bool rejected) { DCHECK_NOT_NULL(entry); @@ -356,38 +391,46 @@ void CompileCacheHandler::MaybeSaveImpl(CompileCacheEntry* entry, : "accepted"); if (entry->cache != nullptr && !rejected) { // accepted Debug("keeping the in-memory entry\n"); - return; + return false; } if (read_only_) { Debug("read-only, not serializing\n"); - return; + return false; } Debug("%s the in-memory entry\n", entry->cache == nullptr ? "initializing" : "refreshing"); + entry->rejected = rejected; + entry->cache.reset(); ScriptCompiler::CachedData* data = SerializeCodeCache(func_or_mod); if (data == nullptr) { Debug("[compile cache] nothing to serialize for %s %s\n", entry->type_name(), entry->source_filename); - return; + return true; } DCHECK_EQ(data->buffer_policy, ScriptCompiler::CachedData::BufferOwned); entry->refreshed = true; entry->cache.reset(data); + return true; } void CompileCacheHandler::MaybeSave(CompileCacheEntry* entry, Local mod, bool rejected) { DCHECK(mod->IsSourceTextModule()); - MaybeSaveImpl(entry, mod, rejected); + if (MaybeSaveImpl(entry, mod, rejected)) { + entry->module_script.Reset(isolate_, mod->GetUnboundModuleScript()); + } } void CompileCacheHandler::MaybeSave(CompileCacheEntry* entry, Local func, bool rejected) { - MaybeSaveImpl(entry, func, rejected); + if (MaybeSaveImpl(entry, func, rejected)) { + // Nothing else keeps the CommonJS wrapper function alive once it ran. + entry->function.Reset(isolate_, func); + } } void CompileCacheHandler::MaybeSave(CompileCacheEntry* entry, @@ -397,6 +440,36 @@ void CompileCacheHandler::MaybeSave(CompileCacheEntry* entry, MaybeSaveImpl(entry, mod, rejected); } +void CompileCacheHandler::SerializeAfterExecution(CompileCacheEntry* entry) { + if (entry->function.IsEmpty() && entry->module_script.IsEmpty()) { + return; + } + HandleScope handle_scope(isolate_); + std::unique_ptr data( + entry->function.IsEmpty() + ? ScriptCompiler::CreateCodeCache(entry->module_script.Get(isolate_)) + : SerializeCodeCache(entry->function.Get(isolate_))); + entry->function.Reset(); + entry->module_script.Reset(); + // V8 flushes the bytecode of functions that have not run for a while, the + // top level included, so in a long-running process the cache produced at + // compilation can be the larger one. + int compiled_size = entry->cache == nullptr ? 0 : entry->cache->length; + int executed_size = data == nullptr ? 0 : data->length; + Debug("[compile cache] cache for %s %s after execution is %d bytes, %d at " + "compilation, keeping the one %s\n", + entry->type_name(), + entry->source_filename, + executed_size, + compiled_size, + executed_size > compiled_size ? "after execution" : "from compilation"); + if (executed_size > compiled_size) { + DCHECK_EQ(data->buffer_policy, ScriptCompiler::CachedData::BufferOwned); + entry->cache = std::move(data); + entry->refreshed = true; + } +} + void CompileCacheHandler::MaybeSave(CompileCacheEntry* entry, std::string_view transpiled) { if (read_only_) { @@ -451,6 +524,7 @@ void CompileCacheHandler::Persist() { for (auto& pair : compiler_cache_store_) { auto* entry = pair.second.get(); const char* type_name = entry->type_name(); + SerializeAfterExecution(entry); if (entry->cache == nullptr) { Debug("[compile cache] skip persisting %s %s because the cache was not " "initialized\n", @@ -472,6 +546,23 @@ void CompileCacheHandler::Persist() { entry->source_filename); continue; } + // Another process may have written a cache for the same code since this + // one read the file, e.g. when processes that loaded the same modules + // exit one after another. What the cache holds depends on what ran, so + // keep a file that is at least as large. A rejected one is replaced. + if (!entry->rejected) { + uint32_t size_on_disk = ReadCacheSizeOnDisk(entry); + uint32_t size = static_cast(entry->cache->length); + if (size_on_disk >= size) { + Debug("[compile cache] skip persisting %s %s because the cache on " + "disk is as large (%d >= %d bytes)\n", + type_name, + entry->source_filename, + size_on_disk, + size); + continue; + } + } std::vector data = SerializeEntry(entry); const uint32_t* headers = reinterpret_cast(data.data()); diff --git a/src/compile_cache.h b/src/compile_cache.h index ec405cf55b80..4ba0cd879a41 100644 --- a/src/compile_cache.h +++ b/src/compile_cache.h @@ -38,6 +38,17 @@ struct CompileCacheEntry { CachedCodeType type; bool refreshed = false; bool persisted = false; + // V8 rejected the cache read from disk, so the file is replaced even if it + // holds a larger cache. + bool rejected = false; + + // The compiled code of a CommonJS or ES module that missed the cache, kept + // to serialize the cache again when it is persisted. V8 compiles functions + // lazily, so the cache produced right after compilation only holds the top + // level, while one produced after the module ran also holds the functions + // that were called. + v8::Global function; + v8::Global module_script; // Copy the cache into a new store for V8 to consume. Caller takes // ownership. @@ -118,10 +129,19 @@ class CompileCacheHandler { private: void ReadCacheFile(CompileCacheEntry* entry); + // Size of the cache in the entry's file on disk if the file holds a cache + // for the same code, 0 otherwise. + uint32_t ReadCacheSizeOnDisk(const CompileCacheEntry* entry); + // Serializes the cache of the entry again from its compiled code, which has + // run by now, and keeps it if it is larger than the cache produced at + // compilation. + void SerializeAfterExecution(CompileCacheEntry* entry); static std::vector SerializeEntry(const CompileCacheEntry* entry); + // Returns true if the cache was not accepted and is produced by this + // process. template - void MaybeSaveImpl(CompileCacheEntry* entry, + bool MaybeSaveImpl(CompileCacheEntry* entry, v8::Local func_or_mod, bool rejected); diff --git a/test/fixtures/compile-cache-after-execution.js b/test/fixtures/compile-cache-after-execution.js new file mode 100644 index 000000000000..110c9c7c9ff8 --- /dev/null +++ b/test/fixtures/compile-cache-after-execution.js @@ -0,0 +1,40 @@ +'use strict'; + +// Used by test-compile-cache-after-execution.js. late() is only called after +// the module has been loaded, when it is named on the command line. + +// V8 compiles a function in parentheses eagerly, together with the top level. +const eager = (function() { + let sum = 0; + for (let i = 0; i < 10; i++) sum += i * 2; + return [sum].map((x) => x + 1); +})(); + +function body(n) { + let acc = 0; + for (let i = 0; i < n; i++) { + switch (i % 4) { + case 0: acc += i; break; + case 1: acc ^= i * 3; break; + case 2: acc = Math.imul(acc, 31) + String(i).length; break; + default: acc -= n; + } + } + return { acc, label: `n=${n}` }; +} +function atLoad() { return body(1).acc + [1, 2, 3].map((x) => x * 2).length; } +function late() { return body(3).acc + [4, 5, 6].map((x) => x * 3).length; } + +atLoad(eager); +const args = process.argv.slice(2); +setImmediate(() => { + if (args.includes('late')) late(); + // With --stress-flush-code, this flushes the bytecode of every function + // that is not running, as V8 does after a few minutes without running it. + if (args.includes('gc')) globalThis.gc(); + if (args.includes('wait')) { + // Stay alive until the parent closes stdin. + process.stdin.resume(); + process.stdout.write('ready\n'); + } +}); diff --git a/test/fixtures/compile-cache-after-execution.mjs b/test/fixtures/compile-cache-after-execution.mjs new file mode 100644 index 000000000000..ae4767bd6bc4 --- /dev/null +++ b/test/fixtures/compile-cache-after-execution.mjs @@ -0,0 +1,22 @@ +// Used by test-compile-cache-after-execution.js. late() is only called after +// the module has been evaluated, when it is named on the command line. + +function body(n) { + let acc = 0; + for (let i = 0; i < n; i++) { + switch (i % 4) { + case 0: acc += i; break; + case 1: acc ^= i * 3; break; + case 2: acc = Math.imul(acc, 31) + String(i).length; break; + default: acc -= n; + } + } + return { acc, label: `n=${n}` }; +} +function atLoad() { return body(1).acc + [1, 2, 3].map((x) => x * 2).length; } +function late() { return body(3).acc + [4, 5, 6].map((x) => x * 3).length; } + +atLoad(); +setImmediate(() => { + if (process.argv.includes('late')) late(); +}); diff --git a/test/parallel/test-compile-cache-after-execution.js b/test/parallel/test-compile-cache-after-execution.js new file mode 100644 index 000000000000..69063a3a66ec --- /dev/null +++ b/test/parallel/test-compile-cache-after-execution.js @@ -0,0 +1,155 @@ +'use strict'; + +// This tests that the compile cache is produced again from the compiled code +// when it is persisted, after the code ran, so that functions first called +// after a module was loaded come from the cache in the next process instead +// of being compiled lazily again. + +const common = require('../common'); +const { spawnSyncAndAssert } = require('../common/child_process'); +const assert = require('assert'); +const { spawn } = require('child_process'); +const fixtures = require('../common/fixtures'); +const tmpdir = require('../common/tmpdir'); +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const zlib = require('zlib'); + +tmpdir.refresh(); +const cjs = fixtures.path('compile-cache-after-execution.js'); +const esm = fixtures.path('compile-cache-after-execution.mjs'); +const logFile = tmpdir.resolve('v8.log'); +// V8 only accepts a cache produced under the same flags, the name of the log +// file included, so all runs that log use the same flags. +const logFlags = [ + '--log-function-events', + `--logfile=${logFile}`, + '--no-logfile-per-isolate', +]; + +function env(dir) { + return { + ...process.env, + NODE_DEBUG_NATIVE: 'COMPILE_CACHE', + NODE_COMPILE_CACHE: dir, + }; +} + +function run(dir, flags, script, args, stderr) { + spawnSyncAndAssert(process.execPath, [...flags, script, ...args], { + env: env(dir), + cwd: tmpdir.path, + }, { + stderr(output) { + console.log(output); // Logging for debugging. + stderr?.(output); + return true; + }, + }); +} + +// Names of the functions that V8 compiled from source (not from a cache) in +// the last run that logged. +function compiledFromSource() { + const names = new Set(); + for (const line of fs.readFileSync(logFile, 'utf8').split('\n')) { + const fields = line.split(','); + if (fields[0] === 'function' && fields[1] === 'interpreter') { + names.add(fields.at(-1)); + } + } + return names; +} + +function cacheFile(dir) { + const [versionDir] = fs.readdirSync(dir); + const files = fs.readdirSync(path.join(dir, versionDir)); + assert.strictEqual(files.length, 1); + return path.join(dir, versionDir, files[0]); +} + +for (const [type, script] of [['CommonJS', cjs], ['ESM', esm]]) { + // A function that first ran after the module was loaded is in the cache. + const dir = tmpdir.resolve(`after-execution-${type}`); + run(dir, logFlags, script, ['late'], common.mustCall((output) => { + assert.match(output, new RegExp(`cache for ${type} .*after-execution\\.m?js after execution is \\d+ bytes, \\d+ at compilation, keeping the one after execution`)); + assert.match(output, new RegExp(`writing cache for ${type} .*after-execution\\.m?js.*success`)); + })); + assert(compiledFromSource().has('late')); + + run(dir, logFlags, script, ['late'], common.mustCall((output) => { + assert.match(output, /after-execution\.m?js was accepted, keeping the in-memory entry/); + })); + const compiled = compiledFromSource(); + assert(!compiled.has('atLoad')); + assert(!compiled.has('late')); +} + +{ + // V8 flushes the bytecode of functions that have not run for a while, + // including the top level, so in a long-running process the cache produced + // at compilation can be larger than the one produced at exit, and is kept. + // --stress-flush-code makes gc() flush all of it. + const dir = tmpdir.resolve('flushed'); + const flags = ['--expose-gc', '--stress-flush-code']; + run(dir, flags, cjs, ['late', 'gc'], common.mustCall((output) => { + assert.match(output, /cache for CommonJS .*after-execution\.js after execution is \d+ bytes, \d+ at compilation, keeping the one from compilation/); + assert.match(output, /writing cache for CommonJS .*after-execution\.js.*success/); + })); + run(dir, flags, cjs, [], common.mustCall((output) => { + assert.match(output, /after-execution\.js was accepted, keeping the in-memory entry/); + })); +} + +{ + // A cache that V8 rejected is replaced even if the file is larger. + const dir = tmpdir.resolve('rejected'); + run(dir, [], cjs, ['late']); + const file = cacheFile(dir); + const contents = fs.readFileSync(file); + // Change the magic number of V8's data, after the 5 uint32 of the header + // that Node.js writes, and update the hash of the data in that header. + contents[20] ^= 1; + contents[`writeUInt32${os.endianness()}`](zlib.crc32(contents.subarray(20)), 16); + fs.writeFileSync(file, contents); + run(dir, [], cjs, [], common.mustCall((output) => { + assert.match(output, /after-execution\.js was rejected, refreshing the in-memory entry/); + assert.match(output, /writing cache for CommonJS .*after-execution\.js.*success/); + })); + assert(fs.statSync(file).size < contents.length); + run(dir, [], cjs, [], common.mustCall((output) => { + assert.match(output, /after-execution\.js was accepted, keeping the in-memory entry/); + })); +} + +{ + // A process does not replace a cache file with a smaller one written by + // another process for the same code after it read the directory, e.g. by a + // process that ran more of the code and exited first. + const dir = tmpdir.resolve('concurrent'); + const waiting = spawn(process.execPath, [cjs, 'wait'], { + env: env(dir), + cwd: tmpdir.path, + stdio: ['pipe', 'pipe', 'pipe'], + }); + let stderr = ''; + waiting.stderr.setEncoding('utf8'); + waiting.stderr.on('data', (data) => { stderr += data; }); + waiting.stdout.setEncoding('utf8'); + waiting.stdout.once('data', common.mustCall((data) => { + assert.strictEqual(data, 'ready\n'); + run(dir, [], cjs, ['late'], common.mustCall((output) => { + assert.match(output, /writing cache for CommonJS .*after-execution\.js.*success/); + })); + const written = fs.readFileSync(cacheFile(dir)); + waiting.on('close', common.mustCall((code) => { + console.log(stderr); + assert.strictEqual(code, 0); + assert.match(stderr, /after-execution\.js was not initialized, initializing the in-memory entry/); + assert.match(stderr, /skip persisting CommonJS .*after-execution\.js because the cache on disk is as large/); + assert.deepStrictEqual(fs.readFileSync(cacheFile(dir)), written); + })); + waiting.stdin.end(); + })); +}