Skip to content

Hand WorkerLoader::get()'s source to KJ in the microtask that converts it - #8671

Merged
bartlomieju merged 2 commits into
mainfrom
biwanczuk/worker-loader-await-js-same-continuation
Nov 21, 2026
Merged

bartlomieju merged 2 commits into
mainfrom
biwanczuk/worker-loader-await-js-same-continuation

Conversation

@bartlomieju

@bartlomieju bartlomieju commented Nov 19, 2026 •

Copy link
Copy Markdown
Collaborator

WorkerLoader::get() turns the WorkerCode resolved by the application's getCode() into a
DynamicWorkerSource, which the runtime loads the Worker from. That source owns KJ objects: the
global outbound and tail subrequest channels, the serialized env, and the module content. Today it
gets from JavaScript to KJ in two steps:

return getCode(js).then(js, ioctx.addFunctor([...](jsg::Lock& js, IoContext& ioctx, WorkerCode code) {
  return toDynamicWorkerSource(js, ioctx, compatDateValidation, kj::mv(code));
}));

The conversion runs in one microtask and produces a jsg::Promise<DynamicWorkerSource>. The reentry
callback waits on that promise with awaitJs(), and a second microtask hands the source to the KJ
promise the runtime is waiting on. If execution is terminated between the two, for example because
the Worker exceeded its CPU limit, V8 discards the second microtask. The source has been built but
never reaches KJ. The runtime's wait stays pending until something else ends it, such as the
IoContext being aborted, and the source and its channels stay in the V8 heap until garbage
collection. awaitJs()'s header comment already covers this case: when func produces KJ objects,
prefer awaitJs(js, promise, func) over awaitJs(js, promise.then(js, func)). This PR does that:

return ioctx.awaitJs(js, getCode(js), [compatDateValidation](jsg::Lock& js, WorkerCode code) {
  return toDynamicWorkerSource(js, IoContext::current(), compatDateValidation, kj::mv(code));
});

The motivation for this change is the Rust port of Worker Loader. The port converts the code with
IoContext::await_js_local(), which waits on getCode()'s promise and maps the result under
the lock, with the IoContext, in the same continuation. The map may return values that aren't
Send, such as KJ channels and the source content. That is the shape this PR gives the C++ code, so
the two implementations match step for step. The port doesn't have to reproduce the .then() chain,
which would mean storing a non-Send Rust value in a JS promise and adding an addFunctor
equivalent to bind its reaction to the context. The small behavior changes described below land
here, in C++, where they can be reviewed on their own. Switching from the C++ loader to the Rust one
later then changes no behavior, and reviewing the port means checking a one-to-one translation
rather than arguing that two different promise chains are equivalent.

makeReentryCallbackWeak() needs no change. A callback that returns a kj::Promise takes its
plain-value branch, and IoContext::run() flattens the promise, as it already did for the promise
the jsg::Promise branch gets from awaitJs().

The conversion itself is unchanged and runs at the same point, in the reaction to getCode()'s
promise, so any env getters that serialization invokes run in the same order relative to the
Worker's own microtasks as before. One internal microtask goes away: it existed only to move the
result from JS to KJ, and a Worker has no handle on it, so its removal isn't observable apart from
the fixed termination case. The other difference is that if the runtime stops waiting before
getCode() resolves, awaitJs() skips the conversion, where before it ran and its result was
dropped. A Worker can reach this only when its getCode() resolves after the load was abandoned,
and what gets skipped is the env getters run by serialization and the uncaught exception logged
for an invalid WorkerCode that no caller was waiting for.

No compatibility flag was added and I need a double check if that's okay.

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.
@bartlomieju
bartlomieju requested review from a team as code owners November 19, 2026 12:49

@clanky-the-clanker clanky-the-clanker Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Superseded by the review of fda2ed93.

This review, of 055be6b6

✅ Approved — No findings: the switch to the two-argument awaitJs() keeps the context binding and passes the converted source to KJ in the same continuation, as intended.

The decision is advisory: this review is a comment and never approves, blocks or requests changes on the pull request.


✅ All checks passed

🔒 Security: ✅ LGTM

No issues found. The context binding is kept: awaitJs() holds the fulfiller via IoOwn, so it can only be dereferenced in the originating IoContext.


📖 AGENTS.md: ✅ LGTM

No issues found.


📋 Code Quality: ✅ LGTM

No issues found.


⚡ Performance: ✅ LGTM

No issues found.


📝 Documentation: ✅ LGTM

No issues found.


Reviewed commit: 055be6b6

@clanky-the-clanker clanky-the-clanker Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ Approved — No findings: the two-argument awaitJs() keeps the context binding and hands the converted source to KJ in the same continuation. A new test covers the termination case.

The decision is advisory: this review is a comment and never approves, blocks or requests changes on the pull request.


✅ All checks passed

🔒 Security: ✅ LGTM

No issues found. The context binding is kept: awaitJs() holds the fulfiller through IoOwn, so only the IoContext that created it can dereference it.


📖 AGENTS.md: ✅ LGTM

No issues found.


📋 Code Quality: ✅ LGTM

No issues found. The conversion runs in the reaction to getCode()'s promise, and the same continuation settles the KJ promise. WorkerCode is still moved, and the lambda captures nothing by bare reference. The new test target matches the targets around it in BUILD.bazel.


⚡ Performance: ✅ LGTM

No issues found.


📝 Documentation: ✅ LGTM

No issues found.


Reviewed commit: fda2ed93

@bartlomieju
bartlomieju merged commit 2a90085 into main Nov 21, 2026
36 of 37 checks passed
@bartlomieju
bartlomieju deleted the biwanczuk/worker-loader-await-js-same-continuation branch November 21, 2026 08:39
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants