Repository navigation
Conversation
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.
|
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 Commit 199e8a3 merges main 57fe602, because the PR had conflicts. The two test probes are bindgen schemas now. A second defect in the same tables is not fixed here. CI on e90e8e6 (build 133232) is green: 181 of 181 jobs pass. |
|
No actionable comments were generated in the recent review. ℹ️ Recent review info
WalkthroughThe 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. ChangesHashMap deletion and churn
Console table cleanup
Suggested reviewers: Priority: Merge Risk:
|
There was a problem hiding this comment.
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.
…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.
|
Updated 2:27 PM PT - Oct 26th, 2026
✅ @robobun, your commit e90e8e65d1e95637c847e8eec3e3943211a2d4a4 passed in 🧪 To try this PR locally: bunx bun-pr 44280That installs a local version of the PR into your bun-44280 --bun |
|
#44317 moves the three 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
|
…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.
There was a problem hiding this comment.
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_indexbackward shift: the condition(hole - home) & mask < (next - home) & maskmatches Algorithm R, metadata stays consistent (each moved-from slot becomes the next hole and the final hole is setSLOT_FREE), and the walk always terminates because the taken slot guarantees aNonein the table even before the 80% load bound.- Dropping the probe
limitinget_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/countResetkeep the same observable behavior withremovein place oftake()/zeroing;count_argumenthandles 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.
- `$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.
There was a problem hiding this comment.
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_indexbackward shift: thewrapping_sub & maskdistance 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 probelimitinget_index/get_or_put_slotis 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.rsare addressed in code:enforceRangein the.bind.tsschema replaces the rawto_int32, the comparison counter is au64, andlive == 0skips 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 inbundle_v2.rswrites 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.
|
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. |
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, becauseremove_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+revokeObjectURLshows it: 1 us to 27 us a pair.Fix
remove_by_indexcloses the gap by backward shift (Knuth, TAOCP 6.4, Algorithm R). No tombstone exists. A map that never removes keeps its layout.timeEndcallsremove(), as the WHATWG Console Standard says (Remove timerTable[label]).countResetcalls it too. The output does not change.test/js/web/console/console-timeLog.test.ts,test/internal/hash-map.test.ts, 8 unit tests inzig_hash_map.rs, the http2, lockfile and router suites.Option<Timer>stays, becauseget_or_putneedsDefault.Background
bun:internal-for-testingprobes: the defect shows only as memory or time.Downsides
bun.lockuses maps that never remove.Notes
Reproduction (release build 1.4.3-canary, linux x64)
Bun.servehandler, 2,000,000 requests: main 33 MB to 148 MB, this PR 40 MB to 54 MB.console.timecall: 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.countResethad the same growth. The WHATWG text sets the count to 0 incountReset. The nextconsole.countprints 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.Why the map changes in this PR
countResetcarried the commentwe don't delete it because deleting is implemented via tombstoning. A plainremove()intimeEndon the old map trades the memory growth for a scan.remove_by_indexgave 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:hashMapChurnProbe(1000, 100000):maxComparisonsis 1,000 on main (every stored entry) and 6 with this PR. The capacity is 2,048 in both.DenseMapuses the same delete for a linear-probing table.Other maps that remove (release builds, main 367d939 against this PR, interleaved runs, a loaded machine)
URL.createObjectURL+revokeObjectURL, 2,000 live, last 10,000 of 70,000 cycles, 5 roundsnode:http2, one session, after a burst of 5,000 streamsfs.watch+ close after a burst of 20,000 watchersCost of a remove in real runs (entries walked past the removed one, debug build with a temporary counter)
test/js/node/http2/(596 tests)fs.watchand http2 burst probestime+timeEndpair 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.lockonly insert, and a unit test now pins the insert-only order. Thebun pm migrateoutput for the yarn-cli-repo fixture equals its snapshot. The order in whichnode:http2closes 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_urltakes 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.IdentityContextover dense consecutive integers puts all keys in one run, and one remove would walk all of it (100,000 entries at 100,000 live). EveryIdentityContextmap insrc/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:
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
replenish_windowswalks 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."\uD800","\uDC00"and"\uFFFD"become the same bytes. The ASCII labelsrequest-za1_____AXzpBDAF4andrequest-za1_____BXzpBDAF4have the same wyhash. For each groupconsole.countprints 1, 2 where node v26.3.0 prints 1, 1, and acountResetortimeEndof one label ends the other. The first question below decides the fix.bun testkeys by a wyhash of the snapshot name in the same way. Two tests namedrequest-za1_____AAAAAAAAXzpBDAF4suffixandrequest-za1_____BBBBBBBBXzpBDAF4suffixshare one entry: withtoMatchSnapshot()the second test fails on its first run withExpected: "one",Received: "two". It is outside this PR and has no owner.Binary (
llvm-nm -Son release builds. The base binary is 367d939, where both source files equal the merge base.bloatyis not installed on the machine that measured.)removegrows from 978 B to 4,885 B,get_indexshrinks from 11,956 B to 8,053 B.timeEnd+347 B,countReset+370 B.Tests
hashMapChurnProbe(256, 2000)returnsmaxComparisons: 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.retaintest. 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.test/js/node/http2/675 pass.bun-lock,bun-workspaces,bun-pm-why,npmrc, yarn and pnpm lock migration,framework-router,hmr-socket-protocolanddeinitialization: 1,491 pass. The json5, toml, xml, yaml, console andfs.watchdirectories: 6,226 pass.Merge with main (199e8a3, on main 57fe602)
$newRustFunctionis gone on main. The two probes are bindgen schemas now:src/jsc/ConsoleObject.bind.tsandsrc/runtime/hash_map_testing.bind.ts.HashMap::retain. Its callers needkeepto run once for each entry:rebind_to_cleaned_lockfileremaps 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.retainnow starts behind a free slot and looks at a slot again after a removal. With main's loop on this map, main'sretain_shows_each_entry_onceand the three model tests fail.Self-review (10 concerns, 9 addressed: 8 in ea0f7db, 1 in this text)
hash-map.test.tspinnedmaxComparisons: 19, which depends on the integer hash. It now bounds the count at 32.hashMapChurnProberead its arguments asi32, so a value above 2^31 wrapped before the clamp. Its schema now takes an integer in a range.consoleTableSizestook&mut ConsoleObjectfor a read. It now reads through a shared borrow.IdentityContextis only for keys that are hashes. TheIdentityHashdocs allow any integer, so the header now gives the condition: a run stays short only when the hash spreads the keys.countReset. The standard sets the count to 0 there.value % 8 == 0in a unit test fails clippy (manual_is_multiple_of) with--all-targets.Option<Timer>and is neverNonenow.get_or_putneedsDefault,Timerhas none, andentry()probes twice on a miss. One doc line states the invariant.Questions for a maintainer
Bun__ConsoleObject__countsayswe don't want to store these strings, it will take too much memory. With this PR an entry lives only untiltimeEndorcountReset. 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.IdentityContextrefuse keys that are not hashes? The header only says that a run stays short when the hash spreads the keys.Open PRs on the same lines
timeandtimeEndand keep thetake().zig_hash_map.rs. None of them changes the delete.[human-review] gate passed · iteration 0 · 11 files touched
fails on main (without fix)
passes on PR (with fix)
diff hotspot
gate history · 2 passed · 0 rejected · iteration 0
evidence per changed file