From 73cf39402c46e65bc3654a8f9b87ff412a80a9cf Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 29 Sep 2026 21:52:05 +0000 Subject: [PATCH 1/7] Add test probes for the console tables and for HashMap lookups consoleTableSizes() in bun:internal-for-testing returns the entry count and the slot count of the console.time table and of the console.count table. hashMapChurnProbe() drives a bun_collections::HashMap and counts the stored entries that a lookup of an absent key is compared against. The new tests pin what a program sees today: an ended timer prints nothing more, console.time starts it again, and console.countReset restarts a count. --- src/codegen/generate-js2native.ts | 2 + src/js/internal-for-testing.ts | 15 ++++ src/jsc/ConsoleObject.rs | 34 ++++++++- src/runtime/dispatch_js2native.rs | 1 + src/runtime/hash_map_testing.rs | 76 +++++++++++++++++++++ src/runtime/lib.rs | 1 + test/internal/hash-map.test.ts | 13 ++++ test/js/web/console/console-timeLog.test.ts | 58 ++++++++++++++++ 8 files changed, 199 insertions(+), 1 deletion(-) create mode 100644 src/runtime/hash_map_testing.rs create mode 100644 test/internal/hash-map.test.ts diff --git a/src/codegen/generate-js2native.ts b/src/codegen/generate-js2native.ts index 343b603abced..6b5d80cdcc75 100644 --- a/src/codegen/generate-js2native.ts +++ b/src/codegen/generate-js2native.ts @@ -46,6 +46,7 @@ const sourceFiles = readdirRecursiveWithExclusionsAndExtensionsSync( const rustIdentifierPaths: Record = { "bun.rs": "bun.rs", "ipc.rs": "runtime/ipc_host.rs", + "ConsoleObject.rs": "jsc/ConsoleObject.rs", "Counters.rs": "jsc/Counters.rs", "FrameworkRouter.rs": "runtime/bake/FrameworkRouter.rs", "JSBundler.rs": "runtime/api/JSBundler.rs", @@ -87,6 +88,7 @@ const rustIdentifierPaths: Record = { "patch.rs": "patch/patch.rs", "postgres.rs": "sql_jsc/postgres.rs", "runtime/dns_jsc/dns.rs": "runtime/dns_jsc/dns.rs", + "runtime/hash_map_testing.rs": "runtime/hash_map_testing.rs", "runtime/node/types.rs": "runtime/node/types.rs", "runtime/socket/socket.rs": "runtime/socket/socket.rs", "runtime/timer/Timer.rs": "runtime/timer/Timer.rs", diff --git a/src/js/internal-for-testing.ts b/src/js/internal-for-testing.ts index 79099c16ce05..1e240b3d6aee 100644 --- a/src/js/internal-for-testing.ts +++ b/src/js/internal-for-testing.ts @@ -573,6 +573,21 @@ export const linearFifoOrderedRemoveProbe = $newRustFunction( "TestingAPIs.orderedRemoveProbe", 1, ) as (scenario: number) => number[]; +/** Entries and slots of this thread's `console.time` table and of this VM's `console.count` table. */ +export const consoleTableSizes = $newRustFunction("ConsoleObject.rs", "tableSizesForTesting", 0) as () => { + timerEntries: number; + timerCapacity: number; + countEntries: number; + countCapacity: number; +}; +/** + * Keeps `live` keys in a `bun_collections::HashMap`, replaces the oldest with a new key `cycles` times, then looks + * up 1,000 absent keys. `maxComparisons` is the most stored entries one of those lookups was compared against. + */ +export const hashMapChurnProbe = $newRustFunction("runtime/hash_map_testing.rs", "churnProbe", 2) as ( + live: number, + cycles: number, +) => { capacity: number; length: number; maxComparisons: number }; export const hasNonReifiedStatic = $newCppFunction("InternalForTesting.cpp", "jsFunction_hasReifiedStatic", 1); interface setSocketOptionsFn { diff --git a/src/jsc/ConsoleObject.rs b/src/jsc/ConsoleObject.rs index 54c1e9bea13f..f457feb9fbe6 100644 --- a/src/jsc/ConsoleObject.rs +++ b/src/jsc/ConsoleObject.rs @@ -9,7 +9,7 @@ use core::ffi::c_void; use crate as jsc; use crate::virtual_machine::VirtualMachine; -use crate::{EventType, JSGlobalObject, JSPromise, JSValue, JsResult}; +use crate::{CallFrame, EventType, JSGlobalObject, JSPromise, JSValue, JsResult}; use bun_collections::HashMap; use bun_core::{EncodedSlice, String as BunString, strings}; use bun_core::{Output, StackCheck}; @@ -5919,6 +5919,38 @@ pub(crate) extern "C" fn Bun__ConsoleObject__timeLog( let _ = bun_io::Write::flush(&mut writer); } +/// `consoleTableSizes()` in `bun:internal-for-testing`: entries and slots of +/// this thread's `console.time` table and of this VM's `console.count` table. +pub fn table_sizes_for_testing(global: &JSGlobalObject, _frame: &CallFrame) -> JsResult { + let (timer_entries, timer_capacity) = + PENDING_TIME_LOGS.with_borrow(|map| (map.len(), map.capacity())); + // SAFETY: top-level JS-thread host call ⇒ exclusive access to the + // set-once `VirtualMachine.console` box. + let counts = unsafe { &vm_console_mut(global).counts }; + let sizes = JSValue::create_empty_object(global, 4); + sizes.put( + global, + b"timerEntries", + JSValue::js_number(timer_entries as f64), + ); + sizes.put( + global, + b"timerCapacity", + JSValue::js_number(timer_capacity as f64), + ); + sizes.put( + global, + b"countEntries", + JSValue::js_number(counts.len() as f64), + ); + sizes.put( + global, + b"countCapacity", + JSValue::js_number(counts.capacity() as f64), + ); + Ok(sizes) +} + /// Stamp out the empty `Bun__ConsoleObject__*` C-ABI hooks that JSC's /// `ConsoleClient` vtable requires but Bun leaves unimplemented. Two arms cover /// the two trailing-arg shapes the C++ side declares in diff --git a/src/runtime/dispatch_js2native.rs b/src/runtime/dispatch_js2native.rs index ad58e5a3d8d4..8f8caa08c777 100644 --- a/src/runtime/dispatch_js2native.rs +++ b/src/runtime/dispatch_js2native.rs @@ -36,6 +36,7 @@ pub(crate) use bun_install_jsc::ini_jsc::ini_testing_parse as ini_ini_ini_testin pub(crate) use bun_jsc::bindgen_test::get_bindgen_test_functions as jsc_bindgen_test_get_bindgen_test_functions; pub(crate) use bun_jsc::bytecode_order_recorder::names_for_testing as jsc_bytecode_order_recorder_names_for_testing; +pub(crate) use bun_jsc::console_object::table_sizes_for_testing as jsc_console_object_table_sizes_for_testing; pub(crate) use bun_jsc::counters::create_counters_object as jsc_counters_create_counters_object; pub(crate) use bun_jsc::event_loop::get_active_tasks as jsc_event_loop_get_active_tasks; pub(crate) use bun_jsc::virtual_machine_exports::Bun__setSyntheticAllocationLimitForTesting as jsc_virtual_machine_exports_bun__set_synthetic_allocation_limit_for_testing; diff --git a/src/runtime/hash_map_testing.rs b/src/runtime/hash_map_testing.rs new file mode 100644 index 000000000000..23d8c5581d06 --- /dev/null +++ b/src/runtime/hash_map_testing.rs @@ -0,0 +1,76 @@ +//! Test-only bridge exposing `bun_collections::HashMap` to +//! `bun:internal-for-testing` (see `src/js/internal-for-testing.ts`). +//! +//! The map has no JS-visible surface of its own, and the cost of a lookup +//! shows from JS only as time. This bridge counts it instead: its hash context +//! gives every key the same fingerprint, so the map calls `ctx_eql` once for +//! each stored entry a lookup walks past, and the context counts those calls. +//! +//! Lives in `bun_runtime` (not `bun_collections`) because it needs the JSC +//! types. + +use core::cell::Cell; + +use bun_collections::{HashContext, HashMap}; +use bun_jsc::{CallFrame, JSGlobalObject, JSValue, JsResult}; + +thread_local! { + static COMPARISONS: Cell = const { Cell::new(0) }; +} + +struct CountingContext; + +impl HashContext for CountingContext { + fn ctx_hash(key: &u64) -> u64 { + // The fingerprint is the top 7 bits of the hash: clear them. + bun_wyhash::auto_hash(key) >> 7 + } + fn ctx_eql(a: &u64, b: &u64) -> bool { + COMPARISONS.set(COMPARISONS.get() + 1); + a == b + } +} + +const MISSES: u64 = 1000; + +/// `hashMapChurnProbe(live, cycles)`: inserts the keys `0..live`, then +/// `cycles` times removes the oldest key and inserts the next integer, so the +/// map always holds `live` entries. Then looks up 1,000 keys that were never +/// inserted. Returns `{ capacity, length, maxComparisons }`, where +/// `maxComparisons` is the largest number of stored entries that one of those +/// lookups was compared against. +pub(crate) fn churn_probe(global: &JSGlobalObject, frame: &CallFrame) -> JsResult { + let live = frame.argument(0).to_int32().clamp(0, 1 << 20) as u64; + let cycles = frame.argument(1).to_int32().clamp(0, 1 << 24) as u64; + + let mut map: HashMap = HashMap::new(); + for key in 0..live { + map.insert(key, ()); + } + for cycle in 0..cycles { + map.remove(&cycle); + map.insert(live + cycle, ()); + } + + let mut max_comparisons = 0; + for miss in 0..MISSES { + COMPARISONS.set(0); + let found = map.contains_key(&(u64::MAX - miss)); + debug_assert!(!found); + max_comparisons = max_comparisons.max(COMPARISONS.get()); + } + + let result = JSValue::create_empty_object(global, 3); + result.put( + global, + b"capacity", + JSValue::js_number(map.capacity() as f64), + ); + result.put(global, b"length", JSValue::js_number(map.len() as f64)); + result.put( + global, + b"maxComparisons", + JSValue::js_number(f64::from(max_comparisons)), + ); + Ok(result) +} diff --git a/src/runtime/lib.rs b/src/runtime/lib.rs index 22f3000363af..4b9b9d4a9811 100644 --- a/src/runtime/lib.rs +++ b/src/runtime/lib.rs @@ -52,6 +52,7 @@ pub(crate) mod shell; #[path = "api.rs"] pub(crate) mod api; pub(crate) mod dispatch; +pub(crate) mod hash_map_testing; pub(crate) mod hw_exports; pub(crate) mod ipc; pub(crate) mod ipc_host; diff --git a/test/internal/hash-map.test.ts b/test/internal/hash-map.test.ts new file mode 100644 index 000000000000..b2fcfb928213 --- /dev/null +++ b/test/internal/hash-map.test.ts @@ -0,0 +1,13 @@ +/** + * `bun_collections::HashMap` (src/collections/zig_hash_map.rs) is an internal + * Rust map with no JS-visible surface of its own. From JS the length of a + * lookup shows only as time, so these tests count it: `hashMapChurnProbe` + * (src/runtime/hash_map_testing.rs, exposed via `bun:internal-for-testing`) + * returns how many stored entries a lookup of an absent key is compared against. + */ +import { hashMapChurnProbe } from "bun:internal-for-testing"; +import { expect, test } from "bun:test"; + +test("a lookup in a map that never removed an entry walks one short run", () => { + expect(hashMapChurnProbe(256, 0)).toEqual({ capacity: 512, length: 256, maxComparisons: 19 }); +}); diff --git a/test/js/web/console/console-timeLog.test.ts b/test/js/web/console/console-timeLog.test.ts index bf7ddc485e5b..febf6ef1a2be 100644 --- a/test/js/web/console/console-timeLog.test.ts +++ b/test/js/web/console/console-timeLog.test.ts @@ -1,6 +1,8 @@ import { file, spawn } from "bun"; +import { consoleTableSizes } from "bun:internal-for-testing"; import { expect, it } from "bun:test"; import { bunEnv, bunExe } from "harness"; +import { randomUUID } from "node:crypto"; import { join } from "node:path"; it.concurrent("console.timeEnd with empty label emits exactly one trailing newline", async () => { @@ -29,6 +31,62 @@ it.concurrent("console.timeEnd with non-empty label emits exactly one trailing n expect(exitCode).toBe(0); }); +it.concurrent("an ended timer and a reset count start again from nothing", async () => { + await using proc = Bun.spawn({ + cmd: [ + bunExe(), + "-e", + ` + console.time("a"); + console.timeEnd("a"); + console.error("ended:"); + console.timeEnd("a"); + console.timeLog("a", "x"); + console.error("started again:"); + console.time("a"); + console.timeLog("a", "y"); + console.timeEnd("a"); + + console.count("a"); + console.count("a"); + console.count("b"); + console.countReset("a"); + console.countReset("never counted"); + console.count("a"); + console.count("b"); + `, + ], + env: bunEnv, + stdout: "pipe", + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + expect(stderr.replace(/^\[[\d.]+[mnµ]?s\]/gm, "[time]")).toBe( + "[time] a\nended:\nstarted again:\n[time] a y\n[time] a\n", + ); + expect(stdout).toBe("a: 1\na: 2\nb: 1\na: 1\nb: 2\n"); + expect(exitCode).toBe(0); +}); + +it("consoleTableSizes() counts the running timers and the counted labels", () => { + // Labels that no earlier run of this test in this process has used. + const run = randomUUID(); + const before = consoleTableSizes(); + console.time(run + " a"); + console.time(run + " b"); + console.count(run + " c"); + const started = consoleTableSizes(); + console.timeEnd(run + " a"); + console.timeEnd(run + " b"); + console.countReset(run + " c"); + expect({ + timers: started.timerEntries - before.timerEntries, + counts: started.countEntries - before.countEntries, + }).toEqual({ timers: 2, counts: 1 }); + expect(started.timerCapacity).toBeGreaterThanOrEqual(started.timerEntries); + expect(started.countCapacity).toBeGreaterThanOrEqual(started.countEntries); +}); + it("should log to console correctly", async () => { const { stderr, exited } = spawn({ cmd: [bunExe(), join(import.meta.dir, "console-timeLog.js")], From d8689a00cef44b11eb707658cec399779a76067d Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 29 Sep 2026 23:42:06 +0000 Subject: [PATCH 2/7] collections: delete from HashMap by backward shift, leave no tombstone A removal wrote a tombstone and gave its capacity back, so tombstones never counted as load and nothing ever cleared them. A map that removed and inserted distinct keys ran out of free slots, and from then on each lookup of an absent key, and so each insert of a new key, read every slot of the table. remove_by_index now closes the gap (Knuth, TAOCP 6.4, Algorithm R): it walks the rest of the run and moves back each entry whose probe path crosses the hole. Every slot is free or used, so a probe ends at the first free slot and the tombstone bookkeeping in get_index and get_or_put_slot goes away. A map that never removes keeps its layout slot for slot. --- src/collections/lib.rs | 4 +- src/collections/zig_hash_map.rs | 301 +++++++++++++++++++++++++++----- test/internal/hash-map.test.ts | 4 + 3 files changed, 266 insertions(+), 43 deletions(-) diff --git a/src/collections/lib.rs b/src/collections/lib.rs index 57539df10913..37645c3f0803 100644 --- a/src/collections/lib.rs +++ b/src/collections/lib.rs @@ -440,8 +440,8 @@ impl SmallList { // ────────────────────────────────────────────────────────────────────────── // HashMap // -// Linear-probe layout (open-addressing, tombstones, power-of-two cap, -// 80% load) with deterministic iteration order — required by callers that +// Linear-probe layout (open-addressing, backward-shift delete, power-of-two +// cap, 80% load) with deterministic iteration order — required by callers that // snapshot the iteration sequence (lockfile debug stringify, etc.). The `Ctx` // type parameter is load-bearing: `AutoHashContext` wyhashes the key, // `IdentityContext` uses `k as u64` so pre-hashed keys aren't re-hashed. diff --git a/src/collections/zig_hash_map.rs b/src/collections/zig_hash_map.rs index f1e5fcc0cc7c..9435680abe84 100644 --- a/src/collections/zig_hash_map.rs +++ b/src/collections/zig_hash_map.rs @@ -1,7 +1,14 @@ -//! Open-addressing hash map — linear-probe, tombstone-on-delete, power-of-two -//! capacity, 80% max load. Layout (and therefore iteration order) is -//! load-bearing: callers snapshot the iteration sequence (e.g. lockfile debug -//! stringify). +//! Open-addressing hash map — linear-probe, backward-shift delete, +//! power-of-two capacity, 80% max load. The layout of a map that only inserts +//! (and therefore its iteration order) is load-bearing: callers snapshot the +//! iteration sequence (e.g. `bun.lock`, lockfile debug stringify). A removal +//! moves the later entries of its run back by one or more slots, so the order +//! after a removal is unspecified. +//! +//! A removal walks its run to the next free slot and hashes every key it +//! passes. Runs are short only when the hash spreads the keys: use +//! `IdentityContext` for keys that are hashes already, never for dense +//! integers. //! //! Storage is split: `Vec` for metadata + `Vec>` for //! slots. This costs an `Option` discriminant per slot but keeps the @@ -17,24 +24,11 @@ use crate::identity_context::{IdentityContext, IdentityHash}; // ─── Metadata byte ───────────────────────────────────────────────────────── // bit 7 = `used`, bits 0..7 = `fingerprint`. const SLOT_FREE: u8 = 0x00; // used=0, fp=0 -const SLOT_TOMBSTONE: u8 = 0x01; // used=0, fp=1 #[inline] fn meta_is_used(m: u8) -> bool { m & 0x80 != 0 } -#[inline] -fn meta_is_free(m: u8) -> bool { - m == SLOT_FREE -} -#[inline] -fn meta_is_tombstone(m: u8) -> bool { - m == SLOT_TOMBSTONE -} -#[inline] -fn meta_fingerprint(m: u8) -> u8 { - m & 0x7F -} /// Top 7 bits of the 64-bit hash. #[inline] fn take_fingerprint(hash: u64) -> u8 { @@ -101,7 +95,7 @@ pub struct HashMap { metadata: Vec, slots: Vec>, size: u32, - /// Slots writable before a grow (counts free *and* tombstone consumption). + /// Entries that fit before a grow. available: u32, _ctx: PhantomData, } @@ -298,7 +292,8 @@ impl> HashMap { self.size += 1; } - /// Probe for `key`, stop on free, skip tombstones. + /// Probe for `key`. A run of used slots always ends at a free one: the + /// table is never more than 80% full and a removal leaves no tombstone. fn get_index(&self, key: &Q) -> Option where K: Borrow, @@ -308,22 +303,19 @@ impl> HashMap { if self.size == 0 { return None; } - let cap = self.metadata.len(); let hash = C::ctx_hash(key); - let mask = cap - 1; - let fp = take_fingerprint(hash); - let mut limit = cap; + let mask = self.metadata.len() - 1; + let meta = meta_fill(take_fingerprint(hash)); let mut idx = (hash as usize) & mask; - while !meta_is_free(self.metadata[idx]) && limit != 0 { - if meta_is_used(self.metadata[idx]) && meta_fingerprint(self.metadata[idx]) == fp { + while meta_is_used(self.metadata[idx]) { + if self.metadata[idx] == meta { if let Some((k, _)) = &self.slots[idx] { if C::ctx_eql(key, k.borrow()) { return Some(idx); } } } - limit -= 1; idx = (idx + 1) & mask; } None @@ -381,33 +373,24 @@ impl> HashMap { fn get_or_put_slot(&mut self, key: &K) -> (usize, bool) { self.grow_if_needed(1); - let cap = self.metadata.len(); let hash = C::ctx_hash(key); - let mask = cap - 1; - let fp = take_fingerprint(hash); - let mut limit = cap; + let mask = self.metadata.len() - 1; + let meta = meta_fill(take_fingerprint(hash)); let mut idx = (hash as usize) & mask; - let mut first_tombstone_idx = cap; // invalid sentinel - while !meta_is_free(self.metadata[idx]) && limit != 0 { - if meta_is_used(self.metadata[idx]) && meta_fingerprint(self.metadata[idx]) == fp { + while meta_is_used(self.metadata[idx]) { + if self.metadata[idx] == meta { if let Some((k, _)) = &self.slots[idx] { if C::ctx_eql(key, k) { return (idx, true); } } - } else if first_tombstone_idx == cap && meta_is_tombstone(self.metadata[idx]) { - first_tombstone_idx = idx; } - limit -= 1; idx = (idx + 1) & mask; } - if first_tombstone_idx < cap { - idx = first_tombstone_idx; - } self.available -= 1; - self.metadata[idx] = meta_fill(fp); + self.metadata[idx] = meta; self.size += 1; (idx, false) } @@ -473,9 +456,25 @@ impl> HashMap { Ok(()) } + /// Takes the entry at `idx` and closes the gap (Knuth, TAOCP 6.4, + /// Algorithm R), so that no tombstone is left for later probes to walk + /// over. Each later entry of the run moves back into the hole when the + /// hole lies on its probe path, between its home slot and its own. fn remove_by_index(&mut self, idx: usize) -> Option<(K, V)> { - self.metadata[idx] = SLOT_TOMBSTONE; let kv = self.slots[idx].take(); + let mask = self.metadata.len() - 1; + let mut hole = idx; + let mut next = (idx + 1) & mask; + while let Some((key, _)) = &self.slots[next] { + let home = (C::ctx_hash(key) as usize) & mask; + if (hole.wrapping_sub(home) & mask) < (next.wrapping_sub(home) & mask) { + self.metadata[hole] = self.metadata[next]; + self.slots[hole] = self.slots[next].take(); + hole = next; + } + next = (next + 1) & mask; + } + self.metadata[hole] = SLOT_FREE; self.size -= 1; self.available += 1; kv @@ -694,3 +693,223 @@ impl<'a, K, V, C: HashContext> VacantEntry<'a, K, V, C> { &mut self.map.slots[idx].as_mut().unwrap().1 } } + +#[cfg(test)] +mod tests { + use super::*; + + /// Five home slots for every key: long runs in a small table. + struct FiveHomes; + impl HashContext for FiveHomes { + fn ctx_hash(key: &u64) -> u64 { + (key % 5) | (key << 57) + } + fn ctx_eql(a: &u64, b: &u64) -> bool { + a == b + } + } + + /// Home slots at the end of the table: every run wraps around to slot 0. + struct LastSlots; + impl HashContext for LastSlots { + fn ctx_hash(key: &u64) -> u64 { + u64::MAX - (key % 3) + } + fn ctx_eql(a: &u64, b: &u64) -> bool { + a == b + } + } + + fn xorshift(state: &mut u64) -> u64 { + *state ^= *state >> 12; + *state ^= *state << 25; + *state ^= *state >> 27; + state.wrapping_mul(0x2545_F491_4F6C_DD1D) + } + + fn slot_keys(map: &HashMap, slots: usize) -> Vec> { + map.slots[..slots] + .iter() + .map(|slot| slot.map(|kv| kv.0)) + .collect() + } + + /// What a probe relies on: each entry is reachable from its home slot + /// without crossing a free slot, and each slot without an entry is free. + /// `model[key]` is the value the map must hold for `key`. + fn check>(map: &HashMap, model: &[Option]) { + let expected = model.iter().flatten().count(); + assert_eq!(map.len(), expected); + let cap = map.metadata.len(); + if cap == 0 { + return; + } + let mask = cap - 1; + let mut used = 0; + for i in 0..cap { + let Some((key, value)) = map.slots[i] else { + assert_eq!(map.metadata[i], SLOT_FREE, "slot {i} holds no entry"); + continue; + }; + used += 1; + assert_eq!(model[key as usize], Some(value)); + let hash = C::ctx_hash(&key); + assert_eq!(map.metadata[i], meta_fill(take_fingerprint(hash))); + let mut j = (hash as usize) & mask; + while j != i { + assert!( + meta_is_used(map.metadata[j]), + "key {key} in slot {i}: slot {j} on its probe path is free" + ); + j = (j + 1) & mask; + } + } + assert_eq!(used, expected); + assert_eq!(map.available as usize, cap * 80 / 100 - used); + } + + fn run_against_model>(seed: u64, key_space: usize, operations: usize) { + let mut state = seed | 1; + let mut map: HashMap = HashMap::new(); + let mut model: Vec> = vec![None; key_space]; + for _ in 0..operations { + let key = xorshift(&mut state) % key_space as u64; + let value = xorshift(&mut state); + let slot = &mut model[key as usize]; + match xorshift(&mut state) % 100 { + 0..=29 => assert_eq!(map.insert(key, value), slot.replace(value)), + 30..=39 => { + let entry = map.get_or_put(key).unwrap(); + assert_eq!(entry.found_existing, slot.is_some()); + *entry.value_ptr = value; + *slot = Some(value); + } + 40..=44 => { + let got = *map.entry(key).or_insert_with(|| value); + assert_eq!(got, *slot.get_or_insert(value)); + } + 45..=79 => assert_eq!(map.remove(&key), slot.take()), + 80..=84 => { + let got = map.fetch_remove(&key).map(|kv| (kv.key, kv.value)); + assert_eq!(got, slot.take().map(|value| (key, value))); + } + 85..=94 => assert_eq!(map.get(&key), slot.as_ref()), + 95..=96 => map.reserve((value % 40) as usize), + 97 => { + // Empty the map in key order: the first entry of each run goes first. + for (key, slot) in model.iter_mut().enumerate() { + assert_eq!(map.remove(&(key as u64)), slot.take()); + } + } + _ => { + if value % 8 == 0 { + map.clear(); + model.fill(None); + } + } + } + check(&map, &model); + } + } + + // CI runs these under Miri, which interprets each statement: keep its share small. + const OPERATIONS: usize = if cfg!(miri) { 150 } else { 20_000 }; + + #[test] + fn agrees_with_a_model_wyhash() { + run_against_model::(1, 48, OPERATIONS); + } + + #[test] + fn agrees_with_a_model_identity_hash() { + run_against_model::>(2, 40, OPERATIONS); + } + + #[test] + fn agrees_with_a_model_long_runs() { + run_against_model::(3, 60, OPERATIONS); + } + + #[test] + fn agrees_with_a_model_runs_that_wrap() { + run_against_model::(4, 40, OPERATIONS); + } + + #[test] + fn insert_only_order_wyhash() { + let mut map: HashMap = HashMap::new(); + for key in 0..20 { + map.insert(key, ()); + } + let order: Vec = map.keys().copied().collect(); + assert_eq!( + order, + [ + 0, 15, 13, 19, 11, 9, 7, 5, 18, 3, 1, 16, 14, 12, 10, 8, 6, 4, 2, 17 + ] + ); + } + + #[test] + fn insert_only_order_identity_hash() { + // The slot is `key & 7`: 17, 9, 1 and 33 start at slot 1, 2 and 10 at slot 2. + let mut map: HashMap> = HashMap::new(); + for key in [17, 9, 1, 33, 2, 10] { + map.insert(key, ()); + } + let order: Vec = map.keys().copied().collect(); + assert_eq!(order, [17, 9, 1, 33, 2, 10]); + } + + #[test] + fn removal_moves_back_the_entries_that_probed_past_it() { + // 0, 5, 10, 15 share home slot 0 and fill slots 0..=3. 1 has home slot 1 and lands in slot 4. + let mut map: HashMap = HashMap::new(); + for key in [0, 5, 10, 15, 1] { + map.insert(key, key); + } + assert_eq!(map.remove(&5), Some(5)); + assert_eq!( + slot_keys(&map, 5), + [Some(0), Some(10), Some(15), Some(1), None] + ); + assert_eq!(map.metadata[4], SLOT_FREE); + for key in [0, 10, 15, 1] { + assert_eq!(map.get(&key), Some(&key)); + } + assert_eq!(map.get(&5), None); + } + + #[test] + fn removal_leaves_an_entry_in_its_home_slot() { + // 0 and 5 share home slot 0 and fill slots 0 and 1. 2 sits in its home slot 2. + let mut map: HashMap = HashMap::new(); + for key in [0, 5, 2] { + map.insert(key, key); + } + assert_eq!(map.remove(&0), Some(0)); + assert_eq!(slot_keys(&map, 3), [Some(5), None, Some(2)]); + } + + #[test] + fn a_churn_of_distinct_keys_leaves_free_slots() { + const LIVE: u64 = 64; + const CYCLES: u64 = if cfg!(miri) { 300 } else { 50_000 }; + let mut map: HashMap = HashMap::new(); + for key in 0..LIVE { + map.insert(key, ()); + } + for cycle in 0..CYCLES { + assert_eq!(map.remove(&cycle), Some(())); + map.insert(LIVE + cycle, ()); + } + assert_eq!(map.len(), LIVE as usize); + assert_eq!(map.capacity(), 128); + let free = map + .metadata + .iter() + .filter(|&&meta| meta == SLOT_FREE) + .count(); + assert_eq!(free, 128 - LIVE as usize); + } +} diff --git a/test/internal/hash-map.test.ts b/test/internal/hash-map.test.ts index b2fcfb928213..a270bd4f4331 100644 --- a/test/internal/hash-map.test.ts +++ b/test/internal/hash-map.test.ts @@ -11,3 +11,7 @@ import { expect, test } from "bun:test"; test("a lookup in a map that never removed an entry walks one short run", () => { expect(hashMapChurnProbe(256, 0)).toEqual({ capacity: 512, length: 256, maxComparisons: 19 }); }); + +test("a lookup still walks one short run after 2,000 removals", () => { + expect(hashMapChurnProbe(256, 2000)).toEqual({ capacity: 512, length: 256, maxComparisons: 19 }); +}); From c85065a77bfee128612ace3a3ee63fde6f15e245 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 29 Sep 2026 23:52:40 +0000 Subject: [PATCH 3/7] console: timeEnd and countReset remove their table entry console.timeEnd emptied the value of its entry and kept the key, and console.countReset set the count to 0 and kept the key, so each distinct label held a slot of the table for the life of the thread. A process that times each request under a label with an id in it grew without bound, and each doubling of the table was a pause inside one console.time call. Both now remove the entry. The table holds the running timers and the live counts only. What a program prints does not change. --- src/jsc/ConsoleObject.rs | 15 ++++++--------- test/js/web/console/console-timeLog.test.ts | 16 ++++++++++++++++ 2 files changed, 22 insertions(+), 9 deletions(-) diff --git a/src/jsc/ConsoleObject.rs b/src/jsc/ConsoleObject.rs index f457feb9fbe6..1eea6e8b5c87 100644 --- a/src/jsc/ConsoleObject.rs +++ b/src/jsc/ConsoleObject.rs @@ -5790,12 +5790,12 @@ pub(crate) extern "C" fn Bun__ConsoleObject__countReset( // SAFETY: caller passes a valid (ptr, len) pair. let slice = unsafe { bun_core::ffi::slice(ptr, len) }; let hash = bun_wyhash::hash(slice); - // we don't delete it because deleting is implemented via tombstoning - if let Some(v) = this.counts.get_mut(&hash) { - *v = 0; - } + this.counts.remove(&hash); } +/// The timers that `console.time` started and `console.timeEnd` has not ended. +/// The value is an `Option` only because `get_or_put` needs a `Default`: an +/// entry always holds `Some`. type PendingTimers = bun_collections::HashMap>; thread_local! { static PENDING_TIME_LOGS: RefCell = RefCell::new(PendingTimers::default()); @@ -5819,7 +5819,7 @@ pub(crate) extern "C" fn Bun__ConsoleObject__time( PENDING_TIME_LOGS.with_borrow_mut(|map| { let result = map.get_or_put(id).expect("unreachable"); - if !result.found_existing || result.value_ptr.is_none() { + if !result.found_existing { *result.value_ptr = Some(bun_core::time::Timer::start()); } }); @@ -5840,12 +5840,9 @@ pub(crate) extern "C" fn Bun__ConsoleObject__timeEnd( // SAFETY: caller passes a valid (ptr, len) pair. let slice = unsafe { bun_core::ffi::slice(chars, len) }; let id = bun_wyhash::hash(slice); - // Replace the slot with `None`, returning the previous value. - let Some(prev) = PENDING_TIME_LOGS.with_borrow_mut(|m| m.get_mut(&id).map(|slot| slot.take())) - else { + let Some(Some(value)) = PENDING_TIME_LOGS.with_borrow_mut(|m| m.remove(&id)) else { return; }; - let Some(value) = prev else { return }; // get the duration in microseconds, then display it in milliseconds Output::print_elapsed( (value.read() / bun_core::time::NS_PER_US) as f64 / bun_core::time::US_PER_MS as f64, diff --git a/test/js/web/console/console-timeLog.test.ts b/test/js/web/console/console-timeLog.test.ts index febf6ef1a2be..d5e14ff31d7f 100644 --- a/test/js/web/console/console-timeLog.test.ts +++ b/test/js/web/console/console-timeLog.test.ts @@ -87,6 +87,22 @@ it("consoleTableSizes() counts the running timers and the counted labels", () => expect(started.countCapacity).toBeGreaterThanOrEqual(started.countEntries); }); +it("console.timeEnd and console.countReset give their table entry back", () => { + // Use both tables once, so that the loop is not what allocates them. + console.time("given back"); + console.timeEnd("given back"); + console.count("given back"); + console.countReset("given back"); + const before = consoleTableSizes(); + for (let i = 0; i < 20; i++) { + console.time("timer " + i); + console.timeEnd("timer " + i); + console.count("count " + i); + console.countReset("count " + i); + } + expect(consoleTableSizes()).toEqual(before); +}); + it("should log to console correctly", async () => { const { stderr, exited } = spawn({ cmd: [bunExe(), join(import.meta.dir, "console-timeLog.js")], From bbdbbaa6659cfa7d9d6af74c48b1291de7b90006 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Wed, 30 Sep 2026 05:43:52 +0000 Subject: [PATCH 4/7] hash map probe: coerce the arguments, count in u64, skip the churn with no live key hashMapChurnProbe read its arguments with to_int32, which asserts on a value that is not a number. It now coerces them and can throw. The comparison counter is a u64, so no accepted cycle count overflows it. With live = 0 the loop had no key to remove and only inserted, so the map grew to `cycles` entries. It now does nothing in that case. --- src/runtime/hash_map_testing.rs | 25 ++++++++++++++----------- test/internal/hash-map.test.ts | 4 ++++ 2 files changed, 18 insertions(+), 11 deletions(-) diff --git a/src/runtime/hash_map_testing.rs b/src/runtime/hash_map_testing.rs index 23d8c5581d06..6ee52ca7a6c8 100644 --- a/src/runtime/hash_map_testing.rs +++ b/src/runtime/hash_map_testing.rs @@ -15,7 +15,7 @@ use bun_collections::{HashContext, HashMap}; use bun_jsc::{CallFrame, JSGlobalObject, JSValue, JsResult}; thread_local! { - static COMPARISONS: Cell = const { Cell::new(0) }; + static COMPARISONS: Cell = const { Cell::new(0) }; } struct CountingContext; @@ -35,21 +35,24 @@ const MISSES: u64 = 1000; /// `hashMapChurnProbe(live, cycles)`: inserts the keys `0..live`, then /// `cycles` times removes the oldest key and inserts the next integer, so the -/// map always holds `live` entries. Then looks up 1,000 keys that were never -/// inserted. Returns `{ capacity, length, maxComparisons }`, where -/// `maxComparisons` is the largest number of stored entries that one of those -/// lookups was compared against. +/// map always holds `live` entries. With no live key there is nothing to +/// replace. Then looks up 1,000 keys that were never inserted. Returns +/// `{ capacity, length, maxComparisons }`, where `maxComparisons` is the +/// largest number of stored entries that one of those lookups was compared +/// against. pub(crate) fn churn_probe(global: &JSGlobalObject, frame: &CallFrame) -> JsResult { - let live = frame.argument(0).to_int32().clamp(0, 1 << 20) as u64; - let cycles = frame.argument(1).to_int32().clamp(0, 1 << 24) as u64; + let live = frame.argument(0).coerce_to_i32(global)?.clamp(0, 1 << 20) as u64; + let cycles = frame.argument(1).coerce_to_i32(global)?.clamp(0, 1 << 24) as u64; let mut map: HashMap = HashMap::new(); for key in 0..live { map.insert(key, ()); } - for cycle in 0..cycles { - map.remove(&cycle); - map.insert(live + cycle, ()); + if live > 0 { + for cycle in 0..cycles { + map.remove(&cycle); + map.insert(live + cycle, ()); + } } let mut max_comparisons = 0; @@ -70,7 +73,7 @@ pub(crate) fn churn_probe(global: &JSGlobalObject, frame: &CallFrame) -> JsResul result.put( global, b"maxComparisons", - JSValue::js_number(f64::from(max_comparisons)), + JSValue::js_number(max_comparisons as f64), ); Ok(result) } diff --git a/test/internal/hash-map.test.ts b/test/internal/hash-map.test.ts index a270bd4f4331..78596afa0629 100644 --- a/test/internal/hash-map.test.ts +++ b/test/internal/hash-map.test.ts @@ -15,3 +15,7 @@ test("a lookup in a map that never removed an entry walks one short run", () => test("a lookup still walks one short run after 2,000 removals", () => { expect(hashMapChurnProbe(256, 2000)).toEqual({ capacity: 512, length: 256, maxComparisons: 19 }); }); + +test("the probe churns nothing when no key is live", () => { + expect(hashMapChurnProbe(0, 1000)).toEqual({ capacity: 0, length: 0, maxComparisons: 0 }); +}); From c488d7c9a3c8c7b0565111a3acb931817cef48aa Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Wed, 30 Sep 2026 06:00:51 +0000 Subject: [PATCH 5/7] Shorten the comments of the map delete and of the test probes --- src/collections/zig_hash_map.rs | 29 +++++++++-------------------- src/js/internal-for-testing.ts | 6 +----- src/jsc/ConsoleObject.rs | 7 ++----- src/runtime/hash_map_testing.rs | 20 +++----------------- 4 files changed, 15 insertions(+), 47 deletions(-) diff --git a/src/collections/zig_hash_map.rs b/src/collections/zig_hash_map.rs index 9435680abe84..374a1883ec89 100644 --- a/src/collections/zig_hash_map.rs +++ b/src/collections/zig_hash_map.rs @@ -1,14 +1,8 @@ -//! Open-addressing hash map — linear-probe, backward-shift delete, -//! power-of-two capacity, 80% max load. The layout of a map that only inserts -//! (and therefore its iteration order) is load-bearing: callers snapshot the -//! iteration sequence (e.g. `bun.lock`, lockfile debug stringify). A removal -//! moves the later entries of its run back by one or more slots, so the order -//! after a removal is unspecified. -//! -//! A removal walks its run to the next free slot and hashes every key it -//! passes. Runs are short only when the hash spreads the keys: use -//! `IdentityContext` for keys that are hashes already, never for dense -//! integers. +//! Open-addressing hash map — linear-probe, backward-shift delete, power-of-two +//! capacity, 80% max load. The layout of a map that only inserts (and +//! therefore its iteration order) is load-bearing: callers snapshot the +//! iteration sequence (e.g. lockfile debug stringify). A removal walks and +//! reorders its run, so `IdentityContext` is only for keys that are hashes. //! //! Storage is split: `Vec` for metadata + `Vec>` for //! slots. This costs an `Option` discriminant per slot but keeps the @@ -292,8 +286,7 @@ impl> HashMap { self.size += 1; } - /// Probe for `key`. A run of used slots always ends at a free one: the - /// table is never more than 80% full and a removal leaves no tombstone. + /// Probe for `key`, stop on free. A run always ends at a free slot. fn get_index(&self, key: &Q) -> Option where K: Borrow, @@ -456,10 +449,7 @@ impl> HashMap { Ok(()) } - /// Takes the entry at `idx` and closes the gap (Knuth, TAOCP 6.4, - /// Algorithm R), so that no tombstone is left for later probes to walk - /// over. Each later entry of the run moves back into the hole when the - /// hole lies on its probe path, between its home slot and its own. + /// Backward-shift delete (Knuth, TAOCP 6.4, Algorithm R): leaves no tombstone. fn remove_by_index(&mut self, idx: usize) -> Option<(K, V)> { let kv = self.slots[idx].take(); let mask = self.metadata.len() - 1; @@ -467,6 +457,7 @@ impl> HashMap { let mut next = (idx + 1) & mask; while let Some((key, _)) = &self.slots[next] { let home = (C::ctx_hash(key) as usize) & mask; + // Move `next` into the hole only if the hole is on its probe path. if (hole.wrapping_sub(home) & mask) < (next.wrapping_sub(home) & mask) { self.metadata[hole] = self.metadata[next]; self.slots[hole] = self.slots[next].take(); @@ -734,9 +725,7 @@ mod tests { .collect() } - /// What a probe relies on: each entry is reachable from its home slot - /// without crossing a free slot, and each slot without an entry is free. - /// `model[key]` is the value the map must hold for `key`. + /// Each entry is reachable from its home slot, and every other slot is free. fn check>(map: &HashMap, model: &[Option]) { let expected = model.iter().flatten().count(); assert_eq!(map.len(), expected); diff --git a/src/js/internal-for-testing.ts b/src/js/internal-for-testing.ts index 1e240b3d6aee..f518b48026a5 100644 --- a/src/js/internal-for-testing.ts +++ b/src/js/internal-for-testing.ts @@ -573,17 +573,13 @@ export const linearFifoOrderedRemoveProbe = $newRustFunction( "TestingAPIs.orderedRemoveProbe", 1, ) as (scenario: number) => number[]; -/** Entries and slots of this thread's `console.time` table and of this VM's `console.count` table. */ export const consoleTableSizes = $newRustFunction("ConsoleObject.rs", "tableSizesForTesting", 0) as () => { timerEntries: number; timerCapacity: number; countEntries: number; countCapacity: number; }; -/** - * Keeps `live` keys in a `bun_collections::HashMap`, replaces the oldest with a new key `cycles` times, then looks - * up 1,000 absent keys. `maxComparisons` is the most stored entries one of those lookups was compared against. - */ +/** `maxComparisons`: the most stored entries that a lookup of an absent key is compared against. */ export const hashMapChurnProbe = $newRustFunction("runtime/hash_map_testing.rs", "churnProbe", 2) as ( live: number, cycles: number, diff --git a/src/jsc/ConsoleObject.rs b/src/jsc/ConsoleObject.rs index 1eea6e8b5c87..34cc0ee3ae5b 100644 --- a/src/jsc/ConsoleObject.rs +++ b/src/jsc/ConsoleObject.rs @@ -5793,9 +5793,7 @@ pub(crate) extern "C" fn Bun__ConsoleObject__countReset( this.counts.remove(&hash); } -/// The timers that `console.time` started and `console.timeEnd` has not ended. -/// The value is an `Option` only because `get_or_put` needs a `Default`: an -/// entry always holds `Some`. +/// `Option` only because `get_or_put` needs `Default`: an entry always holds `Some`. type PendingTimers = bun_collections::HashMap>; thread_local! { static PENDING_TIME_LOGS: RefCell = RefCell::new(PendingTimers::default()); @@ -5916,8 +5914,7 @@ pub(crate) extern "C" fn Bun__ConsoleObject__timeLog( let _ = bun_io::Write::flush(&mut writer); } -/// `consoleTableSizes()` in `bun:internal-for-testing`: entries and slots of -/// this thread's `console.time` table and of this VM's `console.count` table. +/// `consoleTableSizes()` in `bun:internal-for-testing`. pub fn table_sizes_for_testing(global: &JSGlobalObject, _frame: &CallFrame) -> JsResult { let (timer_entries, timer_capacity) = PENDING_TIME_LOGS.with_borrow(|map| (map.len(), map.capacity())); diff --git a/src/runtime/hash_map_testing.rs b/src/runtime/hash_map_testing.rs index 6ee52ca7a6c8..2e2d28fa4157 100644 --- a/src/runtime/hash_map_testing.rs +++ b/src/runtime/hash_map_testing.rs @@ -1,13 +1,4 @@ -//! Test-only bridge exposing `bun_collections::HashMap` to -//! `bun:internal-for-testing` (see `src/js/internal-for-testing.ts`). -//! -//! The map has no JS-visible surface of its own, and the cost of a lookup -//! shows from JS only as time. This bridge counts it instead: its hash context -//! gives every key the same fingerprint, so the map calls `ctx_eql` once for -//! each stored entry a lookup walks past, and the context counts those calls. -//! -//! Lives in `bun_runtime` (not `bun_collections`) because it needs the JSC -//! types. +//! `hashMapChurnProbe` in `bun:internal-for-testing` (in `bun_runtime` for the JSC types). use core::cell::Cell; @@ -18,6 +9,7 @@ thread_local! { static COMPARISONS: Cell = const { Cell::new(0) }; } +/// Gives every key one fingerprint, so `ctx_eql` runs for each stored entry a lookup passes. struct CountingContext; impl HashContext for CountingContext { @@ -33,13 +25,7 @@ impl HashContext for CountingContext { const MISSES: u64 = 1000; -/// `hashMapChurnProbe(live, cycles)`: inserts the keys `0..live`, then -/// `cycles` times removes the oldest key and inserts the next integer, so the -/// map always holds `live` entries. With no live key there is nothing to -/// replace. Then looks up 1,000 keys that were never inserted. Returns -/// `{ capacity, length, maxComparisons }`, where `maxComparisons` is the -/// largest number of stored entries that one of those lookups was compared -/// against. +/// Keeps `live` keys, replaces the oldest `cycles` times, then looks up 1,000 absent keys. pub(crate) fn churn_probe(global: &JSGlobalObject, frame: &CallFrame) -> JsResult { let live = frame.argument(0).coerce_to_i32(global)?.clamp(0, 1 << 20) as u64; let cycles = frame.argument(1).coerce_to_i32(global)?.clamp(0, 1 << 24) as u64; From ea0f7dbff8df2ffd492efbe62c84c55eb724b5f8 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 1 Oct 2026 04:46:54 +0000 Subject: [PATCH 6/7] map tests and probes: pin the insert-only order across two grows, bound the probe counts - zig_hash_map tests: one order test with the identity hash that crosses two grows replaces the two order tests. Remove the model test with the identity hash: none of its removals moved an entry. Under Miri, check the layout on every eighth operation. - hashMapChurnProbe: clamp the arguments as numbers, so a value above 2^31 no longer wraps to 0. - consoleTableSizes: read `counts` through a shared borrow. - hash-map.test.ts: bound `maxComparisons`. The exact value depends on the integer hash. - File header: a run stays short only when the hash spreads the keys. --- src/collections/zig_hash_map.rs | 42 ++++++++++----------------------- src/jsc/ConsoleObject.rs | 5 ++-- src/runtime/hash_map_testing.rs | 8 +++++-- test/internal/hash-map.test.ts | 9 +++++-- 4 files changed, 28 insertions(+), 36 deletions(-) diff --git a/src/collections/zig_hash_map.rs b/src/collections/zig_hash_map.rs index 374a1883ec89..10cc65b839dd 100644 --- a/src/collections/zig_hash_map.rs +++ b/src/collections/zig_hash_map.rs @@ -2,7 +2,7 @@ //! capacity, 80% max load. The layout of a map that only inserts (and //! therefore its iteration order) is load-bearing: callers snapshot the //! iteration sequence (e.g. lockfile debug stringify). A removal walks and -//! reorders its run, so `IdentityContext` is only for keys that are hashes. +//! reorders its run, which stays short only when the hash spreads the keys. //! //! Storage is split: `Vec` for metadata + `Vec>` for //! slots. This costs an `Option` discriminant per slot but keeps the @@ -761,7 +761,7 @@ mod tests { let mut state = seed | 1; let mut map: HashMap = HashMap::new(); let mut model: Vec> = vec![None; key_space]; - for _ in 0..operations { + for op in 0..operations { let key = xorshift(&mut state) % key_space as u64; let value = xorshift(&mut state); let slot = &mut model[key as usize]; @@ -791,17 +791,20 @@ mod tests { } } _ => { - if value % 8 == 0 { + if value.is_multiple_of(8) { map.clear(); model.fill(None); } } } - check(&map, &model); + if !cfg!(miri) || op % 8 == 7 { + check(&map, &model); + } } + check(&map, &model); } - // CI runs these under Miri, which interprets each statement: keep its share small. + // CI runs these under Miri, which interprets each statement: fewer operations and checks there. const OPERATIONS: usize = if cfg!(miri) { 150 } else { 20_000 }; #[test] @@ -809,11 +812,6 @@ mod tests { run_against_model::(1, 48, OPERATIONS); } - #[test] - fn agrees_with_a_model_identity_hash() { - run_against_model::>(2, 40, OPERATIONS); - } - #[test] fn agrees_with_a_model_long_runs() { run_against_model::(3, 60, OPERATIONS); @@ -825,29 +823,15 @@ mod tests { } #[test] - fn insert_only_order_wyhash() { - let mut map: HashMap = HashMap::new(); - for key in 0..20 { - map.insert(key, ()); - } - let order: Vec = map.keys().copied().collect(); - assert_eq!( - order, - [ - 0, 15, 13, 19, 11, 9, 7, 5, 18, 3, 1, 16, 14, 12, 10, 8, 6, 4, 2, 17 - ] - ); - } - - #[test] - fn insert_only_order_identity_hash() { - // The slot is `key & 7`: 17, 9, 1 and 33 start at slot 1, 2 and 10 at slot 2. + fn insert_only_order_is_fixed() { + // The slot is `key & mask`, so the order shows where collisions and the two grows put each key. let mut map: HashMap> = HashMap::new(); - for key in [17, 9, 1, 33, 2, 10] { + for key in [17, 9, 1, 33, 2, 10, 49, 3, 25, 41, 57, 18, 26, 11] { map.insert(key, ()); } + assert_eq!(map.capacity(), 32); let order: Vec = map.keys().copied().collect(); - assert_eq!(order, [17, 9, 1, 33, 2, 10]); + assert_eq!(order, [1, 33, 2, 3, 9, 10, 41, 11, 17, 49, 18, 25, 57, 26]); } #[test] diff --git a/src/jsc/ConsoleObject.rs b/src/jsc/ConsoleObject.rs index 34cc0ee3ae5b..a6a465c6e64c 100644 --- a/src/jsc/ConsoleObject.rs +++ b/src/jsc/ConsoleObject.rs @@ -5918,9 +5918,8 @@ pub(crate) extern "C" fn Bun__ConsoleObject__timeLog( pub fn table_sizes_for_testing(global: &JSGlobalObject, _frame: &CallFrame) -> JsResult { let (timer_entries, timer_capacity) = PENDING_TIME_LOGS.with_borrow(|map| (map.len(), map.capacity())); - // SAFETY: top-level JS-thread host call ⇒ exclusive access to the - // set-once `VirtualMachine.console` box. - let counts = unsafe { &vm_console_mut(global).counts }; + // SAFETY: see [`vm_console`]. Nothing writes `counts` during this JS-thread read. + let counts = unsafe { &(*vm_console(global)).counts }; let sizes = JSValue::create_empty_object(global, 4); sizes.put( global, diff --git a/src/runtime/hash_map_testing.rs b/src/runtime/hash_map_testing.rs index 2e2d28fa4157..3ab86fb5858c 100644 --- a/src/runtime/hash_map_testing.rs +++ b/src/runtime/hash_map_testing.rs @@ -25,10 +25,14 @@ impl HashContext for CountingContext { const MISSES: u64 = 1000; +fn count_argument(global: &JSGlobalObject, value: JSValue, max: u32) -> JsResult { + Ok(value.to_number(global)?.clamp(0.0, f64::from(max)) as u64) +} + /// Keeps `live` keys, replaces the oldest `cycles` times, then looks up 1,000 absent keys. pub(crate) fn churn_probe(global: &JSGlobalObject, frame: &CallFrame) -> JsResult { - let live = frame.argument(0).coerce_to_i32(global)?.clamp(0, 1 << 20) as u64; - let cycles = frame.argument(1).coerce_to_i32(global)?.clamp(0, 1 << 24) as u64; + let live = count_argument(global, frame.argument(0), 1 << 20)?; + let cycles = count_argument(global, frame.argument(1), 1 << 24)?; let mut map: HashMap = HashMap::new(); for key in 0..live { diff --git a/test/internal/hash-map.test.ts b/test/internal/hash-map.test.ts index 78596afa0629..ca0ab9708dcc 100644 --- a/test/internal/hash-map.test.ts +++ b/test/internal/hash-map.test.ts @@ -8,12 +8,17 @@ import { hashMapChurnProbe } from "bun:internal-for-testing"; import { expect, test } from "bun:test"; +// The exact count depends on the integer hash, so these bound it. A delete that leaves tombstones gives `length` after the churn. test("a lookup in a map that never removed an entry walks one short run", () => { - expect(hashMapChurnProbe(256, 0)).toEqual({ capacity: 512, length: 256, maxComparisons: 19 }); + const { maxComparisons, ...size } = hashMapChurnProbe(256, 0); + expect(size).toEqual({ capacity: 512, length: 256 }); + expect(maxComparisons).toBeLessThanOrEqual(32); }); test("a lookup still walks one short run after 2,000 removals", () => { - expect(hashMapChurnProbe(256, 2000)).toEqual({ capacity: 512, length: 256, maxComparisons: 19 }); + const { maxComparisons, ...size } = hashMapChurnProbe(256, 2000); + expect(size).toEqual({ capacity: 512, length: 256 }); + expect(maxComparisons).toBeLessThanOrEqual(32); }); test("the probe churns nothing when no key is live", () => { From e90e8e65d1e95637c847e8eec3e3943211a2d4a4 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Mon, 26 Oct 2026 20:01:50 +0000 Subject: [PATCH 7/7] bun-types test: list the two new bindgen schemas `ConsoleObject.bind.ts` and `hash_map_testing.bind.ts` hold test probes only, so the published types call them nothing. --- test/integration/bun-types/bun-types.test.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/test/integration/bun-types/bun-types.test.ts b/test/integration/bun-types/bun-types.test.ts index 56b65fa42b9f..103e384e10da 100644 --- a/test/integration/bun-types/bun-types.test.ts +++ b/test/integration/bun-types/bun-types.test.ts @@ -318,6 +318,7 @@ const PUBLISHED_AS: Record = { "BunTest.bind.ts": null, "ByteStream.bind.ts": null, "BytecodeOrderRecorder.bind.ts": null, + "ConsoleObject.bind.ts": null, "Counters.bind.ts": null, "Crypto.bind.ts": 'typeof Bun & { Crypto: Class>; timingSafeEqual: typeof import("node:crypto").timingSafeEqual }', @@ -396,6 +397,7 @@ const PUBLISHED_AS: Record = { "typeof Bun & { FrameworkFileSystemRouter: Class<{ match(path: string): any; toJSON(): any }> }", "fmt_jsc.bind.ts": null, "h2_frame_parser.bind.ts": null, + "hash_map_testing.bind.ts": null, "headers_jsc.bind.ts": null, "hosted_git_info_jsc.bind.ts": null, "html_rewriter.bind.ts": "{ HTMLRewriter: typeof HTMLRewriter }",