diff --git a/src/collections/lib.rs b/src/collections/lib.rs index 22edbb91820f..9b1b493b8fa6 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 c559767ca7ba..d0e33fcca256 100644 --- a/src/collections/zig_hash_map.rs +++ b/src/collections/zig_hash_map.rs @@ -1,7 +1,8 @@ -//! 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. lockfile debug stringify). A removal walks and +//! 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 @@ -17,24 +18,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 +89,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 +286,7 @@ impl> HashMap { self.size += 1; } - /// Probe for `key`, stop on free, skip tombstones. + /// Probe for `key`, stop on free. A run always ends at a free slot. fn get_index(&self, key: &Q) -> Option where K: Borrow, @@ -308,22 +296,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 +366,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) } @@ -459,9 +435,23 @@ impl> HashMap { Ok(()) } + /// Backward-shift delete (Knuth, TAOCP 6.4, Algorithm R): leaves no tombstone. 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; + // 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(); + hole = next; + } + next = (next + 1) & mask; + } + self.metadata[hole] = SLOT_FREE; self.size -= 1; self.available += 1; kv @@ -496,10 +486,18 @@ impl> HashMap { /// std `retain`. Calls `keep` exactly once per entry. pub fn retain(&mut self, mut keep: impl FnMut(&K, &mut V) -> bool) { - for idx in 0..self.slots.len() { - if let Some((key, value)) = &mut self.slots[idx] - && !keep(key, value) - { + // The scan starts behind a free slot, so it meets each run at its first entry. + let Some(start) = self.slots.iter().position(Option::is_none) else { + return; + }; + let mask = self.slots.len() - 1; + for offset in 1..self.slots.len() { + let idx = (start + offset) & mask; + // A removal can move the next entry of the run into `idx`. + while let Some((key, value)) = &mut self.slots[idx] { + if keep(key, value) { + break; + } let _ = self.remove_by_index(idx); } } @@ -692,6 +690,222 @@ impl<'a, K, V, C: HashContext> VacantEntry<'a, K, V, C> { } } +#[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() + } + + /// 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); + 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 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]; + 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()); + } + } + 98 => { + let rejects = |key: u64| key.wrapping_add(value).is_multiple_of(3); + let mut shown = vec![0u8; key_space]; + map.retain(|key, _| { + shown[*key as usize] += 1; + !rejects(*key) + }); + for (key, slot) in model.iter_mut().enumerate() { + assert_eq!(shown[key], u8::from(slot.is_some()), "key {key}"); + if rejects(key as u64) { + *slot = None; + } + } + } + _ => { + if value.is_multiple_of(8) { + map.clear(); + model.fill(None); + } + } + } + if !cfg!(miri) || op % 8 == 7 { + check(&map, &model); + } + } + check(&map, &model); + } + + // 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] + fn agrees_with_a_model_wyhash() { + run_against_model::(1, 48, 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_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, 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, [1, 33, 2, 3, 9, 10, 41, 11, 17, 49, 18, 25, 57, 26]); + } + + #[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); + } +} + #[cfg(test)] mod retain_tests { use super::*; diff --git a/src/js/internal-for-testing.ts b/src/js/internal-for-testing.ts index aa59331a30db..f5835cdf8abb 100644 --- a/src/js/internal-for-testing.ts +++ b/src/js/internal-for-testing.ts @@ -663,6 +663,12 @@ export const getCounters = $bindgen("Counters.bind.ts", "createCountersObject"); export const linearFifoOrderedRemoveProbe = $bindgen("linear_fifo_testing.bind.ts", "orderedRemoveProbe") as ( scenario: number, ) => number[]; +export const consoleTableSizes = $bindgen("ConsoleObject.bind.ts", "tableSizesForTesting"); +/** `maxComparisons`: the most stored entries that a lookup of an absent key is compared against. */ +export const hashMapChurnProbe = $bindgen("hash_map_testing.bind.ts", "churnProbe") as ( + live: number, + cycles: number, +) => { capacity: number; length: number; maxComparisons: number }; export const hasNonReifiedStatic = $newCppFunction("InternalForTesting.cpp", "jsFunction_hasReifiedStatic", 1); const setNativeSocketOptions: (socket: unknown, option: 1 | 2, size: number) => void = $bindgen( diff --git a/src/jsc/ConsoleObject.bind.ts b/src/jsc/ConsoleObject.bind.ts new file mode 100644 index 000000000000..99dbde3ed5d8 --- /dev/null +++ b/src/jsc/ConsoleObject.bind.ts @@ -0,0 +1,12 @@ +import * as b from "../codegen/bindgen-lib.ts"; + +export default b.module({ rustPath: "crate::console_object" }); + +export const ConsoleTableSizes = b.dictionary({ + timerEntries: b.usize, + timerCapacity: b.usize, + countEntries: b.usize, + countCapacity: b.usize, +}); + +export const tableSizesForTesting = b.fn({ returns: ConsoleTableSizes, capability: "heap" }); diff --git a/src/jsc/ConsoleObject.rs b/src/jsc/ConsoleObject.rs index a1d0bc4ea332..970cd78c3175 100644 --- a/src/jsc/ConsoleObject.rs +++ b/src/jsc/ConsoleObject.rs @@ -8,6 +8,8 @@ use core::cell::{Cell, RefCell}; use core::ffi::c_void; use crate as jsc; +use crate::bindgen::JsHeap; +use crate::generated_bindgen::console_object::ConsoleTableSizes; use crate::virtual_machine::VirtualMachine; use crate::{EventType, JSGlobalObject, JSPromise, JSValue, JsResult}; use bun_collections::HashMap; @@ -5747,12 +5749,10 @@ pub(crate) extern "C" fn Bun__ConsoleObject__countReset( // set-once `VirtualMachine.console` box. let this = unsafe { vm_console_mut(global_this) }; let hash = bun_wyhash::hash(&label.to_utf8()); - // 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); } +/// `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()); @@ -5774,7 +5774,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()); } }); @@ -5794,12 +5794,9 @@ pub(crate) extern "C" fn Bun__ConsoleObject__timeEnd( let label = label.to_utf8(); let slice: &[u8] = &label; 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, @@ -5871,6 +5868,22 @@ pub(crate) extern "C" fn Bun__ConsoleObject__timeLog( let _ = bun_io::Write::flush(&mut writer); } +/// `consoleTableSizes()` in `bun:internal-for-testing`. +pub(crate) fn table_sizes_for_testing(heap: &JsHeap<'_>) -> ConsoleTableSizes { + let (timer_entries, timer_capacity) = + PENDING_TIME_LOGS.with_borrow(|map| (map.len(), map.capacity())); + // SAFETY: only the VM's console is read through it. + let global = unsafe { heap.global() }; + // SAFETY: see [`vm_console`]. Nothing writes `counts` during this JS-thread read. + let counts = unsafe { &(*vm_console(global)).counts }; + ConsoleTableSizes { + timer_entries, + timer_capacity, + count_entries: counts.len(), + count_capacity: counts.capacity(), + } +} + /// 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/hash_map_testing.bind.ts b/src/runtime/hash_map_testing.bind.ts new file mode 100644 index 000000000000..3f1a535062b0 --- /dev/null +++ b/src/runtime/hash_map_testing.bind.ts @@ -0,0 +1,14 @@ +import * as b from "../codegen/bindgen-lib.ts"; + +export default b.module({ rustPath: "crate::hash_map_testing" }); + +export const ChurnProbeResult = b.dictionary({ + capacity: b.usize, + length: b.usize, + maxComparisons: b.usize, +}); + +export const churnProbe = b.fn({ + args: { live: b.u32.enforceRange(0, 1 << 20), cycles: b.u32.enforceRange(0, 1 << 24) }, + returns: ChurnProbeResult, +}); diff --git a/src/runtime/hash_map_testing.rs b/src/runtime/hash_map_testing.rs new file mode 100644 index 000000000000..db75fe1f3dd4 --- /dev/null +++ b/src/runtime/hash_map_testing.rs @@ -0,0 +1,57 @@ +//! `hashMapChurnProbe` in `bun:internal-for-testing` (in `bun_runtime`: `bun_collections` has no bindings). + +use core::cell::Cell; + +use bun_collections::{HashContext, HashMap}; + +use crate::generated_bindgen::hash_map_testing::ChurnProbeResult; + +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 { + 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; + +/// Keeps `live` keys, replaces the oldest `cycles` times, then looks up 1,000 absent keys. +pub(crate) fn churn_probe(live: u32, cycles: u32) -> ChurnProbeResult { + let (live, cycles) = (u64::from(live), u64::from(cycles)); + + let mut map: HashMap = HashMap::new(); + for key in 0..live { + map.insert(key, ()); + } + if live > 0 { + 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()); + } + + ChurnProbeResult { + capacity: map.capacity(), + length: map.len(), + max_comparisons: max_comparisons as usize, + } +} diff --git a/src/runtime/lib.rs b/src/runtime/lib.rs index c80555447ea1..a839ead60655 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; #[cfg(debug_assertions)] pub(crate) mod imported_class_test; 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 }", diff --git a/test/internal/hash-map.test.ts b/test/internal/hash-map.test.ts new file mode 100644 index 000000000000..ca0ab9708dcc --- /dev/null +++ b/test/internal/hash-map.test.ts @@ -0,0 +1,26 @@ +/** + * `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"; + +// 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", () => { + 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", () => { + 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", () => { + expect(hashMapChurnProbe(0, 1000)).toEqual({ capacity: 0, length: 0, maxComparisons: 0 }); +}); diff --git a/test/js/web/console/console-timeLog.test.ts b/test/js/web/console/console-timeLog.test.ts index bf7ddc485e5b..d5e14ff31d7f 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,78 @@ 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("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")],