Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
8b513f4
Service the regular loop's concurrent queue while a macro is being wa…
robobun Aug 21, 2026
f202cb0
[autofix.ci] apply automated fixes
autofix-ci[bot] Aug 21, 2026
b19e793
Tighten comments
robobun Aug 21, 2026
2386c5a
Use into_task for the batch move, cover the un-awaited digest exit
robobun Aug 21, 2026
e6933c1
Fold take_concurrent_tasks into take_concurrent_batch
robobun Aug 21, 2026
6a2a313
Share the ticket issue path between ticket and regular_ticket
robobun Aug 21, 2026
c6e5d93
Cover the other regular-loop producers a macro can await
dylan-conway Aug 22, 2026
5eb0d4d
Route completions by the loop current when the work was initiated
dylan-conway Aug 22, 2026
30dbe52
[autofix.ci] apply automated fixes
autofix-ci[bot] Aug 22, 2026
9e92026
Assert the un-awaited digest continuation runs before exit
robobun Aug 22, 2026
c0e7d52
Take LoopKind across the FFI as the enum, not u8
dylan-conway Aug 22, 2026
ea43333
Capture the loop for cross-thread MessagePort and BroadcastChannel de…
dylan-conway Aug 22, 2026
7da4c35
[autofix.ci] apply automated fixes
autofix-ci[bot] Aug 22, 2026
5e922f9
Name BunLoopKind values loopKind, not loop
dylan-conway Aug 22, 2026
a5ead42
Make loopKind postTaskTo's second parameter, with no default
dylan-conway Aug 22, 2026
6c974b9
[autofix.ci] apply automated fixes
autofix-ci[bot] Aug 22, 2026
a87fb37
Restore multi-line lambda layout at the postTaskTo call sites
dylan-conway Aug 22, 2026
add5509
Inline postTaskToWorkerObject at its call sites
dylan-conway Aug 22, 2026
69704ce
JSCTaskScheduler: keep the two pending containers, store the loop kin…
dylan-conway Aug 22, 2026
61822af
Use the currentLoopKind accessor at the JSWorker request-reply sites
robobun Aug 22, 2026
1e73951
postTaskTo: use the caller's loopKind as given
dylan-conway Aug 22, 2026
33cb02c
JSCTaskScheduler: minimal change — store the loop kind as the map val…
dylan-conway Aug 22, 2026
a622a44
WebCrypto: capture the loop kind at dispatch and pass it to postTaskT…
dylan-conway Aug 22, 2026
f094e2b
event_loop.rs: keep the original drain, add only the finished-macro a…
dylan-conway Aug 22, 2026
80078b9
Rename finished_macro_loop to macro_loop_if_not_running
dylan-conway Aug 22, 2026
8f1658d
Merge branch 'main' into farm/4186ec60/macro-webcrypto-hang
dylan-conway Aug 22, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions src/jsc/CppTask.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,8 +84,11 @@ extern "C" fn ConcurrentCppTask__createAndRun(
) {
crate::mark_binding!();
let vm = global.bun_vm();
vm.event_loop_shared().ref_keep_alive();
let ticket = vm.ticket();
// The result comes back through `postTaskTo` → `post_cpp_task`, a weak
// post that always lands on the regular loop, so the keep-alive and the
// ticket that releases it live there too.
Comment thread
robobun marked this conversation as resolved.
Resolved
vm.regular_event_loop.ref_keep_alive();
let ticket = vm.regular_ticket();
WorkPool::schedule_new(ConcurrentCppTask {
cpp_task,
ticket,
Expand Down
15 changes: 15 additions & 0 deletions src/jsc/VmHandle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -516,6 +516,21 @@
);
Ticket::issue(&h.0, self.current_loop_kind())
}

/// Like [`ticket`](Self::ticket), but pinned to the regular loop: for
/// work whose completion comes back through a weak post
/// ([`VmHandle::post_cpp_task`]), which always lands there.
Comment thread
robobun marked this conversation as resolved.
Resolved
#[track_caller]
#[inline]
pub fn regular_ticket(&self) -> Ticket {
let h = self.handle_ref();
h.assert_js_thread();
debug_assert!(
h.0.state() != State::Closed,
"off-thread work started after the VM finished draining"
);
Ticket::issue(&h.0, LoopKind::Regular)
}

Check warning on line 533 in src/jsc/VmHandle.rs

View check run for this annotation

Claude / Claude Code Review

regular_ticket() duplicates ticket() body

`regular_ticket()` copies `ticket()`'s body verbatim — same `handle_ref()`, `assert_js_thread()`, identical `debug_assert!` — differing only in the final `LoopKind` argument. Per REVIEW.md's dedup rule, extract a private `#[track_caller] #[inline] fn issue_ticket(&self, kind: LoopKind) -> Ticket` with the shared body and reduce both public fns to one-liners (same class of feedback as the `take_concurrent_tasks`/`take_concurrent_batch` fold in e6933c1).
Comment thread
robobun marked this conversation as resolved.
Resolved
}

