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
28 changes: 19 additions & 9 deletions docs/startup-snapshot.md
Original file line number Diff line number Diff line change
Expand Up @@ -118,8 +118,10 @@ all of these hold:
V8's cleanup task pops each cell and the callback call throws instead of running. No
JavaScript runs past step 2. Any such cell fails the zygote: those objects are C++-held
state the snapshot does not carry, and their cleanups must not be dropped silently.
4. Isolate-level handles are reset (the opaque template, `workerEnvObj`, `workerExportsObj`,
template handles drained from Rust JSG).
4. Isolate-level handles are reset (the opaque template, `workerEnvObj`, `workerExportsObj`).
The templates of Rust JSG resource types are first pinned at isolate level and recorded by
`TypeId` in `artifact.rustResourceTemplates` (`pinResourceTemplatesIntoSnapshot()`,
`src/rust/jsg/ffi.h`).
5. `bakeConstructorTemplatesIntoSnapshot()`: every materialized JSG resource constructor
template is pinned at isolate level and recorded, by position, in
`artifact.constructorTemplateIndices`.
Expand Down Expand Up @@ -193,6 +195,7 @@ long as the isolate does. In order:
| C++ callback addresses the blob refers to | `registerExternalReference()` table | `externalReferences` |
| `env` with its bindings, main module namespace | context-level `AddData`, fixed indices | `blob` (indices in `snapshot.h`) |
| JSG resource constructor templates | isolate-level `AddData`, by position | `constructorTemplateIndices` |
| Rust JSG resource templates | isolate-level `AddData`, by `TypeId` | `rustResourceTemplates` |
| Live JSG objects' native side | tag only (stateless) or `snapshotClone()`; wrapper payload = slot index | `liveWrappables` |
| References between those objects | slot indices, relinked after restore | `liveWrappables[].references` |
| Per-isolate bootstrap state | one pinned object | `bootstrapStateIndex` |
Expand Down Expand Up @@ -227,18 +230,24 @@ A JSG resource type whose instance can be alive when top-level evaluation ends n
been wrapped and so belongs to no isolate (the `Fetcher` a `WrappedBinding` copy holds, or the
`LoopbackDurableObjectClass` of a loopback namespace copy). It is called in the zygote on the
live original, and once more per started worker on the stored copy.
- for a Rust JSG resource, `#[jsg_resource(snapshot_stateless)]` (`UrlUtil`, `DnsUtil`,
`InspectorModule`), which requires `Default`. Every Rust resource shares one
CppHeapPointerTag, so the type cannot be recorded by tag alone: the Rust-side `Wrappable`'s
`snapshotClone()` asks the resource for a fresh instance
(`GarbageCollected::snapshot_recreate`) that stands in for the clone. See
`src/rust/jsg/README.md`.
- for a Rust JSG resource, an impl of `jsg::SnapshotTransfer` (`src/rust/jsg/snapshot.rs`); see
below. `#[jsg_resource(snapshot_stateless)]` (`UrlUtil`, `DnsUtil`, `InspectorModule`)
generates one, with an empty snapshot, for a type that implements `Default`. Every Rust
resource shares one CppHeapPointerTag, so a Rust type is never recorded by tag alone: it goes
through the Rust-side `Wrappable`'s `snapshotClone()`.

A type that holds a `jsg::Ref` to another transferred object whose identity JavaScript can see
also overrides `Wrappable::snapshotReferences()` and `snapshotRelink()`, as `Crypto` does for
`subtle`: the restored instance is built afresh, and would otherwise refer to a new object rather
than to the one behind the restored wrapper.

`jsg::SnapshotTransfer` covers both for a Rust type: `snapshot()` and `restore()` stand for the
two `snapshotClone()` calls, through an isolate-independent `Snapshot` value, and
`snapshot_references()` and `snapshot_relink()` for their C++ counterparts. A Worker started from the snapshot restores the Rust resource templates
into its new `Realm` (`restoreResourceTemplatesFromSnapshot()`) before anything is wrapped, so
that its new wrappers of a type and the restored ones share a template. `relinkReferences()` runs
with the new context entered, for the `Lock` of `snapshot_relink()`.

