Skip to content

Delete from HashMap by backward shift, free the entry in console.timeEnd and countReset - #44280

Closed
robobun wants to merge 8 commits into
mainfrom
robobun/b42a1f26/testing-probes
Closed

robobun wants to merge 8 commits into
mainfrom
robobun/b42a1f26/testing-probes

Conversation

@robobun

@robobun robobun commented Sep 30, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

  • console.time(label) + console.timeEnd(label) keeps one table slot per distinct label: 35 MB to 450 MB after 10,000,000 labels (node: 144 MB).
  • Bun__ConsoleObject__timeEnd (src/jsc/ConsoleObject.rs) keeps the key, because remove_by_index (src/collections/zig_hash_map.rs) left a tombstone that nothing cleared. After a churn, each lookup of a missing key reads the whole table.
  • URL.createObjectURL + revokeObjectURL shows it: 1 us to 27 us a pair.

Fix

  • remove_by_index closes the gap by backward shift (Knuth, TAOCP 6.4, Algorithm R). No tombstone exists. A map that never removes keeps its layout.
  • timeEnd calls remove(), as the WHATWG Console Standard says (Remove timerTable[label]). countReset calls it too. The output does not change.
  • Verified: 10,000,000 labels stay at 53 MB. The url pair stays at 0.6 us. Tests: test/js/web/console/console-timeLog.test.ts, test/internal/hash-map.test.ts, 8 unit tests in zig_hash_map.rs, the http2, lockfile and router suites.
  • Self-reviewed: 10 concerns raised, 9 addressed. Rejected: Option<Timer> stays, because get_or_put needs Default.

Background

  • The map uses linear probing. A tombstone marks a removed entry so that lookups walk past it.
  • The tests read two new bun:internal-for-testing probes: the defect shows only as memory or time.
  • Considered tombstones counted as load: one live entry rebuilds the table every 10 operations. Considered a second map type: other removers keep the defect.

Downsides

  • A remove walks to the next free slot: mean 0.1 to 4.4 entries, maximum 87, in 208,000 real removes.
  • A remove changes the order of the other entries. bun.lock uses maps that never remove.
  • A table keeps its peak capacity. The binary grows by 2.7 KB.
Notes

Reproduction (release build 1.4.3-canary, linux x64)

for (let id = 0; id < 10_000_000; id++) {
  console.time("req-" + id);
  console.timeEnd("req-" + id);
}
RSS after a forced GC before after 10,000,000 labels
main 35 MB 450 MB, steps at the table doublings
this PR 40 MB 52 to 55 MB from the first million on
node v26.3.0 58 MB 144 MB
  • The same loop inside a Bun.serve handler, 2,000,000 requests: main 33 MB to 148 MB, this PR 40 MB to 54 MB.
  • Each doubling of the table was a pause inside one console.time call: 40 ms at label 838,861, 80 ms at 1,677,722, 128 ms at 3,355,444. With this PR no call in 4,000,000 labels is tied to a doubling. The slowest call was 19 ms once and the rest were 3 ms or less, on a loaded machine.
  • console.count + console.countReset had the same growth. The WHATWG text sets the count to 0 in countReset. The next console.count prints 1 in both cases, and bun prints no warning for a reset of an unknown label, so a program cannot see the removal. node deletes there too.
  • node fixed the same leak in 2015: nodejs/node commit a5cce79ec3f0, "console: delete timers that have ended".

Why the map changes in this PR

countReset carried the comment we don't delete it because deleting is implemented via tombstoning. A plain remove() in timeEnd on the old map trades the memory growth for a scan. remove_by_index gave the capacity of a tombstone back, so tombstones never counted as load and the table never rebuilt. Counts on a copy of the map file with counters, for one remove plus one insert of a new key:

live entries old map backward shift tombstones as load
1 10 probes 2 probes + 1 walk step 2.6 probes, 102,711 table rebuilds per 1,000,000 operations
1,000 2,051 probes 3.9 probes + 2.9 walk steps, worst 70 4.7 probes, worst 2,222, twice the slots
100,000 47,000 and rising 11.9 probes + 10.9 walk steps, worst 356 6.0 probes, worst 230,952, twice the slots
1,000,000 inserts, no remove 6.48 probes 6.48 probes, same layout 6.48 probes, same layout
  • hashMapChurnProbe(1000, 100000): maxComparisons is 1,000 on main (every stored entry) and 6 with this PR. The capacity is 2,048 in both.
  • LLVM's DenseMap uses the same delete for a linear-probing table.

