Skip to content
Merged
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
31 changes: 20 additions & 11 deletions docs/reference/detail/new-module-registry.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,11 @@ The new module registry was designed to address several limitations of the legac
worker bundle ESM modules at startup.

4. **Cross-isolate compile cache.** ESM modules cache their V8 compiled bytecode
in a `kj::MutexGuarded` field on the `Module` object itself. When a second
isolate imports the same module, the cached bytecode is consumed, skipping
recompilation. If the embedder gives isolates a code cache store
in a `kj::MutexGuarded` field on the `Module` object itself. The second
isolate to compile a module generates the bytecode, and later isolates
consume it, skipping recompilation. The first isolate does not serialize, so
a module compiled by only one isolate never pays for it. If the embedder
gives isolates a code cache store
(`jsg::CodeCacheStore`, see `jsg/code-cache.h`), bundle, builtin and fallback
modules use the store when a cache key is available. Both registries share
the store. Embedded builtin bytecode takes precedence. Otherwise, compilation
Expand Down Expand Up @@ -214,9 +216,10 @@ consumption through `CompilationObserver::onCompileHintsConsumed`.
Embedded bytecode takes precedence. For bundle modules with a `codeCacheKey`, an
installed isolate code cache takes precedence on both misses and hits. Modules
without an applicable store use the definition-local shared slot: existing bytecode
takes precedence, while an empty slot compiles with hints and can cache the result
for subsequent isolates. Hint production bypasses caches and supplied hints. Missing
hints preserve ordinary source compilation, and builtins do not consume bundle hints.
takes precedence, while an empty slot compiles with hints and, from the second
compile on, caches the result for subsequent isolates. Hint production bypasses
caches and supplied hints. Missing hints preserve ordinary source compilation, and
builtins do not consume bundle hints.

#### Source Encoding (`EncodedSource`)

Expand Down Expand Up @@ -247,19 +250,25 @@ and the shared compile cache stays consistent.
First isolate compiles module:
1. lockShared(sharedCompileCache) -> empty -> no cached data
2. CompileModule(source, supplied hints if present) -> v8::Module
3. lockExclusive(sharedCompileCache) -> still empty?
-> CreateCodeCache(module) -> store Own<CachedData>
3. lockExclusive(sharedCompileCache) -> still empty, not yet compiled?
-> mark compiled, no serialization

Second isolate compiles same module:
1. lockShared(sharedCompileCache) -> empty -> no cached data
2. CompileModule(source, supplied hints if present) -> v8::Module
3. lockExclusive(sharedCompileCache) -> still empty, already compiled?
-> CreateCodeCache(module) -> store Own<CachedData>