A type whose state lives on the context, and so does not exist yet when `snapshotClone()` runs
for the started worker, also overrides `Wrappable::snapshotContextReady()`. The file system
handles bind to the worker's VFS there, when the `Worker` constructor, having installed the VFS
Expand Down Expand Up @@ -340,12 +349,13 @@ once.
| Test | Covers |
| -------------------------------------------------------------------- | -------------------------------------------------------------------------- |
| `src/workerd/jsg/snapshot-test.c++` | restore-time globals: install, removal, rejection cases; live-wrappable round trip (stateless, cloned, dropped and untransferable types), `dropUnreachableWrappables()` and `releaseSlotsWithChecks()` findings; FinalizationRegistry cleanups settled before the record, rejected after it |
| `src/rust/jsg-test/tests/startup_snapshot.rs` | Rust resources: state, shared templates, relinked references, and a type without `SnapshotTransfer` |
| `src/workerd/api/tests/startup-snapshot-globals-test` | top-level code touching `Error.stackTraceLimit`, `WebAssembly`, `Iterator`, `Temporal` (with and without the flag), a frozen `Date.prototype`, deleted restore-time globals, and the `process`/`Buffer` globals |
| `src/workerd/api/tests/startup-snapshot-listeners-test` | top-level `addEventListener()` across the snapshot: `once`, `passive`, an object listener's `handleEvent`, a replaced global `addEventListener`; `signal` fallback |
| `src/workerd/api/tests/startup-snapshot-functions-test` | a top-level `createRequire()` function across the snapshot; an `AsyncLocalStorage.bind()` function falls back |
| `src/workerd/api/tests/startup-snapshot-modules-test` | module identity across the snapshot (ESM, JSON, CJS, `node:buffer`) |
| `src/workerd/api/tests/startup-snapshot-new-module-registry-test` | the same with the new module registry: re-importing modules the top level imported (also under a query or a fragment, and `import()` from inside those) and builtins, importing one it never loaded, and `import.meta`, including an `import.meta.resolve` the top level kept |
| `src/workerd/api/tests/startup-snapshot-node-test` | Node.js API objects (`AsyncLocalStorage`, a root-frame `AsyncResource`, `node:diagnostics_channel`) across the snapshot; an `AsyncLocalStorage` with a default value and an `AsyncResource` created inside a frame fall back |
| `src/workerd/api/tests/startup-snapshot-node-test` | Node.js API objects (`AsyncLocalStorage`, a root-frame `AsyncResource`, `node:diagnostics_channel`, and the Rust resources behind `node:url` and `node:dns`) across the snapshot; an `AsyncLocalStorage` with a default value and an `AsyncResource` created inside a frame fall back |
| `src/workerd/api/tests/startup-snapshot-wrappables-test` | live objects (Headers, URL, TextEncoder, TextDecoder, crypto, navigator, performance, tracing spans started outside a request, file system handles to a `/tmp` file and to a bundle file, `node:fs`, bindings) and the identity of `crypto`, `crypto.subtle` and `navigator`, GC and a FinalizationRegistry cleanup across the snapshot; unclonable, `URLSearchParams`, a mid-stream `TextDecoder`, `performance` with a recorded entry and C++ streams left awaiting a `pull()` or `cancel()` fall back; a Worker on C++ streams otherwise transfers |
| `src/workerd/api/tests/startup-snapshot-bindings-test` | bindings captured at module scope (service stub, Durable Object namespace and ID) used at request time; an RPC method taken off a stub, `wrapped` and `cryptoKey` fall back |
| `src/workerd/server/tests/startup-snapshot-console` | console output printed once; no zygote under an inspector; a top level that throws gets no snapshot and its startup error is reported once |
Expand Down
12 changes: 12 additions & 0 deletions src/rust/jsg-compile-tests/erased-snapshot-relink-is-unsafe.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
// Copyright (c) 2026 Cloudflare, Inc.
// Licensed under the Apache 2.0 license found in the LICENSE file or at:
// https://opensource.org/licenses/Apache-2.0

// The type-erased relink reads each entry of `restored` as the address of a `Wrappable`, so safe
// code can't call it with addresses of its own.
use jsg::ErasedSnapshotTransfer;

