Skip to content

Commit 2a90085

Browse files
authored
Hand WorkerLoader::get()'s source to KJ in the converting microtask (#8671)
The reentry callback returned `getCode(js).then(js, addFunctor(f))`, which makeReentryCallbackImpl() then waited on with the one-argument awaitJs(). `f` produces a DynamicWorkerSource, which owns KJ objects: the globalOutbound and tail subrequest channels, the Frankenvalue env and the module content. With `.then()`, the source reached KJ only in a second microtask. If execution was terminated between the two, as a limit does, the second microtask was discarded: the runtime's wait never settled, and the source stayed in the V8 heap until GC. The callback now returns `ioctx.awaitJs(js, getCode(js), f)`, so `f` runs and its result is handed to the KJ promise in the same continuation. makeReentryCallbackImpl() needs no change: a callback returning a kj::Promise takes its plain-value branch, and run()'s result type, kj::PromiseForResult, flattens the promise, as it already did for the promise the jsg::Promise branch gets from awaitJs(). Other internal differences: the conversion no longer runs if the wait was canceled before getCode() resolved, and a getCode() promise resolved from another context now fails through awaitJs()'s IoOwn check rather than addFunctor()'s. Nothing JS-visible changes: error messages, the Python compat-flag fixups, limits, and the globalOutbound/tails handling are all in toDynamicWorkerSource(), which is untouched. A rejected getCode() still rejects the wait with the tunneled exception. No compatibility flag is needed. worker-loader-source-test terminates execution between the two microtasks and checks that the wait resolves to the source, owned by the KJ promise. With the old shape it fails: the wait stays pending.
1 parent 9d77593 commit 2a90085

3 files changed

Lines changed: 156 additions & 7 deletions

File tree

