Skip to content

kj-rs: add LoopChecked and KjFuture::into_send() for Send futures on a KJ event loop - #8857

Open
nathanwhit wants to merge 3 commits into
mainfrom
nathanwhit/kj-rs-loop-checked
Open

nathanwhit wants to merge 3 commits into
mainfrom
nathanwhit/kj-rs-loop-checked

Conversation

@nathanwhit

@nathanwhit nathanwhit commented Nov 24, 2026 •

Copy link
Copy Markdown
Member

Why

In edgeworker, a KJ event loop migrates between OS threads together with its tasks, so IoContext::await_io and IoContext::await_io_and_run require Send futures (and now callbacks) to rule out OS-thread-pinned state (MutexGuard, Rc cloned from a thread_local!, etc.).

Bridged C++ async fn promises and KjOwn<T> handles are !Send by default so they cannot accidentally cross into tokio::spawn or JSG resources. This stack adds lightweight, kj::EventLoop::Id-checked opt-in wrappers so Send futures and callbacks that stay on the same KJ event loop can hold KJ objects and await C++ promises without unchecked unsafe at call sites.

Stack

  1. kj-rs: add LoopChecked — Send + !Sync wrapper storing a value alongside kj::EventLoop::Id::current() (8 bytes, Copy, zero atomics). Fails get()/get_mut()/get_pin_mut() off-loop (into_inner() returns Err(self)), panics if polled off-loop, and aborts on drop off-loop (including after loop destruction) or inside kj::DisallowAsyncDestructorsScope. Intended to be wrapped inside a private field of a !Traced binding struct at construction.
  2. io-context: require await_io_and_run's callback to be Send — Adds + Send to await_io_and_run / await_io callbacks. Wraps SpanBuilder and TraceContext in LoopChecked at construction (removing ThreadBoundSpan's unsafe impl Send) while keeping them !Traced so JSG resources must still use IoContext::add_span().
  3. kj-rs: add KjFuture::into_send() — extern "C++" async fn now requires a current KJ event loop and returns a !Send, !Unpin sealed kj_rs::KjFuture. .into_send() is a safe opt-in returning SendKjFuture<Self> (Send + !Sync + !Unpin, preserving input borrows) that returns an error if polled off-loop and aborts if dropped off-loop. Updates TokioEventPort::cancelSpawnedTasks() to re-enter its loop's WaitScope if needed so tasks drop on-loop.

Overhead

Measured with cross-language LTO: ~1.5 ns per loop check, ~3.9 ns per LoopChecked create/read/drop lifecycle, and ~5.5 ns per awaited SendKjFuture (zero atomics or allocations).

Testing

  • Compile tests for !Send KjFuture, Send + !Sync SendKjFuture, borrow preservation across into_send(), !Sync / unsafe new() on LoopChecked, Send callbacks on await_io_and_run / await_io, SpanBuilder rejection in #[jsg_resource] / #[jsg_traced], and taken spans in await_io_and_run.
  • Runtime kj_test suites (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, and TokioEventPort teardown after WaitScope.

@nathanwhit
nathanwhit requested review from a team as code owners November 24, 2026 04:47

@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 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 fn is 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 reads kj::EventLoop::Id::current(), so a bridged async fn called on a thread with no event loop throws. The comment says the promise stays owned in that case, but no test exercises this path.
  • SendKjFuture returns Poll::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 !Send as a blanket rule, but KjOwn<T> is Send when T: 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

Comment thread src/rust/cxx/kj-rs/promise.h Resolved
Comment thread src/rust/cxx/kj-rs/promise.rs Resolved
Comment thread src/rust/cxx/kj-rs/README.md Resolved
@nathanwhit
nathanwhit force-pushed the nathanwhit/kj-rs-loop-checked branch from 3b131a7 to 1c902af Compare November 24, 2026 19:19

@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 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 fn called with no current event loop. (src/rust/cxx/kj-rs/promise.h:72)
  • [INFO] The SendKjFuture doc 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>&&) reads kj::EventLoop::Id::current() before it takes the promise. A bridged async fn called with no event loop therefore throws while the promise still owns its node. No test exercises this path; the new promise-test.rs only has static Send/!Sync assertions.
  • src/rust/cxx/kj-rs/promise.rs:165: SendKjFuture returns Poll::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, but KjOwn<T> is Send when T: Send. (src/rust/cxx/kj-rs/README.md:44)
