From 4722cefdcfb55d1e1fbabe386e89d84dc47cbf23 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sat, 15 Aug 2026 05:05:38 +0000 Subject: [PATCH 1/9] bun test: attribute late expect() calls of an abandoned test to that test When the runner gives up on a test or hook whose callback is still running (it timed out, or an unhandled error failed it while it was awaiting), the callback keeps running while the next entry executes. expect() attributed itself to whatever entry was running at the time, so a late toMatchSnapshot() was written under the next test's name (and shifted that test's own snapshot numbering), and late expect() calls were charged to the next test's expect.assertions() count. Every test and hook invocation now runs under an async context carrying an AsyncContextRef for that invocation. The sequence keeps the same RefData while the callback is in flight and marks it abandoned when the runner moves on without the callback having completed. expect(), expect.assertions() and expect.hasAssertions() called from JS that descends from an abandoned invocation attribute to it: file snapshot matchers reject with the existing "after the test has finished executing" error before the snapshot file is created, and the calls no longer count against the running test. Invocations that completed are never consulted, so callbacks registered by an earlier entry and invoked later still attribute to the running entry. Callbacks passed to test()/describe()/hooks are now wrapped with their registration-time async context when they are stored rather than when the arguments are parsed, so registration keeps looking at the real function: its length decides whether it takes done, and .each binds the row to it. This also fixes both of those for callbacks registered inside an AsyncLocalStorage store, where the wrapper was previously inspected instead. --- src/js/node/async_hooks.ts | 14 +- src/jsc/bindings/AsyncContextFrame.cpp | 98 +++++++++ src/jsc/generated_classes_list.rs | 1 + src/runtime/cli/test_command.rs | 4 + src/runtime/test_runner/AsyncContextRef.rs | 64 ++++++ src/runtime/test_runner/Collection.rs | 2 +- src/runtime/test_runner/Execution.rs | 66 +++++- src/runtime/test_runner/ScopeFunctions.rs | 4 +- src/runtime/test_runner/bun_test.rs | 37 +++- src/runtime/test_runner/expect.rs | 108 ++++++---- src/runtime/test_runner/jest.classes.ts | 13 ++ src/runtime/test_runner/jest.rs | 4 + src/runtime/test_runner/mod.rs | 2 + src/runtime/test_runner/snapshot.rs | 23 +- test/js/bun/test/expect-assertions.test.ts | 40 ++++ test/js/bun/test/jest-each.test.ts | 35 +++- .../snapshot-tests/snapshots/snapshot.test.ts | 197 +++++++++++++++++- 17 files changed, 651 insertions(+), 61 deletions(-) create mode 100644 src/runtime/test_runner/AsyncContextRef.rs diff --git a/src/js/node/async_hooks.ts b/src/js/node/async_hooks.ts index ade40926f8da..f543eeae1945 100644 --- a/src/js/node/async_hooks.ts +++ b/src/js/node/async_hooks.ts @@ -22,6 +22,11 @@ // each key is an AsyncLocalStorage object and the value is the associated value. There are a ton of // calls to $assert which will verify this invariant (only during bun-debug) // +// The one other key that can appear is bun:test's AsyncContextRef (src/runtime/test_runner/AsyncContextRef.rs), +// which the test runner adds while a test or hook callback runs; it is stored as both key and value and +// is only ever looked up from native code, so everything in here just carries it along like any other +// pair it does not own. +// const setAsyncHooksEnabled = $newCppFunction("NodeAsyncHooks.cpp", "jsSetAsyncHooksEnabled", 1); const cleanupLater = $newCppFunction("NodeAsyncHooks.cpp", "jsCleanupLater", 0); const { validateFunction, validateString, validateObject } = require("internal/validators"); @@ -49,7 +54,7 @@ function assertValidAsyncContextArray(array: unknown): array is ReadonlyArray 0, "AsyncContextData should be undefined if empty, got", Bun.inspect(array, { depth: 1 })); for (var i = 0; i < array.length; i += 2) { $assert( - array[i] instanceof AsyncLocalStorage, + array[i] instanceof AsyncLocalStorage || isBunTestAsyncContextRef(array[i]), `Odd indexes in AsyncContextData should be an array of AsyncLocalStorage\nIndex %s was %s`, i, array[i], @@ -58,12 +63,17 @@ function assertValidAsyncContextArray(array: unknown): array is ReadonlyArray | undefined) { if (value === undefined) return "undefined"; let str = "{\n"; for (var i = 0; i < value.length; i += 2) { - str += ` ${value[i].__id__}: typeof = ${typeof value[i + 1]}\n`; + str += ` ${isBunTestAsyncContextRef(value[i]) ? "bun:test" : value[i].__id__}: typeof = ${typeof value[i + 1]}\n`; } str += "}"; return str; diff --git a/src/jsc/bindings/AsyncContextFrame.cpp b/src/jsc/bindings/AsyncContextFrame.cpp index fd11c1d8291a..fb118495095b 100644 --- a/src/jsc/bindings/AsyncContextFrame.cpp +++ b/src/jsc/bindings/AsyncContextFrame.cpp @@ -1,7 +1,10 @@ #include "root.h" #include "ZigGlobalObject.h" +#include "ZigGeneratedClasses.h" #include "AsyncContextFrame.h" +#include #include +#include #if ASSERT_ENABLED #include @@ -131,3 +134,98 @@ JSValue AsyncContextFrame::profiledCall(JSGlobalObject* global, JSValue function return AsyncContextFrame::call(global, functionObject, thisValue, args); } #undef ASYNCCONTEXTFRAME_CALL_IMPL + +// ── bun:test (src/runtime/test_runner/AsyncContextRef.rs) ────────────────── +// +// The async context value (AsyncLocalStorage's storage, see node/async_hooks.ts) +// is an array of [key, value, ...] pairs that promise reactions, timers and +// native callbacks snapshot and restore. bun:test adds one pair per test or +// hook invocation, with the invocation's AsyncContextRef as both key and value, +// so that code still running on behalf of that invocation can be told apart +// from the entry the runner is executing now. + +static bool isAsyncContextRef(JSValue value) +{ + return dynamicDowncast(value) != nullptr; +} + +// AsyncContextFrame::call only unwraps the wrappers withAsyncContextIfNeeded() +// creates while a context is installed when tracking is enabled (normally +// constructing an AsyncLocalStorage enables it). node:vm contexts copy the flag +// when they are created, so bun test enables it before loading each test file. +extern "C" [[ZIG_EXPORT(nothrow)]] void Bun__AsyncContextRef__enableTracking(JSC::JSGlobalObject* globalObject) +{ + globalObject->setAsyncContextTrackingEnabled(true); +} + +// Returns `callback` wrapped so that it runs with the context it would have run +// with anyway (the one it was registered under if it is already wrapped, else +// the current one) plus the pair (ref, ref). A pair left over from the +// invocation that registered the callback is dropped, so a context carries at +// most one ref: the innermost invocation. +extern "C" [[ZIG_EXPORT(zero_is_throw)]] JSC::EncodedJSValue Bun__AsyncContextRef__bind(JSC::JSGlobalObject* globalObject, JSC::EncodedJSValue callbackValue, JSC::EncodedJSValue refValue) +{ + auto& vm = JSC::getVM(globalObject); + auto scope = DECLARE_THROW_SCOPE(vm); + + JSValue callback = JSValue::decode(callbackValue); + JSValue ref = JSValue::decode(refValue); + ASSERT(isAsyncContextRef(ref)); + + JSValue baseContext; + if (auto* frame = dynamicDowncast(callback)) { + baseContext = frame->context.get(); + callback = frame->callback.get(); + } else { + baseContext = globalObject->m_asyncContextData.get()->getInternalField(0); + } + + MarkedArgumentBuffer entries; + if (auto* base = dynamicDowncast(baseContext)) { + unsigned length = base->length(); + entries.ensureCapacity(length + 2); + for (unsigned i = 0; i < length; i += 2) { + JSValue key = base->getIndex(globalObject, i); + RETURN_IF_EXCEPTION(scope, {}); + JSValue value = i + 1 < length ? base->getIndex(globalObject, i + 1) : jsUndefined(); + RETURN_IF_EXCEPTION(scope, {}); + if (isAsyncContextRef(key)) + continue; + entries.append(key); + entries.append(value); + } + } + entries.append(ref); + entries.append(ref); + if (entries.hasOverflowed()) [[unlikely]] { + throwOutOfMemoryError(globalObject, scope); + return {}; + } + + JSArray* context = constructArray(globalObject, static_cast(nullptr), entries); + RETURN_IF_EXCEPTION(scope, {}); + + // Installing a context is what makes wrappers appear (see enableTracking above). + globalObject->setAsyncContextTrackingEnabled(true); + return JSValue::encode(AsyncContextFrame::create(globalObject, callback, context)); +} + +// The AsyncContextRef in the current async context, or undefined when the JS +// running right now does not descend from a bun:test invocation. +extern "C" [[ZIG_EXPORT(nothrow)]] JSC::EncodedJSValue Bun__AsyncContextRef__current(JSC::JSGlobalObject* globalObject) +{ + JSValue context = globalObject->m_asyncContextData.get()->getInternalField(0); + auto* array = dynamicDowncast(context); + if (!array) + return JSValue::encode(jsUndefined()); + + unsigned length = array->length(); + for (unsigned i = 0; i < length; i += 2) { + if (!array->canGetIndexQuickly(i)) + continue; + JSValue key = array->getIndexQuickly(i); + if (isAsyncContextRef(key)) + return JSValue::encode(key); + } + return JSValue::encode(jsUndefined()); +} diff --git a/src/jsc/generated_classes_list.rs b/src/jsc/generated_classes_list.rs index 0a3be533a841..8c14429a23bb 100644 --- a/src/jsc/generated_classes_list.rs +++ b/src/jsc/generated_classes_list.rs @@ -33,6 +33,7 @@ pub mod Classes { pub use crate::crypto::CryptoHasher; pub use crate::image as Image; pub use crate::shell::Interpreter as ShellInterpreter; + pub use crate::test_runner::async_context_ref::AsyncContextRef; pub use crate::test_runner::done_callback::DoneCallback; pub use crate::test_runner::expect::Expect; pub use crate::test_runner::expect::ExpectAny; diff --git a/src/runtime/cli/test_command.rs b/src/runtime/cli/test_command.rs index 577d075d380d..fbffeb046bdd 100644 --- a/src/runtime/cli/test_command.rs +++ b/src/runtime/cli/test_command.rs @@ -3276,6 +3276,10 @@ impl TestCommand { } // need to wake up so autoTick() doesn't wait for 16-100ms after loading the entrypoint vm.wakeup(); + // Every test and hook callback runs under an async context (see + // AsyncContextRef.rs); this must be on before the file (or a preload) + // can create a node:vm context, which copies the flag. + jsc::cpp::Bun__AsyncContextRef__enableTracking(vm.global()); let promise = vm.load_entry_point_for_test_runner(file_path)?; // Only count the file once, not once per repeat if repeat_index == 0 { diff --git a/src/runtime/test_runner/AsyncContextRef.rs b/src/runtime/test_runner/AsyncContextRef.rs new file mode 100644 index 000000000000..78a7d6285d1a --- /dev/null +++ b/src/runtime/test_runner/AsyncContextRef.rs @@ -0,0 +1,64 @@ +//! What `bun:test` puts into the async context while a test or hook callback +//! runs, so that everything the callback awaits, schedules or registers keeps +//! pointing back at that invocation of it. +//! +//! `expect()` attributes itself to whatever entry the runner is executing at +//! the moment it is called. When the runner abandons an invocation that is +//! still running (it timed out, or an unhandled error failed it while it was +//! awaiting), that rule would attribute the rest of its body (snapshot names, +//! `expect()` counts) to whatever entry runs next. So `Execution` binds every +//! invocation to one of these and flips [`RefData::abandoned`] when it gives +//! up on the invocation; `bun_test::caller_ref` then attributes JS running +//! under an abandoned invocation's context to that invocation, whose +//! `RefData` no longer resolves to a running entry, instead of to the entry +//! running now. Invocations that completed are never consulted, so a callback +//! registered by one entry and invoked during a later one (a server started in +//! `beforeAll`, ...) still attributes to the entry that is running, as before. +//! +//! [`RefData::abandoned`]: crate::test_runner::bun_test::RefData::abandoned + +use bun_jsc::{JSGlobalObject, JSValue, JsClass as _, JsResult}; + +use crate::test_runner::bun_test::RefDataPtr; + +#[bun_jsc::JsClass(no_construct, no_constructor)] // codegen wires to_js / from_js +pub struct AsyncContextRef { + /// Owned `+1`, released in `finalize`. + r#ref: RefDataPtr, +} + +impl AsyncContextRef { + // Codegen's `host_fn_finalize` calls this via `|b| AsyncContextRef::finalize(b)` + // and requires `fn finalize(self: Box)`; clippy::boxed_local is a + // false positive on that contract. + #[allow(clippy::boxed_local)] + pub fn finalize(self: Box) { + // `RefPtr` has no `Drop` (src/ptr/ref_count.rs); release explicitly + // before the Box frees the allocation. + self.r#ref.deref(); + } + + /// Wraps `callback` so that it, and every continuation of it, runs with + /// `refdata` in the async context. Takes over the caller's `+1` on `refdata`. + pub(crate) fn bind(global: &JSGlobalObject, callback: JSValue, refdata: RefDataPtr) -> JsResult { + // `to_js` boxes `self` and hands the pointer to the wrapper; `finalize` releases the ref. + let ref_js = AsyncContextRef { r#ref: refdata }.to_js(global); + let bound = bun_jsc::cpp::Bun__AsyncContextRef__bind(global, callback, ref_js); + ref_js.ensure_still_alive(); + bound + } + + /// A `+1` to the `RefData` of the abandoned invocation whose async context + /// the currently running JS descends from, or `None` when it descends from + /// no invocation or from one the runner did not abandon. + pub(crate) fn abandoned_caller(global: &JSGlobalObject) -> Option { + let this = Self::from_js(bun_jsc::cpp::Bun__AsyncContextRef__current(global))?; + // SAFETY: `from_js` returned the live payload of a wrapper that the + // current async context (a GC-visited array) keeps alive for this call. + let refdata: &RefDataPtr = unsafe { &(*this).r#ref }; + if !refdata.abandoned.get() { + return None; + } + Some(refdata.dupe_ref()) + } +} diff --git a/src/runtime/test_runner/Collection.rs b/src/runtime/test_runner/Collection.rs index 44bfd6875d28..6a7d11b16391 100644 --- a/src/runtime/test_runner/Collection.rs +++ b/src/runtime/test_runner/Collection.rs @@ -141,7 +141,7 @@ impl Collection { // `self.active_scope` in `step()` and mutated through). self.current_scope_callback_queue.push(QueuedDescribe { active_scope: self.active_scope, - callback: DeprecatedStrong::init(cb), + callback: DeprecatedStrong::init(bun_test::keep_registration_async_context(cb)), new_scope: NonNull::from(new_scope), }); } diff --git a/src/runtime/test_runner/Execution.rs b/src/runtime/test_runner/Execution.rs index a864c8f8b17b..4d016987f5fd 100644 --- a/src/runtime/test_runner/Execution.rs +++ b/src/runtime/test_runner/Execution.rs @@ -45,8 +45,8 @@ use bun_core::scoped_log; use super::debug::group as group_log; // bun_test.debug.group use super::bun_test::{ - group_begin, AddedInPhase, BunTest, BunTestPtr, EntryData, ExecutionEntry, - HandleUncaughtExceptionResult, Order, RefDataValue, ScopeMode, StepResult, + group_begin, AddedInPhase, AsyncContextRef, BunTest, BunTestPtr, EntryData, ExecutionEntry, + HandleUncaughtExceptionResult, Order, RefDataPtr, RefDataValue, ScopeMode, StepResult, }; use crate::cli::test_command; @@ -167,6 +167,12 @@ pub struct ExecutionSequence { /// Expectation set by expect.hasAssertions() or expect.assertions(n). pub(crate) expect_assertions: ExpectAssertions, pub(crate) maybe_skip: bool, + /// The `RefData` bound into the async context of the callback this sequence + /// is executing right now (see AsyncContextRef.rs), so the runner can mark it + /// abandoned if it has to move on before that callback completes. Owned + /// `+1`, released by `advance_sequence` (or `Drop`, for a file torn down + /// mid-callback). + pub(crate) executing_ref: Option, } impl ExecutionSequence { @@ -189,6 +195,22 @@ impl ExecutionSequence { expect_call_count: 0, expect_assertions: ExpectAssertions::NotSet, maybe_skip: false, + executing_ref: None, + } + } + + /// The runner is moving on from the callback this sequence is executing + /// even though that callback has not completed: whatever the callback still + /// does belongs to it, not to the entries that run next. + pub(crate) fn abandon_executing_callback(&self) { + if let Some(executing_ref) = &self.executing_ref { + executing_ref.abandoned.set(true); + } + } + + fn release_executing_ref(&mut self) { + if let Some(executing_ref) = self.executing_ref.take() { + executing_ref.deref(); } } @@ -201,6 +223,12 @@ impl ExecutionSequence { } } +impl Drop for ExecutionSequence { + fn drop(&mut self) { + self.release_executing_ref(); + } +} + #[derive(Clone, Copy, PartialEq, Eq, Default, strum::IntoStaticStr)] #[repr(u8)] pub enum Result { @@ -509,6 +537,7 @@ impl Execution { let sequence = unsafe { &mut *sequence_ptr.as_ptr() }; debug_assert!(sequence.executing); + sequence.release_executing_ref(); if let Some(entry_ptr) = sequence.active_entry { // SAFETY: arena-owned entry, alive for lifetime of BunTest let entry = unsafe { entry_ptr.as_ref() }; @@ -974,6 +1003,8 @@ fn step_sequence_one( // SAFETY: arena-owned entry let active_entry = unsafe { &mut *active_entry_ptr.as_ptr() }; if active_entry.evaluate_timeout(sequence, now) { + // The callback is still running; it is the runner that is moving on. + sequence.abandon_executing_callback(); Execution::advance_sequence(buntest_ptr, sequence_ptr, group); return Ok(None); // run again } @@ -1012,6 +1043,13 @@ fn step_sequence_one( }; group_log::log(format_args!("runSequence queued callback: {}", callback_data)); + // One RefData per invocation, shared between the sequence (which marks it + // abandoned if the runner moves on before the callback completes) and + // the async context the callback runs under (how late callers find it). + let executing_ref: RefDataPtr = BunTest::ref_(buntest_strong, callback_data.clone()); + debug_assert!(sequence.executing_ref.is_none()); + sequence.executing_ref = Some(executing_ref.dupe_ref()); + let prev_on_stack = this.on_stack_entry.replace(Some(next_item_ptr)); let prev_on_stack_data = this.on_stack_entry_data.replace(Some(entry_data)); let on_stack_cell = &raw const this.on_stack_entry; @@ -1023,10 +1061,32 @@ fn step_sequence_one( (*on_stack_data_cell).set(prev_on_stack_data); }); + // `sequence` and `this` are not used again below this point: both the + // failure branch here and run_test_callback re-enter BunTest. + let callback = match AsyncContextRef::bind(global_this, cb.get(), executing_ref) { + Ok(bound) => bound, + Err(err) => { + // Out of memory building the context. Charge it to this entry and + // still run the callback unbound, as run_test_callback does when + // binding the done callback fails. + // SAFETY: `buntest_ptr` is the live per-file BunTest; no `&mut` + // derived from it is used after this call (see above). + unsafe { + (*buntest_ptr.as_ptr()).on_uncaught_exception( + global_this, + Some(global_this.take_exception(err)), + false, + &callback_data, + ); + } + cb.get() + } + }; + if BunTest::run_test_callback( buntest_strong, global_this, - cb.get(), + callback, next_item.has_done_parameter, callback_data, &next_item.timespec, diff --git a/src/runtime/test_runner/ScopeFunctions.rs b/src/runtime/test_runner/ScopeFunctions.rs index a30dd6f486b5..4a88943b34b9 100644 --- a/src/runtime/test_runner/ScopeFunctions.rs +++ b/src/runtime/test_runner/ScopeFunctions.rs @@ -664,10 +664,12 @@ pub(crate) fn parse_arguments( }; let (description, callback, options) = (items.description, items.callback, items.options); + // The function itself; it picks up the async context it was registered under + // when it is stored (`bun_test::keep_registration_async_context`). let result_callback: Option = if cfg.callback != CallbackMode::Require && callback.is_undefined_or_null() { None } else if callback.is_function() { - Some(callback.with_async_context_if_needed(global)) + Some(callback) } else { let ordinal = if cfg.kind == FunctionKind::Hook { "first" } else { "second" }; return Err(global.throw(format_args!("{} expects a function as the {} argument", signature, ordinal))); diff --git a/src/runtime/test_runner/bun_test.rs b/src/runtime/test_runner/bun_test.rs index 8f2ee1f522c2..713f30e09e53 100644 --- a/src/runtime/test_runner/bun_test.rs +++ b/src/runtime/test_runner/bun_test.rs @@ -52,11 +52,38 @@ fn strong_create(value: JSValue) -> Strong { Strong::create(value, global) } +/// A callback handed to `test()`, `describe()` or a hook runs later, from the +/// runner, and like any other deferred callback it keeps the async context +/// (AsyncLocalStorage) it was registered under. Applied where the callback is +/// stored rather than when the arguments are parsed: registration still needs +/// the function itself (its `length` decides whether it takes `done`, `.each` +/// binds arguments to it), and the wrapper is not a function. +pub(crate) fn keep_registration_async_context(callback: JSValue) -> JSValue { + // Same per-thread global as `strong_create`: `ExecutionEntry::create` has none in scope. + callback.with_async_context_if_needed(VirtualMachine::get().global()) +} + pub(crate) fn clone_active_strong() -> Option { let runner = Jest::runner()?; runner.bun_test_root.clone_active_file() } +/// Where an `expect()`-family call made by the JS running right now belongs: +/// the entry the runner is executing, unless the caller is the remainder of an +/// invocation the runner already abandoned (see AsyncContextRef.rs), in which +/// case it is that invocation, so that what it does late is rejected instead +/// of being charged to the entry that is running now. `None` outside `bun test`. +/// Returns an owned `+1`. +pub(crate) fn caller_ref(global: &JSGlobalObject) -> Option { + if let Some(abandoned) = AsyncContextRef::abandoned_caller(global) { + return Some(abandoned); + } + let buntest_strong = clone_active_strong()?; + let state = buntest_strong.get().get_current_state_data(); + Some(BunTest::ref_(&buntest_strong, state)) +} + +pub use super::async_context_ref::AsyncContextRef; pub use super::done_callback::DoneCallback; pub mod js_fns { @@ -736,6 +763,7 @@ impl BunTest { bun_ptr::IntrusiveRc::new(RefData { buntest_weak: Rc::downgrade(this_strong), phase, + abandoned: core::cell::Cell::new(false), ref_count: bun_ptr::RefCount::init(), }) } @@ -1511,6 +1539,11 @@ impl fmt::Display for RefDataValue { pub struct RefData { pub(crate) buntest_weak: BunTestPtrWeak, pub(crate) phase: RefDataValue, + /// Set when `phase` is an invocation the runner moved on from while its + /// callback was still running (timed out, or failed by an unhandled error + /// while awaiting). Only ever set on the `RefData` an `AsyncContextRef` + /// carries; read by [`caller_ref`]. + pub(crate) abandoned: core::cell::Cell, pub(crate) ref_count: bun_ptr::RefCount, } // `*RefData` crosses FFI (`as_promise_ptr`), so this MUST be `bun_ptr::IntrusiveRc` (= `RefPtr`), never `Rc`. @@ -1943,9 +1976,9 @@ impl ExecutionEntry { ScopeMode::Skip => None, ScopeMode::Todo => { let run_todo = Jest::runner().is_some_and(|runner| runner.run_todo); - if run_todo { Some(strong_create(c)) } else { None } + if run_todo { Some(strong_create(keep_registration_async_context(c))) } else { None } } - _ => Some(strong_create(c)), + _ => Some(strong_create(keep_registration_async_context(c))), }; } entry diff --git a/src/runtime/test_runner/expect.rs b/src/runtime/test_runner/expect.rs index 3f551ac9a85b..386dfcc3c1de 100644 --- a/src/runtime/test_runner/expect.rs +++ b/src/runtime/test_runner/expect.rs @@ -188,7 +188,10 @@ impl Expect { let Some(parent) = self.parent.as_ref() else { return }; // not in bun:test let Some(buntest_strong) = parent.bun_test() else { return }; // the test file this expect() call was for is no longer let buntest = buntest_strong.get(); - if let Some(sequence) = parent.phase.sequence(buntest) { + // An abandoned invocation's sequence has already been reported (and may be + // running a retry by now); its late expect() calls only count towards the total. + let sequence = if parent.abandoned.get() { None } else { parent.phase.sequence(buntest) }; + if let Some(sequence) = sequence { // found active sequence sequence.expect_call_count = sequence.expect_call_count.saturating_add(1); } else { @@ -621,12 +624,26 @@ impl Expect { pub(crate) fn get_snapshot_name(&self, hint: &[u8]) -> crate::Result> { let parent = self.parent.as_ref().ok_or(crate::Error::NoTest)?; + if parent.abandoned.get() { + // The runner gave up on the test this expect() belongs to (see + // AsyncContextRef.rs); whatever entry is running now is not it. + return Err(crate::Error::TestNotActive); + } let buntest_strong = parent.bun_test().ok_or(crate::Error::TestNotActive)?; let buntest = buntest_strong.get(); - let execution_entry = parent - .phase - .entry(buntest) - .ok_or(crate::Error::SnapshotInConcurrentGroup)?; + let execution_entry = match &parent.phase { + // `entry()` is None once the runner has advanced past the entry that was + // running when this expect() was created. + bun_test::RefDataValue::Execution { entry_data: Some(_), .. } => { + parent.phase.entry(buntest).ok_or(crate::Error::TestNotActive)? + } + bun_test::RefDataValue::Execution { entry_data: None, .. } => { + return Err(crate::Error::SnapshotInConcurrentGroup); + } + bun_test::RefDataValue::Start + | bun_test::RefDataValue::Collection { .. } + | bun_test::RefDataValue::Done => return Err(crate::Error::NoTest), + }; let test_name: &[u8] = execution_entry.base.name.as_deref().unwrap_or(b"(unnamed)"); @@ -707,22 +724,13 @@ impl Expect { } } - let active_execution_entry_ref = if let Some(buntest_strong_) = bun_test::clone_active_strong() { - let buntest_strong = buntest_strong_; - let state = buntest_strong.get().get_current_state_data(); - Some(bun_test::BunTest::ref_(&buntest_strong, state)) - } else { - None - }; - // The ref - // moves into `Expect` below and `to_js()` is infallible, so there is no - // error path between ref creation and the wrapper taking ownership; from - // then on `Expect::finalize` derefs `parent` (RefDataPtr has no Drop). - + // The ref moves into `Expect` below and `to_js()` is infallible, so there + // is no error path between ref creation and the wrapper taking ownership; + // from then on `Expect::finalize` derefs `parent` (RefDataPtr has no Drop). let expect = Expect { flags: Cell::new(Flags::default()), custom_label, - parent: active_execution_entry_ref, + parent: bun_test::caller_ref(global_this), }; // `JsClass::to_js` boxes `self` and hands the pointer to `${T}__create`. let expect_js_value = expect.to_js(global_this); @@ -1212,6 +1220,20 @@ impl Expect { let existing_value = match runner.snapshots.get_or_put(this, &pretty_value, hint) { Ok(v) => v, Err(err) => { + // Attribution errors first: the test file this expect() belongs to + // may already be gone. + match err { + crate::Error::SnapshotInConcurrentGroup => { + return Err(global_this.throw(format_args!("Snapshot matchers are not supported in concurrent tests"))); + } + crate::Error::TestNotActive => { + return Err(global_this.throw(format_args!("Snapshot matchers are not supported after the test has finished executing"))); + } + crate::Error::NoTest => { + return Err(global_this.throw(format_args!("Snapshot matchers cannot be used outside of a test"))); + } + _ => {} + } let Some(buntest_strong) = this.bun_test() else { return Err(global_this.throw(format_args!("Snapshot matchers cannot be used outside of a test"))); }; @@ -1247,12 +1269,6 @@ impl Expect { )) } } - crate::Error::SnapshotInConcurrentGroup => { - global_this.throw(format_args!("Snapshot matchers are not supported in concurrent tests")) - } - crate::Error::TestNotActive => { - global_this.throw(format_args!("Snapshot matchers are not supported after the test has finished executing")) - } _ => { let mut formatter = ConsoleObject::Formatter::new(global_this); global_this.throw(format_args!("Failed to snapshot value: {}", value.to_fmt(&mut formatter))) @@ -1660,18 +1676,32 @@ impl Expect { // SAFETY: bun_vm() returns the live VM pointer for this global. let _gc = global_this.bun_vm().as_mut().auto_gc_on_drop(); - let Some(buntest_strong) = bun_test::clone_active_strong() else { + Self::with_caller_sequence(global_this, |sequence| { + if !matches!(sequence.expect_assertions, ExpectAssertions::Exact(_)) { + sequence.expect_assertions = ExpectAssertions::AtLeastOne; + } + }) + } + + /// Runs `f` on the sequence that `expect.assertions()` / `expect.hasAssertions()`, + /// called by the JS running right now, applies to. + fn with_caller_sequence( + global_this: &JSGlobalObject, + f: impl FnOnce(&mut super::execution::ExecutionSequence), + ) -> JsResult { + let Some(caller) = bun_test::caller_ref(global_this) else { return Err(global_this.throw(format_args!("expect.assertions() must be called within a test"))); }; - let buntest = buntest_strong.get(); - let state_data = buntest.get_current_state_data(); - let Some(execution) = state_data.sequence(buntest) else { + // `RefPtr` has no Drop; release the `+1` from `caller_ref` on every exit path. + let caller = scopeguard::guard(caller, |caller| caller.deref()); + let buntest_strong = if caller.abandoned.get() { None } else { caller.bun_test() }; + let sequence = buntest_strong + .as_ref() + .and_then(|buntest_strong| caller.phase.sequence(buntest_strong.get())); + let Some(sequence) = sequence else { return Err(global_this.throw(format_args!("expect.assertions() is not supported in the describe phase, in concurrent tests, between tests, or after test execution has completed"))); }; - if !matches!(execution.expect_assertions, ExpectAssertions::Exact(_)) { - execution.expect_assertions = ExpectAssertions::AtLeastOne; - } - + f(sequence); Ok(JSValue::UNDEFINED) } @@ -1712,17 +1742,9 @@ impl Expect { let unsigned_expected_assertions: u32 = expected_assertions as u32; - let Some(buntest_strong) = bun_test::clone_active_strong() else { - return Err(global_this.throw(format_args!("expect.assertions() must be called within a test"))); - }; - let buntest = buntest_strong.get(); - let state_data = buntest.get_current_state_data(); - let Some(execution) = state_data.sequence(buntest) else { - return Err(global_this.throw(format_args!("expect.assertions() is not supported in the describe phase, in concurrent tests, between tests, or after test execution has completed"))); - }; - execution.expect_assertions = ExpectAssertions::Exact(unsigned_expected_assertions); - - Ok(JSValue::UNDEFINED) + Self::with_caller_sequence(global_this, |sequence| { + sequence.expect_assertions = ExpectAssertions::Exact(unsigned_expected_assertions); + }) } diff --git a/src/runtime/test_runner/jest.classes.ts b/src/runtime/test_runner/jest.classes.ts index cb7c7b8d5735..97b9ec174ce6 100644 --- a/src/runtime/test_runner/jest.classes.ts +++ b/src/runtime/test_runner/jest.classes.ts @@ -803,6 +803,19 @@ export default [ klass: {}, proto: {}, }), + // Never reaches user code: lives in the async context array while a test or + // hook callback runs (see AsyncContextRef.rs). + define({ + name: "AsyncContextRef", + construct: false, + noConstructor: true, + finalize: true, + JSType: "0b11101110", + values: [], + configurable: false, + klass: {}, + proto: {}, + }), define({ name: "ScopeFunctions", construct: false, diff --git a/src/runtime/test_runner/jest.rs b/src/runtime/test_runner/jest.rs index 2889638ff424..4dcbb95dc561 100644 --- a/src/runtime/test_runner/jest.rs +++ b/src/runtime/test_runner/jest.rs @@ -614,6 +614,10 @@ pub(crate) mod on_unhandled_rejection { if sequence.test_entry.map(|p| p.as_ptr()) != Some(entry) { // mark errors in hooks as 'unhandled error between tests' current_state_data = RefDataValue::Start; + } else { + // `add_result` below moves the runner past this test while + // its callback may still be awaiting. + sequence.abandon_executing_callback(); } } } diff --git a/src/runtime/test_runner/mod.rs b/src/runtime/test_runner/mod.rs index 4281593576e6..b99c33f4d2a8 100644 --- a/src/runtime/test_runner/mod.rs +++ b/src/runtime/test_runner/mod.rs @@ -134,6 +134,7 @@ macro_rules! throw_pretty_static { } cfg_jsc! { + #[path = "AsyncContextRef.rs"] pub mod async_context_ref; #[path = "bun_test.rs"] pub mod bun_test; #[path = "Collection.rs"] pub mod collection; #[path = "debug.rs"] pub mod debug; @@ -493,6 +494,7 @@ pub mod expect { // public surface for `crate::test_runner::*` consumers cfg_jsc! { + pub use async_context_ref::AsyncContextRef; pub use done_callback::DoneCallback; pub use expect::{ Expect, ExpectAny, ExpectAnything, ExpectArrayContaining, ExpectCloseTo, diff --git a/src/runtime/test_runner/snapshot.rs b/src/runtime/test_runner/snapshot.rs index 39e1fdd93197..fde2d827db77 100644 --- a/src/runtime/test_runner/snapshot.rs +++ b/src/runtime/test_runner/snapshot.rs @@ -120,19 +120,21 @@ impl Snapshots { pub(crate) fn add_count(&mut self, expect: &Expect, hint: &[u8]) -> Result<(Vec, usize), Error> { self.total += 1; let snapshot_name = expect.get_snapshot_name(hint)?; - // bun_collections::StringHashMap::get_or_put can't hand out `key_ptr`, so return the - // owned `snapshot_name` (same bytes as the interned key) instead. + let count = self.increment_count(&snapshot_name)?; + Ok((snapshot_name, count)) + } + + fn increment_count(&mut self, snapshot_name: &[u8]) -> Result { let gop = self .counts - .get_or_put(&snapshot_name) + .get_or_put(snapshot_name) .map_err(Error::from)?; if gop.found_existing { *gop.value_ptr += 1; } else { *gop.value_ptr = 1; } - let count = *gop.value_ptr; - Ok((snapshot_name, count)) + Ok(*gop.value_ptr) } pub(crate) fn get_or_put( @@ -141,9 +143,16 @@ impl Snapshots { target_value: &[u8], hint: &[u8], ) -> Result, Error> { + self.total += 1; + // Resolve the name before touching the file system: an expect() that no + // longer belongs to a running test must not create the snapshot directory + // or file. The count is taken after `get_snapshot_file`, which resets the + // counts when it switches to this test file's snapshot file. + let name = expect.get_snapshot_name(hint)?; + let buntest_strong = expect .bun_test() - .ok_or(crate::Error::SnapshotFailed)?; + .ok_or(crate::Error::TestNotActive)?; let bun_test = buntest_strong.get(); match self.get_snapshot_file(bun_test.file_id)? { bun_sys::Result::Ok(()) => {} @@ -160,7 +169,7 @@ impl Snapshots { } } - let (name, counter) = self.add_count(expect, hint)?; + let counter = self.increment_count(&name)?; let mut counter_string_buf = [0u8; 32]; let counter_string = bun_core::fmt::int_as_bytes(&mut counter_string_buf, counter); diff --git a/test/js/bun/test/expect-assertions.test.ts b/test/js/bun/test/expect-assertions.test.ts index d8df6410fdb6..b1db8e7fe032 100644 --- a/test/js/bun/test/expect-assertions.test.ts +++ b/test/js/bun/test/expect-assertions.test.ts @@ -28,3 +28,43 @@ test("expect.assertions causes the test to fail when it should", async () => { expect(result.stderr.toString()).toContain("5 fail\n"); expect(result.stderr.toString()).toContain("0 pass\n"); }); + +test("expect() calls made by a test after it timed out do not count towards the next test", async () => { + // "timed out" only continues once "counts its own" has started, so it has always timed out by + // then; the two expect() calls it makes from there on belong to it, not to the running test. + using dir = tempDir("late-expect-calls", { + "late.test.ts": /* ts */ ` + import { expect, test } from "bun:test"; + const nextStarted = Promise.withResolvers(); + const lateCallsDone = Promise.withResolvers(); + test("timed out", async () => { + await nextStarted.promise; + expect(1).toBe(1); + expect(2).toBe(2); + lateCallsDone.resolve(); + }, 1); + test("counts its own", async () => { + expect.assertions(1); + nextStarted.resolve(); + await lateCallsDone.promise; + expect(3).toBe(3); + }); + `, + }); + + await using proc = Bun.spawn({ + cmd: [bunExe(), "test", "late.test.ts"], + cwd: String(dir), + env: bunEnv, + stdout: "pipe", + stderr: "pipe", + }); + const [stderr, exitCode] = await Promise.all([proc.stderr.text(), proc.exited]); + + expect(stderr).toContain("(fail) timed out"); + expect(stderr).toContain("(pass) counts its own"); + expect(stderr).not.toContain("expected 1 assertion"); + // The late calls are still counted in the total, just not against the running test. + expect(stderr).toContain(" 3 expect() calls\n"); + expect(exitCode).toBe(1); +}); diff --git a/test/js/bun/test/jest-each.test.ts b/test/js/bun/test/jest-each.test.ts index 0bd0239ac72a..bacd50186d57 100644 --- a/test/js/bun/test/jest-each.test.ts +++ b/test/js/bun/test/jest-each.test.ts @@ -1,4 +1,5 @@ -import { describe, expect, it } from "bun:test"; +import { beforeEach, describe, expect, it } from "bun:test"; +import { AsyncLocalStorage } from "node:async_hooks"; const NUMBERS = [ [1, 1, 2], @@ -57,3 +58,35 @@ describe.each(["some", "cool", "strings"])("works with describe: %s", s => { describe("does not return zero", () => { expect(it.each([1, 2])("wat", () => {})).toBeUndefined(); }); + +// Callbacks registered while an AsyncLocalStorage store is active run with that store. Registration +// must still look at the function itself: its length decides whether it takes `done`, and `.each` +// binds the row to it. +describe("registered inside an AsyncLocalStorage context", () => { + const storage = new AsyncLocalStorage(); + storage.run("registration", () => { + beforeEach(() => { + expect(storage.getStore()).toBe("registration"); + }); + it("a test without a done parameter is not waited on", () => { + expect(storage.getStore()).toBe("registration"); + }); + it("a test with a done parameter still gets one", done => { + expect(storage.getStore()).toBe("registration"); + done(); + }); + it.each(NUMBERS)("it.each: %i + %i = %i", (a, b, e) => { + expect(a + b).toBe(e); + expect(storage.getStore()).toBe("registration"); + }); + it.each([[1, 1, 2]])("it.each with a done parameter: %i + %i = %i", (a, b, e, done) => { + expect(a + b).toBe(e); + (done as unknown as () => void)(); + }); + describe.each(["nested"])("describe.each: %s", s => { + it(`keeps the store in ${s} describes`, () => { + expect(storage.getStore()).toBe("registration"); + }); + }); + }); +}); diff --git a/test/js/bun/test/snapshot-tests/snapshots/snapshot.test.ts b/test/js/bun/test/snapshot-tests/snapshots/snapshot.test.ts index bef562452a65..7e60f545ba0f 100644 --- a/test/js/bun/test/snapshot-tests/snapshots/snapshot.test.ts +++ b/test/js/bun/test/snapshot-tests/snapshots/snapshot.test.ts @@ -1,7 +1,8 @@ import { $ } from "bun"; import { describe, expect, it, test } from "bun:test"; -import { readFileSync, writeFileSync } from "fs"; +import { existsSync, readFileSync, writeFileSync } from "fs"; import { bunEnv, bunExe, DirectoryTree, isDebug, tempDir, tempDirWithFiles } from "harness"; +import { join } from "path"; function test1000000(arg1: any, arg218718132: any) {} @@ -958,3 +959,197 @@ test("write snapshot from filter", async () => { expect(await Bun.file(dir + "/mytests/snap2.test.ts").text()).toBe(sver("b", true)); expect(await Bun.file(dir + "/mytests/more/testing.test.ts").text()).toBe(sver("TEST", true)); }); + +// When the runner gives up on a test or hook that is still running (it timed out, or an unhandled +// error failed it while it was awaiting), its body keeps running while the next test executes. The +// snapshot matchers it calls from then on must be rejected, not written under the next test's name. +describe("snapshot matchers called after the runner gave up on the test", () => { + const rejected = "Snapshot matchers are not supported after the test has finished executing"; + const header = "// Bun Snapshot v1, https://bun.sh/docs/test/snapshots\n"; + + // `report` logs whether each late matcher wrote or threw, so stdout tells the two apart. + const prelude = /* ts */ ` + import { beforeAll, beforeEach, describe, expect, test } from "bun:test"; + function report(label: string, matcher: () => void) { + try { + matcher(); + console.log(label + ": wrote a snapshot"); + } catch (error) { + console.log(label + ": " + (error as Error).message); + } + } + `; + + async function runTestFile(source: string) { + using dir = tempDir("snapshot-after-runner-moved-on", { "late.test.ts": prelude + source }); + await using proc = Bun.spawn({ + cmd: [bunExe(), "test", "late.test.ts"], + cwd: String(dir), + env: { ...bunEnv, CI: "false" }, + stdout: "pipe", + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + const snapPath = join(String(dir), "__snapshots__", "late.test.ts.snap"); + const snap = existsSync(snapPath) ? readFileSync(snapPath, "utf8") : null; + // stdout starts with the "bun test vX.Y.Z (sha)" banner; the rest is what the test file logged. + return { stdout: stdout.replace(/^bun test v.*\n/, ""), stderr, exitCode, snap }; + } + + test.concurrent("a test that timed out", async () => { + // Same body for both cases, as with test.each. The first case only continues once the second + // one has started, so it has always timed out by then; the second case then waits for the + // first one's late matchers before taking its own snapshots. + const { stdout, stderr, snap } = await runTestFile(/* ts */ ` + const secondStarted = Promise.withResolvers(); + const firstDone = Promise.withResolvers(); + async function migrate(name: string) { + if (name === "first") { + await secondStarted.promise; + report("late with hint", () => expect("lockfile of " + name).toMatchSnapshot(name)); + report("late without hint", () => expect("lockfile of " + name).toMatchSnapshot()); + report("late toThrowErrorMatchingSnapshot", () => + expect(() => { + throw new Error(name); + }).toThrowErrorMatchingSnapshot(), + ); + firstDone.resolve(); + return; + } + secondStarted.resolve(); + await firstDone.promise; + expect("lockfile of " + name).toMatchSnapshot(name); + expect("lockfile of " + name).toMatchSnapshot(); + } + describe("migrate", () => { + test("first", () => migrate("first"), 1); + test("second", () => migrate("second")); + }); + `); + + expect(stdout).toBe( + [ + `late with hint: ${rejected}`, + `late without hint: ${rejected}`, + `late toThrowErrorMatchingSnapshot: ${rejected}`, + "", + ].join("\n"), + ); + expect(stderr).toContain("this test timed out after 1ms"); + expect(stderr).toContain("(pass) migrate > second"); + // Nothing of the first case's under the second case's name, and the second case's own + // unhinted snapshot is still number 1. + expect(snap).toBe( + header + + '\nexports[`migrate second: second 1`] = `"lockfile of second"`;\n' + + '\nexports[`migrate second 1`] = `"lockfile of second"`;\n', + ); + }); + + test.concurrent("a hook that timed out", async () => { + const { stdout, stderr, snap } = await runTestFile(/* ts */ ` + const secondStarted = Promise.withResolvers(); + const hookDone = Promise.withResolvers(); + let hookRuns = 0; + beforeEach(async () => { + if (hookRuns++ > 0) return; + await secondStarted.promise; + report("late from the hook", () => expect("from the hook").toMatchSnapshot("hook")); + hookDone.resolve(); + }, 1); + test("first", () => {}); + test("second", async () => { + secondStarted.resolve(); + await hookDone.promise; + expect("from second").toMatchSnapshot(); + }); + `); + + expect(stdout).toBe(`late from the hook: ${rejected}\n`); + expect(stderr).toContain("(pass) second"); + expect(snap).toBe(header + '\nexports[`second 1`] = `"from second"`;\n'); + }); + + test.concurrent("a test failed by an unhandled error while it was awaiting", async () => { + // The only snapshot matcher in the file is the late one, so nothing at all should be written: + // not even an empty snapshot file. + const { stdout, stderr, snap } = await runTestFile(/* ts */ ` + const secondStarted = Promise.withResolvers(); + const firstDone = Promise.withResolvers(); + test("first", async () => { + Promise.reject(new Error("failure in the background")); + await secondStarted.promise; + report("late after the rejection", () => expect("from first").toMatchSnapshot()); + firstDone.resolve(); + }); + test("second", async () => { + secondStarted.resolve(); + await firstDone.promise; + }); + `); + + expect(stdout).toBe(`late after the rejection: ${rejected}\n`); + expect(stderr).toContain("failure in the background"); + expect(stderr).toContain("(pass) second"); + expect(snap).toBeNull(); + }); + + test.concurrent("an attempt that the runner gave up on, while its retry runs", async () => { + const { stdout, stderr, snap } = await runTestFile(/* ts */ ` + const retryStarted = Promise.withResolvers(); + const firstAttemptDone = Promise.withResolvers(); + let attempts = 0; + test( + "retried", + async () => { + if (attempts++ === 0) { + Promise.reject(new Error("first attempt fails in the background")); + await retryStarted.promise; + report("late from the first attempt", () => expect("from attempt 1").toMatchSnapshot()); + firstAttemptDone.resolve(); + return; + } + retryStarted.resolve(); + await firstAttemptDone.promise; + expect("from attempt 2").toMatchSnapshot(); + }, + { retry: 1 }, + ); + `); + + expect(stdout).toBe(`late from the first attempt: ${rejected}\n`); + expect(stderr).toContain("(pass) retried"); + // The passing attempt owns "retried 1"; a later run must compare against its value. + expect(snap).toBe(header + '\nexports[`retried 1`] = `"from attempt 2"`;\n'); + }); + + test.concurrent("callbacks registered by a finished hook still snapshot under the running test", async () => { + // The server's fetch handler was registered by beforeAll, which finished normally, so its + // snapshots belong to whichever test is making the request, as before. + const { stderr, snap, exitCode } = await runTestFile(/* ts */ ` + let server: ReturnType; + beforeAll(() => { + server = Bun.serve({ + port: 0, + fetch(request) { + expect(new URL(request.url).pathname).toMatchSnapshot("requested path"); + return new Response("ok"); + }, + }); + }); + test("one", async () => { + expect(await (await fetch(server.url + "one")).text()).toBe("ok"); + }); + test("two", async () => { + expect(await (await fetch(server.url + "two")).text()).toBe("ok"); + server.stop(true); + }); + `); + + expect(stderr).toContain(" 2 pass\n"); + expect(snap).toBe( + header + '\nexports[`one: requested path 1`] = `"/one"`;\n' + '\nexports[`two: requested path 1`] = `"/two"`;\n', + ); + expect(exitCode).toBe(0); + }); +}); From 645b968d90c7a2db9963f3710a67ad1337d4e9d2 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sat, 15 Aug 2026 06:05:02 +0000 Subject: [PATCH 2/9] bun test: keep what a callback does to the async context; only take the ref back out Wrapping every invocation in an AsyncContextFrame made Bun__JSValue__call put the previous context back after each callback, which discarded als.enterWith() done in a sync beforeEach/beforeAll/test body; those stores used to stay in effect for the entries that follow. The ref is now installed directly for callbacks registered without a context and removed again right after the call (the previous value is restored when the callback left the slot untouched, otherwise what it installed stays minus the ref). Callbacks registered under a context still run as wrapped callbacks do. run_test_callback owns enter/leave so the ref comes out before microtasks are drained. Also drain stdout in the expect-assertions test. --- src/jsc/bindings/AsyncContextFrame.cpp | 161 +++++++++++++++------ src/runtime/test_runner/AsyncContextRef.rs | 42 ++++-- src/runtime/test_runner/Collection.rs | 1 + src/runtime/test_runner/Execution.rs | 31 +--- src/runtime/test_runner/bun_test.rs | 75 ++++++++-- src/runtime/test_runner/jest.classes.ts | 6 +- test/js/bun/test/expect-assertions.test.ts | 2 +- test/js/bun/test/jest-each.test.ts | 6 + test/js/bun/test/jest-hooks.test.ts | 39 +++++ 9 files changed, 266 insertions(+), 97 deletions(-) diff --git a/src/jsc/bindings/AsyncContextFrame.cpp b/src/jsc/bindings/AsyncContextFrame.cpp index fb118495095b..0879d0d73236 100644 --- a/src/jsc/bindings/AsyncContextFrame.cpp +++ b/src/jsc/bindings/AsyncContextFrame.cpp @@ -149,6 +149,46 @@ static bool isAsyncContextRef(JSValue value) return dynamicDowncast(value) != nullptr; } +// The key of the first ref pair in `context`, or undefined. +static JSValue findAsyncContextRef(JSValue context) +{ + auto* array = dynamicDowncast(context); + if (!array) + return jsUndefined(); + unsigned length = array->length(); + for (unsigned i = 0; i < length; i += 2) { + if (!array->canGetIndexQuickly(i)) + continue; + JSValue key = array->getIndexQuickly(i); + if (isAsyncContextRef(key)) + return key; + } + return jsUndefined(); +} + +// Appends the pairs of `context` (if it is an array) to `entries`, leaving out +// ref pairs. The caller checks for an exception afterwards. +static void appendPairsWithoutRefs(JSGlobalObject* globalObject, JSValue context, MarkedArgumentBuffer& entries) +{ + auto& vm = JSC::getVM(globalObject); + auto scope = DECLARE_THROW_SCOPE(vm); + auto* array = dynamicDowncast(context); + if (!array) + return; + unsigned length = array->length(); + entries.ensureCapacity(length + 2); + for (unsigned i = 0; i < length; i += 2) { + JSValue key = array->getIndex(globalObject, i); + RETURN_IF_EXCEPTION(scope, ); + JSValue value = i + 1 < length ? array->getIndex(globalObject, i + 1) : jsUndefined(); + RETURN_IF_EXCEPTION(scope, ); + if (isAsyncContextRef(key)) + continue; + entries.append(key); + entries.append(value); + } +} + // AsyncContextFrame::call only unwraps the wrappers withAsyncContextIfNeeded() // creates while a context is installed when tracking is enabled (normally // constructing an AsyncLocalStorage enables it). node:vm contexts copy the flag @@ -158,74 +198,103 @@ extern "C" [[ZIG_EXPORT(nothrow)]] void Bun__AsyncContextRef__enableTracking(JSC globalObject->setAsyncContextTrackingEnabled(true); } -// Returns `callback` wrapped so that it runs with the context it would have run -// with anyway (the one it was registered under if it is already wrapped, else -// the current one) plus the pair (ref, ref). A pair left over from the -// invocation that registered the callback is dropped, so a context carries at -// most one ref: the innermost invocation. -extern "C" [[ZIG_EXPORT(zero_is_throw)]] JSC::EncodedJSValue Bun__AsyncContextRef__bind(JSC::JSGlobalObject* globalObject, JSC::EncodedJSValue callbackValue, JSC::EncodedJSValue refValue) +// Arranges for `callback`, about to be invoked once by the test runner, to run +// with `ref` in its async context, and returns what to invoke in its place. +// +// The context it runs with is the one it would have run with anyway plus the +// pair (ref, ref); a ref left over from the invocation that registered the +// callback is dropped, so a context names one invocation, the innermost. +// +// - A callback registered while a context was active (`als.run(() => test(..))`) +// is already an AsyncContextFrame. It keeps running the way wrapped callbacks +// run: a new frame installs the combined context for the call and +// Bun__JSValue__call puts the previous value back afterwards. +// - Otherwise the combined context is installed directly, exactly as the +// callback would have found the slot before, so whatever it does to the +// context (`als.enterWith()` in a beforeEach) is still there afterwards, as it +// always was; __leave only takes the ref back out. +extern "C" [[ZIG_EXPORT(zero_is_throw)]] JSC::EncodedJSValue Bun__AsyncContextRef__enter(JSC::JSGlobalObject* globalObject, JSC::EncodedJSValue callbackValue, JSC::EncodedJSValue refValue) { auto& vm = JSC::getVM(globalObject); auto scope = DECLARE_THROW_SCOPE(vm); JSValue callback = JSValue::decode(callbackValue); - JSValue ref = JSValue::decode(refValue); - ASSERT(isAsyncContextRef(ref)); - - JSValue baseContext; - if (auto* frame = dynamicDowncast(callback)) { - baseContext = frame->context.get(); - callback = frame->callback.get(); - } else { - baseContext = globalObject->m_asyncContextData.get()->getInternalField(0); - } + auto* ref = dynamicDowncast(JSValue::decode(refValue)); + ASSERT(ref); + auto* slot = globalObject->m_asyncContextData.get(); + + auto* registrationFrame = dynamicDowncast(callback); + JSValue previousContext = registrationFrame ? registrationFrame->context.get() : slot->getInternalField(0); MarkedArgumentBuffer entries; - if (auto* base = dynamicDowncast(baseContext)) { - unsigned length = base->length(); - entries.ensureCapacity(length + 2); - for (unsigned i = 0; i < length; i += 2) { - JSValue key = base->getIndex(globalObject, i); - RETURN_IF_EXCEPTION(scope, {}); - JSValue value = i + 1 < length ? base->getIndex(globalObject, i + 1) : jsUndefined(); - RETURN_IF_EXCEPTION(scope, {}); - if (isAsyncContextRef(key)) - continue; - entries.append(key); - entries.append(value); - } - } + appendPairsWithoutRefs(globalObject, previousContext, entries); + RETURN_IF_EXCEPTION(scope, {}); entries.append(ref); entries.append(ref); if (entries.hasOverflowed()) [[unlikely]] { throwOutOfMemoryError(globalObject, scope); return {}; } - JSArray* context = constructArray(globalObject, static_cast(nullptr), entries); RETURN_IF_EXCEPTION(scope, {}); // Installing a context is what makes wrappers appear (see enableTracking above). globalObject->setAsyncContextTrackingEnabled(true); - return JSValue::encode(AsyncContextFrame::create(globalObject, callback, context)); + + if (registrationFrame) + return JSValue::encode(AsyncContextFrame::create(globalObject, registrationFrame->callback.get(), context)); + + ref->m_previousContext.set(vm, ref, previousContext); + ref->m_installedContext.set(vm, ref, context); + slot->putInternalField(vm, 0, context); + return JSValue::encode(callback); +} + +// Called once the callback returned (before microtasks are drained, where +// Bun__JSValue__call restores for wrapped callbacks). Takes the ref back out of +// the slot: the previous value comes back if the callback left the slot alone, +// otherwise what the callback installed stays, minus the ref. +extern "C" [[ZIG_EXPORT(check_slow)]] void Bun__AsyncContextRef__leave(JSC::JSGlobalObject* globalObject, JSC::EncodedJSValue refValue) +{ + auto& vm = JSC::getVM(globalObject); + auto scope = DECLARE_THROW_SCOPE(vm); + + auto* ref = dynamicDowncast(JSValue::decode(refValue)); + ASSERT(ref); + JSValue installed = ref->m_installedContext.get(); + if (!installed) + return; // __enter returned a frame; Bun__JSValue__call already restored. + JSValue previous = ref->m_previousContext.get(); + ref->m_installedContext.clear(); + ref->m_previousContext.clear(); + + auto* slot = globalObject->m_asyncContextData.get(); + JSValue current = slot->getInternalField(0); + if (current == installed) { + slot->putInternalField(vm, 0, previous); + return; + } + if (findAsyncContextRef(current).isUndefined()) + return; // replaced by something that does not carry the ref (e.g. the enterWith() cleanup reset it) + + MarkedArgumentBuffer entries; + appendPairsWithoutRefs(globalObject, current, entries); + RETURN_IF_EXCEPTION(scope, ); + if (entries.hasOverflowed()) [[unlikely]] { + throwOutOfMemoryError(globalObject, scope); + return; + } + JSValue remaining = jsUndefined(); + if (!entries.isEmpty()) { + remaining = constructArray(globalObject, static_cast(nullptr), entries); + RETURN_IF_EXCEPTION(scope, ); + } + slot->putInternalField(vm, 0, remaining); } // The AsyncContextRef in the current async context, or undefined when the JS // running right now does not descend from a bun:test invocation. extern "C" [[ZIG_EXPORT(nothrow)]] JSC::EncodedJSValue Bun__AsyncContextRef__current(JSC::JSGlobalObject* globalObject) { - JSValue context = globalObject->m_asyncContextData.get()->getInternalField(0); - auto* array = dynamicDowncast(context); - if (!array) - return JSValue::encode(jsUndefined()); - - unsigned length = array->length(); - for (unsigned i = 0; i < length; i += 2) { - if (!array->canGetIndexQuickly(i)) - continue; - JSValue key = array->getIndexQuickly(i); - if (isAsyncContextRef(key)) - return JSValue::encode(key); - } - return JSValue::encode(jsUndefined()); + return JSValue::encode(findAsyncContextRef(globalObject->m_asyncContextData.get()->getInternalField(0))); } diff --git a/src/runtime/test_runner/AsyncContextRef.rs b/src/runtime/test_runner/AsyncContextRef.rs index 78a7d6285d1a..041eb22d1e66 100644 --- a/src/runtime/test_runner/AsyncContextRef.rs +++ b/src/runtime/test_runner/AsyncContextRef.rs @@ -6,15 +6,20 @@ //! the moment it is called. When the runner abandons an invocation that is //! still running (it timed out, or an unhandled error failed it while it was //! awaiting), that rule would attribute the rest of its body (snapshot names, -//! `expect()` counts) to whatever entry runs next. So `Execution` binds every -//! invocation to one of these and flips [`RefData::abandoned`] when it gives -//! up on the invocation; `bun_test::caller_ref` then attributes JS running -//! under an abandoned invocation's context to that invocation, whose +//! `expect()` counts) to whatever entry runs next. So every invocation runs +//! with one of these in its context and `Execution` flips [`RefData::abandoned`] +//! when it gives up on the invocation; `bun_test::caller_ref` then attributes +//! JS running under an abandoned invocation's context to that invocation, whose //! `RefData` no longer resolves to a running entry, instead of to the entry //! running now. Invocations that completed are never consulted, so a callback //! registered by one entry and invoked during a later one (a server started in //! `beforeAll`, ...) still attributes to the entry that is running, as before. //! +//! The ref is the only thing added to the context: what the callback itself +//! does to the context (`als.enterWith()` in a `beforeEach`) stays visible to +//! the entries that follow, as it did before (see `Bun__AsyncContextRef__enter` +//! in AsyncContextFrame.cpp). +//! //! [`RefData::abandoned`]: crate::test_runner::bun_test::RefData::abandoned use bun_jsc::{JSGlobalObject, JSValue, JsClass as _, JsResult}; @@ -27,6 +32,15 @@ pub struct AsyncContextRef { r#ref: RefDataPtr, } +/// Returned by [`AsyncContextRef::enter`]: what to invoke in place of the +/// callback, and the ref wrapper to hand to [`AsyncContextRef::leave`] once it +/// returned. Plain `JSValue`s (not an `Option`) so the conservative stack scan +/// keeps both alive across the call. +pub(crate) struct Entered { + pub(crate) callable: JSValue, + pub(crate) ref_js: JSValue, +} + impl AsyncContextRef { // Codegen's `host_fn_finalize` calls this via `|b| AsyncContextRef::finalize(b)` // and requires `fn finalize(self: Box)`; clippy::boxed_local is a @@ -38,14 +52,24 @@ impl AsyncContextRef { self.r#ref.deref(); } - /// Wraps `callback` so that it, and every continuation of it, runs with - /// `refdata` in the async context. Takes over the caller's `+1` on `refdata`. - pub(crate) fn bind(global: &JSGlobalObject, callback: JSValue, refdata: RefDataPtr) -> JsResult { + /// Puts `refdata` into the async context `callback` is about to be invoked + /// with, so that it and every continuation of it carry the ref. Takes over + /// the caller's `+1` on `refdata`. + pub(crate) fn enter(global: &JSGlobalObject, callback: JSValue, refdata: RefDataPtr) -> JsResult { // `to_js` boxes `self` and hands the pointer to the wrapper; `finalize` releases the ref. let ref_js = AsyncContextRef { r#ref: refdata }.to_js(global); - let bound = bun_jsc::cpp::Bun__AsyncContextRef__bind(global, callback, ref_js); + let callable = bun_jsc::cpp::Bun__AsyncContextRef__enter(global, callback, ref_js); + ref_js.ensure_still_alive(); + Ok(Entered { callable: callable?, ref_js }) + } + + /// Takes the ref back out of the context. Runs right after the callback + /// returned, before microtasks are drained, which is also when a wrapped + /// callback's context is restored by `Bun__JSValue__call`. + pub(crate) fn leave(global: &JSGlobalObject, ref_js: JSValue) -> JsResult<()> { + let result = bun_jsc::cpp::Bun__AsyncContextRef__leave(global, ref_js); ref_js.ensure_still_alive(); - bound + result } /// A `+1` to the `RefData` of the abandoned invocation whose async context diff --git a/src/runtime/test_runner/Collection.rs b/src/runtime/test_runner/Collection.rs index 6a7d11b16391..e4e35d368d3a 100644 --- a/src/runtime/test_runner/Collection.rs +++ b/src/runtime/test_runner/Collection.rs @@ -238,6 +238,7 @@ impl Collection { buntest_strong, global_this, callback.get(), + None, false, RefDataValue::Collection { active_scope: previous_scope }, &Timespec::EPOCH, diff --git a/src/runtime/test_runner/Execution.rs b/src/runtime/test_runner/Execution.rs index 4d016987f5fd..c30974087a33 100644 --- a/src/runtime/test_runner/Execution.rs +++ b/src/runtime/test_runner/Execution.rs @@ -45,7 +45,7 @@ use bun_core::scoped_log; use super::debug::group as group_log; // bun_test.debug.group use super::bun_test::{ - group_begin, AddedInPhase, AsyncContextRef, BunTest, BunTestPtr, EntryData, ExecutionEntry, + group_begin, AddedInPhase, BunTest, BunTestPtr, EntryData, ExecutionEntry, HandleUncaughtExceptionResult, Order, RefDataPtr, RefDataValue, ScopeMode, StepResult, }; use crate::cli::test_command; @@ -1046,9 +1046,9 @@ fn step_sequence_one( // One RefData per invocation, shared between the sequence (which marks it // abandoned if the runner moves on before the callback completes) and // the async context the callback runs under (how late callers find it). - let executing_ref: RefDataPtr = BunTest::ref_(buntest_strong, callback_data.clone()); + let invocation_ref: RefDataPtr = BunTest::ref_(buntest_strong, callback_data.clone()); debug_assert!(sequence.executing_ref.is_none()); - sequence.executing_ref = Some(executing_ref.dupe_ref()); + sequence.executing_ref = Some(invocation_ref.dupe_ref()); let prev_on_stack = this.on_stack_entry.replace(Some(next_item_ptr)); let prev_on_stack_data = this.on_stack_entry_data.replace(Some(entry_data)); @@ -1061,32 +1061,11 @@ fn step_sequence_one( (*on_stack_data_cell).set(prev_on_stack_data); }); - // `sequence` and `this` are not used again below this point: both the - // failure branch here and run_test_callback re-enter BunTest. - let callback = match AsyncContextRef::bind(global_this, cb.get(), executing_ref) { - Ok(bound) => bound, - Err(err) => { - // Out of memory building the context. Charge it to this entry and - // still run the callback unbound, as run_test_callback does when - // binding the done callback fails. - // SAFETY: `buntest_ptr` is the live per-file BunTest; no `&mut` - // derived from it is used after this call (see above). - unsafe { - (*buntest_ptr.as_ptr()).on_uncaught_exception( - global_this, - Some(global_this.take_exception(err)), - false, - &callback_data, - ); - } - cb.get() - } - }; - if BunTest::run_test_callback( buntest_strong, global_this, - callback, + cb.get(), + Some(invocation_ref), next_item.has_done_parameter, callback_data, &next_item.timespec, diff --git a/src/runtime/test_runner/bun_test.rs b/src/runtime/test_runner/bun_test.rs index 713f30e09e53..af957ab1dd69 100644 --- a/src/runtime/test_runner/bun_test.rs +++ b/src/runtime/test_runner/bun_test.rs @@ -1146,10 +1146,15 @@ impl BunTest { } /// if sync, the result is returned. if async, None is returned. + /// + /// `invocation_ref` (a `+1`, consumed) is the `RefData` a test or hook + /// invocation runs under (see AsyncContextRef.rs); describe callbacks pass + /// `None` and run as they are. pub(crate) fn run_test_callback( this_strong: &BunTestPtr, global_this: &JSGlobalObject, cfg_callback: JSValue, + invocation_ref: Option, cfg_done_parameter: bool, cfg_data: RefDataValue, timeout: &Timespec, @@ -1180,24 +1185,68 @@ impl BunTest { }; } + let mut callable: JSValue = cfg_callback; + let mut entered_ref: JSValue = JSValue::ZERO; + if let Some(invocation_ref) = invocation_ref { + match AsyncContextRef::enter(global_this, cfg_callback, invocation_ref) { + Ok(entered) => { + callable = entered.callable; + entered_ref = entered.ref_js; + } + Err(e) => { + // Out of memory building the context. Charge it to this entry and + // still run the callback, as with a done callback that failed to bind. + // SAFETY: `UnsafeCell`-derived; sole `&mut` at this point. + unsafe { (*this).on_uncaught_exception(global_this, Some(global_this.take_exception(e)), false, &cfg_data) }; + } + } + } + // SAFETY: `UnsafeCell`-derived; sole `&mut` at this point (before JS re-entry). unsafe { (*this).update_min_timeout(global_this, timeout) }; let args_slice: &[JSValue] = if !done_arg.is_empty() { core::slice::from_ref(&done_arg) } else { &[] }; - let result: JSValue = match vm.event_loop_mut().run_callback_with_result_and_forcefully_drain_microtasks( - cfg_callback, - global_this, - JSValue::UNDEFINED, - args_slice, - ) { - Ok(v) => v, - Err(_) => { + + // `JSValue::call`, then the ref comes back out, then microtasks are drained: + // the same order as `run_callback_with_result_and_forcefully_drain_microtasks`, + // with the context restored at the point a wrapped callback's would be. + // A failure anywhere is charged to this entry; the callback's own exception + // is taken before `leave` so that `leave` does not mistake it for its own. + // `Some` once something failed; the inner `None` is a termination (nothing + // to print), which is what `on_uncaught_exception` takes. + let mut failure: Option> = None; + let mut result: JSValue = JSValue::UNDEFINED; + if !global_this.has_exception() { + match callable.call(global_this, JSValue::UNDEFINED, args_slice) { + Ok(v) => result = v, + Err(_) => { + global_this.clear_termination_exception(); + failure = Some(global_this.try_take_exception()); + } + } + } + if !entered_ref.is_empty() { + if let Err(e) = AsyncContextRef::leave(global_this, entered_ref) { + // Out of memory; the callback's own failure, if any, is the one worth reporting. + let exception = global_this.take_exception(e); + if failure.is_none() { + failure = Some(Some(exception)); + } + } + } + if failure.is_none() { + if let Err(stopped) = vm.event_loop_mut().drain_microtasks_with_global(global_this, vm.jsc_vm()) { + let _ = stopped.throw(global_this); global_this.clear_termination_exception(); - // SAFETY: re-derive after JS callback returned; no outer `&mut` was held across it. - unsafe { (*this).on_uncaught_exception(global_this, global_this.try_take_exception(), false, &cfg_data) }; - bun_core::scoped_log!(bun_test_group, "callTestCallback -> error"); - JSValue::ZERO + failure = Some(global_this.try_take_exception()); } - }; + } + result.ensure_still_alive(); + if let Some(exception) = failure { + // SAFETY: re-derive after JS callback returned; no outer `&mut` was held across it. + unsafe { (*this).on_uncaught_exception(global_this, exception, false, &cfg_data) }; + bun_core::scoped_log!(bun_test_group, "callTestCallback -> error"); + result = JSValue::ZERO; + } done_callback.ensure_still_alive(); diff --git a/src/runtime/test_runner/jest.classes.ts b/src/runtime/test_runner/jest.classes.ts index 97b9ec174ce6..9c3c46cc0553 100644 --- a/src/runtime/test_runner/jest.classes.ts +++ b/src/runtime/test_runner/jest.classes.ts @@ -804,14 +804,16 @@ export default [ proto: {}, }), // Never reaches user code: lives in the async context array while a test or - // hook callback runs (see AsyncContextRef.rs). + // hook callback runs (see AsyncContextRef.rs). The values are the array + // Bun__AsyncContextRef__enter installed and the value it replaced, so that + // __leave can put the latter back when the callback left the slot untouched. define({ name: "AsyncContextRef", construct: false, noConstructor: true, finalize: true, JSType: "0b11101110", - values: [], + values: ["installedContext", "previousContext"], configurable: false, klass: {}, proto: {}, diff --git a/test/js/bun/test/expect-assertions.test.ts b/test/js/bun/test/expect-assertions.test.ts index b1db8e7fe032..a87c735337af 100644 --- a/test/js/bun/test/expect-assertions.test.ts +++ b/test/js/bun/test/expect-assertions.test.ts @@ -59,7 +59,7 @@ test("expect() calls made by a test after it timed out do not count towards the stdout: "pipe", stderr: "pipe", }); - const [stderr, exitCode] = await Promise.all([proc.stderr.text(), proc.exited]); + const [, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); expect(stderr).toContain("(fail) timed out"); expect(stderr).toContain("(pass) counts its own"); diff --git a/test/js/bun/test/jest-each.test.ts b/test/js/bun/test/jest-each.test.ts index bacd50186d57..eb7e47545efa 100644 --- a/test/js/bun/test/jest-each.test.ts +++ b/test/js/bun/test/jest-each.test.ts @@ -89,4 +89,10 @@ describe("registered inside an AsyncLocalStorage context", () => { }); }); }); + + // The beforeEach above still runs (with its own store) before this test; its store must not + // be left behind for a test that was registered outside of it. + it("a test registered outside of the store does not see it", () => { + expect(storage.getStore()).toBeUndefined(); + }); }); diff --git a/test/js/bun/test/jest-hooks.test.ts b/test/js/bun/test/jest-hooks.test.ts index 425951591a14..49eb177951a5 100644 --- a/test/js/bun/test/jest-hooks.test.ts +++ b/test/js/bun/test/jest-hooks.test.ts @@ -1,4 +1,5 @@ import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from "bun:test"; +import { AsyncLocalStorage } from "node:async_hooks"; let hooks_run: string[] = []; @@ -249,3 +250,41 @@ describe("test jest hooks in bun-test", () => { }); }); }); + +// The runner adds its own entry to the async context while a hook or test runs; what the +// callback itself does to the context has to stay in effect afterwards, as it always has. +describe("AsyncLocalStorage.enterWith() in a hook stays in effect for the tests that follow", () => { + const storage = new AsyncLocalStorage(); + afterAll(() => storage.disable()); + + describe("entered in beforeAll", () => { + beforeAll(() => { + storage.enterWith("from beforeAll"); + }); + + it("is the store of the first test", () => { + expect(storage.getStore()).toBe("from beforeAll"); + }); + + it("and of the next one, before and after an await", async () => { + expect(storage.getStore()).toBe("from beforeAll"); + await Promise.resolve(); + expect(storage.getStore()).toBe("from beforeAll"); + }); + }); + + describe("entered in beforeEach", () => { + let runs = 0; + beforeEach(() => { + storage.enterWith(`beforeEach run ${++runs}`); + }); + + it("is the store of the test it ran for", () => { + expect(storage.getStore()).toBe("beforeEach run 1"); + }); + + it("and is replaced for the next test", () => { + expect(storage.getStore()).toBe("beforeEach run 2"); + }); + }); +}); From b7f1c9db1905e2fb9cd6eb614fc8eec0a7d73f32 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sat, 15 Aug 2026 06:16:41 +0000 Subject: [PATCH 3/9] bun test: trim the comments around AsyncContextRef --- src/js/node/async_hooks.ts | 6 +-- src/jsc/bindings/AsyncContextFrame.cpp | 51 +++++------------- src/runtime/cli/test_command.rs | 4 +- src/runtime/test_runner/AsyncContextRef.rs | 63 +++++++--------------- src/runtime/test_runner/Execution.rs | 16 ++---- src/runtime/test_runner/ScopeFunctions.rs | 3 +- src/runtime/test_runner/bun_test.rs | 43 +++++---------- src/runtime/test_runner/expect.rs | 14 ++--- src/runtime/test_runner/jest.classes.ts | 5 +- src/runtime/test_runner/jest.rs | 3 +- src/runtime/test_runner/snapshot.rs | 6 +-- 11 files changed, 61 insertions(+), 153 deletions(-) diff --git a/src/js/node/async_hooks.ts b/src/js/node/async_hooks.ts index f543eeae1945..8fe3b472d634 100644 --- a/src/js/node/async_hooks.ts +++ b/src/js/node/async_hooks.ts @@ -22,10 +22,8 @@ // each key is an AsyncLocalStorage object and the value is the associated value. There are a ton of // calls to $assert which will verify this invariant (only during bun-debug) // -// The one other key that can appear is bun:test's AsyncContextRef (src/runtime/test_runner/AsyncContextRef.rs), -// which the test runner adds while a test or hook callback runs; it is stored as both key and value and -// is only ever looked up from native code, so everything in here just carries it along like any other -// pair it does not own. +// The one other key that can appear is bun:test's AsyncContextRef (stored as both key and value, only +// read from native code; see src/runtime/test_runner/AsyncContextRef.rs). Nothing in here touches it. // const setAsyncHooksEnabled = $newCppFunction("NodeAsyncHooks.cpp", "jsSetAsyncHooksEnabled", 1); const cleanupLater = $newCppFunction("NodeAsyncHooks.cpp", "jsCleanupLater", 0); diff --git a/src/jsc/bindings/AsyncContextFrame.cpp b/src/jsc/bindings/AsyncContextFrame.cpp index 0879d0d73236..ca632c44e96c 100644 --- a/src/jsc/bindings/AsyncContextFrame.cpp +++ b/src/jsc/bindings/AsyncContextFrame.cpp @@ -137,19 +137,14 @@ JSValue AsyncContextFrame::profiledCall(JSGlobalObject* global, JSValue function // ── bun:test (src/runtime/test_runner/AsyncContextRef.rs) ────────────────── // -// The async context value (AsyncLocalStorage's storage, see node/async_hooks.ts) -// is an array of [key, value, ...] pairs that promise reactions, timers and -// native callbacks snapshot and restore. bun:test adds one pair per test or -// hook invocation, with the invocation's AsyncContextRef as both key and value, -// so that code still running on behalf of that invocation can be told apart -// from the entry the runner is executing now. +// The context array ([key, value, ...], see node/async_hooks.ts) gets one extra +// pair per test or hook invocation: (ref, ref), the invocation's AsyncContextRef. static bool isAsyncContextRef(JSValue value) { return dynamicDowncast(value) != nullptr; } -// The key of the first ref pair in `context`, or undefined. static JSValue findAsyncContextRef(JSValue context) { auto* array = dynamicDowncast(context); @@ -166,8 +161,7 @@ static JSValue findAsyncContextRef(JSValue context) return jsUndefined(); } -// Appends the pairs of `context` (if it is an array) to `entries`, leaving out -// ref pairs. The caller checks for an exception afterwards. +// The caller checks for an exception afterwards. static void appendPairsWithoutRefs(JSGlobalObject* globalObject, JSValue context, MarkedArgumentBuffer& entries) { auto& vm = JSC::getVM(globalObject); @@ -189,30 +183,18 @@ static void appendPairsWithoutRefs(JSGlobalObject* globalObject, JSValue context } } -// AsyncContextFrame::call only unwraps the wrappers withAsyncContextIfNeeded() -// creates while a context is installed when tracking is enabled (normally -// constructing an AsyncLocalStorage enables it). node:vm contexts copy the flag -// when they are created, so bun test enables it before loading each test file. +// node:vm contexts copy this flag when created, so it is set before a test file loads. extern "C" [[ZIG_EXPORT(nothrow)]] void Bun__AsyncContextRef__enableTracking(JSC::JSGlobalObject* globalObject) { globalObject->setAsyncContextTrackingEnabled(true); } -// Arranges for `callback`, about to be invoked once by the test runner, to run -// with `ref` in its async context, and returns what to invoke in its place. -// -// The context it runs with is the one it would have run with anyway plus the -// pair (ref, ref); a ref left over from the invocation that registered the -// callback is dropped, so a context names one invocation, the innermost. -// -// - A callback registered while a context was active (`als.run(() => test(..))`) -// is already an AsyncContextFrame. It keeps running the way wrapped callbacks -// run: a new frame installs the combined context for the call and -// Bun__JSValue__call puts the previous value back afterwards. -// - Otherwise the combined context is installed directly, exactly as the -// callback would have found the slot before, so whatever it does to the -// context (`als.enterWith()` in a beforeEach) is still there afterwards, as it -// always was; __leave only takes the ref back out. +// Returns what to invoke in place of `callback` so that it runs with its usual +// context plus (ref, ref). A callback registered under a context (already an +// AsyncContextFrame) gets a new frame, which Bun__JSValue__call installs and +// restores as usual. Any other callback gets the array installed in place, so +// that, as before, what it does to the context (als.enterWith()) outlives it; +// __leave then only removes the ref. extern "C" [[ZIG_EXPORT(zero_is_throw)]] JSC::EncodedJSValue Bun__AsyncContextRef__enter(JSC::JSGlobalObject* globalObject, JSC::EncodedJSValue callbackValue, JSC::EncodedJSValue refValue) { auto& vm = JSC::getVM(globalObject); @@ -238,7 +220,6 @@ extern "C" [[ZIG_EXPORT(zero_is_throw)]] JSC::EncodedJSValue Bun__AsyncContextRe JSArray* context = constructArray(globalObject, static_cast(nullptr), entries); RETURN_IF_EXCEPTION(scope, {}); - // Installing a context is what makes wrappers appear (see enableTracking above). globalObject->setAsyncContextTrackingEnabled(true); if (registrationFrame) @@ -250,10 +231,6 @@ extern "C" [[ZIG_EXPORT(zero_is_throw)]] JSC::EncodedJSValue Bun__AsyncContextRe return JSValue::encode(callback); } -// Called once the callback returned (before microtasks are drained, where -// Bun__JSValue__call restores for wrapped callbacks). Takes the ref back out of -// the slot: the previous value comes back if the callback left the slot alone, -// otherwise what the callback installed stays, minus the ref. extern "C" [[ZIG_EXPORT(check_slow)]] void Bun__AsyncContextRef__leave(JSC::JSGlobalObject* globalObject, JSC::EncodedJSValue refValue) { auto& vm = JSC::getVM(globalObject); @@ -263,7 +240,7 @@ extern "C" [[ZIG_EXPORT(check_slow)]] void Bun__AsyncContextRef__leave(JSC::JSGl ASSERT(ref); JSValue installed = ref->m_installedContext.get(); if (!installed) - return; // __enter returned a frame; Bun__JSValue__call already restored. + return; // __enter returned a frame instead JSValue previous = ref->m_previousContext.get(); ref->m_installedContext.clear(); ref->m_previousContext.clear(); @@ -274,9 +251,9 @@ extern "C" [[ZIG_EXPORT(check_slow)]] void Bun__AsyncContextRef__leave(JSC::JSGl slot->putInternalField(vm, 0, previous); return; } + // The callback replaced the array (enterWith() copies it); keep its version without the ref. if (findAsyncContextRef(current).isUndefined()) - return; // replaced by something that does not carry the ref (e.g. the enterWith() cleanup reset it) - + return; MarkedArgumentBuffer entries; appendPairsWithoutRefs(globalObject, current, entries); RETURN_IF_EXCEPTION(scope, ); @@ -292,8 +269,6 @@ extern "C" [[ZIG_EXPORT(check_slow)]] void Bun__AsyncContextRef__leave(JSC::JSGl slot->putInternalField(vm, 0, remaining); } -// The AsyncContextRef in the current async context, or undefined when the JS -// running right now does not descend from a bun:test invocation. extern "C" [[ZIG_EXPORT(nothrow)]] JSC::EncodedJSValue Bun__AsyncContextRef__current(JSC::JSGlobalObject* globalObject) { return JSValue::encode(findAsyncContextRef(globalObject->m_asyncContextData.get()->getInternalField(0))); diff --git a/src/runtime/cli/test_command.rs b/src/runtime/cli/test_command.rs index fbffeb046bdd..5eaab8c8e181 100644 --- a/src/runtime/cli/test_command.rs +++ b/src/runtime/cli/test_command.rs @@ -3276,9 +3276,7 @@ impl TestCommand { } // need to wake up so autoTick() doesn't wait for 16-100ms after loading the entrypoint vm.wakeup(); - // Every test and hook callback runs under an async context (see - // AsyncContextRef.rs); this must be on before the file (or a preload) - // can create a node:vm context, which copies the flag. + // Before the file loads: node:vm contexts copy this flag when they are created. jsc::cpp::Bun__AsyncContextRef__enableTracking(vm.global()); let promise = vm.load_entry_point_for_test_runner(file_path)?; // Only count the file once, not once per repeat diff --git a/src/runtime/test_runner/AsyncContextRef.rs b/src/runtime/test_runner/AsyncContextRef.rs index 041eb22d1e66..c7ef563a4200 100644 --- a/src/runtime/test_runner/AsyncContextRef.rs +++ b/src/runtime/test_runner/AsyncContextRef.rs @@ -1,26 +1,13 @@ -//! What `bun:test` puts into the async context while a test or hook callback -//! runs, so that everything the callback awaits, schedules or registers keeps -//! pointing back at that invocation of it. +//! Put into the async context for the duration of one test or hook invocation, +//! so that the invocation's continuations can still be traced back to it. //! -//! `expect()` attributes itself to whatever entry the runner is executing at -//! the moment it is called. When the runner abandons an invocation that is -//! still running (it timed out, or an unhandled error failed it while it was -//! awaiting), that rule would attribute the rest of its body (snapshot names, -//! `expect()` counts) to whatever entry runs next. So every invocation runs -//! with one of these in its context and `Execution` flips [`RefData::abandoned`] -//! when it gives up on the invocation; `bun_test::caller_ref` then attributes -//! JS running under an abandoned invocation's context to that invocation, whose -//! `RefData` no longer resolves to a running entry, instead of to the entry -//! running now. Invocations that completed are never consulted, so a callback -//! registered by one entry and invoked during a later one (a server started in -//! `beforeAll`, ...) still attributes to the entry that is running, as before. -//! -//! The ref is the only thing added to the context: what the callback itself -//! does to the context (`als.enterWith()` in a `beforeEach`) stays visible to -//! the entries that follow, as it did before (see `Bun__AsyncContextRef__enter` -//! in AsyncContextFrame.cpp). -//! -//! [`RefData::abandoned`]: crate::test_runner::bun_test::RefData::abandoned +//! `expect()` belongs to whatever entry the runner is executing when it is +//! called. Once the runner has abandoned an invocation that is still running +//! (timeout, or an unhandled error while it was awaiting), that would be the +//! next entry; `RefData::abandoned` makes `bun_test::caller_ref` attribute such +//! late calls to the abandoned invocation instead, which rejects them. +//! Invocations that completed are never consulted, so callbacks they +//! registered keep belonging to whichever entry runs them. use bun_jsc::{JSGlobalObject, JSValue, JsClass as _, JsResult}; @@ -32,53 +19,41 @@ pub struct AsyncContextRef { r#ref: RefDataPtr, } -/// Returned by [`AsyncContextRef::enter`]: what to invoke in place of the -/// callback, and the ref wrapper to hand to [`AsyncContextRef::leave`] once it -/// returned. Plain `JSValue`s (not an `Option`) so the conservative stack scan -/// keeps both alive across the call. +/// Plain `JSValue`s (not an `Option`) so the conservative stack scan sees both. pub(crate) struct Entered { + /// What to invoke in place of the callback passed to [`AsyncContextRef::enter`]. pub(crate) callable: JSValue, + /// For [`AsyncContextRef::leave`]. pub(crate) ref_js: JSValue, } impl AsyncContextRef { - // Codegen's `host_fn_finalize` calls this via `|b| AsyncContextRef::finalize(b)` - // and requires `fn finalize(self: Box)`; clippy::boxed_local is a - // false positive on that contract. + // Codegen calls `finalize(Box)`; clippy::boxed_local is a false positive. #[allow(clippy::boxed_local)] pub fn finalize(self: Box) { - // `RefPtr` has no `Drop` (src/ptr/ref_count.rs); release explicitly - // before the Box frees the allocation. - self.r#ref.deref(); + self.r#ref.deref(); // `RefPtr` has no `Drop` } - /// Puts `refdata` into the async context `callback` is about to be invoked - /// with, so that it and every continuation of it carry the ref. Takes over - /// the caller's `+1` on `refdata`. + /// Puts `refdata` (a `+1`, consumed) into the context `callback` is about to + /// run with. See `Bun__AsyncContextRef__enter` for what that does to the slot. pub(crate) fn enter(global: &JSGlobalObject, callback: JSValue, refdata: RefDataPtr) -> JsResult { - // `to_js` boxes `self` and hands the pointer to the wrapper; `finalize` releases the ref. let ref_js = AsyncContextRef { r#ref: refdata }.to_js(global); let callable = bun_jsc::cpp::Bun__AsyncContextRef__enter(global, callback, ref_js); ref_js.ensure_still_alive(); Ok(Entered { callable: callable?, ref_js }) } - /// Takes the ref back out of the context. Runs right after the callback - /// returned, before microtasks are drained, which is also when a wrapped - /// callback's context is restored by `Bun__JSValue__call`. + /// Takes the ref back out once the callback returned, before microtasks are drained. pub(crate) fn leave(global: &JSGlobalObject, ref_js: JSValue) -> JsResult<()> { let result = bun_jsc::cpp::Bun__AsyncContextRef__leave(global, ref_js); ref_js.ensure_still_alive(); result } - /// A `+1` to the `RefData` of the abandoned invocation whose async context - /// the currently running JS descends from, or `None` when it descends from - /// no invocation or from one the runner did not abandon. + /// A `+1` to the abandoned invocation the running JS descends from, if any. pub(crate) fn abandoned_caller(global: &JSGlobalObject) -> Option { let this = Self::from_js(bun_jsc::cpp::Bun__AsyncContextRef__current(global))?; - // SAFETY: `from_js` returned the live payload of a wrapper that the - // current async context (a GC-visited array) keeps alive for this call. + // SAFETY: the live payload of a wrapper the current context array keeps alive. let refdata: &RefDataPtr = unsafe { &(*this).r#ref }; if !refdata.abandoned.get() { return None; diff --git a/src/runtime/test_runner/Execution.rs b/src/runtime/test_runner/Execution.rs index c30974087a33..3c333c4a240b 100644 --- a/src/runtime/test_runner/Execution.rs +++ b/src/runtime/test_runner/Execution.rs @@ -167,11 +167,8 @@ pub struct ExecutionSequence { /// Expectation set by expect.hasAssertions() or expect.assertions(n). pub(crate) expect_assertions: ExpectAssertions, pub(crate) maybe_skip: bool, - /// The `RefData` bound into the async context of the callback this sequence - /// is executing right now (see AsyncContextRef.rs), so the runner can mark it - /// abandoned if it has to move on before that callback completes. Owned - /// `+1`, released by `advance_sequence` (or `Drop`, for a file torn down - /// mid-callback). + /// The `RefData` the callback being executed runs under (AsyncContextRef.rs). + /// Owned `+1`, released by `advance_sequence` or `Drop`. pub(crate) executing_ref: Option, } @@ -199,9 +196,7 @@ impl ExecutionSequence { } } - /// The runner is moving on from the callback this sequence is executing - /// even though that callback has not completed: whatever the callback still - /// does belongs to it, not to the entries that run next. + /// Called when the runner moves on before the executing callback completed. pub(crate) fn abandon_executing_callback(&self) { if let Some(executing_ref) = &self.executing_ref { executing_ref.abandoned.set(true); @@ -1003,7 +998,6 @@ fn step_sequence_one( // SAFETY: arena-owned entry let active_entry = unsafe { &mut *active_entry_ptr.as_ptr() }; if active_entry.evaluate_timeout(sequence, now) { - // The callback is still running; it is the runner that is moving on. sequence.abandon_executing_callback(); Execution::advance_sequence(buntest_ptr, sequence_ptr, group); return Ok(None); // run again @@ -1043,9 +1037,7 @@ fn step_sequence_one( }; group_log::log(format_args!("runSequence queued callback: {}", callback_data)); - // One RefData per invocation, shared between the sequence (which marks it - // abandoned if the runner moves on before the callback completes) and - // the async context the callback runs under (how late callers find it). + // Shared by the sequence (to mark it abandoned) and the callback's async context. let invocation_ref: RefDataPtr = BunTest::ref_(buntest_strong, callback_data.clone()); debug_assert!(sequence.executing_ref.is_none()); sequence.executing_ref = Some(invocation_ref.dupe_ref()); diff --git a/src/runtime/test_runner/ScopeFunctions.rs b/src/runtime/test_runner/ScopeFunctions.rs index 4a88943b34b9..5a11fa0c88d6 100644 --- a/src/runtime/test_runner/ScopeFunctions.rs +++ b/src/runtime/test_runner/ScopeFunctions.rs @@ -664,8 +664,7 @@ pub(crate) fn parse_arguments( }; let (description, callback, options) = (items.description, items.callback, items.options); - // The function itself; it picks up the async context it was registered under - // when it is stored (`bun_test::keep_registration_async_context`). + // Unwrapped; `bun_test::keep_registration_async_context` applies when it is stored. let result_callback: Option = if cfg.callback != CallbackMode::Require && callback.is_undefined_or_null() { None } else if callback.is_function() { diff --git a/src/runtime/test_runner/bun_test.rs b/src/runtime/test_runner/bun_test.rs index af957ab1dd69..ac3684f54538 100644 --- a/src/runtime/test_runner/bun_test.rs +++ b/src/runtime/test_runner/bun_test.rs @@ -52,14 +52,10 @@ fn strong_create(value: JSValue) -> Strong { Strong::create(value, global) } -/// A callback handed to `test()`, `describe()` or a hook runs later, from the -/// runner, and like any other deferred callback it keeps the async context -/// (AsyncLocalStorage) it was registered under. Applied where the callback is -/// stored rather than when the arguments are parsed: registration still needs -/// the function itself (its `length` decides whether it takes `done`, `.each` -/// binds arguments to it), and the wrapper is not a function. +/// Applied when a test/describe/hook callback is stored, not when the arguments +/// are parsed: registration reads `.length` and `.bind()`s the function itself, +/// and the wrapper is not a function. pub(crate) fn keep_registration_async_context(callback: JSValue) -> JSValue { - // Same per-thread global as `strong_create`: `ExecutionEntry::create` has none in scope. callback.with_async_context_if_needed(VirtualMachine::get().global()) } @@ -68,12 +64,9 @@ pub(crate) fn clone_active_strong() -> Option { runner.bun_test_root.clone_active_file() } -/// Where an `expect()`-family call made by the JS running right now belongs: -/// the entry the runner is executing, unless the caller is the remainder of an -/// invocation the runner already abandoned (see AsyncContextRef.rs), in which -/// case it is that invocation, so that what it does late is rejected instead -/// of being charged to the entry that is running now. `None` outside `bun test`. -/// Returns an owned `+1`. +/// What an `expect()`-family call made right now belongs to: the entry being +/// executed, or the abandoned invocation the caller descends from (AsyncContextRef.rs). +/// `None` outside `bun test`. Returns an owned `+1`. pub(crate) fn caller_ref(global: &JSGlobalObject) -> Option { if let Some(abandoned) = AsyncContextRef::abandoned_caller(global) { return Some(abandoned); @@ -1147,9 +1140,8 @@ impl BunTest { /// if sync, the result is returned. if async, None is returned. /// - /// `invocation_ref` (a `+1`, consumed) is the `RefData` a test or hook - /// invocation runs under (see AsyncContextRef.rs); describe callbacks pass - /// `None` and run as they are. + /// `invocation_ref` (a `+1`, consumed) is what the callback runs under + /// (AsyncContextRef.rs); describe callbacks pass `None`. pub(crate) fn run_test_callback( this_strong: &BunTestPtr, global_this: &JSGlobalObject, @@ -1194,8 +1186,7 @@ impl BunTest { entered_ref = entered.ref_js; } Err(e) => { - // Out of memory building the context. Charge it to this entry and - // still run the callback, as with a done callback that failed to bind. + // OOM: charge it to this entry and still run the callback, as for `done` above. // SAFETY: `UnsafeCell`-derived; sole `&mut` at this point. unsafe { (*this).on_uncaught_exception(global_this, Some(global_this.take_exception(e)), false, &cfg_data) }; } @@ -1206,13 +1197,8 @@ impl BunTest { unsafe { (*this).update_min_timeout(global_this, timeout) }; let args_slice: &[JSValue] = if !done_arg.is_empty() { core::slice::from_ref(&done_arg) } else { &[] }; - // `JSValue::call`, then the ref comes back out, then microtasks are drained: - // the same order as `run_callback_with_result_and_forcefully_drain_microtasks`, - // with the context restored at the point a wrapped callback's would be. - // A failure anywhere is charged to this entry; the callback's own exception - // is taken before `leave` so that `leave` does not mistake it for its own. - // `Some` once something failed; the inner `None` is a termination (nothing - // to print), which is what `on_uncaught_exception` takes. + // Call, leave, then drain microtasks. The callback's exception is taken + // before `leave` runs. `Some(None)` is a termination (nothing to print). let mut failure: Option> = None; let mut result: JSValue = JSValue::UNDEFINED; if !global_this.has_exception() { @@ -1226,7 +1212,6 @@ impl BunTest { } if !entered_ref.is_empty() { if let Err(e) = AsyncContextRef::leave(global_this, entered_ref) { - // Out of memory; the callback's own failure, if any, is the one worth reporting. let exception = global_this.take_exception(e); if failure.is_none() { failure = Some(Some(exception)); @@ -1588,10 +1573,8 @@ impl fmt::Display for RefDataValue { pub struct RefData { pub(crate) buntest_weak: BunTestPtrWeak, pub(crate) phase: RefDataValue, - /// Set when `phase` is an invocation the runner moved on from while its - /// callback was still running (timed out, or failed by an unhandled error - /// while awaiting). Only ever set on the `RefData` an `AsyncContextRef` - /// carries; read by [`caller_ref`]. + /// The runner moved on while this invocation's callback was still running + /// (set through `ExecutionSequence::executing_ref`, read by [`caller_ref`]). pub(crate) abandoned: core::cell::Cell, pub(crate) ref_count: bun_ptr::RefCount, } diff --git a/src/runtime/test_runner/expect.rs b/src/runtime/test_runner/expect.rs index 386dfcc3c1de..200d4416bf48 100644 --- a/src/runtime/test_runner/expect.rs +++ b/src/runtime/test_runner/expect.rs @@ -188,8 +188,7 @@ impl Expect { let Some(parent) = self.parent.as_ref() else { return }; // not in bun:test let Some(buntest_strong) = parent.bun_test() else { return }; // the test file this expect() call was for is no longer let buntest = buntest_strong.get(); - // An abandoned invocation's sequence has already been reported (and may be - // running a retry by now); its late expect() calls only count towards the total. + // An abandoned invocation's late calls only count towards the total. let sequence = if parent.abandoned.get() { None } else { parent.phase.sequence(buntest) }; if let Some(sequence) = sequence { // found active sequence @@ -625,15 +624,12 @@ impl Expect { pub(crate) fn get_snapshot_name(&self, hint: &[u8]) -> crate::Result> { let parent = self.parent.as_ref().ok_or(crate::Error::NoTest)?; if parent.abandoned.get() { - // The runner gave up on the test this expect() belongs to (see - // AsyncContextRef.rs); whatever entry is running now is not it. return Err(crate::Error::TestNotActive); } let buntest_strong = parent.bun_test().ok_or(crate::Error::TestNotActive)?; let buntest = buntest_strong.get(); let execution_entry = match &parent.phase { - // `entry()` is None once the runner has advanced past the entry that was - // running when this expect() was created. + // None once the runner advanced past the entry this expect() was created in. bun_test::RefDataValue::Execution { entry_data: Some(_), .. } => { parent.phase.entry(buntest).ok_or(crate::Error::TestNotActive)? } @@ -1220,8 +1216,7 @@ impl Expect { let existing_value = match runner.snapshots.get_or_put(this, &pretty_value, hint) { Ok(v) => v, Err(err) => { - // Attribution errors first: the test file this expect() belongs to - // may already be gone. + // These need no test file; the one this expect() belongs to may be gone. match err { crate::Error::SnapshotInConcurrentGroup => { return Err(global_this.throw(format_args!("Snapshot matchers are not supported in concurrent tests"))); @@ -1683,8 +1678,7 @@ impl Expect { }) } - /// Runs `f` on the sequence that `expect.assertions()` / `expect.hasAssertions()`, - /// called by the JS running right now, applies to. + /// Runs `f` on the sequence an `expect.assertions()`-style call made right now applies to. fn with_caller_sequence( global_this: &JSGlobalObject, f: impl FnOnce(&mut super::execution::ExecutionSequence), diff --git a/src/runtime/test_runner/jest.classes.ts b/src/runtime/test_runner/jest.classes.ts index 9c3c46cc0553..ff1b83ea9153 100644 --- a/src/runtime/test_runner/jest.classes.ts +++ b/src/runtime/test_runner/jest.classes.ts @@ -803,10 +803,7 @@ export default [ klass: {}, proto: {}, }), - // Never reaches user code: lives in the async context array while a test or - // hook callback runs (see AsyncContextRef.rs). The values are the array - // Bun__AsyncContextRef__enter installed and the value it replaced, so that - // __leave can put the latter back when the callback left the slot untouched. + // Internal to the runner (AsyncContextRef.rs); the values belong to Bun__AsyncContextRef__enter/__leave. define({ name: "AsyncContextRef", construct: false, diff --git a/src/runtime/test_runner/jest.rs b/src/runtime/test_runner/jest.rs index 4dcbb95dc561..843c0beef622 100644 --- a/src/runtime/test_runner/jest.rs +++ b/src/runtime/test_runner/jest.rs @@ -615,8 +615,7 @@ pub(crate) mod on_unhandled_rejection { // mark errors in hooks as 'unhandled error between tests' current_state_data = RefDataValue::Start; } else { - // `add_result` below moves the runner past this test while - // its callback may still be awaiting. + // `add_result` below moves past this test while its callback may still be awaiting. sequence.abandon_executing_callback(); } } diff --git a/src/runtime/test_runner/snapshot.rs b/src/runtime/test_runner/snapshot.rs index fde2d827db77..af3c8bbf2190 100644 --- a/src/runtime/test_runner/snapshot.rs +++ b/src/runtime/test_runner/snapshot.rs @@ -144,10 +144,8 @@ impl Snapshots { hint: &[u8], ) -> Result, Error> { self.total += 1; - // Resolve the name before touching the file system: an expect() that no - // longer belongs to a running test must not create the snapshot directory - // or file. The count is taken after `get_snapshot_file`, which resets the - // counts when it switches to this test file's snapshot file. + // Name first, so a rejected expect() creates no snapshot file; count after + // `get_snapshot_file`, which resets the counts when it switches files. let name = expect.get_snapshot_name(hint)?; let buntest_strong = expect From 764fbb3213ff174ef9120156eb2114551c6256d9 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sat, 15 Aug 2026 06:34:01 +0000 Subject: [PATCH 4/9] bun test: name the matcher in expect.hasAssertions() errors; cover late inline snapshots expect.hasAssertions() reported its errors as expect.assertions(). The timed-out snapshot case now also makes a late toMatchInlineSnapshot() call, which keeps working at its own source location but must not bump the next test's counter, and the it.each done-parameter case asserts the store too. --- src/runtime/test_runner/expect.rs | 11 ++++++----- test/js/bun/test/jest-each.test.ts | 1 + .../test/snapshot-tests/snapshots/snapshot.test.ts | 12 ++++++++---- 3 files changed, 15 insertions(+), 9 deletions(-) diff --git a/src/runtime/test_runner/expect.rs b/src/runtime/test_runner/expect.rs index 200d4416bf48..7a391e09b559 100644 --- a/src/runtime/test_runner/expect.rs +++ b/src/runtime/test_runner/expect.rs @@ -1671,20 +1671,21 @@ impl Expect { // SAFETY: bun_vm() returns the live VM pointer for this global. let _gc = global_this.bun_vm().as_mut().auto_gc_on_drop(); - Self::with_caller_sequence(global_this, |sequence| { + Self::with_caller_sequence(global_this, "expect.hasAssertions()", |sequence| { if !matches!(sequence.expect_assertions, ExpectAssertions::Exact(_)) { sequence.expect_assertions = ExpectAssertions::AtLeastOne; } }) } - /// Runs `f` on the sequence an `expect.assertions()`-style call made right now applies to. + /// Runs `f` on the sequence a call of `matcher_name` made right now applies to. fn with_caller_sequence( global_this: &JSGlobalObject, + matcher_name: &str, f: impl FnOnce(&mut super::execution::ExecutionSequence), ) -> JsResult { let Some(caller) = bun_test::caller_ref(global_this) else { - return Err(global_this.throw(format_args!("expect.assertions() must be called within a test"))); + return Err(global_this.throw(format_args!("{matcher_name} must be called within a test"))); }; // `RefPtr` has no Drop; release the `+1` from `caller_ref` on every exit path. let caller = scopeguard::guard(caller, |caller| caller.deref()); @@ -1693,7 +1694,7 @@ impl Expect { .as_ref() .and_then(|buntest_strong| caller.phase.sequence(buntest_strong.get())); let Some(sequence) = sequence else { - return Err(global_this.throw(format_args!("expect.assertions() is not supported in the describe phase, in concurrent tests, between tests, or after test execution has completed"))); + return Err(global_this.throw(format_args!("{matcher_name} is not supported in the describe phase, in concurrent tests, between tests, or after test execution has completed"))); }; f(sequence); Ok(JSValue::UNDEFINED) @@ -1736,7 +1737,7 @@ impl Expect { let unsigned_expected_assertions: u32 = expected_assertions as u32; - Self::with_caller_sequence(global_this, |sequence| { + Self::with_caller_sequence(global_this, "expect.assertions()", |sequence| { sequence.expect_assertions = ExpectAssertions::Exact(unsigned_expected_assertions); }) } diff --git a/test/js/bun/test/jest-each.test.ts b/test/js/bun/test/jest-each.test.ts index eb7e47545efa..9a9265ba6dac 100644 --- a/test/js/bun/test/jest-each.test.ts +++ b/test/js/bun/test/jest-each.test.ts @@ -81,6 +81,7 @@ describe("registered inside an AsyncLocalStorage context", () => { }); it.each([[1, 1, 2]])("it.each with a done parameter: %i + %i = %i", (a, b, e, done) => { expect(a + b).toBe(e); + expect(storage.getStore()).toBe("registration"); (done as unknown as () => void)(); }); describe.each(["nested"])("describe.each: %s", s => { diff --git a/test/js/bun/test/snapshot-tests/snapshots/snapshot.test.ts b/test/js/bun/test/snapshot-tests/snapshots/snapshot.test.ts index 7e60f545ba0f..8c5f48f58208 100644 --- a/test/js/bun/test/snapshot-tests/snapshots/snapshot.test.ts +++ b/test/js/bun/test/snapshot-tests/snapshots/snapshot.test.ts @@ -967,13 +967,13 @@ describe("snapshot matchers called after the runner gave up on the test", () => const rejected = "Snapshot matchers are not supported after the test has finished executing"; const header = "// Bun Snapshot v1, https://bun.sh/docs/test/snapshots\n"; - // `report` logs whether each late matcher wrote or threw, so stdout tells the two apart. + // `report` logs whether each late matcher threw, and what, so stdout tells the outcomes apart. const prelude = /* ts */ ` import { beforeAll, beforeEach, describe, expect, test } from "bun:test"; function report(label: string, matcher: () => void) { try { matcher(); - console.log(label + ": wrote a snapshot"); + console.log(label + ": did not throw"); } catch (error) { console.log(label + ": " + (error as Error).message); } @@ -999,7 +999,8 @@ describe("snapshot matchers called after the runner gave up on the test", () => test.concurrent("a test that timed out", async () => { // Same body for both cases, as with test.each. The first case only continues once the second // one has started, so it has always timed out by then; the second case then waits for the - // first one's late matchers before taking its own snapshots. + // first one's late matchers before taking its own snapshots. The inline snapshot is keyed by + // its own source location, so it still works late; it must just not count against "second". const { stdout, stderr, snap } = await runTestFile(/* ts */ ` const secondStarted = Promise.withResolvers(); const firstDone = Promise.withResolvers(); @@ -1013,6 +1014,7 @@ describe("snapshot matchers called after the runner gave up on the test", () => throw new Error(name); }).toThrowErrorMatchingSnapshot(), ); + report("late toMatchInlineSnapshot", () => expect("lockfile of " + name).toMatchInlineSnapshot(\`"lockfile of first"\`)); firstDone.resolve(); return; } @@ -1032,13 +1034,15 @@ describe("snapshot matchers called after the runner gave up on the test", () => `late with hint: ${rejected}`, `late without hint: ${rejected}`, `late toThrowErrorMatchingSnapshot: ${rejected}`, + "late toMatchInlineSnapshot: did not throw", "", ].join("\n"), ); expect(stderr).toContain("this test timed out after 1ms"); expect(stderr).toContain("(pass) migrate > second"); // Nothing of the first case's under the second case's name, and the second case's own - // unhinted snapshot is still number 1. + // unhinted snapshot is still number 1 (on the previous behaviour the late calls, the inline + // one included, pushed it to number 2). expect(snap).toBe( header + '\nexports[`migrate second: second 1`] = `"lockfile of second"`;\n' + From 7a90379aa66f12e49cecbf18542489c5e91cf86b Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sat, 15 Aug 2026 07:58:51 +0000 Subject: [PATCH 5/9] bun test: ignore the runner's own ref when registering callbacks; rebuild the context on leave; reject late inline snapshots Hooks registered inside a test body were stored as an AsyncContextFrame because the runner's (ref, ref) pair was in the context at that point, so they ran with frame semantics and an als.enterWith() in them was discarded. Registration now treats a context holding nothing but refs as no context. Leaving an invocation used to restore the array seen on enter when the slot still held the installed array, but als.disable() splices that array in place, so the disable was undone. Leave now always strips the refs out of whatever the callback left in the slot, which also removes the two values the AsyncContextRef class carried for this. toMatchInlineSnapshot / toThrowErrorMatchingInlineSnapshot called from an invocation the runner gave up on are rejected like the .snap matchers; under a retry both attempts otherwise queued different values for the same line and the file's inline snapshots were not written at all. --- src/jsc/bindings/AsyncContextFrame.cpp | 56 ++++++++++------- src/runtime/test_runner/AsyncContextRef.rs | 24 +++----- src/runtime/test_runner/bun_test.rs | 16 ++--- src/runtime/test_runner/expect.rs | 24 ++++++-- src/runtime/test_runner/jest.classes.ts | 4 +- test/js/bun/test/jest-hooks.test.ts | 60 ++++++++++++++++++- .../snapshot-tests/snapshots/snapshot.test.ts | 59 +++++++++++++----- 7 files changed, 175 insertions(+), 68 deletions(-) diff --git a/src/jsc/bindings/AsyncContextFrame.cpp b/src/jsc/bindings/AsyncContextFrame.cpp index ca632c44e96c..cb5c7df1b0ef 100644 --- a/src/jsc/bindings/AsyncContextFrame.cpp +++ b/src/jsc/bindings/AsyncContextFrame.cpp @@ -161,6 +161,23 @@ static JSValue findAsyncContextRef(JSValue context) return jsUndefined(); } +// True for a context the runner alone populated, i.e. one that would have been +// no context at all without it. +static bool holdsOnlyAsyncContextRefs(JSValue context) +{ + auto* array = dynamicDowncast(context); + if (!array) + return false; + unsigned length = array->length(); + if (length == 0) + return false; + for (unsigned i = 0; i < length; i += 2) { + if (!array->canGetIndexQuickly(i) || !isAsyncContextRef(array->getIndexQuickly(i))) + return false; + } + return true; +} + // The caller checks for an exception afterwards. static void appendPairsWithoutRefs(JSGlobalObject* globalObject, JSValue context, MarkedArgumentBuffer& entries) { @@ -189,8 +206,19 @@ extern "C" [[ZIG_EXPORT(nothrow)]] void Bun__AsyncContextRef__enableTracking(JSC globalObject->setAsyncContextTrackingEnabled(true); } +// AsyncContextFrame::withAsyncContextIfNeeded for a test, describe or hook +// callback being registered: the (ref, ref) of the invocation registering it +// is not a context of its own. Whatever else the context holds is captured +// as usual; __enter replaces the stale ref when the callback runs. +extern "C" [[ZIG_EXPORT(nothrow)]] JSC::EncodedJSValue Bun__AsyncContextRef__withAsyncContextIfNeeded(JSC::JSGlobalObject* globalObject, JSC::EncodedJSValue callbackValue) +{ + if (holdsOnlyAsyncContextRefs(globalObject->m_asyncContextData.get()->getInternalField(0))) + return callbackValue; + return JSValue::encode(AsyncContextFrame::withAsyncContextIfNeeded(globalObject, JSValue::decode(callbackValue))); +} + // Returns what to invoke in place of `callback` so that it runs with its usual -// context plus (ref, ref). A callback registered under a context (already an +// context plus (ref, ref). A callback registered under a context (an // AsyncContextFrame) gets a new frame, which Bun__JSValue__call installs and // restores as usual. Any other callback gets the array installed in place, so // that, as before, what it does to the context (als.enterWith()) outlives it; @@ -201,8 +229,8 @@ extern "C" [[ZIG_EXPORT(zero_is_throw)]] JSC::EncodedJSValue Bun__AsyncContextRe auto scope = DECLARE_THROW_SCOPE(vm); JSValue callback = JSValue::decode(callbackValue); - auto* ref = dynamicDowncast(JSValue::decode(refValue)); - ASSERT(ref); + JSValue ref = JSValue::decode(refValue); + ASSERT(isAsyncContextRef(ref)); auto* slot = globalObject->m_asyncContextData.get(); auto* registrationFrame = dynamicDowncast(callback); @@ -225,33 +253,21 @@ extern "C" [[ZIG_EXPORT(zero_is_throw)]] JSC::EncodedJSValue Bun__AsyncContextRe if (registrationFrame) return JSValue::encode(AsyncContextFrame::create(globalObject, registrationFrame->callback.get(), context)); - ref->m_previousContext.set(vm, ref, previousContext); - ref->m_installedContext.set(vm, ref, context); slot->putInternalField(vm, 0, context); return JSValue::encode(callback); } -extern "C" [[ZIG_EXPORT(check_slow)]] void Bun__AsyncContextRef__leave(JSC::JSGlobalObject* globalObject, JSC::EncodedJSValue refValue) +// Takes the refs back out of whatever the callback left in the slot +// (als.enterWith() replaces the array, als.disable() splices it in place), so +// that those effects outlive the callback as they did before. After a frame +// the call itself restored the slot, which then holds no ref. +extern "C" [[ZIG_EXPORT(check_slow)]] void Bun__AsyncContextRef__leave(JSC::JSGlobalObject* globalObject) { auto& vm = JSC::getVM(globalObject); auto scope = DECLARE_THROW_SCOPE(vm); - auto* ref = dynamicDowncast(JSValue::decode(refValue)); - ASSERT(ref); - JSValue installed = ref->m_installedContext.get(); - if (!installed) - return; // __enter returned a frame instead - JSValue previous = ref->m_previousContext.get(); - ref->m_installedContext.clear(); - ref->m_previousContext.clear(); - auto* slot = globalObject->m_asyncContextData.get(); JSValue current = slot->getInternalField(0); - if (current == installed) { - slot->putInternalField(vm, 0, previous); - return; - } - // The callback replaced the array (enterWith() copies it); keep its version without the ref. if (findAsyncContextRef(current).isUndefined()) return; MarkedArgumentBuffer entries; diff --git a/src/runtime/test_runner/AsyncContextRef.rs b/src/runtime/test_runner/AsyncContextRef.rs index c7ef563a4200..07aaaff6ae38 100644 --- a/src/runtime/test_runner/AsyncContextRef.rs +++ b/src/runtime/test_runner/AsyncContextRef.rs @@ -8,6 +8,8 @@ //! late calls to the abandoned invocation instead, which rejects them. //! Invocations that completed are never consulted, so callbacks they //! registered keep belonging to whichever entry runs them. +//! +//! The slot manipulation lives next to `AsyncContextFrame` (AsyncContextFrame.cpp). use bun_jsc::{JSGlobalObject, JSValue, JsClass as _, JsResult}; @@ -19,14 +21,6 @@ pub struct AsyncContextRef { r#ref: RefDataPtr, } -/// Plain `JSValue`s (not an `Option`) so the conservative stack scan sees both. -pub(crate) struct Entered { - /// What to invoke in place of the callback passed to [`AsyncContextRef::enter`]. - pub(crate) callable: JSValue, - /// For [`AsyncContextRef::leave`]. - pub(crate) ref_js: JSValue, -} - impl AsyncContextRef { // Codegen calls `finalize(Box)`; clippy::boxed_local is a false positive. #[allow(clippy::boxed_local)] @@ -35,19 +29,17 @@ impl AsyncContextRef { } /// Puts `refdata` (a `+1`, consumed) into the context `callback` is about to - /// run with. See `Bun__AsyncContextRef__enter` for what that does to the slot. - pub(crate) fn enter(global: &JSGlobalObject, callback: JSValue, refdata: RefDataPtr) -> JsResult { + /// run with, and returns what to invoke in its place. Pair with [`Self::leave`]. + pub(crate) fn enter(global: &JSGlobalObject, callback: JSValue, refdata: RefDataPtr) -> JsResult { let ref_js = AsyncContextRef { r#ref: refdata }.to_js(global); let callable = bun_jsc::cpp::Bun__AsyncContextRef__enter(global, callback, ref_js); ref_js.ensure_still_alive(); - Ok(Entered { callable: callable?, ref_js }) + callable } - /// Takes the ref back out once the callback returned, before microtasks are drained. - pub(crate) fn leave(global: &JSGlobalObject, ref_js: JSValue) -> JsResult<()> { - let result = bun_jsc::cpp::Bun__AsyncContextRef__leave(global, ref_js); - ref_js.ensure_still_alive(); - result + /// Call once the callback returned, before its microtasks run. + pub(crate) fn leave(global: &JSGlobalObject) -> JsResult<()> { + bun_jsc::cpp::Bun__AsyncContextRef__leave(global) } /// A `+1` to the abandoned invocation the running JS descends from, if any. diff --git a/src/runtime/test_runner/bun_test.rs b/src/runtime/test_runner/bun_test.rs index ac3684f54538..30b3e6d56134 100644 --- a/src/runtime/test_runner/bun_test.rs +++ b/src/runtime/test_runner/bun_test.rs @@ -52,11 +52,13 @@ fn strong_create(value: JSValue) -> Strong { Strong::create(value, global) } +/// `JSValue::with_async_context_if_needed`, except that the ref of the test +/// registering the callback (AsyncContextRef.rs) does not count as a context. /// Applied when a test/describe/hook callback is stored, not when the arguments /// are parsed: registration reads `.length` and `.bind()`s the function itself, /// and the wrapper is not a function. pub(crate) fn keep_registration_async_context(callback: JSValue) -> JSValue { - callback.with_async_context_if_needed(VirtualMachine::get().global()) + bun_jsc::cpp::Bun__AsyncContextRef__withAsyncContextIfNeeded(VirtualMachine::get().global(), callback) } pub(crate) fn clone_active_strong() -> Option { @@ -1178,12 +1180,12 @@ impl BunTest { } let mut callable: JSValue = cfg_callback; - let mut entered_ref: JSValue = JSValue::ZERO; + let mut entered = false; if let Some(invocation_ref) = invocation_ref { match AsyncContextRef::enter(global_this, cfg_callback, invocation_ref) { - Ok(entered) => { - callable = entered.callable; - entered_ref = entered.ref_js; + Ok(v) => { + callable = v; + entered = true; } Err(e) => { // OOM: charge it to this entry and still run the callback, as for `done` above. @@ -1210,8 +1212,8 @@ impl BunTest { } } } - if !entered_ref.is_empty() { - if let Err(e) = AsyncContextRef::leave(global_this, entered_ref) { + if entered { + if let Err(e) = AsyncContextRef::leave(global_this) { let exception = global_this.take_exception(e); if failure.is_none() { failure = Some(Some(exception)); diff --git a/src/runtime/test_runner/expect.rs b/src/runtime/test_runner/expect.rs index 7a391e09b559..b070b8050703 100644 --- a/src/runtime/test_runner/expect.rs +++ b/src/runtime/test_runner/expect.rs @@ -212,6 +212,19 @@ impl Expect { parent.bun_test() } + /// An invocation the runner gave up on (AsyncContextRef.rs) gets to record + /// nothing more, with the error an `expect()` left over from a finished test gets. + fn reject_snapshot_if_abandoned(&self, global_this: &JSGlobalObject) -> JsResult<()> { + if self.parent.as_ref().is_some_and(|parent| parent.abandoned.get()) { + return Err(Self::throw_test_finished(global_this)); + } + Ok(()) + } + + fn throw_test_finished(global_this: &JSGlobalObject) -> JsError { + global_this.throw(format_args!("Snapshot matchers are not supported after the test has finished executing")) + } + pub(crate) fn get_signature( matcher_name: &'static str, args: &'static str, @@ -623,9 +636,8 @@ impl Expect { pub(crate) fn get_snapshot_name(&self, hint: &[u8]) -> crate::Result> { let parent = self.parent.as_ref().ok_or(crate::Error::NoTest)?; - if parent.abandoned.get() { - return Err(crate::Error::TestNotActive); - } + // Under a retry, an abandoned attempt's entry is current again; `reject_snapshot_if_abandoned` ran first. + debug_assert!(!parent.abandoned.get()); let buntest_strong = parent.bun_test().ok_or(crate::Error::TestNotActive)?; let buntest = buntest_strong.get(); let execution_entry = match &parent.phase { @@ -1061,6 +1073,7 @@ impl Expect { let signature = Self::get_signature(fn_name, "", false); return throw!(this, global_this, signature, "\n\nMatcher error: Snapshot matchers cannot be used outside of a test\n"); }; + this.reject_snapshot_if_abandoned(global_this)?; match runner.snapshots.add_count(this, b"") { Ok(_) => {} Err(crate::Error::Alloc(bun_alloc::AllocError)) => return Err(JsError::OutOfMemory), @@ -1209,6 +1222,7 @@ impl Expect { fn_name: &'static str, ) -> JsResult { let this = self; + this.reject_snapshot_if_abandoned(global_this)?; let mut pretty_value: Vec = Vec::new(); this.match_and_fmt_snapshot(global_this, value, property_matchers, &mut pretty_value, fn_name)?; @@ -1221,9 +1235,7 @@ impl Expect { crate::Error::SnapshotInConcurrentGroup => { return Err(global_this.throw(format_args!("Snapshot matchers are not supported in concurrent tests"))); } - crate::Error::TestNotActive => { - return Err(global_this.throw(format_args!("Snapshot matchers are not supported after the test has finished executing"))); - } + crate::Error::TestNotActive => return Err(Self::throw_test_finished(global_this)), crate::Error::NoTest => { return Err(global_this.throw(format_args!("Snapshot matchers cannot be used outside of a test"))); } diff --git a/src/runtime/test_runner/jest.classes.ts b/src/runtime/test_runner/jest.classes.ts index ff1b83ea9153..d2cca26ffbcf 100644 --- a/src/runtime/test_runner/jest.classes.ts +++ b/src/runtime/test_runner/jest.classes.ts @@ -803,14 +803,14 @@ export default [ klass: {}, proto: {}, }), - // Internal to the runner (AsyncContextRef.rs); the values belong to Bun__AsyncContextRef__enter/__leave. + // Internal to the runner (AsyncContextRef.rs). define({ name: "AsyncContextRef", construct: false, noConstructor: true, finalize: true, JSType: "0b11101110", - values: ["installedContext", "previousContext"], + values: [], configurable: false, klass: {}, proto: {}, diff --git a/test/js/bun/test/jest-hooks.test.ts b/test/js/bun/test/jest-hooks.test.ts index 49eb177951a5..3de94e88e9e2 100644 --- a/test/js/bun/test/jest-hooks.test.ts +++ b/test/js/bun/test/jest-hooks.test.ts @@ -1,4 +1,4 @@ -import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from "bun:test"; +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, onTestFinished } from "bun:test"; import { AsyncLocalStorage } from "node:async_hooks"; let hooks_run: string[] = []; @@ -253,10 +253,33 @@ describe("test jest hooks in bun-test", () => { // The runner adds its own entry to the async context while a hook or test runs; what the // callback itself does to the context has to stay in effect afterwards, as it always has. -describe("AsyncLocalStorage.enterWith() in a hook stays in effect for the tests that follow", () => { +describe("what a hook does to the AsyncLocalStorage context stays in effect for the tests that follow", () => { const storage = new AsyncLocalStorage(); afterAll(() => storage.disable()); + // First, while no store has been entered yet: a hook registered while a store is active runs + // under that store instead (last describe in this file). The runner's own entry is in the + // context when these hooks are registered, and must not count as such a store. + describe("entered in hooks registered inside a test", () => { + let storeWhenOnTestFinishedRan: string | undefined; + + it("registers them", () => { + afterEach(() => { + storage.enterWith("from the afterEach"); + }); + // Runs after the afterEach hooks, including the file's. + onTestFinished(() => { + storeWhenOnTestFinishedRan = storage.getStore(); + storage.enterWith("from the onTestFinished"); + }); + }); + + it("each one's store is in effect for what follows it", () => { + expect(storeWhenOnTestFinishedRan).toBe("from the afterEach"); + expect(storage.getStore()).toBe("from the onTestFinished"); + }); + }); + describe("entered in beforeAll", () => { beforeAll(() => { storage.enterWith("from beforeAll"); @@ -287,4 +310,37 @@ describe("AsyncLocalStorage.enterWith() in a hook stays in effect for the tests expect(storage.getStore()).toBe("beforeEach run 2"); }); }); + + // disable() splices the storage out of the context array in place rather than replacing it. + describe("disabled in a later beforeAll", () => { + beforeAll(() => { + storage.enterWith("entered before disable()"); + }); + beforeAll(() => { + storage.disable(); + }); + + it("stays gone: run() does not bring the old store back", () => { + storage.run("inside run()", () => {}); + expect(storage.getStore()).toBeUndefined(); + }); + }); +}); + +describe("a hook registered inside a test under AsyncLocalStorage.run() runs with that store", () => { + const storage = new AsyncLocalStorage(); + let storeSeenByAfterEach: string | undefined; + + it("registers the hook", () => { + storage.run("store of the run() that registered it", () => { + afterEach(() => { + storeSeenByAfterEach = storage.getStore(); + }); + }); + }); + + it("the hook saw the store; the next test does not", () => { + expect(storeSeenByAfterEach).toBe("store of the run() that registered it"); + expect(storage.getStore()).toBeUndefined(); + }); }); diff --git a/test/js/bun/test/snapshot-tests/snapshots/snapshot.test.ts b/test/js/bun/test/snapshot-tests/snapshots/snapshot.test.ts index 8c5f48f58208..e9bf4ff7ec35 100644 --- a/test/js/bun/test/snapshot-tests/snapshots/snapshot.test.ts +++ b/test/js/bun/test/snapshot-tests/snapshots/snapshot.test.ts @@ -981,7 +981,8 @@ describe("snapshot matchers called after the runner gave up on the test", () => `; async function runTestFile(source: string) { - using dir = tempDir("snapshot-after-runner-moved-on", { "late.test.ts": prelude + source }); + const testFile = prelude + source; + using dir = tempDir("snapshot-after-runner-moved-on", { "late.test.ts": testFile }); await using proc = Bun.spawn({ cmd: [bunExe(), "test", "late.test.ts"], cwd: String(dir), @@ -992,16 +993,17 @@ describe("snapshot matchers called after the runner gave up on the test", () => const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); const snapPath = join(String(dir), "__snapshots__", "late.test.ts.snap"); const snap = existsSync(snapPath) ? readFileSync(snapPath, "utf8") : null; + // Inline snapshots are written into the test file itself once the run is over. + const testFileAfterwards = readFileSync(join(String(dir), "late.test.ts"), "utf8"); // stdout starts with the "bun test vX.Y.Z (sha)" banner; the rest is what the test file logged. - return { stdout: stdout.replace(/^bun test v.*\n/, ""), stderr, exitCode, snap }; + return { stdout: stdout.replace(/^bun test v.*\n/, ""), stderr, exitCode, snap, testFile, testFileAfterwards }; } test.concurrent("a test that timed out", async () => { // Same body for both cases, as with test.each. The first case only continues once the second // one has started, so it has always timed out by then; the second case then waits for the - // first one's late matchers before taking its own snapshots. The inline snapshot is keyed by - // its own source location, so it still works late; it must just not count against "second". - const { stdout, stderr, snap } = await runTestFile(/* ts */ ` + // first one's late matchers before taking its own snapshots. + const { stdout, stderr, snap, testFile, testFileAfterwards } = await runTestFile(/* ts */ ` const secondStarted = Promise.withResolvers(); const firstDone = Promise.withResolvers(); async function migrate(name: string) { @@ -1014,7 +1016,15 @@ describe("snapshot matchers called after the runner gave up on the test", () => throw new Error(name); }).toThrowErrorMatchingSnapshot(), ); - report("late toMatchInlineSnapshot", () => expect("lockfile of " + name).toMatchInlineSnapshot(\`"lockfile of first"\`)); + // Block bodies: a matcher called in tail position gets located at report()'s own call to it. + report("late toMatchInlineSnapshot", () => { + expect("lockfile of " + name).toMatchInlineSnapshot(); + }); + report("late toThrowErrorMatchingInlineSnapshot", () => { + expect(() => { + throw new Error(name); + }).toThrowErrorMatchingInlineSnapshot(); + }); firstDone.resolve(); return; } @@ -1034,20 +1044,23 @@ describe("snapshot matchers called after the runner gave up on the test", () => `late with hint: ${rejected}`, `late without hint: ${rejected}`, `late toThrowErrorMatchingSnapshot: ${rejected}`, - "late toMatchInlineSnapshot: did not throw", + `late toMatchInlineSnapshot: ${rejected}`, + `late toThrowErrorMatchingInlineSnapshot: ${rejected}`, "", ].join("\n"), ); expect(stderr).toContain("this test timed out after 1ms"); expect(stderr).toContain("(pass) migrate > second"); // Nothing of the first case's under the second case's name, and the second case's own - // unhinted snapshot is still number 1 (on the previous behaviour the late calls, the inline - // one included, pushed it to number 2). + // unhinted snapshot is still number 1 (on the previous behaviour the late calls pushed it to + // number 2). expect(snap).toBe( header + '\nexports[`migrate second: second 1`] = `"lockfile of second"`;\n' + '\nexports[`migrate second 1`] = `"lockfile of second"`;\n', ); + // The late inline matchers did not get their snapshots written into the test file either. + expect(testFileAfterwards).toBe(testFile); }); test.concurrent("a hook that timed out", async () => { @@ -1099,32 +1112,48 @@ describe("snapshot matchers called after the runner gave up on the test", () => }); test.concurrent("an attempt that the runner gave up on, while its retry runs", async () => { - const { stdout, stderr, snap } = await runTestFile(/* ts */ ` + // Both attempts run the same inline matcher. On the previous behaviour the first attempt's late + // call and the retry's call asked for different values on the same line, which fails the + // writing of the file's inline snapshots as a whole ("Multiple inline snapshots on the same + // line must all have the same value"). + const { stdout, stderr, snap, testFile, testFileAfterwards } = await runTestFile(/* ts */ ` const retryStarted = Promise.withResolvers(); const firstAttemptDone = Promise.withResolvers(); let attempts = 0; test( "retried", async () => { - if (attempts++ === 0) { + const attempt = ++attempts; + // Block body: a matcher called in tail position gets located at the call to inline() instead. + const inline = () => { + expect("from attempt " + attempt).toMatchInlineSnapshot(); + }; + if (attempt === 1) { Promise.reject(new Error("first attempt fails in the background")); await retryStarted.promise; - report("late from the first attempt", () => expect("from attempt 1").toMatchSnapshot()); + report("late from the first attempt", () => expect("from attempt " + attempt).toMatchSnapshot()); + report("late inline from the first attempt", inline); firstAttemptDone.resolve(); return; } retryStarted.resolve(); await firstAttemptDone.promise; - expect("from attempt 2").toMatchSnapshot(); + expect("from attempt " + attempt).toMatchSnapshot(); + inline(); }, { retry: 1 }, ); `); - expect(stdout).toBe(`late from the first attempt: ${rejected}\n`); + expect(stdout).toBe(`late from the first attempt: ${rejected}\nlate inline from the first attempt: ${rejected}\n`); expect(stderr).toContain("(pass) retried"); - // The passing attempt owns "retried 1"; a later run must compare against its value. + expect(stderr).not.toContain("Failed to update inline snapshot"); + // The passing attempt owns "retried 1" and the inline snapshot; a later run must compare + // against its values. expect(snap).toBe(header + '\nexports[`retried 1`] = `"from attempt 2"`;\n'); + expect(testFileAfterwards).toBe( + testFile.replace("toMatchInlineSnapshot()", 'toMatchInlineSnapshot(`"from attempt 2"`)'), + ); }); test.concurrent("callbacks registered by a finished hook still snapshot under the running test", async () => { From 96f46f4894f9d75d6822de1e26755b6285fcb688 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sat, 15 Aug 2026 08:20:56 +0000 Subject: [PATCH 6/9] bun test: scope the timed-out hook of the snapshot test to one test; shorter comments The 1ms beforeEach also ran for "second", and a hook that returns right away still fails with a timeout when invoking it took longer than that, which happened under load (3 of 12 concurrent runs). The hook now lives in a describe holding only "first". --- src/jsc/bindings/AsyncContextFrame.cpp | 17 +++++++---------- src/runtime/test_runner/bun_test.rs | 8 +++----- src/runtime/test_runner/expect.rs | 3 +-- .../snapshot-tests/snapshots/snapshot.test.ts | 19 +++++++++++-------- 4 files changed, 22 insertions(+), 25 deletions(-) diff --git a/src/jsc/bindings/AsyncContextFrame.cpp b/src/jsc/bindings/AsyncContextFrame.cpp index cb5c7df1b0ef..e70f4bda7253 100644 --- a/src/jsc/bindings/AsyncContextFrame.cpp +++ b/src/jsc/bindings/AsyncContextFrame.cpp @@ -161,8 +161,7 @@ static JSValue findAsyncContextRef(JSValue context) return jsUndefined(); } -// True for a context the runner alone populated, i.e. one that would have been -// no context at all without it. +// A context the runner alone populated: without the runner there would be none. static bool holdsOnlyAsyncContextRefs(JSValue context) { auto* array = dynamicDowncast(context); @@ -206,10 +205,9 @@ extern "C" [[ZIG_EXPORT(nothrow)]] void Bun__AsyncContextRef__enableTracking(JSC globalObject->setAsyncContextTrackingEnabled(true); } -// AsyncContextFrame::withAsyncContextIfNeeded for a test, describe or hook -// callback being registered: the (ref, ref) of the invocation registering it -// is not a context of its own. Whatever else the context holds is captured -// as usual; __enter replaces the stale ref when the callback runs. +// AsyncContextFrame::withAsyncContextIfNeeded for a callback being registered: the +// registering invocation's (ref, ref) is not a context to capture. __enter drops it +// from a context that is. extern "C" [[ZIG_EXPORT(nothrow)]] JSC::EncodedJSValue Bun__AsyncContextRef__withAsyncContextIfNeeded(JSC::JSGlobalObject* globalObject, JSC::EncodedJSValue callbackValue) { if (holdsOnlyAsyncContextRefs(globalObject->m_asyncContextData.get()->getInternalField(0))) @@ -257,10 +255,9 @@ extern "C" [[ZIG_EXPORT(zero_is_throw)]] JSC::EncodedJSValue Bun__AsyncContextRe return JSValue::encode(callback); } -// Takes the refs back out of whatever the callback left in the slot -// (als.enterWith() replaces the array, als.disable() splices it in place), so -// that those effects outlive the callback as they did before. After a frame -// the call itself restored the slot, which then holds no ref. +// Takes the refs out of whatever the callback left in the slot, keeping the rest +// in effect as before. Always rebuilt: als.disable() splices the installed array +// in place. After a frame the call restored the slot itself, so there is no ref. extern "C" [[ZIG_EXPORT(check_slow)]] void Bun__AsyncContextRef__leave(JSC::JSGlobalObject* globalObject) { auto& vm = JSC::getVM(globalObject); diff --git a/src/runtime/test_runner/bun_test.rs b/src/runtime/test_runner/bun_test.rs index 30b3e6d56134..4d9e43849417 100644 --- a/src/runtime/test_runner/bun_test.rs +++ b/src/runtime/test_runner/bun_test.rs @@ -52,11 +52,9 @@ fn strong_create(value: JSValue) -> Strong { Strong::create(value, global) } -/// `JSValue::with_async_context_if_needed`, except that the ref of the test -/// registering the callback (AsyncContextRef.rs) does not count as a context. -/// Applied when a test/describe/hook callback is stored, not when the arguments -/// are parsed: registration reads `.length` and `.bind()`s the function itself, -/// and the wrapper is not a function. +/// `JSValue::with_async_context_if_needed` minus the registering test's own ref (AsyncContextRef.rs). +/// Applied where the callback is stored: registration reads `.length` of and `.bind()`s the +/// function itself, and the wrapper is not a function. pub(crate) fn keep_registration_async_context(callback: JSValue) -> JSValue { bun_jsc::cpp::Bun__AsyncContextRef__withAsyncContextIfNeeded(VirtualMachine::get().global(), callback) } diff --git a/src/runtime/test_runner/expect.rs b/src/runtime/test_runner/expect.rs index b070b8050703..9994f20c9cad 100644 --- a/src/runtime/test_runner/expect.rs +++ b/src/runtime/test_runner/expect.rs @@ -212,8 +212,7 @@ impl Expect { parent.bun_test() } - /// An invocation the runner gave up on (AsyncContextRef.rs) gets to record - /// nothing more, with the error an `expect()` left over from a finished test gets. + /// Same error as for an `expect()` left over from a finished test (AsyncContextRef.rs). fn reject_snapshot_if_abandoned(&self, global_this: &JSGlobalObject) -> JsResult<()> { if self.parent.as_ref().is_some_and(|parent| parent.abandoned.get()) { return Err(Self::throw_test_finished(global_this)); diff --git a/test/js/bun/test/snapshot-tests/snapshots/snapshot.test.ts b/test/js/bun/test/snapshot-tests/snapshots/snapshot.test.ts index e9bf4ff7ec35..cdeabd211ccf 100644 --- a/test/js/bun/test/snapshot-tests/snapshots/snapshot.test.ts +++ b/test/js/bun/test/snapshot-tests/snapshots/snapshot.test.ts @@ -1064,17 +1064,19 @@ describe("snapshot matchers called after the runner gave up on the test", () => }); test.concurrent("a hook that timed out", async () => { + // The hook only applies to "first": a 1ms timeout also fails a hook that returns right away + // whenever invoking it took longer than that, which happens on a loaded machine. const { stdout, stderr, snap } = await runTestFile(/* ts */ ` const secondStarted = Promise.withResolvers(); const hookDone = Promise.withResolvers(); - let hookRuns = 0; - beforeEach(async () => { - if (hookRuns++ > 0) return; - await secondStarted.promise; - report("late from the hook", () => expect("from the hook").toMatchSnapshot("hook")); - hookDone.resolve(); - }, 1); - test("first", () => {}); + describe("with the hook", () => { + beforeEach(async () => { + await secondStarted.promise; + report("late from the hook", () => expect("from the hook").toMatchSnapshot("hook")); + hookDone.resolve(); + }, 1); + test("first", () => {}); + }); test("second", async () => { secondStarted.resolve(); await hookDone.promise; @@ -1083,6 +1085,7 @@ describe("snapshot matchers called after the runner gave up on the test", () => `); expect(stdout).toBe(`late from the hook: ${rejected}\n`); + expect(stderr).toContain("(fail) with the hook > first"); expect(stderr).toContain("(pass) second"); expect(snap).toBe(header + '\nexports[`second 1`] = `"from second"`;\n'); }); From 3ed79568bfe63909b979589b30e106cbc623be72 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sat, 15 Aug 2026 11:39:14 +0000 Subject: [PATCH 7/9] bun test: reject hooks registered by an abandoned invocation; drop the snapshot hunks other PRs own afterEach/afterAll/onTestFinished called by a test body the runner has already given up on were added to whichever test was running by then. They now fail with an error, through the same ref expect() uses. The snapshot.rs reordering and the get_snapshot_name reclassification are not needed once the abandoned check happens before the matchers touch anything, and they overlap with #38799 and #38874, so they are gone. The two cases that fail the running test with an unhandled error now wait through done() instead of a returned promise, so they describe the situation the runner gives up on whether or not #36719 has landed. --- src/runtime/test_runner/AsyncContextRef.rs | 33 +++++++----- src/runtime/test_runner/bun_test.rs | 8 +++ src/runtime/test_runner/expect.rs | 41 ++++---------- src/runtime/test_runner/jest.rs | 4 +- src/runtime/test_runner/snapshot.rs | 21 +++----- .../snapshot-tests/snapshots/snapshot.test.ts | 42 +++++++++------ .../js/bun/test/test-on-test-finished.test.ts | 54 +++++++++++++++++++ 7 files changed, 130 insertions(+), 73 deletions(-) diff --git a/src/runtime/test_runner/AsyncContextRef.rs b/src/runtime/test_runner/AsyncContextRef.rs index 07aaaff6ae38..ef3547f9a68b 100644 --- a/src/runtime/test_runner/AsyncContextRef.rs +++ b/src/runtime/test_runner/AsyncContextRef.rs @@ -1,13 +1,15 @@ //! Put into the async context for the duration of one test or hook invocation, //! so that the invocation's continuations can still be traced back to it. //! -//! `expect()` belongs to whatever entry the runner is executing when it is -//! called. Once the runner has abandoned an invocation that is still running -//! (timeout, or an unhandled error while it was awaiting), that would be the -//! next entry; `RefData::abandoned` makes `bun_test::caller_ref` attribute such -//! late calls to the abandoned invocation instead, which rejects them. -//! Invocations that completed are never consulted, so callbacks they -//! registered keep belonging to whichever entry runs them. +//! `expect()`, the snapshot matchers, `expect.assertions()` and hook registration +//! belong to whatever entry the runner is executing when they are called. Once +//! the runner has abandoned an invocation that is still running (timeout, or an +//! unhandled error while it was awaiting), that would be the next entry; +//! `RefData::abandoned` makes `bun_test::caller_ref` attribute such late calls +//! to the abandoned invocation instead, which rejects them. Invocations that +//! completed are never consulted, so callbacks they registered keep belonging to +//! whichever entry runs them. Uncaught errors are not covered: by the time one is +//! reported (`jest::on_unhandled_rejection`) the context it was thrown in is gone. //! //! The slot manipulation lives next to `AsyncContextFrame` (AsyncContextFrame.cpp). @@ -44,12 +46,19 @@ impl AsyncContextRef { /// A `+1` to the abandoned invocation the running JS descends from, if any. pub(crate) fn abandoned_caller(global: &JSGlobalObject) -> Option { + Self::abandoned_in_context(global).map(RefDataPtr::dupe_ref) + } + + pub(crate) fn caller_is_abandoned(global: &JSGlobalObject) -> bool { + Self::abandoned_in_context(global).is_some() + } + + /// To use right away: the borrow is of a wrapper that the context array + /// installed at this moment keeps alive. + fn abandoned_in_context(global: &JSGlobalObject) -> Option<&RefDataPtr> { let this = Self::from_js(bun_jsc::cpp::Bun__AsyncContextRef__current(global))?; - // SAFETY: the live payload of a wrapper the current context array keeps alive. + // SAFETY: live payload of the wrapper `__current` just found in the context array. let refdata: &RefDataPtr = unsafe { &(*this).r#ref }; - if !refdata.abandoned.get() { - return None; - } - Some(refdata.dupe_ref()) + refdata.abandoned.get().then_some(refdata) } } diff --git a/src/runtime/test_runner/bun_test.rs b/src/runtime/test_runner/bun_test.rs index 4d9e43849417..338bd946e2bc 100644 --- a/src/runtime/test_runner/bun_test.rs +++ b/src/runtime/test_runner/bun_test.rs @@ -193,6 +193,14 @@ pub mod js_fns { let tag_name: &'static str = tag.into(); let sig_bytes: &'static [u8] = tag.sig(); + // Otherwise the hook would be added to whatever happens to be running now. + if AsyncContextRef::caller_is_abandoned(global_this) { + return Err(global_this.throw(format_args!( + "Cannot call {}() here. The test or hook it was called from has already finished executing (it timed out, or failed while it was still running).", + tag_name + ))); + } + let args = ScopeFunctions::parse_arguments( global_this, call_frame, diff --git a/src/runtime/test_runner/expect.rs b/src/runtime/test_runner/expect.rs index 9994f20c9cad..7b9753dd4a21 100644 --- a/src/runtime/test_runner/expect.rs +++ b/src/runtime/test_runner/expect.rs @@ -215,15 +215,11 @@ impl Expect { /// Same error as for an `expect()` left over from a finished test (AsyncContextRef.rs). fn reject_snapshot_if_abandoned(&self, global_this: &JSGlobalObject) -> JsResult<()> { if self.parent.as_ref().is_some_and(|parent| parent.abandoned.get()) { - return Err(Self::throw_test_finished(global_this)); + return Err(global_this.throw(format_args!("Snapshot matchers are not supported after the test has finished executing"))); } Ok(()) } - fn throw_test_finished(global_this: &JSGlobalObject) -> JsError { - global_this.throw(format_args!("Snapshot matchers are not supported after the test has finished executing")) - } - pub(crate) fn get_signature( matcher_name: &'static str, args: &'static str, @@ -635,22 +631,12 @@ impl Expect { pub(crate) fn get_snapshot_name(&self, hint: &[u8]) -> crate::Result> { let parent = self.parent.as_ref().ok_or(crate::Error::NoTest)?; - // Under a retry, an abandoned attempt's entry is current again; `reject_snapshot_if_abandoned` ran first. - debug_assert!(!parent.abandoned.get()); let buntest_strong = parent.bun_test().ok_or(crate::Error::TestNotActive)?; let buntest = buntest_strong.get(); - let execution_entry = match &parent.phase { - // None once the runner advanced past the entry this expect() was created in. - bun_test::RefDataValue::Execution { entry_data: Some(_), .. } => { - parent.phase.entry(buntest).ok_or(crate::Error::TestNotActive)? - } - bun_test::RefDataValue::Execution { entry_data: None, .. } => { - return Err(crate::Error::SnapshotInConcurrentGroup); - } - bun_test::RefDataValue::Start - | bun_test::RefDataValue::Collection { .. } - | bun_test::RefDataValue::Done => return Err(crate::Error::NoTest), - }; + let execution_entry = parent + .phase + .entry(buntest) + .ok_or(crate::Error::SnapshotInConcurrentGroup)?; let test_name: &[u8] = execution_entry.base.name.as_deref().unwrap_or(b"(unnamed)"); @@ -1229,17 +1215,6 @@ impl Expect { let existing_value = match runner.snapshots.get_or_put(this, &pretty_value, hint) { Ok(v) => v, Err(err) => { - // These need no test file; the one this expect() belongs to may be gone. - match err { - crate::Error::SnapshotInConcurrentGroup => { - return Err(global_this.throw(format_args!("Snapshot matchers are not supported in concurrent tests"))); - } - crate::Error::TestNotActive => return Err(Self::throw_test_finished(global_this)), - crate::Error::NoTest => { - return Err(global_this.throw(format_args!("Snapshot matchers cannot be used outside of a test"))); - } - _ => {} - } let Some(buntest_strong) = this.bun_test() else { return Err(global_this.throw(format_args!("Snapshot matchers cannot be used outside of a test"))); }; @@ -1275,6 +1250,12 @@ impl Expect { )) } } + crate::Error::SnapshotInConcurrentGroup => { + global_this.throw(format_args!("Snapshot matchers are not supported in concurrent tests")) + } + crate::Error::TestNotActive => { + global_this.throw(format_args!("Snapshot matchers are not supported after the test has finished executing")) + } _ => { let mut formatter = ConsoleObject::Formatter::new(global_this); global_this.throw(format_args!("Failed to snapshot value: {}", value.to_fmt(&mut formatter))) diff --git a/src/runtime/test_runner/jest.rs b/src/runtime/test_runner/jest.rs index 843c0beef622..8dd82e37d461 100644 --- a/src/runtime/test_runner/jest.rs +++ b/src/runtime/test_runner/jest.rs @@ -603,7 +603,9 @@ pub(crate) mod on_unhandled_rejection { // re-borrows. Const→mut projection is centralized in `buntest_as_mut` // pending the BunTestPtr interior-mut reshape (see bun_test.rs). let buntest = unsafe { bun_test::buntest_as_mut(&buntest_strong) }; - // mark unhandled errors as belonging to the currently active test. note that this can be misleading. + // mark unhandled errors as belonging to the currently active test. note that this can be misleading: + // it includes errors thrown late by an abandoned invocation (AsyncContextRef.rs), whose context is + // no longer installed when the error gets here. let mut current_state_data = buntest.get_current_state_data(); // split entry()/sequence() borrows via raw-ptr capture (per-use reborrow). let entry_ptr: Option<*mut bun_test::ExecutionEntry> = current_state_data diff --git a/src/runtime/test_runner/snapshot.rs b/src/runtime/test_runner/snapshot.rs index af3c8bbf2190..39e1fdd93197 100644 --- a/src/runtime/test_runner/snapshot.rs +++ b/src/runtime/test_runner/snapshot.rs @@ -120,21 +120,19 @@ impl Snapshots { pub(crate) fn add_count(&mut self, expect: &Expect, hint: &[u8]) -> Result<(Vec, usize), Error> { self.total += 1; let snapshot_name = expect.get_snapshot_name(hint)?; - let count = self.increment_count(&snapshot_name)?; - Ok((snapshot_name, count)) - } - - fn increment_count(&mut self, snapshot_name: &[u8]) -> Result { + // bun_collections::StringHashMap::get_or_put can't hand out `key_ptr`, so return the + // owned `snapshot_name` (same bytes as the interned key) instead. let gop = self .counts - .get_or_put(snapshot_name) + .get_or_put(&snapshot_name) .map_err(Error::from)?; if gop.found_existing { *gop.value_ptr += 1; } else { *gop.value_ptr = 1; } - Ok(*gop.value_ptr) + let count = *gop.value_ptr; + Ok((snapshot_name, count)) } pub(crate) fn get_or_put( @@ -143,14 +141,9 @@ impl Snapshots { target_value: &[u8], hint: &[u8], ) -> Result, Error> { - self.total += 1; - // Name first, so a rejected expect() creates no snapshot file; count after - // `get_snapshot_file`, which resets the counts when it switches files. - let name = expect.get_snapshot_name(hint)?; - let buntest_strong = expect .bun_test() - .ok_or(crate::Error::TestNotActive)?; + .ok_or(crate::Error::SnapshotFailed)?; let bun_test = buntest_strong.get(); match self.get_snapshot_file(bun_test.file_id)? { bun_sys::Result::Ok(()) => {} @@ -167,7 +160,7 @@ impl Snapshots { } } - let counter = self.increment_count(&name)?; + let (name, counter) = self.add_count(expect, hint)?; let mut counter_string_buf = [0u8; 32]; let counter_string = bun_core::fmt::int_as_bytes(&mut counter_string_buf, counter); diff --git a/test/js/bun/test/snapshot-tests/snapshots/snapshot.test.ts b/test/js/bun/test/snapshot-tests/snapshots/snapshot.test.ts index cdeabd211ccf..46e7efc5e73e 100644 --- a/test/js/bun/test/snapshot-tests/snapshots/snapshot.test.ts +++ b/test/js/bun/test/snapshot-tests/snapshots/snapshot.test.ts @@ -961,8 +961,8 @@ test("write snapshot from filter", async () => { }); // When the runner gives up on a test or hook that is still running (it timed out, or an unhandled -// error failed it while it was awaiting), its body keeps running while the next test executes. The -// snapshot matchers it calls from then on must be rejected, not written under the next test's name. +// error failed it while it was still waiting), its body keeps running while the next test executes. +// The snapshot matchers it calls from then on must be rejected, not written under the next test's name. describe("snapshot matchers called after the runner gave up on the test", () => { const rejected = "Snapshot matchers are not supported after the test has finished executing"; const header = "// Bun Snapshot v1, https://bun.sh/docs/test/snapshots\n"; @@ -1090,17 +1090,23 @@ describe("snapshot matchers called after the runner gave up on the test", () => expect(snap).toBe(header + '\nexports[`second 1`] = `"from second"`;\n'); }); - test.concurrent("a test failed by an unhandled error while it was awaiting", async () => { + // The two cases below fail the running test with an unhandled error. They wait through a done + // callback rather than a returned promise: the runner gives up on a test that is only waiting for + // done() as soon as the error is reported (an awaited body is going to be waited for instead, + // see #36719), and that is the situation these cases are about. + test.concurrent("a test failed by an unhandled error while it was waiting for done()", async () => { // The only snapshot matcher in the file is the late one, so nothing at all should be written: // not even an empty snapshot file. const { stdout, stderr, snap } = await runTestFile(/* ts */ ` const secondStarted = Promise.withResolvers(); const firstDone = Promise.withResolvers(); - test("first", async () => { + test("first", done => { Promise.reject(new Error("failure in the background")); - await secondStarted.promise; - report("late after the rejection", () => expect("from first").toMatchSnapshot()); - firstDone.resolve(); + secondStarted.promise.then(() => { + report("late after the rejection", () => expect("from first").toMatchSnapshot()); + firstDone.resolve(); + done(); + }); }); test("second", async () => { secondStarted.resolve(); @@ -1118,14 +1124,15 @@ describe("snapshot matchers called after the runner gave up on the test", () => // Both attempts run the same inline matcher. On the previous behaviour the first attempt's late // call and the retry's call asked for different values on the same line, which fails the // writing of the file's inline snapshots as a whole ("Multiple inline snapshots on the same - // line must all have the same value"). + // line must all have the same value"). The first attempt never calls done(): the runner has + // given up on it, and only the retry's done() is meant to end the test. const { stdout, stderr, snap, testFile, testFileAfterwards } = await runTestFile(/* ts */ ` const retryStarted = Promise.withResolvers(); const firstAttemptDone = Promise.withResolvers(); let attempts = 0; test( "retried", - async () => { + done => { const attempt = ++attempts; // Block body: a matcher called in tail position gets located at the call to inline() instead. const inline = () => { @@ -1133,16 +1140,19 @@ describe("snapshot matchers called after the runner gave up on the test", () => }; if (attempt === 1) { Promise.reject(new Error("first attempt fails in the background")); - await retryStarted.promise; - report("late from the first attempt", () => expect("from attempt " + attempt).toMatchSnapshot()); - report("late inline from the first attempt", inline); - firstAttemptDone.resolve(); + retryStarted.promise.then(() => { + report("late from the first attempt", () => expect("from attempt " + attempt).toMatchSnapshot()); + report("late inline from the first attempt", inline); + firstAttemptDone.resolve(); + }); return; } retryStarted.resolve(); - await firstAttemptDone.promise; - expect("from attempt " + attempt).toMatchSnapshot(); - inline(); + firstAttemptDone.promise.then(() => { + expect("from attempt " + attempt).toMatchSnapshot(); + inline(); + done(); + }); }, { retry: 1 }, ); diff --git a/test/js/bun/test/test-on-test-finished.test.ts b/test/js/bun/test/test-on-test-finished.test.ts index de75e4734733..3bcc56d4a561 100644 --- a/test/js/bun/test/test-on-test-finished.test.ts +++ b/test/js/bun/test/test-on-test-finished.test.ts @@ -1,4 +1,5 @@ import { afterAll, afterEach, describe, expect, onTestFinished, test } from "bun:test"; +import { bunEnv, bunExe, tempDir } from "harness"; // Test the basic ordering of onTestFinished describe("onTestFinished ordering", () => { @@ -130,3 +131,56 @@ describe("onTestFinished with failing test", () => { expect(output).toEqual(["test", "onTestFinished"]); }); }); + +// A test the runner has given up on (here: it timed out) keeps running while the next test +// executes; hooks it registers from then on have no test to attach to and must be rejected rather +// than added to the test that happens to be running. +test("hooks registered by a test after the runner gave up on it are rejected", async () => { + using dir = tempDir("hooks-after-runner-moved-on", { + "late.test.ts": /* ts */ ` + import { afterAll, afterEach, onTestFinished, test } from "bun:test"; + const secondStarted = Promise.withResolvers(); + const firstDone = Promise.withResolvers(); + test("first", async () => { + await secondStarted.promise; + for (const [name, register] of [ + ["onTestFinished", onTestFinished], + ["afterEach", afterEach], + ["afterAll", afterAll], + ] as const) { + try { + register(() => console.log(name + " registered by first ran")); + console.log(name + ": registered"); + } catch (error) { + console.log(name + ": " + (error as Error).message); + } + } + firstDone.resolve(); + }, 1); + test("second", async () => { + secondStarted.resolve(); + await firstDone.promise; + }); + `, + }); + + await using proc = Bun.spawn({ + cmd: [bunExe(), "test", "late.test.ts"], + cwd: String(dir), + env: bunEnv, + stdout: "pipe", + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + + const rejected = (name: string) => + `${name}: Cannot call ${name}() here. The test or hook it was called from has already finished executing (it timed out, or failed while it was still running).`; + expect(stdout.replace(/^bun test v.*\n/, "")).toBe( + [rejected("onTestFinished"), rejected("afterEach"), rejected("afterAll"), ""].join("\n"), + ); + expect(stderr).toContain("this test timed out after 1ms"); + expect(stderr).toContain("(pass) second"); + expect(stderr).toContain(" 1 pass\n"); + expect(stderr).toContain(" 1 fail\n"); + expect(exitCode).toBe(1); +}); From 9364ef223ee8f4bdf5716061e96224125bd5ffb4 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sat, 15 Aug 2026 12:10:12 +0000 Subject: [PATCH 8/9] ci: retrigger From 25fd236e4fdb6adddc233e096533978965d44eae Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sat, 15 Aug 2026 12:39:01 +0000 Subject: [PATCH 9/9] event loop: remove run_callback_with_result_and_forcefully_drain_microtasks, its only caller was inlined --- src/jsc/event_loop.rs | 20 -------------------- 1 file changed, 20 deletions(-) diff --git a/src/jsc/event_loop.rs b/src/jsc/event_loop.rs index 4058f8e0b9b4..8a138a6be800 100644 --- a/src/jsc/event_loop.rs +++ b/src/jsc/event_loop.rs @@ -1138,26 +1138,6 @@ impl EventLoop { } } - /// Prefer `runCallbackWithResult` unless you really need to make sure that microtasks are drained. - pub fn run_callback_with_result_and_forcefully_drain_microtasks( - &mut self, - callback: JSValue, - global_object: &JSGlobalObject, - this_value: JSValue, - arguments: &[JSValue], - ) -> JsResult { - // Same gate as `run_callback`. - if global_object.has_exception() { - return Ok(JSValue::UNDEFINED); - } - let result = callback.call(global_object, this_value, arguments)?; - result.ensure_still_alive(); - let jsc_vm = global_object.bun_vm().jsc_vm(); - self.drain_microtasks_with_global(global_object, jsc_vm) - .map_err(|stopped| stopped.throw(global_object))?; - Ok(result) - } - /// Keep one poll registered with the loop so `us_loop_run_bun_tick` parks /// instead of returning immediately on `num_polls == 0`. #[cfg(not(windows))]