‎src/workerd/api/BUILD.bazel‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1084,3 +1084,12 @@ wd_test(
10841084
args = ["--experimental"],
10851085
data = ["streams/body-read-operation-test.js"],
10861086
)
1087+
1088+
kj_test(
1089+
src = "worker-loader-source-test.c++",
1090+
deps = [
1091+
":worker-loader",
1092+
"//src/workerd/io",
1093+
"//src/workerd/tests:test-fixture",
1094+
],
1095+
)
Lines changed: 141 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,141 @@
1+
// Copyright (c) 2026 Cloudflare, Inc.
2+
// Licensed under the Apache 2.0 license found in the LICENSE file or at:
3+
// https://opensource.org/licenses/Apache-2.0
4+
//
5+
// Tests of how WorkerLoader::get() hands the DynamicWorkerSource that getCode() describes to the
6+
// runtime that loads the Worker.
7+
8+
#include <workerd/api/http.h>
9+
#include <workerd/api/worker-loader.h>
10+
#include <workerd/io/io-context.h>
11+
#include <workerd/jsg/jsg.h>
12+
#include <workerd/tests/test-fixture.h>
13+
14+
#include <kj/test.h>
15+
16+
namespace workerd::api {
17+
namespace {
18+
19+
// Records its destruction. WorkerLoader makes it the loaded Worker's global outbound, so it lives
20+
// exactly as long as the DynamicWorkerSource that holds it.
21+
class TrackedChannel final: public IoChannelFactory::SubrequestChannel {
22+
public:
23+
explicit TrackedChannel(bool& destroyed): destroyed(destroyed) {}
24+
~TrackedChannel() noexcept(false) {
25+
destroyed = true;
26+
}
27+
28+
kj::Own<WorkerInterface> startRequest(IoChannelFactory::SubrequestMetadata) override {
29+
KJ_UNREACHABLE;
30+
}
31+
void requireAllowsTransfer() override {}
32+
kj::OneOf<kj::Array<byte>, kj::Promise<kj::Array<byte>>> getTokenMaybeSync(
33+
IoChannelFactory::ChannelTokenUsage) override {
34+
KJ_UNREACHABLE;
35+
}
36+
37+
private:
38+
bool& destroyed;
39+
};
40+
41+
class NeverUsedStubChannel final: public WorkerStubChannel {
42+
public:
43+
kj::Rc<IoChannelFactory::SubrequestChannel> getEntrypointResolved(
44+
kj::Maybe<kj::String>, Frankenvalue, kj::Maybe<ResourceLimits>) override {
45+
KJ_UNREACHABLE;
46+
}
47+
kj::Rc<IoChannelFactory::ActorClassChannel> getActorClassResolved(
48+
kj::Maybe<kj::String>, Frankenvalue, kj::Maybe<ResourceLimits>) override {
49+
KJ_UNREACHABLE;
50+
}
51+
};
52+
53+
// What the loader channel factory shares with the test.
54+
struct LoaderState {
55+
bool channelDestroyed = false;
56+
kj::Maybe<kj::Function<kj::Promise<DynamicWorkerSource>()>> fetchSource;
57+
};
58+
59+
// Keeps the source callback that WorkerLoader::get() passes to loadIsolate(), so the test can
60+
// call it as the runtime would when it first needs the Worker.
61+
struct LoaderChannelFactory final: public TestFixture::DummyIoChannelFactory {
62+
LoaderChannelFactory(TimerChannel& timer, LoaderState& state)
63+
: DummyIoChannelFactory(timer),
64+
state(state) {}
65+
66+
kj::Rc<SubrequestChannel> getSubrequestChannelResolved(
67+
uint channel, kj::Maybe<Frankenvalue>, kj::Maybe<VersionRequest>, Persistent) override {
68+
KJ_ASSERT(channel == IoContext::NULL_CLIENT_CHANNEL);
69+
return kj::rc<TrackedChannel>(state.channelDestroyed);
70+
}
71+
72+
kj::Own<WorkerStubChannel> loadIsolate(uint,
73+
kj::Maybe<kj::String>,
74+
kj::Function<kj::Promise<DynamicWorkerSource>()> fetchSource) override {
75+
state.fetchSource = kj::mv(fetchSource);
76+
return kj::refcounted<NeverUsedStubChannel>();
77+
}
78+
79+
LoaderState& state;
80+
};
81+
82+
WorkerLoader::WorkerCode makeWorkerCode() {
83+
auto modules = kj::heapArrayBuilder<jsg::Dict<
84+
kj::OneOf<jsg::V8Ref<v8::WasmModuleObject>, WorkerLoader::Module, kj::String>>::Field>(1);
85+
modules.add(kj::str("main.js"), kj::str("export default {}"));
86+
return {
87+
.compatibilityDate = kj::str("2024-01-01"),
88+
.mainModule = kj::str("main.js"),
89+
.modules = {.fields = modules.finish()},
90+
};
91+
}
92+
93+
KJ_TEST("WorkerLoader::get() hands the source to KJ in the microtask that converts it") {
94+
// A limit can terminate execution between two microtasks, discarding the rest of the queue. The
95+
// microtask that converts the WorkerCode into a DynamicWorkerSource must also hand the source to
96+
// the KJ promise returned to the runtime. Were the handoff left to another microtask, it would
97+
// be discarded: the runtime's wait would never settle, and the source, with the KJ channels it
98+
// holds, would stay parked in the V8 heap.
99+
LoaderState state;
100+
TestFixture fixture(TestFixture::SetupParams{
101+
.ioChannelFactory = kj::Function<kj::Rc<IoChannelFactory>(TimerChannel&)>(
102+
[&state](TimerChannel& timer) -> kj::Rc<IoChannelFactory> {
103+
return kj::rc<LoaderChannelFactory>(timer, state);
104+
}),
105+
});
106+
auto request = fixture.newIncomingRequest();
107+
auto& context = request->getContext();
108+
109+
context
110+
.run([&](Worker::Lock& lock) {
111+
auto& js = jsg::Lock::from(lock.getIsolate());
112+
auto loader = js.alloc<WorkerLoader>(0, CompatibilityDateValidation::CODE_VERSION);
113+
loader->get(
114+
js, kj::none, jsg::Function<jsg::Promise<WorkerLoader::WorkerCode>()>([](jsg::Lock& js) {
115+
// Terminates execution in the second round of microtasks: after the microtask that the
116+
// WorkerCode's resolution schedules, and before any microtask that one schedules in turn.
117+
js.resolvedPromise().then(js, [](jsg::Lock&) {}).then(js, [](jsg::Lock& js) {
118+
js.terminateExecutionNow();
119+
});
120+
return js.resolvedPromise(makeWorkerCode());
121+
}));
122+
}).wait(fixture.getWaitScope());
123+
124+
auto promise = KJ_ASSERT_NONNULL(state.fetchSource)();
125+
fixture.pollEventLoop();
126+
// Were the handoff left to a discarded microtask, the wait would never settle, and the source
127+
// would stay in the V8 heap.
128+
KJ_ASSERT(promise.poll(fixture.getWaitScope()), "the termination discarded the source");
129+
{
130+
auto source = promise.wait(fixture.getWaitScope());
131+
KJ_EXPECT(source.globalOutbound != kj::none);
132+
KJ_EXPECT(!state.channelDestroyed);
133+
}
134+
KJ_EXPECT(state.channelDestroyed);
135+
136+
state.fetchSource = kj::none;
137+
fixture.drainAndDestroy(kj::mv(request));
138+
}
139+
140+
} // namespace
141+
} // namespace workerd::api

‎src/workerd/api/worker-loader.c++‎

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -84,13 +84,12 @@ jsg::Ref<WorkerStub> WorkerLoader::get(
8484
[getCode = kj::mv(getCode), compatDateValidation = compatDateValidation](
8585
jsg::Lock& js, IoContext& ioctx) mutable {
8686
// getCode() is application-provided and may resolve its promise from a different context.
87-
// Binding the continuation to this context ensures that it either runs here or throws before
88-
// accessing the context.
89-
return getCode(js).then(js,
90-
ioctx.addFunctor([compatDateValidation](jsg::Lock& js, IoContext& ioctx,
91-
WorkerCode code) -> DynamicWorkerSource {
92-
return toDynamicWorkerSource(js, ioctx, compatDateValidation, kj::mv(code));
93-
}));
87+
// awaitJs() runs the conversion only in this context, and in the same continuation that hands
88+
// the resulting DynamicWorkerSource, which owns KJ objects, to the returned KJ promise.
89+
return ioctx.awaitJs(js, getCode(js),
90+
[compatDateValidation](jsg::Lock& js, WorkerCode code) -> DynamicWorkerSource {
91+
return toDynamicWorkerSource(js, IoContext::current(), compatDateValidation, kj::mv(code));
92+
});
9493
});
9594

9695
auto isolateChannel =

0 commit comments

Comments
 (0)