View full review
  • src/rust/cxx/kj-rs/README.md:44: the README says a KjOwn<T> of a C++ type is !Send as a blanket rule. In fact KjOwn<T> is Send whenever T: 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

Comment thread src/rust/cxx/kj-rs/promise.rs Resolved
@nathanwhit
nathanwhit force-pushed the nathanwhit/kj-rs-loop-checked branch from 1c902af to cd69d00 Compare November 24, 2026 20:50

@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 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-commenter

codecov-commenter commented Nov 24, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 56.09756% with 72 lines in your changes missing coverage. Please review.
✅ Project coverage is 69.99%. Comparing base (1b795e9) to head (0b8484f).
⚠️ Report is 202 commits behind head on main.

Files with missing lines Patch % Lines
src/rust/cxx/kj-rs/promise.rs 38.09% 26 Missing ⚠️
src/rust/cxx/kj-rs/loop_checked.rs 57.40% 23 Missing ⚠️
src/rust/cxx/kj-rs/awaiter.rs 41.17% 10 Missing ⚠️
src/rust/cxx/kj-rs/loop-checked.c++ 44.44% 9 Missing and 1 partial ⚠️
src/workerd/io/io-context/trace.rs 90.00% 2 Missing ⚠️
src/rust/cxx/kj-rs/lib.rs 75.00% 1 Missing ⚠️
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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@nathanwhit

Copy link
Copy Markdown
Member Author

The part I am most uncertain about is whether or not it's worth trying to make this all fully sound. Requiring Send on await_io futures is technically correct and necessary for soundness, but creates complexity trying to satisfy that bound (as seen in this PR).

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 Send bound on await_io, leave it safe, and rely on review and lints catching the thread safety hazards prevented by Send right now.

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 Rc in a thread_local and use that from a future (one pattern that would potentially cause UB), but auditing third party dependencies is a different story - especially when to the rest of the rust ecosystem !Send constitutes a promise that the future will not change threads. A promise which we would subvert by (unsoundly, but conveniently) dropping that bound.

@nathanwhit
nathanwhit force-pushed the nathanwhit/kj-rs-loop-checked branch from cd69d00 to 53201c2 Compare November 25, 2026 23:03

@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 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

@bartlomieju

Copy link
Copy Markdown
Collaborator