fn relink(transfer: &dyn ErasedSnapshotTransfer, lock: &mut jsg::Lock<'_>) {
transfer.snapshot_relink(lock, &[8]);
//~^ ERROR E0133
}
34 changes: 34 additions & 0 deletions src/rust/jsg-compile-tests/snapshot-holds-no-gc-references.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// Copyright (c) 2026 Cloudflare, Inc.
// Licensed under the Apache 2.0 license found in the LICENSE file or at:
// https://opensource.org/licenses/Apache-2.0

// What a startup snapshot stores of a resource belongs to no isolate, so it can't hold a GC
// reference: a `Traced` type that does not claim `HoldsNoGcReferences` is refused even when it is
// `Send` and `Sync`. A resource takes its references back with `snapshot_relink` instead.
use jsg_macros::jsg_resource;

/// Traced by hand, so it may hold a GC reference.
struct MaybeHoldsReferences;

impl jsg::Traced for MaybeHoldsReferences {
fn trace(&self, _visitor: &mut jsg::v8::GcVisitor) {}
}

#[jsg_resource]
struct Holder;

#[jsg_resource]
impl Holder {}

impl jsg::SnapshotTransfer for Holder {
type Snapshot = MaybeHoldsReferences;
//~^ ERROR E0277: the trait bound `MaybeHoldsReferences: HoldsNoGcReferences` is not satisfied

fn snapshot(&self) -> MaybeHoldsReferences {
MaybeHoldsReferences
}

fn restore(_snapshot: &MaybeHoldsReferences) -> Self {
Self
}
}
4 changes: 2 additions & 2 deletions src/rust/jsg-macros/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -697,8 +697,8 @@ because `Traced::trace` receives `&self`. A field that holds a `jsg::Rc` or a

`#[jsg_resource(snapshot_stateless)]` declares that any fresh instance of the type is
interchangeable with any other, so a live instance can transfer through a V8 startup snapshot:
the macro adds a `GarbageCollected::snapshot_recreate` method that leaks a `Default` instance
for the wrapper restored from the snapshot. The type must implement `Default`. See
the macro implements `jsg::SnapshotTransfer` with an empty snapshot, restoring every instance
as the type's `Default`. The type must implement `Default`. See
`jsg/README.md` §Startup snapshots.

### Manual tracing with `custom_trace`
Expand Down
50 changes: 38 additions & 12 deletions src/rust/jsg-macros/resource.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,8 +84,8 @@ pub fn generate_resource_struct(attr: TokenStream, input: &syn::DeriveInput) ->
&name_str,
&memory_info.gc_fn,
&drop_detach_types(custom_trace, &fields),
&snapshot_recreate_method(snapshot_stateless),
);
let snapshot_transfer_impl = snapshot_stateless_impl(&name, snapshot_stateless);
let visit_for_memory_info_impl = &memory_info.visit_impl;

quote! {
Expand Down Expand Up @@ -153,6 +153,8 @@ pub fn generate_resource_struct(attr: TokenStream, input: &syn::DeriveInput) ->

#traced_impl
#gc_impl

#snapshot_transfer_impl
#visit_for_memory_info_impl
}
.into()
Expand Down Expand Up @@ -652,16 +654,26 @@ fn drop_probe_items() -> proc_macro2::TokenStream {
}
}

