Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion doc/api/module.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
103 changes: 97 additions & 6 deletions src/compile_cache.cc
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
namespace node {

using v8::Function;
using v8::HandleScope;
using v8::Local;
using v8::Module;
using v8::ScriptCompiler;
Expand Down Expand Up @@ -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<char*>(headers), sizeof(headers));
const int r = uv_fs_read(nullptr, &req, file, &headers_buf, 1, 0, nullptr);
if (r != static_cast<int>(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
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -344,7 +379,7 @@ ScriptCompiler::CachedData* SerializeCodeCache(Local<WasmModuleObject> mod) {
}

template <typename T>
void CompileCacheHandler::MaybeSaveImpl(CompileCacheEntry* entry,
bool CompileCacheHandler::MaybeSaveImpl(CompileCacheEntry* entry,
Local<T> func_or_mod,
bool rejected) {
DCHECK_NOT_NULL(entry);
Expand All @@ -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<Module> 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<Function> 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,
Expand All @@ -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<ScriptCompiler::CachedData> 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_) {
Expand Down Expand Up @@ -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",
Expand All @@ -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<uint32_t>(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<char> data = SerializeEntry(entry);
const uint32_t* headers = reinterpret_cast<const uint32_t*>(data.data());
Expand Down
22 changes: 21 additions & 1 deletion src/compile_cache.h
Original file line number Diff line number Diff line change
Expand Up @@ -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<v8::Function> function;
v8::Global<v8::UnboundModuleScript> module_script;

// Copy the cache into a new store for V8 to consume. Caller takes
// ownership.
Expand Down Expand Up @@ -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<char> SerializeEntry(const CompileCacheEntry* entry);

// Returns true if the cache was not accepted and is produced by this
// process.
template <typename T>
void MaybeSaveImpl(CompileCacheEntry* entry,
bool MaybeSaveImpl(CompileCacheEntry* entry,
v8::Local<T> func_or_mod,
bool rejected);

Expand Down
40 changes: 40 additions & 0 deletions test/fixtures/compile-cache-after-execution.js
Original file line number Diff line number Diff line change
@@ -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');
}
});
22 changes: 22 additions & 0 deletions test/fixtures/compile-cache-after-execution.mjs
Original file line number Diff line number Diff line change
@@ -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();
});
Loading
Loading