Some data for this from the workerd repl port (#8914), since it hit exactly this question.

The REPL is host code in the workerd binary. Its JS handles hold Rc state shared with the Rust server crate's in-process servers, and its promises await futures over that state. It first used non-Send variants, await_io_local and IoOwnedLocal, which are the unsound pattern you pointed out. So I tried porting it onto this PR, with await_io, IoOwned and LoopChecked around the KJ objects. It stops at the server crate:

  • The Rcs in InProcessServer are cloned into its run task and into every channel it hands out, so LoopChecked::new's "an Rc with a clone outside value" rules it out.
  • Those tasks run on kj-rs-tokio's thread-local LocalSet, which the README says should hold plain !Send values.
  • Meeting the bound would mean moving workerd_server to Arc/Mutex. The locks would never be contended, and they'd protect loops that kj-rs-tokio already pins to their thread.

So for hosts in the workerd binary the complexity is real and buys nothing, because their loops can't move. For API crates that also run in the internal project, the hazard is real, and I agree the third-party dependency argument is the strong one: a dependency may well rely on !Send meaning "stays on this thread".

That suggests keeping the Send bound on await_io and making the non-Send path something only pinned-loop code can reach. Two options:

  1. Move await_io_local/IoOwnedLocal into a host-only crate whose Bazel visibility is limited to //src/workerd/server/..., so a crate shared with the internal project can't depend on it. The pinned-loop assumption is then written once, in that crate, and reviewers see any change to the visibility list.
  2. Keep everything in LoopChecked, but reword new()'s contract so that an Rc whose clones are all held by values on the same loop is allowed, which is the kj::Refcounted case C++ relies on. Hosts would then write await_io(unsafe { LoopChecked::new(..) }) with a SAFETY comment at each call site.

Neither option seems great. Would either work for you?

@jasnell

jasnell commented Nov 25, 2026

Copy link
Copy Markdown
Collaborator

AI generated review comments:

  1. The loop check allocates and changes loop behaviour. event_loop_id_is_current() (kj-rs/loop-checked.c++) calls kj::tryGetCurrentThreadExecutor(), which goes through EventLoop::getExecutor() (kj/async.c++:1879-1884). That creates the loop's Executor the first time.

    • This contradicts the "zero allocations" claim.
    • On a loop with no event port (common in tests), having an executor changes wait(): instead of failing with "Nothing to wait for; this thread would hang forever." (:1957), it blocks forever.
    • TokioEventPort::cancelSpawnedTasks() has the same side effect.
    • Suggested fix: add a check to KJ that doesn't allocate, e.g. EventLoop::Id::isCurrent() or tryCurrent(). It would mirror assertCurrentEventLoop() (:1905-1908), which just reads the thread-local.
  2. cancelSpawnedTasks() only enters the port's loop when no loop is current. If a different loop is current on that thread, it enters nothing, and the tasks are dropped off their loop, which aborts. That's contrived, but checking for this port's loop specifically and failing clearly otherwise costs nothing.

  3. AsyncTracker is tied to the OS thread (existing problem, surfaced here). async-trace.c++ identifies its owner by the address of a thread_local, and onOwnerThread() silently drops calls from any other OS thread. The PR relies on this for TraceContext and calls it sound, which is true. But it also means edgeworker loses async-trace data for an IoContext after its first migration. Since this PR makes EventLoop::Id cheap to use, the tracker could key on the loop instead. That would be a follow-up.

  4. The LoopChecked::new() safety rule and README wording are inaccurate. "Read no thread-local but the current event loop, as KJ's own do" isn't true. KJ reads other thread-locals, such as disallowAsyncDestructorsScope and the exception-callback stack, and spans reach AsyncTracker::inTurn(). Those are fine because they are set and cleared without returning to the loop. The real rule, per the threading doc, is: no thread-local state that persists across a return to the event loop.

  5. The bridge has the same gap (latent). Rust futures handed to C++ through extern "Rust" async fn are boxed as dyn Future + 'a without Send (cxx/macro/src/expand.rs:1348). In edgeworker they ride migrating loops too. Today the only such functions are memory-cache's waiter_wait and io-context's, and io-context's already wrap Send futures, so nothing is broken now. But it bears on Nathan's open question: if Send is the line, the bridge should eventually enforce it as well. I'd keep Send, for the reason he gives about third-party crates.

  6. Minor:

    • The PR adds "edgeworker" to public workerd code in 5 places, plus in commit messages. workerd already mentions it elsewhere, so it's your convention rather than a rule. Generic wording works: "an embedder may run a loop on different OS threads between turns".
    • await-io-callback-handles-are-scoped.rs now expects the Send error, so it no longer tests the lifetime scoping for await_io.

@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 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.rs
  • src/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 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. (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() calls kj::tryGetCurrentThreadExecutor() to decide whether a loop is current. In KJ this goes through EventLoop::getExecutor(), which creates an atomically refcounted Executor the first time it is called. Every LoopChecked access and drop, and every SendKjFuture poll and drop, runs this check, so the first one on each loop allocates an Executor.
    • This contradicts the "zero atomics or allocations" claim.
    • On a loop with no event port, a loop that has an Executor waits in wait() for cross-thread events. Without one, it fails with "Nothing to wait for". A test that touches a LoopChecked could 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-tokio teardown 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;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ WARNING · 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.

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.

@nathanwhit

Copy link
Copy Markdown
Member Author

Option 1 sounds right to me. The pinned-loop assumption is a property of the workerd binary, so it should live there once rather than as an unsafe at every call site. io-context can expose an unsafe non-Send await_io whose contract is that the loop stays on its thread, and a host-only crate whose visibility is limited to //src/workerd/server/... wraps it safely for the REPL. API crates shared with the internal build can't reach it.

Separately, I'll loosen LoopChecked::new()'s contract to allow an Rc whose clones all belong to the same loop (the kj::Refcounted case), since that's the actual requirement.

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.
@nathanwhit
nathanwhit force-pushed the nathanwhit/kj-rs-loop-checked branch from d2eec2d to 0b8484f Compare November 26, 2026 05:31

@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 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 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. (src/rust/cxx/kj-rs/loop-checked.c++:19)
View full review
  • src/rust/cxx/kj-rs/loop-checked.c++:19: every LoopChecked access and drop, and every SendKjFuture poll and drop, runs event_loop_id_is_current(). It first calls kj::tryGetCurrentThreadExecutor(), which in KJ probably goes through EventLoop::getExecutor() and creates an atomically refcounted Executor the 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".
    • TokioEventPort loops have a port, so they are not affected.
  • io-context/lib.rs, trace.rs and loop_checked.rs look 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 guybedford left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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> {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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) |

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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()?;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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") {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

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.

5 participants