/// The `snapshot_recreate` method of a `#[jsg_resource(snapshot_stateless)]` type, which rebuilds
/// the instance behind every wrapper restored from a startup snapshot through its `Default` impl;
/// nothing for any other type.
fn snapshot_recreate_method(snapshot_stateless: bool) -> proc_macro2::TokenStream {
/// The `jsg::SnapshotTransfer` impl of a `#[jsg_resource(snapshot_stateless)]` type, whose
/// snapshot is empty and whose every restored instance is its `Default`; nothing for any other
/// type.
fn snapshot_stateless_impl(
name: &syn::Ident,
snapshot_stateless: bool,
) -> proc_macro2::TokenStream {
if !snapshot_stateless {
return quote! {};
}
quote! {
fn snapshot_recreate(&self) -> Option<jsg::SnapshotRecreated> {
Some(jsg::snapshot_recreate_leak(<Self as ::core::default::Default>::default()))
#[automatically_derived]
impl jsg::SnapshotTransfer for #name {
type Snapshot = ();

fn snapshot(&self) {}

fn restore((): &()) -> Self {
<Self as ::core::default::Default>::default()
}
}
}
}
Expand All @@ -684,15 +696,13 @@ fn drop_detach_types(
}

/// The `jsg::GarbageCollected` impl of a resource named `name`, with `memory_info_fn`, its
/// `memory_info` method or nothing, `drop_detach_types`, the types whose
/// `Traced::needs_drop_detach` makes the resource detach its references before it is dropped,
/// and `snapshot_recreate_fn`, its `snapshot_recreate` method or nothing.
/// `memory_info` method or nothing, and `drop_detach_types`, the types whose
/// `Traced::needs_drop_detach` makes the resource detach its references before it is dropped.
fn generate_gc_impl(
name: &syn::Ident,
name_str: &str,
memory_info_fn: &proc_macro2::TokenStream,
drop_detach_types: &[proc_macro2::TokenStream],
snapshot_recreate_fn: &proc_macro2::TokenStream,
) -> proc_macro2::TokenStream {
let drop_probe = drop_probe_items();
quote! {
Expand All @@ -717,7 +727,23 @@ fn generate_gc_impl(
.needs_drop_detach())*
}

#snapshot_recreate_fn
fn snapshot_transfer(&self) -> ::std::option::Option<&dyn jsg::ErasedSnapshotTransfer> {
// As in `has_drop_impl`: the inherent method applies exactly when the resource
// implements `jsg::SnapshotTransfer`.
struct Probe<'a, T>(&'a T);
trait NoSnapshotTransfer<'a> {
fn snapshot_transfer(&self) -> ::std::option::Option<&'a dyn jsg::ErasedSnapshotTransfer> {
::std::option::Option::None
}
}
impl<'a, T> NoSnapshotTransfer<'a> for Probe<'a, T> {}
impl<'a, T: jsg::SnapshotTransfer> Probe<'a, T> {
fn snapshot_transfer(&self) -> ::std::option::Option<&'a dyn jsg::ErasedSnapshotTransfer> {
::std::option::Option::Some(self.0)
}
}
Probe(self).snapshot_transfer()
}
}
}
}
Expand Down
77 changes: 75 additions & 2 deletions src/rust/jsg-test/ffi.c++
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
#include <workerd/jsg/dom-exception.h>
#include <workerd/jsg/ser.h>
#include <workerd/jsg/setup.h>
#include <workerd/jsg/snapshot.h>
#include <workerd/rust/jsg-test/lib.rs.h>
#include <workerd/rust/jsg/ffi-inl.h>
#include <workerd/rust/jsg/ffi.h>
Expand Down Expand Up @@ -249,6 +250,78 @@ void TestHarness::run_in_context(
});
}