Other maps that remove (release builds, main 367d939 against this PR, interleaved runs, a loaded machine)

case main this PR
URL.createObjectURL + revokeObjectURL, 2,000 live, last 10,000 of 70,000 cycles, 5 rounds 24.5 to 28.5 us a pair 0.53 to 0.62 us
same, 20,000 live, 400,000 cycles 183 to 193 us 0.71 to 0.81 us
node:http2, one session, after a burst of 5,000 streams climbs to about 170 us a request flat: 60 to 95 us, as before the burst
fs.watch + close after a burst of 20,000 watchers climbs to about 95 us a cycle about 21 us

Cost of a remove in real runs (entries walked past the removed one, debug build with a temporary counter)

run removes mean max largest table
test/js/node/http2/ (596 tests) 61,458 0.08 15 2,048 slots
console, inspect, JSON5, TOML and expect suites (938 tests) 28,536 0.40 23 4,096
object url churn, 20,000 live 59,904 4.36 87 32,768
fs.watch and http2 burst probes 57,856 0.09 to 0.15 12 4,096
install, workspaces and migration suites 1,335 0.04 4 8
  • A frozen install of 1,301 packages from the cache and two large bundles did not remove from this map at all.
  • A map that removes a few entries and never churns pays the walk and gains nothing: about 8 steps against 4 for a remove plus insert at 1,000 live.
  • A fixed label: a time + timeEnd pair now writes two metadata bytes where it wrote none. The wall-clock is inside the noise: 806 to 849 ns a pair against 828 to 1,013 ns on main.

What can differ

  • The order of the entries that stay changes at a remove. The maps behind bun.lock only insert, and a unit test now pins the insert-only order. The bun pm migrate output for the yarn-cli-repo fixture equals its snapshot. The order in which node:http2 closes the streams of a destroyed session follows the slot order and can change. So can the order in which one session flushes queued DATA frames and sends WINDOW_UPDATE frames across its streams. That order is the hash order on main too.

  • Options.registries (install): scope_for_registry_url takes the first scope in table order that has credentials for a registry URL. With two such scopes the pick is in hash order, on main too. After a config layer removes a scope, the pick can now differ.

  • IdentityContext over dense consecutive integers puts all keys in one run, and one remove would walk all of it (100,000 entries at 100,000 live). Every IdentityContext map in src/ is keyed by a hash value. The file header says that a run stays short only when the hash spreads the keys.

  • A peer of an http2 session can pick stream ids that share one home slot: the integer hash has no seed. Then each lookup and each insert costs the run length, on main too. A remove now also hashes and moves the rest of its run. Measured on the two map files alone, with odd ids whose wyhash has the same low 14 bits:

    ids that share one slot main this PR
    1,000 stay live, one opens and the oldest closes 4,006 slots read, 3.0 to 3.3 us 4,504 slots, 1,006 hashes, 1,000 moves, 2.9 to 3.0 us
    a burst of 1,000: open, for each id 1,945 slots, 1.4 to 1.8 us 1,945 slots, 0.7 us
    then close, oldest first 1,001 slots, 0.5 to 0.6 us 502 slots, 502 hashes, 500 moves, 0.8 us
    or close, newest first 1,001 slots, 0.7 to 0.9 us 1,001 slots, 0.4 us
    each later id of that kind 1,002 slots, 0.5 to 0.8 us 2 slots, 0.01 us

    At 10,000 ids each figure is about 10 times larger, except the last one of this PR. So the total stays quadratic in both. With this PR a burst costs 14% to 50% less time, and the steady case costs the same within the noise. One part costs more: a close of the oldest id. The first row is one cycle: a lookup that misses, an insert, three lookups that hit and a remove. An open is a miss, an insert and a hit. A close is a hit and a remove. The counts are exact, from a copy of each map file with a counter in its probe loops. The times are from the same copies without the counter: release build, 3 interleaved rounds, the minimum of 5 runs in each. node:http2: keep the stream tables dense and in open order #44317 moves the http2 stream tables to another map type.

