Repository navigation
Conversation
… of its caller Http2Session.settings(settings, callback) ran the callback, and the 'localSettings' event of that SETTINGS frame, in the async context that the session was made in. node runs both in the async context of the settings() caller. Each entry of the pending settings queue now holds the async context of its call, and the acknowledgement is delivered in it. A call made while the socket of the session connects keeps the context of the session, as the 'connect' listener that node submits it from does. The entries of settings() and ping() are queued before the frame is submitted, and taken back when nothing was sent. A transport that JS writes to can deliver the acknowledgement inside the submit: each callback now gets its own acknowledgement there. settings() reads its argument before it queues the entry, and destroy() lets go of the entries that got no acknowledgement.
|
Warning Review limit reachedYou've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository. Next included review available in 12 minutes. View limit details
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. Comment |
|
Status: ready for review. Reproduction. Two callers share one session. Each calls
|
|
Updated 6:03 AM PT - Oct 22nd, 2026
✅ @robobun, your commit 18413d8e392f152605fdaad722ace47450a1a7e5 passed in 🧪 To try this PR locally: bunx bun-pr 46463That installs a local version of the PR into your bun-46463 --bun |
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 two things and ruled them out: destroy() clearing the queue without invoking the settings() callbacks matches Node (the callback is never called after destroy), and the cross-ModuleGraph fallback in deliverSettingsAck is the same rule main already applies for every caller, so it is not a regression.
Extended reasoning...
The change is confined to the JS-side SETTINGS/ping queue in src/js/node/http2.ts plus two new test files, with no native code or security-sensitive surface. Inline findings already signal that a human look is needed; this note only records what else was examined.
Additional findings (outside the current diff — GitHub can't attach inline comments there):
-
🟣
src/js/node/http2.ts— A client session that was close()d while still connecting and whose socket then closes keeps every queued settings() callback and its captured async-context frame, although the new comment at src/js/node/http2.ts:6007 promises they are released. #onClose at :5534 nulls #parser before calling destroy(), and the early return at :5910 fires before the clear at :6009, so #pendingSettingsCallbacks is never emptied. Fix: clear #pendingSettingsCallbacks on every teardown path, including this early return and the #onClose path, or move the clear ahead of the :5910 check. [also at: src/js/node/http2.ts:6009 - A client session that was close()d while still connecting and whose socket then closes keeps every queued settings() callback and its captured ALS store for the life of the session object, contrary to the PR's stated guarantee.]Why this was flagged
Trigger: a client calls session.settings(opts, cb) and then session.close() before the socket connects, and the socket emits 'close' without 'error' (user calls socket.destroy() on a createConnection() socket, or the peer closes during the TLS handshake). #onClose at src/js/node/http2.ts:5526-5538 sets this.#parser = null at :5534 and then calls destroy(). destroy() reaches :5910 with #closed true, #connected false and #parser null and returns. The clear at :6009 never runs, so the PendingSettings entries at :1977 with their callbacks and [als, store] frames stay on the session. The PR says destroy() empties the queue so a kept session does not retain the callers' stores, and the comment at :6007 states that guarantee; this path breaks it. Base retained [callback, start] here too, but did not hold async-context frames, which can pin whole request scopes. Remedy: run the queue clear before the :5910 early return, or clear in #onClose next to the parser detach.
Verification: Triggered when settings() is queued, close() is called before the socket connects, and the socket then emits 'close' without a prior 'error'. #onClose nulls #parser (src/js/node/http2.ts:5534) then calls destroy(), which returns at :5910 before the clear at :6009, so the callback and its async-context frame stay on the session. The base already retained the callback on every destroy path.
| if (node && parseInt(nodeVersion, 10) >= 24 && !isMusl) { | ||
| describe("Node.js compatibility", () => { | ||
| test("tests should run on node.js", async () => { | ||
| await using proc = Bun.spawn({ | ||
| cmd: [node, "--test", import.meta.filename], | ||
| stdout: "inherit", | ||
| stderr: "inherit", | ||
| stdin: "ignore", | ||
| }); | ||
| assert.strictEqual(await proc.exited, 0); | ||
| }); | ||
| }); | ||
| } |
There was a problem hiding this comment.
🟡 nit (optional): maintainers lose visibility of the Node compatibility run when node is missing, old, or on musl: the whole describe is not registered, so the file reports only passes. The sibling test/js/node/http2/node-http2-client-close.test.ts:366 registers the test and passes { skip: !node || isMusl } so a skip shows up with a reason. Fix: always register "tests should run on node.js" and use node:test's skip option with a reason string for the node-absent, node < 24 and musl cases.
Why this was flagged
On a CI lane without a node binary of version 24 or newer, or on Alpine, the if (node && parseInt(nodeVersion, 10) >= 24 && !isMusl) guard at test/js/node/http2/node-http2-settings-async-context.test.ts:929 skips registering the describe block entirely. The runner then reports the file as fully passing with no skipped entry, so nobody can tell the Node parity check never ran. The sibling file node-http2-client-close.test.ts:366 uses { skip: !node || isMusl } on a registered test, which surfaces as a skip. The repository review instructions ask for a harness skip mechanism with a reason instead of silently omitting a test. No production behaviour is affected; this is test-reporting consistency only.
Verification: nit. Trigger: any lane where Bun.which("node") is empty, node reports a major < 24, or the runtime is musl. At test/js/node/http2/node-http2-settings-async-context.test.ts:924-941 the describe/test registration sits inside the if, so no test exists and the runner shows only passes with no skipped entry. The sibling node-http2-client-close.test.ts:365-366 always registers the test with { skip: !node || isMusl }.
| const index = pending.lastIndexOf(entry); | ||
| if (index !== -1) pending.splice(index, 1); |
There was a problem hiding this comment.
🟡 (optional) Any program or dependency that patches Array.prototype.lastIndexOf, splice or the array iterator corrupts the SETTINGS and ping queues after this change, where base only depended on push and shift. submitQueued at src/js/node/http2.ts:1957-1958 and settingsSnapshot at :1967 call user-overridable prototype methods on internal state, which the src/js rule forbids for builtins. Fix: use primordial-safe calls for every new site in the diff ($arrayLastIndexOf/$arraySplice style intrinsics or a captured-at-load reference, and ArrayPrototypeSlice.$call or a manual copy for remoteCustomSettings), so a tampered Array.prototype cannot reorder or drop queued acknowledgements.
Why this was flagged
The repository review instructions require $-prefixed intrinsics and primordial-safe calls in src/js builtins and say an explicitly requested check is not style. The diff adds three new sites: pending.lastIndexOf(entry) at src/js/node/http2.ts:1957, pending.splice(index, 1) at :1958, and [...snapshot.remoteCustomSettings] at :1967. A polyfill or test shim that replaces Array.prototype.splice or wraps the array iterator runs for every settings() and ping() call that the native parser rejects, and for every client settings() that passes remoteCustomSettings. If lastIndexOf returns a wrong index, :1958 removes a different caller's entry and every later callback receives the wrong acknowledgement, which is the exact misalignment this PR set out to fix. Base used only .push/.shift on these queues, so the exposed surface grows. Remedy: replace the three new calls with intrinsic or load-captured equivalents.
Verification: pre-existing (nit). Triggering condition: a program replaces Array.prototype.lastIndexOf/splice or the array iterator with a non-spec implementation before an http2 submit fails. src/js/node/http2.ts:1957-1958 and :1967 go through user-overridable Array.prototype methods. The base already routes the identical queues through equally user-overridable .push/.shift, so the diff only widens the set of method names involved.
| function submitQueued(pending: unknown[], entry: unknown, submit: Function, parser, argument) { | ||
| pending.push(entry); | ||
| let sent = false; | ||
| try { | ||
| sent = submit.$call(parser, argument) !== false; | ||
| } finally { | ||
| if (!sent) { | ||
| const index = pending.lastIndexOf(entry); | ||
| if (index !== -1) pending.splice(index, 1); | ||
| } | ||
| } | ||
| return sent; |
There was a problem hiding this comment.
🟣 pre-existing, not blocking: pre-existing: a settings() call the native parser rejects leaves the session believing an acknowledgement is still outstanding, so later close() waits the 250 ms grace timer and the maxOutstandingSettings budget drains for good. submitQueued at src/js/node/http2.ts:1955-1959 removes the queue entry when parser.settings throws, but the callers set #pendingSettingsAck = true and #pendingSettingsAckCount++ before the submit (src/js/node/http2.ts:4768-4774 and 5693-5699) and never roll them back. Fix: when the submit throws or returns false, undo both counters in the same path as the entry removal, on both the client and server settings(). A trigger without getters: settings({ customSettings: { "1e3": 1 } }) passes validateSettings but the native base-10 key parse throws.
A small fix can ride a push you are already making; otherwise a short reply is enough.
Why this was flagged
The user calls session.settings({ customSettings: { "1e3": 1 } }) on a client or server session. validateSettings at src/js/node/http2.ts:217-226 accepts the key because Number("1e3") is the integer 1000. settings() then increments #pendingSettingsAckCount and sets #pendingSettingsAck = true (src/js/node/http2.ts:4768-4773, 5693-5698). The native update_settings calls load_settings_from_js_value, whose parse_int::("1e3", 10) fails (src/runtime/api/bun/h2_frame_parser.rs:4551-4559) and throws ERR_HTTP2_INVALID_SETTING_VALUE before any frame is written. submitQueued's finally removes the queue entry (src/js/node/http2.ts:1956-1959) and the throw propagates to the caller, but the two counters stay. #pendingSettingsAckCount stays one too high, so close() on an idle session takes the scheduleSettingsAckGraceNT 250 ms path (src/js/node/http2.ts:4802, 5887) instead of destroying at once. The base branch has the same exposure; this diff adds the throw-path cleanup in submitQueued but leaves the counters out of it.
Verification: pre-existing. Trigger: any settings() call whose customSettings key passes JS validation but fails the native decimal parse. Both settings() methods set state before the submit (src/js/node/http2.ts:4768-4774, 5693-5699) and submitQueued's finally (:1955-1959) only splices the queue entry, so the exception propagates with the counter and flag left set. Base branch had the identical order with no rollback.
Problem
session.settings(settings, cb)runscband that frame's'localSettings'in the async context the session was made in. Node runs both in the caller's context. The queue entry[callback, Date.now()]holds no context (src/js/node/http2.ts:4740).settings()andping()queue the entry after the write. Overstream.duplexPair()the acknowledgement arrives first, so each callback gets the next call's.Fix
settings()queues[callback, start, context]. The acknowledgement runs the callback, then'localSettings', in that context. A call made while the socket connects keeps the session's context, as in Node.settings()andping()queue the entry before the submit and remove it when nothing was sent.settings()reads its argument first.test/js/node/http2/node-http2-settings-async-context.test.ts(main fails 23 of 36, passes undernode --test), 282 vendored http2 tests.Background
AsyncLocalStoragestores.H2FrameParserbinds each JS handler once, to the session constructor's context.Bun.ModuleGraphis not installed, as on main. node:net: complete a write that waited for the socket in the async context of the write #46141 has the same rule.Downsides
settings()without a callback keeps one array (+51 B) until its acknowledgement. A client call now copies its settings object.settings(cb)round trip: +136 of 25,806 instructions at JIT steady state, +3,818 of 39,422 with the JIT off. Binary: +1,508 B.write()/end()callbacks and'drain'behind the flow-control window differ from Node.Notes
How it was found. A comparison of Bun and Node v26.3.0 found this. Two callers share one session, and each calls
settings({}, cb)inside its ownals.run(). Node prints each caller's own store. Main prints the store of thehttp2.connect()caller for a client session and of thelisten()caller for a server session. Bun 1.3.13 and 1.4.2 do the same, so it is not a regression.What Node does (measured on v26.3.0, source
lib/internal/http2/core.js).'localSettings'event of that frame run in the context of thesettings()call, also for a call without a callback.'localSettings'. A callback that throws skips the event.thisisundefined.settings()copies its argument ({ ...settings }, L1569) before it records the frame.'connect'listener (L1569-L1574), so the callback runs in the context of that event. For the socket thatconnect()makes, that is the context of theconnect()caller.destroy()before the acknowledgement: the callback is never called.What changed, by function (
src/js/node/http2.ts).submitQueued: pushes the entry, calls the native submit, and removes the entry when the submit throws or returnsfalse.settings()andping()of both session classes use it.settingsSnapshot: copies the settings object,customSettingsandremoteCustomSettingsbefore the entry is queued. The parser then reads plain data. Without it, a getter that callssettings()puts its frame on the wire first and its entry in the queue second. The server copied the top level on main already.submitSettings: returns when a getter destroyed the session (Node: L898-L900), picks the context, and keeps an entry for a call without a callback.deliverSettingsAck: installs the context, calls the callback and emits the event, and restores the previous context in afinally. It does not userun()ofinternal/async_context_frame: that one does not restore when the context is already the current one, so a store that the callback enters withenterWith()would stay.destroy(): empties the queue. A destroyed session that a program keeps no longer keeps the callbacks and contexts of its callers.thisof the callback isundefined. On main it is the internal queue entry.Bun.ModuleGraph. A context inside another graph than the running one is not installed. The callback and the event then run where the events of the session run, which is what main does for every caller. #46141 (node:net writes) adds the same rule as
runInSameGraph.Still different from Node, and not changed here.
write()andend()and the'drain'event for data that waits for the flow-control window: 9 of 24 rows of a per-call probe differ from Node (13 on main). The 4 rows that this change moves aresettings(cb)and its'localSettings'on both session classes.'localSettings'run beforesettings()returns (Node: after), andpendingSettingsAckisfalseafter the call (Node:true). The cause is thatsettings()flushes in the call. On main the callback ran later, for the acknowledgement of the next call.settings()call made from a frame listener, inside a read, is still acknowledged one call late. That path is native. node:http2: treat a SETTINGS ACK with no SETTINGS outstanding as a connection error #42519 is open for it.createConnection()socket that still connects, made in another store than the session: Node runs the callback in the store of the socket's connect event, Bun in the store of the session, as on main.'connect'listener of the socket that runs before the listener of the session: the callback runs in that store. Node and main use the store of the session.'uncaughtException'outside the store of its caller, as on main.ping(): its callback ran in the store of its caller on main already. Only the order of the queue changed.Measurements. Linux x64 release builds of main 9634520 with and without this change. The diff is JS only, so the two builds differ in the bundled
node/http2.jsalone.sizetext: 107,350,736 B to 107,352,244 B (+1,508 B). File: +4,096 B (one page). Bundlednode/http2.js: 169,540 B to 171,048 B. No new host function, binding or native code.(count(2N) - count(N)) / Nfrom aperf_eventinstructions:ucounter, median of 7 to 11 interleaved A/B runs. Spread is max minus min of the base runs.perf,valgrindandstraceare not installed in the build container.settings(cb)25,806 to 25,942 (+136, spread 142).settings()25,466 to 25,740 (+273, spread 204).ping(cb)10,957 to 11,053 (+96, spread 889). Insideals.run():settings(cb)+527 of 25,773,settings()+474 of 25,547.settings(cb)39,422 to 43,240 (+3,818, spread 970).settings()37,749 to 43,223 (+5,474, spread 176).ping(cb)26,112 to 26,479 (+367, spread 414). A userland copy of the new code puts about 1,400 of these instructions in the copy of the settings object.settings()orping()(N = 1,000 connect and destroy cycles, JIT off): 1,226,448 to 1,223,889 (-2,559, spread 12,980). The one added call and the one length check are below the noise.heapStats()afterBun.gc(true), 5,000 calls to a peer that never answers):settings(cb)1 Array before and after (73.2 B to 75.8 B),settings()0 to 1 Array (25.2 B to 75.8 B),ping(cb)6 cells before and after.catch syscall write writev sendto sendmsg): 2 persettings()round trip and 2 perping()round trip on both builds.Tests.
node-http2-settings-async-context.test.tsruns underbun testandnode --test, and one of its tests runs the file under Node. Node v26.3.0: 29 of 29 pass. Main: 23 of 36 fail. This branch: 36 of 36 pass (debug and release).async-context/async-context-http2-session-settings.jsis a fixture ofAsyncLocalStorage-tracking.test.ts, which runs each fixture under Node and Bun. It fails on main.!socketcheck ofsubmitSettings, which is equivalent to the!parsercheck after a completedestroy().test-http2-*,test-diagnostics-channel-http2-*andtest-async-local-storage-http*tests, the 5 sequentialtest-http2-*tests, every test file intest/js/node/http2/,AsyncLocalStorage.test.ts,AsyncLocalStorage-tracking.test.ts,async_hooks.node.test.ts, and themodule-graphtests.Self-review, addressed in part.
http2.ts. A shared form belongs next torunInSameGraphof node:net: complete a write that waited for the socket in the async context of the write #46141, which is not merged.close()ends through its grace timer, or that is closed before it connects, keeps its queue as on main.Open PRs that change the same lines. #41322, #43605, #44481 and #44816 change
settings(): each conflict is one to three lines. #43531, #45992, #46036 and #46141 merge clean.The native variant is on the branch
robobun/367e1155-backup-http2-settings.