::rust::String snapshot_round_trip(::rust::Slice<const uint8_t> flags,
size_t topLevelData,
::rust::Fn<void(size_t, Isolate*, EvalContext&)> topLevel,
size_t restoredData,
::rust::Fn<void(size_t, Isolate*, EvalContext&)> restored) {
using ::workerd::jsg::IsolateBase;
return ::workerd::jsg::runInV8Stack([&](::workerd::jsg::V8StackScope&) -> ::rust::String {
kj::Own<::workerd::jsg::SnapshotArtifact> artifact;
{
// As Worker::Worker does in the zygote: the serializer callbacks are registered with the
// context, the top level runs, and the context handle and the Rust realm's templates are
// handed to createSnapshotBlob().
auto zygote = kj::heap<TestIsolate>(getV8System(), ::workerd::jsg::newIsolateGroup(), nullptr,
kj::heap<::workerd::jsg::IsolateObserver>(),
::workerd::jsg::defaultExternalStringAllocator(), v8::Isolate::CreateParams{}, true,
::workerd::jsg::SnapshotConfig(::workerd::jsg::MutableSnapshot{
.artifact = kj::atomicRefcounted<::workerd::jsg::SnapshotArtifact>()}));
kj::Maybe<kj::Exception> failure;
zygote->runInLockScope([&](TestIsolate::Lock& lock) {
auto realm = ::workerd::rust::jsg::realm_create(lock.v8Isolate, flags);
::workerd::jsg::WrappablesSerializeMetadata metadata;
uint32_t badTagFieldsCount = 0;
auto& isolateBase = IsolateBase::from(lock.v8Isolate);
failure = kj::runCatchingExceptions([&] {
v8::Global<v8::Context> contextHandle;
lock.withinHandleScope([&] {
auto jsContext = lock.newContext<TestContext>();
auto context = jsContext.getHandle(lock);
v8::Context::Scope contextScope(context);
isolateBase.setSnapshotDefaultContext(context, &badTagFieldsCount, &metadata);
{
EvalContext evalContext(lock.v8Isolate, context);
topLevel(topLevelData, lock.v8Isolate, evalContext);
}
isolateBase.settleFinalizationRegistriesForSnapshot(lock);
isolateBase.removeRestoreTimeGlobalsBeforeSnapshot(lock, context);
contextHandle = jsContext.extractContextGlobalForSnapshot();
});
auto rustTemplates =
::workerd::rust::jsg::pinResourceTemplatesIntoSnapshot(lock.v8Isolate);
isolateBase.createSnapshotBlob(
kj::mv(contextHandle), kj::mv(rustTemplates), &badTagFieldsCount, &metadata);
});
});
KJ_IF_SOME(e, failure) {
return ::rust::String(e.getDescription().cStr());
}
artifact = zygote->extractSnapshotArtifact();
}

auto isolate = kj::heap<TestIsolate>(getV8System(), ::workerd::jsg::newIsolateGroup(), nullptr,
kj::heap<::workerd::jsg::IsolateObserver>(),
::workerd::jsg::defaultExternalStringAllocator(), v8::Isolate::CreateParams{}, true,
::workerd::jsg::SnapshotConfig(
::workerd::jsg::FinalizedSnapshot{.artifact = artifact->addRef()}));
isolate->runInLockScope([&](TestIsolate::Lock& lock) {
// As Worker::Isolate does: the realm takes the snapshot's templates before anything wraps
// a Rust resource.
auto realm = ::workerd::rust::jsg::realm_create(lock.v8Isolate, flags);
::workerd::rust::jsg::restoreResourceTemplatesFromSnapshot(lock.v8Isolate);
lock.withinHandleScope([&] {
auto jsContext = lock.newContext<TestContext>();
auto context = jsContext.getHandle(lock);
v8::Context::Scope contextScope(context);
EvalContext evalContext(lock.v8Isolate, context);
restored(restoredData, lock.v8Isolate, evalContext);
});
});
return ::rust::String();
});
}

void TestHarness::drop_realm_then_gc(size_t data, ::rust::Fn<void(size_t)> callback) const {
isolate->runInLockScope([&](TestIsolate::Lock& lock) {
realm = kj::none;
Expand All @@ -259,9 +332,9 @@ void TestHarness::drop_realm_then_gc(size_t data, ::rust::Fn<void(size_t)> callb

void TestHarness::take_realm_templates() const {
isolate->runInLockScope([&](TestIsolate::Lock& lock) {
for (auto& handle:
for (auto& entry:
::workerd::rust::jsg::realm_take_resource_templates(*KJ_ASSERT_NONNULL(realm))) {
::workerd::rust::jsg::global_from_ffi<v8::FunctionTemplate>(kj::mv(handle)).Reset();
::workerd::rust::jsg::global_from_ffi<v8::FunctionTemplate>(kj::mv(entry.handle)).Reset();
}
});
}
Expand Down
10 changes: 10 additions & 0 deletions src/rust/jsg-test/ffi.h
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,16 @@ class TestHarness {
// `Worker::Isolate` does, the isolate-level JSG switches derived from them.
kj::Own<TestHarness> create_test_harness(::rust::Slice<const uint8_t> flags, FastApi fast_api);

// Builds a startup snapshot the way a Worker's zygote does and starts an isolate from it. Calls
// `topLevel` in a context of the zygote, with its Rust realm created from `flags`, and then, if the
// snapshot was created, `restored` in the context of a new isolate started from it. Returns why the
// zygote failed, or an empty string if it did not.
::rust::String snapshot_round_trip(::rust::Slice<const uint8_t> flags,
size_t topLevelData,
::rust::Fn<void(size_t, Isolate*, EvalContext&)> topLevel,
size_t restoredData,
::rust::Fn<void(size_t, Isolate*, EvalContext&)> restored);

// Forward-declared; defined by the CXX-generated lib.rs.h header.
enum class GcType : uint8_t;

Expand Down
Loading
Loading