Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
9 changes: 7 additions & 2 deletions src/jsc/CppTask.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,8 +84,13 @@ 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 lands on the regular loop even while a macro runs, so the
// keep-alive and the ticket that releases it live there too: a macro-loop
// delta posted from the pool thread would sit unfolded once the macro
// returned (that loop only ticks inside a macro wait).
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
16 changes: 16 additions & 0 deletions src/jsc/VmHandle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -516,6 +516,22 @@ impl VirtualMachine {
);
Ticket::issue(&h.0, self.current_loop_kind())
}

/// Like [`ticket`](Self::ticket), but pinned to the regular loop whatever
/// loop is current — for work whose completion comes back through a weak
/// post ([`VmHandle::post_cpp_task`]), which always lands on the regular
/// loop.
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)
}
}

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

self.run_imminent_gc_timer();

let concurrent = self.concurrent_tasks.pop_batch();
let count = concurrent.count;
if count == 0 {
return 0;
let start_count = self.tasks.readable_length();
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
}

let mut iter = concurrent.iterator();
let start_count = self.tasks.readable_length();
let _ = self.tasks.ensure_unused_capacity(count);
/// 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 mut iter = batch.iterator();
let _ = self.tasks.ensure_unused_capacity(batch.count);

// Defer destruction of the ConcurrentTask to avoid issues with pointer aliasing
let mut to_destroy: Option<*mut ConcurrentTaskItem> = None;
Expand Down Expand Up @@ -625,8 +639,23 @@ impl EventLoop {
// SAFETY: see above
let _ = unsafe { bun_core::heap::take(dest) };
}
}

self.tasks.readable_length() - start_count
/// The regular loop, when this is the macro loop a macro wait is ticking.
/// A cross-thread post that carries no ticket (`VmHandle::post_cpp_task` —
/// a WebCrypto result delivered through `postTaskTo`) always lands on the
/// regular loop, which does not tick while a macro is being waited on, so
/// the wait services that queue too or a macro could never await such work.
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
62 changes: 62 additions & 0 deletions test/regression/issue/39900.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
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: the digest result
// is posted to the regular event loop, which does not tick while the macro's
// promise is being waited on. The process exiting afterwards also covers the
// keep-alive the WebCrypto work queue releases from the pool thread.
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

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"],
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);
},
);

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