Skip to content
2 changes: 2 additions & 0 deletions src/codegen/generate-js2native.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ const sourceFiles = readdirRecursiveWithExclusionsAndExtensionsSync(
const rustIdentifierPaths: Record<string, string> = {
"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",
Expand Down Expand Up @@ -87,6 +88,7 @@ const rustIdentifierPaths: Record<string, string> = {
"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",
Expand Down
15 changes: 15 additions & 0 deletions src/js/internal-for-testing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*/
Comment thread
robobun marked this conversation as resolved.
Resolved
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 {
Expand Down
34 changes: 33 additions & 1 deletion src/jsc/ConsoleObject.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -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.
Comment thread
robobun marked this conversation as resolved.
Resolved
pub fn table_sizes_for_testing(global: &JSGlobalObject, _frame: &CallFrame) -> JsResult<JSValue> {
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
Expand Down
1 change: 1 addition & 0 deletions src/runtime/dispatch_js2native.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
76 changes: 76 additions & 0 deletions src/runtime/hash_map_testing.rs
Original file line number Diff line number Diff line change
@@ -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.
Comment thread
robobun marked this conversation as resolved.
Resolved

use core::cell::Cell;

use bun_collections::{HashContext, HashMap};
use bun_jsc::{CallFrame, JSGlobalObject, JSValue, JsResult};

thread_local! {
static COMPARISONS: Cell<u32> = const { Cell::new(0) };
}

struct CountingContext;

impl HashContext<u64> 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);
Comment thread
robobun marked this conversation as resolved.
Resolved
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<JSValue> {
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;
Comment thread
robobun marked this conversation as resolved.
Resolved

let mut map: HashMap<u64, (), CountingContext> = HashMap::new();
for key in 0..live {
map.insert(key, ());
}
for cycle in 0..cycles {
map.remove(&cycle);
map.insert(live + cycle, ());
Comment thread
robobun marked this conversation as resolved.
Resolved
}

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)
}
1 change: 1 addition & 0 deletions src/runtime/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
13 changes: 13 additions & 0 deletions test/internal/hash-map.test.ts
Original file line number Diff line number Diff line change
@@ -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 });
});
58 changes: 58 additions & 0 deletions test/js/web/console/console-timeLog.test.ts
Original file line number Diff line number Diff line change
@@ -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 () => {
Expand Down Expand Up @@ -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")],
Expand Down
Loading