Later isolates compile same module:
1. lockShared(sharedCompileCache) -> has data -> borrow bytes under lock
-> kConsumeCodeCache -> CompileModule(source, cache)
2. No exclusive lock needed (cache already populated)
```

Rejected bytecode is cleared under the exclusive lock only if the slot's
generation has not changed, preserving replacements made by another replica.
Snapshot preparation can consume existing bytecode but never generates or
regenerates an entry.
Snapshot preparation can consume existing bytecode but never marks, generates
or regenerates an entry.

#### Code cache store

Expand Down Expand Up @@ -893,7 +902,7 @@ returning a rejected promise with the cached exception.
O(n) reverse scan is eliminated.

4. **Cross-isolate caching.** ESM compile cache and Wasm compiled modules are
shared across isolate replicas, reducing startup time for subsequent replicas.
shared across isolate replicas, reducing startup time for later replicas.
With a code cache store, bundle, builtin and fallback module caches are shared
across registries. Builtin bundles consume embedded build-time caches first.
Runtime cache production is deferred until startup evaluation completes;
Expand Down
49 changes: 39 additions & 10 deletions src/workerd/jsg/code-cache-test.c++
Original file line number Diff line number Diff line change
Expand Up @@ -544,10 +544,34 @@ void compileSharedModule(
KJ_EXPECT(JsValue(check(ns->Get(js.v8Context(), js.str("value"_kj)))).toString(js) == "6");
}

void compileInFreshIsolate(const SharedModuleCompilationCache& cache, CountingObserver& observer) {
withIsolate({}, observer, Defer::NO, [&](Lock& js) { compileSharedModule(js, cache, observer); });
}

// Compiles in two isolates, the first of which only marks the slot, so that it holds bytecode.
void populateSharedSlot(const SharedModuleCompilationCache& cache, CountingObserver& observer) {
compileInFreshIsolate(cache, observer);
compileInFreshIsolate(cache, observer);
}

KJ_TEST("A shared slot generates bytecode when a second replica compiles from source") {
SharedModuleCompilationCache cache;
CountingObserver observer;
compileInFreshIsolate(cache, observer);
KJ_EXPECT(observer.generated == 0);
compileInFreshIsolate(cache, observer);
KJ_EXPECT(observer.generated == 1);
KJ_EXPECT(observer.found == 0);
compileInFreshIsolate(cache, observer);
KJ_EXPECT(observer.found == 1);
KJ_EXPECT(observer.generated == 1);
KJ_EXPECT(observer.rejected == 0);
}

void expectSharedSlotRejected(size_t corruptOffset, CompatibilityCheckResult expectedCheck) {
SharedModuleCompilationCache cache;
CountingObserver observer;
withIsolate({}, observer, Defer::NO, [&](Lock& js) { compileSharedModule(js, cache, observer); });
populateSharedSlot(cache, observer);
KJ_EXPECT(observer.generated == 1);
SharedModuleCompilationCacheTestAccess::corrupt(cache, corruptOffset);
withIsolate({}, observer, Defer::NO, [&](Lock& js) {
Expand All @@ -558,7 +582,7 @@ void expectSharedSlotRejected(size_t corruptOffset, CompatibilityCheckResult exp
KJ_EXPECT(observer.rejected == 1);
KJ_EXPECT(observer.generated == 2);
KJ_EXPECT(observer.found == 0);
withIsolate({}, observer, Defer::NO, [&](Lock& js) { compileSharedModule(js, cache, observer); });
compileInFreshIsolate(cache, observer);
KJ_EXPECT(observer.found == 1);
KJ_EXPECT(observer.generated == 2);
KJ_EXPECT(observer.rejected == 1);
Expand All @@ -574,7 +598,7 @@ KJ_TEST("Shared slot rejection preserves a replacement made before taking the ex
SharedModuleCompilationCache cache;
CountingObserver observer;
CountingObserver replacementObserver;
withIsolate({}, observer, Defer::NO, [&](Lock& js) { compileSharedModule(js, cache, observer); });
populateSharedSlot(cache, observer);
SharedModuleCompilationCacheTestAccess::corrupt(cache, FLAGS_HASH_OFFSET);
withIsolate({}, observer, Defer::NO, [&](Lock& js) {
// The observer runs after the read lock is released, before the write lock is acquired.
Expand All @@ -587,7 +611,7 @@ KJ_TEST("Shared slot rejection preserves a replacement made before taking the ex
KJ_EXPECT(observer.generated == 1);
KJ_EXPECT(replacementObserver.rejected == 1);
KJ_EXPECT(replacementObserver.generated == 1);
withIsolate({}, observer, Defer::NO, [&](Lock& js) { compileSharedModule(js, cache, observer); });
compileInFreshIsolate(cache, observer);
KJ_EXPECT(observer.found == 1);
KJ_EXPECT(observer.generated == 1);
}
Expand All @@ -605,7 +629,10 @@ KJ_TEST("Snapshot preparation consumes shared slots without generating or regene
};
snapshotCompile();
KJ_EXPECT(observer.generated == 0);
withIsolate({}, observer, Defer::NO, [&](Lock& js) { compileSharedModule(js, cache, observer); });
// Snapshot preparation does not mark the slot, so this is still the first compile from source.
compileInFreshIsolate(cache, observer);
KJ_EXPECT(observer.generated == 0);
compileInFreshIsolate(cache, observer);
KJ_EXPECT(observer.generated == 1);
snapshotCompile();
KJ_EXPECT(observer.found == 1);
Expand All @@ -614,7 +641,7 @@ KJ_TEST("Snapshot preparation consumes shared slots without generating or regene
snapshotCompile();
KJ_EXPECT(observer.rejected == 1);
KJ_EXPECT(observer.generated == 1);
withIsolate({}, observer, Defer::NO, [&](Lock& js) { compileSharedModule(js, cache, observer); });
compileInFreshIsolate(cache, observer);
KJ_EXPECT(observer.generated == 2);
KJ_EXPECT(observer.rejected == 1);
KJ_EXPECT(observer.generationFailed == 0);
Expand Down Expand Up @@ -915,15 +942,16 @@ KJ_TEST("New registry: isolates with separate registries share the store") {
using Options = modules::ModuleRegistry::Builder::Options;
evalWithFreshRegistry(Options::CODE_CACHE_KEYS);
evalWithFreshRegistry(Options::CODE_CACHE_KEYS);
// A registry built without code cache keys does not use the store.
// A registry built without code cache keys does not use the store, and its one isolate does
// not generate bytecode into the definition's slot.
evalWithFreshRegistry(Options::NONE);

auto lock = store->state.lockShared();
KJ_EXPECT(lock->lookups == 2);
KJ_EXPECT(lock->hits == 1);
KJ_EXPECT(lock->inserts == 1);
KJ_EXPECT(observer.found == 1);
KJ_EXPECT(observer.generated == 2);
KJ_EXPECT(observer.generated == 1);
}

kj::Arc<modules::ModuleRegistry> newLazyModuleRegistry(
Expand Down Expand Up @@ -984,11 +1012,12 @@ KJ_TEST("New registry: an unkeyed module consumes hints despite an installed cod
CountingObserver observer;
int hints[] = {16};
auto registry = newLazyModuleRegistry(modules::ModuleRegistry::Builder::Options::NONE, hints);
for (auto i KJ_UNUSED: kj::zeroTo(2)) {
// The second isolate generates the slot's bytecode, which the third consumes.
for (auto i: kj::zeroTo(3)) {
withIsolate(kj::atomicAddRef(*store), observer, Defer::YES, [&](jsg::Lock& js) {
evalNewRegistry(js, *registry, observer, CollectCompileHints::NO);
}, UseNewModuleRegistry::YES);
KJ_EXPECT(observer.hintsConsumed == 1);
KJ_EXPECT(observer.hintsConsumed == kj::min(i + 1, 2));
}
auto lock = store->state.lockShared();
KJ_EXPECT(lock->lookups == 0);
Expand Down
6 changes: 5 additions & 1 deletion src/workerd/jsg/compilation.c++
Original file line number Diff line number Diff line change
Expand Up @@ -221,7 +221,11 @@ v8::MaybeLocal<v8::Module> SharedModuleCompilationCache::compile(Lock& js,
if (lock->generation == generation) lock->data = kj::none;
}
if (lock->data == kj::none && !js.isPreparingSnapshot()) {
if (auto ptr = v8::ScriptCompiler::CreateCodeCache(module->GetUnboundModuleScript())) {
if (!lock->compiled) {
// Serializing is wasted work unless another replica compiles this definition, so the
// first one only marks the slot.
lock->compiled = true;
} else if (auto ptr = v8::ScriptCompiler::CreateCodeCache(module->GetUnboundModuleScript())) {
lock->data = kj::Own<v8::ScriptCompiler::CachedData>(
ptr, kj::_::HeapDisposer<v8::ScriptCompiler::CachedData>::instance);
++lock->generation;
Expand Down
8 changes: 6 additions & 2 deletions src/workerd/jsg/compilation.h
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,10 @@ kj::Array<int> getProducedCompileHints(Lock& js, v8::Local<v8::Module> module);
class SharedModuleCompilationCache {
public:
// Compiles using the slot, regenerating rejected bytecode. An empty slot uses supplied hints
// for source compilation. Snapshot preparation consumes existing bytecode but never generates
// it, because V8 forbids serialization in that phase.
// for source compilation. The first compile from source only marks the slot: bytecode is
// generated by the next replica that misses, so a definition compiled by a single isolate never
// pays for serialization. Snapshot preparation consumes existing bytecode but neither marks nor
// generates it, because V8 forbids serialization in that phase.
v8::MaybeLocal<v8::Module> compile(Lock& js,
v8::Local<v8::String> source,
const v8::ScriptOrigin& origin,
Expand All @@ -60,6 +62,8 @@ class SharedModuleCompilationCache {
kj::Maybe<kj::Own<v8::ScriptCompiler::CachedData>> data;
// Distinguishes replacements even if the allocator reuses a rejected entry's address.
uint64_t generation = 0;
// Set by the first compile from source outside snapshot preparation.
bool compiled = false;
};
kj::MutexGuarded<State> cachedData;

Expand Down
9 changes: 7 additions & 2 deletions src/workerd/jsg/modules-compile-hints-test.c++
Original file line number Diff line number Diff line change
Expand Up @@ -232,11 +232,16 @@ KJ_TEST("the new registry consumes copied hints and prefers its shared code cach
KJ_EXPECT(observer.calls == 1);
KJ_EXPECT(observer.lastHintCount == 3);
KJ_EXPECT(observer.lastEagerFunctionCount == 2);
KJ_EXPECT(observer.cachesGenerated == 0);

// A second isolate also compiles with the hints, and generates bytecode for later replicas.
withNewRegistry(*registry, evaluate, CollectCompileHints::NO, observer);
KJ_EXPECT(observer.calls == 2);
KJ_EXPECT(observer.cachesGenerated == 1);

// A second isolate consumes the bytecode generated by the hinted compilation.
// A third isolate consumes the bytecode generated by the hinted compilation.
withNewRegistry(*registry, evaluate, CollectCompileHints::NO, observer);
KJ_EXPECT(observer.calls == 1);
KJ_EXPECT(observer.calls == 2);
KJ_EXPECT(observer.cachesFound == 1);
KJ_EXPECT(observer.cachesGenerated == 1);
}
Expand Down
29 changes: 14 additions & 15 deletions src/workerd/jsg/modules-new-test.c++
Original file line number Diff line number Diff line change
Expand Up @@ -2602,31 +2602,30 @@ KJ_TEST("ESM compile cache is reused across isolates") {
bundleBuilder.addEsmModule("foo", "export default 123;"_kjc);
auto registry = ModuleRegistry::Builder(BASE).add(bundleBuilder.finish()).finish();

{
auto compileInNewIsolate = [&]() {
PREAMBLE([&](Lock& js) {
auto attached = registry->attachToIsolate(js, observer);
KJ_ASSERT(ModuleRegistry::resolve(js, "foo").isNumber());
});
}
};

// The first isolate does not serialize: no other isolate may ever compile the module.
compileInNewIsolate();
auto first = observer.getCounts();
KJ_ASSERT(first.cacheGenerated == 1);
KJ_ASSERT(first.cacheGenerated == 0);
KJ_ASSERT(first.cacheFound == 0);
KJ_ASSERT(first.cacheRejected == 0);
KJ_ASSERT(first.cacheGenerationFailed == 0);

{
PREAMBLE([&](Lock& js) {
auto attached = registry->attachToIsolate(js, observer);
KJ_ASSERT(ModuleRegistry::resolve(js, "foo").isNumber());
});
}

compileInNewIsolate();
auto second = observer.getCounts();
KJ_ASSERT(second.cacheGenerated == 1);
KJ_ASSERT(second.cacheFound == 1);
KJ_ASSERT(second.cacheRejected == 0);
KJ_ASSERT(second.cacheGenerationFailed == 0);
KJ_ASSERT(second.cacheFound == 0);

compileInNewIsolate();
auto third = observer.getCounts();
KJ_ASSERT(third.cacheGenerated == 1);
KJ_ASSERT(third.cacheFound == 1);
KJ_ASSERT(third.cacheRejected == 0);
KJ_ASSERT(third.cacheGenerationFailed == 0);
}

// ======================================================================================
Expand Down
Loading