Not in this PR

  • The map never shrinks. After a burst of 20,000 streams an http2 request stays at about 130 us (90 on a fresh session), because replenish_windows walks the whole stream table once per receive batch. node:http2: keep the stream tables dense and in open order #44317 moves the http2 stream tables to a dense table. After 1,000,000 timers that run at once the timer table keeps 2,097,152 slots, about 52 MB.
  • Different labels can share one counter or one timer. The tables key an entry by a wyhash of the label's UTF-8 and store no label. "\uD800", "\uDC00" and "\uFFFD" become the same bytes. The ASCII labels request-za1_____AXzpBDAF4 and request-za1_____BXzpBDAF4 have the same wyhash. For each group console.count prints 1, 2 where node v26.3.0 prints 1, 1, and a countReset or timeEnd of one label ends the other. The first question below decides the fix.
  • The snapshot store of bun test keys by a wyhash of the snapshot name in the same way. Two tests named request-za1_____AAAAAAAAXzpBDAF4suffix and request-za1_____BBBBBBBBXzpBDAF4suffix share one entry: with toMatchSnapshot() the second test fails on its first run with Expected: "one", Received: "two". It is outside this PR and has no owner.
  • The timer table is per thread, not per console object.

Binary (llvm-nm -S on release builds. The base binary is 367d939, where both source files equal the merge base. bloaty is not installed on the machine that measured.)

  • Outlined map code: 100,629 B to 99,472 B. remove grows from 978 B to 4,885 B, get_index shrinks from 11,956 B to 8,053 B.
  • timeEnd +347 B, countReset +370 B.
  • The two probes: 3.1 KB.
  • These numbers are from c488d7c, before the merge with main. The probes are bindgen schemas now and were not measured again.

Tests

  • With only the probes applied to main, hashMapChurnProbe(256, 2000) returns maxComparisons: 256, and the map test fails: its bound is 32. 2,000 ended timers leave { timerEntries: 2000, timerCapacity: 4096 }. On main itself the probes do not exist, so both test files fail at the import.
  • The file has 8 unit tests: 7 from this PR and main's retain test. 6 of the 7 fail on the old map. The other one pins the insert-only order and passes on both. All 8 pass under Miri.
  • Suites on a debug ASAN build of the merge with main 57fe602: test/js/node/http2/ 675 pass. bun-lock, bun-workspaces, bun-pm-why, npmrc, yarn and pnpm lock migration, framework-router, hmr-socket-protocol and deinitialization: 1,491 pass. The json5, toml, xml, yaml, console and fs.watch directories: 6,226 pass.

Merge with main (199e8a3, on main 57fe602)

  • $newRustFunction is gone on main. The two probes are bindgen schemas now: src/jsc/ConsoleObject.bind.ts and src/runtime/hash_map_testing.bind.ts.
  • main added HashMap::retain. Its callers need keep to run once for each entry: rebind_to_cleaned_lockfile remaps ids in place. A backward-shift removal can move the next entry of the run into the slot that the scan is at. It can also move an entry from the table start into a slot that the scan reaches later. retain now starts behind a free slot and looks at a slot again after a removal. With main's loop on this map, main's retain_shows_each_entry_once and the three model tests fail.
  • The callers were read again on main (80 files use the map). No code keeps a pointer or an index into a slot across a removal. The places where the order after a removal reaches output are under "What can differ".