// ── Test suite only: deterministic late completions ───────────────────────
Expand Down
104 changes: 45 additions & 59 deletions src/jsc/event_loop.rs
Original file line number Diff line number Diff line change
Expand Up @@ -586,47 +586,50 @@ impl EventLoop {

self.run_imminent_gc_timer();

let concurrent = self.concurrent_tasks.pop_batch();
let count = concurrent.count;
if count == 0 {
return 0;
}

let mut iter = concurrent.iterator();
let start_count = self.tasks.readable_length();
let _ = self.tasks.ensure_unused_capacity(count);

// Defer destruction of the ConcurrentTask to avoid issues with pointer aliasing
let mut to_destroy: Option<*mut ConcurrentTaskItem> = None;

loop {
let task = iter.next();
if task.is_null() {
break;
}
if let Some(dest) = to_destroy.take() {
// SAFETY: dest was returned by iterator and marked auto_delete; uniquely owned here
let _ = unsafe { bun_core::heap::take(dest) };
}

// SAFETY: `task` is non-null (checked above) and owned by this
// batch; only shared reads follow (`auto_delete`, the `task` copy).
let task_ref = unsafe { &*task };
if task_ref.auto_delete() {
to_destroy = Some(task);
}

// LinearFifo's fields are private — `write_item` is the
// public path (single-slot copy, same complexity).
let _ = self.tasks.write_item(task_ref.task);
let posted = self.concurrent_tasks.pop_batch();
self.take_concurrent_batch(posted);
if let Some(regular) = self.regular_loop_during_macro() {
regular.apply_concurrent_ref_delta();
let posted = regular.concurrent_tasks.pop_batch();
self.take_concurrent_batch(posted);
}
self.tasks.readable_length() - start_count
Comment thread
robobun marked this conversation as resolved.
Resolved
}

if let Some(dest) = to_destroy {
// SAFETY: see above
let _ = unsafe { bun_core::heap::take(dest) };
/// Move a popped batch into `self.tasks`, freeing the heap
/// `ConcurrentTask` carriers that asked for it.
Comment thread
robobun marked this conversation as resolved.
Resolved
fn take_concurrent_batch(
&mut self,
batch: bun_threading::unbounded_queue::Batch<ConcurrentTaskItem>,
) {
if batch.count == 0 {
return;
}
let _ = self.tasks.ensure_unused_capacity(batch.count);
let mut iter = batch.iterator();
while let Some(node) = NonNull::new(iter.next()) {
// SAFETY: a node of the popped batch; the iterator has already
// moved past it.
let task = unsafe { ConcurrentTaskItem::into_task(node) };
let _ = self.tasks.write_item(task);
}
Comment thread
robobun marked this conversation as resolved.
Resolved
}

self.tasks.readable_length() - start_count
/// The regular loop, when this is the macro loop a macro wait is ticking.
/// Weak posts (`VmHandle::post_cpp_task` — a WebCrypto result through
/// `postTaskTo`) always land on the regular loop, which does not tick
/// during the wait, so the wait services that queue too.
Comment thread
robobun marked this conversation as resolved.
Resolved
fn regular_loop_during_macro(&self) -> Option<&EventLoop> {
Comment thread
robobun marked this conversation as resolved.
Resolved
let vm = self.vm();
// SAFETY: `vm` is the live owning VM (set in `init()`). `addr_of!`
// projects to sibling fields without materializing a
// `&VirtualMachine` that would alias the `&mut self` callers hold.
unsafe {
(core::ptr::addr_of!((*vm).macro_mode).read()
&& core::ptr::eq(self, core::ptr::addr_of!((*vm).macro_event_loop)))
.then(|| &*core::ptr::addr_of!((*vm).regular_event_loop))
}
}

/// Fold refs/unrefs queued through `ref_keep_alive`/`unref_keep_alive`
Expand Down Expand Up @@ -838,36 +841,19 @@ impl EventLoop {
}
}

/// Move whatever other threads posted (`concurrent_tasks`) into
/// `self.tasks`, freeing the heap `ConcurrentTask` carriers, so one pass
/// over `self.tasks` releases everything. Called by `release_queued_tasks`
/// in teardown, after `join_child_workers()` (every child has posted its
/// close task by then) and before the JSC VM is destroyed (so captured
/// `Ref<>`s in queued C++ lambdas drop against a live heap).
fn take_concurrent_tasks(&mut self) {
let mut iter = self.concurrent_tasks.pop_batch().iterator();
loop {
let node = iter.next();
if node.is_null() {
break;
}
// SAFETY: `node` is non-null and owned by the popped batch; the
// iterator advanced past it before returning.
let task =
unsafe { ConcurrentTask::ConcurrentTask::into_task(NonNull::new_unchecked(node)) };
let _ = self.tasks.write_item(task);
}
}

/// Release, without running, every task still queued — what other
/// threads posted and what this thread enqueued — through each type's
/// `Taskable::release_unrun`, and refuse (release on arrival) anything
/// enqueued from here on. Teardown phase B (JS thread, script forbidden,
/// JSC heap alive, children joined): called on every turn of the wait, and
/// once more after `Closed`.
/// once more after `Closed`. Runs after `join_child_workers()` (every
/// child has posted its close task by then) and before the JSC VM is
/// destroyed (so captured `Ref<>`s in queued C++ lambdas drop against a
/// live heap).
Comment thread
robobun marked this conversation as resolved.
Resolved
pub fn release_queued_tasks(&mut self) {
self.closed_for_tasks = true;
self.take_concurrent_tasks();
let posted = self.concurrent_tasks.pop_batch();
self.take_concurrent_batch(posted);
let _ = self.promote_yield_tasks();
while let Some(task) = self.tasks.read_item() {
// SAFETY: JS thread, heap alive; `task` just left the queue.
Expand Down
79 changes: 79 additions & 0 deletions test/regression/issue/39900.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import { expect, test } from "bun:test";
import { bunEnv, bunExe, tempDir } from "harness";

// https://github.com/oven-sh/bun/issues/39900
// A macro that awaits crypto.subtle.digest() hung forever.

const expected = Buffer.from(await crypto.subtle.digest("SHA-256", new Uint8Array(4096))).toString("base64url");

const files = {
"macro.ts": `export async function sha() {
const digest = await crypto.subtle.digest("SHA-256", new Uint8Array(4096));
return Buffer.from(digest).toString("base64url");
}
`,
"index.ts": `import { sha } from "./macro.ts" with { type: "macro" };
console.log(sha());
`,
};

test.concurrent("macro that awaits crypto.subtle.digest resolves under bun run", async () => {
using dir = tempDir("39900-run", files);
await using proc = Bun.spawn({
cmd: [bunExe(), "index.ts"],
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
env: bunEnv,
cwd: String(dir),
stderr: "pipe",
});
const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);
expect(stderr).toBe("");
// A debug build also logs "[macro] call sha" to stdout.
expect(stdout).toContain(`${expected}\n`);
expect(exitCode).toBe(0);
});

// The keep-alive the WebCrypto work queue releases from the pool thread must
// land on a loop that still ticks once the macro returned, or the process
// never exits.
test.concurrent("macro that starts crypto.subtle.digest without awaiting still exits", async () => {
using dir = tempDir("39900-unawaited", {
"macro.ts": `export function start() {
crypto.subtle.digest("SHA-256", new Uint8Array(4096)).then(() => console.log("settled"));
return 1;
}
`,
"index.ts": `import { start } from "./macro.ts" with { type: "macro" };
console.log(start());
`,
});
await using proc = Bun.spawn({
cmd: [bunExe(), "index.ts"],
env: bunEnv,
cwd: String(dir),
stderr: "pipe",
});
const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);
expect(stderr).toBe("");
expect(stdout).toContain("1\n");
expect(exitCode).toBe(0);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
});

test.concurrent("macro that awaits crypto.subtle.digest resolves under Bun.build", async () => {
using dir = tempDir("39900-build", {
...files,
"build.ts": `const result = await Bun.build({ entrypoints: ["./index.ts"] });
if (!result.success) throw new AggregateError(result.logs);
console.log(await result.outputs[0].text());
`,
});
await using proc = Bun.spawn({
cmd: [bunExe(), "build.ts"],
env: bunEnv,
cwd: String(dir),
stderr: "pipe",
});
const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);
expect(stderr).toBe("");
expect(stdout).toContain(expected);
expect(exitCode).toBe(0);
});
Loading