Repository navigation
chore(sync): merge upstream Bun through 4b02e1031d - #51
Merged
Merged
Conversation
…allback (oven-sh#44250) ### Problem - With nothing else alive, a JS stream piped into a `FileSink` on a pipe stops at the first full drain. Un-awaited `Bun.write(Bun.stdout, new Response(stream))` delivers 4,194,304 of 8,388,608 bytes, exits with code 0, and never settles. - `FileSink::on_write` (`src/runtime/webcore/FileSink.rs:366`) ran its microtask checkpoint before it resumed the pump. The run loop does not count the microtask the pump queues. `on_close` had no checkpoint. ### Fix - `completion_scope()` opens an event-loop scope while a stream is piped in. Its exit is the checkpoint. `on_write` and `on_close` open it before they enter JS. - Correct because a callback from the loop owes a checkpoint for the JS it enters. - Verified: `test/js/bun/util/filesink.test.ts`, seven new tests, 0 of 7 on main. Each scope has a test that fails without it. Also 15 more Linux suites. - Self-reviewed: 6 concerns raised, 5 addressed as proposed, 1 otherwise (Notes). ### Background - The pump (`readStreamIntoSink`) feeds the sink from a JS stream and waits for `ready()` after a short write. A microtask checkpoint runs queued promise reactions. - Considered a drain in the run loop after each poll callback: every loop turn pays. A scope around every `FileSink` poll callback charges plain writers too. ### Downsides - A sink written from script pays 7 more instructions per `on_write` and per `on_close`. `.text` grows by 256 bytes. - An un-awaited `Bun.write` whose stream fails now exits with code 1. Main exits 0 in 9 of 10 runs. - After `proc.unref()`, a stream stdin that can always produce now arrives in full. Main cuts it. <details><summary>Notes</summary> All numbers are from release builds of main ad60a9b and of this branch at 028985b on Linux x64, unless a line says debug. **Repro** (no `beforeExit` listener, no timer, no top-level await): ```js // bun repro.mjs | (sleep 0.4; wc -c) expected 8388608, main prints 4194304 const first = new Uint8Array(4 * 1024 * 1024).fill(97); const chunk = new Uint8Array(64 * 1024).fill(98); let pulls = 0; Bun.write(Bun.stdout, new Response(new ReadableStream({ pull(c) { if (++pulls === 1) return c.enqueue(first); if (pulls <= 65) return c.enqueue(chunk); c.close(); }, }))); ``` **Why main loses the step.** The run loop is `while vm.is_event_loop_alive() { vm.tick(); vm.auto_tick_active(); }` (`src/runtime/cli/run_command.rs`). `auto_tick_active` runs the poll callback. `on_write` drops the loop ref of the poll because the buffer is empty, and `src.ready()` makes the pump read the next chunk. The chunk steps, close steps and error steps of that read are queued with `queueReactionJob` (`src/jsc/bindings/webcore/streams/JSReadRequest.cpp`). The callback returns, nothing is alive, and the loop ends before the next `tick()`. One ref'd timer gives the loop another turn and hides the bug. **The fix itself**, 20 runs per shape. A run counts when every byte arrived and the reaction of the promise ran. | Shape | main | this branch | | --- | --- | --- | | chunks arrive after the pump parked, to a piped stdout | 0 of 20 | 20 of 20 | | the same into a FIFO | 0 of 20 | 20 of 20 | | stream closes while the pump is parked | 2 of 20 | 20 of 20 | | stream fails while the pump is parked | 1 of 20 | 20 of 20 | | direct stream, closed with bytes still buffered | 0 of 20 | 20 of 20 | | small chunk, sink ended against a full socket | 0 of 20 | 20 of 20 | | direct stream that awaits each `flush()` (control) | 20 of 20 | 20 of 20 | **Each scope is needed** (debug+ASAN builds, the seven new tests): | Build | Failing tests | | --- | --- | | main | 7 | | this branch | 0 | | this branch without the scope in `on_write` | 5: chunks to stdout, chunks to FIFO, `beforeExit` count, close, error | | this branch without the scope in `on_close` | 1: sink closed with no source parked | **Microtask checkpoints and `enter()` calls per callback**, from debug logs (`BUN_DEBUG_ALL=1`), constant over 3 runs. The column for main is from a debug build of 1313ca6, where `FileSink.rs` is the same file as on ad60a9b. | Callback | main | this branch | | --- | --- | --- | | drain that resumes the pump | 1 checkpoint, 1 `enter()` | 1 checkpoint, 2 `enter()` | | drain that leaves bytes in the buffer | 0, 0 | 0, 0 | | close, a source had parked | 1, 1 | 1, 3 | | close, no source parked | 1, 1 | 2, 2 | | sink written from script, drain or close | 1, 1 | 1, 1 | On main the one checkpoint of a drain runs before the pump is resumed. On this branch it runs after. **`beforeExit` emissions** for the 8 MiB pump with a listener installed, 10 runs: main 1 to 21, this branch 1 in 10 of 10, Node v26.3.0 1 in 10 of 10. **Cost for a sink written from script.** One `on_write(65536, Drained)` call: 46 instructions on main, 53 on this branch, no `call` instruction in either. One `on_close` call: 28 and 35, 2 `call` instructions in both. Counted with gdb `nexti` on release builds with symbols, identical over 8 calls. Binary size with `size`: `.text` 80,667,862 to 80,668,118, `data` and `bss` equal, the file keeps its size of 80,836,168 bytes. `on_write` grows from 1,302 to 1,530 bytes and `on_close` from 1,860 to 1,983. **Not measured:** `write(2)` calls that return `EAGAIN` per drain. `strace`, `perf` and `valgrind` are not installed where I measured, and under gdb `catch syscall` the writer is so slow that the pipe never fills. **A stream that fails with no handler**, 10 runs. Main: exit code 0 and nothing on stderr in 9 runs, `error: boom` and exit code 1 in 1 run. This branch: `error: boom` and exit code 1 in 10 runs. The same stream awaited at top level gives `error: boom` and exit code 1 on both builds. **`proc.unref()` and a stream stdin**, 10 runs per cell. The child starts to read only after the pump has taken the first chunk. | Stream | main | this branch | | --- | --- | --- | | can always produce | 4,194,304 of 8,388,608 | 8,388,608 | | all data queued and closed before the spawn | 219,264 in 9 of 10 runs | 219,264 in 9 of 10 runs | | produces one chunk, then waits on a promise that never settles | 4,194,304, parent exits | 4,194,304, parent exits | | can always produce, no `unref()` | 8,388,608 | 8,388,608 | This change does not touch `Writable::unref`, which clears the loop ref of the stdin writer also while it holds accepted bytes (second row). What `unref()` must mean for a writer that owes bytes is a decision for a maintainer and relates to oven-sh#33533. No test here uses `unref()`. **Sites that this change leaves alone, and why.** | Site | Reason | | --- | --- | | `on_ready` | The POSIX writer never calls it. It is the `on_writable` slot on Windows, where the unfixed build has no failing case. | | `EndOfFile` arm of `on_write` | No test reaches it with a piped stream on POSIX. | | Windows settle for a borrowed fd, in `end_writer` and in the abort handler | No failing case on Windows. oven-sh#42819 rewrites that code. | | `on_auto_flush` | It runs inside the deferred task queue, where `EventLoop::exit()` does not drain. The task that `run_pending_later` queues just before the resume keeps the loop alive for the next `tick()`. | | Other sinks and other poll owners | Not examined here. | **Other PRs that touch the same lines.** - oven-sh#43761 added a ref guard at the top of `on_close` and merged while this PR was open. This branch contains it: guard first, scope second. Its stdin test passes and the tests here pass. - oven-sh#42032 adds a checkpoint after the `beforeExit` dispatch. On unfixed code with that hunk, six of the seven tests pass, because the loop passes through that dispatch after each drain. The seventh fails: `beforeExit` fires more than once for one stream (8 times in my run). With this change and that hunk together all seven pass. **Self-review.** Concerns raised and what I did: 1. A ref guard in `on_close` repeated oven-sh#43761 without its tests. The proposal was to stack this PR on oven-sh#43761. I removed the guard and did not stack: the scope does not read the sink when it ends, so it does not need the guard. oven-sh#43761 has merged since. 2. A `cfg(windows)` scope in `end_writer` had no failing test and sits in code that oven-sh#42819 rewrites. Removed. 3. A scope and a guard in `on_ready`, and an `EndOfFile` clause in `on_write`, had no failing test. Removed. 4. A gate on `VM::is_entered()` had no failing test. I built the change without the gate and ran a script that closes the sink inside the `Bun.write` call with a microtask already queued. The order of the microtask did not change, because a script frame already runs inside an entered scope. Removed. 5. The predicate also matched a `stdin: "pipe"` sink that script never read, and shell pipes. It now tests only for a piped stream. 6. The tests would pass on unfixed code once oven-sh#42032 lands. Added the test that counts `beforeExit`. **Platforms.** On Windows Server 2019 x64 a debug build of main passes every portable shape, also with a first chunk of 64 MiB and of 256 MiB where the child waits 0.6 to 2.3 s for the reader. So on Windows the five portable tests guard against a regression only. The first revision of the FIFO test read its end with `Bun.file(fd).bytes()`. On macOS that read never finished, 8 of 8 attempts, although the child had exited. The test now reads with `read(2)` in a poll with a deadline, and passes on macOS. **Suites** on the debug build of this branch, 60 s per test, all pass: `filesink` (77 after the merge with main), `bun-write` (86), `spawn-stdin-readable-stream` (4 files, 55), `spawn-streaming-stdin`, `spawn-stdin-destroy`, `spawn-stdin-pipe-fd-leak`, `readablestream-helpers`, `streams` (624), `compression`, `sync-pull-fast-path`, `native-source-onclose-leak`, `direct-readable-stream`, `bunshell` (436). </details> <!-- robobun:evidence:begin --> --- **no test proof** · iteration 4 · platform-specific test(s) that do not run on this machine, deferring to CI, which covers all platforms: test/js/bun/util/filesink.test.ts <!-- robobun:evidence:end -->
…ven-sh#44191) ### Problem - An `https` request through a proxy emits only `'close'` when the connection ends between the `200` of the CONNECT and the end of the TLS handshake. Node emits `'error'` first: `ECONNRESET`, `Client network socket disconnected before secure TLS connection was established`. - `Agent#createSocket` gives the request the failed socket with the error (`src/js/node/_http_agent.ts:354`, `:530`). The TLS layer set `_hadError` on it, so the guard at `src/js/node/_http_client.ts:1076` skips the `'error'`. ### Fix - `Agent#createSocket` passes only the error, as Node does. `https.Agent#createConnection` closes the proxy connection after every `ERR_PROXY_TUNNEL`, which the request did before. `_http_client.ts` does not change. - Correct: a request gets no socket that it did not listen to. 13 of 13 failure routes equal Node v26.3.0 in events, code and tick (base: 0). - Verified: `test/js/node/http/node-http-proxy-url.test.ts`: 23 tests fail without the fix, 22 also under Node. Also 100 vendored Node tests. - Self-reviewed: 8 concerns raised, 8 addressed. ### Background - The forwarding is from oven-sh#31587 ([thread](oven-sh#31587 (comment))), to close a connection that a proxy holds after a refused CONNECT. That thread set aside the close in `createConnection`, which this PR takes. - Considered a guard in the request: one tick after Node, and a custom `createConnection` callback `(err, x)` stays broken. ### Downsides - Not as Node, on purpose: after a refused CONNECT, a direct `https.Agent#createConnection` caller gets a destroyed socket. Node leaves it open. - As in Node: `agent.createSocket()` calls back with `(err)` only. A request with no `'error'` listener throws this `ECONNRESET`. - Not covered: `https-proxy-agent`, `tunnel` and a direct `https` request still report `ERR_SOCKET_CLOSED` (oven-sh#43381, item 4). <details><summary>Notes</summary> #### Reproduction ```js // bun repro.mjs / node repro.mjs import net from "node:net"; import https from "node:https"; const proxy = net.createServer(s => { s.on("error", () => {}); s.once("data", () => { s.write("HTTP/1.1 200 Connection established\r\n\r\n"); s.once("data", () => s.end()); // the ClientHello }); }); await new Promise(r => proxy.listen(0, "127.0.0.1", r)); const agent = new https.Agent({ proxyEnv: { https_proxy: `http://127.0.0.1:${proxy.address().port}` } }); const req = https.get({ host: "example.invalid", port: 443, path: "/", agent }); req.on("error", e => console.log("error:", e.code, e.message)); req.on("close", () => { console.log("close"); proxy.close(); }); ``` ``` node v26.3.0, and bun with this PR: error: ECONNRESET Client network socket disconnected before secure TLS connection was established close bun 1.4.0, 1.4.1, 1.4.2, main 1313ca6 (3 of 3 runs each, linux-x64): close ``` The proxy ends its side with `end()` after it read the ClientHello. A `destroy()` with unread bytes is a reset, which takes another path through the client and was reported before. The proxy does not have to be at fault: a proxy that relays the close of a target that hangs up during the handshake gives the same result. The report also says that the process never exits. No handle is left open: both sockets are closed and `process.getActiveResourcesInfo()` is empty. The awaited promise never settles, and Bun does not exit on an unsettled top-level await (oven-sh#33283). #### Who hits it - The built-in proxy support of `node:https`: `new https.Agent({ proxyEnv })`, the global agent under `NODE_USE_ENV_PROXY=1`, and `http.setGlobalProxyFromEnv()`. - An `http://` proxy connection that ends with the `200` or after it, and an `https://` proxy connection that ends during its own TLS handshake or after its `200`. - A request that waited behind `maxSockets`. - No proxy: a custom `Agent#createConnection` that calls back with `(err, socket)`. With a second argument that has no `destroy()` the process ended with `TypeError: socket.destroy is not a function`. The request destroyed a live socket that it was given this way. Node leaves the second argument alone. Not this bug: `https-proxy-agent`, `tunnel` and a direct `https` request, where the request writes to the TLS socket before the handshake is done. They report `ERR_SOCKET_CLOSED` where Node reports `ECONNRESET`, before and after this PR. That is item 4 of oven-sh#43381, and oven-sh#43392 is the open PR for it. #### The earlier decision in oven-sh#31587 The review thread of oven-sh#31587 found that a proxy which refuses the CONNECT and holds the connection left that connection open, as in Node. It named two ways: forward the socket from the Agent to the request (taken, d677423), or close the connection in `cleanupAndPropagate` for every error (set aside as further from upstream). The forwarding applies to every failed socket creation, not only to a refused CONNECT. So the request also gets the sockets that the TLS layer already marked, and loses its `'error'`. With this PR the Agent is Node's text again, and the one line that differs from Node is the condition in `cleanupAndPropagate`. The test that oven-sh#31587 added for the held connection passes with no change to its assertions. Node has the same guard since nodejs/node#61770. With an agent whose `createSocket` calls back with `(err, socket)` and a socket that the peer ended during the TLS handshake, Node v26.3.0 also emits only `'close'`. So the forwarding cannot go upstream as it is. Node v26.3.0 leaves the held connection open. #### Measurements Release builds of 1313ca6 and of the three source expressions of this PR on it, linux-x64, and Node v26.3.0. `_http_agent.ts`, `https.ts` and `_http_client.ts` are the same at 1313ca6 and at the base of this branch. Every count is the same in 5 of 5 runs. - builtin JS text: `_http_agent.js` -13 B, `https.js` -33 B, `_http_client.js` 0 B (`wc -c`, `cmp`: identical). bun binary text+data -46 B (`size`: text 80662588 to 80662542, data 110424). - success path: 0 changed bytecode instructions. `onSocketReady` 47, `onSocketCreatedForPending` 45, `cleanupAndPropagateImpl` 36 instructions (base 48/47/38, JSC bytecode dump). - successful request, `nextTick` entries / listener registrations on the socket / `bind` calls, from the moment the Agent has the socket to the `'socket'` event: http 2/9/1, keep-alive 1/5/1, https 2/10/1, tunnel 2/9/0. Base and PR are identical. `createSocket` reported an error 0 of 800 times. - failed creation, `nextTick` entries / listener registrations on the failed socket, from the failure callback to the `'close'` of the request: FIN 1/0 (base 2/1, node 1/0), held 407 1/0 (base 3/1, node 1/1). - 13 of 13 failure routes equal Node v26.3.0 in events, error code and `nextTick` turn (base 0 of 13). FIN routes: `'error'` and `'close'` at turn 1/1 (node 1/1, base no `'error'`, `'close'` at turn 2). The message equals Node's on 11 of 13. The other 2 are texts of the TLS library, the same before and after. - held non-200 CONNECT: the proxy connection is closed for 7 of 7 callers (node 0, base 2) and for 5 of 5 status lines without a code. A direct `createConnection` caller sees `socket.destroyed === true` in its callback (node `false`, base `false`). - custom `createConnection` `cb(err, x)`: 16 of 16 rows equal Node (base 0 of 16), `destroy()` is called on `x` 0 times (node 0, base 8), 0 rows end in an uncaught exception (base 10). The callback of `agent.createSocket()` gets 1 argument after a failure (node 1, base 2). The 13 routes: FIN after the ClientHello, `200` with the FIN, `https://` proxy FIN during its handshake, `https://` proxy `200` then FIN, held 407, 500, RST after the `200`, bytes that are not TLS after the `200`, certificate error, end before the `200`, tunnel timeout, request queued behind `maxSockets`, global agent with `NODE_USE_ENV_PROXY=1`. The 7 callers: a request through the agent, a request queued behind `maxSockets`, `agent.createSocket()`, a subclass that passes on only the error, the `createConnection` option of a request, `agent.createConnection()` with a callback and without one. #### Behavior that changes besides the fix - `'close'` of a request comes one `nextTick` turn earlier after every failed socket creation, on the turn where Node emits it. - The request does not call `destroy()` on what a custom `createConnection` passes with an error. - A subclass that overrides `createSocket` and calls back with `(err, socket)` for a request that waited behind `maxSockets`: the request emits `'error'`, then `'close'`, and does not call `destroy()` on that socket. Before, it emitted only `'close'` when the socket had `_hadError`, and destroyed the socket. The subclass owns that socket now, as in Node. - After a CONNECT reply with a status line that has no usable code (for example `HTTP/1.1 abc`), a direct caller of `createConnection` gets a destroyed socket, as in Node. #### Left as it is - `req.onSocket(socket, err)` called directly with a socket that has `_hadError`, and a subclass that overrides `createSocket` and calls back with `(err, socket)` for a request that did not wait: only `'close'`, also in Node. - The `createConnection` option of a request that reports an error through its callback: `'error'` and no `'close'`, also in Node. - A tunnel that is still pending: while the proxy does not answer the CONNECT, `req.destroy(err)`, `req.abort()`, an aborted signal and `agent.destroy()` emit no `'error'` and no `'close'`, and the proxy connection stays open. When the proxy closes, the request reports `ERR_PROXY_TUNNEL`. Node v26.3.0 does the same. - Two changes of Node's tunnel code after v26.3.0 are not ported here: the limit on the headers of the CONNECT reply (nodejs/node 84e367579e) and the handling of TLS options that `tls.connect()` rejects (nodejs/node#66096). Both are separate work. - Error messages of the TLS library differ from Node's (`WRONG_VERSION_NUMBER`, `self signed certificate`). - `agent.sockets[name]` is deleted after a failed creation. Node keeps an empty array. #### Tests - `test/js/node/http/node-http-proxy-url.node.mts` runs under Node and under Bun. 22 new tests: 4 ways a proxy connection ends, a destroyed and an aborted request, `new http.ClientRequest`, `http.setGlobalProxyFromEnv()`, `diagnostics_channel`, a queued request, 5 tests of a refused CONNECT, 7 of a creation callback with an error and a second argument. 6 of them also assert the `nextTick` turn of `'error'` and `'close'`. - `test/js/node/http/node-http-proxy-url.test.ts`: the global agent with `NODE_USE_ENV_PROXY=1`, in a child process. - linux-x64, debug build. With the fix: 32 of 32 in the dual file (Node v26.3.0: 32 of 32) and 4 of 4 in the wrapper. Without the fix: the 22 and the 1 fail. - Each source edit alone, reverted on a debug build: `_http_agent.ts:350` 17 tests fail, `:524` 1 test fails, `https.ts` 5 tests fail. With `req.onSocket` one `nextTick` late, the 6 turn assertions fail. - CI build 121492 at 6c55f8a ran `node-http-proxy-url.test.ts` and `node-http.test.ts` on every lane, and both pass at the first attempt: Linux glibc and musl, macOS and Windows, each on x64 and arm64, and the ASAN lane. The Node run reports 32 of 32 on each lane. - Windows x64, without the fix: the canary a7c73fd prints only `close` for the reproduction. - Unchanged and passing on linux-x64: `node-http.test.ts` (263 pass), `node-https-agent-checkserveridentity-reuse.test.ts` (30), `node-http-agent-free-socket.test.ts` (9), `node-http-client-request-gc.test.ts`, `trace-events.test.ts`, the two Agent tests of `module-graph-io.test.ts`. - Vendored Node tests: 100 of 101 pass (`test-https-proxy-request-*`, `test-http-proxy-request-*`, `test-http-agent*`, `test-https-agent*`, `test-http-client-abort*`, `test-http-set-global-proxy-from-env-*`, `test-tls-over-http-tunnel`, and more). `test-http-agent-keepalive.js` fails on a debug build with and without this change. </details> <!-- robobun:evidence:begin --> --- **no test proof** · iteration 1 · platform-specific test(s) that do not run on this machine, deferring to CI, which covers all platforms: test/js/node/http/node-http.test.ts <!-- robobun:evidence:end -->
…erSocket::halfClose() (oven-sh#44243) ### Problem - The native `end()` of the `node:http` server socket holds its half-close sequence inline (`jsFunctionNodeHTTPServerSocketEnd`, `src/jsc/bindings/node/JSNodeHTTPServerSocketPrototype.cpp:313`). - The next PR of this stack calls the same sequence from the drain gate of uWS, for a `socket.end()` that waited for buffered bytes. A second copy can drift from the first. ### Fix - Move the sequence into `JSNodeHTTPServerSocket::halfClose()`. The move is verbatim: pause the reads, write with `ended` set (this sends the FIN), resume the reads. - `jsFunctionNodeHTTPServerSocketEnd` calls it and returns its value, as before. - Remove the `us_socket_pause` and `us_socket_resume` declarations from the prototype file. They have no user there now. - Verified: the existing suites, unchanged, on a release build of this commit. The Notes block has the list and the counts. Behaviour change: none ### Background - A half-close sends the FIN and keeps the socket open for reads. `socket.end()` in Node is a half-close. - The reads must be armed after the shutdown. If they are not, the server does not see the FIN of the peer, and the socket never closes (oven-sh#34356). - This is PR 1 of 2. oven-sh#44244 is PR 2. The alternative was a second inline copy of the sequence for the new caller. ### Downsides - None found. Checked the release builds of main 9f70da0 and of this commit (Linux x64). The compiler inlines `halfClose()`: `jsFunctionNodeHTTPServerSocketEnd` goes from 633 to 671 bytes, and from 192 to 191 instructions. `.text` (58148853 bytes) and the binary (80832072 bytes) do not change. <details><summary>Notes</summary> All runs are on Linux x64, on release builds of main 9f70da0 and of this commit 7c98ad5. | Suite | Result on this commit | |---|---| | `test/js/node/http/node-http-server-socket-end-drain.test.ts` | 9 pass | | `test/js/node/http/node-http-connect.test.ts` | 61 pass, 2 todo | | `test/js/node/http/node-http-backpressure.test.ts` | 83 pass | | `test/js/node/http/node-http-pinned-write.test.ts` | 10 pass | | `test/js/node/http/node-http-server-close-drain.test.ts` | 28 pass | | `test/js/node/http/node-http.test.ts` | 263 pass, 1 skip | | 43 files of `test/js/node/test/parallel/` (`test-http-*`, `test-https-*`) that start a server and end, pipeline or write on its socket | 43 exit 0 (main: 43) | A debug build with ASAN of this commit alone did not run. The same suites ran on a debug build with ASAN of the second PR of the stack, which contains this change. They pass there, apart from three timeouts from the load of the host. Each of those three tests passes alone. oven-sh#44244 has the list. Method for the sizes: `llvm-nm -S` and `llvm-objdump -d` on `bun-profile`, `llvm-size -A` for `.text`. Every other function of the socket binding and of `HttpContext` has the same bytes in both builds. </details>
…tor cannot grow (oven-sh#42929) ### Problem - `Bun.sliceAnsi` and `Bun.stripANSI` each abort on a legal input: `panic(main thread): abort() called`, exit 134. Fuzzing found both, with no user report. - `sliceAnsi` keeps one 24-byte `Vector` entry (`pending`, `src/jsc/bindings/sliceAnsi.cpp:1257`) for each escape sequence that waits for the next visible character. `Vector::append` calls `CRASH()` at the 77,731,543rd: 78 MB of lone `\x9c` bytes. - `stripANSI` writes into a `Vector<Char>` as long as the input (`src/jsc/bindings/stripANSI.cpp:48`). A 16-bit string of 2^30 code units passes `INT32_MAX` bytes, so `Vector::grow` calls `CRASH()`. Bun 1.3.12 returns it (Notes). ### Fix - `sliceAnsi`: both lists grow with `tryAppend` behind `Bun::maxVectorSize<T>()`. On failure the binding throws `RangeError: Out of memory`, as oven-sh#42833 and oven-sh#42649 do. - `stripANSI`: the buffer is a `String` from `String::tryCreateUninitialized`, which holds every legal string, so the 2^30 input returns again. A failed allocation throws the same `RangeError`. - Outputs that fit do not change: 1.8 million seeded random calls match. The `String` buffer adds no copy (Notes). - Verified: `test/js/bun/util/sliceAnsi.test.ts` (1 new test), `test/js/bun/util/stripANSI.test.ts` (2 new tests). All 3 fail without the fix. The other ANSI suites pass (Notes). ### Background - `WTF::Vector<T>` holds `INT32_MAX / sizeof(T)` elements and grows by half. Past that, `append` and `grow` call `CRASH()` and `tryAppend` returns false. - A `WTF::String` holds 2^31 - 1 characters, 4 GiB when 16-bit. - A sequence waits in `pending` until the next visible character shows whether it is inside a grapheme cluster or past the range. - `Bun::maxVectorSize<T>()` is the `Vector` bound, lowered by `Bun__stringSyntheticAllocationLimit`. The tests set that to 64 KiB in a child. <details><summary>Notes</summary> **Repros, release builds on Linux x64: `main` against this branch** ```js // 1. Before: exit 134 at 4.7 GB peak. After: RangeError in 3.3 s, 4.6 GB. Bun.sliceAnsi("a" + "\x9c".repeat(77731543) + "b", 0, 2); // 77,731,542 sequences return the whole string before and after. "\x1b[m" gives the same counts (233 MB, 5.4 GB). // 2. Before: exit 134 after 2.3 s, 4.3 GB peak. After: returns 2^30 characters in 5.7 s, 8.4 GB peak. Bun.stripANSI("\x1b[31m" + "\u3042".repeat(2 ** 30)); ``` - In repro 2 the input takes 4 GiB (the repeated string and the flat copy of the rope). The buffer and the result take 2 GiB each. **Where each number comes from** - A `Pending` entry is 24 bytes, so the largest legal capacity is 89,478,485. `FastMalloc::nextCapacity` grows a full `Vector` from 77,731,542 to 116,597,313, which passes it. `tryAppend` refuses at the same step. `maxVectorSize` binds only when a test lowers the limit. oven-sh#42833 has the same property. - `pendingHl` has one 24-byte tuple for each waiting hyperlink. It is never longer than `pending`, so the `pending` check covers its bound. Its `tryAppend` covers a failed allocation. - `SgrStyleState::entries` stays as it is. It holds one entry for each attribute slot, and `parseSgrParams` clamps a parameter below 1,000,000. **When stripANSI started to abort** - oven-sh#28767 (in 1.3.12) replaced the `StringBuilder` with `Vector<Char>::grow(input.size())`. At that time `isValidCapacityForVector` accepted `UINT_MAX / sizeof(T)` elements, so the `Vector` held every legal string. - The WebKit upgrade oven-sh#29161 (in 1.3.13) halved that bound to `(UINT_MAX >> 1) / sizeof(T)`. Bun 1.3.12 returns repro 2 and Bun 1.3.13 aborts. - `sliceAnsi` has had `pending` since oven-sh#26963 added the function. The old bound only moved its abort to a higher count, so that half was never correct. No issue exists for either, so the tests are in the module test files. **The String buffer adds no copy** - `StringImpl::adopt(Vector&&)` moves the buffer only when the `Vector` allocator is `StringImplMalloc` (`wtf/text/StringImpl.h`). That is `FastCompactMalloc`, and a plain `Vector<Char>` uses `FastMalloc`, so it takes the `create(vector.span())` branch and copies. - The old path was `fastMalloc`, a `fastRealloc` in `shrinkToFit()` when the output was under half of the input, then that copy. The new path is `tryCreateUninitialized` for the buffer, then a copy into a second `tryCreateUninitialized` string of the exact length. Both allocations are fallible, so a failure of the second one also throws. - I also measured `StringImpl::tryReallocate` in place of the copy. It saves the copy for a large input with few sequences, and it keeps up to a third of slack on a small result. The copy keeps the memory of each result as it is today, so this PR uses the copy. **Benchmark of stripANSI**: release builds of `main` (b841a68) and of this change on it, LLVM 21, minimum of 6 interleaved runs. The runs are from before a293e34, which replaced `String(span)` with the same allocation and copy in a fallible form. | input (characters in, out) | `main` | this PR | |---|---|---| | SGR, 8-bit (19, 9) | 90.5 ns | 73.7 ns | | SGR, 16-bit (19, 9) | 87.2 ns | 69.4 ns | | hyperlink (44, 9) | 87.6 ns | 71.6 ns | | mixed SGR (69, 41) | 131.9 ns | 122.6 ns | | one escape (1,005, 1,000) | 286.1 ns | 258.5 ns | | one escape (64,005, 64,000) | 7.98 us | 7.72 us | | dense SGR (5,600, 1,600) | 14.22 us | 14.30 us | | dense SGR (212,992, 49,152) | 404.6 us | 408.9 us | | dense SGR, 16-bit (212,992, 49,152) | 421.2 us | 408.2 us | | no escape (16,384) | 175.5 ns | 176.1 ns | - A `sliceAnsi` benchmark (dense SGR, hyperlinks, 100 waiting sequences between characters) is within 2% of `main`. **No change for outputs that fit** - A seeded generator builds inputs from SGR, OSC 8, C1, unterminated and malformed sequences, control bytes, wide, zero-width, combining and surrogate characters. It calls `stripANSI` once and `sliceAnsi` three times for each input, with random ranges and ellipses. - A hash of 1.8 million results is equal on the two release builds. The debug ASAN build of this branch gives the same hash for the first 600,000. **The tests** - Two tests run a child with `BUN_FEATURE_FLAG_SYNTHETIC_MEMORY_LIMIT=65536`, the knob the oven-sh#42649 and oven-sh#42833 tests use. The bounds become 2730 waiting sequences and a buffer of 65,536 characters. - Each bound has an input that sits exactly at it and returns, and the same input one element longer, which throws: SGR sequences (Latin-1 and UTF-16), lone C1 ST bytes, hyperlinks, and the `stripANSI` buffer (Latin-1 and UTF-16). More cases: sequences at the end of the input, runs under the bound with visible characters between them, sequences before the range, and an input over the limit with nothing to strip. - Without the fix every input returns its normal length, so the failure is an assertion diff and not an abort. - The third test runs `stripANSI` at the real size: a 16-bit string of 1,073,741,826 code units. Every code unit is inside an `ESC ( x` sequence, so the output is empty and the child never writes to the buffer. It needs 2.2 GB (2.4 GB and 6 s in a debug ASAN build), and it skips under 8 GiB of memory, as `utf8-conversion-limit.test.ts` does. Without the fix the child exits with SIGABRT. - No test runs `sliceAnsi` at its real size (4.6 GB). - Other suites run on the debug ASAN build: `sliceAnsi-fuzz`, `wrapAnsi`, `wrapAnsi.npm`, `stringWidth`, and the rest of `sliceAnsi` and `stripANSI`. **Not changed here: `Bun.sliceAnsi` aborts that are not a `Vector`** oven-sh#42931 tracks them. All five exit 134 on a release build of this branch. - The result fits, and a `StringBuilder` doubles its capacity past the longest 16-bit string. oven-sh/WebKit#631 (open) fixes the builder. - `Bun.sliceAnsi("\u3042".repeat(2 ** 30), 0, 4)`: `result.reserveCapacity(input.size())` (`sliceAnsi.cpp:876`) reserves 2^30 8-bit characters, and the first 16-bit append converts the buffer. 2.2 GB, for a result of 2 characters. - `Bun.sliceAnsi("\x1b[31m" + "a".repeat(2 ** 30), 0, 4, "\u2026")`: the same, and the ellipsis is the first 16-bit append. 2.2 GB, for a result of 14 characters. - `Bun.sliceAnsi("\x1b]8;;" + "\u3042".repeat(2 ** 30) + "\x07x", 0, 1)`: the builder of one hyperlink in `parseHyperlink` (`sliceAnsi.cpp:572`). 8.6 GB. - The result passes the string length limit. This is the `sliceAnsi` sibling of oven-sh#42225 (`wrapAnsi`, open). - `Bun.sliceAnsi("\x1b[31m" + "a".repeat(2 ** 31 - 6), 1)`: `StringBuilder result`. 6.5 GB. - `Bun.sliceAnsi("a".repeat(2 ** 31 - 2), 1, undefined, "\u2026" + "\u200b".repeat(10))`: `makeString` on the ASCII fast path (`sliceAnsi.cpp:1400`). 2.2 GB. **Self-review** - Changes made after it: exact-bound test cases, the real-size `stripANSI` test, one-line comments, the list above, and the 1.3.12 to 1.3.13 account. - After the bot reviews: the exact-length copy in `stripANSI` is fallible too (a293e34). - Deferred: a `sliceAnsi` that needs no list (it scans the waiting run again when the next visible character arrives). That removes the throw. It touches the hot loop, so it is a PR of its own. - oven-sh#42908 (open) edits other lines of `stripANSI.cpp`. Whichever lands second needs a small rebase. </details> <!-- robobun:evidence:begin --> --- **[human-review]** gate passed · iteration 0 · 4 files touched <details><summary>fails on main (without fix)</summary> ```console ASAN without fix: 3 FAILED $ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/pr_gate.xml" test/js/bun/util/sliceAnsi.test.ts test/js/bun/util/stripANSI.test.ts bun test v1.4.3 (09bb546) test/js/bun/util/stripANSI.test.ts: (pass) Bun.stripANSI > returns same string object when no ANSI sequences present [171.84ms] (pass) Bun.stripANSI > returns new string when ANSI sequences are removed [2.47ms] (pass) Bun.stripANSI > "\u001b[31mred\u001b[39m" [2.01ms] (pass) Bun.stripANSI > "\u001b[32mgreen\u001b[39m" [0.85ms] (pass) Bun.stripANSI > "\u001b[33myellow\u001b[39m" [0.29ms] (pass) Bun.stripANSI > "\u001b[34mblue\u001b[39m" [0.30ms] (pass) Bun.stripANSI > "\u001b[35mmagenta\u001b[39m" [0.37ms] (pass) Bun.stripANSI > "\u001b[36mcyan\u001b[39m" [0.26ms] (pass) Bun.stripANSI > "\u001b[37mwhite\u001b[39m" [0.28ms] (pass) Bun.stripANSI > "\u001b[41mred background\u001b[49m" [0.30ms] (pass) Bun.stripANSI > "\u001b[42mgreen background\u001b[49m" [0.26ms] (pass) Bun.stripANSI > "\u001b[1mbold\u001b[22m" [0.26ms] (pass) Bun.stripANSI > "\u001b[2mdim\u001b[22m" [0.27ms] (pass) Bun.stripANSI > "\u001b[3mitalic\u001b[23m" [0.26ms] (pass) B ... (truncated) release without fix: all passed bun test v1.4.3-canary.1 (ee97718) test/js/bun/util/stripANSI.test.ts: (pass) Bun.stripANSI > returns same string object when no ANSI sequences present [2.25ms] (pass) Bun.stripANSI > returns new string when ANSI sequences are removed [0.05ms] (pass) Bun.stripANSI > "\u001b[31mred\u001b[39m" [0.02ms] (pass) Bun.stripANSI > "\u001b[32mgreen\u001b[39m" (pass) Bun.stripANSI > "\u001b[33myellow\u001b[39m" (pass) Bun.stripANSI > "\u001b[34mblue\u001b[39m" (pass) Bun.stripANSI > "\u001b[35mmagenta\u001b[39m" (pass) Bun.stripANSI > "\u001b[36mcyan\u001b[39m" (pass) Bun.stripANSI > "\u001b[37mwhite\u001b[39m" (pass) Bun.stripANSI > "\u001b[41mred background\u001b[49m" (pass) Bun.stripANSI > "\u001b[42mgreen background\u001b[49m" (pass) Bun.stripANSI > "\u001b[1mbold\u001b[22m" (pass) Bun.stripANSI > "\u001b[2mdim\u001b[22m" (pass) Bun.stripANSI > "\u001b[3mitalic\u001b[23m" (pass) Bun.stripANSI > "\u001b[4munderline\u001b[24m" (pass) Bun.stripANSI > "\u001b[5mblink\u001b[25m" (pass) Bun.stripANSI > "\u001b[7mreverse\u001b[27m" (pass) Bun.stripANSI > "\u001b[8mhidden\u001b[28m" (pass) Bun.stripANSI > "\u001b[9mstrikethrough\u001b[29m" (pass) Bun.stripANSI > "\u001b[38;5;1 ... (truncated) ``` </details> <details><summary>passes on PR (with fix)</summary> ```console ASAN with fix: all passed $ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/pr_gate.xml" test/js/bun/util/sliceAnsi.test.ts test/js/bun/util/stripANSI.test.ts bun test v1.4.3 (09bb546) test/js/bun/util/stripANSI.test.ts: (pass) Bun.stripANSI > returns same string object when no ANSI sequences present [188.15ms] (pass) Bun.stripANSI > returns new string when ANSI sequences are removed [2.74ms] (pass) Bun.stripANSI > "\u001b[31mred\u001b[39m" [2.55ms] (pass) Bun.stripANSI > "\u001b[32mgreen\u001b[39m" [0.48ms] (pass) Bun.stripANSI > "\u001b[33myellow\u001b[39m" [0.32ms] (pass) Bun.stripANSI > "\u001b[34mblue\u001b[39m" [0.28ms] (pass) Bun.stripANSI > "\u001b[35mmagenta\u001b[39m" [0.36ms] (pass) Bun.stripANSI > "\u001b[36mcyan\u001b[39m" [0.28ms] (pass) Bun.stripANSI > "\u001b[37mwhite\u001b[39m" [0.26ms] (pass) Bun.stripANSI > "\u001b[41mred background\u001b[49m" [0.30ms] (pass) Bun.stripANSI > "\u001b[42mgreen background\u001b[49m" [0.28ms] (pass) Bun.stripANSI > "\u001b[1mbold\u001b[22m" [0.62ms] (pass) Bun.stripANSI > "\u001b[2mdim\u001b[22m" [0.28ms] (pass) Bun.stripANSI > "\u001b[3mitalic\u001b[23m" [0.25ms] (pass) B ... (truncated) release with fix: all passed $ bun scripts/build.ts --profile=release [configured] bun-profile → bun (stripped) in 709ms (unchanged) ninja: Entering directory `/workspace/bun/build/release' [1/8] gen cpp.rs (cppbind) [1/8] cargo bun_runtime → libbun_runtime.a �[1m�[33mwarning�[0m�[1m: binary `bun_shim_impl` should have a kebab-case name�[0m �[1m�[94m|�[0m �[1m�[94m 1�[0m �[1m�[94m|�[0m /workspace/bun/build/release/rust-target/.../bun_shim_impl �[1m�[94m|�[0m �[1m�[33m^^^^^^^^^^^^^�[0m �[1m�[94m|�[0m �[1m�[94m= �[0m�[1mnote�[0m: `cargo::non_kebab_case_bins` is set to `warn` by default �[1m�[96mhelp�[0m: to change the binary name to `bun-shim-impl`, convert `bin.name` �[1m�[94m--> �[0msrc/install/windows-shim/Cargo.toml:41:8 �[1m�[94m|�[0m �[1m�[94m41�[0m �[91m- �[0mname = �[91m"bun_shim_impl"�[0m �[1m�[94m41�[0m �[92m+ �[0mname = �[92m"bun-shim-impl"�[0m �[1m�[94m|�[0m �[1m�[33mwarning�[0m: `bun_shim_impl` (manifest) generated 1 warning �[1m�[33mwarning�[0m�[1m: `feature(generic_const_exprs)` is not supported with the next-generation trait solver�[0m �[1m�[94m--> �[0msrc/shell_parser/lib.rs:1:30 �[1m�[94m|�[0m �[1m�[94m1�[0m ... (truncated) ``` </details> <details><summary>diff hotspot</summary> ``` src/jsc/bindings/sliceAnsi.cpp | 30 ++++++++------ src/jsc/bindings/stripANSI.cpp | 42 +++++++++++--------- test/js/bun/util/sliceAnsi.test.ts | 73 ++++++++++++++++++++++++++++++++++ test/js/bun/util/stripANSI.test.ts | 81 ++++++++++++++++++++++++++++++++++++++ 4 files changed, 196 insertions(+), 30 deletions(-) ``` </details> **gate history** · 2 passed · 0 rejected · iteration 0 <details><summary>evidence per changed file</summary> ``` file reads edits tests src/jsc/bindings/sliceAnsi.cpp 8 6 26 src/jsc/bindings/stripANSI.cpp 5 12 26 test/js/bun/util/sliceAnsi.test.ts 2 2 17 test/js/bun/util/stripANSI.test.ts 1 1 17 ``` </details> <!-- robobun:evidence:end -->
…es (oven-sh#43571) ### Problem - `Bun.serve` ignores the `If-Range` request header. A `Range` request whose validator does not match the response still gets `206 Partial Content`. A client that resumes a download after the file changed joins bytes of two versions. - All three Range paths are affected: `FileRoute::serve` (`FileRoute.rs:371`), `DirectoryRoute::on` (`DirectoryRoute.rs:161`) and `RequestContext::do_sendfile` (`RequestContext.rs:1909`). ### Fix - `RangeRequest::from_request` takes the `ETag` and `Last-Modified` of the response. If `If-Range` does not match them, it returns no range, and the route sends the full `200` body. File routes and `{ dir }` routes use it. - The handler path keeps a copy of `If-Range`. `do_sendfile` compares it with the `ETag` and `Last-Modified` the handler set on its Response. Without them, the response is the full body. - Correct per RFC 9110 §13.1.5: an entity-tag uses the strong comparison, and an HTTP-date must name GMT and equal `Last-Modified`. - Verified: `test/js/bun/http/bun-serve-file.test.ts` (45 new cases, 33 fail on 1.4.3) and `test/js/bun/http/serve-directory-routes.test.ts`. Also `bun-serve-static`, `serve-if-none-match`, `serve-http2`, `serve-http3`. Self-reviewed: 2 concerns raised, 2 addressed. ### Background - `If-Range` carries the validator (an ETag or a Last-Modified date) of the partial copy that the client has. It means: send the range only if the file is still that version, otherwise send all of it. - The strong comparison needs two byte-equal tags that are not weak (no `W/` prefix). The ETag of a `{ dir }` route is weak, so only the date form can match there. - `do_sendfile` serves a handler's `new Response(Bun.file(p))`. It can run after the uWS request object is gone, so the context copies the header. <details><summary>Notes</summary> Repro on 1.4.3. `/dir/*` is a `{ dir }` route, `/file` is a file route, and the `fetch` handler returns `new Response(Bun.file(p))`. Each request sends `Range: bytes=0-3` and `If-Range: "does-not-match"`: ``` /dir/big.bin 206 bytes 0-3/100000 (with this PR: 200, full body) /file 206 bytes 0-3/100000 (with this PR: 200, full body) /fetch-handler 206 bytes 0-3/100000 (with this PR: 200, full body) ``` - oven-sh#33548 made the same fix for the file route and the handler path. It was closed as stale because it conflicted with `main`, not because of the fix. This PR also covers `{ dir }` routes. - oven-sh#41502 (open) replaces `jsc_hooks::parse_http_date` with a strict HTTP-date parser for `If-Modified-Since` and `If-Unmodified-Since`. The `If-Range` date uses `parse_http_date`, like the other date preconditions on `main`. The PR that lands second should switch it. - A failed `If-Range` also turns off `416`, because the server ignores the `Range` header as a whole. - `If-Range` without a usable `Range` (absent, multi-range, malformed) has no effect, and the request context does not copy it. - A weak `If-Range` tag never matches, as in Go `net/http`. A client that sends the weak ETag of a `{ dir }` route gets the full file. That is correct, but it is not a resume. nginx compares the bytes of the two tags, and npm `send` does a substring match. The docs now say that the date is the validator to resume with on a `{ dir }` route. - The date must end in `GMT`. `parse_http_date` is `Date.parse`, which reads a date with no zone (the obsolete asctime form) in the server's local time. Such a date never matches, so the result does not depend on the server's time zone. The IMF-fixdate and rfc850 forms match. The strict parser of oven-sh#41502 can accept asctime as GMT. - The date comparison is exact to the second, as in nginx and Go `net/http`. A file that is rewritten twice in one second keeps the same `Last-Modified`, and the server cannot see that. RFC 9110 §8.8.2.2 gives that check to the client: it may use a `Last-Modified` as a strong validator only when the response's `Date` is later than it. - HEAD on the handler path does not evaluate `Range` on `main` (it does not reach `do_sendfile`). The HEAD cases cover the file route and the `{ dir }` route. - Cost for a request without `Range`: one branch in `RequestContext::create`, and one more header lookup in `FileRoute::serve`. The copy happens only when `Range` parses and `If-Range` is present. - The self-review raised two points, and the second commit addresses both. No test responded after an async hop, which is the case the header copy exists for. The `it.each` names did not say what the `If-Range` value was. - A manual check over HTTP/2 (`node:http2` client, `http2: true` server) gives the same results as HTTP/1.1 on all three paths. - Suites run with the debug build: `bun-serve-file`, `serve-directory-routes`, `bun-serve-static`, `serve-if-none-match`, `serve-http2`, `serve-http3`, `regression/issue/29181`, the `Content-Range` block of `serve.test.ts`, and `test/internal/source-lints/`. - The three `pollable Bun.file(...)` tests in `bun-serve-file.test.ts` take 2.6 to 6.5 s under the debug ASAN build in my container, so they can exceed the default 5 s timeout when the host is busy. Five interleaved runs of the base binary and the fixed binary show the same times for both. </details> <!-- robobun:evidence:begin --> --- **no test proof** · iteration 3 · platform-specific test(s) that do not run on this machine, deferring to CI, which covers all platforms: test/js/bun/http/serve-directory-routes.test.ts, test/js/bun/http/bun-serve-file.test.ts <!-- robobun:evidence:end -->
…d takes it back (oven-sh#44217) ### Problem - A replaced node:http response keeps its socket pointer. After the close, a call on it reads freed memory: `heap-use-after-free` in `uws_res_state` (`NodeHTTPResponse::is_socket_closed_or_closing`), or `Segmentation fault at address 0x0`. Without one, the process never exits. - `JSNodeHTTPServerSocket` tells only its current and queued responses about a close. `startPipelinedResponse()` and the dispatch (`NodeHTTP.cpp`) replace the current response silently. `res.detachSocket()` plus a pipelined request reach that. - After a WebSocket upgrade, a queued response reads the old socket: `heap-buffer-overflow` in `uWS::HttpContextData::isParsing`. ### Fix - `setCurrentResponse()` alone stores the current response and takes the connection back from the one that leaves. `onUpgraded()` does that for a WebSocket upgrade. - `Flags::CURRENT` marks the response that has the connection. `writer()` answers only for it, `reader()` also for a queued response. - Verified: `test/js/node/http/node-http-displaced-response.test.ts` (20 pass, main fails all 20), the `node-http*.test.ts` files, node's `test-http-*` files. ### Background - uWS keeps one response state per socket. The current response writes through it. A pipelined response waits in a queue. - A take-back flushes the tail of a `write()` into the socket buffer, clears the response's socket handlers, and releases its refs. JS sees a closed response. - Considered: telling replaced responses about a close. They could still write into the next response. ### Downsides - A replaced response drops its writes. main sent some. Node.js buffers them. - Each keep-alive request after the first runs 14 more instructions. `.text` grows by 1,792 bytes. - A replaced request gets no `'aborted'` event at the close. <details><summary>Notes</summary> **Repro** (from the report; `bun repro.mjs` printed a segfault on 1.4.0 to 1.4.3, `returned` on 1.3.14 and Node.js v26.3.0): ```js import http from "node:http"; import net from "node:net"; let n = 0; const server = http.createServer((req, res) => { if (n++ > 0) return; res.detachSocket(req.socket); setTimeout(() => { res.end("late"); console.log("returned"); server.close(); server.closeAllConnections(); }, 100); }); server.listen(0, "127.0.0.1", () => { const c = net.connect(server.address().port, "127.0.0.1", () => { c.write("GET /a HTTP/1.1\r\nHost: t\r\n\r\n"); c.write("GET /b HTTP/1.1\r\nHost: t\r\n\r\n"); setTimeout(() => c.destroy(), 30); }); c.on("error", () => {}); c.resume(); }); ``` **Commits.** The first commit changes no behaviour: `raw_response` moves into a private module behind `writer()` / `reader()`, and `currentResponseObject` becomes private behind `currentResponse()` / `setCurrentResponse()`. The release build of that commit alone, on its earlier base 1313ca6, had the `.text` size of that base (58,143,989 bytes) and the same instruction count in every `NodeHTTPResponse` function. The second commit is the role and the take-back. The third is the WebSocket case. **States of a response that is replaced.** | Flags | How | Take-back | |---|---|---| | ended and complete | Each keep-alive request replaces the one before. Its native handle (`resume`, `pauseReads`, `notifyWhenReadParsed`, `flushHeaders`, `end`) read the freed socket after a close. | Releases the handle. 14 instructions, inlined into the dispatch. | | in flight | The four JS triggers, then a pipelined request. | Out of line: tail, handlers, handle, `SOCKET_CLOSED`, refs. | | complete, not ended, still pending | The dispatch promise settled before the response ended, then the next request came. The process never exited. | The same. | A taken-back response gets `SOCKET_CLOSED`, so `is_done()`, the `Drop` assertion and the JS checks of `handle.flags` need no change. JS gets no event for it. **Label of each site** (`NodeHTTPResponse.rs` unless a file is named; 23 writer, 17 reader, 2 release, 1 take_for_upgrade): | Site | Label | Reason | |---|---|---| | `get_this_value`, `get_server_socket_value`, `notify_when_read_parsed` | reader | Looks up the socket, writes nothing. | | `capture_request_trailers` | reader | Takes the trailers of the request. | | `pause_socket`, `pause_socket_reads`, `resume_socket`, `do_pause`, `do_resume` | reader | Flow control of the request body. A queued request uses it. | | `release_body_slot`, `set_on_data` | reader | The request body handler. | | `set_on_aborted_handler`, dispatch tail (`mod.rs`) | reader | The timeout handler shares its user data slot with the request body handler. Both belong to the exchange that was dispatched last, which can be a queued one. | | `is_socket_closed_or_closing` | reader | Reads a connection-scoped state bit. | | `get_buffered_amount`, `has_unflushed_write` | reader | Reads the byte count of the socket buffer. `res.writableLength` of a queued response includes it (`node-http-backpressure.test.ts`). | | `abort` (first site) | reader | Asks uWS to close the connection after the read that it parses. | | `abort` (second and third site) | writer | Ends the response. A queued request that is destroyed no longer writes an empty response into the place of the response in flight. | | `write_head_impl`, `write_head_and_end`, `write_or_end` (7), `write_continue`, `write_informational`, `flush_headers`, `cork`, `on_auto_flush`, `spill_pending_pinned_write` | writer | Sends bytes of the response. | | `set_on_writable` | writer | Arms the drain handler of the response. | | `set_timeout` | writer | Sets the timeout of the response in flight. | | `node_http_request_on_resolve`, `node_http_request_on_reject`, thrown dispatch (`mod.rs`) | writer | Ends the response for a settled or thrown dispatch. | | `on_upgrade` (`server_body.rs`) | writer | Writes the 101 status and headers. | | `upgrade` | take_for_upgrade | Only the current response can hand the socket to a WebSocket. | | `handle_abort_or_timeout` (2) | release | The socket closed. | **Measurements.** Release builds of main (9f70da0) and of this PR, linux x64. `perf` is not permitted in the container (`perf_event_paranoid` is 4) and `valgrind` cannot be installed, so there is no dynamic instruction count. | What | main | PR | Tool | |---|---|---|---| | `.text` | 58,148,853 | 58,150,645 (+1,792) | `size -A` | | stripped binary | 80,832,072 | 80,836,168 (+4,096) | `ls -l` | | `NodeHTTPServer__onRequest_http` | 1,500 instructions | 1,525 | `llvm-objdump -d` | | of them at the slot store, previous response finished | 0 | 14, no call (the take-back is inlined) | `llvm-objdump -d` | | `NodeHTTPResponsePrototype__getFlags` | 28 | 28 | | | `NodeHTTPResponsePrototype__writeHeadAndEnd` | 221 | 226 | | | `write_or_end::<true>` | 713 | 723 | | | `write_head_impl` | 456 | 453 | | | `NodeHTTPResponse__createForJS` | 192 | 195 | | | pipelined activation (`startPipelinedResponse`) | 278, 5 calls, 3 lock-prefixed | 333 (262 + 71 out of line), 7 calls, 3 lock-prefixed | | | WebSocket upgrade callback | 6 | 142, 7 calls, 2 lock-prefixed (`onUpgraded`) | | | extern "C" entries | | +3 (`Bun__NodeHTTPResponse_takeBackConnection`, `Bun__NodeHTTPResponse_grantConnection`, `uws_res_clear_handlers_of`), -0 | `nm` | | JS to native calls per request | | unchanged in 4 of 4 shapes (sequential or pipelined, sync or async handler) | wrapped prototypes, debug builds | | `NodeHTTPResponse` | 544 bytes | 544 | `size_of` | | `Flags` | 2 | 2 | compile-time assertion | | `JSNodeHTTPServerSocket` | 208 | 208 | `llvm-dwarfdump` | | `NodeHTTPResponse` cells after 100 replaced responses, connections closed, full GC | 101 | 1 | `heapStats()` | | user CPU per request, 200,000 sequential keep-alive requests, 8 interleaved runs | median 12.5 us (10.2 to 15.6) | median 13.5 us (11.5 to 17.1) | `process.cpuUsage()`; the ranges overlap, the host was loaded | | the new test file | | 2.7 s release, 76 s debug+ASAN | | **Tests.** Each test spawns one fixture process that runs the scenarios of one suite. A fixture that finds a response with its refs still held exits with code 1, so an unfixed build fails in seconds. - 4 triggers x 11 later uses x 2 read orders (second request in the same read, or in a later one), on TCP and TLS. - A finished response that the next keep-alive request replaced: 11 calls on its native handle after the close. - The client stays: response 2 and 3 arrive in order, response 1 cannot write, and the socket does not take response 1 again. - A queued response calls its native handle: nothing reaches the wire before its turn. Without the `CURRENT` check this test fails. - A replaced response with an 8 MB write in the socket buffer: the bytes go out before response 2, and the process exits after a GC. - A response that native code completed is replaced: the process exits. - A WebSocket adopts the connection with a response queued, on TCP and TLS. On TLS the socket block is bigger, so main shows no sanitizer report there. The check of the held refs fails on main for both. - main (9f70da0), debug+ASAN: 0 pass, 20 fail. Release 1.4.3: 0 pass, 20 fail. - The tests are in a new file. `node-http-uaf.test.ts` runs two fixtures that loop thousands of requests and are close to their time limits on debug and ASAN builds. The 20 fixture processes of this file would compete with them for the CPU. - The time limit in the test file applies only to a local debug or ASAN build, which needs about 4 s to start one fixture. CI uses the time of its runner. **Still different from Node.js after a replacement.** Not changed here. - Node.js buffers the writes of a detached response until `assignSocket()`. Bun drops them. `write()` returns false, `end()` emits `'prefinish'`. - Node.js ignores a `'close'` event that user code emits on a response. Bun's dispatcher takes it as the end of the response. - Node.js aborts the request of a replaced response at the close (`abortIncoming`). Bun emits nothing for it. - Node.js does not dispatch a request that follows an Upgrade request in the same read. Bun queues it. **Found, not fixed here.** - `res.writeContinue()` and `res.addTrailers()` of a response that lost the connection go through the socket's current response and reach the wire in its place. `res._send()` on a queued response has no queue check. - After `res.emit('close')` on an open response whose handler returned, native code ends the response with a bare `\r\n`. - A request that is queued behind a WebSocket upgrade gets its `'aborted'` and `'close'` events when the WebSocket closes, not at the upgrade. Its abort callback destroys the socket, which the WebSocket has then. - A response that upgrades while a large `write()` still holds a tail by reference drops that tail. main does the same. **Self-review.** A review ran on an earlier state of this branch: the first two commits, as two PRs. Its verdict asked for three changes, and all three are here: one PR that has the tests, the WebSocket case, and no statement about Node.js in the tests that was not checked. It also showed that no test failed with the `CURRENT` check disabled. The queued-response test covers that now. The full list of its findings was not kept, so other findings can be open. The third commit, the inlined take-back of a finished response, and the two newest tests had no second review. **Question for a maintainer.** The response keeps its pointer and a `CURRENT` bit, and the socket pushes a take-back. The other form removes the pointer and asks the socket on each use: about 15 more loads per request, and the wrapper grows from 64 to 80 bytes. This PR builds the first. **Platforms.** I ran the tests on Linux x64. CI ran the new test file on macOS and Windows, x64 and aarch64: 20 pass on each. </details>
…try already removed (oven-sh#42311) ### Problem - A `require()` that fails after its `require.cache` entry is gone aborts assert builds: `ASSERTION FAILED: wasRemoved || (graph && graph->disposed())` at `JSCommonJSModule.cpp(1403)` in `Bun::finishRequireWithError` (`ASSERTION FAILED: wasRemoved` before oven-sh#42590). - Bun removes it first when a `Module._extensions` handler calls the loader it replaced and the ES module fails to load. `requireESMFromHijackedExtension` (`src/js/builtins/CommonJS.ts:216`) deleted the entry and rethrew. On release, a handler that catches that error lost its module from `require.cache`. Node keeps it. - User code removes it first with `delete require.cache[__filename]; throw new Error("x")`. ### Fix - `requireESMFromHijackedExtension` no longer deletes the entry. The enclosing native `$require` removes the entry if the error escapes the handler. - `finishRequireWithError` and `JSCommonJSModule::load` no longer assert that the removal found the key. User code can remove it first. - Verified: 14 new tests in `test/js/node/module/require-extensions.test.ts` and `test/js/bun/resolve/require.test.ts` fail on a debug build of main. Also ran `test/js/node/module/`, `module-graph.test.ts`. - Self-reviewed: 2 concerns raised, 1 addressed. Rejected: a test for `load()`, nothing reaches it (Notes). ### Background - The require map is the `Map` behind `require.cache`. `overridableRequire` puts a placeholder in it before the load, and a failed load must remove it. - `$require` is the native `jsFunctionRequireCommonJS`. Every throw inside it goes through `finishRequireWithError`, which removes the entry and rethrows. - `Module._extensions['.js']` is the native `builtinLoader`. A handler that replaces it (pirates, ts-node) usually calls it back. For an ES module it calls the builtin `requireESMFromHijackedExtension`. - A `Bun.ModuleGraph` has its own require map. oven-sh#42590 exempted a disposed graph from the assert. <details><summary>Notes</summary> **Why `overridableRequire` keeps its own `catch`.** With no handler, `$require` returns -1 for an ES module and `overridableRequire` loads it after `$require` returned. That path still does `requireMap.$delete(id)` in a `catch`, because no native frame is left to do it. **Rebase onto oven-sh#42590 (per-graph CommonJS).** That PR reworded both asserts to `ASSERT_UNUSED(wasRemoved, wasRemoved || (graph && graph->disposed()))` and made the `catch` in `requireESMFromHijackedExtension` delete from `this.$requireMap || $requireMap`. In an ordinary program `graph` is null, so the condition is the same as before. This PR removes the whole assert, so the `disposed()` clause goes with it: a disposed graph is one more way the entry can already be gone. The removal still uses the graph's map. The module that `requireESMFromHijackedExtension` receives is the child that `overridableRequire` created, and `$createCommonJSModule` gives it the graph of its parent, so `finishRequireWithError` removes from the same map that the old `catch` used. Two of the new tests run inside a `Bun.ModuleGraph` that is not disposed. Both abort on main. **Self-review.** Addressed: each wrapper row now asserts that the handler ran (`calls: 1`), so a row cannot pass through the path that has no handler. Other suites run on the fixed debug build: `test/js/bun/resolve/require-esm-*.test.ts`, `esModule.test.ts`, `test/cli/run/run-cjs.test.ts`, `test/regression/issue/24387.test.ts`, `test/js/bun/test/mock/mock-module.test.ts`, `test/regression/issue/require-extensions-override.test.ts`, `test/regression/issue/22929-module-extensions-asi.test.ts`. Before the rebase I also ran the Node `test-require-*` and `test-module-*` files (48 pass) and the repro scripts under `BUN_JSC_validateExceptionChecks=1`. In `module-graph.test.ts`, 288 tests pass. The 4 `dynamicImport: ...` tests time out at 5 s in the full debug run and pass when run alone (3.5 s to 4.6 s each), so that is the speed of the debug build. **Original repro** (`bun repro.cjs`, debug build of main: rc 134. Release: prints `caught boom | still cached: false`): ```js const fs = require("fs"), path = require("path"), os = require("os"), Module = require("module"); const dir = fs.mkdtempSync(path.join(os.tmpdir(), "extesm-")); const f = path.join(dir, "esm-throws.js"); fs.writeFileSync(f, "export default 1;\nthrow new Error('boom');\n"); const orig = Module._extensions[".js"]; Module._extensions[".js"] = function (m, filename) { return orig.call(this, m, filename); }; try { require(f); } catch (e) { console.log("caught", e.message, "| still cached:", f in require.cache); } fs.rmSync(dir, { recursive: true, force: true }); ``` **Call path of the double removal.** `overridableRequire` sets the require map entry and calls `$require`. `fetchCommonJSModuleNonBuiltin<false>` gets a `CommonJSCustomExtension` result and calls `evaluateCommonJSCustomExtension`, which calls the user's handler. The handler calls `builtinLoader`, which gets -1 (ES module) and calls `requireESMFromHijackedExtension`. Its `catch` deleted the key. The exception unwound to `jsFunctionRequireCommonJS`, and `finishRequireWithError` removed the same key again. **Handler that catches the error** (the release-visible part). With a handler of the shape `try { return orig.call(this, m, f) } catch (e) { m.exports = { recovered: e.message } }` and an ES module that throws: | | first `require(f)` | `f in require.cache` | second `require(f)` | |---|---|---|---| | node v26.3.0 | `{ recovered: "boom" }` | true | same object, handler ran once | | bun 1.4.3-canary.1 | `{ recovered: "boom" }` | false | throws `boom`, not through the handler | | this PR | `{ recovered: "boom" }` | true | same object, handler ran once | The second `require()` threw on release because the map entry was gone, the ES module registry still had the failed record, and `fetchCommonJSModule` returns -1 for a file the registry already knows without a call to the handler. **Each half of the fix is needed.** With only the C++ change, the handler-catches test fails. With only the JS change, the eviction tests in `require.test.ts` and the `pirates-evict` row fail with the assert. **Rows in the new tests.** Handler that calls the original loader: `.js` with ES module syntax, `.ts`, `.mjs`, `.js` under `"type": "module"`, an import that does not resolve, a file with neither CommonJS nor ES module syntax (`nope();`, the transpiler classifies it as an ES module), top-level await, the pirates shape (wrap `module._compile`, then call the original loader), and the plain wrapper inside a `Bun.ModuleGraph`. Eviction before the throw: the module deletes itself (in the host and inside a `Bun.ModuleGraph`), a child module deletes its parent, and a `module._compile` wrapper deletes the entry before a CommonJS file runs. Each row runs in its own process, because the assert aborts the process. **`JSCommonJSModule::load`.** It is the same copied block, so the assert there is wrong for the same reason. I did not find a deterministic way to reach it. `load()` only evaluates a module that an ES module import created in the map and that has not run yet. With the current loader a CommonJS file that an ES module imports runs right after its fetch, so a `require()` from a sibling never finds it in that state (checked with static imports and with `import()` after startup: the sibling is not in `require.cache` yet). A module that `require()` itself is loading has a null `sourceCode`, so `load()` returns early for it. **Windows.** The fix has no platform code. Before the rebase I ran both test files on Windows x64 with the canary build to check the path handling in the fixtures: 29 pass, and the handler-catches test fails as it does on every release build without the fix. **Not changed here.** `Module.prototype.require.call(plainObject, id)` throws `TypeError: undefined is not a function` and leaves the placeholder in the map, so a later `require(id)` returns `{}`. That is an entry that nothing removes, not a double removal. It is a separate bug. **Nearby open PRs.** oven-sh#38645 and oven-sh#38072 change the same functions for other reasons. Neither touches this removal. </details> <!-- robobun:evidence:begin --> --- **[human-review]** gate passed · iteration 1 · 4 files touched <details><summary>fails on main (without fix)</summary> ```console ASAN without fix: 12 failed, 3 skipped $ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/pr_gate.xml" test/js/bun/resolve/require.test.ts test/js/node/module/require-extensions.test.ts bun test v1.4.3 (4ff9193) test/js/bun/resolve/require.test.ts: (pass) require(specifier) > has a length of 1 [3.86ms] (pass) require(specifier) > is a function [1.89ms] (pass) require(specifier) > has an empty prototype [4.72ms] (pass) require(specifier) > when specifier is a path to a non js/ts/etc file > require('obj.toml') synchronously produces an object [12.43ms] (pass) require(specifier) > when specifier is a path to a non js/ts/etc file > require('obj.json') synchronously produces an object [4.24ms] (pass) require(specifier) > when specifier is a path to a non js/ts/etc file > require('obj.jsonc') synchronously produces an object [4.07ms] (pass) require(specifier) > when specifier is a path to a non js/ts/etc file > require('obj.xml') synchronously produces an object [4.48ms] (pass) require(specifier) > when specifier is a path to a non js/ts/etc file > require('arr.json') synchronously produces an array [7.30ms] (pass) require(specifier) > when ... (truncated) release without fix: 3 skipped bun test v1.4.3-canary.1 (9c3bcdd) test/js/bun/resolve/require.test.ts: (pass) require(specifier) > has a length of 1 [0.04ms] (pass) require(specifier) > is a function [0.05ms] (pass) require(specifier) > has an empty prototype [0.12ms] (pass) require(specifier) > when specifier is a path to a non js/ts/etc file > require('obj.toml') synchronously produces an object [0.37ms] (pass) require(specifier) > when specifier is a path to a non js/ts/etc file > require('obj.json') synchronously produces an object [0.11ms] (pass) require(specifier) > when specifier is a path to a non js/ts/etc file > require('obj.jsonc') synchronously produces an object [0.09ms] (pass) require(specifier) > when specifier is a path to a non js/ts/etc file > require('obj.xml') synchronously produces an object [0.08ms] (pass) require(specifier) > when specifier is a path to a non js/ts/etc file > require('arr.json') synchronously produces an array [0.15ms] (pass) require(specifier) > when specifier is a path to a non js/ts/etc file > require('arr.jsonc') synchronously produces an array [0.07ms] (pass) require(specifier) > when specifier is a path to a non js/ts/etc file > require('*.txt') sy ... (truncated) ``` </details> <details><summary>passes on PR (with fix)</summary> ```console ASAN with fix: 3 skipped $ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/pr_gate.xml" test/js/bun/resolve/require.test.ts test/js/node/module/require-extensions.test.ts bun test v1.4.3 (4ff9193) test/js/bun/resolve/require.test.ts: (pass) require(specifier) > has a length of 1 [3.08ms] (pass) require(specifier) > is a function [2.57ms] (pass) require(specifier) > has an empty prototype [4.14ms] (pass) require(specifier) > when specifier is a path to a non js/ts/etc file > require('obj.toml') synchronously produces an object [10.72ms] (pass) require(specifier) > when specifier is a path to a non js/ts/etc file > require('obj.json') synchronously produces an object [3.23ms] (pass) require(specifier) > when specifier is a path to a non js/ts/etc file > require('obj.jsonc') synchronously produces an object [22.57ms] (pass) require(specifier) > when specifier is a path to a non js/ts/etc file > require('obj.xml') synchronously produces an object [3.00ms] (pass) require(specifier) > when specifier is a path to a non js/ts/etc file > require('arr.json') synchronously produces an array [5.47ms] (pass) require(specifier) > whe ... (truncated) release with fix: 3 skipped $ bun scripts/build.ts --profile=release [configured] bun-profile → bun (stripped) in 808ms (unchanged) ninja: Entering directory `/workspace/bun/build/release' [1/22] gen cpp.rs (cppbind) [2/22] gen JS modules (bundle-modules) Preprocess modules (12513ms) Bundle modules (70ms) Postprocesss modules (162ms) Bundle Functions (690ms) Generate Code (48ms) [13.49s] Bundled "src/js" for production 2599 kb 197 internal modules 13 native modules 50 internal functions across 16 files [2/8] cargo bun_runtime → libbun_runtime.a ^[[1m^[[92m Compiling^[[0m bun_core v0.0.0 (/workspace/bun/src/bun_core) ^[[1m^[[92m Compiling^[[0m bun_errno v0.0.0 (/workspace/bun/src/errno) ^[[1m^[[92m Compiling^[[0m bun_ptr v0.0.0 (/workspace/bun/src/ptr) ^[[1m^[[92m Compiling^[[0m bun_boringssl_sys v0.0.0 (/workspace/bun/src/boringssl_sys) ^[[1m^[[92m Compiling^[[0m bun_safety v0.0.0 (/workspace/bun/src/safety) ^[[1m^[[92m Compiling^[[0m bun_base64 v0.0.0 (/workspace/bun/src/base64) ^[[1m^[[92m Compiling^[[0m bun_cares_sys v0.0.0 (/workspace/bun/src/cares_sys) ^[[1m^[[92m Compiling^[[0m bun_zlib_sys v0.0.0 (/workspace/bun/src/zlib_sys) ^[[1m^[[92m Compiling^[[0m bun_zstd v0.0.0 (/workspace/bu ... (truncated) ``` </details> <details><summary>diff hotspot</summary> ``` src/js/builtins/CommonJS.ts | 10 +-- src/jsc/bindings/JSCommonJSModule.cpp | 14 ++-- test/js/bun/resolve/require.test.ts | 49 ++++++++++- test/js/node/module/require-extensions.test.ts | 109 ++++++++++++++++++++++++- 4 files changed, 164 insertions(+), 18 deletions(-) ``` </details> **gate history** · 2 passed · 0 rejected · iteration 1 <details><summary>evidence per changed file</summary> ``` file reads edits tests src/js/builtins/CommonJS.ts 1 2 29 src/jsc/bindings/JSCommonJSModule.cpp 4 3 29 test/js/bun/resolve/require.test.ts 3 2 21 test/js/node/module/require-extensions.test.ts 4 2 24 ``` </details> <!-- robobun:evidence:end -->
… found it dead (oven-sh#44279) ### What does this PR do? Fixes a segfault in `WTF::Vector::takeLast` under `JSFinalizationRegistry::takeDeadHoldingsValue` ← `runFinalizationCleanup` ← `Bun__runDeferredWork` (Sentry BUN-4SGV). It happens with `node:vm` contexts and with `bun test --isolate` / `--parallel`, on every platform. **Cause** - A `DeferredWorkTimer` ticket's cells (the registry, a `waitAsync` promise, a wasm promise) are marked only by their realm, so the sweep frees them once the realm is dead. - JSC cancels a dead realm's tickets at the end of each collection, in `DeferredWorkTimer::cancelPendingWork(VM&)`. It walks `m_pendingTickets`, which is empty in Bun because `onAddPendingWork` takes each ticket into `JSCTaskScheduler`'s maps. - `~JSGlobalObject` cancels them too, but a lazily swept global is destroyed later. A cleanup job that was already queued runs in between, on a registry that has been destroyed. **Fix** - `JSVMClientData` implements `VM::ClientData::reconcileWeakReferencesAtGCEnd`, the embedder hook JSC calls after marking and before sweeping. - There, `JSCTaskScheduler::cancelWorkOfDeadRealms` finds the unmarked realms that still have pending tickets and calls `JSGlobalObject::clearWeakTickets()` on each. This is the fixing line. It is what `~JSGlobalObject` calls: it unregisters the realm's `Atomics.waitAsync` waiters, then cancels its tickets through the existing `onCancelPendingWork` hook, which drops the map entry and releases the event loop ref. - `JSCDeferredWorkTask` stores its `JSVMClientData` instead of reaching the VM through `ticket->scriptExecutionOwner()`, which is a freed cell for exactly these jobs. The null check in `Bun__deleteDeferredWorkTask` goes with it: `~VM` deletes `clientData` last and never nulls it. A second effect: `Atomics.notify` no longer counts or wakes the `Atomics.waitAsync` of a dead context. No WebKit change. Supersedes oven-sh#39994. ### How did you verify your code works? Two new tests in `test/js/node/vm/vm.test.ts`. Each also keeps one context alive and requires its callback to still run. | | 1.4.2 | fixed (debug + ASAN, Linux x64) | |---|---|---| | a FinalizationRegistry cleanup job is dropped when its context dies before the job runs | segfault (exit 139) | pass | | Atomics.notify does not wake the Atomics.waitAsync of a context that died | `woken: 5` | `woken: 1`, pass | The first test also segfaults on canary `11c41c645`. The `FinalizationRegistry` tests in `test/cli/test/isolation.test.ts` pass with the change.
… server against (oven-sh#41761) ### Problem - `new Bun.SQL({ url, tls: Bun.file("ca.pem") })` is a form the public type advertises (`tls?: Bun.BunFile | TLSOptions | …`). It negotiated TLS but never verified the server certificate and never read the file. A wrong CA, a nonexistent path and a non-PEM file all connected. The `ssl` alias behaved the same. - Cause: `parseOptions` (`src/js/internal/sql/shared.ts:2027`) kept the Blob as the `tls` object. A Blob has no `ca`, `caFile` or `rejectUnauthorized`, so the sslmode was only raised to `require`. ### Fix - A BunFile `tls` or `ssl` option becomes `{ ca: file }`. The existing rules then select `verify-full` (an explicit `verify-ca` is kept), add `serverName`, and read the file when the connection is created. A wrong CA, a missing file (`ENOENT`) and a non-file `Blob` (`ERR_INVALID_ARG_TYPE`) now reject. - The alternative was to throw for a BunFile and drop it from the type. `test/js/sql/sql-mysql.test.ts` already passes `tls: Bun.file(ca.pem)` for the TLS image with this meaning, so this PR implements it. That suite now runs with `verify-full`. - Verified: `test/js/sql/adapter-env-var-precedence.test.ts`. Also `tls-sql.test.ts` and the new MySQL test against local TLS servers with the repo certificates, and `bun-types.test.ts`. ### Background - `Bun.SQL` folds the `tls`/`ssl` options, URL `?sslmode=` and `PGSSLMODE` into one `sslMode` plus a `TLSOptions` object for the native connection. - `require` encrypts but does not authenticate the server. `verify-ca` checks the chain against the CA. `verify-full` also checks the hostname. - `TLSOptions.ca` already accepts a `BunFile`. `SSLConfig` reads it when the connection object is constructed (`src/runtime/socket/SSLConfig.rs:75`). <details><summary>Notes</summary> - Reproduced on 1.4.3-canary (f42e980) against a python pg-over-TLS stub whose leaf chains to `root.pem` only. Before: `tls: Bun.file(other.pem)`, `tls: Bun.file('/nonexistent.pem')`, `ssl: Bun.file(other.pem)` and `tls: new Blob([..])` all connected and ran the query. After: `UNABLE_TO_VERIFY_LEAF_SIGNATURE`, `ENOENT`, `UNABLE_TO_VERIFY_LEAF_SIGNATURE`, `ERR_INVALID_ARG_TYPE`; `tls: Bun.file(root.pem)` connects with verification on. - The new `adapter-env-var-precedence.test.ts` block fails on 1.4.3-canary (`sslMode` is 2, `tls` is the Blob) and passes with this change. - MySQL shares the normaliser. Checked against a local MariaDB with `test/js/sql/mysql-tls/ssl` certs: right CA connects (verify-full, `IP:127.0.0.1` SAN), wrong CA rejects with `SELF_SIGNED_CERT_IN_CHAIN`, missing file `ENOENT`. - The postgres docker test uses `?sslmode=verify-ca` for the positive case because `docker-tls/server.crt` names `127.0.0.1` as a DNS SAN, not an IP SAN, and a bare BunFile leaves no room for `serverName`. The MySQL certificate has an IP SAN, so that suite verifies the hostname too. - `tls-sql.test.ts`: 34 pass against a local postgres 17 started with the `postgres_tls` certificates and hba rules (`BUN_TEST_SERVICE_postgres_tls=...`). The new test fails on 1.4.3-canary against the same server (the wrong-CA connection succeeds). - Docs: added a short "Custom CA Certificates" section to `docs/runtime/sql.mdx` and a JSDoc note on `tls`. </details> <!-- robobun:evidence:begin --> --- **no test proof** · iteration 0 · platform-specific test(s) that do not run on this machine, deferring to CI, which covers all platforms: test/js/sql/adapter-env-var-precedence.test.ts <!-- robobun:evidence:end -->
…sh#42948) ### Problem - `bun build` silently drops a live CSS rule that has nested rules. `.a{color:red} .q{color:blue} .q{color:red} .q{color:red;.n{color:green}} .q{color:blue}` prints `.a, .q {color: red}` and `.q {color: #00f}`. `.q .n {color: green}` is gone. - The cause is a stale index in `StyleRuleKeyMap` (`src/css/rules/mod.rs`). `cascade_merge_with_previous` pops the merged `.q` rule from slot 1, but the table keeps index 1. The rule with the nested `.n` takes slot 1, and the last `.q{color:blue}` erases it as a duplicate. ### Fix - After each `rules.pop()`, the cascade calls the new `StyleRuleKeyMap::truncate`, which removes the popped index from its bucket. It uses the key stored at insertion, because a later merge can change the hash of the rule. - The `other_idx != key.index` guard from oven-sh#31920 is gone. It covered one symptom of the same stale index. - The [oven-sh#31920 review](oven-sh#31920 (comment)) proposed this purge. [My reply](oven-sh#31920 (comment)) declined it and called a stale match sound. That was wrong: `is_duplicate` does not read nested rules. - Verified: `test/js/bun/css/duplicate-declaration-merge-hang.test.ts` (fails on bun 1.4.3). Also `test/js/bun/css/`, `test/bundler/css/`, `test/bundler/esbuild/css.test.ts`. Self-reviewed: 1 concern raised, 1 addressed. Restarts cut that review short. ### Background - `CssRuleList::minify` runs on each CSS file that `bun build` reads, with or without `--minify`. It moves the parsed rules into a new `rules` list. - The duplicate-rule table maps a hash of a style rule to indices into `rules`. A later rule with the same selectors and property names makes the earlier rule `CssRule::Ignored`. Only a rule without nested rules enters the table. - The merge cascade joins the last rule into the rule before it, then pops it. Only this pop shrinks `rules`. <details><summary>Notes</summary> Trace of the repro on the unfixed build: 1. `.a{color:red}` goes to slot 0, `.q{color:blue}` goes to slot 1. The table records both. 2. `.q{color:red}` merges its declarations into slot 1. 3. `.q{color:red;.n{color:green}}` cannot merge, because it has nested rules. Its arrival settles slot 1 to `.q{color:red}`. The cascade joins slot 1 into slot 0 (`.a,.q{color:red}`) and pops slot 1. The table still holds index 1. 4. The rule with the nested `.n` is pushed into slot 1. It never enters the table. 5. `.q{color:blue}` goes to slot 2. Its lookup finds index 1. `StyleRule::is_duplicate` compares selectors and property names only, so it matches, and slot 1 is erased with its nested rule. Each of the five rules is needed. Without the leading `.a`, the first `.q{color:blue}` or the last `.q{color:blue}`, the output keeps `.q .n`. The second input in the new test has `.q{font-style:italic}` merge into slot 1 after the table recorded it. At the pop, the rule hashes to a different bucket than its table entry. This pins the stored-key lookup in `truncate`: a version that hashes the popped rule again does not find the entry. Differential check, not committed: a script generates small random stylesheets over `.a`, `.b`, `.q` with an optional nested `.n`, minifies them, parses the output, and compares which declaration wins for each element. bun 1.4.3 gives 17 mismatches in 60,000 stylesheets, all of the shape above. The debug build with this fix gives 0 in the same 60,000. The output for the 15 real-world stylesheets in `test/js/bun/css/files/` (bootstrap, bulma, tailwind and others) is byte-identical between bun 1.4.3 and this branch, minified and not minified. lightningcss has the same stale index: parcel-bundler/lightningcss#1235, with the open PR parcel-bundler/lightningcss#1236. That PR also moves a rule to a new bucket when a merge changes it, so that later duplicates are found. This PR does not change which duplicates are found. oven-sh#33684 is a different bug in the same dedup step (`is_duplicate` matches too much for custom properties and `!important`). </details> <!-- robobun:evidence:begin --> --- **[human-review]** gate passed · iteration 0 · 2 files touched <details><summary>fails on main (without fix)</summary> ```console ASAN without fix: 1 FAILED $ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/pr_gate.xml" test/js/bun/css/duplicate-declaration-merge-hang.test.ts bun test v1.4.3 (c6b7fcb) test/js/bun/css/duplicate-declaration-merge-hang.test.ts: (pass) duplicate declarations across merged rules minify in linear time instead of hanging [3090.67ms] (pass) deferred merge re-minify keeps per-merge output [6.76ms] (pass) stale duplicate-rule entries do not erase a later rule [2.51ms] 150 | // the rule with the nested .n takes slot 1, and the last .q{color:blue} 151 | // matched the stale index: both inputs used to drop ".q .n{color:green}". 152 | test("stale duplicate-rule entries do not erase a rule that has nested rules", () => { 153 | expect( 154 | cssInternals.minifyTest(".a{color:red}.q{color:blue}.q{color:red}.q{color:red;.n{color:green}}.q{color:blue}", ""), 155 | ).toBe(".a,.q{color:red}.q{color:red;& .n{color:green}}.q{color:#00f}"); ^ error: expect(received).toBe(expected) Expected: ".a,.q{color:red}.q{color:red;& .n{color:green}}.q{color:#00f}" Received: ".a,.q{color:red}.q{color:#00f}" at <anonymous> (/w ... (truncated) release without fix: 1 FAILED bun test v1.4.3-canary.1 (c6b7fcb) test/js/bun/css/duplicate-declaration-merge-hang.test.ts: (pass) duplicate declarations across merged rules minify in linear time instead of hanging [57.55ms] (pass) deferred merge re-minify keeps per-merge output [0.33ms] (pass) stale duplicate-rule entries do not erase a later rule [0.07ms] 150 | // the rule with the nested .n takes slot 1, and the last .q{color:blue} 151 | // matched the stale index: both inputs used to drop ".q .n{color:green}". 152 | test("stale duplicate-rule entries do not erase a rule that has nested rules", () => { 153 | expect( 154 | cssInternals.minifyTest(".a{color:red}.q{color:blue}.q{color:red}.q{color:red;.n{color:green}}.q{color:blue}", ""), 155 | ).toBe(".a,.q{color:red}.q{color:red;& .n{color:green}}.q{color:#00f}"); ^ error: expect(received).toBe(expected) Expected: ".a,.q{color:red}.q{color:red;& .n{color:green}}.q{color:#00f}" Received: ".a,.q{color:red}.q{color:#00f}" at <anonymous> (/workspace/bun/test/js/bun/css/duplicate-declaration-merge-hang.test.ts:155:5) (fail) stale duplicate-rule entries do not erase a rule that has nested rules [0.32ms] (pass) declaration ... (truncated) ``` </details> <details><summary>passes on PR (with fix)</summary> ```console ASAN with fix: all passed $ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/pr_gate.xml" test/js/bun/css/duplicate-declaration-merge-hang.test.ts bun test v1.4.3 (c6b7fcb) test/js/bun/css/duplicate-declaration-merge-hang.test.ts: (pass) duplicate declarations across merged rules minify in linear time instead of hanging [4521.77ms] (pass) deferred merge re-minify keeps per-merge output [11.15ms] (pass) stale duplicate-rule entries do not erase a later rule [3.44ms] (pass) stale duplicate-rule entries do not erase a rule that has nested rules [6.89ms] (pass) declaration merges do not drop partitioned incompatible selectors [4.45ms] 5 pass 0 fail 8 expect() calls Ran 5 tests across 1 file. [7.27s] __F:0:S:0 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 8ba54a0 features lto, baseline 23 deps, 131 codegen, 1176 objects in 926ms ninja: Entering directory `/workspace/bun/build/release' [1/1250] install /workspace/bun bun install v1.4.3-canary.1 (c6b7fcb) Checked 22 installs across 61 packages (no changes) [5.00ms] [2/1250] install /workspace/bun/packages/bun-error bun install v1.4.3-canary.1 (c6b7fcb) Checked 1 install across 2 packages (no changes) [4.00ms] [3/1250] install /workspace/bun/src/node-fallbacks bun install v1.4.3-canary.1 (c6b7fcb) Checked 111 installs across 104 packages (no changes) [14.00ms] [4/1250] gen ErrorCode+*.h [5/1250] gen bindgenv2 [6/1250] gen node-fallbacks/react-refresh.js Bundled 1 module in 20ms react-refresh.js 4.81 KB (entry point) [7/1250] esbuild bun-error ../../build/release/codegen/bun-error/index.js 34.9kb ../../build/release/codegen/bun-error/bun-error.css 12.8kb ⚡ Done in 53ms [8/1250] fetch libjpeg-turbo [libjpeg-turbo] up to date [9/1223] fetch zlib [zlib] ... (truncated) ``` </details> <details><summary>diff hotspot</summary> ``` src/css/rules/mod.rs | 50 ++++++++++++++-------- .../css/duplicate-declaration-merge-hang.test.ts | 25 +++++++++-- 2 files changed, 53 insertions(+), 22 deletions(-) ``` </details> **gate history** · 1 passed · 0 rejected · iteration 0 <details><summary>evidence per changed file</summary> ``` file reads edits tests src/css/rules/mod.rs 3 6 14 test/js/bun/css/duplicate-declaration-merge-hang.test.ts 3 4 13 ``` </details> **self-review** · 1 surviving concern - consider: Kind: bug fix. Losing a live rule was never decided, but leaving popped indices un-purged was: oven-sh#31920's author declined this exact purge in review with a soundness argument. The PR body never mentions that, and this PR's repro disproves the argument. 16 concerns were raised and did not survive verification. <!-- robobun:evidence:end -->
…oven-sh#35119) ## Problem When a statement inside a PostgreSQL transaction fails, the session enters the failed-transaction state (`25P02`) and a subsequent `COMMIT` is answered with `CommandComplete('ROLLBACK')`, not `'COMMIT'`: nothing was committed. `sql.begin()` ignored the returned command tag and resolved with the callback's return value, so a caller that swallowed an error inside the callback saw `begin()` resolve for a transaction the server rolled back: ```js await sql.begin(async tx => { await tx`INSERT INTO t VALUES (1)`; await tx`SELECT * FROM nope`.catch(() => {}); // swallows 42P01, tx now aborted return 'ok'; }); // resolved 'ok', but t is empty ``` ## Fix Check the `COMMIT` result's `.command` tag and reject `begin()` with `ERR_POSTGRES_COMMIT_ROLLED_BACK` when it reads `'ROLLBACK'`. MySQL and SQLite never answer COMMIT with a ROLLBACK tag, so the check is a no-op there. ## Verification `test/js/sql/sql-begin-commit-rolled-back.test.ts` runs the scenario above against a real Postgres: on main `begin()` resolves `'ok'` with an empty table; with this change it rejects with `ERR_POSTGRES_COMMIT_ROLLED_BACK` and the table is still empty. --------- Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
…ven-sh#44281) ### What does this PR do? Fixes a segfault at address `0x10` in `JSC::JSModuleLoader::loadModule` ← `moduleLoadTopSettled` (Sentry BUN-4NFS, BUN-41VH), on every platform. The fix is in oven-sh/WebKit#748 (merged), which also explains why it belongs there. This PR bumps WebKit to it and adds the tests. Two things ride along: - **The WebKit bump goes to `fb1167ebf2cb`, the current tip.** Besides the fix (`0e8e9c238e91`) that brings in one more commit, oven-sh/WebKit#749: on Linux, OS randomness is read with `getrandom(2)`, and `/dev/urandom` is opened only when that fails. - **A type error on main.** `src/js/bun/sql.ts(892,26): error TS2339: Property 'command' does not exist on type '{}'` came in with oven-sh#35119 and fails "Lint JavaScript" for every PR that includes it. `unsafeQueryFromTransaction()` now says what its query resolves to (`SQLResultArray`). It is a type argument only, so the code that runs is the same. **Cause** The module loader has two tables of what is loaded: the registry, and a shortcut that lets a repeated `import()` skip resolving. Removing a module clears both. But an `import()` of that module that is still in flight adds it to the shortcut afterwards, when its dependencies have loaded. The next `import()` finds the old module there, pairs it with a new registry entry that has no load promise yet, and dereferences null. ```ts const inFlight = import("./a"); // a.ts is registered, its dependencies are still loading mock.module("./a", () => ({ a: "mocked-a" })); await inFlight; await import("./a"); // segfault ``` Everything that removes a module while its `import()` is in flight gets there: | route | 1.4.2 | canary `11c41c645` | with the fix | |---|---|---|---| | `delete require.cache[path]` | segfault | ok (oven-sh#40123) | ok | | `mock.module()` | segfault | segfault | ok | | `build.module()` in a plugin | segfault | segfault | ok | | a `bun --hot` reload | segfault | segfault | ok | | a plugin's `onResolve` redirecting a → b → c → d, `delete require.cache[d]`, `import(a)` again | segfault | segfault | ok | The last one needs nothing in flight: the shortcut is keyed by the name that was asked for, and removing a module cleared it only by the name it resolved to. It was found in review, and nothing in the crash reports points at it. Of the 481 reports, 273 are from `bun test`, 203 from `bun run` or `bun <file>`, and 240 had an HTTP server running. **Fix** (oven-sh/WebKit#748) The place that adds a module to the shortcut first checks that the registry still holds it, and skips the write if not. And removing a module clears it from the shortcut under whatever name it was asked for. It is eleven lines in Bun's part of the loader. For a program that removes no module nothing changes. ### How did you verify your code works? Four new tests, one for each route that still crashes. All four fail on 1.4.2 and on canary `11c41c645`, and pass against oven-sh/WebKit#748 on debug and release builds (Linux x64). Without the WebKit bump, CI had all three segfault at `0x10` on every platform: macOS, Linux glibc and musl, and Windows, x64 and arm64. The hot reload test passed 10 runs of 10. | test | file | |---|---| | mock.module() of a module whose import() is still loading its dependencies | `mock-module.test.ts` | | build.module() of a module whose import() is still loading its dependencies | `plugins.test.ts` | | should import a module again after a hot reload while its import() was still loading its dependencies | `hot.test.ts` | | import() after delete require.cache of a module that onResolve redirected a resolved path to | `plugins.test.ts` | The WebKit PR has the evidence that nothing changes for a program that removes no module, the comparison of behavior with main, WebKit's own module tests and the cost.
…n-sh#38616) ### Problem - `bun pm ls --all` (and `bun list --all`) aborts with `panic: buf_print: buffer too small` (exit 134) as soon as it reaches a package whose resolution is longer than 512 bytes, for example a dependency installed from a tarball URL with a ~600 character path. Plain `bun pm ls` prints the same package fine. - Reproduced with bun 1.4.0-canary.1 and main: serve a `.tgz` from a local `Bun.serve`, depend on it as `http://127.0.0.1:PORT/aaaa...(600 chars)/bar-0.0.2.tgz`, `bun install` (succeeds), `bun pm ls --all` prints the root line and `├── ` and panics. - Cause: the `--all` tree printer (`print_node_modules_folder_structure`, `src/runtime/cli/package_manager_command.rs`) formatted each resolution into `let mut resolution_buf = [0u8; 512]` with `buf_print_infallible`, which panics on overflow. Two sites: the header line of a package that owns a nested `node_modules` folder (formerly line 764) and the line of every other package (formerly line 890). - A tarball, folder or git resolution repeats the user supplied spec verbatim, so there is no length a stack buffer can be sized to. oven-sh#37469 fixed the same class of panic in the installer and `bun patch`; this printer was left out. ### Fix - Pass the resolution's `Display` formatter (`resolutions[id].fmt(string_bytes, PathSep::Auto)`) straight to `prettyln!` at both sites and delete the buffer and the now unused `buf_print_infallible` import. - Correct because the formatted bytes were only ever printed: the buffer added no information, and removing it removes the only length limit on the path. - Output is unchanged for every label that used to fit. The old code formatted the same `Display` impl into the buffer and re-printed it through `BStr`, and `BStr` prints the valid UTF-8 that `Display` produces byte for byte, so the only observable difference is on labels that used to panic. - This is already how the other two `pm ls` paths print the label: the top-level listing (`bun pm ls`) and `--all --trusted` (`print_trusted_dependencies_flat`) both pass the formatter directly, which is why they never had the problem. - Verified with `test/cli/install/bun-pm.test.ts`, "should list all dependencies when a resolution is longer than 512 bytes": the root depends on two tarballs with ~620 byte URLs plus `[email protected]`; one tarball (`moo`) depends on versions of `bar` and `baz` that conflict with the root's, so it owns a nested `node_modules` and its label goes through the header site, while the other tarball (`bar`) goes through the per-package site. The test asserts the full tree. It fails on the unfixed binary with the panic above and passes with the fix; the rest of `bun-pm.test.ts` and `test/regression/issue/24502/bun-pm-ls-all-invalid-package-id.test.ts` still pass. `cargo fmt --check` and `cargo clippy -p bun_runtime` are clean. ### Background - A package's resolution is the lockfile's record of what it was installed from: a version for registry packages, otherwise the spec itself (tarball URL or path, folder path, git reference). `Resolution::fmt` returns a `Display` formatter that renders it as the `@...` label `bun pm ls` prints after each package name. - `bun pm ls --all` walks the lockfile's hoisted tree one `node_modules` folder at a time. Each folder's header names the package that owns it, and each package inside the folder that does not own a folder of its own gets a line of its own; those are the two print sites. - `buf_print_infallible` (`src/bun_core/fmt.rs`) formats into a caller supplied slice and panics if the output does not fit; it is meant for buffers whose contents have a known bound. The Zig version of this code used `std.fmt.bufPrint` with `try`, so the same overflow used to surface as an error instead of a panic, but `--all` failed either way.
…solved import is imported twice (oven-sh#44340) ### What does this PR do? Fixes `panic: index out of bounds: the len is 0 but the index is 0` in the dev server (`DevServer::is_file_cached`, Sentry BUN-4QTH and BUN-54KE, 16 reports on 1.4.2 and later). **Trigger** An HTML route whose first bundle has a file with an import that does not resolve, and a second file that imports that file: ```ts // entry.ts import "./broken"; import "./other"; // broken.ts import "not-installed-pkg"; export const value = 1; // other.ts (a hop or two further down) import { value } from "./broken"; ``` **Cause** Every file in `IncrementalGraph::bundled_files` is meant to have a bit in `stale_files`. `insert_empty` and `insert_failure` grow the bit set when they add a file. `insert_stale_extra` did not: it set the bit only if the set happened to be long enough already, and left growing it to its callers. `get_log_for_resolution_failures` calls it in the middle of a bundle, for the file whose import failed. With only HTML routes the bit set is still empty during the first bundle, so when the bundler then resolves another import of that file, `is_file_cached` finds it in `bundled_files` and reads a bit that is not there. **Fix** `insert_stale_extra` grows the bit set and sets the bit, with the same two lines as `insert_failure`. The other two inserts, `receive_chunk` and `insert_css_file_on_server`, only run while a bundle is finalized, after all resolution, and `finalize_bundle` grows the set right after them. ### How did you verify your code works? A new test in `test/bake/dev/html.test.ts`. It also fixes the broken file afterwards and expects the page to reload and run. | | the new test | |---|---| | 1.4.2 | fails, with the panic above | | this PR, debug build | passes | The same files outside the test harness panic in 20 of 20 runs on canary `7fe13e1b9`, with 2, 5 and 13 hops between the entry point and the second import. `html.test.ts` and `bundle.test.ts`: 35 pass on the debug build.
…ir with '..' in it (oven-sh#44342) ### What does this PR do? Fixes `panic: range start index 123 out of range for slice of length 119` in `new Bun.FileSystemRouter()` (`RouteLoader::load`, Sentry BUN-564Q and BUN-54X5, 7 reports on 1.4.2), and the wrong route names the same bug gives when it does not panic. **Trigger** An absolute `dir` with `..` in it, which is what `import.meta.dir + "/../pages"` is: ```ts new Bun.FileSystemRouter({ dir: "/app/other/../pages", style: "nextjs" }); ``` | file | route on canary `7fe13e1b9` | expected | |---|---|---| | `pages/index.tsx` | `/` | `/` | | `pages/api/x.tsx` | panic | `/api/x` | | `pages/a-long-directory-name/deeper/page.tsx` | `/ng-directory-name/deeper/page` | `/a-long-directory-name/deeper/page` | **Cause** A route is named by what follows the router's directory in the directory of its file: `&entry_dir[base_dir.len() - 1..]`. The router enters each subdirectory by a normalized path, so that is how the directory of a nested file is spelled. The constructor normalized a relative `dir`, by joining it to the working directory. An absolute `dir` was used as written, with only repeated separators collapsed. With `..` in it, it is longer than the normalized path, so for a nested file the slice starts too far in: inside a directory name, or past the end when the path below the router's directory is shorter than what `..` folds away. **Fix** Both kinds go through the same join, which takes an absolute part as it is and normalizes it. It is the length-checked one, since the string comes from the user. A `dir` too long for the buffer gets the constructor's `Unable to find directory` error. ### How did you verify your code works? A new test in `filesystem_router.test.ts` that compares the routes of both spellings of one directory, with the three files above. | | the new test | |---|---| | 1.4.2 | fails: the child ends with 134 and `panic: range start index 35 out of range for slice of length 31` | | this PR, debug build | passes | `filesystem_router.test.ts`: 36 pass on the debug build. Relative paths with `..`, `.` or doubled separators, absolute paths with doubled separators, and symlinked directories already gave the right routes on canary. **`..` after a symlink** is folded as text, as it already was for a relative `dir`. It did not work for an absolute one before. With `/app/link` a symlink to `/srv/x`, routes in `/srv/pages`, and `dir: "/app/link/../pages"`: | | canary `7fe13e1b9` | this PR | the same path written relative, on both | |---|---|---|---| | no `/app/pages` | throws `ENOENT opening route: /app/pages/index.tsx` | throws `Unable to find directory: /app/pages` | throws `Unable to find directory: /app/pages` | | an unrelated `/app/pages` exists | throws the same `ENOENT` | the routes of `/app/pages` | the routes of `/app/pages` |
… a method (oven-sh#44345) ### What does this PR do? Fixes `panic: internal error: entered unreachable code` in the dev server and in `bun build --react-fast-refresh`, and two kinds of wrong output next to it. ```tsx // app.tsx, in a project that has react installed export class C { m() { return useThing(); } } ``` Serving a page that imports this ends the dev server process. It takes a `.tsx` file, Fast Refresh, and a call to anything named `use[A-Z]...` in a method, getter, setter or constructor. No decorator and no tsconfig is involved. `app.useGlobalPipes()` is such a call. **Cause** A function expression with a hook call in it is wrapped in its signature: `_s(function () { ... }, "hash")`. The function of a method is a function expression to the visitor too, so it was wrapped as well, and a method cannot hold a call. | | before | now | |---|---|---| | class statement in `.tsx` | panic: `lower_class` expects the value of a method to be a function | unchanged method | | class expression, or any class in `.jsx` (with `react-refresh` installed) | `class { m: _s(function() { ... }) }`, a syntax error | unchanged method | | object method | `{ m: _s(function() { ... }) }`: no longer a method, so `super` in it is a syntax error | unchanged method | **Fix** The function of a method already says that it is one: `parse_property` sets `Function::IsUniqueFormalParameters` ("This is true if the function is a method") where it sets `Property::IsMethod`. `e_function` gives such a function no hook storage. A hook call without storage was already ignored. `visit_func` took missing storage for a mistake of its caller and now takes it for "no signature". This is what `react-refresh/babel` does. It emits signatures from two visitors, `FunctionDeclaration` and `ArrowFunctionExpression|FunctionExpression`. A hook call is recorded for its `getFunctionParent()`, so one in a `ClassMethod` or `ObjectMethod` is recorded for a node that nothing reads: it is ignored, and does not count for a function around the method. A function inside a method is still signed. ### How did you verify your code works? Seven new tests in `bundler_jsx.test.ts`, which run the bundle: every kind of class member, a class expression, and an object method that uses `super`, each as `.tsx` and `.jsx`, and one that counts the signatures of a function around a method and a function inside it. `itBundled` gets a `reactFastRefresh` option for them. | | new tests | `bundler_jsx.test.ts` | |---|---|---| | 1.4.2 | 7 fail: the `.tsx` class statement by the panic, the other `.tsx` ones by the output, the `.jsx` ones because the signature brings an import of `react-refresh/runtime`, which the fixture does not have | | | this PR, debug | 7 pass | 64 pass, 0 fail | By hand, the dev server with a stub `react` and the file above plus a component: 1.4.2 and canary `7fe13e1b9` panic. With this PR the page is served, the methods are as written and the component has its signature.
…ven-sh#44351) ### What does this PR do? Puts `console.write` back to how it behaved before oven-sh#43649, and marks the tests that depend on the new behaviour as todo. oven-sh#43649 turned on typechecking for `src/js`. `wrote += writer.write(...)` does not typecheck, because a backed-up `FileSink` returns a Promise instead of a byte count. That PR rewrote the loop to track Promises and added tests for it. One of them, `an awaited console.write rejects with EPIPE when the reader has hung up (several arguments)`, is flaky on `main`: it prints `caught EPIPE` and then dies on an unhandled `EPIPE`. - The old function body is back. Two `as number` casts and the type annotations on `this` are the only differences, and they have no effect at runtime. - Only `console.write` is reverted. The rest of oven-sh#43649 stays. - The two several-arguments test cases are now `test.todo`. They keep their original assertions, and each has a comment with the failure it shows. The one-argument byte count and `EPIPE` tests stay as they were, because the old code passes them. #### Known bugs this brings back Bun 1.4.2 has both, and the two todo tests cover them: - `await console.write(big, new Uint8Array(3))` gives the string `"[object Promise][object Promise]"` when stdout is backed up. - `await console.write(big, "tail")` to a reader that hung up dies on an unhandled `EPIPE`, even inside `try`/`catch`. #### Not changed `packages/bun-types/globals.d.ts` still declares `number | Promise<number>`. That is correct for one argument. ### How did you verify your code works? - `bun bd test test/js/bun/console/console-write.test.ts`: 4 pass, 2 todo on a Linux debug build. - With `--todo`, both todo tests fail in the way their comments describe. - Before the todo tests were added, the same file ran 200 times, 8 at a time, on that build: 200 passes. - The 4 tests that run also pass on Bun 1.4.2, which has the old implementation. - `bun x tsc --noEmit -p src/js/tsconfig.json` passes. - Not run on macOS or Windows.
…ists (oven-sh#44196) A TLS socket over a `stream.Duplex` (`tls.connect({ socket })`, `new TLSSocket(duplex)`) has no fd. Bun runs a TLS engine over the stream, and a queued task starts that engine after the wrap. "Before the engine" below is the rest of the script, `process.nextTick`, microtasks and promise jobs. The lost EOF needs the close hook of oven-sh#39066. The freed listener functions need the `pending_close` branch of oven-sh#42176. No release has either. ### What the TLS socket emits | The transport, before the engine | Node v26.10 | main | This PR | |---|---|---|---| | Client: EOF, close | `end`, ECONNRESET, `close` true | `close` false | as Node | | Server wrap: EOF, close | `end`, `close` false | `close` false | as Node | | Client: bytes, EOF, close | `end`, ECONNRESET, `close` true | `close` false | as Node | | Server wrap: bytes, EOF, close | `end`, `close` false | `close` false | as Node | | Client: non-TLS bytes, EOF | ERR_SSL_HTTP_REQUEST, `close` true | `secureConnect`, `end`, `close` false | `end`, ECONNRESET, `close` true | | Server wrap: a complete ClientHello, EOF | `end`, 1 write | `end`, 1 write | as Node | | Server wrap: a complete ClientHello, EOF, close | `close` false | `close` false | `end`, `close` false | Last row: Node writes its answer to the ended transport, and that failure closes the socket ahead of `end`. The same rows after the engine started do not change. ### What happens to the transport | Case | Node v26.10 | main | This PR | |---|---|---|---| | `tls.connect({ socket: netSocket }).destroy()` in the same tick | raw socket closed, peer gets a FIN | raw socket open, no FIN | as Node | | The socket or the transport is destroyed after the engine started | no `end()`, `writableEnded` false | `end()` on the destroyed transport, `writableEnded` true | as Node | | 16 wraps closed before the engine, a GC, then 8 new wraps | | 7 of 8 never reach `secureConnect` | 8 of 8 answer | Last row: the close left the four listener functions of the context set. The GC freed them, and the task that frees the context then wrote into the freed cells. ### What the transport throws | Case | Node v26.10 | main | This PR | |---|---|---|---| | The `write` getter throws (the ClientHello) | `uncaughtException` | the exception stays pending on the VM (debug build: panic) | `error` on the socket, `close` true | | The `end` getter throws, close after the engine started | `end` is not read | the exception stays pending on the VM (debug build: assertion) | `uncaughtException` | | `end()` throws, close after the engine started | `end()` is not called | dropped | `uncaughtException` | | `end()` or its getter throws, close before the engine | `end()` is not called | `end()` is not called | `uncaughtException` | The `end` rows need a transport that is not ended and not destroyed when the socket closes. ### Behavior changes | Case | Before | After | |---|---|---| | Close before the engine, transport not ended and not destroyed | the transport is left as it is | `end()` is called on it | | `end()` of the transport throws during the close | dropped | uncaught exception | | Close after the engine started, transport destroyed | `end()` is called, `writableEnded` true | no call, `writableEnded` false | | EOF before the engine | held until the engine starts | reported inside the transport's `'end'` | | Client, EOF only, before the engine | 1 write (the ClientHello) | 0 writes (Node: 1) | | Client, bytes ahead of an EOF, before the engine | the engine reads them | not read, so an SSL error in them shows as ECONNRESET | | Server wrap, `socket.end()` in an `'end'` listener | transport `writableEnded` true, `final` not called | `writableEnded` false, `final` not called (Node: true, `final` called, see oven-sh#42350) | ### Not in this PR - oven-sh#32929: non-TLS bytes give a client `secureConnect`. - oven-sh#38058: a server wrap whose handshake fails gets no `'close'`. - oven-sh#43392: an extra `'end'` ahead of `'close'` when the socket is destroyed after the engine started. - oven-sh#42350: `socket.end()` ends the transport. - oven-sh#38028: destroy a wrapped `net.Socket`, as Node does. This PR ends it. ### Tests `node-tls-connect.test.ts` and `node-tls-duplex-close-throw-uaf.test.ts`: 25 fail on main (9f70da0), 0 fail with this PR. `test/js/node/tls` and `test/js/node/http2`: 1077 pass, 0 fail. Debug + ASAN, macOS arm64. <!-- robobun:evidence:begin --> --- **[human-review]** gate passed · iteration 3 · 4 files touched <details><summary>fails on main (without fix)</summary> ```console ASAN without fix: 15 failed, 18 skipped $ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/pr_gate.xml" test/js/node/tls/node-tls-connect.test.ts test/js/node/tls/node-tls-duplex-close-throw-uaf.test.ts bun test v1.4.3 (367d939) test/js/node/tls/node-tls-duplex-close-throw-uaf.test.ts: (pass) tls.connect({socket: Duplex}) does not read freed Handlers > when a pre-open duplex error races StartTLS [1332.69ms] (pass) tls.connect({socket: Duplex}) does not read freed Handlers > when duplex.end() throws after close [1443.48ms] 25 | const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); 26 | 27 | // On failure stderr carries the ASAN "use-after-poison" report; include 28 | // it in the assertion so the diff shows the crash rather than just an 29 | // empty stdout. 30 | expect({ stdout: stdout.trim(), stderr, exitCode }).toEqual({ stdout: expected, stderr: "", exitCode: 0 }); ^ error: expect(received).toEqual(expected) { "exitCode": 0, "stderr": "", "stdout": - "the duplex closes, end() calls: 1 - the soc ... (truncated) release without fix: 34 failed, 22 skipped bun test v1.4.3-canary.1 (367d939) test/js/node/tls/node-tls-duplex-close-throw-uaf.test.ts: (skip) tls.connect({socket: Duplex}) does not read freed Handlers > when duplex.end() throws after close (skip) tls.connect({socket: Duplex}) does not read freed Handlers > when a pre-open duplex error races StartTLS (skip) tls.connect({socket: Duplex}) does not read freed Handlers > when duplex.end() throws after a close that comes before StartTLS (skip) tls.connect({socket: Duplex}) does not read freed Handlers > when an EOF listener destroys the socket and throws before StartTLS test/js/node/tls/node-tls-connect.test.ts: (pass) should have checkServerIdentity [0.20ms] (pass) should thow ECONNRESET if FIN is received before handshake [8.07ms] (pass) initializes authorizationError to null in the TLSSocket constructor [0.16ms] (pass) setMaxSendFragment mirrors OpenSSL's [512, 16384] acceptance without throwing [3.07ms] (pass) should be able to grab the JSStreamSocket constructor [0.23ms] (skip) tls.connect > should work with alpnProtocols (pass) tls.connect > Bun.serve() should work with tls and Bun.file() [42.60ms] (pass) tls.connect > should have peer certificate when ... (truncated) ``` </details> <details><summary>passes on PR (with fix)</summary> ```console ASAN with fix: 18 skipped $ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/pr_gate.xml" test/js/node/tls/node-tls-connect.test.ts test/js/node/tls/node-tls-duplex-close-throw-uaf.test.ts bun test v1.4.3 (367d939) test/js/node/tls/node-tls-duplex-close-throw-uaf.test.ts: (pass) tls.connect({socket: Duplex}) does not read freed Handlers > when duplex.end() throws after close [2203.98ms] (pass) tls.connect({socket: Duplex}) does not read freed Handlers > when a pre-open duplex error races StartTLS [1670.45ms] (pass) tls.connect({socket: Duplex}) does not read freed Handlers > when duplex.end() throws after a close that comes before StartTLS [2263.36ms] (pass) tls.connect({socket: Duplex}) does not read freed Handlers > when an EOF listener destroys the socket and throws before StartTLS [2238.29ms] test/js/node/tls/node-tls-connect.test.ts: (pass) should have checkServerIdentity [2.07ms] (pass) should thow ECONNRESET if FIN is received before handshake [276.06ms] (pass) initializes authorizationError to null in the TLSSocket constructor [6.64ms] (pass) setMaxSendFragment mirrors OpenSSL's [512, 16384] acceptance without th ... (truncated) release with fix: 22 skipped $ bun scripts/build.ts --profile=release [configured] bun-profile → bun (stripped) target linux-x64-gnu build type Release build dir ./build/release revision 562c022 features lto, baseline 23 deps, 136 codegen, 1176 objects in 4630ms 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 244 units: 172 lib, 16 proc-macro (host), 19 custom-build (host), 15 run custom-build, 17 lib (host), 4 run custom-build (host), 1 rlib [3/4] reconfigure [1/1499] mkdir stamps [2/1499] mkdir codegen [3/1499] install /workspace/bun bun install v1.4.3-canary.1 (367d939) Checked 26 installs across 65 packages (no changes) [730.00ms] [4/1499] rustc unicode_ident [5/1499] rustc build_script_build [6/1499] rustc heck [7/1499] install /workspace/bun/packages/bun-error bun install v1.4.3-canary.1 (367d939) Checked 1 install across 2 packages (no changes) [110.00ms] [8/1499] rustc build_script_build [9/1499] rustc unicode_xid [10/1499] rustc build_script_build [11/1499] rustc build_s ... (truncated) ``` </details> <details><summary>diff hotspot</summary> ``` src/runtime/socket/UpgradedDuplex.rs | 41 +-- src/runtime/socket/socket_body.rs | 2 +- test/js/node/tls/node-tls-connect.test.ts | 332 ++++++++++++++++++++- .../tls/node-tls-duplex-close-throw-uaf.test.ts | 103 ++++++- 4 files changed, 451 insertions(+), 27 deletions(-) ``` </details> **gate history** · 1 passed · 3 rejected · iteration 3 <details><summary>evidence per changed file</summary> ``` file reads edits tests src/runtime/socket/UpgradedDuplex.rs 8 6 68 src/runtime/socket/socket_body.rs 7 2 68 test/js/node/tls/node-tls-connect.test.ts 6 5 54 test/js/node/tls/node-tls-duplex-close-throw-uaf.test.ts 2 1 43 ``` </details> <!-- robobun:evidence:end --> --------- Co-authored-by: Jarred Sumner <[email protected]>
### What does this PR do? Fixes oven-sh#41012 Fixes a use-after-free in `bun --hot`: it goes on reading the promise of the entry point after the promise has been collected. What happens next depends on what the memory is used for. | the cell is reused by | `--hot` | |---|---| | a promise of the program's that was rejected and handled | prints that error as if the entry point had thrown it | | a promise of the program's that is pending | never reloads again | | something that is not a promise | `panic: internal error: entered unreachable code: invalid JSPromise status 255`, or a segfault in `isTerminationException` under `unhandled_rejection` | The first two reproduce every time, below. The third is 21 crash reports on 1.4.2, 11 on macOS arm64 and 10 on Windows, every one from a process with an HTTP server, and oven-sh#41012: a segfault in the read of the status itself, in `report_exception_in_hot_reloaded_module_if_needed`, at an address that ends in `0x…B90`, a cell plus the `0x10` of the word below. I could not reproduce that one, see the end of the next section. **Cause** `VirtualMachine::pending_internal_promise` is the promise of the latest load of the entry point. `--hot` looks at it on every tick, in `report_exception_in_hot_reloaded_module_if_needed`, and again in `reload`: its status, and its result if it is rejected. That goes on for as long as the process runs, long after the promise has settled. It was a `*mut JSInternalPromise` with nothing to keep the cell alive: ```rust self.pending_internal_promise = Some(promise); self.pending_internal_promise_is_protected = false; JSValue::from_cell(promise).ensure_still_alive(); // for this moment only ``` Only the preload path called `protect()`, hence the second field. Once the cell is collected and its memory is used for something else, the status is whatever is there (the panic), or it reads as rejected and the "result" is handed to `unhandled_rejection` (the segfaults). **Reproduction** A `--hot` server whose handler calls `Bun.gc(true)` for `/gc` and makes and keeps 20,000 promises for `/promises`. Save the file once, wait half a second, then `curl /gc`, `curl /promises`, and save the file again. Release builds, Linux x64, no debugger: | | 20,000 rejected and handled: prints `error: someone else's, and handled` | 20,000 pending: the second save never reloads | |---|---|---| | 1.4.2 | 3 of 3 | 3 of 3 | | canary `7fe13e1b9` | 5 of 5 | 5 of 5 | | this PR (CI's build of 853225e) | 0 of 5 | 0 of 5 | The 1.4.2 profile build under lldb, with a breakpoint on `report_exception_in_hot_reloaded_module_if_needed` that logs the pointer (`vm + 0x7328`) and the word it reads the status from (`+ 0x10`, bits 48 and 49), and a handler that lists the address of every `Promise` in `generateHeapSnapshotForDebugging()` after `Bun.gc(true)`: | | the pointer | the word | |---|---|---| | first load | is a live `Promise` | `0x000d000000000000` | | after one reload, 3 runs | is not among the live `Promise`s | `0x000d000000000000` | | then 20,000 rejected promises | is a live `Promise` again, another one | `0x000e000000000000` | | then 20,000 pending promises, instead | the same | `0x0000000000000000` | Whether the promise is collected depends on where the collection starts from, because of what is left on the stack. After a reload, the new load calls `Bun.gc(true)` from a callback, makes 20,000 pending promises, and the file is saved again. Runs in which that save never reloads, of 4, release builds, Linux x64: | the collection starts from | 1.4.2 | canary `7fe13e1b9` | |---|---|---| | `setImmediate`, `setTimeout(0)`, `crypto.randomBytes`, `zlib.gzip`, the exit of a child, `fs.readFile` then `setImmediate` | 4 | 4 | | `fs.readFile`, `fs.promises.readFile`, `Bun.file().text()` | 0 | 4 | | `fs.stat` | 0 | 0 | | a request sent the moment the new load prints, up to ten of them (8 runs) | 0 | 0 | The first load's promise is kept alive by a local of `Run::start`, found by the conservative scan: in a debug build stopped in `JSC__VM__runGC` under the request handler, 4 of the 6 stack words that hold its address are in that frame. For the panic the two bits have to read 3, which no promise has, so the block has to be freed and used for something else. I tried to get there by filling the promise blocks before the reload and flooding the heap with objects of doubles, of integers, typed arrays and strings afterwards, after a reload that works and after one that fails: 25 runs on 1.4.2 and canary, no crash. **Fix** One `jsc::strong::Optional` in place of the pointer and the flag, behind `pending_internal_promise()` and `set_pending_internal_promise()`. The `protect()` / `unprotect()` pairs, the flag and the `ensure_still_alive()` calls go. It is released where `overridden_main` is. **What it shows in `heapStats()`** Every process now has one more protected `Promise`, where before only one with a preload did. The readers that go on after the load are all behind `is_watcher_enabled()`, so the handle could be kept to `--hot` and `--watch`. That would make each of the eight places that store it conditional, with the hand-over from an overridden `Module.runMain` as a special case: the kind of state to keep in step by hand that this PR removes. So it is held always. Two tests counted strong handles in the whole process from inside the top-level await of their entry point, and expected none of the process's own: `timer-gc-roots.test.ts` (at most 1 `StrongRootBlock` left) and a fixture of `module-graph-isolation.test.ts` (0 protected `Promise`s). They now subtract what is there at their start, as `body-clone.test.ts`, `fetch-leak.test.ts`, `module-graph-gc.test.ts` and `serve-stream-reject-flush-leak-fixture.ts` do. Both pass on canary `7fe13e1b9` as well as with this PR. ### How did you verify your code works? Three new tests in `hot.test.ts`. None waits for time to pass. Two are of the behaviour. After a reload the entry point collects from an `fs.readFile` callback, then from `setImmediate`, then from a `crypto.randomBytes` callback, since which of them finds the stack clean differs between builds. It makes 20,000 promises, pending in one test, rejected and handled in the other. The file is saved again: the third load has to happen, with nothing on stderr. Three runs of the two tests each: | | | |---|---| | 1.4.2, release | 2 fail, 3 of 3 | | canary `7fe13e1b9`, release | 2 fail, 3 of 3 | | this PR's sources undone, debug | 1 fails, 3 of 3 | | this PR, CI's release build of 853225e | 2 pass, 3 of 3 | | this PR, debug | 2 pass, 3 of 3 | The third is of the cause, and does not depend on the stack. The entry point takes a heap snapshot after a full collection and prints how many `Promise`s a `StrongRootBlock` refers to, after the first load and after a reload: 0 on 1.4.2, 1 and 1 with this PR. `hot.test.ts`, debug: 16 pass, 0 fail. `test/cli/hot`, `test/cli/watch`, `test/cli/test/isolation.test.ts`, `expect-extend-preload.test.ts` and `node-module-module.test.js` (preloads, `Module.runMain`, the test runner's loads), debug, before the two tests of the behaviour were added: 130 pass, 1 skip, 0 fail.
Preserve unfinished HTTP aborts through the revocable reader connection and native socket owner, retain immediate headers behind writer ownership, and qualify pipelined ownership handoffs. Keep fork FileSink console completion and CommonJS URL cache identity while integrating upstream fixes.
Preserve the upstream sync history while integrating the fork CI lane and N-API threadsafe-function payload ownership fix. Retain all three Unreleased changelog entries; imported fork source and workflow files are unchanged.
Node 24 and both fork binaries keep the first response attached after a manually emitted close. Explicitly detach after notifying close listeners so the displacement fixture actually exercises revoked ownership. Keep all original pending-reference, regrant, late-use and wire-output assertions; the synced binary passes all 20 cases while the baseline fails 18.
Keep literal # paths in the same module-key representation for ESM and CommonJS. Divergent keys could evaluate one module twice and expose a namespace without an environment during split require() loading. Preserve file-URL encoding for literal question marks and real query/fragment identity. The original split-require regression failed five times on fork main and the sync head, while upstream passed five times. The fix passes all five replays, the full splitting suite, and focused module/URL suites; the added identity regression matches Node 24 and fails before the fix.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Sync 19 upstream commits from
ba3f27d1d1through4b02e1031d6195d96fc0446dfbff49297f89f2d6, preserving the fork's HTTP lifecycle fixes and upstream contributor history. This PR must land with a merge commit.Upstream oven-sh#44217 replaces
NodeHTTPResponse.raw_responsewith a revocable connection andreader()/writer()access. Fork #47 now aborts through the live connection's native socket owner usingreader(). Abort writes no HTTP terminator, does not mark the response successfully complete, and retains pinned-write/body cleanup, parser-aware close, and the captured deferred close callback. Response writes—including the fork's immediateflushHeaders()—remain gated bywriter(). The upstream grant/revocation design is unchanged.The original #47 regressions remain. Four added TCP/TLS cases abort the second or fourth pipelined response after it receives the connection, verifying that preceding completed responses arrive fully and the aborted exchange adds no success response. The original 19 cases and four additions pass against Node 24.21.0. The complete 128-test abort suite passes on both qualified Bun platforms.
Conflict resolutions
NodeHTTPResponse.rs: abortreader(); release request accounting without a synthetic successful response.flush_headerswriter()access.JSCommonJSModule.cpp: failed-load cache evictionrequireMapKeyfor URL identity; accept upstream's removal of the assertion when user code already deleted the entry.ConsoleObject.ts: promise/flush handlingFork main through
ec5e3f3760was merged without rebase, retaining #49's CI lane and #50's TSFN fix unchanged. Its only conflict was additive changelog entries; all were preserved. No workflow conflict occurred, and no workflow implementation was edited. The SDK signpost guard was already part of the fork baseline; no additional SDK patch is included.Native qualification
Preserved native qualification compares baseline
6ea7ca5a2c3e396ad64763dec9d4143aa53590e4with sync5bda8fa8ec267c46df36475c0bc196074d8e2b83, on the same host per platform and the same test source. The hash-verified binaries were reused as requested. They predate the subsequent fork-main merge of #49/#50; the exact integrated head is qualified separately by CI and focused proof below.--lto=off)The initial totals deliberately retain environment and timing failures. After paired environment corrections and isolated replays, no persistent new failure remains in those original 166-file native runs. The later CI bundler failure exposed the inherited fork defect diagnosed and repaired below. Coverage includes all
test/js/node/httpfiles, terminal/PTY, spawn/child_process, bun:sqlite and node:sqlite,bun-run.test.ts, and the fork regression manifest. Type checking, JS lint, formatting within the repository's CI scope, sync-workflow tests (24/24), and actionlint pass. macOS builds stayed above 40 GiB free.Known failures retained for the fork
Issues are disabled, so these remain recorded here:
res.emit("close")transfers ownership. A matched Node 24/baseline/synced probe confirms that all three leave the first response attached, the second queued, and send no bytes. The fixture now explicitly detaches after the close notification; all original revocation assertions remain. The preserved synced binary passes 20/20, while baseline fails 18/20. No runtime behavior or test timeout was changed.watchreplay passes both;fsPromisesWatchstill fails both.SHELL/USER. Paired corrected runs pass child_process and OS suites. Linux's remaining process-test failure is its external Node version pin (26.3.0 versus the host's 24.19.0), identical on baseline and synced.No assertions or test timeouts were weakened. The first Rust-check invocation looked for debug codegen; pointing it to the actual release output produced the complete 12-target pass. The AWS lease was released and its released state verified.
OpenClaw consumer comparison
Frozen OpenClaw checkout:
2fe17061547884d7d8cd22edd0433e1e6e459b6c. Fifty-seven HTTP, server, abort/socket, child-process, and PTY files use the matching binary first on PATH,OPENCLAW_VITEST_RUNTIME=bun, private 0700 home/state/temp directories, and one worker. Baseline/candidate grouping and ordering are matched.Both runs executed the same 57-file order and 670-case inventory. All three files previously interrupted by the disk stop ran: watch-node-http and transfer-revocation pass on both, while payload-verification has the same inherited wording failure. The 18 candidate failures match baseline signatures. Chat-abort passed candidate after a baseline RPC timeout; this is not claimed as a source fix. There are no candidate-only failures in this batch. Durations are observations under host load, not performance claims.
Known consumer failures occur in agentsapi-files, Slack socket dispatch, WhatsApp media upload, RFB probe, embeddings HTTP cleanup, rejection transport, payload verification, control-UI performance script, and realtime-talk smoke. All match the same-host baseline. Isolated paired replays for embeddings, rejection-transport, chat-abort, and the historical portal timeout resumed under the revised disk limits; current outcomes are below. No replay replaces the initial results.
Bundler crash classification and fix
The first native CI run exposed a deterministic inherited fork defect, rather than an upstream defect or flake. The test already exists on fork main. Five isolated runs per release binary on one direct AWS Linux x64 host, with the CI GC/integrity settings, gave:
ec5e3f37600x1866f26177e80x184b02e1031dUpstream main's Buildkite run 122295 also reports success with zero failed jobs. Searches for
41236and the exact test name found the original issue and bundler fixes, but no matching crash report. The upstream/flaky exception is not used for the bundler crash; it was repaired.The literal
#in the fixture directory exposed inconsistent module keys: the fork's ESM resolver encoded the path as a file URL, while CommonJS and the shared file-URL helper retained its filesystem key. Duplicate registry entries could expose a namespace without a module environment; the symbolic crash trace confirms that null environment. The same emitted bundle passes in a plain directory and crashes in a#directory on the old fork with GC stress both on and off.Follow-up
65512c7aa3aligns literal#keys while preserving literal?encoding and real query/fragment identity. The original test is unchanged. A new regression requires static import, file-URL import and require to share one evaluated instance, while a real fragment has a distinct instance. It fails before the fix and matches Node 24 after it.Focused Linux proof: splitting 172 pass / 0 fail / 1 skip / 3 todo; query/fragment 45/45; ModuleGraph 298/298; isolation 412/412; Node modules 65/65; require 14/14; extension handlers 21/21. An initial diagnostic invocation omitted the internal-testing flag and failed the folding-only assertion; restoring the CI flag produced the full pass without a test change. Prettier, clang-format and diff checks pass. Independent P2 review of this follow-up is clean.
Exact-head qualification and CI exception
Final head:
65512c7aa39ec27b125d7278d3a2d9c3fd5f4b25.Native CI run 36877039262 built the exact PR merge ref successfully. It passed 132 of 133 selected test files, including the original bundler regression and the added URL identity test. Its only failure is classified (c), inherited flaky:
compile cache wakes an idle loop for deferred modulesreached its existingidle persistence stalledwatchdog.Five isolated replays per binary on the same AWS host, with CI GC/integrity settings and unchanged deadlines, produced:
ec5e3f376065512c7aa3The complete module suite had also passed 65/65 on the patched source. No stable fix is claimed for this flake; the explicitly authorized flaky-check exception is used. The test remains enabled and unchanged. An initial replay filter selected the neighboring idle-wait test; those results are excluded from this classification.
Format, JavaScript Lint, Source lints, clippy, miri, mordant and lol-html checks are green on the final head. The known Claude environment-validation failure is not a code finding.
Completed isolated consumer comparison
Local replays used the revised 18 GiB start / 15 GiB stop limits, unchanged native case deadlines, one worker and private 0700 home/state/temp directories. Each binary collected the same 65 cases: 58 passed / 7 failed.
Embeddings and rejection-transport failure records match exactly. Chat-abort and portal vary with isolation/timing: every candidate failing case name has a same-host baseline failure in the preserved evidence. The isolated synced chat-abort case additionally observed one active lifecycle mutation during cleanup. Its client RPC timeout does not cancel the server mutation, and cleanup checks the count immediately after closing the socket; source ownership explains how a pending creation can produce that diagnostic. However, the log does not identify the counted owner, and one bounded baseline case replay passed. That additional cleanup assertion is observed only on synced and remains unresolved, not claimed inherited or a proven runtime regression. No consumer source, assertion or deadline was changed, and no stable improvement is claimed from the flipped outcomes.
N-API ownership proof
6ea7ca5a2c5bda8fa8ecBoth preserved Mac binaries predate #50. They were reused without rebuilding Bun; only the small test addon was compiled locally. Thus integrated #50 is proven on exact-head Linux, while the Mac runs establish unchanged pre-#50 behavior. Initial direct Bun fixture launches omitted
--expose-internalsand failed fixture import; those setup failures are excluded from runtime counts. The corrected local run stayed above 21.6 GiB free.Review
Independent Codex P2 reviews of the original sync, fork-main integration, ownership fixture correction, the full initial branch, and the module-key follow-up are clean with no actionable findings. The final full-branch landing review is also scoped-clean at P2. All results and the authorized flaky-check exception are recorded above.
Landed with a merge commit, preserving upstream history. Fork main advanced concurrently with #52; the landing merge retains that already-qualified environment fix unchanged. Its owner files and tests are byte-identical to #52, and the sync does not change that implementation.