Self-review (10 concerns, 9 addressed: 8 in ea0f7db, 1 in this text)

  • The order test with wyhash pinned a bucket order that a code comment says no test relies on. One order test with the identity hash, across two grows, replaces both order tests.
  • The model test with the identity hash never moved an entry. It passed with the move disabled, so it is gone.
  • hash-map.test.ts pinned maxComparisons: 19, which depends on the integer hash. It now bounds the count at 32.
  • hashMapChurnProbe read its arguments as i32, so a value above 2^31 wrapped before the clamp. Its schema now takes an integer in a range.
  • consoleTableSizes took &mut ConsoleObject for a read. It now reads through a shared borrow.
  • The file header said that IdentityContext is only for keys that are hashes. The IdentityHash docs allow any integer, so the header now gives the condition: a run stays short only when the hash spreads the keys.
  • This text said that the standard removes in countReset. The standard sets the count to 0 there.
  • The unit tests took 28 s under Miri on the test machine. They now take 6.5 s: fewer layout checks under Miri, and one test less.
  • value % 8 == 0 in a unit test fails clippy (manual_is_multiple_of) with --all-targets.
  • Rejected: the timer value is Option<Timer> and is never None now. get_or_put needs Default, Timer has none, and entry() probes twice on a miss. One doc line states the invariant.

Questions for a maintainer

  • May the console tables keep a reference to the label string? A comment in Bun__ConsoleObject__count says we don't want to store these strings, it will take too much memory. With this PR an entry lives only until timeEnd or countReset. A design review picked a retained string reference as the key. It is exact for every label and adds no allocation: one reference count up when an entry is made, one down when it is freed. It is about 300 lines, and the tables start to own JS strings, so worker teardown and addon strings need care. The zero-cost alternative hashes the exact code units of the label. It separates the surrogate labels only: the two ASCII labels above still share an entry. Neither is in this PR yet.
  • Is "the order after a remove is unspecified" acceptable for this map?
  • Should IdentityContext refuse keys that are not hashes? The header only says that a run stays short when the hash spreads the keys.
  • Is a shrink wanted, and where?

Open PRs on the same lines


[human-review] gate passed · iteration 0 · 11 files touched

fails on main (without fix)
ASAN without fix: BUILD FAILED (no junit output)
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/pr_gate.xml" test/integration/bun-types/bun-types.test.ts test/internal/hash-map.test.ts test/js/web/console/console-timeLog.test.ts
ninja: Entering directory `/workspace/bun/build/debug'
[0/2] cargo plan → /workspace/bun/build/debug/rust-target/plan.json
FAILED: [code=1] rust-target/plan.json /workspace/bun/build/debug/rust-target/plan.json 
/workspace/bun/build/release/bun /workspace/bun/scripts/build/stream.ts cargo --console /workspace/bun/build/release/bun /workspace/bun/scripts/build/rust/plan.ts /workspace/bun/build/debug/rust-target/plan.input.json /workspace/bun/build/debug/rust-target/plan.json
^[[1m^[[91merror^[[0m: cannot update the lock file /workspace/bun/Cargo.lock because --locked was passed to prevent this
help: to generate the lock file without accessing the network, remove the --locked flag and use --offline instead.
error: /opt/rust/bin/cargo build -p bun_runtime --lib … exited with 101
ninja: error: rebuilding 'build.ninja': subcommand failed
error: script "bd" exited with code 1
__F:-1:S:0

release without fix: 1 FAILED
bun test v1.4.3-canary.1 (367d939d9)

test/internal/hash-map.test.ts:

# Unhandled error between tests
-------------------------------
SyntaxError: Export named 'hashMapChurnProbe' not found in module 'bun:internal-for-testing'.
-------------------------------


test/integration/bun-types/bun-types.test.ts:
(pass) @types/bun integration test > building and packing bun-types leaves packages/bun-types untouched [0.28ms]
(pass) @types/bun integration test > packed bun-types includes CLAUDE.md [1.14ms]
(pass) @types/bun integration test > basic type checks > checks without lib.dom.d.ts [8825.39ms]
608 |       expect(ts.getPreEmitDiagnostics(program, file).map(diagnostic => diagnostic.messageText)).toEqual([]);
609 |     }
610 | 
611 |     const checker = program.getTypeChecker();
612 |     const [published, generated] = source.statements.map(statement => checker.getTypeAtLocation(statement));
613 |     expect(schemas.map(file => basename(file)).sort()).toEqual(Object.keys(PUBLISHED_AS).sort());
                                                             ^
error: expect(received).toEqual(expected)

@@ -5,11 +5,10 @@
    "BunObject.bind.ts",
    "BunObjectInternals.bind.
... (truncated)
passes on PR (with fix)
ASAN with fix: 15 skipped
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/pr_gate.xml" test/integration/bun-types/bun-types.test.ts test/internal/hash-map.test.ts test/js/web/console/console-timeLog.test.ts
bun test v1.4.4 (367d939d9)

test/internal/hash-map.test.ts:
(pass) a lookup in a map that never removed an entry walks one short run [32.28ms]
(pass) a lookup still walks one short run after 2,000 removals [7.66ms]
(pass) the probe churns nothing when no key is live [2.32ms]

test/integration/bun-types/bun-types.test.ts:
(pass) @types/bun integration test > building and packing bun-types leaves packages/bun-types untouched [3.08ms]
(pass) @types/bun integration test > packed bun-types includes CLAUDE.md [8.75ms]
(skip) @types/bun integration test > basic type checks > checks without lib.dom.d.ts
(skip) @types/bun integration test > promises nothing that a schema of the bindgen breaks
(skip) @types/bun integration test > TypeScript latest > checks without lib.dom.d.ts
(skip) @types/bun integration test > TypeScript 7.1 > checks the fixture and import attributes through ts7.1/index.d.ts
(pass) @types/bun integration tes
... (truncated)

release with fix: all passed
$ bun scripts/build.ts --profile=release
[configured] bun-profile → bun (stripped)
  target       linux-x64-gnu
  build type   Release
  build dir    ./build/release
  revision     e90e8e65d1
  features     lto, baseline

23 deps, 398 codegen, 1304 objects in 1785ms

ninja: Entering directory `/workspace/bun/build/release'
[1/4] fetch lolhtml
[lolhtml] up to date
[2/4] fetch rust-argon2
[rust-argon2] up to date
[2/4] cargo plan → /workspace/bun/build/release/rust-target/plan.json
282 units: 194 lib, 16 proc-macro (host), 27 custom-build (host), 23 run custom-build, 17 lib (host), 4 run custom-build (host), 1 rlib
[3/4] reconfigure
[1/1673] mkdir stamps
[2/1673] mkdir codegen
[3/1673] gen bake.{client,server,error}.js
-> bake.client.js, bake.server.js, bake.error.js
[4/1673] install /workspace/bun
bun install v1.4.3-canary.1 (367d939d9)

