Repository navigation
kj-rs: add LoopChecked and KjFuture::into_send() for Send futures on a KJ event loop - #8857
nathanwhit wants to merge 3 commits into
Conversation
There was a problem hiding this comment.
Superseded by the review of
1c902af9.
This review, of 3b131a71
💬 Approved with comments — No blocking or production-impact issues. The open notes are a missing test for calling a bridged async fn with no event loop, a documentation caveat about off-loop poll errors, and a README wording nit.
Findings: 3 info (3 are inline comments on the diff)
The decision is advisory: this review is a comment and never approves, blocks or requests changes on the pull request.
📋 Code Quality: 💬 2 info
The design is sound and well tested. There are two non-blocking notes: a missing failure-path test, and how an off-loop poll error interacts with drop.
Recommendation: 💬 Optional Nits
- [INFO] No test covers the new path where a bridged C++
async fnis called with no current event loop. (src/rust/cxx/kj-rs/promise.h:72) - [INFO] An off-loop poll error usually leads straight to an off-loop drop, which aborts the process. (
src/rust/cxx/kj-rs/promise.rs:165)
View full review
KjPromiseNodeImpl(kj::Promise<T>&&)now readskj::EventLoop::Id::current(), so a bridgedasync fncalled on a thread with no event loop throws. The comment says the promise stays owned in that case, but no test exercises this path.SendKjFuturereturnsPoll::Ready(Err(..))when polled off its loop. Most combinators then drop the future, and if that drop is also off-loop the process aborts. The doc line saying it is "left to be polled again on its loop" holds only if the caller keeps it alive.
📝 Documentation: 💬 1 info
One wording nit in the new kj-rs README section.
Recommendation: 💬 Optional Nits
- [INFO] The README says
KjOwn<T>of a C++ type is!Sendas a blanket rule, butKjOwn<T>isSendwhenT: Send. (src/rust/cxx/kj-rs/README.md:44)
View full review
The new README section states as a blanket rule that a KjOwn<T> of a C++ type is !Send. In fact KjOwn<T> is Send whenever T: Send (own.rs:186).
✅ All other checks passed
🔒 Security: ✅ LGTM
The change narrows trust. LoopChecked::new is unsafe, KjFuture is sealed, and the access, poll and drop paths all check the loop id. An off-loop poll never reaches the promise. The unsafe impl Send on the span wrapper is removed, and await_io / await_io_and_run callbacks now require Send.
📖 AGENTS.md: ✅ LGTM
The AGENTS.md updates are consistent with the code.
⚡ Performance: ✅ LGTM
Each poll, access and drop adds one event-loop id comparison. It adds no allocations and no atomics.
Reviewed commit: 3b131a71
3b131a7 to
1c902af
Compare
There was a problem hiding this comment.
Superseded by the review of
cd69d007.
This review, of 1c902af9
💬 Approved with comments — No blocking or production-impact issues. Three INFO notes from the earlier review remain open: a missing test for calling a bridged async fn with no event loop, a doc caveat on off-loop poll errors, and a README KjOwn<T> wording fix.
Findings: 3 info (1 is an inline comment on the diff)
The decision is advisory: this review is a comment and never approves, blocks or requests changes on the pull request.
📋 Code Quality: 💬 2 info
Two earlier INFO notes remain open; nothing new in the code changed since the last review.
Recommendation: 💬 Optional Nits
- [INFO] No test covers a bridged C++
async fncalled with no current event loop. (src/rust/cxx/kj-rs/promise.h:72) - [INFO] The
SendKjFuturedoc implies an off-loop poll error can be recovered from, but callers usually drop the future then, and an off-loop drop aborts. (src/rust/cxx/kj-rs/promise.rs:165)
View full review
src/rust/cxx/kj-rs/promise.h:72:KjPromiseNodeImpl(kj::Promise<T>&&)readskj::EventLoop::Id::current()before it takes the promise. A bridgedasync fncalled with no event loop therefore throws while the promise still owns its node. No test exercises this path; the newpromise-test.rsonly has staticSend/!Syncassertions.src/rust/cxx/kj-rs/promise.rs:165:SendKjFuturereturnsPoll::Ready(Err(..))when polled off its loop. Most callers and combinators then drop the future, and an off-loop drop aborts the process. The doc line saying the future is "left to be polled again on its loop" holds only if the caller keeps it alive.
📝 Documentation: 💬 1 info
One README statement about KjOwn<T> is too broad.
Recommendation: 💬 Optional Nits
- [INFO] The README says every
KjOwn<T>of a C++ type is!Send, butKjOwn<T>isSendwhenT: Send. (src/rust/cxx/kj-rs/README.md:44)
View full review
src/rust/cxx/kj-rs/README.md:44: the README says aKjOwn<T>of a C++ type is!Sendas a blanket rule. In factKjOwn<T>isSendwheneverT: Send.
✅ All other checks passed
🔒 Security: ✅ LGTM
The change narrows trust. LoopChecked::new is unsafe, and KjFuture is sealed. LoopChecked access, polling and into_inner all check the stored loop id, and so do SendKjFuture poll and drop. An off-loop poll fails before it reaches the promise node. The unsafe impl Send on the span wrapper is removed, and the await_io / await_io_and_run callbacks now require Send.
📖 AGENTS.md: ✅ LGTM
The AGENTS.md updates are consistent with the code.
⚡ Performance: ✅ LGTM
Each poll, access and drop adds one event-loop id comparison. It adds no allocations, atomics or blocking work.
Reviewed commit: 1c902af9
1c902af to
cd69d00
Compare
There was a problem hiding this comment.
Superseded by the review of
53201c21.
This review, of cd69d007
✅ Approved — The three notes from the last review are fixed (no-event-loop test added, off-loop poll doc reworded, README KjOwn<T> wording corrected), and the changes since then add no new issues.
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
KjFuture is sealed, so the Send impl on SendKjFuture covers only bridged promise futures. Polling off-loop fails before it reaches the promise node, and dropping off-loop aborts. PhantomData<Cell<()>> keeps the wrapper !Sync. new_callbacks_promise_future requires a loop id, and its safety doc says so.
📖 AGENTS.md: ✅ LGTM
The AGENTS.md updates match the code.
📋 Code Quality: ✅ LGTM
async_fn_requires_event_loop covers calling a bridged async fn with no event loop running. The SendKjFuture doc (promise.rs) now says a caller must keep the future after an off-loop poll error and that dropping it off its loop aborts. This matches poll_checked and Drop. The loop-id check runs before any access to the awaiter, and get_awaiter is now private.
⚡ Performance: ✅ LGTM
Each poll, access and drop adds one event-loop id comparison. It adds no allocations, atomics or blocking work.
📝 Documentation: ✅ LGTM
The kj-rs README now says a KjOwn<T> is !Send unless T is Send.
Reviewed commit: cd69d007
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## main #8857 +/- ##
==========================================
+ Coverage 67.84% 69.99% +2.15%
==========================================
Files 850 883 +33
Lines 216559 232113 +15554
Branches 32582 33681 +1099
==========================================
+ Hits 146915 162467 +15552
+ Misses 50410 49609 -801
- Partials 19234 20037 +803 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
|
The part I am most uncertain about is whether or not it's worth trying to make this all fully sound. Requiring If we accept a certain amount of unsoundness (the risk of using OS thread pinned state, which can cause UB when the future migrates threads) then we could just drop the Basically it comes down to deciding whether or not the thread safety hazards are a real enough issue to deserve the complexity of preventing them at compile time. I think it's unlikely that in first party code we would do something like stash an |
cd69d00 to
53201c2
Compare
There was a problem hiding this comment.
Superseded by the review of
d2eec2d0.
This review, of 53201c21
✅ Approved — The earlier notes stay fixed, and the changes to loop_checked.rs and the kj-rs README since the last review add no new issues.
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
LoopChecked::new is unsafe, and its contract covers OS-thread affinity, so the unconditional Send impl is sound. PhantomData<Cell<()>> keeps the type !Sync. Access, poll and drop all check the loop before touching the value.
📖 AGENTS.md: ✅ LGTM
The AGENTS.md updates match the code.
📋 Code Quality: ✅ LGTM
The accessors check the loop id before giving access. into_inner returns Err(self) off the loop. Drop aborts off the loop and checks that async destructors are allowed. Structural pinning is sound.
⚡ Performance: ✅ LGTM
Each poll, access or drop adds one comparison of event-loop ids, with no allocations or atomics.
📝 Documentation: ✅ LGTM
The kj-rs README matches the code.
Reviewed commit: 53201c21
|
Some data for this from the The REPL is host code in the
So for hosts in the That suggests keeping the
Neither option seems great. Would either work for you? |
|
AI generated review comments:
|
53201c2 to
d2eec2d
Compare
There was a problem hiding this comment.
Superseded by the review of
0b8484f1.
This review, of d2eec2d0
💬 Approved with comments — One WARNING: the loop-presence check in event_loop_id_is_current() probably creates the loop's Executor the first time it runs. That breaks the "zero allocations" claim and can change how wait() behaves on a loop with no event port. Nothing else blocks the change.
Findings: 1 warning (1 is an inline comment on the diff)
Not opened by the correctness review: 2 changed files it was meant to read
src/workerd/io/io-context/lib.rssrc/workerd/io/io-context/trace.rs
The decision is advisory: this review is a comment and never approves, blocks or requests changes on the pull request.
🔧 Fix with your agent
Paste the following into your coding agent to investigate and fix these issues.
Fix the following code review issues found in pull request #8857.
Before making changes, review each issue and present a brief summary table:
- For each finding, state whether you agree, disagree, or need clarification
- If you disagree (e.g., the fix would require disproportionate changes
for minimal ROI, or the finding is factually incorrect), explain why
- If you need to clarify something before deciding, ask those questions
- Then share your plan for which issues to tackle and in what order
## WARNING (1)
### [Code Quality] `event_loop_id_is_current()` probes with `kj::tryGetCurrentThreadExecutor()`, which creates the loop's `Executor` on first use. This adds an allocation and atomics, and can make `wait()` hang on port-less loops instead of failing fast.
- **File:** src/rust/cxx/kj-rs/loop-checked.c++:19
📋 Code Quality: ⚠️ 1 warning
The loop check uses tryGetCurrentThreadExecutor() as a probe, which can create the loop's Executor as a side effect.
Recommendation: 📝 Minor Comments
- [WARNING]
event_loop_id_is_current()probes withkj::tryGetCurrentThreadExecutor(), which creates the loop'sExecutoron first use. This adds an allocation and atomics, and can makewait()hang on port-less loops instead of failing fast. (src/rust/cxx/kj-rs/loop-checked.c++:19)
View full review
src/rust/cxx/kj-rs/loop-checked.c++:19:event_loop_id_is_current()callskj::tryGetCurrentThreadExecutor()to decide whether a loop is current. In KJ this goes throughEventLoop::getExecutor(), which creates an atomically refcountedExecutorthe first time it is called. EveryLoopCheckedaccess and drop, and everySendKjFuturepoll and drop, runs this check, so the first one on each loop allocates anExecutor.- This contradicts the "zero atomics or allocations" claim.
- On a loop with no event port, a loop that has an
Executorwaits inwait()for cross-thread events. Without one, it fails with "Nothing to wait for". A test that touches aLoopCheckedcould then hang instead of failing fast. - Fix: probe for the loop without creating an
Executor, or document the side effect and correct the overhead claim.
- The
kj-rs-tokioteardown uses the same probe, but only once, so it matters much less there.
✅ All other checks passed
🔒 Security: ✅ LGTM
LoopChecked::new is unsafe and documents the thread-affinity contract. The accessors, into_inner, poll and drop all check the loop before touching the value. KjFuture is sealed, so into_send() applies only to bridged promise futures.
📖 AGENTS.md: ✅ LGTM
The AGENTS.md updates match the code.
⚡ Performance: ✅ LGTM
After the first check on a loop, each check is a thread-local lookup and an id comparison. The Executor side effect is covered in the code quality section.
📝 Documentation: ✅ LGTM
The kj-rs README and doc comments match the code.
Reviewed commit: d2eec2d0
| } | ||
|
|
||
| bool event_loop_id_is_current(EventLoopId id) { | ||
| return kj::tryGetCurrentThreadExecutor() != kj::none && kj::EventLoop::Id::current() == id; |
There was a problem hiding this comment.
event_loop_id_is_current() probes with kj::tryGetCurrentThreadExecutor(), which creates the loop's Executor on first use. This adds an allocation and atomics, and can make wait() hang on port-less loops instead of failing fast.
kj::tryGetCurrentThreadExecutor() goes through EventLoop::getExecutor(), which creates the loop's atomically refcounted Executor the first time it is called. This check runs on every LoopChecked access and drop and every SendKjFuture poll and drop, so the first check on a loop allocates one. That contradicts the zero-allocation/zero-atomics claim. On a loop with no event port, an existing Executor also changes wait(): it blocks on cross-thread events instead of failing with "Nothing to wait for", so a test could hang instead of failing fast. Consider a non-throwing "is there a current loop" probe that does not create an Executor, or catching the throw from Id::current() on the rare off-loop path.
|
Option 1 sounds right to me. The pinned-loop assumption is a property of the Separately, I'll loosen |
KJ objects, and the futures of bridged C++ promises, are `!Send`, so a `Send` future can't hold one across an `.await`, though such a future runs on a KJ event loop and the object belongs to that loop. `LoopChecked<T>` holds a value with the id (`kj::EventLoop::Id`) of the event loop it was wrapped on. It is `Send` for every `T`, and `!Sync`. Checking the loop reads the current loop's id from a thread-local, with no atomics: - `get()`, `get_mut()` and `get_pin_mut()` fail off that loop, and `into_inner()` returns the wrapper back. - It is a future when `T` is, and polling it off the loop panics. - Dropping it off the loop aborts the process, as destroying a KJ object there would be unsound. That includes after the loop is gone: since the value is always dropped at once, never deferred to a later turn, it needs no `'static` bound and may borrow, as the future of a C++ async function that takes a reference does. - Like a KJ async object, it also aborts when dropped in a `kj::DisallowAsyncDestructorsScope`, which C++ JSG uses to catch a JavaScript object that holds a KJ I/O object other than through an `IoOwn`. Dropping it on its loop under that scope is sound, but means a JavaScript object held it directly. `LoopChecked::new()` is unsafe. The caller vouches that the value belongs to the current loop, sharing state that is not thread-safe only with the loop's other values, and that it has no affinity to its OS thread, so that moving it with its loop between OS threads, as an embedder may between turns, is sound. KJ objects meet this, and so does an `Rc` whose clones all belong to the loop; a `MutexGuard`, or a value that keeps state in a `thread_local!` between turns, does not. A `Send` tokio task can now hold KJ objects, through a `LoopChecked`, and kj-rs-tokio's `TokioPort` drops such tasks after the loop, which aborts. Its comments now say to spawn those tasks with `kj_rs_tokio::spawn` instead.
The callback of `IoContext::await_io_and_run()`, and of `await_io()`, which passes its own to it, waits on the event loop with the future, and an embedder may run an event loop on different OS threads between turns. So it moves between OS threads too, and must be `Send` for the same reason as the future: it must not hold anything tied to its OS thread, such as a `MutexGuard` or a `std::rc::Rc` with a clone elsewhere. A span was `!Send`, though it belongs to its request's event loop, not to the OS thread, and three callbacks end one. `SpanBuilder` and `TraceContext` now hold their C++ object in a `kj_rs::LoopChecked` from the start, bound to the loop of the IoContext that made it, so they are `Send` but not `Sync`. Using one off its loop panics, and dropping one off its loop aborts. Binding them at creation, rather than when a caller asks, means a span kept past its loop can't be bound to another one. memory-cache's `PendingRead` and wait span, and the test bridge's user spans, are then `Send` as they are. `IoOwnedSpan` no longer needs an `unsafe impl Send` for its span. A span is still not `Traced`, so a resource can hold one only through `IoContext::add_span()`. `src/rust/AGENTS.md` now says that, instead of calling spans thread-bound. `TraceContext` relies on `AsyncTracker` skipping calls from any OS thread but its own, which loses async trace data after the loop moves but is sound. A handle is not `Send`, so the `Send` error now catches a callback that captures one, before the lifetime check would. To keep testing that a callback's handles are scoped to its lock, the compile tests of both `await_io()` and `await_io_and_run()` stash a handle of the callback's own lock through a `thread_local!`.
The future of a C++ `async` function now holds the id (`kj::EventLoop::Id`) of the event loop that made its promise, and implements `kj_rs::KjFuture`. It stays `!Send`. `into_send()` wraps it in a `SendKjFuture`, which is `Send` and `!Sync` and keeps the call's borrows. Polling it off its loop returns an error. Dropping it off its loop aborts the process, also once the loop is gone, rather than destroy or leak its awaiter there. Unlike `LoopChecked::new()`, `into_send()` is safe: `KjFuture` is sealed to bridged promise futures, which have no OS-thread affinity. Calling a C++ `async` function now needs an event loop on the thread. `TokioEventPort` enters its loop's scope to cancel spawned tasks if its owner has already left it, so that tasks holding a `SendKjFuture` or `LoopChecked` drop them on the loop. The kj-rs README gains a section on which of `into_send()`, `LoopChecked` and `IoOwned` to use where, which the cxx README and the AGENTS files point to.
d2eec2d to
0b8484f
Compare
There was a problem hiding this comment.
💬 Approved with comments — One WARNING is still open: the loop-presence check in event_loop_id_is_current() probably creates the loop's Executor on first use. That adds an allocation and can change wait() on loops with no event port. Nothing blocks the change.
Findings: 1 warning
The decision is advisory: this review is a comment and never approves, blocks or requests changes on the pull request.
🔧 Fix with your agent
Paste the following into your coding agent to investigate and fix these issues.
Fix the following code review issues found in pull request #8857.
Before making changes, review each issue and present a brief summary table:
- For each finding, state whether you agree, disagree, or need clarification
- If you disagree (e.g., the fix would require disproportionate changes
for minimal ROI, or the finding is factually incorrect), explain why
- If you need to clarify something before deciding, ask those questions
- Then share your plan for which issues to tackle and in what order
## WARNING (1)
### [Code Quality] `event_loop_id_is_current()` checks for a loop with `kj::tryGetCurrentThreadExecutor()`, which probably creates the loop's `Executor` on first use. That adds an allocation and atomics, and can change `wait()` on loops with no event port.
- **File:** src/rust/cxx/kj-rs/loop-checked.c++:19
📋 Code Quality: ⚠️ 1 warning
The Executor side effect of the loop-presence check is still present; the rest looks correct.
Recommendation: 📝 Minor Comments
- [WARNING]
event_loop_id_is_current()checks for a loop withkj::tryGetCurrentThreadExecutor(), which probably creates the loop'sExecutoron first use. That adds an allocation and atomics, and can changewait()on loops with no event port. (src/rust/cxx/kj-rs/loop-checked.c++:19)
View full review
src/rust/cxx/kj-rs/loop-checked.c++:19: everyLoopCheckedaccess and drop, and everySendKjFuturepoll and drop, runsevent_loop_id_is_current(). It first callskj::tryGetCurrentThreadExecutor(), which in KJ probably goes throughEventLoop::getExecutor()and creates an atomically refcountedExecutorthe first time it is called on a loop.- That contradicts the "zero atomics or allocations" claim in the description.
- On a loop with no event port,
wait()may then block waiting for cross-thread events instead of failing with "Nothing to wait for". TokioEventPortloops have a port, so they are not affected.
io-context/lib.rs,trace.rsandloop_checked.rslook correct.
✅ All other checks passed
🔒 Security: ✅ LGTM
LoopChecked::new is unsafe and documents its thread-affinity contract. Access, into_inner, poll and drop all check the loop before touching the value, and !Sync comes from PhantomData<Cell<()>>. KjFuture is sealed, so into_send() works only on bridged promise futures.
📖 AGENTS.md: ✅ LGTM
The AGENTS.md updates match the code.
⚡ Performance: ✅ LGTM
After the first check on a loop, each check is a constant-time id comparison. into_send() adds no allocations.
📝 Documentation: ✅ LGTM
The kj-rs README and the doc comments match the code.
Reviewed commit: 0b8484f1
guybedford
left a comment
There was a problem hiding this comment.
I went through the model this builds on as well as the diff. Two properties are in play and Send stands in for both: a value that rides a loop must have no OS-thread affinity, and a loop-bound value must only be touched where its loop is current. The compiler checks the first wherever the bound is present. It checks the second nowhere; the new types check it at runtime. The comments below are the places where I think that check, or the argument around it, has a gap.
Left out on purpose:
- James's points 4, 5 and 6, which he already raised.
- Any position on Nathan's question about dropping the Send bound.
- The fiber and forgotten-future items, which I haven't validated.
| /// # Errors | ||
| /// | ||
| /// Fails off the value's event loop. | ||
| pub fn get(&self) -> Result<&T, KjException> { |
There was a problem hiding this comment.
get() checks the loop when the borrow is taken, and the &T is then used unchecked for as long as it lives. Nothing ties that lifetime to the turn the check ran in.
A future can take the borrow, await, and use it on a later poll. When T is !Sync that future is !Send, so it stays on its OS thread while the loop moves, and the later use runs with the loop current on another thread. I ran this locally: the future calls get(), awaits once, then writes through the borrow. Polled once under a WaitScope on thread A; the loop is then entered on thread B; the second poll on A changed the value and no check failed.
await_io rejects that future, since it isn't Send. What it needs is something that polls a !Send future across turns from one OS thread, and a thread_local! is enough for that in safe code. get_mut() and get_pin_mut() are the same. The Future impl, into_inner() and Drop are not: they check in the same call that uses the value.
|
|
||
| | Where the KJ value lives | What to use | | ||
| | --- | --- | | ||
| | Single-loop task (`kj_rs_tokio::spawn` / `LocalSet`, `server/`) | Plain `!Send` `KjFuture` and `KjOwn<T>` directly (no wrapper needed) | |
There was a problem hiding this comment.
This row, and "so they cannot accidentally cross into tokio::spawn" above it, treat !Send as "stays on its loop". !Send says "stays on its OS thread". Those are the same only while the thread and the loop are: a loop that moves, or one destroyed before its thread exits, separates them.
A KjOwn kept in a thread_local! is the concrete case. It compiles, and it is later used or dropped on that thread under a different loop, or under none. So the bare types depend on a rule the README doesn't state: nothing loop-bound persists in thread-keyed storage across a return to the event loop. Is that what "single-loop" is meant to guarantee here? If so, breaking it is UB from safe code, not a convention.
| // SAFETY: the bridge made the spans in the current `IoContext`, so on its event loop, and | ||
| // they are as for `SpanBuilder::on_current_loop()`. Their async trace operation belongs to | ||
| // an `AsyncTracker`, which skips calls from any OS thread but the one it was made on: | ||
| // after its loop moves, the operation is not recorded, which is sound. |
There was a problem hiding this comment.
The tracker compares against the thread it was made on, so after its loop moves it does two different things. On the loop's new thread, calls are skipped, which is the case this comment describes. On the original thread they are still accepted.
AsyncResource is Send and documented in ffi.rs as droppable on any thread, so a drop on the original thread reaches impl->destroy() there. Separately, linkFromCallerTurn() reads caller.impl with no owner check, on the assumption that a tracker in a turn is on its owner thread, which stops holding once the loop has moved.
I haven't established whether those two can overlap; that depends on which locks cover each. But "skips calls from any OS thread but the one it was made on" leaves out the made-on thread, and after a move that is the one that matters.
| /// `future` and its output are `Send` because the future's later polls run without the | ||
| /// isolate lock. | ||
| /// isolate lock. `future` and `callback` are `Send` because they wait on the event loop, which | ||
| /// an embedder may run on different OS threads between turns. |
There was a problem hiding this comment.
make_reentry_callback_weak() waits on the same loop and has no such bound. ReentryFuture and ReentryFn in ffi.rs are documented as "need not be Send" because C++ polls them "on the thread of the IoContext". With this sentence the crate says both that the IoContext's loop moves between OS threads and that it has a thread. The futures of extern "Rust" async fns are the other unbounded path, as James noted.
| } | ||
|
|
||
| bool event_loop_id_is_current(EventLoopId id) { | ||
| return kj::tryGetCurrentThreadExecutor() != kj::none && kj::EventLoop::Id::current() == id; |
There was a problem hiding this comment.
Confirming James's first point with a test. On a loop with no event port, kj::Promise<void>(kj::NEVER_DONE).wait(waitScope) throws "Nothing to wait for; this thread would hang forever". After one LoopChecked::get() on that loop, the same wait blocks until the test times out. tryGetCurrentThreadExecutor() creates the loop's Executor on its first call, and EventLoop::wait() waits on the executor when there is no port.
| self: Pin<&mut Self>, | ||
| cx: &mut Context, | ||
| ) -> Result<bool, cxx::KjException> { | ||
| self.loop_id.require_current()?; |
There was a problem hiding this comment.
The awaiter under this is already an ExecutorGuarded, so a checked poll compares the loop twice, with two notions of identity: the EventLoop::Id taken when the promise was made, and the kj::Executor& taken at first poll. They differ at the edges. Before the first poll only the id exists. ~ExecutorGuarded throws off its loop, but its member is still destroyed there. And the executor is compared by address after its loop may be gone, where an id is never reused.
| // promise, the id of the promise's event loop, and a waker, and is polled and dropped only while | ||
| // that event loop is current. A KJ promise depends on its event loop, not on the OS thread | ||
| // that runs it, and an embedder may run an event loop, with its promises, on different OS threads | ||
| // between turns; the arguments the C++ function borrowed, which the promise may use, are its |
There was a problem hiding this comment.
This covers what the function borrowed. Arguments it took by value are also owned by the promise from here on, and move between OS threads with it, without having passed a Send bound.
| }); | ||
| } | ||
|
|
||
| KJ_TEST("a LoopChecked future is polled only on its event loop") { |
There was a problem hiding this comment.
Each runtime test either succeeds on the thread that made the value, or fails on another loop or on none. None enters the loop itself on a second OS thread and uses or drops the value there, which is the case the type exists for. I tried it locally with a WaitScope on one thread and then another, and both a LoopChecked and a polled SendKjFuture behave.
Why
In edgeworker, a KJ event loop migrates between OS threads together with its tasks, so
IoContext::await_ioandIoContext::await_io_and_runrequireSendfutures (and now callbacks) to rule out OS-thread-pinned state (MutexGuard,Rccloned from athread_local!, etc.).Bridged C++
async fnpromises andKjOwn<T>handles are!Sendby default so they cannot accidentally cross intotokio::spawnor JSG resources. This stack adds lightweight,kj::EventLoop::Id-checked opt-in wrappers soSendfutures and callbacks that stay on the same KJ event loop can hold KJ objects and await C++ promises without uncheckedunsafeat call sites.Stack
kj-rs: add LoopChecked—Send + !Syncwrapper storing a value alongsidekj::EventLoop::Id::current()(8 bytes,Copy, zero atomics). Failsget()/get_mut()/get_pin_mut()off-loop (into_inner()returnsErr(self)), panics if polled off-loop, and aborts on drop off-loop (including after loop destruction) or insidekj::DisallowAsyncDestructorsScope. Intended to be wrapped inside a private field of a!Tracedbinding struct at construction.io-context: require await_io_and_run's callback to be Send— Adds+ Sendtoawait_io_and_run/await_iocallbacks. WrapsSpanBuilderandTraceContextinLoopCheckedat construction (removingThreadBoundSpan'sunsafe impl Send) while keeping them!Tracedso JSG resources must still useIoContext::add_span().kj-rs: add KjFuture::into_send()—extern "C++"async fnnow requires a current KJ event loop and returns a!Send,!Unpinsealedkj_rs::KjFuture..into_send()is a safe opt-in returningSendKjFuture<Self>(Send + !Sync + !Unpin, preserving input borrows) that returns an error if polled off-loop and aborts if dropped off-loop. UpdatesTokioEventPort::cancelSpawnedTasks()to re-enter its loop'sWaitScopeif needed so tasks drop on-loop.Overhead
Measured with cross-language LTO: ~1.5 ns per loop check, ~3.9 ns per
LoopCheckedcreate/read/drop lifecycle, and ~5.5 ns per awaitedSendKjFuture(zero atomics or allocations).Testing
!SendKjFuture,Send + !SyncSendKjFuture, borrow preservation acrossinto_send(),!Sync/unsafe new()onLoopChecked,Sendcallbacks onawait_io_and_run/await_io,SpanBuilderrejection in#[jsg_resource]/#[jsg_traced], and taken spans inawait_io_and_run.kj_testsuites (loop-checked-test.c++,send-kj-future-test.c++,tokio-event-port-test.c++) covering off-loop access/poll errors, off-loop drop aborts (unpolled, pending, armed, and post-loop destruction),DisallowAsyncDestructorsScope/AllowAsyncDestructorsScope, andTokioEventPortteardown afterWaitScope.