← Back to Pull requests

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

Open
unknown opened this pull request with 353 lines diff across 4 files
View on GitHub
unknown unknown commented on Nov 24, 2026 04:47 UTC
Author

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.
  • Diff: 353 lines (+264 / -89) across 4 files Reviewer: nathanwhit Review duration: 6539m
    All Vouch review confidence checks passed
    Residual risk 0.24 = Change Risk (0.42) × (1 − Review Confidence (0.43)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.42 · 353 lines diff across 4 files
    0.42
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.02 · 1 substantive comment(s)
    0.02
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    42%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.351
    Shallow Review Depth shallow_review_depth
    0.344
    Real PR Conversation Timeline
    1 comments
    "Review active on #8857"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 43.0% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 42.5% (MEDIUM) · Higher = larger blast radius
    42.5%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 43.0% · Lower = rushed or shallow review
    43.0%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 24.2% · Safe to merge
    24.2%