Checked 22 installs across 44 packages (no changes) [860.00ms]
[5/1673] install /workspace/bun/packages/bun-error
bun install v1.4.3-canary.1 (367d939d9)

Checked 1 install across 2 packages (no changes) [58.00ms]
[6/1673] gen lint-rule-pages.txt
[7/1673] esbuild bun-error

  ../../build/release/codegen/bun-error/index.js       3
... (truncated)
diff hotspot
src/collections/lib.rs                       |   4 +-
 src/collections/zig_hash_map.rs              | 304 +++++++++++++++++++++++----
 src/js/internal-for-testing.ts               |   6 +
 src/jsc/ConsoleObject.bind.ts                |  12 ++
 src/jsc/ConsoleObject.rs                     |  31 ++-
 src/runtime/hash_map_testing.bind.ts         |  14 ++
 src/runtime/hash_map_testing.rs              |  57 +++++
 src/runtime/lib.rs                           |   1 +
 test/integration/bun-types/bun-types.test.ts |   2 +
 test/internal/hash-map.test.ts               |  26 +++
 test/js/web/console/console-timeLog.test.ts  |  74 +++++++
 11 files changed, 475 insertions(+), 56 deletions(-)

gate history · 2 passed · 0 rejected · iteration 0

evidence per changed file
file                                          reads  edits  tests
src/collections/lib.rs                            0      0     53
src/collections/zig_hash_map.rs                   1      0     62
src/js/internal-for-testing.ts                    0      0     59
src/jsc/ConsoleObject.bind.ts                     0      0     54
src/jsc/ConsoleObject.rs                          2      1     55
src/runtime/hash_map_testing.bind.ts              0      0     54
src/runtime/hash_map_testing.rs                   0      1     54
src/runtime/lib.rs                                0      0     54
test/integration/bun-types/bun-types.test.ts      0      0      3
test/internal/hash-map.test.ts                    0      2     38
test/js/web/console/console-timeLog.test.ts       1      2     37

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.
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.
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.
@robobun

robobun commented Sep 30, 2026 •

Copy link
Copy Markdown
Collaborator Author

Status

How the defect was reproduced (release build 1.4.3-canary, linux x64):

for (let id = 0; id < 10_000_000; id++) {
  console.time("req-" + id);
  console.timeEnd("req-" + id);
}

RSS goes from 35 MB to 450 MB on main. node v26.3.0 stays at 144 MB. With this PR it stays at 40 MB to 53 MB.

This PR (#44280) holds the whole change: the delete in bun_collections::HashMap, the console change, and the test probes.

Commit 199e8a3 merges main 57fe602, because the PR had conflicts. The two test probes are bindgen schemas now. HashMap::retain, which is new on main, keeps its rule that keep runs once for each entry.

A second defect in the same tables is not fixed here. console.count and console.time key an entry by a hash of the label's UTF-8, so the labels "\uD800", "\uDC00" and "\uFFFD" share one counter, and so do the ASCII labels request-za1_____AXzpBDAF4 and request-za1_____BXzpBDAF4. node keeps them apart. The fix needs a maintainer's decision on whether the tables may keep a reference to the label string: see "Questions for a maintainer" in the PR body.

CI on e90e8e6 (build 133232) is green: 181 of 181 jobs pass.

@coderabbitai

coderabbitai Bot commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository: oven-sh/bun/.coderabbit.yaml

Review profile: ASSERTIVE

Plan: Essentials

Run ID: c2451aa4-e53a-4d39-ad9f-8e95b53c59ec

📥 Commits

Reviewing files that changed from the base of the PR and between c488d7c and ea0f7db.

📒 Files selected for processing (4)
  • src/collections/zig_hash_map.rs
  • src/jsc/ConsoleObject.rs
  • src/runtime/hash_map_testing.rs
  • test/internal/hash-map.test.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 0 remain after this review.

Walkthrough

The pull request replaces HashMap tombstones with backward-shift deletion and adds tests for map behavior and churn metrics. It also changes console timer and count entry removal and adds testing bindings and tests for table sizes.

Changes

HashMap deletion and churn

Layer / File(s) Summary
Backward-shift deletion and validation
src/collections/lib.rs, src/collections/zig_hash_map.rs
HashMap removal shifts entries to close gaps instead of marking slots as tombstones. Tests cover model agreement, collisions, wraparound, iteration order, deletion, and repeated churn.
HashMap churn probe
src/runtime/hash_map_testing.rs, src/runtime/lib.rs, src/js/internal-for-testing.ts, src/codegen/generate-js2native.ts, test/internal/hash-map.test.ts
Adds a testing probe that churns a HashMap and reports capacity, length, and maximum comparisons across absent-key lookups. Tests check its reported results.

Console table cleanup

Layer / File(s) Summary
Console entry lifecycle and size inspection
src/jsc/ConsoleObject.rs, src/runtime/dispatch_js2native.rs, src/js/internal-for-testing.ts, src/codegen/generate-js2native.ts, test/js/web/console/console-timeLog.test.ts
Timer and count operations remove entries when ended or reset. A testing binding reports table entry counts and capacities, and tests check console behavior and table sizes.

Suggested reviewers: jarred-sumner

Priority: Normal

Merge Risk: Minimal · up to ea0f7

The supplied evidence does not establish a user-visible regression in the HashMap or console changes. Proceed with ordinary CI and test validation.

Pre-merge checks: Passed 4
Check name Status Explanation
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Title check Passed The title clearly describes the two primary changes: backward-shift HashMap deletion and freeing entries from console timers and counters.
Description check Passed The description is complete and directly covers what the PR changes and how the changes were verified. It uses equivalent headings instead of the template headings, with details under “Fix” and “Tests…
Full details: Description check

Explanation

The description is complete and directly covers what the PR changes and how the changes were verified. It uses equivalent headings instead of the template headings, with details under “Fix” and “Tests,” but all required information is present.

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nothing blocking. The comments below are optional suggestions. There is no need to push a fix for them before merging.

Beyond the inline findings, I also checked the unsafe { vm_console_mut(global) } borrow in table_sizes_for_testing (src/jsc/ConsoleObject.rs): it follows the same set-once-box / single-JS-thread pattern the existing count/countReset entry points use, and the counts reference is only read for len()/capacity() across put calls on a fresh empty object, which cannot re-enter the console or user JS. No production code path changes; both probes are reachable only through bun:internal-for-testing.

Extended reasoning...

The change adds two test-only probes (console table sizes and a HashMap churn/lookup counter) wired through internal-for-testing, the js2native codegen table, and dispatch re-exports, plus two tests; it touches no security-sensitive surface. The inline findings are all about the new test probe's argument handling and counter overflow in debug builds, not production behavior. The console-side probe's borrow pattern was checked against the existing accessor contract and matches it.

Comment thread src/runtime/hash_map_testing.rs Resolved
Comment thread src/runtime/hash_map_testing.rs Resolved
Comment thread src/runtime/hash_map_testing.rs Resolved
…th 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.
@robobun robobun changed the title Add test probes for the console tables and for HashMap lookups Delete from HashMap by backward shift; console.timeEnd and countReset free their entry Sep 30, 2026
Comment thread src/collections/lib.rs Resolved
Comment thread src/collections/zig_hash_map.rs Resolved
Comment thread src/collections/zig_hash_map.rs Resolved
Comment thread src/collections/zig_hash_map.rs Resolved
Comment thread src/collections/zig_hash_map.rs Resolved
Comment thread src/js/internal-for-testing.ts Resolved
Comment thread src/jsc/ConsoleObject.rs Resolved
Comment thread src/jsc/ConsoleObject.rs Resolved
Comment thread src/runtime/hash_map_testing.rs Resolved
Comment thread src/runtime/hash_map_testing.rs Resolved
Comment thread src/collections/zig_hash_map.rs Resolved
@robobun

robobun commented Sep 30, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 2:27 PM PT - Oct 26th, 2026

✅ @robobun, your commit e90e8e65d1e95637c847e8eec3e3943211a2d4a4 passed in Build #133232! 🎉


🧪   To try this PR locally:

bunx bun-pr 44280

That installs a local version of the PR into your bun-44280 executable, so you can run:

bun-44280 --bun

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code review found no issues

No high-confidence issues detected in this change.

@robobun

robobun commented Sep 30, 2026

Copy link
Copy Markdown
Collaborator Author

#44317 moves the three node:http2 stream tables from HashMap to ArrayHashMap. The two PRs touch different files, except that each adds an export to src/js/internal-for-testing.ts. The http2 tables need #44317 with or without this PR: Connection::replenish_windows walks the engine's table twice per read, and a HashMap walk reads its peak capacity.

Before I found this PR I had written the other fix for the map, the one the Background lists: a tombstone counts as load. I did not open a PR for it. The commit is 8531b0f on robobun/0a4a6336/hashmap-tombstones-as-load, for comparison only. It differs from the variant measured here in one point: it clears the tombstones in place and allocates nothing.

  • A remove stays one slot write and hashes no neighbour. The order of the entries changes only at a rehash.
  • It costs more elsewhere: +15.9 KB of release text (87 monomorphs of a cold make_room), one in-place rehash for every 0.4 x capacity inserts or more, and one more doubling for a map that stays over 40% full.
  • 6 of its 12 unit tests pin the insert-only layout, the growth points and the reserved capacities against a plain model. They pass on main and do not depend on the design.

…nd 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.
Comment thread src/collections/zig_hash_map.rs Resolved

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I reviewed the latest push and found no bugs; because this swaps the delete algorithm of a map shared by ~75 source files and changes post-removal iteration order, a human look at the consumer side is still worthwhile.

What was reviewed:

  • remove_by_index backward shift: the condition (hole - home) & mask < (next - home) & mask matches Algorithm R, metadata stays consistent (each moved-from slot becomes the next hole and the final hole is set SLOT_FREE), and the walk always terminates because the taken slot guarantees a None in the table even before the 80% load bound.
  • Dropping the probe limit in get_index/get_or_put_slot: safe since no tombstone can exist and load never reaches 100%, so every run ends at a free slot.
  • Remove-during-iteration hazards: iterators borrow the map, so the borrow checker rules out shifting entries under a live iterator; pointer-locking users (SavedSourceMap, StandaloneModuleGraph) store copied pointer values, not pointers into slots. No remaining references to the deleted tombstone helpers in src/.
  • Console: time/timeEnd/timeLog/countReset keep the same observable behavior with remove in place of take()/zeroing; count_argument handles NaN/Infinity/negatives via clamp then saturating cast.
Extended reasoning...

The change replaces tombstone deletion with backward-shift deletion in bun_collections::HashMap (src/collections/zig_hash_map.rs), makes console.timeEnd and countReset remove their entries in src/jsc/ConsoleObject.rs, and adds two bun:internal-for-testing probes plus unit and JS tests. It touches no auth, crypto, or input-parsing surface; the only JS-facing input is the test-only probe's two numeric arguments, which are coerced and clamped. The algorithm and console changes check out, and the three concerns from the prior run (non-number coercion, u64 counter, live==0) are addressed in the current code. The reason to defer rather than approve is scope: the map is a hot shared utility and removals now reorder entries, which the author claims no consumer depends on but which I could not exhaustively confirm, and cargo could not be run in this environment to execute the new unit tests. No CODEOWNERS entry covers the changed files and the hunt ran dry.

@robobun robobun changed the title Delete from HashMap by backward shift; console.timeEnd and countReset free their entry Delete from HashMap by backward shift, free the entry in console.timeEnd and countReset Oct 1, 2026
- `$newRustFunction` is gone on main. The two probes are now
  `ConsoleObject.bind.ts` and `hash_map_testing.bind.ts`.
- main added `HashMap::retain`. A backward-shift removal can move the
  next entry of the run into the slot that the scan is at. The scan now
  starts behind a free slot and looks at a slot again after a removal,
  so `keep` still sees each entry once. The model test covers it.
`ConsoleObject.bind.ts` and `hash_map_testing.bind.ts` hold test probes
only, so the published types call them nothing.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I reviewed the latest push (bindgen port of the two probes, the retain rewrite) and found no bugs; since this swaps the delete strategy of the shared bun_collections::HashMap under every caller in the tree, a human look is still worthwhile.

What was reviewed:

  • remove_by_index backward shift: the wrapping_sub & mask distance test handles wrap-around (hole at the last slot, home at slot 0) and the home-equals-hole case; the walk terminates because the 80% load cap guarantees a free slot, which is also why dropping the probe limit in get_index/get_or_put_slot is safe.
  • retain: starting one past a free slot and re-checking the same index after a removal keeps "keep called exactly once per entry", since a shift only moves entries into the hole or later slots; the model test counts calls to confirm this.
  • Earlier inline concerns on hash_map_testing.rs are addressed in code: enforceRange in the .bind.ts schema replaces the raw to_int32, the comparison counter is a u64, and live == 0 skips the churn loop.
  • Searched for raw pointers into map values held across a removal (the one property tombstones gave that backward shift does not); the only from_mut(value_ptr) site in bundle_v2.rs writes back before any map mutation.
Extended reasoning...

The change replaces tombstone deletion with backward-shift deletion in src/collections/zig_hash_map.rs, which every bun_collections::HashMap user in src/ inherits, and makes console.timeEnd/countReset remove their table entry; it adds two bindgen test probes (ConsoleObject.bind.ts, hash_map_testing.bind.ts) and tests in test/internal/hash-map.test.ts and test/js/web/console/console-timeLog.test.ts. It touches no security-sensitive surface. The decisive facts for defer rather than approve are that a removal now reorders the surviving entries of a run for all callers (the PR itself names http2 stream-close order and install registry scope selection as observable), and the unsafe vm_console deref in the new probe, which are design-level trade-offs a maintainer should weigh even though the algorithm and tests check out.

@robobun

robobun commented Nov 17, 2026

Copy link
Copy Markdown
Collaborator Author

Closing as stale: this PR conflicts with main, and its last commit is from 2026-10-26.

The branch stays, so the work is not lost. To pick it up again, rebase the branch on main and reopen this PR.

@robobun robobun closed this Nov 17, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants