Repository navigation
chore(sync): merge upstream Bun through a4f1429148 - #21
Merged
Merged
Conversation
…SQLConnection::encode_request; pin Bind wire bytes (oven-sh#43892) Behaviour change: none Part 1 of 3 of the follow-up to oven-sh#34732 ([plan](oven-sh#34732 (comment))). Rebased on main after oven-sh#43898 merged. ### Problem - Six call sites encode a request's Bind parameters: four in `PostgresSQLConnection::advance` and two in `PostgresSQLQuery::do_run`. Each calls one of three batch writers in `PostgresRequest.rs` directly, and `advance` carries seven copies of the same error arm. - The next two PRs change what happens around that encode. With six entry points each change needs six edits, and a seventh call site can bypass them. ### Fix - `PostgresSQLConnection::encode_request(global, EncodeRequest)` is now the only route to `bind_and_execute`, `prepare_and_query_with_signature` and `parse_and_bind_and_execute`. They and `write_bind` are private to `PostgresRequest.rs`. - `advance` rejects a request whose write failed through one function, `reject_failed_write`, at all seven arms. The one difference between the old arms (a statement's first write marks the statement failed) is its `new_statement` argument. - `postgres-bind-wire.test.ts` pins the exact frontend bytes for 13 kinds of parameter, a binary result column, the `sql()` helper, no parameters, and `prepare: false`. It passes on main without this PR. `wire-frames.ts` gets frontend builders with a layout self-test. - Verified: existing coverage is `sql.test.ts`, `sql-prepare-false.test.ts`, `postgres-prepared-pipeline-reorder.test.ts`, `postgres-split-prepare-reorder.test.ts`, `postgres-simple-query-pipeline.test.ts`, `postgres-bytea-bind.test.ts`, `wire-frames.test.ts`. All 255 tests in `test/js/sql/postgres-*` pass on the debug build. ### Background - A Bind carries the parameter values of one execution. Encoding them calls into JS (`toString`, `toJSON`, getters). - The corpus leaves out the types whose announced format and encoding disagree today (`float4`, `numeric`, `time`, `int4[]`). oven-sh#41976 fixes those. ### Downsides - Per batch: one call and one match on a 3-variant enum of 48 bytes, if `encode_request` is not inlined. No allocation, no syscall. <!-- robobun:evidence:begin --> --- **[human-review]** gate passed · iteration 3 · 6 files touched <details><summary>fails on main (without fix)</summary> ```console ASAN without fix: BUILD FAILED (no junit output) $ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/pr_gate.xml" test/js/sql/postgres-bind-wire.test.ts test/js/sql/wire-frames.test.ts ninja: Entering directory `/workspace/bun/build/debug' [0/2] cargo plan → /workspace/bun/build/debug/rust-target/plan.json FAILED: [code=1] rust-target/plan.json /workspace/bun/build/debug/rust-target/plan.json /workspace/bun/build/release/bun /workspace/bun/scripts/build/stream.ts cargo --console /workspace/bun/build/release/bun /workspace/bun/scripts/build/rust/plan.ts /workspace/bun/build/debug/rust-target/plan.input.json /workspace/bun/build/debug/rust-target/plan.json �[1m�[91merror�[0m: cannot update the lock file /workspace/bun/Cargo.lock because --locked was passed to prevent this help: to generate the lock file without accessing the network, remove the --locked flag and use --offline instead. error: /root/.cargo/bin/cargo build -p bun_runtime --lib … exited with 101 ninja: error: rebuilding 'build.ninja': subcommand failed error: script "bd" exited with code 1 __F:-1:S:0 release without fix: all passed bun test v1.4.3-canary.1 (41e52b1) test/js/sql/wire-frames.test.ts: (pass) mysqlLenencInt encodes per page_protocol_basic_dt_integers.html [0.16ms] (pass) pgErrorResponse encodes per §55.7 [0.17ms] (pass) frontend message builders encode per §55.7 [0.55ms] (pass) postgres: pgAuthenticationOk + pgReadyForQuery are accepted by Bun's parser [6.68ms] (pass) postgres: COPY OUT response frames are consumed and the following result set decodes [3.62ms] (pass) postgres: pgMinimalReadyServer satisfies connect() [0.88ms] (pass) mysql: mysqlHandshakeV10 + mysqlOkPacket are accepted by Bun's parser [1.71ms] test/js/sql/postgres-bind-wire.test.ts: (pass) named statements > null [1.80ms] (pass) named statements > boolean as bool [0.57ms] (pass) named statements > integer as int4 [0.46ms] (pass) named statements > BigInt as int8 [0.50ms] (pass) named statements > double as float8 [0.42ms] (pass) named statements > Date as timestamptz [0.50ms] (pass) named statements > ASCII string as text [0.36ms] (pass) named statements > non-ASCII string as text [0.50ms] (pass) named statements > object as jsonb [0.62ms] (pass) named statements > array as json [0.51ms] (pass) named stateme ... (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/sql/postgres-bind-wire.test.ts test/js/sql/wire-frames.test.ts bun test v1.4.3 (367d939) test/js/sql/wire-frames.test.ts: (pass) mysqlLenencInt encodes per page_protocol_basic_dt_integers.html [12.75ms] (pass) pgErrorResponse encodes per §55.7 [8.47ms] (pass) frontend message builders encode per §55.7 [36.72ms] (pass) postgres: pgAuthenticationOk + pgReadyForQuery are accepted by Bun's parser [380.29ms] (pass) postgres: COPY OUT response frames are consumed and the following result set decodes [236.22ms] (pass) postgres: pgMinimalReadyServer satisfies connect() [46.69ms] (pass) mysql: mysqlHandshakeV10 + mysqlOkPacket are accepted by Bun's parser [69.90ms] test/js/sql/postgres-bind-wire.test.ts: (pass) named statements > null [79.26ms] (pass) named statements > boolean as bool [23.18ms] (pass) named statements > integer as int4 [20.74ms] (pass) named statements > BigInt as int8 [24.29ms] (pass) named statements > double as float8 [20.51ms] (pass) named statements > Date as timestamptz [23.33ms] (pass) named statements > AS ... (truncated) release with fix: all passed $ bun scripts/build.ts --profile=release [configured] bun-profile → bun (stripped) target linux-x64-gnu build type Release build dir ./build/release revision ec7e250 features lto, baseline 23 deps, 136 codegen, 1176 objects in 1214ms ninja: Entering directory `/workspace/bun/build/release' [1/4] fetch rust-argon2 [rust-argon2] up to date [2/4] fetch lolhtml [lolhtml] 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 [1/1493] install /workspace/bun bun install v1.4.3-canary.1 (41e52b1) Checked 26 installs across 65 packages (no changes) [42.00ms] [2/1493] rustc unicode_ident [3/1493] rustc heck [4/1493] rustc build_script_build [5/1493] install /workspace/bun/src/node-fallbacks bun install v1.4.3-canary.1 (41e52b1) Checked 111 installs across 104 packages (no changes) [18.00ms] [6/1493] build.rs build_script_build [7/1493] rustc build_script_build [8/1493] gen generated_host_exports.rs generated_host_exports.rs: 121 exports (host=5, lazy=10, generic=106, r ... (truncated) ``` </details> <details><summary>diff hotspot</summary> ``` src/sql_jsc/postgres/PostgresRequest.rs | 70 ++++++- src/sql_jsc/postgres/PostgresSQLConnection.rs | 162 +++++++---------- src/sql_jsc/postgres/PostgresSQLQuery.rs | 23 ++- test/js/sql/postgres-bind-wire.test.ts | 253 ++++++++++++++++++++++++++ test/js/sql/wire-frames.test.ts | 36 ++++ test/js/sql/wire-frames.ts | 68 +++++++ 6 files changed, 497 insertions(+), 115 deletions(-) ``` </details> **gate history** · 1 passed · 0 rejected · iteration 3 <details><summary>evidence per changed file</summary> ``` file reads edits tests src/sql_jsc/postgres/PostgresRequest.rs 5 4 32 src/sql_jsc/postgres/PostgresSQLConnection.rs 10 1 30 src/sql_jsc/postgres/PostgresSQLQuery.rs 8 3 31 test/js/sql/postgres-bind-wire.test.ts 0 1 16 test/js/sql/wire-frames.test.ts 0 0 21 test/js/sql/wire-frames.ts 3 1 35 ``` </details> <!-- robobun:evidence:end -->
Bumps mordant to c5e56d0, which keeps each build script's baseline count apart and reads member baseline files. Bun's baseline has no build script entries, so it stays as it is.
…oven-sh#43873) ### Problem - `tls.checkServerIdentity("localhost/.evil.test", cert)` accepts a certificate for `*.evil.test`, and so do `tls.connect`, `fetch` and `Bun.connect`. An application that validates the name with a URL parser sees `localhost`. - Both matchers compare an ASCII host as typed (`src/js/node/tls.ts:488`, `src/boringssl/lib.rs:446`), so `*` covers any first label, also `localhost/`. Every Bun release and Node v26.3.0 do this. ### Fix - In both matchers, a DNS host with a character outside letters, digits, `-`, `_` and `.` matches nothing. The rule runs after the IDNA step. It supersedes "an ASCII host is matched as typed" from oven-sh#43040. - IP hosts: the native matcher takes only the strict form of `net.isIP` (`127.1` matched the IP SAN 127.1.0.0). `tls.checkServerIdentity` no longer matches `::1%lo` against a malformed IP SAN. - Verified: `test/js/web/fetch/fetch.tls.wildcard.test.ts` (35 of 183 fail on main, with a sweep of the 62 excluded ASCII bytes). Self-reviewed: 13 concerns, 4 changes made, 3 follow-ups (Notes). ### Background - Two matchers share Node's rules: `checkServerIdentity` in `node:tls`, and a Rust port for the native TLS clients. - Considered: limit only what `*` covers (OpenSSL's rule). Exact matches of such names stay. A revert of oven-sh#43040 opens `evil.test/.example.com` again. ### Downsides - Node v26.8.2 rejects 43 of the 62 bytes (`/`, `?`, `#`, space, `@`). Only Bun rejects the other 19, a literal `*` host, and an exact name like `exact!name.test` against the same SAN. A test that expects Node's result fails. - Cost: 425 bytes less text in the release binary. `tls.checkServerIdentity` for a plain hostname: 2,476 ns per call, main 2,494, noise floor 0.9%. Native: one more host scan per handshake. <details><summary>Notes</summary> **Repro** (no network) ```js const tls = require("tls"); const cert = { subjectaltname: "DNS:*.evil.test", subject: {} }; for (const host of ["localhost/.evil.test", "localhost?.evil.test", "localhost#.evil.test", "localhost\\.evil.test", "db:5432/.evil.test"]) console.log(JSON.stringify(host).padEnd(26), tls.checkServerIdentity(host, cert) ? "rejected" : "ACCEPTED"); ``` | build | result | | --- | --- | | Bun 1.4.2, Node v26.3.0 | ACCEPTED | | main with oven-sh#42977 and without oven-sh#43040 (6d504dd) | rejected | | main 2838e1b | ACCEPTED | | this branch, Node v26.8.2 | rejected | **End to end.** The server has one certificate, `DNS:*.evil.test`. The client dials 127.0.0.1 with `localhost/.evil.test` as `servername` / `tls.serverName`. | entry point | Bun 1.4.2 | main 6d504dd (before oven-sh#43040) | main with oven-sh#43040 | this branch | | --- | --- | --- | --- | --- | | `tls.connect` | authorized | rejected | authorized | rejected | | `fetch` | authorized | authorized | authorized | rejected | The native matcher never had the URL host parse for an ASCII name, so `fetch` and `Bun.connect` accept the name in every build before this one. **Reach.** Only a raw `host` or `servername` string gets there. It takes an application that validates the name with a URL parser (it sees `localhost`, or another single-label name that it trusts) and passes the raw string as `servername`, and an attacker who receives the connection with a `*.evil.test` certificate. It is the mirror image of the case that oven-sh#43040 closed (`evil.test/.example.com` against a raw-string suffix check). One reading of the name is not enough: a name with two readings must not match. **The rule** - The set is letters, digits, `-`, `_` and `.`. An underscore is in it because such names exist (`foo_bar.example.com` under `*.example.com` keeps working). `db.1`, `xn--a.example.com`, a trailing dot and an IP literal keep working. A literal `*` in the host no longer matches a wildcard. - It runs on the name the matcher compares: as typed for an ASCII host, and the UTS #46 form for a host with a non-ASCII code point. So a mapped delimiter (`localhost/.evil.test`) is rejected, and `bücher.example.com` still matches `xn--bcher-kva.example.com`. - JS: an empty label list never matches in `check()`. Rust: `host_is_dns_name` gates the SAN loop and the CN fallback in `check_x509_server_identity`, the one function every native client calls. `X509Certificate#checkHost` keeps OpenSSL's rules, where `*` already covers only letters, digits and `-`. - The error text does not change: `Host: localhost/.evil.test. is not in the cert's altnames: DNS:*.evil.test`. **IP shorthand.** `check_x509_server_identity` asked `ares_inet_pton` whether the host is an IP address. That function is `inet_net_pton` underneath: it reads `127.1` as 127.1.0.0 and `10` as 10.0.0.0, and it takes hex, zero-padded octets and a trailing `/bits`. A resolver reads `127.1` as 127.0.0.1, so such a name has two readings too. With a certificate that has the IP SANs 127.0.0.1, 127.1.0.0, 10.0.0.0, 1.2.3.4 and 1.2.3.0, `fetch` accepted `127.1`, `10`, `0x7f000001`, `127.000.000.001`, `1.2.3`, `1.2.3.4/8` and `127.0.0.1/32` on Bun 1.4.2 and on main, and `tls.checkServerIdentity` rejected each of them. The native matcher now uses `ip_address::parse_strict`, and both reject them. `net.isIP` was already strict. **Zone ids.** `net.isIP` takes an IPv6 address with a zone (`::1%lo`), and `canonicalizeIP()` returns `undefined` for it. It also returns `undefined` for a malformed iPAddress SAN, which the certificate prints as `IP Address:<invalid>`. `tls.checkServerIdentity` then found `undefined` in the list and accepted: with a certificate that has a 5-byte iPAddress SAN, Bun 1.4.2 and main accept `::1%lo` and `fe80::1%eth0`, and Node and the native matcher reject them. The IP branch now needs a canonical form of the host. Both matchers reject a host with a zone, as before for a well-formed SAN. Node strips the zone and accepts `::1%lo` for the IP SAN `::1`. That is a follow-up, because both matchers need it. **Node and prior art.** Of the 62 ASCII bytes outside the set (NUL aside), Node v26.3.0 accepts all 62 in the label under `*`, as Bun 1.4.2 does. Node v26.8.2 rejects 43, because its `url.domainToASCII` step fails on them. It accepts the other 19: tab, CR and LF, which the URL parse drops, and ``!"$&'()*+,;=`{}~``, which are URL host characters. Of the 21 hosts that the tests pin as rejected, v26.8.2 rejects 18 with the same code, reason and host. It accepts `*.wild.test`, `*.example.com` and `exact!name.test`, and the tests mark those rows as Bun only. rustls and mozilla::pkix (Firefox) refuse a reference name that is not a DNS name in the same way, and both allow the underscore. Go limits wildcard matches to valid hostnames and keeps an exact match. **Differential run.** 3,682 pairs of a host and a certificate through `tls.checkServerIdentity` and `fetch` (`tls.serverName`). main: 656 accepted, of which 401 have an ASCII character outside the set (for example `foo\r.wild.test` under `*.wild.test`). This branch: 178 accepted, 0 with such a character. The one difference between the matchers in that run is the empty `serverName`, which means "not set". The run is a script outside the tree. In the tree, the test file now sweeps all 62 bytes through both matchers on one server, and a grid of IP shorthand, zone ids and a malformed iPAddress SAN. **Cost.** Release builds of main 2838e1b with and without this diff. `size`: text 80,659,886 to 80,659,461 bytes (-425, the strict parse replaces two `ares_inet_pton` calls with their 512-byte buffers), data and bss unchanged, file 80,827,936 bytes in both. The first commit alone was +87 bytes. CPU per call from `process.cpuUsage()` for `tls.checkServerIdentity("foo.example.com", cert)`, 2e6 calls, 11 interleaved rounds of main, this diff, main again: 2,494, 2,476 and 2,516 ns. The JS matcher adds one regex test per DNS-name check. The native matcher adds one pass over the host bytes per handshake, and it parses the host once with `core::net` where it called `ares_inet_pton` up to twice. `perf`, `valgrind` and `bloaty` are not on this machine, so there is no instruction count. **Self-review.** It asked for four changes, and all are in: the guard in the JS IP branch, test comments that name the rows only Bun rejects, this description (it supersedes the rule of oven-sh#43040 and splits the rejected names by Node's verdict), and the in-tree sweep in place of the script. Follow-ups, not in this PR: `tls.checkServerIdentity` can call the Rust matcher, so that one implementation is left. `bun_core::ip_address::is_ip_address` still uses `ares_inet_pton` at its other call sites, which only decide whether to send SNI. `bun_boringssl` is not in the crates that CI runs under Miri. **Tests** - `fetch.tls.wildcard.test.ts`: `tls.connect` and `Bun.connect` end to end for `localhost/.example.com` and the U+FF0F form, 12 rows in the `checkServerIdentity == fetch` table (9 rejected, and `foo_bar`, `foo-bar`, `xn--a` accepted), and 13 rows for `tls.checkServerIdentity` with the error text (SAN, CN fallback, an exact odd name, a literal `*`, and `foo_bar` and a trailing dot accepted). The rows for `a b` and `user@foo` from oven-sh#43040 now expect a rejection. Three rows for the native CN fallback (a certificate with the CN `*.cn.a.test` and no SAN, one of them `localhost/.cn.a.test` through `fetch`), and 8 rows for IP shorthand through both matchers. One test sweeps the 62 bytes through both matchers, and 3 rows cover zone ids with a malformed iPAddress SAN. main 8d36bff: 148 pass, 35 fail. This branch: 183 pass. - Also ran with the debug build: `test-tls-check-server-identity.js`, `node-tls-connect-hostname-verification.test.ts`, `node-https-checkServerIdentity.test.ts`, `fetch.tls.test.ts`, `fetch.tls.ipv6.test.ts`, `valkey-tls-verify.test.ts`, `node-tls-cert.test.ts`, `node-tls-connect.test.ts`, `tls-sql.test.ts`. All pass. </details> --------- Co-authored-by: Jarred Sumner <[email protected]>
…st names (oven-sh#43979) Follow-up to oven-sh#43873, found by code reading. Supersedes oven-sh#39931. ### Problem - `bun_core::ip_address` parses with c-ares `ares_inet_pton`, which is `inet_net_pton`. It also takes `127.1`, `0x7f000001`, zero-padded octets and a trailing `/bits`. - `Bun.connect` and `Bun.udpSocket` dial `::` for `::1/64`. On Windows they dial 127.1.0.0 for `127.1`, and elsewhere 127.0.0.1 for `127.0.0.1 db.example`. - fetch, `Bun.connect`, `RedisClient` and `Bun.SQL` verify `0x7f000001` against a certificate for 127.0.0.1. fetch sends no SNI for `127.1`. ### Fix - `is_ip_address`, `is_ipv6_address`, the IPv6 arm of `to_ip_address` and its IPv4 arm on Windows use the `core::net` parser. - Elsewhere the IPv4 arm keeps `inet_aton` and takes a host only when `inet_aton` read it all. The dev server Host check accepts that shorthand too. - Verified on Linux: 75 new test rows in 8 files, 58 fail on main. On Windows: 68 of the rows. - Self-reviewed: 12 concerns raised, 11 addressed. The tarball case has no test. ### Background - SNI is the host name in the first TLS message. RFC 6066 forbids an IP literal there. - Weighed: the strict parse at each call site. It leaves a lenient `is_ip_address` for the callers that oven-sh#42766 and oven-sh#42054 add. ### Downsides - Breaking: a host in hex, zero-padded or `/bits` form no longer matches an IP address in a certificate, only the same text. - Breaking: `Bun.connect` answers `ENOTFOUND` for `"127.0.0.1\n"` and any host with text after whitespace. On Windows also for `0x7f000001` and `127.0.0.1/32`. - Cost: release `.text` -1,024 bytes. Instructions per call fall, with two exceptions: IPv4 shorthand at the dev server (`127.1`: 471 to 1,391) and `::1/64` in `to_ip_address` (520 to 538). <details><summary>Notes</summary> **What changes, by caller** | Function | Callers | A host in shorthand before | Now | | --- | --- | --- | --- | | `is_ip_address` | SNI in `src/http/lib.rs`, `ProxyTunnel.rs`, `WebSocketUpgradeClient.rs`, `WebSocketProxyTunnel.rs` | no SNI | SNI as typed, as `tls.connect` | | | certificate check, `src/boringssl/lib.rs` (file not touched) | `0x7f000001` matched IP:127.0.0.1 | a name: matches a dNSName or CN with that text only | | | `bun install` DNS prefetch, `src/url/lib.rs` | a registry host arrives canonical | the same. A host that the URL parser rejects (`08.1.1.1`) is now prefetched | | `is_ip_address` and `to_ip_address` | dev server Host check, `src/runtime/bake/DevServer.rs` (the one call site that changes) | allowed | what the resolver reads stays allowed (`127.1`), the rest is refused (`[::1/64]`) | | `to_ip_address`, IPv6 arm | `Bun.connect`, `Bun.listen`, `Bun.udpSocket`, `is_valid_hostname`, `strip_ipv6_brackets` (20 call sites) | `::1/64` was the address `::` | not an address: `ENOTFOUND`, `Invalid address`, brackets stay | | `to_ip_address`, IPv4 arm on Windows | the same callers | `127.1` was 127.1.0.0, `127.0.0.1/32` was an address | not an address, as for the Windows resolver | | `to_ip_address`, IPv4 arm elsewhere | the same callers | `127.0.0.1 db.example` was 127.0.0.1, because `inet_aton` stops at whitespace or a NUL | not an address. `127.1` stays 127.0.0.1 | | `is_ipv6_address` | `normalize_dns_name`, brackets of a displayed URL | `::1/64` was IPv6 | not reached: `is_valid_hostname` rejects it first | Shorthand gets to the TLS callers from `tls.serverName`, a proxy in `HTTP_PROXY` or `HTTPS_PROXY`, a tarball URL and a `wss+unix:` URL host. A `fetch` or `wss:` URL host, the `proxy` option and a registry URL go through the URL parser first, which writes `127.1` as `127.0.0.1`. `is_ipv6_address` and `to_ip_address` must change together. `do_lookup` (`src/runtime/dns_jsc/dns.rs`) asks `is_valid_hostname` first, and that asks `to_ip_address`. With a strict `is_ipv6_address` alone, `::1/64` would stay on the c-ares backend, and c-ares reads it as a literal. **Breaking changes, measured.** Linux rows: release builds of one tree that differ only in the two source files. Windows rows: a debug build of this branch against the canary of main (29d9638), on Windows Server 2019 x64. | Case | main | this branch | | --- | --- | --- | | fetch, `ca` set, `tls.serverName` `0x7f000001`, `127.000.000.001`, `127.0.0.1/32`, `127.0.0.1/8`, `::1/128` | verified | `ERR_TLS_CERT_ALTNAME_INVALID` | | `Bun.connect`, `socket.upgradeTLS`, `RedisClient` (`rediss://0x7f000001`), `Bun.SQL` `sslmode=verify-full` | verified | `ERR_TLS_CERT_ALTNAME_INVALID` | | `HTTP_PROXY=https://0x7f000001:PORT` | verified, no SNI | `ERR_TLS_CERT_ALTNAME_INVALID`, SNI `0x7f000001`. On Windows `ENOTFOUND` | | `bun install` of `https://0x7f000001:PORT/pkg.tgz` with `--cafile` | installs | `ERR_TLS_CERT_ALTNAME_INVALID downloading tarball` | | host `127.1` against a certificate with `DNS:127.1`, or `CN=127.1` and no dNSName | rejected | verified | | `127.1`, `10` against IP:127.0.0.1 | rejected | rejected | | `Bun.connect` to `::1/64`, `::1/0`, `2001:db8::1/0`, `[::1/64]` | connects to `::1` | `ENOTFOUND` | | `Bun.udpSocket` `send()` to `::1/64`, `2001:db8::1/0` | delivered to `::1` | throws `Invalid address` | | Windows: `Bun.connect` to `127.1` | connects, the server sees 127.1.0.0 | `ENOTFOUND` | | Windows: `Bun.connect` to `0x7f000001`, `127.000.000.001`, `127.0.0.1/32` | connects to 127.0.0.1 | `ENOTFOUND` | | Windows: `Bun.connect` to `1.2.3.4/8` | dials 1.2.3.4 | `ENOTFOUND` | | Windows: `dns.lookup` of each of these, in Bun and in Node.js v26.3.0 | `ENOTFOUND` | `ENOTFOUND` | | Linux: `Bun.connect` to `127.1`, `0x7f000001`, `2130706433` | connects to 127.0.0.1 | the same | | Linux: `Bun.connect` to `127.0.0.1 db.allowed.example`, `"127.0.0.1\n"`, and the 7 other host names of oven-sh#39931 | connects to 127.0.0.1 (`"12\t7.0.0.1"`: dials 0.0.0.12) | `ENOTFOUND`, with no lookup | | Linux: `Bun.udpSocket` `send()` to `127.0.0.1 rebound.example`, or to `127.0.0.1` and a NUL and more text | delivered to 127.0.0.1 | throws `Invalid address` | **The dev server Host check** | `Host` header | main | this branch | | --- | --- | --- | | `127.0.0.1`, `[::1]`, `localhost` | 200 | 200 | | `127.1:PORT`, `0x7f000001`, `127.000.000.001` (raw, wget 1.25.0, Python 3.13.5 urllib) | 200 | 200. On Windows 403, where no resolver reads them | | `[::1/64]`, `[::ffff:127.1]`, `1.2.3.4/8`, `08.1.1.1` | 200 | 403 | | `2130706433`, `0.0.0.0x1` (`inet_aton` reads them, c-ares did not) | 403 | 200 | | `127.0.0.1 rebound-host.example` (`inet_aton` stops at the space) | 403 | 403 | | `rebound-host.example` | 403 | 403 | An earlier commit of this branch made the check strict, which answered 403 to wget and Python at `http://127.1:PORT`. That stopped no DNS rebinding request: a URL parser writes a dotted quad or rejects the host, so a browser cannot send these forms. The check now takes an IP literal, or a host that starts with a digit and that `to_ip_address` reads as IPv4. Over 25,792 `Host` values, 1,924 go from allowed to refused and 539 from refused to allowed. Each of the 539 has a number as its last label, so none is a DNS name. oven-sh#40946 reports that the check cannot be configured, and oven-sh#40733 adds `development.allowedHosts`. **Measurements.** Release builds on Linux, one tree, the two source files from main against this branch. - Size (`size -A`, `nm -S`): `.text` 58,301,116 to 58,300,092 bytes. File size 80,995,912 bytes in both. `HTTPClient::on_open::<true>` 1,684 to 1,474 bytes, `check_x509_server_identity` 1,481 to 1,336, `parse_strict` 447 to 303, `to_ip_address` 477 to 724, `is_allowed_host_header` 579 to 468. - Instructions per call (`gdb` `stepi` from entry to return, callees included, 3 equal runs per input): | Input | `is_allowed_host_header` | `to_ip_address` | | --- | --- | --- | | `registry.npmjs.org` | 596 to 548 | 367 to 345 | | `localhost` / `example.com` | 592 to 533 (`example.com`) | 386 to 352 / 441 to 409 | | `127.0.0.1` | 617 to 445 | 1,436 to 1,113 | | `::1` (`[::1]` as a Host) | 1,055 to 959 | 424 to 366 | | a 51-byte name | 792 to 465 | 435 to 177 | | a 253-byte name | 724 to 524 | 347 to 216 | | `127.1` | 471 to 1,391 | 1,048 to 813 | | `0x7f000001` | 722 to 1,269 | | | `::1/64` (verdict changes) | | 520 to 538 | - Variants that I measured and dropped: `parse_strict` inlined by LLVM (`.text` +1,024 bytes against main), `parse_strict` for the IPv6 arm too (`to_ip_address("localhost")` 386 to 404), the Host check with `to_ip_address` for every host (`registry.npmjs.org` 596 to 895), and a check of the bytes in the Host check in place of the change in `to_ip_address`. - Stack (`objdump`): `is_allowed_host_header` `sub $0x228,%rsp` to `sub $0x18,%rsp`, `on_open::<true>` `0x278` to `0x68`. Calls into c-ares per check 2 to 0. No allocator call before or after. - Classification by `is_ip_address`, through SNI on the real binaries: 141 server names, 19 go from address to name, 0 go the other way. The result equals `net.isIP` without a zone on every name. - SNI over fetch, a CONNECT tunnel and `wss+unix:`: 28 of 28 shorthand cells change and equal `tls.connect`. 0 of 8 literal cells change. - DNS prefetch calls per `bun install` (`gdb` breakpoint count): `localhost` 1 to 1, `127.1` 0 to 0, `127.0.0.1` 0 to 0, `08.1.1.1` 0 to 1. - `bun run rust:check-all`: 12 of 12 targets, 0 errors. - Not measured: instructions per TLS handshake. `perf`, `valgrind` and `strace` are not on this machine. **Tests.** On Linux with `src/` from main each of the 8 files fails, and only new rows fail in them (58). With this branch they pass: `fetch.tls.test.ts` 56, `fetch.tls.wildcard.test.ts` 158, `proxy.test.ts` 96, `websocket-unix.test.ts` 8, `test/bake/dev/esm.test.ts` 18, `socket-dns-error.test.ts` 29, `udp_socket.test.ts` 230, `tls-reject-before-client-cert.test.ts` 121. On Windows with this branch the same files pass (`websocket-unix.test.ts` is skipped there), and on the canary of main 10 of the 12 UDP rows fail. The 7 rows for oven-sh#39931 came after the Windows run. No new row needs a resolver: a row that expects `ENOTFOUND` has a byte that `is_valid_hostname` refuses, and the rows for `/bits` and for the Windows shorthand are UDP rows, where `send()` throws at once. Same failure set on both Linux builds for `resolve-dns.test.ts`, `node-dns.test.js`, `socket.test.ts`, `serve.test.ts` and `node-dgram.test.js` (they need the network or a user that is not root). The tarball case has no test: the download uses the HTTP client path that the fetch rows pin. **Other open PRs** - oven-sh#43873 changes the two call sites in `src/boringssl/lib.rs` to `parse_strict`. After this PR that gives the same answer. Its hostname rule and its change in `tls.ts` are still needed: 9 of its 11 IP rows pass on this branch alone, and the other 2 are zone rows. Its certificate grid and the one here cover the same names. - oven-sh#39931 makes `to_ip_address` refuse whitespace in the whole host. This PR has that change for IPv4, because the dev server Host check asks `to_ip_address` and must refuse `127.0.0.1 rebound-host.example`. The check here runs after `inet_aton` succeeds, so a host name does not pay for it. The nine host names of its test are rows of `socket-dns-error.test.ts` here. One difference: oven-sh#39931 also refuses whitespace in a `%zone`. This PR leaves the zone as it is on main, because `node:dgram` takes any zone text: `setMulticastInterface("::%lo junk")` succeeds in Node.js v26.3.0 and on main, and throws `EINVAL` with a check of the zone in `to_ip_address`. - oven-sh#37013 adds a NUL check to the three function bodies. The strict parse rejects a NUL, and the `inet_aton` arm now does too, so those three hunks are covered for a host with no `%zone`. Its other hunks are still needed. - oven-sh#42766 and oven-sh#42054 call `is_ip_address` for an SNI decision and get the strict answer with no change. **Not in this PR** - The direct callers of `ares_inet_pton`: `net.SocketAddress` and `net.BlockList` (`SocketAddress.rs`), `dns.setServers` (`dns.rs`), `node_cluster_binding.rs`, `c_ares.rs`, and `canonicalize_ip` in `src/boringssl/lib.rs`. `new net.SocketAddress({ address: "::1/64" })` succeeds, and Node.js throws `ERR_INVALID_ADDRESS`. oven-sh#28792 lists that as a breaking change, and oven-sh#36185 covers the `dns` ones. - The TLS clients that set SNI and never ask: `Bun.connect` and `upgradeTLS` (`socket_body.rs`, `tls_socket_functions.rs`), `Bun.SQL`, HTTP/3 and `node:quic`. They send `127.0.0.1` as SNI. oven-sh#20727 was this defect in `tls.connect`. - A zone: fetch sends the SNI `fe80::1%eth0`, and `net.isIP` says 6 for it. `Bun.connect` dials `::1` for `::1%eth0 junk` with scope 0, as libuv does for a zone that names no interface. Node.js `net.connect` answers `EAI_ADDRFAMILY` for it, because `net.isIP` says 0. That check belongs to the caller, not to `to_ip_address`, which `node:dgram` shares. </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/web/websocket/websocket-unix.test.ts, test/js/web/fetch/fetch.tls.test.ts, test/js/bun/udp/udp_socket.test.ts, test/js/bun/net/tls-reject-before-client-cert.test.ts, test/js/bun/net/socket-dns-error.test.ts, test/js/bun/http/proxy.test.ts, test/bake/dev/esm.test.ts <!-- robobun:evidence:end --> --------- Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
…der, pass thrown non-objects through (oven-sh#36842) Fixes oven-sh#40634 ### Problem - When a queued MySQL query fails on the client, the queue skips the next query, which resolves with another query's rows. In a server, one request's input changes another's response. - The failed query never settles. With `idleTimeout` it rejects late, with `ERR_MYSQL_IDLE_TIMEOUT`. oven-sh#24844 reported it. - The `Err` arm of `advance()` pops the failed head and does `offset += 1` (`src/sql_jsc/mysql/MySQLRequestQueue.rs:176-182`). The guard of `run()` marks the query failed before `reject_with_js_value` runs (`src/sql_jsc/mysql/JSMySQLQuery.rs:394`). ### Fix - `advance()` calls `on_error` and continues. The loop's branch for a completed request retires it. `run()` writes no status, and `do_run` marks the query failed before it rethrows. - Both adapters' query reject callbacks pass a non-object through: a thrown `null` rejects with `null`. - Verified: `test/js/sql/sql-mysql-queued-query-failure.test.ts` (main fails 17 of 18), `test/js/sql/postgres-bind-encode-throw.test.ts` (main fails 4 of 12). Other suites: Notes. - Self-reviewed: 6 concerns raised, 6 addressed. ### Background - The server answers in order, so the client gives each reply to the head of its queue. - A query goes out at once on an idle connection with a prepared statement. Otherwise `advance()` writes it. - oven-sh#33189 and oven-sh#31209 carry the `run()` change only. After this PR, oven-sh#33189 keeps its eviction (oven-sh#42720) and oven-sh#31209 drops that hunk. ### Downsides - A failed query with no rejection handler now raises an unhandled rejection. - Still open: oven-sh#32005, oven-sh#43992, oven-sh#43993. - Release build, 100 successful queries: +0 instructions in `do_run` and `advance`, +195 of 39,326 in `run`. `.text`: unchanged. <details><summary>Notes</summary> **Reply order on main** (one connection, three queries started in one tick, MariaDB 11.8.6) ``` q1 SELECT ? AS v (first use, parameter of 0xFFFFFF bytes) never settles q2 SELECT 'q2' AS marker resolves [{"marker":"q3"}] q3 SELECT 'q3' AS marker never settles ``` With this PR: q1 rejects with `ERR_MYSQL_OVERFLOW`, q2 and q3 get their own rows. - In a `Bun.serve` handler that runs one query for each request, with `max: 1`: one request with a date before 1970 in its query string made two other requests get the row of another request. With this PR each request gets its own row, and the request with the bad date gets the error. With the default pool size the effect is intermittent. - With `idleTimeout: 2` the failed query rejects after 2002 ms with `ERR_MYSQL_IDLE_TIMEOUT` on main. With this PR it rejects after 2 ms with its own error. The examples in `docs/runtime/sql.mdx` use `idleTimeout: 30`. - oven-sh#24844 is an insert of 18,730,521 characters on the first use of a statement. It was a panic in 1.3.2. oven-sh#31221 made it `AnyMySQLError::Overflow`, and since then the query never settles. **What fails in the queue.** A query waits in the queue on the first use of its statement text, or when another query is running. Each of these then never settles on main and rejects with this PR: - a parameter whose `toJSON` throws (an Error, `null`, `undefined`, a string, a number) - a parameter that holds a BigInt or a cycle (`JSON.stringify` throws) - a `Date` outside the range of DATETIME (`ERR_INVALID_ARG_TYPE`) - a parameter or a query text of 16 MiB or more (`ERR_MYSQL_OVERFLOW`) - a wrong number of parameters (`ERR_MYSQL_WRONG_NUMBER_OF_PARAMETERS_PROVIDED`) - a query that shares a statement whose prepare failed (oven-sh#40634) Waiters that hang on main and return with this PR: `sql.begin()`, `sql.close()` and `sql.end()` with no timeout, and a script whose last queries failed. The same query on a prepared statement and an idle connection rejects on main. That is why the existing test "rejects a bind parameter that cannot be framed in a single wire packet" passes: it runs the same statement text once before. **Which edit fixes which symptom** (30 tests in the two files, debug build with ASAN, each edit reverted alone) | Edit reverted | Tests that fail | |---|---| | all of them (main) | 21 | | `fail()` removed from the guard of `run()` | 17 | | `Err` arm of `advance()` | 7 | | `mark_as_failed()` in `do_run` | 1 | | guard in `onRejectMySQLQuery` | 4 | | guard in `onRejectPostgresQuery` | 4 | | none | 0 | - The change to `run()` makes the promise settle. - The change to `advance()` keeps the order of the queries behind the failed one. - The line in `do_run` keeps the state of a query that failed in the call that started it. Built-in JS runs a handle one time, so only the test that runs a handle again sees it. - The two guards let a thrown value that is not an object reach the caller. Before this PR the `Err` arm did not call JS for MySQL. The guard is in the two query callbacks and not in `wrapError`, because `onclose`, `connect()` and `listen()` also call `wrapError` and keep their behaviour. **Tests.** The MySQL tests run on a real server (`describeWithContainer`). To show that a rejected query sends nothing, they read `Com_stmt_prepare` and `Com_stmt_execute` from `SHOW SESSION STATUS`, as `sql-mysql-cached-error.test.ts` does. Each test closes its connection with `close({ timeout: 5 })`. On a build without the fix the queries that never settle then reject with `ERR_MYSQL_CONNECTION_CLOSED`, and the test fails on its assertion. **Measurements.** Release builds of the merge base (29d9638) and of this PR, same flags. `valgrind` and `perf` are not available here, so instruction counts come from gdb single steps (a call counts as one instruction). - Success path, 100 queries on one prepared statement (50 one by one, 50 in one tick): `do_run` 12,351 to 12,351 instructions, `MySQLConnection::advance` 13,720 to 13,720, `run` 39,326 to 39,521. Per entry `run` executes 4 more or 4 fewer instructions. The compiler allocates registers differently. No branch, call or store is added. - `mark_as_failed`, `reject_with_js_value` and `on_error` run 0 times in 20,000 successful queries, on both builds. - Size: `run` 9733 B (was 9740), `advance` 1214 B (was 1422), `do_run` 1429 B (was 1417), `mark_as_failed` 332 B (was inlined into its one caller). `.text` 58,301,116 B and the stripped binary 80,995,912 B do not change. - A query that fails in the call that starts it (100 queries): 1 `mark_as_failed` and 0 native reject callbacks per query, 1 rejection per promise. - A query that fails in the queue (100 queries): 1 `on_error` and 1 `reject_with_js_value` per query, 1 rejection per promise, 0 commands on the wire for it. - After 1,000 failed queued queries and a full GC: `MySQLQuery` objects +0, `Promise` objects +0. - A query that shares a failed prepare and waits behind a written query: rejected before the reply of the query in front in 20 of 20 runs. - The MySQL test file, 20 rounds of 4 concurrent copies on the debug build: 0 of 80 processes fail (1,440 tests). The longest `close()` takes 226 ms against the bound of 5 s. **Other suites** (real MariaDB 11.8.6 and PostgreSQL 17, release builds of the merge base and of this PR) - 12 MySQL test files, 150 tests: the same 9 tests fail on both builds. They need MySQL 8 error texts, MySQL 9 or the TLS container. - 35 PostgreSQL and pool test files, 1,141 tests: the same 18 tests fail on both builds. - The two test files of this PR pass with `BUN_JSC_validateExceptionChecks=1`. **Left open** - oven-sh#32005: the call that starts a query can write it ahead of a request that waits in the queue. A query started from a getter or from `toJSON` during bind can get another query's rows. This PR does not change that. - oven-sh#43992: a thrown object that is not an Error (a plain object, an array, a class instance) is replaced by an empty `MySQLError` on the queue path, as it is by a `PostgresError` on main. A client-side failure rejects with a `MySQLError` on the queue path and with a plain object on the other path. - oven-sh#43993: a statement text of 16 MiB or more rejects with `Overflow failed to prepare query` and no `code`. - oven-sh#27102: MySQL takes no event loop reference when it queues a query. - Not tracked, no effect found: a query that shares a failed prepare behind a written query is rejected from the deferred flush task. Its handler runs no later than the reply of the query in front. - Not tracked, no effect found: `Status::Binding` is set before the packet is framed (`MySQLQuery.rs:145`). Both callers of `run()` now make the request terminal. **Related pull requests** - oven-sh#33189 has the same change to `run()` and the same line in `do_run` (commit c5a4ebc). This PR does not take its eviction of failed prepares, which oven-sh#42720 asks for. - oven-sh#31209 has the same change to `run()` next to its change to `MySQLValue.rs`. - oven-sh#32008 (closed as stale) made `advance()` the only writer. It did not change the `Err` arm. - oven-sh#40273 and oven-sh#35357 rewrite `advance()` and keep both defects. To rebase oven-sh#40273 on this PR: delete `if offset == 0 { queue.discard_if_head(req); } offset += 1;` from its `Err` arm, delete `fail()` from its guard, and add the `do_run` line. - This PR replaces its first version, which had the change to `run()` only. Three reports that were left as comments on it have the same cause and now have tests. **Correction.** The first commit of this PR said that `do_run` rejects through `reject_with_js_value`. It does not. `do_run` throws, and the catch in `src/js/bun/sql.ts` rejects the query. **Evidence block.** In the block below, the line `release without fix: all passed` ran a release binary that was built from this branch. A release build of the merge base fails 21 of the 30 tests: 17 of the 18 MySQL tests and 4 of the 12 tests in the PostgreSQL file. CI ran the MySQL test file against the MySQL container on four Linux lanes, 18 of 18 pass on each. **Question for a maintainer.** Is the `mark_as_failed()` line in `do_run` wanted? Without it the state of a query that failed in the call that started it is `Pending` or `Binding` and not `Fail`. No public path reads it. A second `run()` on such a handle then blocks the connection. </details> <!-- robobun:evidence:begin --> --- **[human-review]** gate passed · iteration 1 · 6 files touched <details><summary>fails on main (without fix)</summary> ```console ASAN without fix: 21 FAILED $ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/pr_gate.xml" test/js/sql/postgres-bind-encode-throw.test.ts test/js/sql/sql-mysql-queued-query-failure.test.ts bun test v1.4.3 (367d939) test/js/sql/sql-mysql-queued-query-failure.test.ts: Container ready via docker-compose: mysql_plain at 127.0.0.1:3306 (fail) mysql > a parameter whose toJSON throws rejects the query and the queries behind it run in order [5009.65ms] ^ this test timed out after 5000ms. # Unhandled error between tests ------------------------------- 81 | const bad = () => sql`SELECT ${parameter()} AS v`; 82 | 83 | // The first `bad` prepares the statement and the second one shares it. 84 | // Both wait in the queue for the prepare. 85 | const [first, second, one, two, after] = await settle(sql, [bad(), bad(), marker(1), marker(2), commands()]); 86 | expect({ first, second, one, two, after: counts(after) }).toEqual({ ^ error: expect(received).toEqual(expected) { "after": { - "Com_stmt_execute": 3, - "Com_stmt_prepare": 2, + ... (truncated) release without fix: all passed bun test v1.4.3-canary.1 (6372fc9) test/js/sql/sql-mysql-queued-query-failure.test.ts: Container ready via docker-compose: mysql_plain at 127.0.0.1:3306 (pass) mysql > a parameter whose toJSON throws rejects the query and the queries behind it run in order [17.11ms] (pass) mysql > a parameter that holds a BigInt rejects the query and the queries behind it run in order [95.85ms] (pass) mysql > a parameter that holds itself rejects the query and the queries behind it run in order [13.77ms] (pass) mysql > a Date that DATETIME cannot hold rejects the query and the queries behind it run in order [5.17ms] (pass) mysql > a parameter too large for one packet rejects the query and the queries behind it run in order [78.89ms] (pass) mysql > a parameter whose toJSON throws an Error rejects the query with that value [5.27ms] (pass) mysql > a parameter whose toJSON throws a string rejects the query with that value [5.37ms] (pass) mysql > a parameter whose toJSON throws a number rejects the query with that value [1.82ms] (pass) mysql > a parameter whose toJSON throws null rejects the query with that value [1.54ms] (pass) mysql > a parameter whose toJSON throws undefined reject ... (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/sql/postgres-bind-encode-throw.test.ts test/js/sql/sql-mysql-queued-query-failure.test.ts bun test v1.4.3 (367d939) test/js/sql/sql-mysql-queued-query-failure.test.ts: Container ready via docker-compose: mysql_plain at 127.0.0.1:3306 (pass) mysql > a parameter whose toJSON throws rejects the query and the queries behind it run in order [390.41ms] (pass) mysql > a parameter that holds a BigInt rejects the query and the queries behind it run in order [91.84ms] (pass) mysql > a parameter that holds itself rejects the query and the queries behind it run in order [70.70ms] (pass) mysql > a Date that DATETIME cannot hold rejects the query and the queries behind it run in order [42.95ms] (pass) mysql > a parameter too large for one packet rejects the query and the queries behind it run in order [66.40ms] (pass) mysql > a parameter whose toJSON throws an Error rejects the query with that value [31.19ms] (pass) mysql > a parameter whose toJSON throws a string rejects the query with that value [17.22ms] (pass) mysql > a parameter whose ... (truncated) release with fix: all passed $ bun scripts/build.ts --profile=release [configured] bun-profile → bun (stripped) in 2762ms (unchanged) ninja: Entering directory `/workspace/bun/build/release' [1/140] gen JS modules (bundle-modules) Preprocess modules (13063ms) Bundle modules (253ms) Postprocesss modules (244ms) Bundle Functions (824ms) Generate Code (54ms) [14.45s] Bundled "src/js" for production 2597 kb 197 internal modules 13 native modules 50 internal functions across 16 files [2/20] rustc bun_install [3/20] rustc bun_jsc [4/20] rustc bun_ast_jsc [5/20] rustc bun_bundler_jsc [6/20] rustc bun_semver_jsc [7/20] rustc bun_patch_jsc [8/20] rustc bun_css_jsc [9/20] rustc bun_sourcemap_jsc [10/20] rustc bun_sys_jsc [11/20] rustc bun_js_parser_jsc [12/20] rustc bun_http_jsc [13/20] rustc bun_install_jsc [14/20] rustc bun_sql_jsc [15/20] rustc bun_runtime [16/20] link bun-profile ld.lld: warning: Linking two modules of different target triples: 'obj/unified/UnifiedSource-src_jsc_bindings-0.cpp.o' is 'x86_64-pc-linux-gnu' whereas '../../../../root/.bun/build-cache/webkit-35e8970dfd926abf-lto/lib/libJavaScriptCore.a(UnifiedSource-inspector-2.cpp.o at 102520730)' is 'x86_64-unkn ... (truncated) ``` </details> <details><summary>diff hotspot</summary> ``` src/js/internal/sql/mysql.ts | 3 +- src/js/internal/sql/postgres.ts | 3 +- src/sql_jsc/mysql/JSMySQLQuery.rs | 3 +- src/sql_jsc/mysql/MySQLRequestQueue.rs | 8 +- test/js/sql/postgres-bind-encode-throw.test.ts | 35 +++ test/js/sql/sql-mysql-queued-query-failure.test.ts | 254 +++++++++++++++++++++ 6 files changed, 296 insertions(+), 10 deletions(-) ``` </details> **gate history** · 3 passed · 0 rejected · iteration 1 <details><summary>evidence per changed file</summary> ``` file reads edits tests src/js/internal/sql/mysql.ts 1 1 28 src/js/internal/sql/postgres.ts 1 1 28 src/sql_jsc/mysql/JSMySQLQuery.rs 6 5 28 src/sql_jsc/mysql/MySQLRequestQueue.rs 3 2 29 test/js/sql/postgres-bind-encode-throw.test.ts 1 2 18 test/js/sql/sql-mysql-queued-query-failure.test.ts 4 6 21 ``` </details> <!-- robobun:evidence:end -->
… 10 crates (oven-sh#43010) Behaviour change: none ### Problem - Six trait impls in `bun_css` and `bun_semver` have no user on any target. A `--gc-sections` link of the debug objects discards all their methods, and no source line needs them. - Ten crates re-export 24 names that no other crate imports. With `pub` rewritten to `pub(crate)`, rustc reports each one as `unused_imports`. ### Fix - Delete the impls: `DeepClone` and `CssEql` for the arena `ArrayList` and for `bun_ast::Loc`, the helper `eql_list`, `PartialCmp` for `CSSInteger`, and `Slicable` for `ExternalString`. - Trim the 24 names from the `pub use` lists. Four `bun_ini` structs lose their only outside path and become `pub(crate)`. The non-unix `FdT` alias loses its only user and is deleted. - Correct because nothing instantiates the removed impls, and the workspace compiles on every target triple with the deny lints on (what ran where is in Notes). - No new test: no caller can observe a difference. Existing tests that cover this code: `test/js/bun/css/css.test.ts`, `test/cli/install/semver.test.ts`, `test/js/bun/ini/ini.test.ts`, `test/cli/run/env.test.ts`. ### Background - The workspace denies `dead_code`, but rustc exempts each `pub` item that a crate root can reach. A `pub` impl or re-export can stay after its last user is gone. - `DeepClone`, `CssEql`, and `PartialCmp` are the CSS value protocol traits in `src/css/generics.rs`. Generated and hand-written CSS types call them through trait bounds. - `Slicable` lets `Lockfile::str` read a semver string out of the lockfile string buffer. Only `semver::String` is passed to it. <details><summary>Notes</summary> Removed items: - `src/css/generics.rs`: `impl DeepClone for ArrayList<'bump, T>`, `impl DeepClone for bun_ast::Loc`, `fn eql_list`, `impl CssEql for ArrayList<'bump, T>`, `impl CssEql for bun_ast::Loc`, `impl PartialCmp for CSSInteger`. `rg -w eql_list src` has no other hit. - `src/semver/lib.rs`: `impl Slicable for ExternalString`. - `src/dotenv/lib.rs`: re-export `DirEntryProbe`. - `src/ini/lib.rs`: re-exports `ConfigIterator`, `ScopeItem`, `ScopeIterator`, `ToStringFormatter`. The four structs become `pub(crate)` because `unreachable_pub` is denied. All four are still used inside the crate. - `src/install/isolated_install/Store.rs`: re-export `StoreKeyFormatter`. - `src/js_parser_jsc/lib.rs`: re-export `toml_datetime_to_js`. - `src/paths/lib.rs`: re-exports `PlatformT`, `RelPathFacts`, `windows_volume_name_len`, `EnvPathInput`, `PathComponentBuilder`. - `src/spawn_sys/lib.rs`: re-exports `FdT`, `IoCounters`, `WinRusage`, `WinTimeval`. - `src/spawn_sys/spawn_process.rs`: the alias `#[cfg(not(unix))] pub type FdT = i32;`. Every use of `FdT` is in `#[cfg(unix)]` code, so the re-export was the only thing that named the non-unix alias. The `mordant` job found this (`unused_pub`, 1 finding over a baseline of 0). The comment on the `bun_windows_sys` dependency in `src/spawn_sys/Cargo.toml` named the removed re-export, so it now names the alias in `spawn_process.rs`. - `src/tcc_sys/lib.rs`: re-exports `ErrorFunc`, `TCCErrorFunc`, `TCCState`. - `src/threading/lib.rs`: re-export `GuardedLock`. - `src/uws_sys/lib.rs`: re-export `PosixLoop`. - `src/watcher/lib.rs`: re-exports `MAX_EVICTION_COUNT`, `WatchItem`, `WatchItemIndex`. For each re-exported name, `rg -w <name>` finds it in no other crate, in no generated Rust under the codegen directory, and in no path of the form `crate::<name>` or `<crate>::<name>`. Except for the non-unix `FdT` alias, the items themselves stay, because each one is still used inside its own crate. How the candidates were found: 1. The debug objects were linked again with `--gc-sections --print-gc-sections`. 615 Rust functions, methods, and trait impls outside the files of the open dead-code PRs have no surviving symbol. 2. All 615 were deleted at once. `cargo check` ran in a loop for linux-gnu, linux-gnu `--tests`, windows-msvc, apple-darwin, freebsd, android, and musl. Each item that an error named was restored. 12 items survived. Most of the others are Windows-only or macOS-only code. 3. Each crate was checked once with `pub` rewritten to `pub(crate)`. This shows the re-exports and items that are unused inside their own crate. Names that appear in any other crate were kept. Candidates that compiled without them but are not dead, and so are not in this PR: - `ArrayBufferSink::flush`, `FetchRequestBodySink::flush`, `BorderImageSideWidth::deep_clone`. A macro-generated trait method forwards to each inherent method (`Self::flush(self)`, `<$t>::deep_clone(self, bump)`). Without the inherent method the trait method calls itself. The `unconditional_recursion` lint catches it. - `bun_zstd::inflate_embedded` and `inflate_embedded_nul`. `embed_compressed!` calls them only under `cfg(bun_codegen_embed)`, which only release builds set. A removed impl is not always a compile error. A call like `a.eql(&b)` on two `ArrayList` values falls back to `impl CssEql for [T]` through auto-deref. That impl compares the length and then each element, the same as the removed `eql_list`. On the base of the first commit, no symbol of a removed impl survived the link, so no reachable code called one. Overlap with other open dead-code PRs: oven-sh#43976 also edits `src/uws_sys/lib.rs`, in other hunks. No other file in this PR is touched by one. What ran on which tree: - First commit (base 2dee3bd): `bun bd`, `bun run rust:check-all` (12 of 12), and these test files with the debug build: `test/js/bun/css/css.test.ts`, `test/cli/install/semver.test.ts`, `test/js/bun/ini/ini.test.ts`, `test/cli/run/env.test.ts`, `test/internal/source-lints/` (174 tests), `test/js/bun/resolve/toml/toml.test.js`, `test/js/node/path/resolve.test.js`, `test/js/bun/ffi/cc.test.ts`, `test/cli/install/bun-lock.test.ts`. - After the merge of main (f063852) plus the `FdT` commit: `cargo check --workspace` for the host, and `bun run rust:check-all` for both Windows triples (2 of 2). The `FdT` commit changes only code that is compiled out on unix, and CI built the merge commit on every platform (build 120695). The debug build and the test files were not run again locally. </details> <!-- robobun:evidence:begin --> --- **[policy-decision:dep]** gate passed · iteration 6 · 14 files touched <details><summary>passes on PR (with fix)</summary> ```console Dependency/toolchain change; no test proof to run. ``` </details> <details><summary>diff hotspot</summary> ``` src/css/generics.rs | 52 ----------------------------------- src/dotenv/lib.rs | 4 +-- src/ini/lib.rs | 13 ++++----- src/install/isolated_install/Store.rs | 2 +- src/js_parser_jsc/lib.rs | 3 +- src/paths/lib.rs | 7 ++--- src/semver/lib.rs | 6 ---- src/spawn_sys/Cargo.toml | 2 +- src/spawn_sys/lib.rs | 4 +-- src/spawn_sys/spawn_process.rs | 2 -- src/tcc_sys/lib.rs | 4 +-- src/threading/lib.rs | 2 +- src/uws_sys/lib.rs | 2 +- src/watcher/lib.rs | 6 ++-- 14 files changed, 21 insertions(+), 88 deletions(-) ``` </details> **gate history** · 1 passed · 3 rejected · iteration 6 <details><summary>evidence per changed file</summary> ``` file reads edits tests src/css/generics.rs 0 0 1 src/dotenv/lib.rs 0 0 1 src/ini/lib.rs 0 0 1 src/install/isolated_install/Store.rs 0 0 1 src/js_parser_jsc/lib.rs 0 0 1 src/paths/lib.rs 0 0 1 src/semver/lib.rs 0 0 1 src/spawn_sys/Cargo.toml 1 2 0 src/spawn_sys/lib.rs 0 0 2 src/spawn_sys/spawn_process.rs 1 1 2 src/tcc_sys/lib.rs 0 0 1 src/threading/lib.rs 0 0 1 src/uws_sys/lib.rs 0 0 2 src/watcher/lib.rs 0 0 1 ``` </details> <!-- robobun:evidence:end --> --------- Co-authored-by: Alistair Smith <[email protected]>
…on the link line (oven-sh#43704) ### What does this PR do? Removes `archive-link` build mode and the `libbun-<exe>.a` it produced. The link takes objects only, with the dependencies' objects as a lazy group. **The mode.** oven-sh#37733 merged CI's `build-cpp` and `build-bun` steps onto one agent and added `archive-link` for it: every C/C++ object was still archived into `libbun-<exe>.a`, the link read that archive "exactly as `rust-and-link` did with the downloaded one", and the archive and dependency libraries were still uploaded "for reproducing a link locally". Nothing downloads them: every `artifact download` in `.buildkite/ci.ts`, `scripts/runner.node.ts` and the release scripts asks for a zip. Since oven-sh#43650 they are not enough to reproduce a link either (the Rust rlibs were never uploaded). It also meant CI and `--profile=release` linked different inputs: one archive in CI, 1,176 loose objects locally. **What the archive was doing for the link.** Relinking a local release build both ways, with the recorded link command: | | loose objects | one archive | | --- | --- | --- | | objects loaded | 1,176 | 869 | | functions | 79,374 | 79,366 | | `.init_array`, `.data`, exports | same | same | The 307 objects the archive never loaded are dependency files nothing references (BoringSSL assembly for other platforms, unused libarchive readers, SPAKE2, …). Loading them anyway has two effects: - On COFF only COMDAT sections are garbage-collected, so dead dependency code stays in the binary. The first build of this PR failed the Windows x64 baseline scan on `aes128gcmsiv_aes_ks` (AVX), from a BoringSSL file nothing uses. - On ELF `--gc-sections` removes the dead code, but after LTO has counted its calls. Eight BoringSSL / zstd / libwebp helpers stopped being inlined because an unreferenced file also calls them (`x25519_ge_frombytes_vartime` is called from `spake25519.cc`, so `ED25519_verify` is 6,360 bytes with a call instead of 20,709 with the helper inlined). So what the link needs is library semantics for the dependencies, not one archive of everything. This uses the mechanism oven-sh#41330 used for the same problem: `link()`'s `lazyObjects`, a group the linker may take from or leave (lld's `--start-lib … --end-lib`, `/start-lib … /end-lib` through clang-cl), passed in a response file of its own as `-Wl,@<exe>.lazy.rsp`. A static library's semantics without the archive: no `ar` edge, no second copy of the objects. Which dependency objects are lazy: - **Windows**: the assembler outputs, as in oven-sh#41330. Their sections are not COMDATs, so `/OPT:REF` cannot drop them. Compiled objects stay eager; `/OPT:REF` drops their unreferenced COMDATs. - **Every other link that goes through lld** (all of CI, including the cross-linked macOS targets): all of them, which is what keeps the inlining above. - **A native macOS link** goes through Apple's `ld`, which has no such group, and takes them as plain objects. This is the same for every profile: `--profile=ci-build` is `--profile=release` with the CI, Buildkite and prebuilt-WebKit settings. **The baseline scanner.** A different link layout moved one false positive. `_aesni_ctr32_ghash_6x` is a local label at the top of `aesni-gcm-x86_64-win.asm` with no PUBLIC record; a zero-size `S_PUB32` gets a synthesized end at the next named symbol, so the helper was attributed to whichever public lld-link laid out before that object. The allowlist recorded one such neighbour (`rsaz_1024_gather5_avx2`, "ceiling widened to cover the bleed"). From oven-sh#41330, which fixed this: the synthesized end never crosses into the next section contribution, and code no symbol covers is named by its object (`<lib:aesni-gcm-x86_64-win.asm.obj>`, `<lib:libcpmt.lib>`). Gone: - `archive-link`, the big `ar` step, the two upload edges with their rules and pool, and `BunOutput.uploadStamps` - `BuildMode`. `Config.mode` stays as the literal `"full"`: it is the tag that tells a `Config` from a `CodegenConfig`. An unknown `--mode` is an error where the mode is read - the one-value `type BuildMode = "build"` in `.buildkite/ci.ts`, with the parameter that carried it - three checks for an undefined `output.exe`, which is a plain `string` Packaging and uploading the zips is gated on `cfg.buildkite`. `/IMPLIB` stays, with its comment reworded. ### How did you verify your code works? - `tsc -p scripts/build/tsconfig.json` and `prettier --check` are clean; `test/js/bun/perf/linker-order.test.ts` passes (its fixture set the removed mode). - Configured `--profile=ci-build --buildkite=off`: no `libbun-` archive edge, no `bk_upload` rules; the `bun-profile` link edge takes bun's 134 objects and the rlibs, and `bun-profile.lazy.rsp` holds the 1,042 dependency objects between `--start-lib` and `--end-lib`. - Relinked a Linux x64 release build with its recorded link command and the dependency objects in the lazy group: the binary runs zlib / sqlite / argon2 / zstd, and `ED25519_verify`, `VP8Decode` and the other affected functions have the sizes they had when linked from the single archive. - The patched scanner with the updated allowlist on the Windows x64 profile binary CI built for this PR: 0 violations, PASS. `cargo test` in `scripts/verify-baseline-static`: 11 pass. `test/internal/build-*`: 72 pass. - Not verified locally: a Windows or macOS link. This PR's CI builds are the first ones linked this way there;
…42947) ### Problem - Two `node:http` error messages print the proxy username and password. Error messages reach logs and error trackers. - `ERR_PROXY_TUNNEL`, when a proxy rejects `CONNECT`: `Failed to establish tunnel to example.com:443 via http://user:[email protected]:8080: HTTP/1.1 407 Proxy Authentication Required`. `ProxyConfig` stores the raw URL in `href` (`src/js/internal/http.ts:405`), and `establishTunnel()` prints it (`src/js/node/https.ts:168`). Node fixed this as CVE-2026-48615 in nodejs/node@3e9954a88b (v26.3.1). - `ERR_PROXY_INVALID_CONFIG`, when the proxy URL does not parse: `Invalid proxy URL: http://user:[email protected]:99999`. Four throw sites print the raw string. Node still does this. ### Fix - `ProxyConfig` clears the username and password on the parsed URL and stores that `href` (the upstream change). The `Proxy-Authorization` header uses the values read before the clear. - For a string that does not parse, `redactInvalidProxyUrl()` removes everything between `scheme://` and the last `@` (an unescaped `/` in a password ends the authority early). This diverges from Node on purpose, only for a URL with `@`. `http.setGlobalProxyFromEnv()` also loses its `Invalid proxy URL: ` prefix, which Node does not have. - Verified: 4 tunnel cases in `node-http.test.ts` and 7 config cases in `node-http-proxy-url.node.mts` (runs under Node and Bun). 10 of the 11 fail without the fix. - Self-reviewed: 1 concern raised, 1 addressed (see Notes). ### Background - `https.Agent` reads proxy settings from `proxyEnv` (`process.env` with `NODE_USE_ENV_PROXY=1`). `ProxyConfig` holds the parsed result. - An HTTPS request through a proxy starts with `CONNECT host:port`. Any status other than `200` produces `ERR_PROXY_TUNNEL`. - Userinfo is the `user:password@` part of a URL. It becomes the `Proxy-Authorization` header. <details><summary>Notes</summary> - Commit 1 is the port of nodejs/node@3e9954a88b. The `ERR_PROXY_INVALID_CONFIG` part came from review. It diverges from Node, so it is in its own commits and can be dropped without the tunnel fix. - Node v26.3.0 leaks in the tunnel message. v26.3.1 and v24.17.0 have the fix. `test/js/node/test/parallel/test-https-proxy-request-auth-failure.mjs` is now the upstream file, byte for byte. - Tunnel message before: `via http://user:[email protected]:8080`. After: `via http://127.0.0.1:8080/`. The trailing slash comes from URL serialization, same as Node v26.3.1. The upstream assertion is `/via http:\/\/localhost:\d+\/?/`. - Tunnel cases covered: `user:password@`, `user@`, `:password@`, and percent-encoded userinfo. Each case also checks that the proxy still receives the credentials. - No other code reads `ProxyConfig.href`. `_http_agent.ts` and `_http_client.ts` read only `auth`, `protocol` and `proxyConnectionOptions`. - The four `Invalid proxy URL` sites: the `ProxyConfig` constructor and the CR/LF check in `parseProxyUrl` (`src/js/internal/http.ts:401` and `:481`), and two in `http.setGlobalProxyFromEnv` (`src/js/node/http.ts:101` and `:104`). Node: [lib/internal/http.js#L114](https://github.com/nodejs/node/blob/3e9954a88b6a291fc4041aa7ff2b9725f4f86025/lib/internal/http.js#L114) and [lib/http.js#L142-L146](https://github.com/nodejs/node/blob/v26.3.0/lib/http.js#L142-L146). - Message shapes, same as Node v26.3.0: `new http.Agent` and `new https.Agent` print `Invalid proxy URL: <url>`. `setGlobalProxyFromEnv` prints `<url>` alone. A URL with CR or LF gets the prefix from both, because the shared environment parser rejects it first. - `node-http-proxy-url.test.ts` runs `node-http-proxy-url.node.mts` with `node --test` and with `bun test`. The expected messages are Node's own. One line depends on the runtime: Node prints the userinfo, Bun removes it. - Config cases covered: no credentials, no credentials with LF in the host (the control, it passes without the fix), port out of range, LF in the password, unescaped `/` in the password, unescaped `@` in the password, space in the host. - `redactInvalidProxyUrl()` can remove too much, never too little. `http://proxy:99999/a@b` prints as `http://b`. A prefix that is not `scheme://` is dropped too: `http:\\user:pw@host:99999` prints as `host:99999`. - The vendored tests still pass. `test-http-proxy-request-invalid-proxy.mjs` asserts the exact message only for URLs without `@`. The `invalid-credentials` tests match `/Invalid proxy URL/`. `test-http-set-global-proxy-from-env-invalid-url.mjs` checks only the code. - Self-review concern: other sites print the raw proxy URL. 4 are fixed here. The rest are not changed, on purpose: - `src/js/node/_http_agent.ts:615` and `:618`. With `NODE_USE_ENV_PROXY=1`, an invalid proxy URL in the environment throws `ERR_INVALID_URL` at startup. The message is `Invalid URL`. The `input` property holds the raw string, as it does for every `new URL()` failure. Node chose this split in nodejs/node#38614: no URL in the message, the URL in `input`. - `util.inspect(agent)` shows the `Proxy-Authorization` value in the `auth` field of the proxy config. This is not an error, and Node shows the same. - The `$debug` lines that print the proxy config. They do not exist in release builds. - `src/jsc/bindings/webcore/WebSocket.cpp:219`. The WebSocket `proxy` option prints the raw string in its own `Invalid proxy URL: ` SyntaxError. The open PR oven-sh#41698 already changes that line (`urlForErrorMessage(proxyUrl)`), so this PR does not touch it. - Suites run with the debug build: all of `node-http.test.ts` (167 pass, 1 skip), `node-http-proxy-url.test.ts` (Node 10 of 10, Bun 10 of 10), and 47 vendored proxy tests (`test-http-proxy-request*.mjs`, `test-https-proxy-request*.mjs`, `test-http-request-proxy-post*.mjs`, `test-https-request-proxy-post.mjs`, `test-http-set-global-proxy-from-env-*.mjs`). - Repro for the tunnel message, without a network: ```js const https = require("https"); const http = require("http"); const proxy = http.createServer(); proxy.on("connect", (req, socket) => socket.end("HTTP/1.1 502 Bad Gateway\r\nconnection: close\r\n\r\n")); proxy.listen(0, "127.0.0.1", () => { const agent = new https.Agent({ proxyEnv: { https_proxy: `http://user:[email protected]:${proxy.address().port}` }, }); const req = https.request({ host: "example.invalid", port: 443, agent }); req.on("error", e => { console.log(e.code, e.message); agent.destroy(); proxy.close(); }); req.end(); }); ``` - Repro for the config message: `new (require("http").Agent)({ proxyEnv: { http_proxy: "http://user:[email protected]:99999" } })`. </details> <!-- robobun:evidence:begin --> --- **[human-review]** gate passed · iteration 0 · 5 files touched <details><summary>fails on main (without fix)</summary> ```console ASAN without fix: 4 failed, 1 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/http/node-http.test.ts bun test v1.4.3 (367d939) test/js/node/http/node-http.test.ts: (pass) node:http > createServer > hello world [465.97ms] (pass) node:http > createServer > is not marked encrypted (oven-sh#5867) [72.27ms] (pass) node:http > createServer > request & response body streaming (large) [125.22ms] (pass) node:http > createServer > request & response body streaming (small) [76.62ms] (pass) node:http > createServer > listen should return server [43.55ms] (pass) node:http > createServer > listen callback should be bound to server [21.19ms] (pass) node:http > createServer > emits 'listening' on the next tick, before the event loop polls [42.57ms] (pass) node:http > createServer > emits a listen() error on the next tick, before the event loop polls [55.48ms] (pass) node:http > createServer > calls the listen() callback after a retry from the EADDRINUSE 'error' handler [54.50ms] (pass) node:http > createServer > http: closing a server listened from 'beforeExit' > re-emits 'beforeExit' [1584.70ms] (pass) node:http > crea ... (truncated) release without fix: 5 failed, 1 skipped bun test v1.4.3-canary.1 (367d939) test/js/node/http/node-http.test.ts: (pass) node:http > createServer > hello world [11.25ms] (pass) node:http > createServer > is not marked encrypted (oven-sh#5867) [2.72ms] (pass) node:http > createServer > request & response body streaming (large) [5.21ms] (pass) node:http > createServer > request & response body streaming (small) [3.50ms] (pass) node:http > createServer > listen should return server [1.38ms] (pass) node:http > createServer > listen callback should be bound to server [1.22ms] (pass) node:http > createServer > emits 'listening' on the next tick, before the event loop polls [1.59ms] (pass) node:http > createServer > emits a listen() error on the next tick, before the event loop polls [4.87ms] (pass) node:http > createServer > calls the listen() callback after a retry from the EADDRINUSE 'error' handler [2.76ms] (pass) node:http > createServer > http: closing a server listened from 'beforeExit' > re-emits 'beforeExit' [24.66ms] (pass) node:http > createServer > https: closing a server listened from 'beforeExit' > re-emits 'beforeExit' [29.72ms] (pass) node:http > createServer > should use the provided port [1.16ms] (pa ... (truncated) ``` </details> <details><summary>passes on PR (with fix)</summary> ```console ASAN with fix: 1 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/http/node-http.test.ts bun test v1.4.3 (367d939) test/js/node/http/node-http.test.ts: (pass) node:http > createServer > hello world [434.51ms] (pass) node:http > createServer > is not marked encrypted (oven-sh#5867) [67.62ms] (pass) node:http > createServer > request & response body streaming (large) [154.08ms] (pass) node:http > createServer > request & response body streaming (small) [77.19ms] (pass) node:http > createServer > listen should return server [35.65ms] (pass) node:http > createServer > listen callback should be bound to server [49.85ms] (pass) node:http > createServer > emits 'listening' on the next tick, before the event loop polls [41.13ms] (pass) node:http > createServer > emits a listen() error on the next tick, before the event loop polls [54.91ms] (pass) node:http > createServer > calls the listen() callback after a retry from the EADDRINUSE 'error' handler [49.71ms] (pass) node:http > createServer > http: closing a server listened from 'beforeExit' > re-emits 'beforeExit' [1395.64ms] (pass) node:http > crea ... (truncated) release with fix: 1 skipped $ bun scripts/build.ts --profile=release [configured] bun-profile → bun (stripped) target linux-x64-gnu build type Release build dir ./build/release revision 10471f4 features lto, baseline 23 deps, 136 codegen, 1176 objects in 873ms ninja: Entering directory `/workspace/bun/build/release' [1/4] fetch rust-argon2 [rust-argon2] up to date [2/4] fetch lolhtml [lolhtml] 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) [13.00ms] [4/1499] install /workspace/bun/packages/bun-error bun install v1.4.3-canary.1 (367d939) Checked 1 install across 2 packages (no changes) [3.00ms] [5/1499] install /workspace/bun/src/node-fallbacks bun install v1.4.3-canary.1 (367d939) Checked 111 installs across 104 packages (no changes) [6.00ms] [6/1499] esbuild bun-error ../../build/release/codegen ... (truncated) ``` </details> <details><summary>diff hotspot</summary> ``` src/js/internal/http.ts | 23 ++++++++-- src/js/node/http.ts | 6 +-- test/js/node/http/node-http-proxy-url.node.mts | 52 +++++++++++++++++++++- test/js/node/http/node-http.test.ts | 43 ++++++++++++++++++ .../test-https-proxy-request-auth-failure.mjs | 3 ++ 5 files changed, 120 insertions(+), 7 deletions(-) ``` </details> **gate history** · 2 passed · 0 rejected · iteration 0 <details><summary>evidence per changed file</summary> ``` file reads edits tests src/js/internal/http.ts 6 9 34 src/js/node/http.ts 3 2 33 test/js/node/http/node-http-proxy-url.node.mts 1 1 38 test/js/node/http/node-http.test.ts 4 5 30 …test/parallel/test-https-proxy-request-auth-failure.mjs 0 0 42 ``` </details> <!-- robobun:evidence:end -->
…ven-sh#43924) Follow-up to oven-sh#43865. ### Problem - A handshake that finishes on a shut-down or fatal connection reports a passed certificate check. A `tls.Server` with `requestCert` and `rejectUnauthorized: true` emits `secureConnection authorized=true authError=null` for an untrusted client. - The peer can cause it alone, with one bad record behind its `Finished`. A local `end()` during the handshake causes it too. - `ssl_trigger_handshake` (`packages/bun-usockets/src/crypto/openssl.c`) reads `us_internal_ssl_verify_error`, which returns zero for such a socket. `SSLWrapper` (`src/uws/lib.rs`) does the same after a renegotiation. ### Fix - `ssl_trigger_handshake` reads the verdict from the `SSL` when the handshake succeeded. - `SSLWrapper::trigger_handshake_callback` takes a `HandshakeOutcome` and derives the result. A failed handshake reports what it reported before. - The server reports `tlsClientError` once for each connection, as Node does (`src/js/node/net.ts`). - Verified: `test/js/node/tls/node-tls-duplex-end-verify.test.ts` (main fails 8 of 12, Node v26.3.0 passes 12) and `renegotiation.test.ts`. Self-reviewed: 9 concerns raised, 8 addressed. ### Background - Bun has two TLS engines. `openssl.c` serves sockets. `SSLWrapper` serves TLS over a Duplex, a named pipe or a proxy tunnel. - Both report a handshake as `(success, verify error)`. Consumers read error 0 as "verified". - Considered a getter swap per call site. oven-sh#43865 did that and three sites stayed wrong. ### Downsides - Connections that these cases accepted are now refused, or report `authorized=false`. - After a server `end()` in the handshake, Node reports `ECONNRESET`. Bun reports `DEPTH_ZERO_SELF_SIGNED_CERT`. Both refuse the client. - Release `.text`: 58154908 B before and after. `ssl_trigger_handshake`: 175 to 178 instructions, 24 conditional branches both. <details><summary>Notes</summary> **Cases, measured on Node v26.3.0, on `main`, and with this change** The peer's certificate is untrusted in every row. | Case | Node | `main` | This PR | |---|---|---|---| | TCP client, `rejectUnauthorized: false`, `end()` on its last handshake flight (TLS 1.2 and 1.3) | `authorized=false`, `UNABLE_TO_VERIFY_LEAF_SIGNATURE` | `authorized=true`, `authError=null` | same as Node | | Server with `requestCert`, `end()` on its socket in the handshake, `rejectUnauthorized: false` | `authorized=false`, `DEPTH_ZERO_SELF_SIGNED_CERT` | `authorized=true`, then it reads the client's data | same as Node | | Same server, `rejectUnauthorized: true` | `tlsClientError ECONNRESET` | `secureConnection authorized=true`, then it reads the client's data | `tlsClientError DEPTH_ZERO_SELF_SIGNED_CERT` | | Same server, `end()` comes from its `tlsClientError` listener after `handshakeTimeout`, slow client | `tlsClientError ERR_TLS_HANDSHAKE_TIMEOUT`, then `close` | then `secureConnection authorized=true` and the client's data | same as Node | | No `end()`. One bad record behind the peer's `Finished`, client side, `rejectUnauthorized: false` | `authorized=false` | `authorized=true` | same as Node | | Same, server side with `requestCert`, `rejectUnauthorized: true` | `tlsClientError ERR_SSL_*` (the bad record) | `secureConnection authorized=true` | `tlsClientError DEPTH_ZERO_SELF_SIGNED_CERT` | | Rejecting client that resumes a session, `end()` on its last flight | `error UNABLE_TO_VERIFY_LEAF_SIGNATURE` | `secureConnect authorized=true` | same as Node | | Client over a Duplex, `end()` in the first handshake, then the server renegotiates | not reachable, its own `end()` fails the connection | second handshake flips to `authorized=true` | `authorized=false` on both handshakes | | `Bun.connect`, `shutdown()` after the ClientHello, `rejectUnauthorized: false` | n/a | `success=true`, `authorized=true`, `getAuthorizationError()` null | `authorized=false`, error set | With `rejectUnauthorized: true` a TCP client on `main` is safe in the full-handshake rows. The inline reject from oven-sh#43694 reads the verdict directly. A resumed handshake verifies no chain, so the inline reject cannot act there. A slow client with a trusted certificate is accepted after the handshake timeout, on Node and on Bun. That does not change. **Mechanism** - `us_internal_ssl_is_shut_down` is true for a socket whose TCP write side is shut down, for `SSL_SENT_SHUTDOWN`, and for `ssl_fatal_error`. - `end()` during a handshake sends no alert (BoringSSL returns from `SSL_shutdown` while `SSL_in_init`). It still shuts the TCP write side down, and `SSLWrapper` still sets `sent_ssl_shutdown`. The handshake continues to run. - A bad record behind `Finished` makes one `SSL_read` finish the handshake and fail. `ssl_park_fatal_reason` sets `ssl_fatal_error` before the handshake is reported. - Consumers that read error 0 as verified: `TLSSocket::on_handshake` (`src/runtime/socket/socket_body.rs`), `net.ts`, `HttpContext.h` (`Bun.serve`, `node:https`), and the Postgres, MySQL and Valkey clients. **What does not change** - Every failed handshake reports the same result as on `main`. `HandshakeOutcome::Aborted` keeps the old rule for its two sites: zero after a shutdown, else the verdict. - A failed handshake over a Duplex still reports `UNABLE_TO_GET_ISSUER_CERT` for a certificate that never arrived. Open PR oven-sh#32929 covers that. - In a normal handshake the same consumers already get `(success, verdict)`. So no consumer gets a pair that it could not get before. - A transport that closes during the handshake: `destroy()` or `end()` by the peer, and `destroy()` or end of the Duplex, with both policies. `main` and this change give the same events, and none is `secureConnect`. **Self-review** Addressed: 1. The TCP proxy in the tests acted on TCP chunks. It now acts on TLS records, and releases a held flight in one write. 2. No test for the case without `end()`. Three tests added. 3. A rename of the test file from oven-sh#43865 made its diff hard to read. The file keeps its name, and the diff to it only adds lines. 4. Unused derives on the new enum. Removed. 5. `require` inside the new renegotiation test. Replaced with module imports. 6. Failure results must not change, because `net.ts` reads them. Checked with a plaintext peer on both engines: same events as `main`. 7. The verdict can now close the socket from inside `us_internal_ssl_close`. The `ssl_gone` checks already cover a close from a handshake callback there. The new tests run that path on an ASAN build. 8. A handshake that completes after its timeout was reported gave a second `tlsClientError`. The reject branch now checks `kerrorEmitted`, as Node's `onSocketTLSError` does. Not addressed here: 9. `us_internal_ssl_verify_error` keeps its shutdown test for `getAuthorizationError()`. The getter falls back to the stored result of the handshake report, which is now correct. The cleanup is a separate change. **Not in this PR** After `end()` in the handshake, a final flight that arrives in two reads is never reported on a TCP socket. The socket gets no `secureConnect`, no `error` and no `close`. Node reports the handshake. `authorized` stays `false`, so this is a missing report and not a wrong one. It is the same on `main`, and this change does not touch it. **Measurements** Release builds of the base `8884311404` and of this change. - release `.text`: +0 B (`llvm-size -A`, 58154908 B both). Stripped `bun`: 80844320 B both. - `ssl_trigger_handshake`: 178 instructions, 24 conditional branches, 669 B. Before: 175, 24, 649 B (`llvm-objdump`, `llvm-nm -S`). The success path skips the two state tests inside `us_internal_ssl_verify_error` and adds one `s->ssl` test. - X509 verdict reads per successful handshake: TCP 39 and 39, Duplex 20 and 20 (gdb breakpoint hit counts on `us_ssl_socket_verify_error_from_ssl`, 20 handshakes each, debug builds). - Shutdown tests inside the verdict reader: Rust 0 (1 before), C 0. - Syscall counts per handshake: not measured. `strace` and `perf` are not installed on the test machine. The change adds no write, read or shutdown call. **Tests** - `test/js/node/tls/node-tls-duplex-end-verify.test.ts` uses `node:test`, so the same file runs on Node: `node --experimental-strip-types --test` passes 12 of 12. The two tests from oven-sh#43865 are unchanged. Two tests assert a different `tlsClientError` code for each runtime, because Bun reports the certificate check there and Node reports how the connection ended. - `renegotiation.test.ts`: `main` fails 1 of 21, the row with `end()`. The row without `end()` passes on `main` and shows that the rule is not new. Node cannot be the client of the `end()` row. - Also run with this change: `test/js/node/tls/`, `test/js/bun/net/socket.test.ts`, `test/js/bun/http/proxy.test.ts`, `test/js/web/websocket/websocket-proxy.test.ts`, `test/js/web/fetch/fetch.tls.test.ts`, `test/js/node/http2/node-http2.test.js`: 1037 pass, 2 fail. Both failures are the same on a build of `main`: `SNICallback runs even when the requested servername matches the bind hostname` (`localhost` resolves to `::1` on the test machine) and `should not call drain before handshake` (needs `www.example.com`). - 22 ported Node tests that use `tlsClientError`, `handshakeTimeout` or `requestCert` (`test/js/node/test/parallel/test-tls-*.js`, `test-https-*.js`): all exit 0 on `main` and with this change. </details> <!-- robobun:evidence:begin --> --- **[human-review]** gate passed · iteration 0 · 5 files touched <details><summary>fails on main (without fix)</summary> ```console ASAN without fix: BUILD FAILED (no junit output) $ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/pr_gate.xml" test/js/node/tls/node-tls-duplex-end-verify.test.ts test/js/node/tls/renegotiation.test.ts ninja: Entering directory `/workspace/bun/build/debug' [0/2] cargo plan → /workspace/bun/build/debug/rust-target/plan.json FAILED: [code=1] rust-target/plan.json /workspace/bun/build/debug/rust-target/plan.json /workspace/bun/build/release/bun /workspace/bun/scripts/build/stream.ts cargo --console /workspace/bun/build/release/bun /workspace/bun/scripts/build/rust/plan.ts /workspace/bun/build/debug/rust-target/plan.input.json /workspace/bun/build/debug/rust-target/plan.json �[1m�[91merror�[0m: cannot update the lock file /workspace/bun/Cargo.lock because --locked was passed to prevent this help: to generate the lock file without accessing the network, remove the --locked flag and use --offline instead. error: /root/.cargo/bin/cargo build -p bun_runtime --lib … exited with 101 ninja: error: rebuilding 'build.ninja': subcommand failed error: script "bd" exited with code 1 __F:-1:S:0 release without fix: all passed bun test v1.4.3-canary.1 (65eea2a) test/js/node/tls/renegotiation.test.ts: HTTP/1.1 GET https://localhost:46229/ User-Agent: Bun/1.4.3 Accept: */* Host: localhost:46229 Accept-Encoding: gzip, deflate, br, zstd < 200 OK < Content-Type: text/plain < X-Peer-CN: < Date: Thu, 24 Sep 2026 22:06:48 GMT < Connection: keep-alive < Keep-Alive: timeout=5 < Transfer-Encoding: chunked (pass) allow renegotiation in fetch [13.74ms] (pass) should fail if renegotiation fails using fetch [2.80ms] (pass) allow renegotiation in https module [24.80ms] (pass) should fail if renegotiation fails using https [4.71ms] (pass) allow renegotiation in tls module [5.06ms] (pass) pauseOnConnect acts on the first handshake only, not on a renegotiation [105.36ms] (pass) should not crash when socket is closed inside the renegotiation handshake callback [13.31ms] (pass) should terminate the connection when the peer exceeds the renegotiation limit over a duplex socket [224.50ms] (pass) a renegotiation keeps the failed certificate check (end() mid-handshake: true) [97.95ms] (pass) a renegotiation keeps the failed certificate check (end() mid-handshake: false) [100.16ms] (pass) should fail if r ... (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/node/tls/node-tls-duplex-end-verify.test.ts test/js/node/tls/renegotiation.test.ts bun test v1.4.3 (367d939) test/js/node/tls/renegotiation.test.ts: HTTP/1.1 GET https://localhost:39677/ User-Agent: Bun/1.4.3-debug Accept: */* Host: localhost:39677 Accept-Encoding: gzip, deflate, br, zstd < 200 OK < Content-Type: text/plain < X-Peer-CN: < Date: Thu, 24 Sep 2026 22:07:43 GMT < Connection: keep-alive < Keep-Alive: timeout=5 < Transfer-Encoding: chunked (pass) allow renegotiation in fetch [53.61ms] (pass) should fail if renegotiation fails using fetch [14.55ms] (pass) allow renegotiation in https module [1317.12ms] (pass) should fail if renegotiation fails using https [121.66ms] (pass) allow renegotiation in tls module [71.41ms] (pass) pauseOnConnect acts on the first handshake only, not on a renegotiation [138.94ms] (pass) should not crash when socket is closed inside the renegotiation handshake callback [337.80ms] (pass) should terminate the connection when the peer exceeds the renegotiation limit over a duplex socket [ ... (truncated) release with fix: all passed $ bun scripts/build.ts --profile=release [configured] bun-profile → bun (stripped) in 1103ms (unchanged) ninja: Entering directory `/workspace/bun/build/release' [0/2] 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 [1/214] gen generated_host_exports.rs generated_host_exports.rs: 121 exports (host=5, lazy=10, generic=106, rust=0); 245 extern-C blocks audited [2/214] gen BunProcess.lut.h Generating /workspace/bun/build/release/codegen/BunProcess.lut.h from /workspace/bun/src/jsc/bindings/BunProcess.cpp [3/214] gen cpp.rs (cppbind) [4/214] gen JS modules (bundle-modules) Preprocess modules (7364ms) Bundle modules (95ms) Postprocesss modules (197ms) Bundle Functions (518ms) Generate Code (40ms) [8.23s] Bundled "src/js" for production 2597 kb 197 internal modules 13 native modules 50 internal functions across 16 files [5/211] cc obj/packages/bun-usockets/src/crypto/openssl.c.o [6/211] build.rs build_script_build [7/211] rustc bun_platform [8/211] rustc bun_core [9/211] rustc bun_output [10/211] rustc bun_ ... (truncated) ``` </details> <details><summary>diff hotspot</summary> ``` packages/bun-usockets/src/crypto/openssl.c | 5 +- src/js/node/net.ts | 7 +- src/uws/lib.rs | 57 ++-- .../js/node/tls/node-tls-duplex-end-verify.test.ts | 334 +++++++++++++++++++++ test/js/node/tls/renegotiation.test.ts | 94 ++++++ 5 files changed, 470 insertions(+), 27 deletions(-) ``` </details> **gate history** · 1 passed · 0 rejected · iteration 0 <details><summary>evidence per changed file</summary> ``` file reads edits tests packages/bun-usockets/src/crypto/openssl.c 1 2 37 src/js/node/net.ts 2 0 36 src/uws/lib.rs 6 6 38 test/js/node/tls/node-tls-duplex-end-verify.test.ts 2 0 28 test/js/node/tls/renegotiation.test.ts 2 1 16 ``` </details> <!-- robobun:evidence:end -->
… pipe (oven-sh#43806) ### Problem - A TLS server over a Duplex crashes when its `ALPNCallback` calls `socket.write()` or `socket.end(data)`: `panic(main thread): Segmentation fault at address 0xB0`. A remote client triggers it. - Over a synchronous Duplex pair, a `write()` made while the peer's last handshake flight is queued completes the handshake unreported: no `secureConnect` or `secure`, and no `rejectUnauthorized` check. - Cause: `SSLWrapper::write_data` (`src/uws/lib.rs:851`) calls `SSL_write` while the handshake is pending, and `SSL_write` runs `SSL_do_handshake` itself. Inside `ALPNCallback` that call fails, and the close frees the SSL under the running handshake. Elsewhere it can finish the handshake with no `on_handshake`. ### Fix - While the state is `HandshakePending`, `write_data` runs `handle_traffic` and returns `WantRead` without `SSL_write`. Only `update_handshake_state` drives the initial handshake, and it reports every result. - Correct because `UpgradedDuplex` and `WindowsNamedPipe` already park a `WantRead` write and retry it after `on_handshake`. Where `SSL_write` returned `WANT_READ` before, nothing changes. - Verified: 8 new tests in `test/js/node/tls/node-tls-connect.test.ts` fail on a build of `main` and pass with the change. They also pass on Windows x64. ### Background - `SSLWrapper` runs BoringSSL over memory BIOs for TLS on a `Duplex`, a Windows named pipe, or a CONNECT tunnel. - Its `handle_traffic` pass calls `SSL_do_handshake` and fires `on_handshake`, where JS emits `secureConnect` and applies `rejectUnauthorized`. A nested call only flushes, so a synchronous peer's answer stays queued. ### Downsides - `socket.destroy()` from `ALPNCallback` over a Duplex still crashes: it reaches the same free through `close`. oven-sh#31364 defers that teardown. - A failed handshake with a write parked now reports like one with no write: with `rejectUnauthorized: false`, a wrong `secureConnect` before the error (oven-sh#32929 corrects it). <details><summary>Notes</summary> - Found by a code audit of `SSLWrapper`. No user reported it. - The crash on main, from an ASAN debug build: the write in `ALPNCallback` reaches `SSL_write`, whose nested `SSL_do_handshake` fails in `tls_can_accept_handshake_data`. `write_data` takes its error branch: `trigger_close_callback`, `UpgradedDuplex::on_close`, `teardown`, `SSLWrapper::deinit`, `SSL_free`. The outer `SSL_do_handshake` then reads the freed ClientHello in `SSL_select_next_proto`. It happens on TLS 1.2 and 1.3, on Linux and Windows, with the in-memory pair and with a Duplex over a TCP socket. - Repro for the unreported handshake: both sides are `Duplex` streams whose `write()` pushes the chunk into the peer at once. The client issues `tlsSocket.write()` from inside its transport `write()`, after the push. With TLS 1.3 that is the ClientHello write. With TLS 1.2 it is the client's second flight. The server case needs the client created first, so that the client's engine is idle and answers from inside the server's transport write. - Stock `stream.duplexPair()` delivers synchronously too. With it, a server `keylog` listener that writes on the client socket hits the same window on TLS 1.3: the client never emits `secureConnect` on 1.4.3-canary. - Results on 1.4.3-canary, TLS 1.3, a chain that fails verification, default `rejectUnauthorized`: the server gets `secure` with the client certificate and the application data, and the client emits neither `secureConnect` nor `error`. Node v26.3.0 emits the client `error` and the server sees nothing. With the fix Bun does the same. - The measurement behind the second Downsides bullet: a client with `minVersion: "TLSv1.3", maxVersion: "TLSv1.2"` over a Duplex, `rejectUnauthorized: false`, and a write right after `tls.connect()`. 1.4.3-canary: `write callback ERR_SOCKET_CLOSED`, `error ERR_SOCKET_CLOSED`, `close`. With the change: `secureConnect authorized=false UNABLE_TO_GET_ISSUER_CERT` first, then the same three. Without the write both builds emit only that `secureConnect`. Node emits `error ERR_SSL_NO_PROTOCOLS_AVAILABLE`. - The fd-backed path already parks these writes. `us_internal_ssl_write` parks a write made inside `SSL_do_handshake` (`ssl_in_use`) and sets `ssl_read_input_length = 0`, so its `SSL_write` cannot read a peer flight. - Node does not park a write made inside `ALPNCallback`. Its handshake fails with `ERR_SSL_UNEXPECTED_MESSAGE`. Bun's fd-backed path delivers it after the handshake ("writing to the socket from inside SNICallback or ALPNCallback delivers the data after the handshake" in `node-tls-server.test.ts`). The Duplex path now does the same for `write()` and `end(data)`. - The rejected-certificate rows: the identity verdict (`servername` not in the certificate) runs on both TLS versions, the chain verdict on TLS 1.3 only. A TLS 1.2 client has the chain verdict before its second flight, so a client that rejects the chain during the handshake (oven-sh#43767, merged) never reaches that write. On TLS 1.3 the early write still gets past that check on `main`: the chain row fails there with `server received secret`. - A TLS 1.2 client that rejects the chain still sends its client certificate before the `error`, as Node does. A TLS 1.2 renegotiation is still driven by reads and writes. A bare `end()` in the same window does not reach `write_data` with data, and behaves the same with and without the change. - A `debug_assert!` in `update_handshake_state` pins the invariant: the initial handshake never completes outside it. - `data` is not read after `handle_traffic` in the new branch. The nested `on_writable` flush can free the buffer that `data` points into (`buffered_data_for_node_net`). The existing `WANT_READ` branch has the same rule. A review suggested a call to `SSL_write` after `handle_traffic` when the handshake completed inside it. I built that: it is a heap-use-after-free under ASAN in `SSL_write`, and the bytes are not lost without it, because the nested flush sends them. - `ProxyTunnel` and `WebSocketProxyTunnel` write only after `on_handshake`, so the guard does not change them. - Self-reviewed. Addressed: the crash explanation, the TLS 1.2 rejected row that oven-sh#43767 makes unreachable, the claim that only the two broken cases change, the `debug_assert!`, the `end(data)` and TCP rows, and the duplicate Duplex-pair helper. Not in this PR: the `destroy()` case (oven-sh#31364), the failure report (oven-sh#32929). - Rebased on `main` abc26b7. Suites run with the debug build on that base: every file in `test/js/node/tls/` and `test/js/bun/net/`, `proxy.test.ts`, `websocket-proxy.test.ts` and `fetch-proxy-connect-tunnel-split-envelope.test.ts`. Five tests fail, and each fails the same way on a build of `main`: `SNICallback runs even when the requested servername matches the bind hostname` (`ECONNREFUSED` in this container), `concurrent Workers all see the same CA certificate lists` (needs 5.0 to 5.2 s on `main`, over the 5 s default), `node:net handle whose socket never starts connecting is collectable`, `an unref'd Bun.listen() with no other references keeps accepting across GC`, and `should not call drain before handshake` (needs `www.example.com`). - Trial merge with oven-sh#43924 (a3b00db): no conflict. On the merged tree `node-tls-connect.test.ts`, `node-tls-duplex-end-verify.test.ts`, `renegotiation.test.ts`, `tls-reject-before-client-cert.test.ts`, `node-tls-wrapped-socket-close.test.ts` and `node-tls-upgrade.test.ts` pass. - Vendored Node tests run with the debug build: `test-tls-connect-stream-writes`, `test-tls-destroy-stream`, `test-tls-destroy-stream-12`, `test-tls-js-stream`, `test-tls-on-empty-socket`, `test-tls-socket-close`, `test-tls-socket-default-options`, `test-tls-socket-destroy`, `test-tls-socket-failed-handshake-emits-error`, `test-tls-streamwrap-buffersize`, `test-tls-transport-destroy-after-own-gc`, `test-tls-wrap-econnreset-pipe`, `test-tls-wrap-event-emmiter`, `test-double-tls-server`, `test-http2-generic-streams`, `test-http2-generic-streams-sendfile`, `test-tls-inception`, `test-tls-alpn-server-client`, `test-tls-close-error`, `test-tls-handshake-error`. - Windows x64, debug build of the rebased head: `node-tls-connect.test.ts` (96 pass, 1 skip), `tls-reject-before-client-cert.test.ts` (117 pass, 2 skip), and `node-tls-namedpipes.test.ts` (6 pass, with a 60 s timeout). On the earlier base `should work with named pipes and tls` (400 connections) needed 5.8 s on that debug build with the change and 5.9 s without it, so it exceeds the 5 s default there either way. </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: 8 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 bun test v1.4.3 (367d939) test/js/node/tls/node-tls-connect.test.ts: (pass) should have checkServerIdentity [2.95ms] (pass) should thow ECONNRESET if FIN is received before handshake [321.60ms] (pass) initializes authorizationError to null in the TLSSocket constructor [6.80ms] (pass) setMaxSendFragment mirrors OpenSSL's [512, 16384] acceptance without throwing [138.65ms] (pass) should be able to grab the JSStreamSocket constructor [22.65ms] (skip) tls.connect > should work with alpnProtocols (pass) tls.connect > Bun.serve() should work with tls and Bun.file() [132.66ms] (pass) tls.connect > should have peer certificate when using self asign certificate [91.20ms] (skip) tls.connect > should have peer certificate (skip) tls.connect > getCipher, getProtocol, getEphemeralKeyInfo, getSharedSigalgs, getSession, exportKeyingMaterial and isSessionReused should work (skip) tls.connect > should process options correctly when connect is called with only options (skip) tls.connect > should process port a ... (truncated) release without fix: 15 failed, 18 skipped bun test v1.4.3-canary.1 (367d939) test/js/node/tls/node-tls-connect.test.ts: (pass) should have checkServerIdentity [0.05ms] (pass) should thow ECONNRESET if FIN is received before handshake [8.80ms] (pass) initializes authorizationError to null in the TLSSocket constructor [0.27ms] (pass) setMaxSendFragment mirrors OpenSSL's [512, 16384] acceptance without throwing [5.64ms] (pass) should be able to grab the JSStreamSocket constructor [0.37ms] (skip) tls.connect > should work with alpnProtocols (pass) tls.connect > Bun.serve() should work with tls and Bun.file() [6.71ms] (pass) tls.connect > should have peer certificate when using self asign certificate [5.79ms] (skip) tls.connect > should have peer certificate (skip) tls.connect > getCipher, getProtocol, getEphemeralKeyInfo, getSharedSigalgs, getSession, exportKeyingMaterial and isSessionReused should work (skip) tls.connect > should process options correctly when connect is called with only options (skip) tls.connect > should process port and host correctly (skip) tls.connect > should process port, host, and callback correctly (skip) tls.connect > should handle the absence of a callback gracefully (skip) tls.c ... (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 bun test v1.4.3 (367d939) test/js/node/tls/node-tls-connect.test.ts: (pass) should have checkServerIdentity [2.73ms] (pass) should thow ECONNRESET if FIN is received before handshake [304.31ms] (pass) initializes authorizationError to null in the TLSSocket constructor [6.88ms] (pass) setMaxSendFragment mirrors OpenSSL's [512, 16384] acceptance without throwing [96.91ms] (pass) should be able to grab the JSStreamSocket constructor [12.12ms] (skip) tls.connect > should work with alpnProtocols (pass) tls.connect > Bun.serve() should work with tls and Bun.file() [73.43ms] (pass) tls.connect > should have peer certificate when using self asign certificate [74.52ms] (skip) tls.connect > should have peer certificate (skip) tls.connect > getCipher, getProtocol, getEphemeralKeyInfo, getSharedSigalgs, getSession, exportKeyingMaterial and isSessionReused should work (skip) tls.connect > should process options correctly when connect is called with only options (skip) tls.connect > should process port and ... (truncated) release with fix: 18 skipped $ bun scripts/build.ts --profile=release [configured] bun-profile → bun (stripped) target linux-x64-gnu build type Release build dir ./build/release revision b2cb31d features lto, baseline 23 deps, 136 codegen, 1176 objects in 1233ms 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] rustc unicode_xid [4/1499] rustc unicode_ident [5/1499] install /workspace/bun bun install v1.4.3-canary.1 (367d939) Checked 26 installs across 65 packages (no changes) [155.00ms] [6/1499] gen bake.{client,server,error}.js -> bake.client.js, bake.server.js, bake.error.js [7/1499] install /workspace/bun/packages/bun-error bun install v1.4.3-canary.1 (367d939) Checked 1 install across 2 packages (no changes) [4.00ms] [8/1499] gen ErrorCode+*.h [9/1499] gen string-map defines_t ... (truncated) ``` </details> <details><summary>diff hotspot</summary> ``` src/uws/lib.rs | 9 + test/js/node/tls/node-tls-connect.test.ts | 302 +++++++++++++++++++++++++++++- 2 files changed, 306 insertions(+), 5 deletions(-) ``` </details> **gate history** · 2 passed · 0 rejected · iteration 0 <details><summary>evidence per changed file</summary> ``` file reads edits tests src/uws/lib.rs 5 6 55 test/js/node/tls/node-tls-connect.test.ts 8 15 51 ``` </details> <!-- robobun:evidence:end -->
…-sh#43105) Fixes oven-sh#43092. ### Problem - A hostname with more than 10 labels registered with `tls.Server#addContext()` or `Bun.serve({ tls: [{ serverName }] })` gets the default certificate at the handshake. A second `addContext()` for that name throws `Failed to register SNI for '...'`. Node selects the added context. - `sni_add` in `packages/bun-usockets/src/crypto/sni_tree.cpp` walks every label. `sni_remove` and `sni_find` copied labels into a fixed `std::string_view labels[10]` and returned `nullptr` at the 11th label. `MAX_LABELS` was defined but never used. So the name was in the tree but never found or removed. ### Fix - A shared `nextLabel()` helper splits the next label off the remaining hostname. `sni_add`, `getUser` (lookup) and `removeUser` (removal) all use it, so the three accept the same names. - `getUser` recurses on the remaining `string_view`, one frame per label, with no allocation. Its input is the ClientHello server name, which the protocol bounds at 255 bytes. - `removeUser` is iterative with an explicit path vector, because its names come from JS and have no bound. It culls empty nodes upward exactly as before. - Verified: `test/js/node/tls/node-tls-server.test.ts` (two new tests) and `test/js/bun/http/bun-serve-ssl.test.ts` (one new test). All three fail on bun 1.4.3 and pass with this change. Also ran `node-tls-context.test.ts` and the rest of both files. ### Background - The SNI tree maps a dot-separated hostname to an `SSL_CTX`. Each label is a node in a `std::map`. `*` is a wildcard node matched during lookup. - `Listener::add_server_name` (`src/runtime/socket/Listener.rs`) removes the old entry, then adds the new one. When the remove misses, the add reports a duplicate and the JS side throws. - This was found by inspection during oven-sh#43082, not from a user report. `node:tls` users can work around it with `SNICallback`. `Bun.serve` has no such hook. <details><summary>Notes</summary> - A standalone ASAN build of `sni_tree.cpp` was checked with add, find, remove, wildcard, trailing-dot, culling, and a 200000-label name. No leaks, no overflow. - `name` and `name.` still split into the same labels, as before this change. That behavior is unchanged and the tests do not depend on it. - The pre-existing test `SNICallback runs even when the requested servername matches the bind hostname` fails on main in this container because `localhost` resolves to `::1` only. It is unrelated. </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/node/tls/node-tls-server.test.ts <!-- robobun:evidence:end -->
…eturn value (oven-sh#42987) ### Problem - A `tls.checkServerIdentity` function replaces Bun's hostname check, and only an Error return value rejects the certificate (`run_check_server_identity`, `src/runtime/webcore/fetch/FetchTasklet.rs:1213`). A Promise approves it, so an `async` wrapper of `tls.checkServerIdentity` accepts any host: on Bun 1.4.3-canary a `localhost` certificate, dialled as `127.0.0.1`, resolves. - `fetch()` ignores a `checkServerIdentity` that is not a function. `parse_tls` (`src/runtime/webcore/fetch/FetchSession.rs:62`) sets it aside, and only the `Bun.FetchSession` constructor throws for it (oven-sh#42937). - Node and Bun's `node:https` fail the connection in these cases. ### Fix - Every truthy return value fails the request, as in Node: an object is the rejection reason, a Promise or a primitive gives `ERR_INVALID_RETURN_VALUE`. A falsy value, a thrown value and `rejectUnauthorized: false` behave as before. - `parse_tls` throws `ERR_INVALID_ARG_TYPE` for a value that is not a function, so `fetch()` rejects as the constructor throws. The `unusable_check_server_identity` field of oven-sh#42937 is gone. `null` and `undefined` mean no function. - **Behaviour change on a released API.** A function that returns `true`, `hosts.push(host)` or a Promise now gets a rejected `fetch()`. A maintainer must decide which release carries this. - Verified: `test/js/web/fetch/fetch.tls.test.ts` (5 new tests fail on a debug build of main, all 46 pass with the change). Other suites: see Notes. ### Background - `tls.checkServerIdentity(hostname, cert)` is a Bun extension to `fetch()`, named after the `node:tls` option. Bun calls it after the certificate chain verifies, and sends the request only after approval. - `Bun.FetchSession` (oven-sh#42692, in no release) holds connection settings, this option included, for the `fetch()` calls that name it. - `ERR_INVALID_RETURN_VALUE` is the Node error code for a callback that returns the wrong type. <details><summary>Notes</summary> **Source and reach.** No user reported this. A sweep of the `Bun.FetchSession` option bag found it during the work on oven-sh#42937. That PR left a `fetch()` request unchanged on purpose and said that the request path needs its own PR, because it is a released surface. This is that PR. In this repository, every function that a test passes to `fetch()` or to `Bun.FetchSession` returns `undefined` or an Error, and no module in `src/js` passes the option to `fetch()`. The type in `globals.d.ts` already excludes every input that now fails. So the case for the change is the severity when it happens, not the number of users. **The rule for a `tls.checkServerIdentity` option, for a maintainer to accept or change once.** | Input | Result | | --- | --- | | option is `undefined` or `null` | no function, Bun's own hostname check runs | | option is a function | Bun calls it after the chain verifies, in place of its own hostname check | | option is any other value | `ERR_INVALID_ARG_TYPE` | | function returns a falsy value | approved | | function returns an object (an Error, a `DOMException`, any other) | the request fails with that object | | function throws | the request fails with the thrown value | | function returns a Promise or a truthy primitive | the request fails with `ERR_INVALID_RETURN_VALUE` | | `rejectUnauthorized: false` | the function runs, Bun ignores the result | **Repro.** An HTTPS server with the `tls` pair of `test/harness`, `ca` set to that certificate, one request for each function. `fetch` is Bun 1.4.3-canary and a debug build of main. `https.get` is Node v26.3.0. Bun's `node:https` gives the same result in every row but the `throws` row. | `checkServerIdentity` | `fetch`, before | `fetch`, after | `https.get` | | --- | --- | --- | --- | | returns `undefined`, `null`, `false`, `0`, `""` | resolves | resolves | resolves | | returns an Error | rejects with it | rejects with it | `error`: it | | throws | rejects with the value | rejects with the value | uncaught exception | | returns `true` | resolves | `ERR_INVALID_RETURN_VALUE` | `error`: `true` | | returns `"pin mismatch"` | resolves | `ERR_INVALID_RETURN_VALUE` | `error`: the string | | returns `{}` or a `DOMException` | resolves | rejects with it | `error`: the object | | `async`, resolves to an Error | resolves | `ERR_INVALID_RETURN_VALUE` | `error`: the Promise | | is `"yes"`, `true`, `1`, `{}`, `false` | resolves, no check | `ERR_INVALID_ARG_TYPE` | throws `ERR_INVALID_ARG_TYPE` | | is `null` or `undefined` | resolves, no check | resolves, no check | throws `ERR_INVALID_ARG_TYPE` | **Node source.** `onConnectSecure` assigns `verifyError = options.checkServerIdentity(hostname, cert)` and then tests `if (verifyError)`: https://github.com/nodejs/node/blob/v26.3.0/lib/internal/tls/wrap.js#L1671-L1688 . `tls.connect` calls `validateFunction(options.checkServerIdentity, "options.checkServerIdentity")`. Bun's `node:tls` has both rules already (`src/js/node/net.ts`, `src/js/node/tls.ts`). **Why a TypeError for a Promise and a primitive.** Node destroys the socket with the returned value, so the `error` event carries `true` or a Promise. `fetch()` would then reject with `true`. Error handlers read `e.message`, and the two likely mistakes (`async`, `return true`) need an explanation, not an echo. The message follows the Node template: `Expected undefined or an Error to be returned from the "tls.checkServerIdentity" function but got an instance of Promise.` An object is different. An Error need not be an `ErrorInstance` cell: a `DOMException` and a `util.inherits()` error are objects that inherit from `Error.prototype`. So every object is the rejection reason as it is, as in Node, and the TypeError cannot say "not an Error" to a value that is one. If a maintainer prefers the Node rule for every value, the change is to return `check_result` in place of the TypeError. **What this does not close.** - A falsy value still approves, as in Node: `return mismatch && new Error("pin")` returns `false` on success. So a function that answers with a boolean (`return cert.fingerprint256 === PIN`) now fails every request that it approves, and still approves a mismatch. The docs and the JSDoc now say that `false` approves, and that the type allows only `undefined` and `Error` for that reason. The type is the one that `@types/node` declares for the `node:tls` option. Two `@ts-expect-error` lines in `test/integration/bun-types/fixture/fetch.ts` hold `() => false` and an `async` function as type errors. - `new Request(url, { tls })` drops the whole `tls` option, as the JSDoc of `BunFetchRequestInit` says. A function given there does not run and is not validated. - An unhandled rejection from an `async` function that rejects is reported as before. - With `rejectUnauthorized: false` Bun ignores a function that throws, as it ignores every result. oven-sh#42692 set this rule and holds it in a test (`"thrown, not enforced"`). Node reports such a throw as an uncaught exception. - `parse_tls` also has a branch that reads a numeric `rejectUnauthorized`. `SSLConfig::from_js` throws for a number (`TLSOptions.rejectUnauthorized must be a boolean`), so only a getter that answers differently on the second read reaches that branch. This PR leaves it alone. **`null`.** `fetch()` reads `null` as no function, and `undefined` too, as the `Bun.FetchSession` constructor does. Node throws for both, because `tls.connect` always has a default function to replace. **Precedent for caution.** Bun 1.3.4 made `fetch()` throw for a `proxy` object without `url`, and users of npm-registry-fetch broke (oven-sh#25413), because Bun's `node:http` client forwarded the `proxy` property of the agent to `fetch()`. oven-sh#25414 made `fetch()` ignore such a value again. No module in `src/js` passes `tls.checkServerIdentity` to `fetch()` today, and the `node:http` client no longer uses `fetch()`. In the other direction, `proxy: true` on a request throws `ERR_INVALID_ARG_TYPE` since oven-sh#42692, with no flag. **Relation to other PRs.** - oven-sh#42937 (merged) made the `Bun.FetchSession` constructor throw for a `checkServerIdentity` that is not a function, through a `TlsOption.unusable_check_server_identity` field that a request ignored. This PR throws in `parse_tls` for both callers and deletes that field and the check in the constructor. The constructor test of oven-sh#42937 in `fetch-session.test.ts` passes unchanged. - oven-sh#42054 (sql, redis) and oven-sh#41648 (WebSocket) add a `checkServerIdentity` option with the old rule (only an Error fails), modelled on `fetch()`. They need the rule that a maintainer accepts here. A shared helper for the rule belongs to the first of them that lands, because main has one native caller today. - oven-sh#35609 forwards the `checkServerIdentity` of a node-fetch agent to `fetch()`. Such a function follows the Node contract, so it needs the Node rule for its return value. - A function that throws under Bun's `node:https` is reported as an uncaught exception and the request continues. That path is `src/js/node/net.ts`, which oven-sh#32824 changes. This PR does not touch it. **Suggested release note.** `fetch()` now rejects when `tls.checkServerIdentity` is not a function, or when it returns a truthy value that is not an Error, for example the Promise of an `async` function. Before, Bun ignored such an option and approved the certificate for such a return value. **Self-review.** 13 concerns raised, 10 addressed. Most asked for facts in this description: the repro that leads the Problem section (now also a test), the reach, the rule table, the order relative to oven-sh#42937, the release note, and the notes about `new Request()` and the numeric `rejectUnauthorized` branch. Not done: - Move the two rules into a shared helper in `bun_jsc` (asked twice). Main has one native caller, and REVIEW.md asks for maintainer agreement before a new shared abstraction. oven-sh#42054 creates that module. - Split into two PRs. The two changes are one bug class in one option. They are independent in the diff (`FetchTasklet.rs` and `FetchSession.rs`), so a maintainer can ask for one half. **Suites (debug build, ASAN).** `test/js/web/fetch/fetch.tls.test.ts` (46 pass), `fetch-session.test.ts` (34), `test/js/bun/http/proxy.test.ts` (92), `proxy-stress-adversarial.test.ts` (151), `proxy-stress-errors.test.ts` (53). On the same change before the last rebase: `fetch.tls.ipv6.test.ts`, `test/regression/issue/26125.test.ts`, `test/js/node/tls/fetch-tls-cert.test.ts`, `ssl-ctx-cache.test.ts`, the `checkServerIdentity` test of `fetch-http2-client.test.ts`. The new tests also pass with `BUN_JSC_validateExceptionChecks=1`. </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/web/fetch/fetch.tls.test.ts <!-- robobun:evidence:end -->
…he peer (oven-sh#43013) ### Problem - With `Bun.serve({ tls })`, `ws.terminate()` waits for the peer's TLS close_notify. A peer that does not read never sends it: the `close` handler does not run, the fd stays open, and `message()` keeps firing. Each inbound frame re-arms the idle timeout, so nothing bounds the wait. Plain `ws://` closes at once. - The cause is `WebSocket::close()` (`packages/bun-uws/src/WebSocket.h:76`): `us_socket_close(s, 0, nullptr)`. On TLS, code 0 is the graceful close (`us_internal_ssl_close`, `packages/bun-usockets/src/crypto/openssl.c:2194`). `forceClose()` with no reason (a reserved opcode) passes the same code. ### Fix - `WebSocket::close()` closes with `FAST_SHUTDOWN` (a FIN, no close_notify). If the socket is still open, usockets parked the close behind its ciphertext spill, and `close()` closes again with `CONNECTION_RESET` (the idiom of oven-sh#39548). `forceClose()` with no reason calls `close()`. - Correct because every caller relies on the close event having run on return (`CloseCode`, `src/uws_sys/us_socket_t.rs:23`). Plain sockets treat codes 0 and 2 alike. A peer that keeps up sees no change. Under send backpressure the close is now a reset (see Notes). - Not changed: the other code 0 closes in uWS (HTTP, HTTP/2), listed in the Notes. - Verified: new `test/js/bun/websocket/websocket-server-forced-close.test.ts`, the 3 `wss` cases fail without the fix. Also `test/js/bun/websocket/`, `test/js/web/websocket/`, `test/js/first_party/ws/`. ### Background - `us_socket_close(s, code, reason)` closes the fd and runs the close handler. On TLS, code 0 sends close_notify and waits for the peer, code 1 resets, and code 2 sends a FIN but waits while a spill is pending. - A spill is TLS ciphertext that bun reported as written, but the kernel did not accept yet. - uWS `close()` is the forced close (1006, no Close frame). `end()`, the graceful close, does not change. - oven-sh#38243 fixed this wait for the client `WebSocket`. <details><summary>Notes</summary> **Repro** (1.4.3, canary c6b7fcb, and a debug build of main b8eacea). A `wss://` server sends one message. The client calls `pause()` and sends one message back. The server calls `ws.terminate()` in `message()`. ``` wss, before: 0.0s SERVER terminate(), readyState 3 12.0s done waiting (close handler never ran) ws, before: 0.0s SERVER close handler: 1006 "" 0.0s SERVER terminate(), readyState 3 wss, after: 0.1s SERVER close handler: 1006 "" 0.1s SERVER terminate(), readyState 3 ``` - With `idleTimeout: 8` and a silent peer, the unfixed server closes at 8.0 s from the idle timer, with the reason "WebSocket timed out from inactivity". - With `idleTimeout: 4` and a paused peer that sends one frame each second, the unfixed server never closes. In 14 s it delivered 14 messages to `message()` after `terminate()`, all with `ws.readyState === 3`. The uWS parser stops only when `us_socket_is_closed()` or `isShuttingDown` is true, and a deferred TLS close sets neither. - Protocol error: a paused `Bun.connect({ tls })` client sends a masked frame with opcode 3, and 300 ms later a valid text frame. Before: no `close`, and the text frame reaches `message()`. After: `close` 1006 at once. The `forceClose()` calls that pass a reason already close at once, because the reason length is the close code and it is never 0. **A peer that keeps up sees no change.** Matrix: `ws.send(payload); ws.terminate()` from a handler and from a timer, payload 100 B, 64 KB, 300 KB and 4 MB, 10 runs each, a Bun `WebSocket` client that reads. All 16 cells are the same for `ws` and `wss`, before and after: the same messages arrive, then `close 1006`, and no `error` event. A node `ws` client also reports `close 1006` with no `error` event, before and after. **A peer under send backpressure gets a reset.** A spill does not prove a dead peer. It means the last flush hit a full kernel buffer, which also happens with a slow peer that still reads. If the first close cannot drain the spill, the second close resets: the kernel drops its send buffer and the peer sees ECONNRESET. Before this change that peer got the kernel buffer and the spill, then close_notify, whenever the spill drained. Plain `ws://` gives it the kernel buffer and a FIN. The uWS backpressure buffer is lost in every variant, so the stream ends in the middle of a message in every variant. The reset is the documented cost of a close that must finish now (`CloseCode::failure` names `terminate()`). The client `WebSocket.terminate()` (oven-sh#38243) and `Socket.terminate()` reset on every close. A FIN that keeps the kernel buffer needs a usockets close that drops the spill without a wait, which is the durable fix that oven-sh#39548 names. **Why a FIN first and not a reset for every TLS close.** With a node TLS client, a server reset gives `error: ECONNRESET`. A bare FIN gives `end`, then `close` with no error, which is what `ws://` gives today. npm `ws` 8.18.3 does the same: its `terminate()` is `socket.destroy()`, and the comment in `us_internal_ssl_close` records that node's destroy sends a bare FIN. **Why the second close.** A build with `FAST_SHUTDOWN` only still hangs in the backpressure test (paused client, the server sends 64 KB messages until `send()` returns -1, then `terminate()`). `us_internal_ssl_close` defers codes 0 and 2 until the spill drains. The check after the first close detects the deferral and does not predict it. usockets first tries to drain the spill, so a peer that recovered still gets a FIN. A check of `us_socket_ssl_spill_pending()` before the close is not equivalent: it resets a peer that has recovered. oven-sh#39548 records that. The read of the socket after the first close is safe. `us_internal_socket_close_raw` links a socket into the loop's closed list only after the close handler returns, so JS that re-enters the event loop from the handler cannot free it. **Other callers of `WebSocket::close()`** that get the same fix: the `open()` exception path in `ServerWebSocket.rs`, the HMR socket (`hmr_socket.rs`), and `DevServer` teardown, which has `debug_assert!(self.active_websocket_connections.is_empty())` right after it closes every socket. **Not fixed here.** These sites have the same exposure. Each needs its own repro and tests, and the durable fix is a usockets close that cannot defer (see the last Background bullet of oven-sh#39548). - `AsyncSocket<SSL>::close()` (`AsyncSocket.h:101`) and the HTTP paths that use it. One case is reproduced: `Bun.serve({ tls, idleTimeout: 4 })` with a peer that completes the handshake and stops reading. The plain server socket is in FIN-WAIT-2 at 12 s. The TLS server socket is still ESTAB at 40 s. - The code 0 closes in `Http2Context.h`. - `JSNodeHTTPServerSocket::close()` (`JSNodeHTTPServerSocket.cpp:90`). It already uses `FAST_SHUTDOWN`, with no second close for a spill. - A peer FIN on a TLS WebSocket that still has a spill, and `closeOnBackpressureLimit`. These are not forced closes. **Order with oven-sh#35874.** That PR replaces the `forceClose()` calls that pass no reason with a graceful `end(1002)`. If it merges first, the `reason.empty()` branch here has no caller and can go, and the reserved opcode test must expect the code that PR reports. If this PR merges first, oven-sh#35874 needs no change to `close()`. **Test file.** The test is a sibling file and not part of `websocket-server.test.ts`. That file has load-related timeouts on a debug build (8 here, in `send()`, `sendText()`, `sendBinary()` and the benchmark). The same tests pass alone. The two `terminate()` tests fail at once on an unfixed build, with `close: 1006 ""` missing between `message` and `terminate() returned`. The reserved opcode test times out there. **Suites run** on a debug+ASAN build: all of `test/js/bun/websocket/`, `websocket.test.js`, `websocket-pause.test.ts`, `websocket-client.test.ts`, `websocket-close-code.test.ts`, `websocket-close-fragmented.test.ts`, `websocket-proxy.test.ts`, `websocket-subprotocol-strict.test.ts`, `websocket-client-short-read.test.ts`, `websocket-close-connecting.test.ts`, `websocket-close-async-dispatch.test.ts`, `websocket-buffered-amount.test.ts`, `websocket-server-send-from-drain.test.ts`, `ws.test.ts`, `ws-upgrade-events.test.ts`, and the pipelined upgrade tests in `serve.test.ts`. Failures that do not come from this change: two `websocket.test.js` tests that need `ws.postman-echo.com`, and tests that spawn a debug build per case and go over 5 s when this machine is loaded ("should connect many times over https", `ws-upgrade-events.test.ts`). They pass alone. </details> <!-- robobun:evidence:begin --> --- **[human-review]** gate passed · iteration 0 · 3 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/websocket/websocket-server-forced-close.test.ts bun test v1.4.3 (c6b7fcb) test/js/bun/websocket/websocket-server-forced-close.test.ts: (pass) ws: forced close with a peer that does not read > terminate() runs the close handler before it returns [189.90ms] (pass) ws: forced close with a peer that does not read > terminate() runs the close handler before it returns under backpressure [156.98ms] (pass) ws: forced close with a peer that does not read > a frame with a reserved opcode closes the socket [139.63ms] 53 | client.onmessage = () => { 54 | client.pause(); 55 | client.send("terminate"); 56 | }; 57 | await terminated.promise; 58 | expect(events).toEqual(["message: terminate", 'close: 1006 ""', "terminate() returned"]); ^ error: expect(received).toEqual(expected) [ "message: terminate", - "close: 1006 """, "terminate() returned", ] - Expected - 1 + Received + 0 at <anonymous> (/workspace/bun/test/js/bun/websocket/websocket-server-f ... (truncated) release without fix: all passed bun test v1.4.3-canary.1 (fed761c) test/js/bun/websocket/websocket-server-forced-close.test.ts: (pass) ws: forced close with a peer that does not read > terminate() runs the close handler before it returns [18.47ms] (pass) ws: forced close with a peer that does not read > terminate() runs the close handler before it returns under backpressure [16.71ms] (pass) ws: forced close with a peer that does not read > a frame with a reserved opcode closes the socket [16.37ms] (pass) wss: forced close with a peer that does not read > terminate() runs the close handler before it returns [17.73ms] (pass) wss: forced close with a peer that does not read > terminate() runs the close handler before it returns under backpressure [11.70ms] (pass) wss: forced close with a peer that does not read > a frame with a reserved opcode closes the socket [10.75ms] 6 pass 0 fail 6 expect() calls Ran 6 tests across 1 file. [85.00ms] __F:0:S:0 ``` </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/websocket/websocket-server-forced-close.test.ts bun test v1.4.3 (c6b7fcb) test/js/bun/websocket/websocket-server-forced-close.test.ts: (pass) ws: forced close with a peer that does not read > terminate() runs the close handler before it returns [278.56ms] (pass) ws: forced close with a peer that does not read > terminate() runs the close handler before it returns under backpressure [237.39ms] (pass) ws: forced close with a peer that does not read > a frame with a reserved opcode closes the socket [210.23ms] (pass) wss: forced close with a peer that does not read > terminate() runs the close handler before it returns [211.46ms] (pass) wss: forced close with a peer that does not read > terminate() runs the close handler before it returns under backpressure [155.50ms] (pass) wss: forced close with a peer that does not read > a frame with a reserved opcode closes the socket [71.47ms] 6 pass 0 fail 6 expect() calls Ran 6 tests across 1 file. [2.82s] __F:0:S:0 release with fix: all passed $ bun scripts/build.ts --profile=release [configured] bun-profile → bun (stripped) in 841ms (unchanged) ninja: Entering directory `/workspace/bun/build/release' [1/128] gen generated_host_exports.rs generated_host_exports.rs: 121 exports (host=5, lazy=10, generic=106, rust=0); 242 extern-C blocks audited [2/128] gen JSSink.{cpp,h,lut.h,rs} generated_jssink.rs: 7 sinks, 84 exported symbols Generating /workspace/bun/build/release/codegen/JSSink.lut.h from /workspace/bun/build/release/codegen/JSSink.lut.txt [3/128] gen cpp.rs (cppbind) [4/128] gen JS modules (bundle-modules) Preprocess modules (11568ms) Bundle modules (91ms) Postprocesss modules (179ms) Bundle Functions (587ms) Generate Code (41ms) [12.48s] Bundled "src/js" for production 2600 kb 197 internal modules 13 native modules 50 internal functions across 16 files [4/26] 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|�[ ... (truncated) ``` </details> <details><summary>diff hotspot</summary> ``` packages/bun-uws/src/WebSocket.h | 8 +- packages/bun-uws/src/WebSocketContext.h | 5 + .../websocket-server-forced-close.test.ts | 152 +++++++++++++++++++++ 3 files changed, 164 insertions(+), 1 deletion(-) ``` </details> **gate history** · 2 passed · 0 rejected · iteration 0 <details><summary>evidence per changed file</summary> ``` file reads edits tests packages/bun-uws/src/WebSocket.h 4 5 21 packages/bun-uws/src/WebSocketContext.h 2 3 20 …/js/bun/websocket/websocket-server-forced-close.test.ts 1 2 20 ``` </details> <!-- robobun:evidence:end --> --------- Co-authored-by: Ciro Spaciari <[email protected]>
…context (oven-sh#42998) ### Problem - `tls.Server` with `ca: caA` plus `addContext("b.test", { ca: caB, key, cert })` refuses a caA client certificate at `b.test` (`UNABLE_TO_VERIFY_LEAF_SIGNATURE`). The same client keeps `a.test`'s `session`, offers it as `servername: "b.test"`, and the handler runs with `authorized: true`. TLS 1.3 and 1.2. - A resumed handshake skips client authentication. BoringSSL resumes only when the session's id context equals the connection's (`vendor/boringssl/ssl/ssl_session.cc:474`). No `node:tls` context sets one. - oven-sh#36174 fixed this for `Bun.serve` `serverName` entries only. nginx fixed the class as CVE-2025-23419. ### Fix - Each `SSL_CTX` a server can serve gets the SHA-256 of its options as its session id context (`create_ssl_context_with_digest`): the `tls.Server` and `Bun.listen` listeners, `SSLContextCache`, `tls.createSecureContext()`. `addCACert` folds its certificate in. - BoringSSL checks the id after the SNI switch, and `SSL_set_SSL_CTX` copies the selected context's id. A mismatch is not an error: a full handshake runs and verifies the certificate against that context's CA. - The id is content-derived, so an `SNICallback` that builds a context per handshake still resumes. Client sockets keep no id: one `SSL_CTX` backs clients and servers, and a client aborts a resume when the ids differ. - Verified: `test/js/node/tls/node-tls-context.test.ts`, 12 new tests, 8 fail on main, each client clear covered by one that fails without it. Other suites and vendored tests: see the notes. ### Background - Session resumption: the client presents a ticket from an earlier connection, both sides skip the certificate exchange, and the server reports the verdict stored in the session. - Session id context: an opaque string on an `SSL_CTX`, copied into each new session. BoringSSL refuses a session whose id differs, and tells servers to partition sessions between SNI hosts this way (`include/openssl/ssl.h:2199-2207`). RFC 6066 section 3 allows resuming only a session established for the requested name. - SNI context: `addContext()` and `SNICallback` pick an `SSL_CTX` per ClientHello. The ticket keys belong to the listener default context, so every context of that listener decrypts its tickets. <details><summary>Notes</summary> **Outcome table** (client certificate issued by caA, session from `a.test` offered at `b.test`, which trusts only caB): | | bun main | this PR | |---|---|---| | `authorized` | `true` | `false` | | `authorizationError` | none | `UNABLE_TO_VERIFY_LEAF_SIGNATURE` | | `isSessionReused()` | `true` | `false` | | handler reached with the default `rejectUnauthorized` | yes | no | | `a.test` session at `a.test` | resumed | resumed | An independent client (`openssl s_client -servername a.test -sess_out`, then `-servername b.test -sess_in`) shows the same before and after, so the door does not depend on Bun's client. **Why the id is derived from the options and not from the context object.** oven-sh#36174 uses a counter, which fits `Bun.serve` because those contexts are built once per server. A `node:tls` `SNICallback` commonly calls `tls.createSecureContext()` for each handshake. With an id per object such a server would never resume. With the options digest, two contexts built from the same options share sessions, which is safe because they authenticate clients the same way. The digest is the existing `BunSocketContextOptions::digest()`, the key of `SSLContextCache`: inline PEM content, and path plus mtime and size for the file options. It is broader than the client-certificate policy, so a change to an unrelated option (`ciphers`, `sigalgs`) also ends resumption for old sessions. That errs toward a full handshake. **Why the server side needs no code at the SNI switch.** `SSL_set_SSL_CTX` replaces the connection's `CERT` with a copy of the new context's `CERT`, and the session id context is a field of `CERT`. So the servername callback, the static SNI tree, the asynchronous `SNICallback` resume and `socket.setKeyCert()` all move the connection to the id of the selected context with no extra call. **Context sharing.** `SSLContextCache` shares one `SSL_CTX` between all users of the same options, clients and servers, which is why the client side clears the id per socket. **Client clears.** The two places that build an `SSL` are `us_internal_ssl_attach` (socket) and `SSLWrapper::init_with_ctx` (duplex, named pipe). `setKeyCert` is the only other caller of `SSL_set_SSL_CTX`, and on a client Bun applies it (Node ignores it there), so it needs the clear too. Tests: `lets a client offer a session under other client options` covers the first two (TCP and Duplex), `lets a client that calls setKeyCert() still resume` the third. Each fails with `ERR_SSL_ATTEMPT_TO_REUSE_SESSION_IN_DIFFERENT_CONTEXT` when its clear is removed. A future `SSL_new` site for a client needs the same line. There is no lint for that. **Landing order.** oven-sh#28691 (server `ticketKeys`) should land after this one: shared ticket keys let one process decrypt another's tickets, which extends the same door across servers and processes, and it needs a negative test for that. The options digest keeps cross-process resumption working for identical options, which a counter or a pointer would not. oven-sh#33483 and oven-sh#42050 touch the SNI switch and `setSecureContext`; they do not set a session id context and do not conflict. **Not covered.** `addCACert()` on a context that already serves connections: a handshake that selected the context before the call, and verifies its client certificate after it, issues a session under the old id. A second context built from the same options without that CA can then resume it. The window is one round trip and needs that sibling context. On `main` any context resumes any session, so this PR narrows that door. Node allows `addCACert()` at any time, so this PR adds no refusal. TLS 1.2 with an `ALPNCallback` that calls `socket.setKeyCert(ctx)`: BoringSSL decides TLS 1.2 resumption before the ALPN callback runs, so a session id context cannot reach that path. TLS 1.3 with the same setup is covered, because ALPN runs before session selection there. The `sessionIdContext` option is still accepted and dropped; honoring it belongs with oven-sh#28691. `node:quic` has its own context path and is not changed. **Suites run on the debug build:** `node-tls-context.test.ts` (29 pass), `node-tls-connect.test.ts` (57 pass), `node-tls-server.test.ts` (77 pass, 1 failure that also fails without this diff: `localhost` resolves to `::1` first in this container), `node-tls-cert.test.ts`, `node-tls-namedpipes.test.ts`, `ssl-ctx-cache.test.ts`, `node-tls-upgrade.test.ts`, `node-tls-internals.test.ts`, `renegotiation.test.ts`, `node-tls-connect-hostname-verification.test.ts`, `bun-serve-ssl.test.ts` (18 pass), `fetch.tls.test.ts` (41 pass), `fetch-session.test.ts` (32 pass), `proxy.test.ts` (90 pass). Vendored Node tests: `test-tls-add-context`, `test-tls-sni-option`, `test-tls-sni-server-client`, `test-tls-sni-servername`, `test-tls-snicallback-error`, `test-tls-empty-sni-context`, `test-tls-client-resume`, `test-tls-client-resume-12`, `test-https-client-resume`, `test-tls-ticket`, `test-tls-ticket-cluster`, `test-tls-session-cache`, `test-tls-secure-session`, `test-tls-connect-secure-context`, `test-tls-secure-context-usage-order`, `test-tls-alpn-server-client`, `test-tls-psk-circuit`, `test-tls-psk-server`, `test-tls-reuse-host-from-socket`, `test-https-agent-session-reuse`, `test-https-agent-disable-session-reuse`, `test-https-agent-session-eviction`, `test-https-agent-session-injection`, `test-https-agent-sni`. **Comments.** The rationale for the deliberate refusal (RFC 6066 section 3, the BoringSSL header) sits on `us_ssl_apply_selected_ctx` in `openssl.c`, next to the SNI switch, and on the test block. The Rust call sites carry one line each. **Self-reviewed:** 6 concerns raised, 6 addressed (default-`rejectUnauthorized` coverage, the Windows named-pipe listener, the `setKeyCert` clear test, the scope claim above, the deliberate-refusal comments at the helper and the test, and the landing order). </details> <!-- robobun:evidence:begin --> --- **[human-review]** gate passed · iteration 1 · 9 files touched <details><summary>fails on main (without fix)</summary> ```console ASAN without fix: 8 FAILED $ 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-context.test.ts bun test v1.4.3 (c6b7fcb) test/js/node/tls/node-tls-context.test.ts: (pass) tls.Server > addContext [898.64ms] (pass) tls.Server > should select the most recently added SecureContext [175.29ms] (pass) tls.Server > should allow multiple CA [175.40ms] (pass) tls.Server > should allow multiple CA in newline-separated strings [53.03ms] (pass) tls.Server > SNI tls.Server + tls.connect [286.16ms] 475 | 476 | // b.test verifies the certificate again, against ca2, whichever 477 | // context's session the client offers. 478 | const fromDefault = await connect(server, "b.test", { session: atDefault.session }); 479 | const fromA = await connect(server, "b.test", { session: atA.session }); 480 | expect([fromDefault.seen, fromA.seen]).toEqual([refused("b.test"), refused("b.test")]); ^ error: expect(received).toEqual(expected) [ { - "authorized": false, - "error": "UNABLE_TO_VERIFY_LEAF_SIGNATURE", + "autho ... (truncated) release without fix: all passed bun test v1.4.3-canary.1 (e0d54a6) test/js/node/tls/node-tls-context.test.ts: (pass) tls.Server > addContext [29.23ms] (pass) tls.Server > should select the most recently added SecureContext [6.86ms] (pass) tls.Server > should allow multiple CA [4.38ms] (pass) tls.Server > should allow multiple CA in newline-separated strings [2.53ms] (pass) tls.Server > SNI tls.Server + tls.connect [11.38ms] (pass) session resumption across SNI contexts (TLSv1.3) > runs a full handshake under a context that trusts another CA [20.26ms] (pass) session resumption across SNI contexts (TLSv1.3) > keeps a refused client out of the handler with the default rejectUnauthorized [9.98ms] (pass) session resumption across SNI contexts (TLSv1.3) > covers the contexts an SNICallback builds for each handshake [10.63ms] (pass) session resumption across SNI contexts (TLSv1.3) > covers contexts that differ only by addCACert [11.52ms] (pass) session resumption across SNI contexts (TLSv1.3) > lets a client offer a session under other client options [9.06ms] (pass) session resumption across SNI contexts (TLSv1.3) > lets a client that calls setKeyCert() still resume [4.72ms] (pass) session resumption ... (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/node/tls/node-tls-context.test.ts bun test v1.4.3 (c6b7fcb) test/js/node/tls/node-tls-context.test.ts: (pass) tls.Server > addContext [765.80ms] (pass) tls.Server > should select the most recently added SecureContext [124.51ms] (pass) tls.Server > should allow multiple CA [201.14ms] (pass) tls.Server > should allow multiple CA in newline-separated strings [75.66ms] (pass) tls.Server > SNI tls.Server + tls.connect [278.18ms] (pass) session resumption across SNI contexts (TLSv1.3) > runs a full handshake under a context that trusts another CA [495.27ms] (pass) session resumption across SNI contexts (TLSv1.3) > keeps a refused client out of the handler with the default rejectUnauthorized [221.28ms] (pass) session resumption across SNI contexts (TLSv1.3) > covers the contexts an SNICallback builds for each handshake [164.83ms] (pass) session resumption across SNI contexts (TLSv1.3) > covers contexts that differ only by addCACert [121.09ms] (pass) session resumption across SNI contexts (TLSv1.3) > lets a client offer a session und ... (truncated) release with fix: all passed $ bun scripts/build.ts --profile=release [configured] bun-profile → bun (stripped) in 783ms (unchanged) ninja: Entering directory `/workspace/bun/build/release' [1/129] gen generated_host_exports.rs generated_host_exports.rs: 121 exports (host=5, lazy=10, generic=106, rust=0); 242 extern-C blocks audited [2/129] gen cpp.rs (cppbind) [3/129] gen JSSink.{cpp,h,lut.h,rs} generated_jssink.rs: 7 sinks, 84 exported symbols Generating /workspace/bun/build/release/codegen/JSSink.lut.h from /workspace/bun/build/release/codegen/JSSink.lut.txt [4/129] gen JS modules (bundle-modules) Preprocess modules (12205ms) Bundle modules (134ms) Postprocesss modules (434ms) Bundle Functions (731ms) Generate Code (51ms) [13.57s] Bundled "src/js" for production 2600 kb 197 internal modules 13 native modules 50 internal functions across 16 files [4/27] 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|� ... (truncated) ``` </details> <details><summary>diff hotspot</summary> ``` packages/bun-usockets/src/crypto/openssl.c | 15 +- src/boringssl_sys/boringssl.rs | 10 ++ src/runtime/api/bun/SSLContextCache.rs | 2 +- src/runtime/api/bun/SecureContext.rs | 27 ++- src/runtime/socket/Listener.rs | 5 +- src/runtime/socket/tls_socket_functions.rs | 4 + src/uws/lib.rs | 6 +- src/uws_sys/SocketContext.rs | 19 ++ test/js/node/tls/node-tls-context.test.ts | 280 ++++++++++++++++++++++++++++- 9 files changed, 356 insertions(+), 12 deletions(-) ``` </details> **gate history** · 2 passed · 0 rejected · iteration 1 <details><summary>evidence per changed file</summary> ``` file reads edits tests packages/bun-usockets/src/crypto/openssl.c 5 2 23 src/boringssl_sys/boringssl.rs 1 3 23 src/runtime/api/bun/SSLContextCache.rs 1 1 23 src/runtime/api/bun/SecureContext.rs 2 3 23 src/runtime/socket/Listener.rs 3 2 23 src/runtime/socket/tls_socket_functions.rs 1 1 23 src/uws/lib.rs 1 2 24 src/uws_sys/SocketContext.rs 3 2 23 test/js/node/tls/node-tls-context.test.ts 6 7 23 ``` </details> <!-- robobun:evidence:end -->
…'s TLS context (oven-sh#43015) ### Problem - `tls.Server#setSecureContext()` on a listening server changes nothing. Later handshakes keep the original certificate, key and client-CA store. A CA that the operator removed keeps authorizing client certificates (`authorized=true`). Node applies the new context to the next connection. - Cause: `Listener::listen` (`src/runtime/socket/Listener.rs`) builds the `SSL_CTX` once. `setSecureContext` (`src/js/node/tls.ts`) only reassigned the option fields that `listen()` reads. ### Fix - `setSecureContext()` on a listening server builds an `SSL_CTX` from the staged options. `us_listen_socket_set_default_ssl_ctx()` makes it the default for later accepts. It runs before any field is assigned, so rejected material throws and nothing changes. - First commit: `listen()` no longer registers the default context under the bind hostname in the SNI tree. That entry shadowed an `addContext()` wildcard and would pin the name to the old context. - As in Node, `setSecureContext()` no longer reads `ALPNProtocols` (constructor only). A cluster worker reads its TLS options when the primary answers, so a call made before `'listening'` counts. - Verified on Linux and Windows: `node-tls-server.test.ts` (17 new tests, 11 fail on bun 1.4.2), `node-tls-namedpipes.test.ts`. On Linux: `test/js/node/tls/`, `node-http2.test.js`, `node-net-server.test.ts`. Self-reviewed: one regression found and fixed (Notes). ### Background - An `SSL_CTX` is BoringSSL's TLS configuration: certificate chain, key, CA store, verify mode. Each accepted socket creates its `SSL` from the listen socket's default and holds a reference. - The SNI tree maps server names to other contexts (`addContext()`). A matching ClientHello switches that connection's context. - Session tickets belong to one `SSL_CTX`, so a new context never resumes an old session. <details><summary>Notes</summary> **Repro** (two CAs, server trusts `caA`, then `setSecureContext({ ..., ca: caB })`): ``` bun 1.4.2 / main this branch = node v26.3.0 after clientA (caA): hello clientA authorized=true refused after clientB (caB): refused hello clientB authorized=true resume clientA session: authorized=true reused=true refused ``` The same holds for an `Http2SecureServer`, which is the class `@grpc/grpc-js` reloads credentials on. **Scope.** `tls.Server` and `Http2SecureServer` only. Not covered, on purpose: - `https.Server` and `Bun.serve().reload({ tls })` (oven-sh#8872). They go through `Bun.serve`, not `Listener.rs`. oven-sh#42576 and the draft oven-sh#35535 add `https.Server#setSecureContext()`. No open PR covers `Bun.serve().reload({ tls })`. - `setSecureContext(secureContextInstance)`. Node takes an options object only. node v26.3.0 reads the instance as options with no key and no certificate, and every later handshake fails. Bun 1.4.2 and this branch both leave the listening socket on its context for that form. A context from `tls.createSecureContext()` carries no `requestCert` verify mode, so this PR does not install it. - ALPN on a connection whose SNI selects an `addContext()` or `SNICallback` context is still not negotiated. That is oven-sh#33253. The wildcard test here asserts the certificate only. **Cluster workers.** A worker's `listen()` completes when the primary answers. `net.ts` built the native TLS options when `listen()` was called, so a `setSecureContext()` or `addContext()` made before `'listening'` was lost. `listenOnPrimaryHandle` now reads them again. For `tls-cluster-set-secure-context-fixture.mjs`, node v26.3.0 prints `default: agent3, viaAddContext: agent2` and bun 1.4.2 prints `agent1` for both. **ALPNProtocols.** This is a behavior change outside a listening server too. `setSecureContext({ ALPNProtocols })` no longer sets the list, also before `listen()`. node v26.3.0 reads the option in the `Server` constructor only (`lib/internal/tls/wrap.js` L1381-L1382). Probe: a server created with `['h2']` and given `['http/1.1']` through `setSecureContext()` negotiates `h2` in node, also after `close()` + `listen()`. Bun 1.4.2 negotiates `http/1.1` after the re-listen. Before this change a listening server reported the new list on `server.ALPNProtocols` while its listener kept the old one. **requestCert clamp.** A server that does not request a client certificate must not reject for one. `net.ts` applied that to the options after `[buntls]` built them. The rule now lives in `[buntls]`, so `listen()`, the cluster reply and the context swap share it. **Related PRs.** The C primitive and its header comment are taken as they are from the drafts oven-sh#35535 and oven-sh#41400, so the C hunks merge without a conflict. The Rust wrapper takes an `&OwnedSslCtx` where the drafts take a raw pointer, so safe code cannot pass a dead pointer. Neither draft calls it from `Listener.rs`. oven-sh#42576 has the same function under the name `us_listen_socket_set_ssl_ctx`. oven-sh#42050 builds `_sharedCreds` eagerly so that bad material throws before `listen()`. Its notes say it does not rotate the listener. It edits the same function in `tls.ts`, so one of the two needs a rebase. oven-sh#32435 adds the `tls.Server` methods to `https.Server`. oven-sh#37896 changes what a cluster TLS worker's `_handle` is. Here a `_handle` that is not a `Listener` is a no-op, and the worker's connections are wrapped in JS from the server's own fields. oven-sh#33365 was the first version of this fix. A stale-PR sweep closed it. oven-sh#42355 and oven-sh#42998 edit `Listener.rs` and `openssl.c` in other places. **Self-review.** A review of the first version of this diff found one regression, and it is fixed. That version moved the bind-hostname SNI entry to the new context. A connection accepted before the swap whose ClientHello arrived after it was switched to the new context, which had no ALPN selector yet, so an h2 server answered `unknownProtocol`. The first commit removes the entry, and two tests pin the case for `tls.Server` and `Http2SecureServer`. The review also asked for h2 coverage, for the `ALPNProtocols` fix, for the requestCert/rejectUnauthorized matrix tests and for the maintainer's symbol name. All are in. **Reference counts.** `secure_ctx` is an `OwnedSslCtx`. The swap is `set_default_ssl_ctx` (C takes its own reference and drops the one on the old default) and `secure_ctx.set(Some(ctx))` (drops the listener's reference on the old one). The test `frees the context it replaces` asserts with `sslCtxLiveCount()` that 20 swaps and one rejected swap add no live `SSL_CTX`, and that `close()` releases the last one. **Windows.** A named-pipe TLS server keeps its context in `WindowsNamedPipeListeningContext.ctx`, now a `JsCell`. Each accept clones the context out of the cell before it can run JS, because `setSecureContext()` can replace the slot. At ddd655c I built the debug binary on Windows x64 and ran `node-tls-namedpipes.test.ts` (7 pass) and the new tests in `node-tls-server.test.ts` (18 pass, the cluster test included). The canary on that machine (1.4.3) fails the named-pipe test: it serves `agent1` after the swap. `bun run rust:check-all` passes for all 12 targets at the same commit. **Test hygiene.** `SNICallback runs even when the requested servername matches the bind hostname` now dials the address `listen()` bound. `localhost` resolves to `::1` and `127.0.0.1` on a dual-stack host, and `connect()` need not pick the one `listen()` did. oven-sh#35160 makes the same change on its own. </details> <!-- robobun:evidence:begin --> --- **no test proof** · iteration 13 · platform-specific test(s) that do not run on this machine, deferring to CI, which covers all platforms: test/js/node/tls/node-tls-server.test.ts, test/js/node/tls/node-tls-namedpipes.test.ts <!-- robobun:evidence:end --> --------- Co-authored-by: Ciro Spaciari <[email protected]>
…rst (oven-sh#36403) ### Problem - A client opens 300 TCP connections to a TLS `Bun.serve` listener and sends no bytes. The 12 s idle sweep closes only a part (`held: 125` on 1.4.3-canary.1). The server holds the other fds until the peer closes. - On Linux, `TCP_DEFER_ACCEPT` releases the burst at once with a readable event per socket (`loop.c:571`). Only 5 TLS handshakes run per loop iteration. `loop.c:674` parks the rest in `low_prio_head`. - `us_internal_timer_sweep` (`loop.c:255`) walks only `head_sockets` and matches `s->timeout` by equality. A socket that is parked during its tick never matches again. ### Fix - The sweep now also walks `low_prio_head` and checks each parked socket against the timestamps of its group. - `low_prio_iterator` (new, mirrored in `uws_sys::InternalLoopData`) keeps the walk valid when a handler closes, detaches, adopts, or drains a parked socket. `group->iterator` does this for `head_sockets`. - Correct because a parked socket keeps its group linked (`low_prio_count`), so the group walk already advanced that timestamp. - Verified: `test/js/bun/http/serve.test.ts`, test `TLS: reaps every zero-byte pre-handshake connection in a burst`. Main fails with `held: 160`. This branch passes. Also all of `serve.test.ts`. ### Background - uSockets stores a timeout as a tick stamp. A sweep runs each 4 s and closes each socket whose stamp equals the current tick. - The low-priority queue spreads TLS handshakes across loop iterations, 5 per iteration. It reuses the socket's `prev`/`next` links, so a parked socket is in no group list. - An idle loop iterates only on the sweep, so a burst drains slowly. A zero-byte connection gets no later event to arm its timeout again. <details><summary>Notes</summary> **Repro** ```js // bun repro.mjs (key and cert: any self-signed pair) import net from "node:net"; const server = Bun.serve({ port: 0, hostname: "127.0.0.1", tls: { key, cert }, fetch: () => new Response("ok") }); let opened = 0, closed = 0; for (let i = 0; i < 300; i++) { const s = net.connect(server.port, "127.0.0.1", () => { opened++; }); s.on("error", () => {}); s.on("close", () => { closed++; }); } await Bun.sleep(20000); console.log(`held=${opened - closed}`); ``` **Measurements (Linux x64, 300 connections)** - 1.4.0 release: `held` is 110, 115, 170 in three runs. With a 5 s poll in the script: 65, 15, 10. - 1.4.3-canary.1+367d939d9: `held: 125`. - Debug build of main (`src/` and `packages/` from main, test from this branch): `held` is 154, 140, 160. - Debug build of this branch: `held: 0` in each run. All 300 connections close at about 14 s. - With the 5 s poll script, bursts of 50, 100, 150 and 200 are fully reaped on 1.4.0. The loss starts when the queue cannot drain before the third sweep tick. **Why only zero-byte TLS connections** - A plain HTTP socket has no `s->ssl`, so the low-priority gate in `loop.c` never parks it. - A TLS connection that sent bytes gets a readable event when the drain enables `READABLE` again. That event drives more loop iterations, and the data path arms the timeout again against the current tick. - A zero-byte socket gets no event after the drain. The stale stamp can match again only after the 240-tick wheel wraps (16 minutes). **Why 12 s** - A socket with no request uses the uWS default `idleTimeout = 10` (`HttpResponseData.h:211`). `us_socket_timeout` rounds it to `(10 + 3) >> 2 = 3` ticks of 4 s (`socket.c:102`). - `Bun.serve({ idleTimeout })` reaches a socket only through `resp.timeout()` on a request. So the test cannot make the wait shorter with that option. **Sites that touch `low_prio_head`** - Unlink or rewire, each maintains `low_prio_iterator`: `us_internal_socket_close_raw` and `us_socket_detach` (`socket.c`), `us_socket_adopt` (`context.c`), `us_internal_handle_low_priority_sockets` (`loop.c`). Review found the last two. - Read-only: the `close_all` drain in `context.c` (it closes through `us_socket_close`) and the listener walk in `openssl.c`. - The park site in `loop.c` only prepends. The walk does not visit a socket that is parked during the walk, and that socket has a new stamp. **Second-order cases** - The sweep timer count includes only linked sockets, and a parked socket is not linked. This is safe: each loop iteration drains up to 5 parked sockets back into `head_sockets`, newest first, so the newest stamp in the queue always has a linked socket that keeps the sweep armed until that tick. - A nested `us_loop_run_bun_tick` from a timeout handler can drain up to 5 sockets out of the queue during the new walk. Those sockets miss this tick, as they did before this change. The iterator stays valid. `Bun.serve` runs no JS for a socket that has no request, so this path needs a `Bun.listen` or `node:tls` handler that waits on the loop. **Test** - The fixture runs in a subprocess through `bunRun`. It counts `held` as the sockets that got `connect` and did not get `close` before the deadline (22 s). - On Windows the accept backlog drops a part of the burst (200 of 300 open), so the test asserts `opened >= 100` and `held == 0`. - macOS and Windows do not set `TCP_DEFER_ACCEPT`. A zero-byte connection gets no readable event there, so nothing parks it and the group walk reaps it. On Windows x64 the test passes with and without the change. I did not run macOS without the change. **Suites** - `test/js/bun/http/serve.test.ts`: 324 pass. Two tests fail in my container with and without the change: `should use correct error when using a root range port(oven-sh#7187)` (the container runs as root) and `only serves /bun:info to loopback clients in development mode`. - Before the merge with main, these matched main: `tls-keepalive.test.ts`, `node-tls-server.test.ts`, `socket.test.ts`, `node-net.test.ts`, `node-http.test.ts`. `bun run rust:check-all` passed for all 10 targets. - The branch is merged with main at a65a98f. The C struct and the Rust mirror have the same field order after the merge. </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.test.ts <!-- robobun:evidence:end -->
… IP host (oven-sh#42766) ### Problem - `new Bun.SQL("postgres://u@[::1]:5432/db?sslmode=verify-full")` rejects a certificate that has `IP:::1` with `ERR_TLS_CERT_ALTNAME_INVALID`. `mysql://` does the same. - `parseOptions` copies `URL.hostname`, brackets kept, into `tls.serverName` (`src/js/internal/sql/shared.ts:2159`). Both adapters check the certificate against that text, and `"[::1]"` is not an IP address. - Both adapters send an IP literal as SNI (`127.0.0.1`). RFC 6066 section 3 forbids that. ### Fix - `SSLConfig::server_name_bytes()` (`src/sql_jsc/jsc.rs`) returns the name through `bun_core::ip_address::strip_ipv6_brackets`. The identity checks of both adapters read the name there. - New `SSLConfig::sni()` returns no name for an IP literal, bracketed or not. Both `adopt_tls` sites use it. libpq and fetch send none either. - Verified: `test/js/sql/sql-tls-ip-literal-host.test.ts` (new, 8 cases). 6 fail on main 0d73249, all pass here. ### Background - `sslmode=verify-full` checks that the certificate names the host. An IP host matches only an IP SAN entry, and only as a bare address (`check_x509_server_identity`, `src/boringssl/lib.rs:452`). - SNI is the host name a TLS client sends in its first message. `adopt_tls` sets it. - Considered a strip in `parseOptions` (the first version). That was a second copy of `strip_ipv6_brackets`, which fetch, RedisClient and Bun.connect use, and it changed `sql.options`. ### Downsides - Bun.SQL sends no SNI for an IP-literal name. A TLS proxy that routes on such a value loses it. - A zone-scoped address (`hostname: "::1%lo"`) still fails `verify-full`, and without brackets it still goes out as SNI: `is_ip_address` accepts no `%zone`. - Cost per TLS connection: one `is_ip_address` call (at most 45 bytes, no allocation) and a bracket check at each name read. <details><summary>Notes</summary> - History of this PR. The first version removed the brackets in `parseOptions` (JS). Main then gained `bun_core::ip_address::strip_ipv6_brackets` and moved every other client to it. A review noted that the JS helper disagreed with it (`[db]` lost its brackets too). aa4d699 moves the fix to the two native accessors and restores `parseOptions` to its state on main. So this PR no longer touches `src/js/internal/sql/shared.ts`, and it does not conflict with oven-sh#42054 or oven-sh#41761, which edit that block. - `sql.options.tls.serverName` and `sql.options.hostname` keep the brackets, as on main. Only the native reads see the bare address. - When this PR opened (canary 09bb546), Bun.SQL also accepted a certificate whose only SAN is `DNS:[::1]`, and a hostname mismatch gave an `Error` with an empty `code` and `message`. Main changed both since: oven-sh#43873 makes a name that is not a hostname match no certificate name, and oven-sh#43694 rejects the mismatch inside the handshake with `ERR_TLS_CERT_ALTNAME_INVALID`. This PR changes neither. - Probed on the debug build with a mock TLS server on 127.0.0.1 and an explicit `tls.serverName`. `"[::1]"` and `"::1"` under `verify-full`: connects, no SNI. `"[db]"` under `verify-full`: `ERR_TLS_CERT_ALTNAME_INVALID`, as on main. `"[fe80::1%lo]"` under `require`: no SNI. `"fe80::1%lo"` and `"127.1"` under `require`: sent as SNI, because `is_ip_address` takes neither as an IP literal (oven-sh#43979). `"localhost"`: sent as SNI. - Observed on main 0d73249: peer SNI `127.0.0.1` for host `127.0.0.1`. With this change: none. - The cases that dial `[::1]` gate on `isIPv6()` (Buildkite Linux has no IPv6 loopback). The other cases run on every lane. One of them dials 127.0.0.1 with `tls.serverName: "[::1]"`, so every lane checks a bracketed name against the `IP:::1` entry. - Two gaps in the same `parseOptions` block are on main and stay out of this PR: `tls.servername` (the Node spelling) is ignored, which oven-sh#42054 owns, and `tls: true` without an sslmode derives no `serverName`, which oven-sh#26369 tracks. A `BunFile` given as `tls` with an explicit sslmode loses the file there, which oven-sh#41761 owns. - Same bug class as oven-sh#30668, which oven-sh#30674 fixed for fetch and WebSocket. The dial path already removes the brackets (`src/uws_sys/socket.rs:791`). - Other suites run on the merged debug build (main 601af5a): `postgres-pgsslmode-env`, `sql-mysql-tls-plaintext-injection`, all of `adapter-env-var-precedence`, and `test/js/bun/net/tls-reject-before-client-cert.test.ts` (121 pass, 9 skip). I ran the new file 40 times on the earlier head: 320 of 320 cases pass. The container TLS suites (`tls-sql`, `local-sql`) need Docker and run in CI. </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 -->
…rops (oven-sh#43995) ### Problem - A `/_bun/hmr` socket that drops a topic still receives it. After `sh`, then `s`, three edits give `["u","u","u"]`, not `[]`. - With no other `h` subscriber, the next bundle aborts a debug build: `panic: assertion failed: ref_count > 0`. A release build leaks the source map entry. - The cause is at `src/runtime/bake/dev_server/hmr_socket.rs:149`. The `else if` that calls `ws.unsubscribe` repeats the condition of its `if`. No user reported this. ### Fix - The condition becomes `!new_bits.contains(bit) && self.subscriptions.contains(bit)`. - This is correct because the handler already replaces the whole set. It calls `on_unsubscribe` for the dropped bits and overwrites `subscriptions`. - Verified: a new case in `test/bake/hmr-socket-protocol.test.ts` fails on main and passes here. Also ran `test/bake/dev/hot.test.ts`. - Self-reviewed: 10 concerns raised, 9 addressed. Deferred: a clippy lint for this pattern. ### Background - `/_bun/hmr` is the WebSocket of the dev server. The frame `s` plus topic letters replaces the topic set of a socket. Topic `h` delivers hot updates (`u`). - uWS (the WebSocket library) holds the subscriptions and publishes. `HmrSocket.subscriptions` is the dev server's copy. `finalize_bundle` counts source map references by the copy. - No other design was weighed: the cause and the fix are on one line. This is the unsubscribe half of oven-sh#37878. It merges cleanly with oven-sh#42547. ### Downsides - A client that dropped a topic no longer gets its frames. No client in the tree sends a second subscribe frame. - `HmrSocket::on_message` grows by 37 bytes (4945 to 4982, linux-x64 release). The file size does not change. <details><summary>Notes</summary> **Reach** - The bug is in all builds, stable included. The Zig version of the handler had the same two conditions (`src/bake/DevServer/HmrSocket.zig`, lines 74 and 96, before oven-sh#30412). - No client in the tree sends a second subscribe frame. `hmr-runtime-client.ts` sends `she` once, `hmr-runtime-error.ts` sends `se` once, the test harness sends `sr` once. The bug affects hand-written clients and tests. - There is no issue and no user report. The ground for the change is `REVIEW.md`: a failure that network bytes can reach must not be a panic. **Conditions for the abort** - The build has debug assertions (debug, ASAN). - A socket dropped `h`, and no other socket has the `h` bit. A browser tab sends `she`, so a connected tab prevents the abort. The extra frames remain. - The bundle has a source map that the store does not hold yet. - An edit starts such a bundle. The first request for a page that is not bundled yet starts one too. The new test uses that. ``` panic: assertion failed: ref_count > 0 SourceMapStore::put_or_increment_ref_count src/runtime/bake/dev_server/source_map_store.rs:467 finalize_bundle src/runtime/bake/DevServer.rs:4578 ``` **Script for the extra frames** ```js import { mkdtempSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { tmpdir } from "node:os"; const dir = mkdtempSync(join(tmpdir(), "elseif-")); process.chdir(dir); writeFileSync(join(dir, "a.html"), `<!doctype html><html><body><script type="module" src="./a.ts"></script></body></html>`); writeFileSync(join(dir, "a.ts"), `console.log("v0");`); const html = (await import(join(dir, "a.html"))).default; const srv = Bun.serve({ routes: { "/a": html }, development: true, port: 0, hostname: "127.0.0.1" }); await (await fetch(`http://127.0.0.1:${srv.port}/a`)).text(); const spin = async ms => { const end = Date.now() + ms; while (Date.now() < end) await new Promise(r => setImmediate(r)); }; const ids = []; const ws = new WebSocket(`ws://127.0.0.1:${srv.port}/_bun/hmr`); ws.binaryType = "arraybuffer"; const ready = Promise.withResolvers(); ws.onmessage = e => { const id = String.fromCharCode(new Uint8Array(e.data)[0]); if (id === "V") { ws.send("sh"); ws.send("s"); ready.resolve(); } else ids.push(id); }; ws.onclose = () => ids.push("<closed>"); await ready.promise; await spin(300); for (let i = 1; i <= 3; i++) { writeFileSync(join(dir, "a.ts"), `console.log("v${i}");`); await spin(700); } console.log("frames after the socket dropped every topic:", JSON.stringify(ids)); process.exit(0); ``` | Build | Result | | --- | --- | | 1.4.2+744846f84 (released) | `["u","u","u"]` | | main 29d9638, release build, canary config | `["u","u","u"]` | | main 29d9638, debug build, one socket | `panic: assertion failed: ref_count > 0` | | this branch, debug build | `[]` | | this branch, debug build, `shr` then `sr` | `["r","r","r"]` (the kept topic still arrives) | Control: a socket that never sends `sh` gets `[]` on each build. **Source map entries on a release build** - In a release build the assert is compiled out. `put_or_increment_ref_count` stores the entry with `ref_count` 0. The only removal path is `unref_at_index`, and no socket owns the entry. - Measurement: one socket, 20 edits, each with a new source map. After the socket closed, I requested the source map URL of each hot update. | Build | Socket sends | Hot updates received | Source maps still served after close | | --- | --- | --- | --- | | 1.4.2+744846f84 (released) | `sh`, then `s` | 20 | 20 | | 1.4.2+744846f84 (released) | `sh` | 20 | 0 | | main 29d9638, release build | `sh`, then `s` | 20 | 20 | | main 29d9638, release build | `sh` | 20 | 0 | | this branch, debug build | `sh`, then `s` | 0 | 0 | **The test** - One socket subscribes to four topic sets in turn: `hr`, `r`, none, `hr`. Each step requests a page that is not bundled yet. That starts exactly one bundle, and the response arrives after the dev server published the frames of that bundle. - A SetUrl round trip (`n` plus a route) opens and closes the frame window of a step. The server answers on the same socket, after each frame that it published to that socket before. - The test uses no file watcher and no second socket. An earlier draft used both and failed 2 of 1033 runs under load, because two sockets have no order between them. - Result on main, release build: the `r` step receives `["r","u"]` and the step with no topic receives `["r","u"]`. Result on main, debug build: the dev server aborts with the panic above. | Setup, debug build of this branch, linux-x64 | Runs | Failures | | --- | --- | --- | | The new case alone | 60 | 0 | | 6 loops of the file beside 15 parallel workers that run other test files | 219 | 0 | | Before 1cede56, the same two setups | 60 and 353 | 0 | | Before 1cede56, 6 copies of the new case in one runner, 4 pinned CPUs, 2 parallel workers beside it | 492 | 0 | - The test is not run on Windows or macOS before this PR. CI is the first run there. - Each awaited promise rejects on its own failure, on the process exit and on the socket close. Each rejection carries the stderr of the dev server. - After a panic, the dev server sends nothing more until the process exits. The crash handler of a debug build needs about 4 s for that. With the default 5 s timeout on a loaded machine, the test can then report a timeout and not the panic text. CI uses 90 s (270 s on the ASAN lane). **Cost for a client that never drops a topic** - Each subscribe frame evaluates the new condition for each of the 6 topics. There is no allocation and no syscall on that path. - `ws.unsubscribe` runs only for a topic that the frame drops. - Sizes are from `nm -S` and `size -A` on `bun-profile`, release builds of 29d9638 and of this branch. File size: 80995912 bytes for both. `bloaty` is not installed. **Possible follow-up: a lint for this pattern** - The clippy lint `same_functions_in_if_condition` reports an `else if` that repeats the call of its `if`. The default lint `ifs_same_cond` does not look at conditions with calls. - `cargo clippy --workspace --no-deps --keep-going -- -D clippy::same_functions_in_if_condition` gives one error on main (this line) and no error with this change (clippy 0.1.100, linux-x64). - The lint is not in this PR. A change to `[workspace.lints.clippy]` changes the rustc flags of each workspace crate, so each crate builds again once. **Relation to other PRs** - oven-sh#37878 had this change and closed with no maintainer objection, in favor of oven-sh#39488. Its other half (the `on_unsubscribe` counter) is on main through oven-sh#33196. - oven-sh#39488 has the same condition (`hmr_socket.rs:133` on its head) but has conflicts since 2026-08-28. - oven-sh#40255 rewrites this handler and keeps the old condition. It must take the new condition on its next rebase. - oven-sh#42547 makes the memory visualizer timer publish an `M` frame each second. A socket that dropped `M` then keeps receiving that frame while another socket holds `M`. This change stops that. A test merge of the two heads (this branch and 95ee86a) has no conflict. </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/bake/hmr-socket-protocol.test.ts bun test v1.4.3 (367d939) test/bake/hmr-socket-protocol.test.ts: (pass) a duplicate testing-batch frame (H) during an in-flight bundle closes the socket instead of aborting [880.24ms] (pass) a SetUrl frame without a leading slash ("nfoo") closes the socket instead of aborting [776.41ms] (pass) a SetUrl frame without a leading slash ("n") closes the socket instead of aborting [1021.87ms] (pass) releasing a testing batch while another bundle is in flight defers it [1042.66ms] 407 | /** Awaits `promise`. Its failure, a process exit, or a socket close rejects with the dev server's stderr. */ 408 | async function orFail<T>(promise: Promise<T>) { 409 | try { 410 | return await Promise.race([promise, failed.promise]); 411 | } catch (e) { 412 | throw new Error(`${(e as Error).message}\n--- dev server stderr ---\n${dev.stderr()}`, { cause: e }); ^ error: hmr websocket closed (code 1006, reason "Connection ended") --- dev server stderr --- Bundled page in 119ms ... (truncated) release without fix: 1 FAILED bun test v1.4.3-canary.1 (abc36e727) test/bake/hmr-socket-protocol.test.ts: (pass) a SetUrl frame without a leading slash ("nfoo") closes the socket instead of aborting [37.14ms] (pass) a SetUrl frame without a leading slash ("n") closes the socket instead of aborting [41.24ms] (pass) a duplicate testing-batch frame (H) during an in-flight bundle closes the socket instead of aborting [52.96ms] 446 | // Frames that arrive before this reply belong to the previous topic set. 447 | await roundTrip(); 448 | await orFail(fetch(`http://127.0.0.1:${port}${page}`).then(response => response.text())); 449 | delivered.push({ topics, ids: [...new Set(await roundTrip())].sort() }); 450 | } 451 | expect(delivered).toEqual([ ^ error: expect(received).toEqual(expected) [ { "ids": [ "r", "u", ], "topics": "hr", }, { "ids": [ "r", + "u", ], "topics": "r", }, { - "ids": [], + "ids": [ + "r", + "u", + ], "topics": "", }, { "ids": [ "r", "u", ], "topics": "hr", }, ] - Expected ... (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/bake/hmr-socket-protocol.test.ts bun test v1.4.3 (367d939) test/bake/hmr-socket-protocol.test.ts: (pass) a SetUrl frame without a leading slash ("nfoo") closes the socket instead of aborting [874.43ms] (pass) releasing a testing batch while another bundle is in flight defers it [1016.05ms] (pass) a subscribe frame that drops a topic stops delivery of that topic [1140.59ms] (pass) a SetUrl frame without a leading slash ("n") closes the socket instead of aborting [1316.42ms] (pass) a duplicate testing-batch frame (H) during an in-flight bundle closes the socket instead of aborting [1595.68ms] 5 pass 0 fail 9 expect() calls Ran 5 tests across 1 file. [4.40s] __F:0:S:0 release with fix: all passed $ bun scripts/build.ts --profile=release [configured] bun-profile → bun (stripped) in 1306ms (unchanged) ninja: Entering directory `/workspace/bun/build/release' [1/57] gen generated_host_exports.rs generated_host_exports.rs: 121 exports (host=5, lazy=10, generic=106, rust=0); 248 extern-C blocks audited [2/56] rustc bun_csrf [3/56] rustc bun_s3_signing [4/56] rustc bun_exe_format [5/56] rustc bun_threading [6/56] rustc bun_dotenv [7/56] rustc bun_uws_sys [8/56] rustc bun_uws [9/56] rustc bun_libarchive [10/56] rustc bun_sql [11/56] rustc bun_watcher [12/56] rustc bun_io [13/56] rustc bun_event_loop [14/56] rustc bun_crash_handler [15/56] rustc bun_md [16/56] rustc bun_spawn [17/56] rustc bun_patch [18/56] rustc bun_ast [19/56] rustc bun_install_types [20/56] rustc bun_resolve_builtins [21/56] rustc bun_options_types [22/56] rustc bun_api [23/56] rustc bun_http [24/56] rustc bun_parsers [25/56] rustc bun_sourcemap [26/56] cxx obj/src/jsc/bindings/BunProcess.cpp.o [27/56] rustc bun_js_printer [28/56] rustc bun_react_compiler [29/56] rustc bun_ini [30/56] rustc bun_css [31/56] rustc bun_js_parser [32/56] rustc bun_resolver [33/56] rustc ... (truncated) ``` </details> <details><summary>diff hotspot</summary> ``` src/runtime/bake/dev_server/hmr_socket.rs | 5 +- test/bake/hmr-socket-protocol.test.ts | 116 ++++++++++++++++++++++++++++++ 2 files changed, 117 insertions(+), 4 deletions(-) ``` </details> **gate history** · 1 passed · 0 rejected · iteration 0 <details><summary>evidence per changed file</summary> ``` file reads edits tests src/runtime/bake/dev_server/hmr_socket.rs 1 1 33 test/bake/hmr-socket-protocol.test.ts 3 5 31 ``` </details> <!-- robobun:evidence:end -->
…h#42235) Builds on oven-sh#42176, which is merged. The base of this PR is `main`. Consolidates oven-sh#42240 (the same fix). ### Problem - A TLS upgrade over a generic `Duplex` listens for the transport's `data`, `end`, `drain` and `close`, but not its `error`. So `transport.destroy(err)` after the upgrade throws `err` as an uncaught exception. Node emits it on the TLS socket. - `transport.listenerCount('error')` is 0 in bun and 1 in node v26.3.0. An `https.request` over such a socket kills the process and does not fail the request. ### Fix - `forwardUpgradedError` (`src/js/node/net.ts`) forwards the transport's `error` through `_emitTLSError`. The four stream-engine attach sites call it. A client sees `'error'`. A server wrap keeps it on `'_tlsError'` (`'tlsClientError'` on a `tls.Server`). The transport's `'close'` then ends the socket (oven-sh#42176). - A `net.Socket` transport (a named pipe, unflushed writes, TLS over TLS) is excluded. Its close paths synthesize a read `ECONNRESET` as soon as anything listens for `'error'`. See Notes. - Verified: `test/js/node/tls/node-tls-connect.test.ts`, 5 new tests. One runs `node-tls-duplex-transport-error-fixture.ts` through `bunRun` (six wrap cases in one subprocess). All 5 fail on `main`. Also `test/js/node/tls` and 9 vendored `test-tls-*` tests. ### Background - A stream with no fd cannot use the kernel TLS path. `upgradeDuplexToTLS` runs a BoringSSL engine over the stream, driven by four native thunks on the stream's events. None is an error thunk. - Node wraps the stream in a `JSStreamSocket`, which re-emits the stream's `'error'`. `TLSSocket._init` forwards that error with `_emitTLSError`. - `_emitTLSError` already exists in `src/js/node/tls.ts`. It emits `'_tlsError'` always, and `'error'` only once `_releaseControl` has run. `tls.connect()` releases control at once, a server socket on `'secure'`. <details><summary>Notes</summary> #### Measurements Each case wraps a `Duplex`, then calls `transport.destroy(new Error("transport failed"))`. Events on the TLS socket (or the request), linux x64, debug+ASAN. The first six rows are `node-tls-duplex-transport-error-fixture.ts`, and the node column is v26.3.0 with the same fixture. The `https.request` row runs in the test process. | case | `main` (has oven-sh#42176) | this branch | node v26.3.0 | | --- | --- | --- | --- | | `tls.connect({ socket })`, destroy in the same tick | uncaught `transport failed`, non-zero exit | `_tlsError`, `error`, `close:false` | same | | `tls.connect({ socket })`, destroy after the ClientHello | uncaught, non-zero exit | `_tlsError`, `error`, `close:false` | same | | server wrap, destroy in the same tick | uncaught, non-zero exit | `_tlsError`, `close:false` | same | | server wrap, destroy after the engine started | uncaught, non-zero exit | `_tlsError`, `close:false` | same | | `tlsServer.emit("connection", duplex)`, destroy in the same tick | uncaught, non-zero exit | `tlsClientError` with the `TLSSocket`, `close:false` | same | | `tlsServer.emit("connection", duplex)`, destroy after the engine started | uncaught, non-zero exit | `tlsClientError` with the `TLSSocket`, `close:false` | same | | `https.request` over the wrap | uncaught, non-zero exit | `req.error`, `req.close` with `req.destroyed === true` | same | A transport that errors without closing also matches node: the error reaches the TLS socket and the socket stays alive (`destroyed === false`). Two more cases from oven-sh#42240, measured by hand on this branch (no test): | case | bun 1.4.3-canary.1 | this branch | node v26.3.0 | | --- | --- | --- | --- | | `tlsSocket.destroy()` over `Duplex.from({ readable, writable })` | uncaught `ABORT_ERR` | `error:ABORT_ERR`, `close:false` | same | | transport whose `write` calls back with an error, `s.write(data, cb)` queued | uncaught `EBOOM`, `cb` never called, no `'close'` | `error:EBOOM`, `cb(ERR_SOCKET_CLOSED)`, `close:false` | `error:EBOOM`, `cb(ECANCELED)`, `close:false` | The callback code in the last row differs because node cancels the queued write through `JSStreamSocket.doClose`. oven-sh#35386 covers `ECANCELED` for cancelled TLS writes. #### Consolidation of oven-sh#42240 oven-sh#42240 carried the same listener with the same `net.Socket` guard. This branch keeps the test shape the review here asked for (`bunRun`, a fixture file, a one-line comment plus the node links). The cases that only oven-sh#42240 had are now in the fixture: a server wrap at both timings, `https.request` over the wrap, `'_tlsError'`, and the `'close'` `hadError` flag. oven-sh#42176 dropped the `attachUpgradedDuplex` helper that both PRs had patched. It now attaches the four thunks inline at each site. So the listener moved to `forwardUpgradedError`, which each site calls after it attaches the four thunks. #### Scope: every `net.Socket` transport is left out Two arms wrap a `net.Socket`, and neither gets the listener: - The fd-adoption arm. `tls.connect({ socket: connectedNetSocket })` with no queued writes hands the fd to a native TLS pair (`upgradeTLS`) and attaches nothing to the `net.Socket`. - The stream-level engine over a `net.Socket`: TLS over TLS, a named pipe, or a socket with queued plain writes. These reach `forwardUpgradedError` and the `instanceof Socket` check skips them. Node attaches the same listener in both, so `sock.destroy(err)` on such a transport is still uncaught in bun. The reason is one mechanism. `SocketEmitEndNT`, `SocketHandlers2.close`, `failWrite` and `ServerHandlers.error` turn a peer reset into `destroy(ECONNRESET)` only when the socket has an `'error'` listener, and stay silent otherwise. A forwarder counts as a listener. The first push of oven-sh#42240 attached it to every transport. `test-tls-inception.js` (TLS over TLS, no `'error'` listener anywhere) then failed on Windows x64, Windows arm64 and macOS arm64 with an uncaught `read ECONNRESET`. On Windows x64 the base passed 5 of 5 runs, that push failed 5 of 5, and the narrowed listener passed 6 of 6. Those arms also have a second route to the same failure (the raw socket's own dispatch), so they need the de-duplication that oven-sh#36534 and oven-sh#38122 are about. `new tls.TLSSocket(stream)` with no `connect()` wraps nothing today, so nothing reaches it there either. That is oven-sh#37664's subject. `_http2_upgrade.ts` has a fifth copy of the same four `.on()` calls. oven-sh#38124 routes its transport error to the h2 session. #### Fixture startup The fixture runs its six cases in one subprocess and takes the key and the cert from `KEY` and `CERT`, which the test sets. An earlier shape ran five subprocesses at once, and each imported `harness`. A debug build needs about 1.5 s to load `node:tls` and about 1 s more for `harness`, so on a loaded machine (load average 150 on 16 cores) two of the five reached the 5 s test timeout. The one subprocess takes 2.1 to 2.8 s on the same machine. #### Suites `test/js/node/tls/node-tls-connect.test.ts`: 84 pass, 0 fail. `test/js/node/tls/`: 391 pass, 3 fail, none on the Duplex wrap path. `SNICallback runs even when the requested servername matches the bind hostname` binds `localhost` and connects to `127.0.0.1`, and fails the same way on the released binary in this container. `tls.Server socket destroySoon > delivers the whole stream when destroySoon follows end` (64 rounds of 2 MB) times out at 5 s on this debug build, and does the same with `main`'s `net.ts`. `root certificate initialization > concurrent Workers all see the same CA certificate lists` times out in some runs on this loaded machine. Vendored, all exit 0: `test-tls-inception`, `test-tls-js-stream`, `test-tls-connect-given-socket`, `test-tls-delayed-attach-error`, `test-tls-socket-failed-handshake-emits-error`, `test-tls-over-http-tunnel`, `test-tls-starttls-server`, `test-tls-destroy-stream`, `test-https-agent-create-connection`. </details> <!-- robobun:evidence:begin --> --- **[human-review]** gate passed · iteration 0 · 3 files touched <details><summary>fails on main (without fix)</summary> ```console ASAN without fix: 7 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 bun test v1.4.3 (367d939) test/js/node/tls/node-tls-connect.test.ts: (pass) should have checkServerIdentity [4.73ms] (pass) should thow ECONNRESET if FIN is received before handshake [534.04ms] (pass) initializes authorizationError to null in the TLSSocket constructor [6.87ms] (pass) setMaxSendFragment mirrors OpenSSL's [512, 16384] acceptance without throwing [120.38ms] (pass) should be able to grab the JSStreamSocket constructor [14.03ms] (skip) tls.connect > should work with alpnProtocols (pass) tls.connect > Bun.serve() should work with tls and Bun.file() [116.64ms] (pass) tls.connect > should have peer certificate when using self asign certificate [150.83ms] (skip) tls.connect > should have peer certificate (skip) tls.connect > getCipher, getProtocol, getEphemeralKeyInfo, getSharedSigalgs, getSession, exportKeyingMaterial and isSessionReused should work (skip) tls.connect > should process options correctly when connect is called with only options (skip) tls.connect > should process port ... (truncated) release without fix: 11 failed, 18 skipped bun test v1.4.3-canary.1 (367d939) test/js/node/tls/node-tls-connect.test.ts: (pass) should have checkServerIdentity [0.03ms] (pass) should thow ECONNRESET if FIN is received before handshake [6.17ms] (pass) initializes authorizationError to null in the TLSSocket constructor [0.16ms] (pass) setMaxSendFragment mirrors OpenSSL's [512, 16384] acceptance without throwing [3.30ms] (pass) should be able to grab the JSStreamSocket constructor [0.21ms] (skip) tls.connect > should work with alpnProtocols (pass) tls.connect > Bun.serve() should work with tls and Bun.file() [5.48ms] (pass) tls.connect > should have peer certificate when using self asign certificate [4.83ms] (skip) tls.connect > should have peer certificate (skip) tls.connect > getCipher, getProtocol, getEphemeralKeyInfo, getSharedSigalgs, getSession, exportKeyingMaterial and isSessionReused should work (skip) tls.connect > should process options correctly when connect is called with only options (skip) tls.connect > should process port and host correctly (skip) tls.connect > should process port, host, and callback correctly (skip) tls.connect > should handle the absence of a callback gracefully (skip) tls.c ... (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 bun test v1.4.3 (367d939) test/js/node/tls/node-tls-connect.test.ts: (pass) should have checkServerIdentity [3.79ms] (pass) should thow ECONNRESET if FIN is received before handshake [386.28ms] (pass) initializes authorizationError to null in the TLSSocket constructor [6.71ms] (pass) setMaxSendFragment mirrors OpenSSL's [512, 16384] acceptance without throwing [102.58ms] (pass) should be able to grab the JSStreamSocket constructor [15.93ms] (skip) tls.connect > should work with alpnProtocols (pass) tls.connect > Bun.serve() should work with tls and Bun.file() [97.47ms] (pass) tls.connect > should have peer certificate when using self asign certificate [122.29ms] (skip) tls.connect > should have peer certificate (skip) tls.connect > getCipher, getProtocol, getEphemeralKeyInfo, getSharedSigalgs, getSession, exportKeyingMaterial and isSessionReused should work (skip) tls.connect > should process options correctly when connect is called with only options (skip) tls.connect > should process port a ... (truncated) release with fix: 18 skipped $ bun scripts/build.ts --profile=release [configured] bun-profile → bun (stripped) target linux-x64-gnu build type Release build dir ./build/release revision 9098c05 features lto, baseline 23 deps, 136 codegen, 1176 objects in 977ms 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 codegen [2/1499] mkdir stamps [3/1499] install /workspace/bun bun install v1.4.3-canary.1 (367d939) Checked 26 installs across 65 packages (no changes) [15.00ms] [4/1499] install /workspace/bun/packages/bun-error bun install v1.4.3-canary.1 (367d939) Checked 1 install across 2 packages (no changes) [4.00ms] [5/1499] install /workspace/bun/src/node-fallbacks bun install v1.4.3-canary.1 (367d939) Checked 111 installs across 104 packages (no changes) [6.00ms] [6/1499] rustc unicode_ident [7/1499] gen node-fallbacks ... (truncated) ``` </details> <details><summary>diff hotspot</summary> ``` src/js/node/net.ts | 10 ++++ test/js/node/tls/node-tls-connect.test.ts | 45 ++++++++++++++++- .../tls/node-tls-duplex-transport-error-fixture.ts | 58 ++++++++++++++++++++++ 3 files changed, 112 insertions(+), 1 deletion(-) ``` </details> **gate history** · 5 passed · 0 rejected · iteration 0 <details><summary>evidence per changed file</summary> ``` file reads edits tests src/js/node/net.ts 13 12 41 test/js/node/tls/node-tls-connect.test.ts 3 4 39 …/js/node/tls/node-tls-duplex-transport-error-fixture.ts 1 3 44 ``` </details> <!-- robobun:evidence:end --> --------- Co-authored-by: robobun <[email protected]> Co-authored-by: Ciro Spaciari <[email protected]>
…amedPipe Fixes the build on every non-Windows target. The variant only exists on Windows, so the cfg(not(windows)) arm failed with E0599.
…ad (oven-sh#42326) ### Problem - `fetch()` with an `Upgrade` header and a streaming body, through a CONNECT proxy, frees the `HTTPClient` while a caller still holds it. ASAN on `main`: `heap-use-after-free ... READ of size 1` in `handle_response_metadata` (`src/http/lib.rs:4870`), reached from `handle_on_data_headers` and `proxy_tunnel::on_data`. - The cause is `SSLWrapper::write_data` (`src/uws/lib.rs:802`). A read that hits a fatal SSL error still delivers the data it decrypted first. The `101` arm of `handle_on_data_headers` calls `flush_stream`, whose write reaches `SSL_write` on the now-fatal SSL. `write_data` then closed the wrapper from inside that callback, and `proxy_tunnel::on_close` freed the client under its own caller. ### Fix - `write_data` fails the write with `ConnectionClosed` and does not close while `fatal_error` is set. The read that set the flag closes once its callbacks return, so the owner's `on_close` runs in the frame that owns it. - Correct because every `write_data` caller already treats `Err` as "no bytes went out" and the close still happens, one frame later. It is the same rule as the `sent_ssl_shutdown` guard above it. - Verified: `test/js/bun/http/proxy.test.ts` ("a bad record delivered with a 101 through a proxy tunnel does not free the client mid-dispatch") with `test/js/bun/http/proxy-upgrade-fatal-record-fixture.ts`. It fails on `main` with the ASAN report and passes with the change. Also all of `proxy.test.ts`, `websocket-proxy.test.ts`, `fetch-proxy-connect-tunnel-split-envelope.test.ts`, `node-tls-connect.test.ts`, and `socket.test.ts`. ### Background - `SSLWrapper` (`src/uws/lib.rs`) runs BoringSSL over memory BIOs for TLS on a transport that is not a `us_socket_t`: a CONNECT tunnel for fetch and WebSocket, a `Duplex`, a Windows named pipe. It calls its owner back through `Handlers` (`on_data`, `write`, `on_close`). - A fatal `SSL_read` sets `fatal_error`, flushes the bytes it already decrypted through `on_data`, and then closes. The owner's `on_close` is its teardown: `proxy_tunnel::on_close` fails the request, which frees the `HTTPClient`. - `flush_stream` exists for the `101` arm, because an upgraded request keeps streaming its body after the response headers arrive. <details><summary>Notes</summary> - Repro (the fixture): a CONNECT proxy holds the origin's records until the `101` response record is whole, then writes it with an application_data record of 32 unauthenticated bytes appended, so one `SSL_read` pass decrypts both. The body is an async generator, so the `101` arm has something to flush. - The fixture clears `NO_PROXY` and the other proxy variables in the child, like the fixture test above it. This container sets `NO_PROXY=localhost,...`, which makes the per-request `proxy:` option a no-op and hides the bug. - Without the guard the process aborts on the first iteration. With it, both iterations finish, the fixture reports `injected: 2` (every connection really got the bad record), and a fresh request on a new connection still answers. - The proxy releases the held bytes once the body generator has been pulled, plus a 100 ms grace. The hand-off of the chunk from the JS thread to the HTTP thread is not observable from JS, so that last hop is a fixed wait. If it were too short the test would pass without exercising the write, it could not fail spuriously. - The ASAN stack: `write_data` (`src/uws/lib.rs:802`) to `trigger_close_callback` to `proxy_tunnel::on_close` (`ProxyTunnel.rs:525`) to `close_and_fail` to `AsyncHTTP::on_async_http_callback_raw` (the free), while frame 19 is `flush_stream` from `handle_on_data_headers`, which reads the client again on return. - Found while I reviewed the TLS-over-Duplex error reporting in oven-sh#42324. That PR needs the same guard, because its `'data'` listener case depends on the close carrying the read's error. This PR sends it to `main` on its own, with a fetch-level regression test. - A fatal `SSL_write` with no read in flight is unchanged: `fatal_error` is only set by the read path before this point, so an ordinary write that fails still closes as before. </details> <!-- robobun:evidence:begin --> --- **[human-review]** gate passed · iteration 3 · 3 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/http/proxy.test.ts bun test v1.4.3 (4ff9193) test/js/bun/http/proxy.test.ts: (pass) GET non-TLS proxy -> non-TLS body type undefined [746.82ms] (pass) POST non-TLS proxy -> non-TLS body type string [738.65ms] (pass) GET TLS proxy -> non-TLS body type undefined [843.47ms] (pass) GET non-TLS proxy -> TLS body type undefined [957.24ms] (pass) POST non-TLS proxy -> TLS body type string [976.61ms] (pass) POST TLS proxy -> non-TLS body type string [352.90ms] (pass) GET TLS proxy -> TLS body type undefined [508.51ms] (pass) POST TLS proxy -> TLS body type string [484.95ms] (pass) proxy can handle redirects with non-TLS server > with empty body oven-sh#12007 [493.61ms] (pass) proxy can handle redirects with non-TLS server > with body oven-sh#12007 [747.46ms] (pass) proxy can handle redirects with TLS server > with empty body oven-sh#12007 [764.30ms] (pass) proxy can handle redirects with TLS server > with body oven-sh#12007 [713.58ms] (pass) proxy can handle redirects with non-TLS server > with chunked body oven-sh#12007 [1249.08ms] (pass) proxy can handle redirec ... (truncated) release without fix: 1 skipped bun test v1.4.3-canary.1 (d4f44b9) test/js/bun/http/proxy.test.ts: (pass) POST non-TLS proxy -> non-TLS body type string [36.97ms] (pass) GET non-TLS proxy -> non-TLS body type undefined [37.29ms] (pass) POST TLS proxy -> non-TLS body type string [43.52ms] (pass) GET TLS proxy -> non-TLS body type undefined [43.56ms] (pass) POST non-TLS proxy -> TLS body type string [52.68ms] (pass) GET non-TLS proxy -> TLS body type undefined [52.72ms] (pass) POST TLS proxy -> TLS body type string [54.88ms] (pass) GET TLS proxy -> TLS body type undefined [54.91ms] (pass) proxy can handle redirects with non-TLS server > with empty body oven-sh#12007 [57.72ms] (pass) proxy can handle redirects with non-TLS server > with body oven-sh#12007 [71.35ms] (pass) proxy can handle redirects with TLS server > with empty body oven-sh#12007 [76.33ms] (pass) proxy can handle redirects with TLS server > with body oven-sh#12007 [75.14ms] (pass) proxy can handle redirects with non-TLS server > with chunked body oven-sh#12007 [651.78ms] (pass) proxy can handle redirects with TLS server > with chunked body oven-sh#12007 [659.64ms] (pass) non-TLS origin redirect through HTTPS proxy forwards every hop through the proxy [7.45ms] (pass) unsupp ... (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/http/proxy.test.ts bun test v1.4.3 (4ff9193) test/js/bun/http/proxy.test.ts: (pass) GET non-TLS proxy -> non-TLS body type undefined [818.58ms] (pass) POST non-TLS proxy -> non-TLS body type string [806.81ms] (pass) GET TLS proxy -> non-TLS body type undefined [923.01ms] (pass) GET non-TLS proxy -> TLS body type undefined [1073.78ms] (pass) POST non-TLS proxy -> TLS body type string [1111.61ms] (pass) POST TLS proxy -> non-TLS body type string [423.33ms] (pass) GET TLS proxy -> TLS body type undefined [615.30ms] (pass) POST TLS proxy -> TLS body type string [587.75ms] (pass) proxy can handle redirects with non-TLS server > with empty body oven-sh#12007 [604.16ms] (pass) proxy can handle redirects with non-TLS server > with body oven-sh#12007 [841.51ms] (pass) proxy can handle redirects with TLS server > with empty body oven-sh#12007 [814.41ms] (pass) proxy can handle redirects with TLS server > with body oven-sh#12007 [741.93ms] (pass) proxy can handle redirects with non-TLS server > with chunked body oven-sh#12007 [1274.71ms] (pass) proxy can handle redir ... (truncated) release with fix: 1 skipped $ bun scripts/build.ts --profile=release [configured] bun-profile → bun (stripped) in 768ms (unchanged) ninja: Entering directory `/workspace/bun/build/release' [0/1] reconfigure [1/173] install /workspace/bun bun install v1.4.3-canary.1 (d4f44b9) Checked 22 installs across 61 packages (no changes) [6.00ms] [2/173] gen JSEvent.lut.h Generating /workspace/bun/build/release/codegen/JSEvent.lut.h from /workspace/bun/src/jsc/bindings/webcore/JSEvent.cpp [3/173] gen ErrorCode+*.h [4/173] gen JSBuffer.lut.h Generating /workspace/bun/build/release/codegen/JSBuffer.lut.h from /workspace/bun/src/jsc/bindings/JSBuffer.cpp [5/173] gen ProcessBindingConstants.lut.h Generating /workspace/bun/build/release/codegen/ProcessBindingConstants.lut.h from /workspace/bun/src/jsc/bindings/ProcessBindingConstants.cpp [6/173] gen ProcessBindingHTTPParser.lut.h Generating /workspace/bun/build/release/codegen/ProcessBindingHTTPParser.lut.h from /workspace/bun/src/jsc/bindings/ProcessBindingHTTPParser.cpp [7/173] gen bindgenv2 [8/173] gen ProcessBindingBuffer.lut.h Generating /workspace/bun/build/release/codegen/ProcessBindingBuffer.lut.h from /workspace/bun/src/jsc/bindings/ProcessBindin ... (truncated) ``` </details> <details><summary>diff hotspot</summary> ``` src/uws/lib.rs | 5 + .../bun/http/proxy-upgrade-fatal-record-fixture.ts | 159 +++++++++++++++++++++ test/js/bun/http/proxy.test.ts | 35 +++++ 3 files changed, 199 insertions(+) ``` </details> **gate history** · 2 passed · 0 rejected · iteration 3 <details><summary>evidence per changed file</summary> ``` file reads edits tests src/uws/lib.rs 7 8 22 test/js/bun/http/proxy-upgrade-fatal-record-fixture.ts 0 1 23 test/js/bun/http/proxy.test.ts 1 1 19 ``` </details> <!-- robobun:evidence:end -->
…n-sh#43947) Follow-up to oven-sh#43924. ### Problem - On a half-closed socket the peer's flight can arrive in two reads. The writable event between them reports `handshake(success=false, error=null)` (`ssl_update_handshake`, `packages/bun-usockets/src/crypto/openssl.c`). BoringSSL then finishes the handshake, and a rejecting `Bun.listen` server passes an untrusted client's data to `data()`. - `us_internal_ssl_verify_error` answers "no error" for a half-closed or fatal socket. ### Fix - `ssl_update_handshake` takes `fin_ends_handshake`. Only the writable event passes 0. - `us_internal_ssl_verify_error` reads the SSL on every open socket, like node's `TLSWrap::VerifyError`. After our FIN a failed handshake reports it only for a chain that it checked. - `on_handshake` (`socket_body.rs`) closes a rejecting `Bun.connect` socket on every failed handshake. - Verified: `socket.test.ts` (9 new, base fails 3), `node-tls-duplex-end-verify.test.ts` (15 new, base fails 3, Node v26.3.0 passes 31 of 31), `node-tls-server.test.ts` (1 new). ### Background - `end()` during a handshake sends a FIN and no alert. The socket keeps reading, so the handshake can still complete. - node:tls reads a failed handshake with an X509 code as an established session, and one with no error after `end()` as its own close. - Considered the close in `on_handshake` alone. The state machine would still report a live handshake as failed. ### Downsides - `getAuthorizationError()` on a half-closed socket answers `UNABLE_TO_GET_ISSUER_CERT`, not `null`, until its handshake reports. - A rejecting `Bun.connect` socket whose handshake fails with no error now closes. It stayed open until the peer closed. - Release `.text`: 58154908 B before and after. Each checked chain costs 1 store. A two-read flight on a half-closed socket costs 2 more `SSL_do_handshake` calls (6 to 8). <details><summary>Notes</summary> **Cases, measured on the head of oven-sh#43924 (a3b00db, merged as 92d6092) and with this change** The peer's certificate is untrusted unless the row says otherwise. "Two reads" means that the peer's last handshake flight arrives in two TCP segments, split inside a record. The peer chooses that. | Case | Node v26.3.0 | oven-sh#43924 | This PR | |---|---|---|---| | `Bun.listen`, `requestCert`, `rejectUnauthorized: true`, `shutdown()` in the handshake, TLS 1.3, two reads | n/a | `handshake(false, null)`, then `data()` delivers the client's bytes, socket stays open | `handshake(true, authorized=false, error)`, close, no data | | Same, trusted client | n/a | `handshake(false, null)`, then `data()` with `authorized=false` | `handshake(true, authorized=true, null)`, then `data()` | | `tls.createServer`, `requestCert`, `rejectUnauthorized: false`, `end()` in the handshake, two reads | `secureConnection authorized=false`, then the data | `tlsClientError ECONNRESET` | same as Node | | Same, `rejectUnauthorized: true`, trusted client | `secureConnection authorized=true`, then the data | `tlsClientError ECONNRESET` | same as Node | | `Bun.connect`, `rejectUnauthorized: true`, `shutdown()` in `open`, peer never answers | n/a | `handshake(false, null)`, socket stays open | `handshake(false, null)`, close | | `tls.connect`, default `rejectUnauthorized`, `end()` in `'connect'`, peer never answers | `finish`, stays `readOnly` | same as Node | same as Node | | `getAuthorizationError()` on a half-closed socket before any handshake report | n/a | `null` | `UNABLE_TO_GET_ISSUER_CERT` | | `getAuthorizationError()` after `handshake(false, null)` on a half-closed socket | n/a | `null` | `null` | | `tls.connect` with the `session` of an earlier unauthorized connection, `end()` in `'connect'`, peer never answers | `finish`, no `secureConnect` | same as Node | same as Node | The tests of oven-sh#43924 release a held flight in one write (5cee17a), so they do not reach the two-read rows. **Mechanism** - `us_internal_ssl_on_data` ends with `ssl_retry_parked_write`, which calls `us_internal_ssl_on_writable`, which calls `ssl_update_handshake`. So the state machine runs between two reads of one flight. - On the base, `ssl_update_handshake` reports a failure when `us_internal_ssl_is_shut_down` is true, that is, for a sent FIN, a sent close_notify or a fatal error. The handshake state becomes `HANDSHAKE_COMPLETED`. The next read finishes the handshake inside `SSL_read`, and no second report follows. - The Rust `on_handshake` marks a failed handshake as `REJECTED`. Only the write paths read that flag, so `data()` still runs. **The two traps from the review of oven-sh#43924** - With no peer certificate the SSL answers `UNABLE_TO_GET_ISSUER_CERT`. `ssl_failed_handshake_verify_error` reads the SSL on a shut-down socket only when `us_cert_verify_cb` ran in this handshake (`ssl_peer_chain_checked`). So a handshake that failed after our FIN, with no certificate, still reports no error, and `net.ts` still reads it as its own close. On a socket that is not shut down the failure branch reads the SSL as before. - `SSL_get0_peer_certificates` is not that test. It is not NULL after an empty Certificate message. Before the ServerHello it returns the chain of the session that the client offered, so the first version of this PR reported `secureConnect` for a handshake that the peer never answered. - A failed handshake can report 0: the chain verified and the handshake failed later. `on_handshake` now closes a rejecting connection on `success == 0`, whatever the error value. **Where this differs from the request** - The close on a failed handshake does not apply to node:tls clients (`Flags::DEFERS_SERVER_IDENTITY`). With it, `tls.connect()` followed by `end()` in `'connect'` emitted `finish`, `end`, `close` at once. Node and the base keep that socket `readOnly` until the peer closes. `net.ts` closes node:tls sockets on the failures that node closes on. The new `end-strict` row in `node-tls-connect.test.ts` pins this. - It does not apply to server sockets. No flag tells a node:tls server socket from a `Bun.listen` one. `net.ts` closes a server socket whose handshake failed in a microtask. A failure that is reported inside a JS call (`us_socket_sni_resolve`) reached the native close first, and the socket never emitted `'close'`. The new test in `node-tls-server.test.ts` pins this. On a server a failed handshake with no error follows the server's own `shutdown()`, and its first flight never left, so that handshake cannot finish. A fatal error reports `EPROTO` and closes as before. - The `ssl_flush_write_batch` change is a separate PR, stacked on this one. It needs this one: without the flag, dropping the flight makes `node-tls-wrapped-socket-close.test.ts` fail 2 tests. **What does not change** - Every failed handshake on a socket that is not shut down reports the same pair as on the base. The three shapes of oven-sh#42181 (`end`, `destroySoon`, `server-end`) and `test-https-agent-create-connection.js` are unchanged. - `on_open`, `us_internal_ssl_close`, `us_socket_sni_resolve` and `us_socket_start_tls_handshake` pass 1 and keep the old rule. `us_internal_ssl_is_shut_down` itself is not touched. - `getAuthorizationError()` on an open socket reads the same sources in the same order. A handshake that failed with `EPROTO` still answers `EPROTO`. After a report, a shut-down socket answers what `on_handshake` stored. **Measurements** Base is the head of oven-sh#43924. Call counts are gdb breakpoint hit counts on debug builds with the debug info stripped. Sizes are from release builds of both trees. - Healthy handshake, 100 in-process `Bun.listen` / `Bun.connect` connections, on 771b423: `SSL_do_handshake` 600 and 600, verify reads 200 and 200, `us_cert_verify_cb` 100 and 100, `BIO_s_custom_write` 700 and 700, `bsd_send` 600 and 600, `bsd_recv` 600 and 600, `ssl_flush_write_batch` 300 and 300, `us_internal_ssl_is_shut_down` 1500 to 1400. - `us_cert_verify_cb` now looks up its socket for every chain, to set `ssl_peer_chain_checked`. On the base only a client with a valid chain did that lookup. So a server, and a client whose chain fails, pay 2 `ex_data` reads per checked chain. Every checked chain pays 1 store. - Release `.text`: 58154908 B both (`size -A`). Stripped `bun`: 80844320 B both. Symbols that changed: `ssl_trigger_handshake` 669 to 704 B, `ssl_update_handshake` 463 to 470 B, `us_cert_verify_cb` 269 to 351 B, `on_handshake` 3036 to 3083 B, `getAuthorizationError` 663 to 676 B. - Measured on 49f139d, the first commit: a half-closed server with the flight in two reads runs `SSL_do_handshake` 8 times, not 6, because the handshake now runs to its end. With the flight in one read: 6 and 6. `ssl_update_handshake` nesting depth: 1 in every run. `getAuthorizationError()`, 50 calls: healthy socket 52 and 52 verify reads, half-closed socket with no report 0 to 50. - Allocations: the change adds none. `strace` and `perf` are not installed on the test machine. **Tests** - `test/js/bun/net/socket.test.ts`, block "shutdown() while the handshake runs": 9 tests. The base fails 3: both two-read cells and the close of a rejecting client. The block is not concurrent: see the stacked PR. - `test/js/node/tls/node-tls-duplex-end-verify.test.ts`: 15 new tests: two-read cells, trusted controls, Duplex twins of both, and the offered session under TLS 1.2 and TLS 1.3. The base fails 3, all on a TCP socket with two reads. Node v26.3.0 passes 31 of 31 (`node --test`). - `test/js/node/tls/node-tls-server.test.ts`: 1 new test, the socket that calls `end()` while its `SNICallback` is pending. It passes on the base and failed on 49f139d. - `test/js/node/tls/node-tls-connect.test.ts`: 1 new row, `end-strict`. It passes on the base, on this change and on Node. - `test/js/node/tls/` and `test/js/bun/net/` together (717 tests), this change and the base side by side: no failure is only on this change. Failures on both: `SNICallback runs even when the requested servername matches the bind hostname` (`localhost` resolves to `::1` on the test machine), `should not call drain before handshake` (needs `www.example.com`), and 3 tests that wait for a garbage collection. - After the rebase on main (e375701) the diff of `src/` and `packages/` is the same, byte for byte. The two directories have 753 tests there. 6 fail, and each of them failed on a build without this change before: the 2 above, the 3 that wait for a garbage collection, and `root certificate initialization > concurrent Workers all see the same CA certificate lists`. - The vendored `test-tls-*` and `test-https-*` files: 250 pass. `test-tls-client-allow-partial-trust-chain.js` and `test-https-timeout.js` fail on the base too. With the stacked PR on top, `test-http2-*` (261) and `test-net-*` (150) pass as well. </details>
…apid reset, CVE-2025-8671 MadeYouReset) (oven-sh#36230) ### Problem - One connection that loops `HEADERS` + `RST_STREAM(CANCEL)` makes a `node:http2` server run the `'stream'` handler and serialize a response for all 20,000 reset streams, at 60-80% CPU. It never sends `GOAWAY`. Node closes that connection after about 1,400 resets (CVE-2023-44487). - The h2 engine (`src/runtime/api/bun/h2/connection.rs`) does not limit stream resets. `streamResetBurst` and `streamResetRate` have no effect. ### Fix - Server sessions get nghttp2's token bucket: 1000 tokens, 33 more per second, set by `streamResetBurst` / `streamResetRate`. An empty bucket sends `GOAWAY(ENHANCE_YOUR_CALM)`, and the session fails with `ERR_HTTP2_ERROR`. - A second, fixed bucket counts the resets that the engine sends itself (CVE-2025-8671, MadeYouReset). - A reset takes a token only when it cancels a live stream. After the server's own `GOAWAY`, resets of older streams are free, as in nghttp2. - Verified: `test/js/node/http2/h2-conformance.test.ts` (14 new tests, 8 fail on main), `node-http2.test.js`, node's 261 `test-http2-*.js`. ### Background - Rapid reset: a client cancels each request at once, so no stream limit applies while the handlers run. - MadeYouReset: an invalid frame makes the server reset the stream itself. - nghttp2 (node) charges each inbound `RST_STREAM` to a token bucket and sends `GOAWAY` when it is empty. ### Downsides - A connection that cancels more than 1000 live streams in a burst, then 33 per second, now fails with `ERR_HTTP2_ERROR`, as in node. The two options raise the limit. - About 1,000 cancelled requests per connection still run the handler and get a response serialized (1,133 measured). Node writes 0 responses, because it emits `'stream'` one tick later. - The `GOAWAY` code is `ENHANCE_YOUR_CALM` with debug text. Node sends `INTERNAL_ERROR` with none. <details><summary>What Node does, and where this PR differs</summary> Sources: nghttp2 v1.69.0 `lib/nghttp2_session.c` (the version in node v26.3.0), node v26.3.0 `src/node_http2.cc`, and `lib/internal/http2/util.js` as extracted from the node 26.3 binary. Measurements are against node v26.3.0. **The bucket.** `session_update_stream_reset_ratelim` returns early unless the session is a server that has not submitted a GOAWAY (`NGHTTP2_GOAWAY_SUBMITTED`). It then updates and drains `stream_reset_ratelim` (`NGHTTP2_DEFAULT_STREAM_RESET_BURST` 1000, `NGHTTP2_DEFAULT_STREAM_RESET_RATE` 33, whole-second timestamps). When the bucket is empty it calls `nghttp2_session_add_goaway(..., NGHTTP2_INTERNAL_ERROR, NULL, 0, ...)`. Its only caller is the last line of `nghttp2_session_on_rst_stream_received`, after `nghttp2_session_close_stream`. So every inbound `RST_STREAM` on a stream that is not idle is charged, also when the stream is already gone. **The options.** `updateOptionsBuffer` in `util.js` (verbatim, `optionsBuffer` is a `Uint32Array`): ```js if (typeof options.streamResetRate === 'number') { flags |= (1 << IDX_OPTIONS_STREAM_RESET_RATE); optionsBuffer[IDX_OPTIONS_STREAM_RESET_RATE] = MathMax(1, options.streamResetRate); } if (typeof options.streamResetBurst === 'number') { flags |= (1 << IDX_OPTIONS_STREAM_RESET_BURST); optionsBuffer[IDX_OPTIONS_STREAM_RESET_BURST] = MathMax(1, options.streamResetBurst); } ``` There is no validation: `-1` becomes 1, `33.5` becomes 33, a value that is not a number is ignored. `node_http2.cc` calls `nghttp2_option_set_stream_reset_rate_limit` only when both flags are set. **After its GOAWAY.** `nghttp2_session_on_request_headers_received` returns `NGHTTP2_ERR_IGN_HEADER_BLOCK` when `session_allow_incoming_new_stream()` is false (`NGHTTP2_GOAWAY_TERM_ON_SEND | NGHTTP2_GOAWAY_SENT`). The block is decoded for HPACK state, no stream is opened, no callback runs. Measured: 3,000 `HEADERS`+`RST_STREAM` pairs after node's GOAWAY give 0 handler runs and 0% CPU. **Resets nghttp2 sends itself.** nghttp2 answers a stream `WINDOW_UPDATE` with a 0 increment, a stream window overflow, and `DATA` on a half-closed (remote) stream with a connection error, not with `RST_STREAM`. `session_on_data_received_fail_fast` returns `NGHTTP2_ERR_IGN_PAYLOAD` for `DATA` on a stream that no longer exists: measured, node answers 1,200 late `DATA` frames with 0 `RST_STREAM`. nghttp2 1.67.0 added a separate `glitch_ratelim` (`session_update_glitch_ratelim`, 1000 / 33 in 1.67 and 1.68, 10000 / 330 in 1.69). It is charged for malformed header blocks, ignored header blocks, empty `DATA` without `END_STREAM`, `PRIORITY` and unknown frames. Node does not set it. Measured: with `maxSessionInvalidFrames: 5000` node answers 1,500 malformed header blocks with `RST_STREAM(PROTOCOL_ERROR)` and then serves the next request. **A request reset in the same read.** Node still runs the `'stream'` handler (its `test-http2-client-rststream-before-connect` depends on that). It emits the event from `process.nextTick` (`onSessionHeaders` in `lib/internal/http2/core.js`), after nghttp2 consumed the whole read. The stream is already reset by then, so nothing the handler writes reaches the wire: 10,000 pairs give about 1,700 handler runs and 0 response frames. | | node | this PR | |---|---|---| | bucket size and refill | 1000 burst / 33 per whole second, server only | same (`RateLimit`, `Connection::stream_reset_limit`) | | `streamResetBurst` / `streamResetRate` | per-key number check, `MathMax(1)`, uint32, applied only when both are given | same (`to_u32().max(1)`, both or neither, `http2.ts` is not touched). Values above 2^32 saturate, node wraps | | which inbound `RST_STREAM` is charged | every one, also for a stream that is already gone | **differs**: only one that closes a stream that is still open. Bun's own http2 client answers each late `DATA` frame on a cancelled stream with `RST_STREAM(STREAM_CLOSED)` (measured: 2,900 for 2,900 late frames, node sends 1). With node's rule one cancelled response with many small frames in flight drains the bucket of a Bun server. A frame for a closed stream cancels nothing | | after the server's GOAWAY | no reset is charged, and no new stream is opened | **differs**: resets of streams opened before the GOAWAY are not charged. This engine still opens streams after its GOAWAY (not changed here), so a reset of such a stream is charged. Each stream carries `opened_after_goaway`, because the engine also accepts a new id below the GOAWAY's last stream id. Without this a client sends `GOAWAY(NO_ERROR)`, holds one stream open and floods free of charge: 380,000 pairs in 5 s at 100% CPU on the previous head. The GOAWAY flag is asked per frame (`Sink::goaway_sent`, set by the parser's `send_go_away`), so a `close()` from inside a handler counts for the rest of that read | | GOAWAY on exhaustion | `INTERNAL_ERROR`, no debug data | **differs**: `ENHANCE_YOUR_CALM` + `"too many stream resets"`, the code and shape of this engine's other flood guard (`note_outbound_ack`). JS sees `ERR_HTTP2_ERROR` in both | | resets the server sends itself | connection errors for the MadeYouReset shapes, and the glitch bucket | **differs**: this engine answers those shapes with the RFC 9113 stream error, so a client can provoke resets. A second fixed bucket (`sent_reset_limit`, 1000 / 33) is charged in `send_rst_stream` when the reset cancels a request that the embedder already has (`recv_final_headers`, state not `Closed`). Not charged: late `DATA` for a stream the server closed (a rejected upload), frames queued behind a reset, and header blocks refused before dispatch, which `maxSessionInvalidFrames` and `maxSessionRejectedStreams` bound as on main | | request reset in the same read | handler runs one tick later on a reset stream, 0 responses | **differs**: Bun emits `'stream'` from the HEADERS dispatch, before the `RST_STREAM` is parsed, so the response is serialized. This PR keeps that order and the bucket bounds it: 10,000 pairs give 1,133 handler runs and responses, then the GOAWAY (main: 10,000 of both) | A dry bucket sets a flag. `receive()` tears the session down between frames, so the frame that emptied the bucket finishes its own dispatch first. </details> <details><summary>Notes</summary> **Tests.** `stream-reset floods` block in `test/js/node/http2/h2-conformance.test.ts`, 14 tests. On bun 1.4.2 eight fail: the RST_STREAM flood, `streamResetBurst`, the refill, the three server-sent-reset shapes, resets of streams opened after the GOAWAY, and server-sent resets after the GOAWAY. The other six pass on main by design. Each is pinned by a mutation that I built and ran. Each run failed exactly the test named (the refill mutations are from the previous round, that code did not change): * `recv_final_headers` clause removed from `send_rst_stream`: "a header block refused before dispatch is not charged" fails * `state != Closed` clause removed from `send_rst_stream`: "a stream error is charged once" fails * the previous head, which charged every server-sent reset: "late DATA for a stream the server already closed is not charged" fails * `state != Closed` clause removed from `handle_rst_stream`: "RST_STREAM frames for a stream that is already closed are not charged" fails * GOAWAY exemption removed: "resets are not charged once the server has sent its own GOAWAY" fails * `opened_after_goaway` clause removed, or replaced by a comparison with the GOAWAY's last stream id: "resets of streams opened after the server's GOAWAY are charged" fails (its flood uses ids below the held stream) * GOAWAY exemption applied to server-sent resets: "server-sent resets stay charged after the server has sent its GOAWAY" fails * window-overflow site closes the stream before `send_rst_stream`: the "WINDOW_UPDATE past 2^31-1" flood fails * refill block removed, or `last_refill +=` removed: "the bucket refills" fails. That test uses `streamResetBurst: 0`, so it also fails without the floor to 1. It waits 1.5 s of wall clock on purpose, because the refill is per whole second. Also passing: the rest of `h2-conformance.test.ts` (84 in total), `node-http2.test.js` (390), seven other test files in `test/js/node/http2/`, and node's 261 `test-http2-*.js`. **Measurements** (release build of an earlier head, the flood path is the same): the flooding connection is closed after 28 ms and a fresh request is served 1-2 ms later, for floods of 1, 3 and 10 s. bun 1.4.2 never closes it and is unreachable for 20-31 s. Node closes after 88 ms. **Seen on main, not changed here.** * The server opens streams after its own GOAWAY. `streamStart` allocates a `ServerHttp2Stream` and counts it, `streamHeaders` drops it because the session is closed, and nothing answers or resets it. A client that opens one stream after the GOAWAY keeps `session.close()` from ever finishing. Node ignores such streams and closes. * The http2 client sends one `RST_STREAM(STREAM_CLOSED)` per late `DATA` frame after it cancels a request. nghttp2 servers charge each of them. * The engine accepts a new client stream id that is lower than an earlier one (RFC 9113 5.1.1 asks for a connection error). The branch is 55a6599 (the change, on main 87466cf), dc32b9d (makes `ResetBy` `Copy` for clippy's `needless_pass_by_value`), and merges of main up to a0a71e2. </details> <!-- robobun:evidence:begin --> --- **[human-review]** gate passed · iteration 11 · 3 files touched <details><summary>fails on main (without fix)</summary> ```console ASAN without fix: 9 FAILED $ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/pr_gate.xml" "test/js/node/http2/h2-conformance.test.ts" bun test v1.4.3 (367d939) test/js/node/http2/h2-conformance.test.ts: (pass) connection preface & SETTINGS handshake (checklist §1) > server sends a SETTINGS frame first (§1.4) [387.56ms] (pass) connection preface & SETTINGS handshake (checklist §1) > server ACKs the client's SETTINGS frame (§3.5) [118.99ms] (pass) connection preface & SETTINGS handshake (checklist §1) > a SETTINGS frame with a non-zero stream id is a PROTOCOL_ERROR (§3.5) [84.79ms] (pass) connection preface & SETTINGS handshake (checklist §1) > a SETTINGS frame whose length is not a multiple of 6 is a FRAME_SIZE_ERROR (§3.5) [43.35ms] (pass) connection preface & SETTINGS handshake (checklist §1) > a SETTINGS ACK that carries a payload is a FRAME_SIZE_ERROR (§3.5) [83.46ms] (pass) PING (checklist §3.7) > server replies to PING with a PING ACK echoing the payload [38.88ms] (pass) PING (checklist §3.7) > a PING with length != 8 is a FRAME_SIZE_ERROR [38.89ms] (pass) PING (checklist §3.7) > a PING on a non-zero str ... (truncated) release without fix: 8 FAILED bun test v1.4.3-canary.1 (367d939) test/js/node/http2/h2-conformance.test.ts: (pass) connection preface & SETTINGS handshake (checklist §1) > server sends a SETTINGS frame first (§1.4) [6.61ms] (pass) connection preface & SETTINGS handshake (checklist §1) > server ACKs the client's SETTINGS frame (§3.5) [1.92ms] (pass) connection preface & SETTINGS handshake (checklist §1) > a SETTINGS frame with a non-zero stream id is a PROTOCOL_ERROR (§3.5) [1.59ms] (pass) connection preface & SETTINGS handshake (checklist §1) > a SETTINGS frame whose length is not a multiple of 6 is a FRAME_SIZE_ERROR (§3.5) [0.86ms] (pass) connection preface & SETTINGS handshake (checklist §1) > a SETTINGS ACK that carries a payload is a FRAME_SIZE_ERROR (§3.5) [0.73ms] (pass) PING (checklist §3.7) > server replies to PING with a PING ACK echoing the payload [0.74ms] (pass) PING (checklist §3.7) > a PING with length != 8 is a FRAME_SIZE_ERROR [0.75ms] (pass) PING (checklist §3.7) > a PING on a non-zero stream id is a PROTOCOL_ERROR [0.60ms] (pass) WINDOW_UPDATE (checklist §6) > a connection-level WINDOW_UPDATE with a 0 increment is a PROTOCOL_ERROR [0.69ms] (pass) WINDOW_UPDATE ... (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/node/http2/h2-conformance.test.ts" bun test v1.4.3 (367d939) test/js/node/http2/h2-conformance.test.ts: (pass) connection preface & SETTINGS handshake (checklist §1) > server sends a SETTINGS frame first (§1.4) [845.40ms] (pass) connection preface & SETTINGS handshake (checklist §1) > server ACKs the client's SETTINGS frame (§3.5) [263.62ms] (pass) connection preface & SETTINGS handshake (checklist §1) > a SETTINGS frame with a non-zero stream id is a PROTOCOL_ERROR (§3.5) [214.04ms] (pass) connection preface & SETTINGS handshake (checklist §1) > a SETTINGS frame whose length is not a multiple of 6 is a FRAME_SIZE_ERROR (§3.5) [100.75ms] (pass) connection preface & SETTINGS handshake (checklist §1) > a SETTINGS ACK that carries a payload is a FRAME_SIZE_ERROR (§3.5) [132.76ms] (pass) PING (checklist §3.7) > server replies to PING with a PING ACK echoing the payload [164.67ms] (pass) PING (checklist §3.7) > a PING with length != 8 is a FRAME_SIZE_ERROR [114.15ms] (pass) PING (checklist §3.7) > a PING on a non-zer ... (truncated) release with fix: all passed $ bun scripts/build.ts --profile=release [configured] bun-profile → bun (stripped) target linux-x64-gnu build type Release build dir ./build/release revision a402383 features lto, baseline 23 deps, 136 codegen, 1176 objects in 960ms 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) [34.00ms] [4/1499] install /workspace/bun/packages/bun-error bun install v1.4.3-canary.1 (367d939) Checked 1 install across 2 packages (no changes) [2.00ms] [5/1499] gen bake.{client,server,error}.js -> bake.client.js, bake.server.js, bake.error.js [6/1499] install /workspace/bun/src/node-fallbacks bun install v1.4.3-canary.1 (367d939) Checked 111 installs across ... (truncated) ``` </details> <details><summary>diff hotspot</summary> ``` src/runtime/api/bun/h2/connection.rs | 138 ++++++++++++++++- src/runtime/api/bun/h2_frame_parser.rs | 24 +++ test/js/node/http2/h2-conformance.test.ts | 240 ++++++++++++++++++++++++++++++ 3 files changed, 398 insertions(+), 4 deletions(-) ``` </details> **gate history** · 15 passed · 0 rejected · iteration 11 <details><summary>evidence per changed file</summary> ``` file reads edits tests src/runtime/api/bun/h2/connection.rs 49 78 122 src/runtime/api/bun/h2_frame_parser.rs 48 41 122 test/js/node/http2/h2-conformance.test.ts 19 26 121 ``` </details> <!-- robobun:evidence:end --> --------- Co-authored-by: Ciro Spaciari <[email protected]>
…ds (oven-sh#44014) ### What does this PR do? Fixes oven-sh#43969. A handler that calls `response.text()` on a `fetch()` Response, does not await it, and returns that Response crashes the process with a stack overflow. The server now calls `error()` with `ERR_BODY_ALREADY_USED`, the same as for `await response.text()`. **Cause.** The upstream body has not arrived, so the body is `Locked` with no stream. `text()` sets `promise` on it. 1. `do_render_with_body` finds no stream and sees `lock.task` (the fetch task). 2. It calls `to_readable_stream` and expects that call to store a stream on the body. 3. `to_readable_stream` sees the promise. It returns a locked stand-in stream and stores nothing. 4. `do_render_with_body` drops the return value and calls itself with the same body. Go to 1. **Fix.** `PendingValue::has_consumer()` is the one rule for "somebody already reads this pending body". A body with a consumer belongs to that consumer: - `do_render_with_body` refuses it. - `cancel_unread_body` and `release_body_stream` leave it alone. Before, they set it to `Used` and dropped the promise. - `Bun.write()` rejects it. Before, it replaced the consumer. - `clone()`, `bodyUsed` and `to_readable_stream` ask the same helper. Pending `fetch()` Response with `response.text()` not awaited: | Then | Before | After | | --- | --- | --- | | returned for GET | crash | `error()`, 500 | | returned for HEAD | 200, `text()` never settles | 200, `text()` resolves | | `Bun.write(path, response)` | `text()` never settles | write rejects, `text()` resolves | ### How did you verify your code works? - 3 new tests: 2 in `serve-reused-response.test.ts`, 1 in `bun-write.test.js`. All fail with `USE_SYSTEM_BUN=1 bun test` and pass with `bun bd test` (macOS arm64). - These pass on the debug build: `serve-pending-promise-abort-leak`, `bun-server`, `serve-body-leak`, `body`, `body-stream`, `body-clone`, `response`, `html-rewriter`. - Not verified locally: 204/304 and client abort. They use the same `cancel_unread_body`.
…h#44012) Part of oven-sh#22559 Behaviour change: none ### Problem - `Address`, the listen target of `Bun.serve`, has two variants. Most of its readers cannot take a third one. Four end in `unreachable!()` (`ServerConfig.rs:666`, `:675`, `:1385`, `server_body.rs:2581`). Seven more use `if let` or `matches!`. - A new variant compiles at those sites and then panics or takes the wrong branch at run time. oven-sh#44013 adds one for `Bun.serve({ fd })`. ### Fix - `ServerConfig::from_js` keeps the port, the hostname and the unix path in locals and builds `Address` in one place. - `Address::is_unix()` replaces the `matches!` readers. The `if let` readers become exhaustive matches. No `unreachable!()` arm on `Address` is left. - `HttpContext::listen` and `listen_unix` share `tcpListenOptions` and `unrefListenSocket`. This PR deletes `uws_app_listen`, which has no caller. - Verified: the `serve-listen`, `bun-serve-args`, `serve-http3`, `node-http`, `hot` and `bake/dev/esm` tests pass. `serve.test.ts` fails the same 2 tests as main (Notes). ### Background - `ServerConfig::from_js` parses the options of `Bun.serve()` and `server.reload()`. - `requestIP`, `timeout` and the `/bun:info` route read the variant on each call. - Weighed: add the new arm at each reader in the feature PR. A reader that the PR misses still compiles with `if let` or `matches!`. With an exhaustive match the compiler finds it. ### Downsides - Release text grows by 512 B. `ServerConfig::from_js` goes from 16,314 to 16,587 B. - None found at run time. `requestIP`, `timeout` and `is_allowed_host_header` have the same instructions as on main. 60 inputs to `http.listen` and `Bun.serve` give the same outcome. <details><summary>Notes</summary> - Builds compared: release, Linux x64, merge base `c86bd18736`. `size` text 80,829,494 to 80,830,006 B. The `bun` file is 80,995,912 B in both. - `on_bun_info_request` differs from main in two constants, which are offsets of the same strings. Every other instruction is the same. - The release binary of main has no `uws_app_listen` symbol: the linker already drops it. The deletion removes source only. The function has no Rust declaration. - `tcpListenOptions` is the one place that adds `LIBUS_LISTEN_DEFER_ACCEPT`. oven-sh#36074 removes that flag for node:http. - The 60 inputs are 47 forms of `http.Server.listen` (no arguments, port, path, host, options objects, `fd: undefined`, handles, bad ports) and 13 forms of `Bun.serve` (`port`, `hostname`, `host`, `unix`, `unix` with `port`, `hostname` with `unix`, `reusePort`, `ipv6Only`, unknown keys). Each one ran on the build of main and on the build of this PR. - The last commit adds three assertions to `bun-serve-args.test.ts`. They read the messages of the errors for `unix` with `hostname` and for a unix socket with only HTTP/3. They pass on main and on this PR. - `serve.test.ts` has two failures in my container, on main and on this PR: `should use correct error when using a root range port(oven-sh#7187)` (the container runs as root) and `only serves /bun:info to loopback clients in development mode`. </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/bun/http/bun-serve-args.test.ts <!-- robobun:evidence:end -->
… has its value from the start (oven-sh#42471) ### Problem - `const { v } = require("./b.js")` copies `v` when the pattern runs. Since oven-sh#41186 (1.4.1) the bundler binds the local to the export when nothing assigns the export, so each later read is live. A `require()` can run while `b.js` still initializes. Then the copy is `undefined`, but the bundle reads `"V"`. 1.4.0 prints `undefined`. - Cause: `binds_call_item` (`src/bundler/LinkerContext.rs:4329`) refuses only an export that `has_been_assigned_to()`. The initializer of `export var v = f()` is not an assignment, and it runs after the pattern when the importee reaches the pattern while it initializes. - oven-sh#42447 finds the import cycles that make this happen. An importee can also reach the pattern through a callback (oven-sh#42449). No import graph shows that path. This PR replaces oven-sh#42447. ### Fix - A `require()` pattern local is bound only to an export that has its value before the importee initializes: a function declaration, or a namespace object. The bundle prints both outside the `__esm` wrapper. A re-export of an external module's binding is never bound (from oven-sh#42447). - Any other export reads through the namespace object when the pattern runs, as in 1.4.0: `const { v } = (init_b(), __toCommonJS(exports_b))`. That object lists only the names the pattern reads, so unused exports are still dropped. - This retires part of oven-sh#41186 on purpose: the elision for a `require()` pattern of a `var`, `let`, `const` or `class` export. `import()` locals stay bound. Its promise settles after the importee initialized. - Verified: `test/bundler/bundler_dynamic_import_dce.test.ts` (328 tests, 54 new, 37 of them fail on 1.4.3). Also 12 other bundler suites (list in Notes). ### Background - A wrapped ES module is `var init_b = __esm(() => { ... })`. The first `init_b()` runs the body. A nested call during that run returns at once. Function declarations and the namespace object `exports_b` are printed before the wrapper. - The namespace object has a getter for each export. A pattern that reads it copies the current value. - To bind a local, the linker merges its symbol with the export's symbol. The pattern prints as `init_b();` and each read prints the export. That is a live read. <details><summary>Notes</summary> Repro from the issue. `bun run entry.js`, 1.4.0 and this branch print `undefined`. 1.4.1, 1.4.2, 1.4.3 and main print `V`. ```js // entry.js import { register } from "./registry.js"; import { early, late } from "./a.js"; register(early); require("./b.js"); console.log(late()); // registry.js let callback; export function register(fn) { callback = fn; } export function fire() { callback(); } // a.js let get; export function early() { const { v } = require("./b.js"); get = () => v; } export function late() { return get(); } // b.js import { fire } from "./registry.js"; fire(); export var v = String("V"); ``` Relation to oven-sh#42447. That PR keeps the binding for a `require()` outside an import cycle and finds cycles with a search over the import records. This rule does not need the search: it treats every `require()` the same, because a callback can make any `require()` run during the initializer. The cycle tests of oven-sh#42447 are ported here. `RequireOfAnotherCycle` now keeps the namespace object. Its `Kind::Import` guard for an external re-export is ported too, with its test: without the guard, `ExternalReExportDestructureIsSnapshot_esm` prints `2 1` on this branch. Cost, measured minified with `--target=bun`. A file with one `require()` pattern of a `const` export: 268 bytes on 1.4.3, 851 bytes here (1.4.0 prints the same shape). The difference is the `__export`, `__toCommonJS` and `__defProp` helpers, once per bundle. A second such pattern adds 22 bytes. Each run of a pattern reads a getter instead of a variable. Tree shaking of the importee is not affected: the object lists only the names the pattern reads. `import()` patterns, which oven-sh#41186 was written for, are unchanged. Follow-up, not in this PR. The other direction from oven-sh#42449 keeps the binding and prints a copy where the pattern runs (`init_b(); const v2 = v;`). That needs a symbol state the linker records without a merge, and printer changes for the pattern, the local statement, and the hoisting of top-level locals out of a wrapper. It restores the elision for `require()` if that matters. Test changes. `ElideInitThrows`, `ElideWrappedImporter` and the class case of `ElideWrappedImporterBoundClass` (now `ElideWrappedImporterClassIsCopy`) keep their `const` and `class` exports and now expect the namespace object. `ElideWrappedImporterBoundFunction` and `ElideWrappedImporterDoesNotRedeclareBoundName` are the same shapes with a function export, which is still bound. `ElideRequireDuringInit*` are the callback shapes from the issue. `ElideImportDuringInitThroughCallbackStaysBound` guards `import()`. Other suites that pass: `esbuild/default`, `esbuild/dce`, `esbuild/importstar`, `esbuild/importstar_ts`, `bundler_edgecase`, `bundler_cjs`, `bundler_cjs2esm`, `bundler_regressions`, `bundler_barrel`, `bundler_splitting`, `bundler_minify`, `bundler_promiseall_deadcode`, and `test/regression/issue/cyclic-imports-async-bundler.test.js`. Self-reviewed: 3 changes asked for, 3 made. They are the external re-export guard with its test, the ported cycle tests, and the original forms of the three adjusted tests kept next to the function variants. </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: 37 FAILED $ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/pr_gate.xml" test/bundler/bundler_dynamic_import_dce.test.ts bun test v1.4.3 (6a92015) test/bundler/bundler_dynamic_import_dce.test.ts: (pass) bundler > dynamic_import_dce/AwaitDestructure [1148.86ms] (pass) bundler > dynamic_import_dce/AwaitDestructureAlias [530.45ms] (pass) bundler > dynamic_import_dce/AwaitDot [600.55ms] (pass) bundler > dynamic_import_dce/AwaitIndex [555.72ms] (pass) bundler > dynamic_import_dce/LetBinding [579.90ms] (pass) bundler > dynamic_import_dce/TwoSitesUnion [581.74ms] (pass) bundler > dynamic_import_dce/BailoutRest [668.62ms] (pass) bundler > dynamic_import_dce/BailoutDefault [854.17ms] (pass) bundler > dynamic_import_dce/BailoutComputed [650.63ms] (pass) bundler > dynamic_import_dce/SplittingNarrowedExports [622.19ms] (pass) bundler > dynamic_import_dce/SplittingTwoImportersUnion [918.75ms] (pass) bundler > dynamic_import_dce/SplittingEscapeKeepsAll [617.29ms] (pass) bundler > dynamic_import_dce/SplittingAwaitDot [543.06ms] (pass) bundler > dynamic_import_dce/SplittingThenDestructure [582.49ms] (pass) bundler > dyna ... (truncated) release without fix: 37 FAILED bun test v1.4.3-canary.1 (6a92015) test/bundler/bundler_dynamic_import_dce.test.ts: (pass) bundler > dynamic_import_dce/AwaitDestructure [34.56ms] (pass) bundler > dynamic_import_dce/AwaitDestructureAlias [19.14ms] (pass) bundler > dynamic_import_dce/AwaitDot [25.20ms] (pass) bundler > dynamic_import_dce/AwaitIndex [19.40ms] (pass) bundler > dynamic_import_dce/LetBinding [13.13ms] (pass) bundler > dynamic_import_dce/TwoSitesUnion [21.14ms] (pass) bundler > dynamic_import_dce/BailoutRest [61.83ms] (pass) bundler > dynamic_import_dce/BailoutDefault [22.37ms] (pass) bundler > dynamic_import_dce/BailoutComputed [22.90ms] (pass) bundler > dynamic_import_dce/SplittingNarrowedExports [21.37ms] (pass) bundler > dynamic_import_dce/SplittingTwoImportersUnion [38.20ms] (pass) bundler > dynamic_import_dce/SplittingEscapeKeepsAll [30.68ms] (pass) bundler > dynamic_import_dce/SplittingAwaitDot [27.77ms] (pass) bundler > dynamic_import_dce/SplittingThenDestructure [25.14ms] (pass) bundler > dynamic_import_dce/SplittingPromiseAllDestructure [27.85ms] (pass) bundler > dynamic_import_dce/SplittingPromiseAllThenDestructure [23.31ms] (pass) bundler > dynamic_import_dce/SplittingProm ... (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/bundler/bundler_dynamic_import_dce.test.ts bun test v1.4.3 (6a92015) test/bundler/bundler_dynamic_import_dce.test.ts: (pass) bundler > dynamic_import_dce/AwaitDestructure [1382.02ms] (pass) bundler > dynamic_import_dce/AwaitDestructureAlias [914.33ms] (pass) bundler > dynamic_import_dce/AwaitDot [575.03ms] (pass) bundler > dynamic_import_dce/AwaitIndex [575.13ms] (pass) bundler > dynamic_import_dce/LetBinding [570.68ms] (pass) bundler > dynamic_import_dce/TwoSitesUnion [627.64ms] (pass) bundler > dynamic_import_dce/BailoutRest [647.56ms] (pass) bundler > dynamic_import_dce/BailoutDefault [621.54ms] (pass) bundler > dynamic_import_dce/BailoutComputed [696.97ms] (pass) bundler > dynamic_import_dce/SplittingNarrowedExports [613.14ms] (pass) bundler > dynamic_import_dce/SplittingTwoImportersUnion [1114.32ms] (pass) bundler > dynamic_import_dce/SplittingEscapeKeepsAll [733.44ms] (pass) bundler > dynamic_import_dce/SplittingAwaitDot [658.49ms] (pass) bundler > dynamic_import_dce/SplittingThenDestructure [678.30ms] (pass) bundler > dyn ... (truncated) release with fix: all passed $ bun scripts/build.ts --profile=release [configured] bun-profile → bun (stripped) in 834ms (unchanged) ninja: Entering directory `/workspace/bun/build/release' [1/139] gen JS modules (bundle-modules) Preprocess modules (10951ms) Bundle modules (65ms) Postprocesss modules (1007ms) Bundle Functions (771ms) Generate Code (55ms) [12.86s] Bundled "src/js" for production 2600 kb 197 internal modules 13 native modules 50 internal functions across 16 files [1/139] cargo bun_runtime → libbun_runtime.a �[1m�[92m Compiling�[0m bun_output_tags v0.0.0 (/workspace/bun/src/bun_output_tags) �[1m�[92m Compiling�[0m bun_core v0.0.0 (/workspace/bun/src/bun_core) �[1m�[92m Compiling�[0m bun_dispatch v0.0.0 (/workspace/bun/src/dispatch) �[1m�[92m Compiling�[0m bun_opaque v0.0.0 (/workspace/bun/src/opaque) �[1m�[92m Compiling�[0m bun_wyhash v0.0.0 (/workspace/bun/src/wyhash) �[1m�[92m Compiling�[0m bun_highway v0.0.0 (/workspace/bun/src/highway) �[1m�[92m Compiling�[0m bun_simdutf_sys v0.0.0 (/workspace/bun/src/simdutf_sys) �[1m�[92m Compiling�[0m bun_core_macros v0.0.0 (/workspace/bun/src/bun_core_macros) �[1m�[92m Compiling�[0m bun_mimalloc_sys v0.0.0 (/ ... (truncated) ``` </details> <details><summary>diff hotspot</summary> ``` src/bundler/LinkerContext.rs | 41 ++- test/bundler/bundler_dynamic_import_dce.test.ts | 385 +++++++++++++++++++++++- 2 files changed, 413 insertions(+), 13 deletions(-) ``` </details> **gate history** · 1 passed · 0 rejected · iteration 0 <details><summary>evidence per changed file</summary> ``` file reads edits tests src/bundler/LinkerContext.rs 4 8 17 test/bundler/bundler_dynamic_import_dce.test.ts 2 11 17 ``` </details> **root cause** · written by the author bot `binds_call_item` in `src/bundler/LinkerContext.rs` bound the local of a destructured `require()` pattern to the export whenever nothing assigned that export, but a `require()` can run while the importee is still initializing (for example through a callback, which no import path reveals), so the bound local read the later initialized value instead of the `undefined` that a plain copy would hold. The fix restricts that binding to exports that already have their value before initialization completes, namely function declarations and ESM namespace references, and treats every other `require()`… <!-- robobun:evidence:end -->
…43158) Fixes oven-sh#35345 ### Problem - `bun test --coverage` counts only the last load of a file loaded more than once. With the host and one `Bun.ModuleGraph`, the host's lines show as uncovered (`100.00 | 60.00 | 4-5`). With two graphs the file has no row. Without a graph, `import("./lib.ts?a")` then `?b` miscounts too, and two overlapping `import()`s drop the file. - `ByteRangeMapping__generate` (`src/sourcemap_jsc/CodeCoverage.rs`) keeps one JSC SourceID per source URL, and each load replaces it. A second graph shares the first graph's compiled code, so nothing runs under the recorded SourceID. - A CommonJS module in a graph has no row. Its wrapper, `GraphCommonJSSourceProvider`, has its own SourceID. ### Fix - `ByteRangeMapping` keeps every SourceID that carried the same text. `Report::generate` collects the blocks of each SourceID, keeps one per byte range (executed if any load executed it), and maps lines once. - A different text still replaces the entry. The line table and the source map describe one text. - The CommonJS wrapper records its SourceID too, if its text is the recorded one. `bun:jsc` `codeCoverageForFile()` now calls `Report::generate`. - Verified: `test/cli/test/coverage.test.ts` (13 new tests, 11 fail on main's `src/`). Also `parallel.test.ts` and `module-graph.test.ts`. Self-reviewed: 3 changes requested, 3 made (Notes). ### Background - JSC's control flow profiler records executed basic blocks per `SourceProvider`, keyed by SourceID. Bun makes a new one for each load of a file. - `ByteRangeMapping` is the coverage record of one file: the line table of its transpiled text and its SourceIDs. - `Bun.ModuleGraph` (oven-sh#42590) loads another instance of an app in one process. Graphs with the same `globals` names share compiled code. <details><summary>Notes</summary> Rows for the subject file, debug build of main's `src/` against this branch: | case | main | this branch | | --- | --- | --- | | host + one graph | `100.00 \| 60.00 \| 4-5` | `100.00 \| 100.00 \|` | | two graphs | no row | `100.00 \| 100.00 \|` | | CommonJS, host + one graph | no row | `100.00 \| 100.00 \|` | | CommonJS, one graph alone | no row | `100.00 \| 80.00 \| 4` (equal to the host alone) | | `?a` then `?b` | `100.00 \| 80.00 \| 3` | `100.00 \| 100.00 \|` | | `require.cache` delete, `require` again | `100.00 \| 80.00 \| 3` | `100.00 \| 100.00 \|` | | file text changes between two loads | last text alone | last text alone | - `--isolate` and `--parallel` workers reuse one `SourceProvider` for a file the module loader transpiles (`IsolatedModuleCache`), so those files were not affected there. A plugin's `onLoad` result is not cached that way: it gets a new `SourceProvider` for every load. The repro of oven-sh#40386 (closed as fixed in 1.4.0) still gives `28.57 | 3-7` under `--isolate` and `--parallel=1` on 1.4.3-canary c6b7fcb, and `100.00 | 100.00` on this branch. One of the new tests covers it. - Two overlapping loads, `Promise.all([import("./m.ts"), import("./m.ts")])`, leave `m.ts` with no row on 1.4.3-canary c6b7fcb. JSC keeps one module record, and the SourceID on record was the other one. This branch prints `100.00 | 100.00`. - Not in this PR: code that runs in a `Worker` is not counted, before or after (oven-sh#43275). A worker has a VM and a coverage map of its own, and only the main thread's map is reported. - The two host-only rows also fail on the 1.4.3 canary that predates `Bun.ModuleGraph`. The repro of oven-sh#35345 gives its `FNF:2 FNH:1 DA:3,0 DA:4,0` there, and `FNF:2 FNH:2` with every line hit on this branch. - Same text is decided by a wyhash of the transpiled text. On a match the line table is not built again. - The result is what JSC records when the loads share one SourceID, which is the `--isolate` case. A function is unexecuted only if no load ran it, so its blank lines do not become uncovered lines (oven-sh#39930). - A SourceID with no recorded blocks (a graph that shares another graph's executable, or the provider a CommonJS wrapper wraps) costs one lookup at report time and adds nothing. - Report time does not grow by one line mapping pass per load. Debug build, 200 graphs that each load one 9 KB CommonJS file with 100 functions: the time from the end of the tests to process exit is 4.7 s, of which the line mapping is 11 ms. With one report per SourceID it was 24.2 s. The rest is JSC returning the blocks of each SourceID. - `module._compile(text, filename)` in a graph also runs under the CommonJS wrapper, with a text of its own. `ByteRangeMapping__addSourceID` compares the wrapper's text hash with the one on record, so that text does not count as a load of `filename`. Without the check, it changed the row of a loaded `subject.cjs` from `80.00 | 3` to `100.00 | 100.00`. One of the two tests that pass on main covers this. The other covers the changed text. - An allocation failure while a report is built now ends in `bun_core::handle_oom`, like the other allocations in the file. Before, the file was left out of the report. - The tests load every case in one `bun test --coverage` run, plus one control run for the three cases that compare against a single load, plus one `--isolate` run for the plugin case. That is 3 spawned processes. - Self-review, the 3 requested changes: link oven-sh#35345 and oven-sh#40386 and correct the note on `--isolate`, add tests for overlapping `import()`s, the plugin case and the lcov output of oven-sh#35345, and state the `Worker` limit with a tracker (oven-sh#43275). - Windows x64 debug build: the 13 new tests pass. Two older tests in the same file (`--parallel merges ...`) fail there, also on main's `src/`: the `--parallel` worker prints `ASSERTION FAILED: currentThreadIsHoldingAPILock()` from `run_as_worker` into stderr. Release builds do not assert. This PR does not touch that code. - `codeCoverageForFile()` keeps its results: the row text, `[]` when nothing of the file is compiled, and `No source for file`. Deleted because this PR makes them dead: `sourceIDForSourceURL`, `ByteRangeMapping__getSourceID`, the C export of `ByteRangeMapping__find`, the block collection copy in `BunJSCModule.h`, and the `ignoreSourceMap` pass-through of `CodeCoverage__withBlocksAndFunctions`. - `module-graph.test.ts` on a debug build: 6 tests time out at 5 s on this branch and 7 on main's `src/` (`dynamicImport: *`, the Worker test, the memory test). The `dynamicImport` fixture takes 7.2 s under debug and prints the right values. No assertion fails. </details> <!-- robobun:evidence:begin --> --- **[human-review]** gate passed · iteration 0 · 7 files touched <details><summary>fails on main (without fix)</summary> ```console ASAN without fix: 11 FAILED $ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/pr_gate.xml" test/cli/test/coverage.test.ts bun test v1.4.3 (c6b7fcb) test/cli/test/coverage.test.ts: bun test v1.4.3 (c6b7fcb) demo.test.ts: --------------|---------|---------|------------------- File | % Funcs | % Lines | Uncovered Line #s --------------|---------|---------|------------------- All files | 0.00 | 66.67 | demo.test.ts | 0.00 | 66.67 | 1 --------------|---------|---------|------------------- 0 pass 0 fail Ran 0 tests across 1 file. [432.00ms] (pass) coverage crash [608.36ms] bun test v1.4.3 (c6b7fcb) demo2.ts: 0 pass 0 fail Ran 0 tests across 1 file. [1.76s] (pass) lcov coverage reporter [2034.85ms] (pass) coverage excludes node_modules directory [369.23ms] (pass) coveragePathIgnorePatterns - single pattern string [1942.18ms] (pass) coveragePathIgnorePatterns - partial coverage without nan [975.60ms] (pass) coveragePathIgnorePatterns - array of patterns [762.24ms] (pass) coveragePathIgnorePatterns - glob patterns [1157.39ms] (pass) coveragePathIgnorePatterns - lcov reporter [826.98ms] (pass) cov ... (truncated) release without fix: 1 FAILED bun test v1.4.3-canary.1 (c6b7fcb) test/cli/test/coverage.test.ts: bun test v1.4.3-canary.1 (c6b7fcb) demo.test.ts: 0 pass 0 fail Ran 0 tests across 1 file. [7.00ms] (pass) coverage crash [19.03ms] bun test v1.4.3-canary.1 (c6b7fcb) demo2.ts: 0 pass 0 fail Ran 0 tests across 1 file. [13.00ms] (pass) lcov coverage reporter [22.48ms] (pass) coverage excludes node_modules directory [24.65ms] (pass) coveragePathIgnorePatterns - single pattern string [26.13ms] (pass) coveragePathIgnorePatterns - partial coverage without nan [24.27ms] (pass) coveragePathIgnorePatterns - array of patterns [73.36ms] (pass) coveragePathIgnorePatterns - glob patterns [24.25ms] (pass) coveragePathIgnorePatterns - lcov reporter [28.16ms] (pass) coveragePathIgnorePatterns - invalid config type [8.71ms] (pass) coveragePathIgnorePatterns - invalid array item [6.41ms] (pass) coveragePathIgnorePatterns - empty array [29.96ms] (pass) coveragePathIgnorePatterns - ignore all files [22.80ms] (pass) --parallel merges line coverage across workers [313.04ms] (pass) --parallel merges function coverage across workers [543.98ms] 917 | cwd: String(dir), 918 | stdout: "pipe", 919 | ... (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/cli/test/coverage.test.ts bun test v1.4.3 (c6b7fcb) test/cli/test/coverage.test.ts: bun test v1.4.3 (c6b7fcb) demo.test.ts: --------------|---------|---------|------------------- File | % Funcs | % Lines | Uncovered Line #s --------------|---------|---------|------------------- All files | 0.00 | 66.67 | demo.test.ts | 0.00 | 66.67 | 1 --------------|---------|---------|------------------- 0 pass 0 fail Ran 0 tests across 1 file. [295.00ms] (pass) coverage crash [392.35ms] bun test v1.4.3 (c6b7fcb) demo2.ts: 0 pass 0 fail Ran 0 tests across 1 file. [312.00ms] (pass) lcov coverage reporter [385.76ms] (pass) coverage excludes node_modules directory [312.49ms] (pass) coveragePathIgnorePatterns - single pattern string [470.28ms] (pass) coveragePathIgnorePatterns - partial coverage without nan [343.72ms] (pass) coveragePathIgnorePatterns - array of patterns [473.35ms] (pass) coveragePathIgnorePatterns - glob patterns [446.86ms] (pass) coveragePathIgnorePatterns - lcov reporter [425.61ms] (pass) cov ... (truncated) release with fix: all passed $ bun scripts/build.ts --profile=release [configured] bun-profile → bun (stripped) target linux-x64-gnu build type Release build dir ./build/release revision b988ec3 features lto, baseline 23 deps, 131 codegen, 1176 objects in 1534ms 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) [54.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] gen ErrorCode+*.h [4/1250] gen bindgenv2 [5/1250] fetch tinycc [tinycc] up to date [6/1249] install /workspace/bun/src/node-fallbacks bun install v1.4.3-canary.1 (c6b7fcb) Checked 111 installs across 104 packages (no changes) [239.00ms] [7/1249] fetch zlib [zlib] up to date [8/1249] esbuild bun-error ../../build/release/codegen/bun-error/index.js 34.9kb ../../build/release/codegen/bun-error/bun-error.css 12.8kb ⚡ Done in 91ms [9/1249] fetch libjpeg-turbo [libjpeg-turbo] up to date [10/1222] gen node-fallbacks/react-refresh.js Bundled 1 mod ... (truncated) ``` </details> <details><summary>diff hotspot</summary> ``` src/jsc/bindings/CodeCoverage.cpp | 7 +- src/jsc/bindings/JSCommonJSModule.cpp | 7 +- src/jsc/bindings/ZigSourceProvider.cpp | 19 +- src/jsc/bindings/ZigSourceProvider.h | 3 +- src/jsc/modules/BunJSCModule.h | 39 +---- src/sourcemap_jsc/CodeCoverage.rs | 145 +++++++++------ test/cli/test/coverage.test.ts | 311 ++++++++++++++++++++++++++++++++- 7 files changed, 427 insertions(+), 104 deletions(-) ``` </details> **gate history** · 1 passed · 0 rejected · iteration 0 <details><summary>evidence per changed file</summary> ``` file reads edits tests src/jsc/bindings/CodeCoverage.cpp 2 0 38 src/jsc/bindings/JSCommonJSModule.cpp 1 1 38 src/jsc/bindings/ZigSourceProvider.cpp 2 2 38 src/jsc/bindings/ZigSourceProvider.h 2 4 39 src/jsc/modules/BunJSCModule.h 1 2 38 src/sourcemap_jsc/CodeCoverage.rs 5 9 40 test/cli/test/coverage.test.ts 4 4 38 ``` </details> <!-- robobun:evidence:end -->
…oven-sh#42549) ### Problem - With `bun build --minify-syntax`, ``ns["tag"]`z` `` prints as ``$tag`z` `` when `tag` is a lifted CommonJS export. The tag then runs with `this === undefined`: `TypeError: undefined is not an object (evaluating 'this._helper')`. ``st["tag"]`z` `` on a default import and ``exports["tag"]`z` `` inside the CommonJS file break too. - The cause is the `a["b"]` to `a.b` rewrite in `e_index` (`src/js_parser/visit/visit_expr.rs:858`). It moves `p.call_target` and `p.delete_target` to the new `E::Dot`, then visits it. It does not move `p.template_tag` (added in oven-sh#41251). So `e_dot` sees no tag, and the linker binds the export directly. ### Fix - The rewrite also points `p.template_tag` at the new `E::Dot`. esbuild does the same (`p.templateTag = dot`). - The second rewrite in `e_index` (`a["x" + "y"]`) is unchanged. It returns the new `E::Dot` without a visit, so nothing reads the marker. That form already works. - Verified: `test/bundler/bundler_cjs2esm.test.ts` (3 new tests, all fail on main). Also 11 other bundler suites (see the notes). - Self-reviewed: 2 concerns raised, 2 addressed. ### Background - Lifting turns `exports.foo = x` in a CommonJS file into `var $foo = x` plus an ES export. The namespace object (`exports_lib`) stands in for `module.exports`. - ``X.name`z` `` passes `X` as `this`, like a method call. ``$name`z` `` passes `undefined`. oven-sh#41251 makes the linker keep `X.name` as written when the file calls it or tags a template with it. - `e_template` stores the tag node in `p.template_tag`. `e_dot` and `e_index` compare their own node with it by address. A rewrite that replaces the node must move the marker. <details><summary>Notes</summary> Repro (fails on 1.4.3-canary.1+6a92015fc and on main b993710). `git tag --contains f31440d` lists bun-v1.4.1 and bun-v1.4.2, so both releases have the same code: ```sh cat > lib.cjs <<'EOF' exports._helper = function (s) { return "helped:" + s[0]; }; exports.tag = function (s) { return this._helper(s); }; EOF cat > entry.mjs <<'EOF' import * as ns from "./lib.cjs"; console.log(ns["tag"]`z`); EOF bun build entry.mjs --minify-syntax --outfile out/min.js --target bun && bun out/min.js # TypeError: undefined is not an object (evaluating 'this._helper') at $tag ``` `out/min.js` on main holds ``console.log($tag`z`)``. With this change it holds ``console.log(exports_lib.tag`z`)`` and prints `helped:z`. The marker reaches three consumers, all through `IdentifierOpts::is_template_tag` set in `e_dot`: - `maybe_rewrite_property_access` (`src/js_parser/fold.rs:271`) for `import * as ns`. - `record_import_property_use` (`src/js_parser/p.rs:6712`) for a default import. - `note_commonjs_export_use` (`src/js_parser/p.rs:5955`) for `exports.name` in the lifted file itself. Each new test covers one consumer. Each test also has the computed method call (`X["parse"]("y")`), which already worked, so both markers are covered under `minifySyntax`. The name `tag` appears only in computed form in each entry, because one marked use of a name keeps every `X.name` of that file as written and would hide the fault. The second rewrite (`ns["ta" + "g"]`, or an inlined TypeScript enum key) does not go through `maybe_rewrite_property_access` at all. It prints ``exports_lib.tag`z` `` on main and with this change. In esbuild that rewrite happens after `maybeRewritePropertyAccess` and carries no marker. Checked by hand with `--minify-syntax` and `--minify`, all print `helped:z`: `const ns = await import("./lib.cjs")`, `require("./lib.cjs")["tag"]`, `const ns = require("./lib.cjs")`, `import * as ns` through an `export *` barrel, and `import { default as st }`. Sites this change leaves alone: - Other folds check only for a call target, not for a template tag: the comma fold in `e_binary`, the ternary fold in `e_if`, and the `[x][0]` fold in `e_index`. They turn ``(0, o.f)`x` `` into ``o.f`x` ``. That is the opposite fault (the tag gains a receiver). It also reaches plain `bun run`: ``(0, o.f)`x` `` sees `this === o` there, and `undefined` in node. oven-sh#42452 (section 4) tracks them. - oven-sh#40829 (open, conflicts with main) is the candidate fix for those folds. Its diff has the same three lines as this change, as one hunk of 26 files. It predates oven-sh#41251. If this change lands first, oven-sh#40829 drops that hunk on its rebase. - oven-sh#42402 (open) changes `has_value_for_this_in_call` at the fold sites. It does not touch this rewrite or `p.template_tag`. The star import test matches the receiver with `\w+` and does not pin `exports_lib`, because oven-sh#41820 (open) gives `import *` of a lifted module a namespace object of its own, with another name. The default import test and the self test pin the exact output. Suites run on the debug build: `bundler_cjs2esm`, `bundler_minify`, `bundler_cjs`, `bundler_edgecase`, `bundler_dynamic_import_dce`, `esbuild/default`, `esbuild/dce`, `esbuild/importstar`, `esbuild/importstar_ts`, `esbuild/ts`, `transpiler/transpiler`, `transpiler/macro-test`. </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: BUILD FAILED (no junit output) $ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/pr_gate.xml" "test/bundler/bundler_cjs2esm.test.ts" ninja: Entering directory `/workspace/bun/build/debug' [1/66] cc obj/src/jsc/bindings/sqlite/sqlite3.c.o [2/66] gen ZigGeneratedClasses.{cpp,h,rs} Found 2 classes from /workspace/bun/src/jsc/resolve_message.classes.ts - ResolveMessage (15 fields) - BuildMessage (10 fields) Found 1 classes from /workspace/bun/src/runtime/api/Archive.classes.ts - Archive (4 fields, 1 class fields) Found 2 classes from /workspace/bun/src/runtime/api/BunObject.classes.ts - ResourceUsage (8 fields) - Subprocess (20 fields) Found 1 classes from /workspace/bun/src/runtime/api/cron.classes.ts - CronJob (5 fields) Found 3 classes from /workspace/bun/src/runtime/api/filesystem_router.classes.ts - FileSystemRouter (5 fields) - FrameworkFileSystemRouter (2 fields) - MatchedRoute (8 fields) Found 1 classes from /workspace/bun/src/runtime/api/Glob.classes.ts - Glob (5 fields) Found 1 classes from /workspace/bun/src/runtime/api/h2.classes.ts - H2FrameParser (32 fields) Found 9 classes from /workspace/bun/src ... (truncated) release without fix: 3 FAILED bun test v1.4.3-canary.1 (6a92015) test/bundler/bundler_cjs2esm.test.ts: (pass) bundler > cjs2esm/ModuleExportsFunction [29.67ms] (pass) bundler > cjs2esm/ImportNamedFromExportStarCJSModuleRef [13.37ms] (pass) bundler > cjs2esm/ImportNamedFromExportStarCJS [14.05ms] (pass) bundler > cjs2esm/BadNamedImportNamedReExportedFromCommonJS [12.90ms] (pass) bundler > cjs2esm/ExportsFunction [12.86ms] (pass) bundler > cjs2esm/ModuleExportsFunctionTreeShaking [14.55ms] (pass) bundler > cjs2esm/ModuleExportsEqualsRequire [14.10ms] (pass) bundler > cjs2esm/ModuleExportsEqualsRequireEntryPoint [14.87ms] (pass) bundler > cjs2esm/ModuleExportsEqualsRequireEntryPointImportedByEntryPoint [12.71ms] (pass) bundler > cjs2esm/ModuleExportsEqualsRequireEntryPointImportedByEntryPointSplitting [11.37ms] (pass) bundler > cjs2esm/ModuleExportsEqualsRequireTwoEntryPoints [12.24ms] (pass) bundler > cjs2esm/ModuleExportsBasedOnNodeEnvProduction [14.95ms] (pass) bundler > cjs2esm/ModuleExportsBasedOnNodeEnvDevelopment [15.54ms] (pass) bundler > cjs2esm/ModuleExportsEqualsRuntimeCondition [11.08ms] (pass) bundler > cjs2esm/UnwrappedModuleRequireAssigned [14.33ms] (pass) bundler > cjs2esm/Unwrap ... (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/bundler/bundler_cjs2esm.test.ts" bun test v1.4.3 (6a92015) test/bundler/bundler_cjs2esm.test.ts: (pass) bundler > cjs2esm/ModuleExportsFunction [956.60ms] (pass) bundler > cjs2esm/ImportNamedFromExportStarCJSModuleRef [435.19ms] (pass) bundler > cjs2esm/ImportNamedFromExportStarCJS [376.00ms] (pass) bundler > cjs2esm/BadNamedImportNamedReExportedFromCommonJS [410.55ms] (pass) bundler > cjs2esm/ExportsFunction [350.96ms] (pass) bundler > cjs2esm/ModuleExportsFunctionTreeShaking [570.76ms] (pass) bundler > cjs2esm/ModuleExportsEqualsRequire [366.45ms] (pass) bundler > cjs2esm/ModuleExportsEqualsRequireEntryPoint [483.54ms] (pass) bundler > cjs2esm/ModuleExportsEqualsRequireEntryPointImportedByEntryPoint [421.50ms] (pass) bundler > cjs2esm/ModuleExportsEqualsRequireEntryPointImportedByEntryPointSplitting [435.10ms] (pass) bundler > cjs2esm/ModuleExportsEqualsRequireTwoEntryPoints [423.59ms] (pass) bundler > cjs2esm/ModuleExportsBasedOnNodeEnvProduction [613.50ms] (pass) bundler > cjs2esm/ModuleExportsBasedOnNodeEnvDevelopment [603 ... (truncated) release with fix: all passed $ bun scripts/build.ts --profile=release [configured] bun-profile → bun (stripped) in 739ms (unchanged) ninja: Entering directory `/workspace/bun/build/release' [1/61] cc obj/src/jsc/bindings/sqlite/sqlite3.c.o [2/61] gen generated_host_exports.rs generated_host_exports.rs: 122 exports (host=5, lazy=10, generic=107, rust=0); 243 extern-C blocks audited [3/61] gen ZigGeneratedClasses.{cpp,h,rs} Found 2 classes from /workspace/bun/src/jsc/resolve_message.classes.ts - ResolveMessage (15 fields) - BuildMessage (10 fields) Found 1 classes from /workspace/bun/src/runtime/api/Archive.classes.ts - Archive (4 fields, 1 class fields) Found 2 classes from /workspace/bun/src/runtime/api/BunObject.classes.ts - ResourceUsage (8 fields) - Subprocess (20 fields) Found 1 classes from /workspace/bun/src/runtime/api/cron.classes.ts - CronJob (5 fields) Found 3 classes from /workspace/bun/src/runtime/api/filesystem_router.classes.ts - FileSystemRouter (5 fields) - FrameworkFileSystemRouter (2 fields) - MatchedRoute (8 fields) Found 1 classes from /workspace/bun/src/runtime/api/Glob.classes.ts - Glob (5 fields) Found 1 classes from /workspace/bun/src/runtime/api/h2 ... (truncated) ``` </details> <details><summary>diff hotspot</summary> ``` src/js_parser/visit/visit_expr.rs | 3 ++ test/bundler/bundler_cjs2esm.test.ts | 62 ++++++++++++++++++++++++++++++++++++ 2 files changed, 65 insertions(+) ``` </details> **gate history** · 1 passed · 0 rejected · iteration 0 <details><summary>evidence per changed file</summary> ``` file reads edits tests src/js_parser/visit/visit_expr.rs 3 1 12 test/bundler/bundler_cjs2esm.test.ts 3 4 12 ``` </details> <!-- robobun:evidence:end -->
…ven-sh#43864) Fixes oven-sh#43831 ### Problem - On Windows, `bun install` never exits when the package it replaces holds the last hard link of a running exe. The process spins at 100% CPU in `Dir::delete_tree` on the uninstall worker thread, and the main thread waits on `pending_tasks` forever. The lockfile is never saved. 1.3.13 completed and left the `.old-<hex>` directory behind. - `src/sys/dir.rs` `delete_tree` treats `EPERM` from `unlinkat` as "this is a directory" and retries with `openat(O_DIRECTORY)`. That returns `ENOTDIR`, which flips back to `unlinkat`. Neither arm remembers the other, so a regular file that the OS refuses to unlink (NTFS `STATUS_CANNOT_DELETE` maps to `EPERM` at `src/errno/windows_errno.rs:847`, a `uchg` file on macOS) loops forever. `delete_tree_open_initial_subpath` has the same loop for the top-level path. ### Fix - Each entry keeps the `EPERM` that made the walker retry it as a directory. When the directory open then fails with `ENOTDIR`, `delete_tree` returns that `EPERM`. `EISDIR` and an iterator kind of "directory" store nothing, so `ENOTDIR` still flips back to unlink for them, as before. - `delete_tree_open_initial_subpath` does the same for the top-level path. - Correct because `ENOTDIR` from `openat(O_DIRECTORY | O_NOFOLLOW)` proves the entry is not a directory, so the `EPERM` was a real "cannot delete". Every caller already handles `Err`. `UninstallTask` finishes, the install completes and saves the lockfile, and the `.old-<hex>` directory stays, as in 1.3.13. - Verified: `test/regression/issue/43831.test.ts` on Windows (passes with the fix, times out on 1.4.3). Also `test/cli/install/{bun-install,bun-add,bun-remove,bun-pm}.test.ts` on Linux. ### Background - `uninstall_before_install` (`src/install/PackageInstall.rs`) renames `node_modules/<pkg>` to `.old-<hex>` and queues `UninstallTask::run`, which calls `dir.delete_tree(basename)` on a thread pool worker. `bun install` waits for every queued task before it saves the lockfile. - `delete_tree` is the shared `rm -rf` that about 50 call sites use (`bun install`, `bun remove`, `bun upgrade`, `bunx`, `bun link`, the isolated linker, `bun pm cache rm`). Any of them could hang the same way. - The `EPERM` arm exists because `unlink(2)` on macOS and BSD returns `EPERM` for a directory. Linux returns `EISDIR`. Windows returns `STATUS_FILE_IS_A_DIRECTORY`, so on Windows `EPERM` never means "directory". - Considered mapping `STATUS_CANNOT_DELETE` to `EBUSY` in `windows_errno.rs`: it closes one of four `EPERM` sources (mapped image, read-only file on non-NTFS, macOS `uchg`, sticky directory), leaves the loop in place, and changes an errno that `fs.rm` exposes to JS. Considered an `lstat` on `EPERM` like `node_fs.rs` does: one more syscall per `EPERM`, where the directory open the walker already makes gives the same answer. ### Downsides - Users on Windows and macOS still get a leftover `node_modules/.old-<hex>` directory after such an install. `UninstallTask::run` reports the failed removal only in debug builds. A follow-up PR will report it in release builds. - Binary size: `delete_tree` +578 bytes and `delete_tree_open_initial_subpath` +145 bytes in the Linux debug build (`nm -S`, unoptimized). Release size not measured (`bloaty` is not available here). - Success path: the only new work is one `Option` move in the `EISDIR | EPERM` arm. No new syscall or allocation. `strace` and `perf` are not available here. Interleaved wall clock of a reinstall that removes a 5000-file package, 5 runs each: main 212 to 300 ms, PR 180 to 264 ms, noise floor about 100 ms. <details><summary>Notes</summary> - Repro on windows-x64 with the debug build: a `file:` dependency installed into `node_modules/dep`, a single-link copy of an exe placed in it and started, then the dependency bumped and `bun install` run again. Before the fix: hung for 30 s, killed, `bun.lock` still named v1. After: completes in under 1 s, `bun.lock` names v2, `.old-<hex>` left in `node_modules`. - The test uses a copy of `cmd.exe` running `pause` on Windows (stdin pipe keeps it alive) and `chflags uchg` on macOS. Linux is skipped: an unprivileged process cannot make `unlink` return `EPERM` on a regular file there, and `chattr +i` needs `CAP_LINUX_IMMUTABLE`, which containers drop. - The test was not run on macOS here (no macOS machine). CI covers it. - `test/cli/install/bun-install.test.ts`: 13 failures, all network (git clone of bitbucket/gitlab) in this sandbox. `bun-link.test.ts`: 1 failure that prints a debug-build stack trace, same on main. - `src/runtime/node/node_fs.rs` has its own recursive rm for `fs.rm`. It never flips on `EPERM` on Linux or Windows, which is why `fs.promises.rm` returns `EPERM` at once on the same folder. - Self-reviewed: 3 concerns raised, 2 addressed (the comment length, the test copying the full bun binary). Not addressed here: surfacing the swallowed delete error in `UninstallTask::run`, which is the follow-up PR. - Review follow-ups in 1aec400: only `EPERM` is remembered (an `EISDIR` then `ENOTDIR` sequence is a race and keeps the unlink retry), and the test asserts that the held process is alive, that the install output is clean, and that one `.old-*` directory with the held file is left. </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/regression/issue/43831.test.ts <!-- robobun:evidence:end -->
…r evaluates it (oven-sh#42695) Fixes oven-sh#42632. Supersedes oven-sh#41386 (its four tests are included). ### Problem - With `--splitting`, a chunk that several entry points share can print an import cycle importer-first. A hoisted `var` then reads as `undefined`: `TypeError: undefined is not an object (evaluating 'a.name')` in opencode built by bun 1.4.1+. - `find_imported_parts_in_js_order` walked each chunk from its files sorted by `(distance_from_entry_point, stable_source_index)`. Neither key tracks evaluation order, so a walk could enter a cycle at the file that has to run first. That file prints last. ### Fix - `EntryWalk` is the traversal of the old visitor, started from an entry point. The walks run in parallel, one per entry point. With `--splitting`, a chunk has one owner, the entry point that loads first among its entry points (`LoadOrder`), and only the owner's walk places its files. Without `--splitting`, each chunk is owned by its own entry point. - The walk records runs of parts. The layout is one linear pass. A build with one entry point prints the same bytes as on main (92 packages). - Deletes `chunk::Order` and `File.distance_from_entry_point`. - Verified: `test/bundler/bundler_splitting.test.ts` (26 new tests, 6 fail on main). Notes: bytes of 92 packages, 6,000 random graphs, wall time. ### Background - A shared chunk holds files that several entry points load. - `entry_bits[file]` has one bit per entry point that loads the file. - A file runs after the files it imports. Inside an import cycle, the file entered first runs last. - A part is one top-level statement. An `import` of a wrapped file prints as a call in its part, so parts print between the files that the file imports. <details><summary>Notes</summary> **Shape of the change** - `EntryWalk` (`findAllImportedPartsInJSOrder.rs`) has the rules of the old `FindImportedPartsVisitor`: it follows every `import` statement of every part, also in files that tree shaking dropped, and the other records of parts that run. It differs in where it starts and in what it records. - There is one walk per entry point that owns a chunk, and the walks run on the worker pool (e702bec). With `--splitting`, the owner of a chunk is the entry point that loads first among the entry points of the chunk. Only the owner's walk places the files of the chunk, so no two walks write the same list. A walk goes through the files of other chunks. Without `--splitting`, each chunk is owned by its own entry point (oven-sh#41263: each entry point keeps its own module order). - `LoadOrder` ranks the entry points in one pass before the walks: the user's entry points, then the chunks that load on demand (`import()`, a `require()` in a part that only declares) in the order evaluation comes to them, then the rest. A split `require()` in a part that runs at load loads its chunk in place, and a walk follows it in place, like a static import. A load counts only the calls in files that its entry point loads. - A placement is a `PartRun`: parts `begin..end` of a file. The parts ahead of the part that imports a file go before that file, the rest goes where the walk leaves the file. A wrapped file goes whole, where the walk leaves it. `ChunkLayout::place` turns the runs of a chunk into part ranges in one linear pass. It has the membership checks and the range merging of the old visitor. - Every claim happens when the frame pops, not when it is pushed (the class-name object of a CSS file, the rank of a split `require()` target, the on-demand list). An import pushed earlier can reach the same target first. - The class-name object of a CSS module goes into the chunk of its importer when that chunk loads the CSS file, whatever load reached the importer. - A part also leads to the files that declare the bindings it uses (`part.dependencies`), for a file that the `import` statements did not reach. The namespace export part is the exception: it comes ahead of the `import` statements and only holds getters, so what it names is walked after the other parts. With CommonJS output it names every export of the entry point, and it must not decide the order. - `reached_chunks_in_order` is a walk per chunk from the chunk's files in the order the pass entered them. It ranks the other chunks for the chunk's `import` statements. It does not order files. - `mark_file_reachable_for_code_splitting` keeps the BFS from main. Only the distance is gone. - Chunk folding rewrites `entry_bits`. A folded file can sit in a chunk whose entry points do not import it. It goes last in its chunk, as it did with the sorted roots on main. **Why the order is not part of the entry bits walk** The previous revision of this PR (f10ab25) gave out positions in `mark_file_reachable_for_code_splitting`. CI showed two regressions, and both come from that merge: - A file's parts interleave with its imports. `import "./a.cjs"; import "./b.js"` prints `require_a()` in a part of the importer, ahead of the code of `b.js`. One position per file puts all parts of the importer after all of its imports: `b` ran before `a` (`react-compiler/BundledReactPreservesImportRefs`, the happy-dom hash in `bundler_bytecode_portable`). - The load graph is not the import graph. The entry bits walk follows what loads. An `import` of a `sideEffects: false` file is no edge there, the walk reaches the file from the part that uses the binding, and it never visits a barrel that tree shaking dropped. A DFS over those edges prints such a file at its first use: `import { x } from "pure"; import "./side.js"` ran `side` first. In a build with one entry point and no `--splitting`, 20 of 92 packages printed different bytes than on main. The order has to follow the import statements, and a walk may place a file only if its entry point loads it (the barrel and unused-import tests). Whether an entry point loads a file is known only when the bits are complete. So the order is its own pass, after the bits. **Shapes** (stdout of the bundle, `ok` = same as the source) | shape | main | oven-sh#41386 | this PR | |---|---|---|---| | oven-sh#42632: cycle, both files at the same import depth | `undefined` | ok | ok | | cycle, the file to run first is deeper | `undefined` | `undefined` | ok | | no cycle, import depth differs from evaluation order | `q p` | `q p` | `p q` (ok) | | lazy page listed before its importer enters the cycle from the other side | ok | `undefined` | ok | | earlier entry point reaches the cycle through a `sideEffects: false` barrel, or an unused import | ok | ok | ok | | top-level `require()` of a split chunk enters the cycle first (`--target=bun`) | ok | ok | ok | | two `import()` calls, the one in an imported file runs first | `undefined` | ok | ok | **Bytes against main** 92 packages from `test/node_modules`, one entry point each (the `module` or `main` file of the package). On the current head, against main c6b7fcb: - `--target=bun`, without and with `--splitting`: all 92 print the same bytes as main. `--format=cjs`: all 92 the same. - Two entry points without `--splitting` (44 pairs): all the same. - Two entry points with `--splitting` (44 pairs): 42 the same. `@grpc/grpc-js` + `@grpc/proto-loader` and `socket.io` + `socket.io-adapter` differ in the order of the lazy `__commonJS` wrappers inside the shared chunk. On e9f9214, against main 7000dc1, also `--bytecode`, `--target=node --format=cjs` and `--minify` (all 92 the same), and `--target=browser` with and without `--format=iife` (the 55 that build are the same). The webpack bundle differs from run to run on main itself, in how `require.resolve("watchpack")` prints. That is a separate bug and I did not count it. The first revision of the walk in this PR (f10ab25) differed from main on 20 of the 92 in the first mode. **Differential run** (measured on e9f9214, before e702bec moved the walks to the worker pool) The generator from `test/bundler/splitting-fuzz.ts` (oven-sh#42442), 2,000 graphs per row, `--splitting --target=bun --format=esm`. The oracle is the unbundled source. A graph counts when a value that a module reads while it loads differs from the source run. | row | main | oven-sh#41386 | this PR | |---|---|---|---| | entry points load their chunks with `import()` | 138 | 123 | 114 | | static entry points | 147 | 133 | 122 | | static entry points, no `require()` | 16 | 14 | 5 | | the same, graphs with one entry point (1,523) | 8 | 7 | 0 | Reads of a binding before its initializer ran: 71 / 55 / 44, 76 / 61 / 48, 12 / 12 / 4. Bundles that are byte for byte the same as on main: 1,933, 1,944 and 1,975 of 2,000. The graphs that stay wrong are wrong on main too (a `require()` cycle that the bundle cannot reproduce, a cycle that two chunks share), except four seeds where main is right and this PR is not: 146 and 1131 (two entry points need opposite orders), 655 and 1744 (below). **Wall time** (measured on e9f9214, where the pass over all entry points was serial) Release builds, main 7000dc1 against this PR, median wall time of `bun build`, runs interleaved. The machine had other load, so read differences under 5% as noise. | project | main | this PR | runs | |---|---|---|---| | 800 entry points x 13 modules over a 3,000-module core, `--splitting` | 776 ms | 754 ms | 11 | | the same, no `--splitting` | 1,987 ms | 1,942 ms | 9 | | 800 entry points x 13 modules over one 200,000-export file (oven-sh#42489), `--splitting` | 1,336 ms | 1,296 ms | 9 | | 300 entry points over the 3,000-module core, `--splitting` | 259 ms | 251 ms | 11 | | the same, no `--splitting` | 722 ms | 708 ms | 15 | | one entry point, 200 routes behind `import()`, all over the 3,000-module core, `--splitting` | 276 ms | 266 ms | 11 | Peak RSS is the same within 1% in every row. **Prior art** - esbuild has the same sort key, from which bun's was ported (`linker.go` `findImportedPartsInJSOrder`), and the same bug: evanw/esbuild#399, open since 2020. - Rollup (`analyseModuleExecution`, `src/utils/executionOrder.ts`) and Rolldown (`sort_modules`) number every module in one post-order DFS from the entry points and sort each chunk by that number. This PR does the same with the walk that bun already had, and keeps the placement per part. **opencode** opencode v1.18.30, its `script/build.ts` options without `compile` (355 outputs). Bundle from main: `opencode run "say hi"` fails, the log has `TypeError: undefined is not an object (evaluating 'node.name')`. Bundle from this PR: the same command starts the session and reaches the call to the model API. **Remaining limits** - When two loaders evaluate the files of a shared chunk in opposite orders, the chunk follows the first. One printed order cannot serve both (seeds 146 and 1131). - A split `require()` counts as `runs at load` when its part has side effects. A function that holds the call and that its own file calls while it loads is on demand (seed 1744). A callback inside a top-level statement that never runs while loading counts as at load. - Seed 655: a top-level `require()` closes a cycle across two chunks. From source, `require()` returns the half-initialized module. In the bundle it runs the other chunk. - The class-name object of a CSS module prints ahead of the first file of the chunk that imports it. Main printed it where its walk first came to the file, also through a dropped file, and also in chunks that do not use it. **Suites** On a debug build of this commit: - `test/bundler/bundler_splitting.test.ts`: 151 pass on the current head. Main fails 6 of the 26 new tests: `TreeShakenImporterPreservesCyclicChunkOrder`, `CyclicChunkPreservesDeepImporterOrderSplit`, `SharedChunkKeepsImportCycleOrder`, `SharedChunkCycleOrderIgnoresImportDepth`, `SharedChunkKeepsSideEffectOrder`, `SharedChunkFollowsTheImportCallThatRunsFirst`. The other new tests guard the walk: earlier revisions of this PR fail `WrappedImportKeepsImportOrder`, `SideEffectsFalseFileKeepsImportOrder`, `SharedChunkKeepsWrappedImportOrder` `NamespaceExportKeepsImportOrder`, `SharedChunkIgnoresImportCallInFileThatEntryDoesNotLoad` and `CssModuleObjectOfFileReachedThroughSplitRequire`. - Pass (on e9f9214): the 13 files of `test/bundler/esbuild/`, the 5 of `test/bundler/css/`, `bundler_{allow_unresolved,banner,barrel,browser,bun,cjs,cjs2esm,comments,compile,compile_autoload,compile_prelinked,compile_splitting,decorator_metadata,defer,drop,dynamic_import_dce,edgecase,env,feature_flag,files,footer,html,html_server,jsx,loader,merged_enum,minify,minify_symbol_for,naming,plugin,plugin_chain,promiseall_deadcode,regressions,string}`, `html-import-manifest`, `metafile`, `cli`, `standalone`, `transpiler/react-compiler`, `transpiler/react-compiler-fixtures`, `regression/issue/25628`, `regression/issue/5344`, `bun-serve-html-manifest`, `bake/dev-and-prod`. - `bun-build-api`: 65 pass. 2 `bytecode:` tests time out at 5 s in a debug build here, the same on a debug build of main. - `bundler_bytecode_portable` times out in a debug build here. With `--bytecode`, the seven library bundles and `libraries.js` of its snapshot are byte for byte the same as on main. </details> <!-- robobun:evidence:begin --> --- **[human-review]** gate passed · iteration 2 · 7 files touched <details><summary>fails on main (without fix)</summary> ```console ASAN without fix: 6 failed, 4 skipped $ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/pr_gate.xml" test/bundler/bundler_splitting.test.ts bun test v1.4.3 (c6b7fcb) test/bundler/bundler_splitting.test.ts: (pass) bundler > splitting/DynamicImportCSSFile [1119.69ms] (pass) bundler > splitting/DynamicImportMultipleCSSImports [758.58ms] (pass) bundler > splitting/StaticAndDynamicCSSImports [480.07ms] (pass) bundler > splitting/NestedDynamicImportWithCSS [621.16ms] (pass) bundler > splitting/SharedCSSBetweenChunks [613.19ms] (pass) bundler > splitting/DynamicImportChainWithCSS [597.55ms] (pass) bundler > splitting/ConditionalDynamicImportWithCSS [580.61ms] (pass) bundler > splitting/MultipleEntryPointsWithSharedCSS [880.35ms] (pass) bundler > splitting/DynamicImportWithOnlyCSSNoJS [554.17ms] (pass) bundler > splitting/CircularDynamicImportsWithCSS [532.18ms] (pass) bundler > splitting/DeadDynamicImportTargetGetsNoChunk-cli [463.81ms] (pass) bundler > splitting/DeadDynamicImportTargetGetsNoChunk-api [356.78ms] (pass) bundler > splitting/DeadDynamicImportTargetNoSplittingReference [551.44ms] (pass) bundler > splitting/DeadDynamicImportTar ... (truncated) release without fix: 4 skipped bun test v1.4.3-canary.1 (5435db8) test/bundler/bundler_splitting.test.ts: (pass) bundler > splitting/DynamicImportCSSFile [20.71ms] (pass) bundler > splitting/DynamicImportMultipleCSSImports [12.29ms] (pass) bundler > splitting/StaticAndDynamicCSSImports [10.52ms] (pass) bundler > splitting/NestedDynamicImportWithCSS [11.94ms] (pass) bundler > splitting/SharedCSSBetweenChunks [14.78ms] (pass) bundler > splitting/DynamicImportChainWithCSS [12.19ms] (pass) bundler > splitting/ConditionalDynamicImportWithCSS [11.19ms] (pass) bundler > splitting/MultipleEntryPointsWithSharedCSS [18.78ms] (pass) bundler > splitting/DynamicImportWithOnlyCSSNoJS [11.22ms] (pass) bundler > splitting/CircularDynamicImportsWithCSS [11.93ms] (pass) bundler > splitting/DeadDynamicImportTargetGetsNoChunk-cli [11.61ms] (pass) bundler > splitting/DeadDynamicImportTargetGetsNoChunk-api [13.19ms] (pass) bundler > splitting/DeadDynamicImportTargetNoSplittingReference [10.49ms] (pass) bundler > splitting/DeadDynamicImportTargetKeptWithoutTreeShaking [10.29ms] (pass) bundler > splitting/LiveDynamicImportTargetStillGetsChunk [12.87ms] (pass) bundler > splitting/DynamicImportChainLiveness [12.89ms] ( ... (truncated) ``` </details> <details><summary>passes on PR (with fix)</summary> ```console ASAN with fix: 4 skipped $ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/pr_gate.xml" test/bundler/bundler_splitting.test.ts bun test v1.4.3 (c6b7fcb) test/bundler/bundler_splitting.test.ts: (pass) bundler > splitting/DynamicImportCSSFile [816.60ms] (pass) bundler > splitting/DynamicImportMultipleCSSImports [486.26ms] (pass) bundler > splitting/StaticAndDynamicCSSImports [644.78ms] (pass) bundler > splitting/NestedDynamicImportWithCSS [551.52ms] (pass) bundler > splitting/SharedCSSBetweenChunks [585.99ms] (pass) bundler > splitting/DynamicImportChainWithCSS [544.72ms] (pass) bundler > splitting/ConditionalDynamicImportWithCSS [629.62ms] (pass) bundler > splitting/MultipleEntryPointsWithSharedCSS [748.73ms] (pass) bundler > splitting/DynamicImportWithOnlyCSSNoJS [474.70ms] (pass) bundler > splitting/CircularDynamicImportsWithCSS [597.88ms] (pass) bundler > splitting/DeadDynamicImportTargetGetsNoChunk-cli [543.99ms] (pass) bundler > splitting/DeadDynamicImportTargetGetsNoChunk-api [357.83ms] (pass) bundler > splitting/DeadDynamicImportTargetNoSplittingReference [455.25ms] (pass) bundler > splitting/DeadDynamicImportTarg ... (truncated) release with fix: 4 skipped $ bun scripts/build.ts --profile=release [configured] bun-profile → bun (stripped) in 629ms (unchanged) ninja: Entering directory `/workspace/bun/build/release' [0/14] 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�[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 ... (truncated) ``` </details> <details><summary>diff hotspot</summary> ``` src/bundler/Chunk.rs | 28 - src/bundler/LinkerContext.rs | 31 +- src/bundler/LinkerGraph.rs | 8 - src/bundler/linker_context/README.md | 9 +- .../findAllImportedPartsInJSOrder.rs | 1040 ++++++++++++++------ src/bundler/linker_context/mergeSmallChunks.rs | 2 +- test/bundler/bundler_splitting.test.ts | 730 ++++++++++++++ 7 files changed, 1489 insertions(+), 359 deletions(-) ``` </details> **gate history** · 7 passed · 1 rejected · iteration 2 <details><summary>evidence per changed file</summary> ``` file reads edits tests src/bundler/Chunk.rs 1 1 72 src/bundler/LinkerContext.rs 6 4 72 src/bundler/LinkerGraph.rs 2 1 72 src/bundler/linker_context/README.md 2 2 72 …bundler/linker_context/findAllImportedPartsInJSOrder.rs 18 5 73 src/bundler/linker_context/mergeSmallChunks.rs 2 0 72 test/bundler/bundler_splitting.test.ts 10 10 72 ``` </details> <!-- robobun:evidence:end --> --------- Co-authored-by: Cliff <[email protected]> Co-authored-by: Jarred Sumner <[email protected]>
… unhashed entry (oven-sh#44023) ### What does this PR do? Two `--splitting` fixes. A shared chunk could still print an import cycle in the wrong order. A lazy chunk could import the entry file, which runs the entry twice when its host loads it with a query string. Fixes oven-sh#42290. Follow-up to oven-sh#42695. **1. One rule for both order walks** - `load_rank` picks the entry point that lays out a shared chunk. `EntryWalk::walk` lays it out. Each had its own copy of the rules for which imports to follow. - The copies differed: only `walk` visited what a namespace export names after the `import` statements. So the wrong entry point could own a chunk that two `import()` targets share. - Both now call `for_each_edge`. **2. No fold into an entry without `[hash]` in its name** - Chunk folding puts code that an entry and its `import()` targets share into the entry chunk. The lazy chunk then has `import "./index.js"`. - The host can load that file as `index.js?v=1`. Browsers, Bun and Node key ES modules by the full URL, so the file runs twice. - Such an entry is now left alone, for every target. The shared code goes into one hashed chunk. - Still folds: HTML entry points, and `[hash]` in `naming.entry`. **3.** `EntryWalk` keeps one vec of owned chunks, not two parallel vecs (the `mordant` finding from oven-sh#42695). | case | main | this PR | |---|---|---| | `SharedChunkOwnerIgnoresNamespaceExportOrder` | `late_b yundefined` | `late_b yx` | | oven-sh#42290: `route.js` imports from | `./index.js` | `./index-[hash].js` | | oven-sh#42290: `import("./out/index.js?v=1")` prints | `shared, index 1, shared, index 1, route 1` | `shared, index 1, route 1` | | `bun build index.html --splitting` | folds | folds, same bytes | ### How did you verify your code works? - `bun bd test test/bundler/bundler_splitting.test.ts`: 172 pass. `SharedChunkOwnerIgnoresNamespaceExportOrder` and `NoChunkImportsEntryWithoutHash/{browser,bun,node}` fail on main. - 14 fold tests now run twice on their original target (`itFolds`): with a plain entry name they assert the new layout, with `[hash]` in the name they keep their old fold assertions. - Random graphs against the unbundled run, on the first commit (4,066 graphs, `--target=bun` and `browser`): 0 uninitialized reads on main and here. - Not run locally on the last commit: the other bundler suites, `mordant`, the `--compile` suites, and `FoldChunksForTesting is ignored without --expose-internals` (skipped in debug builds).
Fixes #25559
Upgrades the WebKit fork to upstream WebKit `7b485a76e9` (2026-09-23):
970 upstream commits since the previous merge base `ccdcb8a026`, about
200 of them in JavaScriptCore, WTF, bmalloc or cmake. Fork PR:
oven-sh/WebKit#725. This PR replaces #42666 (upstream `6b58d86abe`, the
first 216 commits of the range) and contains its source edits.
### Pin
- `WEBKIT_VERSION` is `f20ce77445`, the fork's main. It holds
oven-sh/WebKit#725 (the upgrade) and oven-sh/WebKit#734 (positions).
- oven-sh/WebKit#725 landed as a squash. The tree of `74650443cb` is
identical to the tree of `3a8b1bc93b`, the head that CI tested here
before. The squash has no upstream parent, so `git merge-base` with
upstream is still `ccdcb8a026`. The next upgrade must name `7b485a76e9`
as its base by hand, unless someone first records the merge on the
fork's main (`git merge -s ours` of the branch
`bun/upgrade-to-7b485a76e9`).
### Problem
- The fork is 970 commits behind upstream. #42666 stopped at
`6b58d86abe` and did not land.
- #25559: a `++array.length` loop is quadratic past 100000 elements.
Upstream `ab1caf1170` fixes `JSArray::setLength`. The loop of the issue
takes 5152 ms on the current release build and 726 ms on the debug +
ASAN build of this PR.
### Fix
- `WEBKIT_VERSION` points at the fork's main, with oven-sh/WebKit#725
and oven-sh/WebKit#734.
- `error.stack` costs what it did before the upgrade, within a few
percent (see Downsides). With offsets only, upstream reads a whole
source the first time a position in it is asked for, and decodes the
expression info again for every position. In oven-sh/WebKit#734 the
lexer notes where the lines start while it parses a whole source, the
code and its bytecode carry that table, and each position that was
looked up is kept. Nothing of that is in Bun.
- Upstream no longer stores lines and columns (`c76c52f5b1`).
`SourceCode(provider, firstLine, startColumn)` is gone, and 3 of Bun's 5
call sites would still compile with the integers read as source offsets.
All 5 now pass offsets only, and the provider's start position carries
the node:vm `lineOffset` and `columnOffset`.
- The other source edits follow upstream API changes:
`Error.stackTraceLimit` storage, `CheckedPtr` plumbing for inspector
agents, typed C strings, `ASCIICString` heap names, `char8_t` option
strings. "Notes for Bun" lists each one.
- The builtins share one text, and a `SourceCode` no longer has a first
line, so `at map (native:1:11)` had become `at map (native:3323:11)`.
The source of Bun's builtins, like that of JavaScriptCore's, is now a
`BuiltinsSourceProvider`, which is told where each builtin starts and
counts from there. `processTicksAndRejections (native:7:39)` and the
rest are what they were.
- Verified: `test/js/bun/jsc/webkit-upgrade-7b485a76e9.test.ts` (22
cases, 10 fail on main), 5 cases in `bun-build-compile.test.ts` for the
sources of an executable (fail without oven-sh/WebKit#734), 4
`Error.appendStackTrace` cases in `capture-stack-trace.test.js` (3 fail
on main) and a `SourceTextModule` position case in `vm.test.ts` (fails
on main). `test/bundler/bundler_bytecode_portable.test.ts` has a new
snapshot, because the bytecode cache format changed. 80 outputs with
positions in them are the same as on main: 20 sources, each run from a
file and compiled three ways. The Notes list the other suites.
### Background
- JavaScriptCore used to store a line and a column next to every source
offset in the parser, in `ExpressionInfo` and in the bytecode cache. It
now stores offsets only. `SourceProvider` builds a table of line starts
the first time someone asks for a line or a column, for example when
`Error.stack` is read.
- The bytecode cache (`bun build --bytecode`, `--compile`) has no line
and column fields any more. Payloads in the portability test are 3% to
6% smaller. The cache version is a hash of `WEBKIT_VERSION`, so a new
build rejects old payloads and compiles from source.
- `Error.stackTraceLimit`: JSC kept the limit in a C++ field that only a
`put` on the constructor updated. It now reads the own property of the
`Error` constructor when it captures a stack, as V8 does. Bun's default
of 10 moves to `Options::defaultErrorStackTraceLimit()`.
### Downsides
- Behaviour changes that code could depend on:
`vm.runInNewContext("Error.stackTraceLimit")` is 10 (was 100, Node gives
10). `TypeError.stackTraceLimit = n` and a setter installed on
`Error.stackTraceLimit` no longer change the limit. `BigInt("-")`,
`BigInt("+")` and `BigInt("0x ")` throw `SyntaxError` (were `0n`).
`Intl.DurationFormat("en", { hours: "numeric" }).format({ hours: 1 })`
is `"1:00:00"` (was `"1"`). `Intl.DateTimeFormat`
`resolvedOptions().dayPeriod` is `undefined` for an AM/PM pattern (was
`"short"`). `resize(-1)` and `resize(2 ** 53)` on a detached
`ArrayBuffer` throw `RangeError` (were `TypeError`, and Node throws
`TypeError`): the specification runs `ToIndex` before the detached check
(`223bd0faee`). Of 26 behaviours compared with Node 26.3, 12 changed to
Node's result and this one changed away from it.
- A position now takes a lookup in the source's table of line starts,
which the code did not need when it had its lines and columns. A stack
trace whose call sites are all new executes 3% (1 function deep) to 6%
(10 deep) more instructions than on main. The first `error.stack` in a
file takes 4 to 5 µs longer (20 µs against 15 µs at 100 KB, 27 µs
against 23 µs at 10 MB), where upstream alone takes 2.5 ms at 10 MB.
Repeated reads are 0.95 to 1.05 of main over 22 cases. In a 100 MB
module compiled with `--bytecode` the first read takes 0.03 ms and 0.6
MB of RSS, where upstream alone takes 34.5 ms and 137 MB. Loading a
module of 500 to 12,000 characters executes 2.7% to 3.6% fewer
instructions than on main. The tables are in oven-sh/WebKit#734.
- Positions that change, found by running 37 constructs through
`node:vm` and about 120 scripts of every feature that reports a position
(call sites, uncaught errors, `bun test` output, junit, inline
snapshots, coverage, `--cpu-prof`, the inspector) on main and on this
branch. Everything else was the same.
- The `new X` frame under a field initializer that throws is where the
constructor's parameters start: `4:14` (was `4:15` to `4:17`). Node
gives `4:14`.
- A position in a class field initializer on the same line as the
enclosing function has its true column: `1:45`, and `1:67` with 22
characters before it (was `1:35` for both). That is the shape of
minified code.
- `vm.SourceTextModule` applies `lineOffset` and `columnOffset` as Node
does (both were one short).
- A runtime error in a `vm.Script` with a negative `lineOffset` prints
the source line and a caret, as Node does.
- The frame that disposes a `using` is where its scope ends, `6:2` (was
the first line of the function with a column that meant nothing,
`2:12`). Node gives the last statement, `5:4`.
- The frame of an implicit base-class constructor is `unknown:1:11` (was
`unknown:1:17`). Both are positions in a text that the engine makes up.
- Bytecode holds the line starts of its source, about one byte per line.
It is still smaller than before the upgrade, because it shrank by more
(what TypeScript's `tsc` embeds with `--bytecode`: 16.49 MB to 16.17
MB). An executable without bytecode embeds what it did.
- Upstream's `WeakBlock` redesign (`7f5ab15882`, one week old upstream)
makes `WeakImpl::clear()` edit the free list and the counts of a block
without a lock. A `JSC::Weak` that is destroyed by a thread without the
API lock, or by the lock owner while it has released heap access, now
corrupts the weak blocks. I found no such call: 174,668 probed calls,
and about 4,700 tests with an assertion in `WeakBlock::deallocate`,
child processes included. Not covered: macOS, Windows, native addons
that delete a reference on their own thread, and code that no test runs.
<details><summary>Notes for Bun: every source edit, and what was
verified</summary>
New in this PR (upstream `6b58d86abe..7b485a76e9`):
- `SourceCode` (`c76c52f5b1`). `src/codegen/bundle-functions.ts`,
`JSCommonJSModule.cpp`, `NodeVM.cpp` (two sites) and
`NodeVMSourceTextModule.cpp` drop the line and column arguments. The
three-argument sites in `NodeVM.cpp` and `NodeVMSourceTextModule.cpp`
are the ones that would have compiled with the integers read as
`startOffset` and `endOffset`.
- node:vm start positions. JSC now adds the provider's start position to
every derived line and column, as unsigned numbers. The old `SourceCode`
constructor clamped `firstLine` and `startColumn` to 1. With
`lineOffset: -5`, the unclamped provider gave `e.line === 4294967293`
and broke the arrow header of compile-time errors (2 cases of
`vm.test.ts`). The new `providerStartPosition()` in `NodeVM.cpp` clamps
at zero for `vm.Script`, `vm.compileFunction` and `vm.SourceTextModule`.
`decorateParseErrorStack()` keeps its logic that applies the sign again.
Result: the same output as before this PR for negative offsets. Not
changed by this PR: `vm.compileFunction` reports the first body line one
too high for `lineOffset` 0 and 1 (`vm.js:2`, where Node prints
`vm.js:1` and `vm.js:2`). The 1.4.3 release prints the same lines as
this branch for offsets 0, 1, 5 and -3, and #38240 is the open PR for
it.
- `vm.SourceTextModule` passed zero-based numbers to the one-based
`SourceCode` arguments. With the provider as the only source of the
start position, a module with `lineOffset: n` now reports the same lines
as `vm.Script` with `lineOffset: n`, which is also what Node reports.
`vm.test.ts` has a case for it. #38235 covers the rest of the module
offsets (negative values, the identifier as the file name).
- `Error.appendStackTrace` (fork commit `eacf0ea760`). The fork's
`ErrorInstance::captureStackTrace()` called `value()` on
`JSGlobalObject::stackTraceLimit()`. The limit is empty for a value that
is not a number and for a deleted property, and since `a5bfdb3aaf` also
for `NaN` and for an accessor. `Error.stackTraceLimit = NaN;
Error.appendStackTrace(new Error("a"), new Error("b"))` aborted the
process. The string and the deleted form abort on main too. It now
captures zero frames, like `Error.captureStackTrace`.
- `ErrorStackFrame.cpp`: `ExpressionInfo::Entry` has no `lineColumn`.
`getAdjustedPositionForBytecode()` asks
`SourceProvider::documentLineColumnForOffset()` for the divot.
- `NodeVM.cpp` `decorateParseErrorStack()`: `JSTextPosition::column()`
is gone. The caret column is the distance from the token offset back to
the previous `\n` of the source, which is also how
`nthSourceLineForArrowHeader()` splits lines.
- `Error.stackTraceLimit` (`a5bfdb3aaf`):
`JSGlobalObject::setStackTraceLimit()` is gone. `JSCInitialize` sets
`Options::defaultErrorStackTraceLimit()` to 10. Every realm's `Error`
constructor starts from that option, so node:vm contexts now start at 10
(they started at 100, Node gives 10). `ShadowRealm` already had 10.
- Inspector agents (`9a8a5f7d36`): `InspectorAgentBase` derives from
`AbstractCanMakeCheckedPtr`. `InspectorLifecycleAgent`,
`InspectorTestReporterAgent`, `InspectorHTTPServerAgent` and
`InspectorBunFrontendDevServerAgent` add `CanMakeThreadSafeCheckedPtr`,
`WTF_OVERRIDE_DELETE_FOR_CHECKED_PTR` and
`OVERRIDE_ABSTRACT_CAN_MAKE_CHECKEDPTR`. The thread-safe base is what
upstream uses for agents whose controller can be destroyed on another
thread.
- `BunGCOutputConstraint.cpp`, `BunClientData.cpp` (`9b5592466b`):
marking constraint names are `ASCIICString`, so the literals take `_s`.
- `BunJSCModule.h` (`58e02c19b9`): `Options::samplingProfilerPath()` is
a `const char8_t*`, so the store takes `pathCString.data()`. The edit
adapts the type and nothing else: the statement segfaults on every call,
on main too, because the options are read-only after `Config::finalize`
(#32212), and #41137 replaces it.
- `JSSecrets.cpp` (`29a96fa550`): `CString::mutableSpan()` is protected.
`SecretsJobOptions` holds `UTF8CString`, which keeps `mutableSpan()`
public, so the destructor still zeroes the buffers. The platform
functions keep their `const CString&` parameters.
- `bindings.cpp` (`c17d3df6ec`): includes
`wtf/PlainGregorianDateTime.h`.
- `bundler_bytecode_portable.test.ts`: every hash moves, as the file's
header says for a format change. The bundled JS hashes do not move.
From #42666 (upstream `ccdcb8a026..6b58d86abe`):
- `String::utf8()` returns `UTF8CString` (`00130dc2f3`), whose `data()`
is a `const char8_t*`. 48 calls in 17 files give a NUL-terminated string
to a C function or to a format string, and they call
`legacyCStringPointer()`. The class generator emits the same pattern. 13
calls pass bytes and a length, and they use `span()`.
- `toCString()` is `toUTF8CString()` (`7189f73167`). `WeakGCMap` holds
raw pointers (`8ae0649a80`, `SecureContextCache::set()`).
`String(std::span<const char>)` is private (`74b519d7f9`,
`BunProcess.cpp`). `dataLog()` has no `const char8_t*` overload
(`BunAnalyzeTranspiledModule.cpp`).
- `scripts/verify-baseline-static/allowlist-x64-windows.txt`: this PR no
longer changes it. Its entry `__std_max_8i` was for `5e03b0c541`, which
uses `std::max` over an initializer list of `int64_t` (the MSVC STL
vectorizes that behind an `__isa_available` test). Main now lists the
code of the MSVC STL as `<lib:libcpmt.lib>` (#43704), and the merge of
main (`efdc463da7`) took that entry.
- Tests of #42666. The 5 cases of its
`webkit-upgrade-6b58d86abe.test.ts` are in
`webkit-upgrade-7b485a76e9.test.ts`, some in a longer form (the BigInt
case has its 8 operand shapes plus 6). Its
`webkit-upgrade-ccdcb8a026.test.ts` is carried over as a file: 5 cases
for the previous upstream range, which pass before and after this
upgrade.
Review of this diff (what I checked by hand, and how):
- Stack position of a class field initializer: **a regression, repaired
in the fork.** For a base class with an explicit constructor, `endpoint
= config.url` with `config === null` gave `at new Client (file.ts:7:15)`
on main (the `constructor(` line) and `at new Client (file.ts:9:21)`
with the pin `eacf0ea7` (the last statement of the constructor). Bun's
code frame then puts the caret on a line that did not throw. Cause:
upstream `c76c52f5b1`. The old `StatementNode::setLoc()` gave a scope
node the first line of the function next to the offset of its end, and a
frame used the line. Fork commit `3a8b1bc93b` gives the call the offset
where the constructor starts: `at new Client (file.ts:7:14)`, which is
what Node 26.3 prints. Upstream `main` still has the old call. The
expression info stores that offset, so the bytecode snapshot changes for
the 16 payloads that have a class with instance fields, and the 11
without one keep their hash.
- `using` and `await using`: the frame of the function that owns the
declaration moved from its first line to the statement that leaves the
scope (`work (2:14)` to `work (6:10)`). Node prints `work (6:12)`, so
this stays.
- `SourceCode` call sites: a scan of `src/` for every `SourceCode(...)`
finds 29 calls with one argument and 2 with three,
`bundle-functions.ts:468` and `JSCommonJSModule.cpp:176`. Both pass
`startOffset` and `endOffset`. No call passes a line and a column.
- `ErrorStackFrame.cpp`: `CodeBlock::expressionInfoForBytecodeIndex()`
adds `sourceOffset()` to the divot, so the divot that
`getAdjustedPositionForBytecode()` gives to
`documentLineColumnForOffset()` is an offset in the provider. Upstream's
`CodeBlock::lineColumnForBytecodeIndex()` does the same.
- `allowlist-x64.txt`: in a release build with LTO and the baseline
features, the region that the scanner counts as
`ipint_op_memory_atomic_wait64` is 43,831 bytes and has 8 AVX
instructions. They are the same sequences as in the handlers of
`v128.load8_splat`, `load16_splat`, `load32_splat` and `load64_splat` (3
+ 3 + 1 + 1). The gate is `Options.cpp:943`: `if (isX86_64() &&
!isX86_64_AVX()) Options::useWasmSIMD() = false`.
- `JSSecrets.cpp`: `mutableSpan()` copies a buffer that is shared, so
the destructor would then zero a copy. A breakpoint on
`~SecretsJobOptions()` shows a reference count of 1 for `password`,
`name` and `service` in `set`, `get` and `delete`, so the zeroing is in
place. The container has no keyring, so each call ended with
`ERR_SECRETS_PLATFORM_ERROR`.
- `FuzzilliREPRL.cpp`: no CI lane builds with `FUZZILLI_ENABLED`.
Compiled by hand with that flag, the file of this PR compiles, links and
runs. The file of main does not compile against the new WebKit (`format
specifies type 'char *' but the argument has type 'const char8_t *'`).
- Three worker test files fail on my machine and pass in CI.
`worker.test.ts` and `worker-late-completion.test.ts` hit the 5 second
limit on a host with a load average of 110 (CI, `x64-asan`: 42 of 42 in
3.5 s and 33 of 33 in 7.7 s). The `dns.lookup()` case of
`worker-terminate-lifetime.test.ts` is a LeakSanitizer report at
`node_fs_binding.rs:183` (#39684), in a container without DNS.
Measurements (Linux x64, release builds with LTO of main `8d36bff512`
and of this PR at `701805bae0`, runs interleaved A/B, host load average
about 110, so the quartiles are beside each median):
| | main q1 / median / q3 | this PR q1 / median / q3 |
|---|---|---|
| First `.stack` read, 10 MB source with 90,177 functions (15 runs) |
0.034 / 0.036 / 0.038 ms | 7.31 / 7.63 / 7.79 ms |
| Next 1,000 `.stack` reads, same source | 2.40 / 2.49 / 2.70 ms | 2.72
/ 2.82 / 2.91 ms |
| User CPU of that process | 662 / 684 / 699 ms | 647 / 649 / 665 ms |
| Peak RSS of that process | 105.9 / 106.9 / 107.1 MB | 102.5 / 103.5 /
104.6 MB |
| `new Error().stack`, 2 frames (9 runs) | 2.82 / 3.00 / 3.07 µs | 2.34
/ 3.41 / 3.57 µs |
| `new Error().stack`, 10 frames | 9.04 / 10.04 / 10.53 µs | 9.36 /
11.70 / 12.04 µs |
| `new Error().stack`, 50 frames | 38.2 / 43.3 / 43.7 µs | 39.2 / 46.9 /
49.3 µs |
| `new Error()`, 10 frames, no read of `.stack` | 0.45 / 0.63 / 0.68 µs
| 0.43 / 0.69 / 0.70 µs |
| Startup, `console.log` only, user CPU (25 runs) | 1.95 / 3.02 / 4.05
ms | 1.92 / 2.95 / 3.73 ms |
| Text section of the binary (`size`) | 80,675,832 bytes | 80,452,686
bytes |
The quartiles of the `new Error().stack` rows overlap. The medians are
higher on this PR at every depth (1.14, 1.09, 1.17 and 1.08 times), so
the slowdown is probably real and about 10%. `perf`, `valgrind` and
`strace` are not installed on the machine, so there are no instruction
counts.
`WeakImpl::clear()` and threads. A `Weak` may be destroyed by the thread
that holds the API lock while it has heap access, or by a GC thread
while the world is stopped. `WeakSet::allocate()` asserts the lock, and
nothing asserts it on deallocation. Bun releases heap access in one
place: `us_loop_run_bun_tick` (`epoll_kqueue.c`), between
`Bun__JSC_onBeforeWait` and `Bun__JSC_acquireHeapAccessAfterWait`, when
an idle collection is pending (#43681). In that window the thread runs
the poll and the mimalloc idle hooks. The libuv loop never releases
access.
Measured on Linux x64 with the debug build, with
`BUN_IDLE_GC_SECONDS=1,1,1`:
- A gdb breakpoint on `WeakImpl::clear()` that reads the owner of the
`JSLock`, the `hasAccessBit` of `Heap::m_worldState` and
`Heap::m_worldIsStopped`. 15 runs (12 worker, `MessagePort` and
`BroadcastChannel` test files, `napi.test.ts`, the upgrade test and a
workload with 3 workers, transfers, `fs` and `fetch`): 174,668 calls and
99 parks without heap access. 172,647 calls came from the lock owner
with heap access. 2,021 came from the collector thread with the world
stopped and the JS thread parked, all from `Heap::sweepArrayBuffers()`.
None came from the lock owner without access or from another thread.
- An assertion in `WeakBlock::deallocate` (not in this PR). Two controls
show that it fires: a call from a `Bun Pool` thread gives `ASSERTION
FAILED: m_heap.vm().currentThreadIsHoldingAPILock()`, and a call from a
JS thread that is parked without access gives `ASSERTION FAILED:
m_heap.hasHeapAccess()`. With that build, `test/js/web/workers`,
`test/js/node/worker_threads`, `test/js/web/broadcastchannel`,
`test/napi` and `test/js/web/abort` ran in full, and
`test/js/web/fetch`, `test/js/bun/http` and `test/js/web/streams` ran
for 12 minutes each: about 4,700 passing tests, child processes
included, no assertion failure.
- `napi_delete_reference` in a finalizer stays safe: `WeakSet::sweep`
keeps the block it walks linked (`WeakBlock::IterationScope`) and reads
the next block after the finalizers ran. This PR removes the stale
sentence from the comment there.
- The debug + ASAN `jsc` shell of this WebKit fails
`JSON-parse-reviver.js`: `JSONObject.cpp` and `CloneBase.h` both define
`JSC::WalkerState`, with 4 bytes and 1 byte, and `jsc.cpp` now uses
both. Bun does not have the problem: no file of Bun or of the
JavaScriptCore library includes the clone headers, and the test passes
in Bun (debug + ASAN and release). The fix for the shell is
oven-sh/WebKit#733.
`apply` and `arguments.length` (`a0e2a50e76`): upstream fixed
`sizeOfVarargs()` for a strict `arguments` object only. A sloppy one
with `length = 2 ** 32 + 1` still wraps to 1, before and after this PR
(Node throws `RangeError`). In a CommonJS file Bun drops a
function-level `"use strict"` (#40838), so the function of upstream's
example has a sloppy `arguments` object there.
Checked and unchanged: `runtime/JSType.h`, the fork's
`.github/workflows`, the release tarball names. The WebCore bindings
generator changes do not touch code that Bun's bindings use. JSC
options: `weakBlockPoolDivisor` (16) and `useB3SpecializeSelect` (true)
are new, none is removed.
Verified on Linux x64 with `bun run build:local` (Bun debug + ASAN
against the fork branch at `3a8b1bc93b`): `bun-debug -p 42` prints 42.
These files pass: `webkit-upgrade-7b485a76e9.test.ts` (18),
`webkit-upgrade-ccdcb8a026.test.ts` (5) and the five older
`webkit-upgrade-*.test.ts` files, `node/vm/vm.test.ts`, `vm-sourceUrl`,
`script-leak`, `sourcetextmodule-leak`, `sourcetextmodule-link-gc`,
`vm-script-fetcher-leak`, `happy-dom-vm-16277`,
`node/v8/capture-stack-trace.test.js` (68),
`bun/util/inspect-error.test.js` (39), `inspect.test.js`, `reportError`,
`error-gc-test`, `bun/test/stack.test.ts`, the inline snapshot tests,
`expect-stack-overflow-crash`, `cli/test/coverage.test.ts` (14),
`cli/inspect/` (`inspect`, `bun-inspector-protocol`, `HTTPServerAgent`,
`test-reporter`, `BunFrontendDevServer`, `compile-bytecode-tooling`),
`bun/jsc/bun-jsc.test.ts` (41),
`bun/sourcemap/internal-sourcemap.test.ts`, `bun/cookie/cookie.test.ts`,
`web/workers/worker.test.ts` (42),
`node-inspect-tests/parallel/util-inspect.test.js`, and
`bundler_bytecode_portable.test.ts` (22, with the new snapshot).
`web/fetch/fetch.test.ts` has 6 failures and `bun/http/serve.test.ts`
has 2. The same 8 fail with the release build of main in my container:
it runs as root and has no IPv6.
Not compiled locally: the Windows and macOS code paths. I read every
platform-specific use of `CString`, `utf8()`, `SourceCode` and the other
changed APIs in `src/`. CI builds them for real.
</details>
<details><summary>Upstream changes, 6b58d86abe..7b485a76e9 (754 commits,
154 touch JavaScriptCore, WTF, bmalloc or cmake)</summary>
Each commit appears once, under the most specific heading that applies.
### Needs an embedder-side change, or a check
- `c76c52f5b1` The parser and the bytecode keep source offsets only.
`SourceProvider` derives lines and columns from a lazy `LineStartTable`.
`SourceCode` loses `SourceCode(Ref<SourceProvider>&&, int firstLine, int
startColumn)` and the last two arguments of the five-argument form. An
old three-argument call still compiles, with its integers read as
`startOffset` and `endOffset`. Write `SourceCode(WTF::move(provider))`.
The start position of the provider now carries the line and column
offset. `JSTextPosition` keeps only `offset` and loses `line`,
`lineStartOffset` and `column()`. `ExpressionInfo::Entry::lineColumn`,
`UnlinkedCodeBlock::lineColumnForBytecodeIndex()` and
`CodeBlock::firstLineColumnOffset()` no longer exist. Call
`CodeBlock::lineColumnForBytecodeIndex()`,
`SourceProvider::positionInfoForOffset()` or
`SourceProvider::documentLineColumnForOffset()`.
`SourceCode::firstLine()` and `startColumn()` now build the line table.
`SourceCode::subExpression()`, `ScriptExecutable::recordParse()`,
`parseRootNode()` and `parseFunctionForFunctionConstructor()` lose their
line and column parameters. `Lexer<T>::isWhiteSpace()`,
`isLineTerminator()`, `convertHex()` and `convertUnicode()` become free
functions in `parser/SourceCharacters.h`. The bytecode cache layout is
not compatible: `CachedTypes.cpp` and the `ExpressionInfo` encoding drop
all line and column fields. A raw U+2028 or U+2029 inside a string
literal now starts a new line for reported line numbers.
https://bugs.webkit.org/show_bug.cgi?id=324564
- `a5bfdb3aaf` `JSGlobalObject::setStackTraceLimit()` and
`m_stackTraceLimit` no longer exist. `JSGlobalObject::stackTraceLimit()`
reads the own data property `stackTraceLimit` of the realm `Error`
constructor with `getDirect()`. It returns `std::nullopt` for a value
that is not a number. The initial `Error.stackTraceLimit` comes from
`Options::defaultErrorStackTraceLimit()` (default 100).
`Object.defineProperty(Error, "stackTraceLimit", { value: 3 })` and
inline-cached `Error.stackTraceLimit = n` writes now change the limit.
`TypeError.stackTraceLimit = 2` and a setter installed on
`Error.stackTraceLimit` no longer change it, which matches V8. The
commit message states a cost of about 3 ns per `new Error()`.
https://bugs.webkit.org/show_bug.cgi?id=324314
- `9a8a5f7d36` `Inspector::InspectorAgentBase` now derives from
`WTF::AbstractCanMakeCheckedPtr`. Each concrete agent must add a
`CanMakeCheckedPtr<T>` or `CanMakeThreadSafeCheckedPtr<T>` base,
`WTF_OVERRIDE_DELETE_FOR_CHECKED_PTR(T)` and a public
`OVERRIDE_ABSTRACT_CAN_MAKE_CHECKEDPTR(...)`. Upstream uses the
thread-safe base where teardown can run on another thread.
`JSGlobalObjectInspectorController` now holds agents as `CheckedPtr`
members and declares `m_agents` before them. `m_consoleClient` is now
`const`, so a constructor must call `lazyInitialize(m_consoleClient,
...)`. https://bugs.webkit.org/show_bug.cgi?id=324216
- `9b5592466b` JSC heap names change type from `CString` to
`ASCIICString`. This applies to the constructors of `Subspace`,
`IsoSubspace`, `CompleteSubspace`, `PreciseSubspace`,
`MarkingConstraint`, `SimpleMarkingConstraint`, `SlotVisitor` and
`AbstractSlotVisitor`, and to `MarkingConstraintSet::add()`.
`ASCIICString` has an implicit constructor from `ASCIILiteral`, but its
`const char*` constructor is `explicit`. A caller that passes a plain
literal must add `_s`. `Subspace::name()`, `MarkingConstraint::name()`,
`abbreviatedName()` and `AbstractSlotVisitor::codeName()` now return
`const ASCIICString&`. `ProfilerSupport::markStart()`, `markEnd()`,
`mark()` and `markInterval()` now take `UTF8CString&&`.
`StringPrintStream::toASCIICString()` and `WTF::toASCIICString()` are
new. https://bugs.webkit.org/show_bug.cgi?id=324651
- `58e02c19b9` `OptionsStorage::OptionString` in `runtime/OptionsList.h`
changes from `const char*` to `const char8_t*`. All string option
accessors, for example `Options::samplingProfilerPath()`, now have that
type. The option stores the raw pointer and does not copy the string.
`SourceProvider::sourceCodeDumpFilePath()` takes and returns
`UTF8CString`. WTF adds `String(const char8_t*)` and
`printInternal(PrintStream&, const char8_t*)`. Four sites that decoded
option paths as Latin-1 now decode them as UTF-8.
https://bugs.webkit.org/show_bug.cgi?id=324652
- `c17d3df6ec` `WTF::GregorianDateTime` and `wtf/GregorianDateTime.h` no
longer exist. `PlainGregorianDateTime` moves from
`JavaScriptCore/PlainGregorianDateTime.h` (namespace `JSC`) to
`wtf/PlainGregorianDateTime.h` (namespace `WTF`, with a global `using`).
`PlainGregorianDateTime::fromMilliseconds(double)` and
`currentLocalTime()` replace the old constructor and
`setToCurrentLocalTime()`. The class is a 64-bit payload without
setters, `yearDay()`, `operator tm()` or the `offsetOf...()` functions.
`DateCache::msToGregorianDateTime()`,
`DateInstance::gregorianDateTime()` and `formatDateTime()` already used
`PlainGregorianDateTime`. https://bugs.webkit.org/show_bug.cgi?id=324677
- `29a96fa550` `CString(ASCIILiteral)`, `CString(CStringBuffer*)`,
`CString::mutableSpan()`, `mutableSpanIncludingNullTerminator()` and
`grow()` are now `protected`. `CString(const std::string&)` no longer
exists. `UTF8CString`, `Latin1CString` and `ASCIICString` keep
`mutableSpan()`, `grow()` and the `ASCIILiteral` constructor public.
`safePrintfType(const Latin1CString&)` is deleted.
`JIT::compileTimeStats()` returns `UncheckedKeyHashMap<ASCIICString,
Seconds>`. https://bugs.webkit.org/show_bug.cgi?id=324791
- `99452a3d81` `CString::newUninitialized()` becomes `protected`. Call
`ASCIICString::newUninitialized()`, `UTF8CString::newUninitialized()` or
`Latin1CString::newUninitialized()`. `WTF::setCrashLogMessage()` (Cocoa)
now takes `UTF8CString&&`. `wtf/Forward.h` now exports `ASCIICString`,
`UTF8CString`, `Latin1CString` and `CStringWithEncoding` to the global
namespace. https://bugs.webkit.org/show_bug.cgi?id=324692
- `fd27a24dd1` `StringTypeAdapter<CString>` has a deleted constructor.
`makeString()` and `StringBuilder::append()` reject an untyped `CString`
at compile time. Keep the typed value (`auto s = string.utf8()`), or
pass a span. `TextStream` declares `operator<<(const CString&)` as `=
delete`. `WTF::safeStrerror()` returns `UTF8CString`, and its `length()`
is now the message length.
https://bugs.webkit.org/show_bug.cgi?id=324230
- `eefa5dc4c3` `CString` loses `CString(std::span<const
Latin1Character>)` and `CString(std::span<const char8_t>)`. For bytes
with no known encoding, write `CString(byteCast<char>(bytes))`. For
text, use a typed constructor such as `UTF8CString {
byteCast<char8_t>(bytes) }`. `URLHelpers::userVisibleURL()` now takes
`std::span<const char8_t>`. `TextStream` gains `operator<<` overloads
for the typed strings. https://bugs.webkit.org/show_bug.cgi?id=324082
- `7e37c8055a` `WTF::toHexCString()`, `SHA1::hexDigest()` and
`SHA1::computeHexDigest()` return `ASCIICString`.
`CStringWithEncoding::legacyCStringPointer()` now exists only for
`UTF8CString`. On an `ASCIICString`, call `data()`.
`Wasm::NameSection::setHash()` takes `const
std::optional<ASCIICString>&`.
https://bugs.webkit.org/show_bug.cgi?id=324076
- `8217890851` `SHA1::addBytes(const CString&)` and
`Persistence::Coder<CString>` no longer exist.
`base64EncodeToStringReturnNullIfOverflow(const CString&, ...)` now
takes `const Latin1CString&`.
https://bugs.webkit.org/show_bug.cgi?id=324322
- `f5430ef75d` Intl code carries locale identifiers as `ASCIICString`.
`canonicalizeUnicodeLocaleID()`,
`localeIDBufferForLanguageTagWithNullTerminator()`,
`IntlCache::getBestDateTimePattern()` and
`IntlCache::getFieldDisplayName()` take `const ASCIICString&`. WTF adds
`StringView::ascii()` and `StringImpl::asciiForCharacters()`.
`IntlCache::canonicalizeUnicodeLocaleID()` returns a null `String` for a
non-ASCII tag without an ICU call.
https://bugs.webkit.org/show_bug.cgi?id=324324
- `7f5ab15882` `WeakBlock` now counts its allocated, live and dead
`WeakImpl` slots, so `Heap` no longer scans logically-empty blocks.
`Heap` pools empty blocks for all `WeakSet`s, and block stealing no
longer skips a `MarkedBlock` that had `WeakBlock`s. The new option
`weakBlockPoolDivisor` (default 16) keeps one pooled block per 16
`MarkedBlock`s. `WeakImpl::clear()` moves to `WeakBlock.h`. It now
updates the free list and the counters of the block without a lock, and
it can release the block. The old `clear()` only wrote a tag.
`Heap::addLogicallyEmptyWeakBlock()`, `WeakBlock::SweepResult`,
`takeSweepResult()`, `isLogicallyEmptyButNotFree()` and
`disconnectContainer()` no longer exist. New: `Heap::weakBlockCount()`,
`$vm.weakBlockCount()`, and `alignedMalloc()` plus `tryAlignedMalloc()`
on `FastMalloc` and `FastCompactMalloc`.
https://bugs.webkit.org/show_bug.cgi?id=324140
- `7692eececb` `WeakGCSet<T>` stores raw `T*` values, like `WeakGCMap`
since `8ae0649a80`. `reconcileWeakReferencesAtGCEnd()` removes unmarked
entries in eden and full collections. Iteration yields `T*`, and each
entry is live. `WeakGCSetHash` and `WeakGCSetHashTraits` no longer
exist. `JSGlobalObject::WeakCustomGetterOrSetterHash<T>::hash()` and
`equal()` take `T*`. `WeakGCSet.h` and `WeakGCSetInlines.h` no longer
include `WeakInlines.h`. https://bugs.webkit.org/show_bug.cgi?id=324122
- `aa19dc61a0` The last parameter of the `IsoSubspace` constructor
changes from `std::unique_ptr<AlignedMemoryAllocator>&&` to
`AlignedMemoryAllocator*`, with default `nullptr`. `ISO_SUBSPACE_INIT`
needs no edit. All `IsoSubspace` objects now share
`Heap::fastMallocAllocator`, and structure subspaces share the new
`Heap::structureAllocator`. A `LocalAllocator` can thus steal an empty
`MarkedBlock` from any subspace on the same allocator. The option
`stealEmptyBlocksFromOtherAllocators` (default `true`) still controls
this. `AlignedMemoryAllocator::registerDirectory()`,
`registerSubspace()`, `firstDirectory()` and
`Subspace::findEmptyBlockToSteal()` no longer exist. This is the second
landing of `fe81aba198`, which upstream reverted in the previous range.
https://bugs.webkit.org/show_bug.cgi?id=324020
- `d2cffa902f` JSC's `CloneSerializerBase` and `CloneDeserializerBase`
now handle `ArrayBuffer`, `SharedArrayBuffer`, typed arrays, `DataView`,
`WebAssembly.Module` and shared `WebAssembly.Memory`. The
`CloneDeserializerBase` constructor has a new fourth parameter of type
`CloneDeserializationSideChannels`. `CloneSerializerBase` gets a second
template parameter `SideChannelsType`.
`ArrayBufferContents::shareWith()` and its `operator bool()` become
`const`. Bun's `SerializedScriptValue.cpp` has its own serializer and
does not use these classes.
https://bugs.webkit.org/show_bug.cgi?id=324104
### Runtime, parser and builtins
- `7b485a76e9` The bytecode compiler emits a guarded
`op_construct_varargs` for `Reflect.construct(target, args[,
newTarget])` call sites. The guard makes the ordinary call when the
callee is not the original `Reflect.construct` or the arguments fail its
validation. Microbenchmarks are 1.42x to 3.43x faster. On the fast path,
`Error.stack` has no native `construct` frame between the constructor
and the caller. The new `LinkTimeConstant::reflectConstructFunction`
shifts the values of later `LinkTimeConstant` entries, which cached
bytecode stores. https://bugs.webkit.org/show_bug.cgi?id=324411
- `a89c41295f` `StringToBigInt` now needs at least one digit after a
sign or a radix prefix. `BigInt("-")`, `BigInt(" + ")` and `BigInt("0x
")` throw a `SyntaxError`. They returned `0n` before. `0n == "-"` is now
`false`. https://bugs.webkit.org/show_bug.cgi?id=324127
- `a848db6782` A parenthesized assignment target no longer gives its
name to an anonymous function or class. `(fn) = function () {}` leaves
`fn.name` as `""`. The rule also covers `??=`, `||=`, `&&=` and
destructuring defaults. https://bugs.webkit.org/show_bug.cgi?id=324430
- `ab1caf1170` `JSArray::setLength` skips `countElements()` when the new
length fits in the current vector. A `++array.length` loop past 100000
elements was quadratic. The microbenchmark goes from 2123.65 ms to 5.31
ms. The commit message links
https://github.com/oven-sh/bun/issues/25559.
https://bugs.webkit.org/show_bug.cgi?id=324306
- `433f888ace` `Error.stackTraceLimit = NaN` now clears the internal
limit, and new errors get no `stack`. The old code clamped `NaN` to `0`.
https://bugs.webkit.org/show_bug.cgi?id=323427
- `a0e2a50e76` `sizeOfVarargs()` clamps the `length` of a strict
`arguments` object before it compares it with the argument limit.
`arguments.length = 2 ** 32 + 1; g.apply(null, arguments)` now throws
`RangeError`. https://bugs.webkit.org/show_bug.cgi?id=324226
- `da75c48c45` `ArrayBuffer.prototype.slice` uses the species watchpoint
only when the receiver belongs to the current realm.
`ArrayBuffer.prototype.slice.call(otherRealm.buffer, 0, 8).constructor`
is now `otherRealm.ArrayBuffer`.
https://bugs.webkit.org/show_bug.cgi?id=324619
- `c5c46669ba` `Intl.DateTimeFormat` sets `dayPeriod` only from pattern
characters `b` and `B`, not from the AM/PM marker `a`.
`resolvedOptions().dayPeriod` for `{ hour: "numeric", minute: "2-digit"
}` is now `undefined`. `formatToParts()` still reports the AM/PM marker
as a `dayPeriod` part. https://bugs.webkit.org/show_bug.cgi?id=324559
- `9aea44e083` `Intl.DurationFormat` uses `"always"` as the display
default for minutes and seconds that follow a `"numeric"` or `"2-digit"`
unit. `new Intl.DurationFormat("en", { hours: "numeric" }).format({
hours: 1 })` returns `"1:00:00"`, not `"1"`.
https://bugs.webkit.org/show_bug.cgi?id=324561
- `6319f7420d` `BytecodeGenerator::emitUsingBodyScope()` emits the jump
to `skipSlot` before it ends the try range of each dispose call. DFG
failed in `DFGOSRAvailabilityAnalysisPhase` for some `using` and `await
using` code before. https://bugs.webkit.org/show_bug.cgi?id=324005
- `df94b6ccbb`, `9a38124281` Upstream `JSBigInt` gets Toom-3
multiplication (smaller operand of at least 508 digits) and
Schönhage-Strassen FFT multiplication. Both are ports of V8. The fork
already has both, with the `InterruptCheck` plumbing, so the merge keeps
the fork's versions. https://bugs.webkit.org/show_bug.cgi?id=323587
https://bugs.webkit.org/show_bug.cgi?id=324209
- `d2d61f8871` `JSBigInt` multiplication (`multiplySchoolbook`,
`multiplySpecialLow`, `multiplySpecialHigh`, `multiplyComba` and the
fixed-size variants) uses `std::span` in place of raw pointers. Results
do not change. https://bugs.webkit.org/show_bug.cgi?id=324494
- `ea153e64fb`, `d7240f488f`, `34ccaa804c` `CloneSerializerBase` and
`CloneDeserializerBase` follow JSC throw-scope style and stop at the
first exception. The `jsc` shell adds `structuredClone(value, { transfer
})`. Bun has its own serializer.
https://bugs.webkit.org/show_bug.cgi?id=324423
https://bugs.webkit.org/show_bug.cgi?id=324429
https://bugs.webkit.org/show_bug.cgi?id=324474
- `2a24a9aa7c` `JSClassCreate()` retains
`JSClassDefinition.parentClass`, and the `OpaqueJSClass` destructor
releases it. https://bugs.webkit.org/show_bug.cgi?id=319684
- `8ca47457ed` The new private header `JavaScriptCore/JSStringRefCPP.h`
adds `utf8CString(JSStringRef)` and `createJSString()`.
https://bugs.webkit.org/show_bug.cgi?id=324435
- `18073b9f6c` `JSTypedArrayConstructors.h` declares the explicit
`s_info` specializations for each typed array constructor and for
`JSDataViewConstructor`. Include it before a call to `info()` on these
classes. https://bugs.webkit.org/show_bug.cgi?id=324514
- `125543708a` `TypeProfiler::typeInformationForExpressionAtOffset()` no
longer dereferences a null `TypeLocation`.
https://bugs.webkit.org/show_bug.cgi?id=323314
- `c5fe81278b` `JSObject::crashDueToEmptyValueAtValidOffset` reports new
diagnostic data. The crash reason constant changes to
`0x100900d0ff5e7bad`. https://bugs.webkit.org/show_bug.cgi?id=324194
### RegExp (Yarr)
- `7aeed1e3bd` Non-global `String.prototype.replace(regexp, "")` returns
a substring cell of the subject when the match touches either end.
`string-replace-regexp-strip-prefix` is 2.30x faster.
https://bugs.webkit.org/show_bug.cgi?id=323409
- `ae0a88e6c1` A `\k<name>` back reference in a lookbehind no longer
matches empty when its group is the last group opened.
`/(?<n>.)..(?<=\k<n>.)/.exec("abc")` now returns `null`.
https://bugs.webkit.org/show_bug.cgi?id=324402
- `d8a2cff958` The DFG and FTL anchored first-character filter for
`RegExp.prototype.test` runs only when `lastIndex` is an Int32. Other
`lastIndex` values take the slow path, so the `ToLength(lastIndex)` side
effects stay observable after tier-up.
https://bugs.webkit.org/show_bug.cgi?id=324307
- `d22fa241f1` `SpeculativeJIT::emitRegExpMinimumLengthFilterGuards()`
no longer asserts when base and argument share a register, as in
`re.test(re)`. Debug builds only.
https://bugs.webkit.org/show_bug.cgi?id=324211
### JIT (LLInt, Baseline, DFG, FTL, B3, Air)
- `e57b0d1670` DFG stores OSR exits as a delta-encoded byte stream,
`DFG::OSRExitStream`, and decodes a `DFG::OSRExit` on demand.
`DFG::JITCode::m_osrExit` becomes `m_osrExits`. Exit data in one
JetStream3 run drops from 47.7 MB to 6.3 MB.
https://bugs.webkit.org/show_bug.cgi?id=323407
- `219167e2b4`, `7a5cfe078b` A linked DFG or FTL OSR exit entrance is
now one near call, and the return address identifies the exit. A DFG
entrance shrinks from 8 to 4 bytes on ARM64 and from 11 to 5 bytes on
x86_64. An FTL entrance shrinks from 20 to 4 bytes on ARM64 and from 10
to 5 bytes on x86_64. `DFGOSRExitBase.h` adds `static_assert(isARM64()
|| isX86_64())`. https://bugs.webkit.org/show_bug.cgi?id=324137
https://bugs.webkit.org/show_bug.cgi?id=324407
- `4dbb362ca1` `CodeBlock::updatePredictionsConcurrently()` updates
value profile and array profile predictions without a lock. The Baseline
JIT compiler thread and concurrent GC marking call it, so array profile
updates also move off the main thread.
https://bugs.webkit.org/show_bug.cgi?id=324016
- `418114c05c` `abstractAccess()` calls `entry.prepareToWatch()` when it
resolves a put to a `ClosureVar`. DFG could fold a module variable to a
stale value after an import cycle. This is the upstream form of the
fork's #624, and the merge takes upstream's test files.
https://bugs.webkit.org/show_bug.cgi?id=324124
- `5d1761dffb` DFG SSA lowering emits a separate `CheckInBounds` node
for `StringAt` and `StringCodePointAt`. FTL could remove the bounds
check together with an unused node before. Then `s.codePointAt(i) ===
undefined` stayed `false` for an out-of-bounds `i`.
https://bugs.webkit.org/show_bug.cgi?id=323640
- `54277a51f5` The DFG bytecode parser checks for `BadStringType` exit
sites before it compiles a by-val access as `CheckIdent` plus by-id. A
non-atom key such as `name.toLowerCase()` caused the same OSR exit after
each recompilation. The microbenchmark is 8.03x faster.
https://bugs.webkit.org/show_bug.cgi?id=323839
- `51a07f95fd` The DFG abstract interpreter and the DFG and FTL
`compileSpread()` take the original `Set` structure from the realm of
`node->child1()`. With a cross-realm `Set`, the compiler could treat
`[...set]` as free of side effects.
https://bugs.webkit.org/show_bug.cgi?id=321705
- `4dcc426f83` `B3LowerToAir` checks `crossesInterference()` before it
fuses or moves an `AtomicWeakCAS` or `AtomicStrongCAS` into a later
`Branch` or compare. A wasm `i32.atomic.rmw.cmpxchg` could move past a
`memory.grow` and use a stale memory base.
https://bugs.webkit.org/show_bug.cgi?id=319842
- `9c6d017806` `doneLocation` moves from `PropertyInlineCache` to
`RepatchingPropertyInlineCache`. `HandlerPropertyInlineCache` shrinks
from 88 to 80 bytes. `CodeBlock::findPropertyCache()` no longer exists.
https://bugs.webkit.org/show_bug.cgi?id=324424
- `e87ea0e64e` The specialize-select transform leaves
`B3::ReduceStrength` and becomes the new phase `B3::specializeSelect()`.
The new option `useB3SpecializeSelect` (default `true`) controls it.
https://bugs.webkit.org/show_bug.cgi?id=324673
- `95cec227df`, `7ae08af38b`, `7825a32d2b`, `fda68a8bb0`, `d6cc5eaa35`,
`d7fa43a33f`, `0aad9d201d`, `ba0e7b4024` Compile-time work in Air and
B3: `LiveRange` uses `Vector<Interval, 4>`, `IntervalSet` gets a bulk
constructor, `WTF::Liveness` gets a streaming adapter mode,
`fixObviousSpills` tracks aliased registers in register sets, the dense
liveness budget rises from 4 MB to 8 MB,
`IntervalSet::verifyCoverageConsistency` is a no-op in release builds,
and `B3::Procedure::deleteAllVariables()` is new. Generated code does
not change. https://bugs.webkit.org/show_bug.cgi?id=324009
https://bugs.webkit.org/show_bug.cgi?id=324750
https://bugs.webkit.org/show_bug.cgi?id=324795
https://bugs.webkit.org/show_bug.cgi?id=324695
https://bugs.webkit.org/show_bug.cgi?id=324716
https://bugs.webkit.org/show_bug.cgi?id=324688
https://bugs.webkit.org/show_bug.cgi?id=324759
https://bugs.webkit.org/show_bug.cgi?id=325058
### WebAssembly
- `5ad2bece76` IPInt handler slots shrink from 256 to 128 bytes on
ARM64, and large handlers jump to out-of-line code. offlineasm gains
`bc`, `loadbinc`, `loadbpreinc` and `orlshifti`.
`LowLevelInterpreter.cpp` adds `OFFLINE_ASM_ALIGN_TRAP_128` for Windows
ARM64. The commit message reports about 5% faster IPInt execution.
https://bugs.webkit.org/show_bug.cgi?id=324059
- `b9d477930e` `Heap::finalizeWasmCalleeCleanup()` calls
`WTF::crossModifyingCodeFence()` before it releases Wasm callees.
https://bugs.webkit.org/show_bug.cgi?id=320401
- `778a559d30` Both WasmToJS stubs also store the IPInt `MC` register in
the new `Wasm::WasmToJSIPIntMCSlot`. `Wasm::WasmToJSScratchSpaceSize`
grows from 16 to 32 bytes.
https://bugs.webkit.org/show_bug.cgi?id=324832
- `08f5b5c35e` `JSWebAssemblyInstance::setDebugId()`, `debugId()` and
`m_debugId` exist only under `ENABLE(WEBASSEMBLY_DEBUGGER)`, which
JSCOnly does not set. https://bugs.webkit.org/show_bug.cgi?id=324189
- `f2bd414de3`, `6452e03b9f`, `d8d3577549`, `74efecb8e0`, `a57cde3b59`,
`0aac8dcd47`, `9f9aae3434`, `073031147c` Wasm debugger fixes and the new
`qWasmStackValue` packet. All of this code is under
`ENABLE(WEBASSEMBLY_DEBUGGER)`, which only `PLATFORM(MAC)` sets.
### GC and memory
- `6c0de596d5` `BlockDirectory::findBlockForAllocation()` prefetches the
`MarkedBlock` header before the sweep that builds the free list.
`BlockDirectory::m_blocks` stores `std::pair<MarkedBlock::Handle*,
MarkedBlock*>`. `MarkedBlock::Handle` moves the rarely used `m_weakSet`
behind `m_block`. https://bugs.webkit.org/show_bug.cgi?id=324632
### WTF and bmalloc
- `6c6e928fdc` `WTF::loadLoadFence()` and `WTF::loadStoreFence()` emit
`dmb ishld` on ARM64. They emitted the full `dmb ish` barrier before.
https://bugs.webkit.org/show_bug.cgi?id=324352
- `ce646f1f85`, `3ff034369d`, `2d8b6e5a48`, `95a960a3ae`
`SAFE_WTFLOGALWAYS`, `LOG`, `RELEASE_LOG`, `ASSERT_WITH_MESSAGE` and the
signpost macros convert each argument with `WTF::logPrintfType()`. A
call site can pass a typed C string for `%s`. The helpers move from
`wtf/StdLibExtras.h` to `wtf/Assertions.h`. Existing callers need no
edit. https://bugs.webkit.org/show_bug.cgi?id=324090
https://bugs.webkit.org/show_bug.cgi?id=324142
https://bugs.webkit.org/show_bug.cgi?id=324287
https://bugs.webkit.org/show_bug.cgi?id=324236
- `f83706791b` `CStringWithEncoding::isolatedCopy()` is new.
`CStringBuffer` does not have a thread-safe reference count.
https://bugs.webkit.org/show_bug.cgi?id=319652
- `2d30c8e50c` `StringImpl::simplifyWhiteSpace()` returns `*this`
without allocation when the string is already simplified.
https://bugs.webkit.org/show_bug.cgi?id=324694
- `fbc14a1c5a` `wtf/text/StringCommon.h` adds a SIMD
`countMatchedCharacters()` overload for a compile-time character set.
https://bugs.webkit.org/show_bug.cgi?id=324640
- `77e8645084` `WTF::switchOn()`, `switchOnTupleAtIndex()` and
`WTF::apply()` mark their functor parameters `NOESCAPE`.
https://bugs.webkit.org/show_bug.cgi?id=324320
- `9e74021a2f` `Borrow::~Borrow()` asserts (debug only) that the object
is still borrowed when the borrow ends.
https://bugs.webkit.org/show_bug.cgi?id=324545
- `01f33be1d1` `determineTZoneMallocFallback()` selects
`ForceFastMalloc` when libpas uses MTE (Apple internal SDK on arm64e
only). https://bugs.webkit.org/show_bug.cgi?id=323981
### Build system and platform
- `a2a6f364bf` `WebKitCompilerFlags.cmake` adds `-fwrapv` for GCC, Clang
and `clang-cl` builds when the compiler accepts it. Signed integer
overflow in JSC, WTF and bmalloc code now wraps. Bun compiles its own
C++, which includes JSC inline code, without `-fwrapv`.
https://bugs.webkit.org/show_bug.cgi?id=324351
- `a306abc2c0` `Source/bmalloc/mimalloc/CMakeLists.txt` calls
`add_subdirectory(mimalloc EXCLUDE_FROM_ALL)`. `USE_MIMALLOC=ON` stops
the configure step when CMake is older than 3.25.
https://bugs.webkit.org/show_bug.cgi?id=324458
- `8009ddd215` `wtf/cocoa/MemoryFootprintCocoa.cpp` implements
`memoryFootprint()` with a call to a new overload,
`memoryFootprint(mach_port_t)`. `wtf/MemoryFootprint.h` declares that
overload only under `PLATFORM(COCOA)`, but the JSCOnly port compiles the
file on all Apple targets. The fork widens the guard to `OS(DARWIN)`.
https://bugs.webkit.org/show_bug.cgi?id=323690
- `fd4a9d09bf` `WebKitCommon.cmake` sets
`CMAKE_POSITION_INDEPENDENT_CODE` only when `NOT APPLE`. The fork keeps
its `NOT USE_BUN_JSC_ADDITIONS` condition as well.
https://bugs.webkit.org/show_bug.cgi?id=325064
- `5a819a7b96`, `d00124d9d7`, `6f39f11c5e` `WebKitCommon.cmake` records
the build settings with `set-webkit-configuration` when the build
directory is under the WebKit product directory. The step is not fatal,
and Bun's build directory does not match.
https://bugs.webkit.org/show_bug.cgi?id=324135
https://bugs.webkit.org/show_bug.cgi?id=324558
https://bugs.webkit.org/show_bug.cgi?id=324648
- `5bb1c6d49c` `WebKitCommon.cmake` derives `WTF_CPU_*` from
`CMAKE_OSX_ARCHITECTURES` on Apple hosts when that variable names one
architecture. This corrects an x86_64 build on an arm64 Mac, including
the offlineasm backend choice.
https://bugs.webkit.org/show_bug.cgi?id=319646
- `94ff070fff` `_WEBKIT_ADD_CODE_SIGN` reads entitlements from the
`CODE_SIGN_ENTITLEMENTS` target property. The fork keeps its early
`return()` for `CMAKE_CROSSCOMPILING`.
https://bugs.webkit.org/show_bug.cgi?id=324292
- `5cc3f23625` `WebKitCompilerFlags.cmake` no longer sets
`CMAKE_COMPILE_WARNING_AS_ERROR` for `DEVELOPER_MODE` builds on Windows.
https://bugs.webkit.org/show_bug.cgi?id=324157
- `61b575f0d0`, `2834de45ef`, `78c1083fa2`, `27504b2544` Build fixes and
one removed CMake option (`ENABLE_SWIFT_DEMO_URI_SCHEME`). No effect on
a JSCOnly build.
### Reverted within the range
- `b34e745e23` Upstream reverts the Linux main-thread detection from
317619@main (`getpid() == gettid()`), which aborted hosts that start WTF
on another thread. The fork had disabled that path under
`USE(BUN_JSC_ADDITIONS)`. The merge drops the fork's guards.
https://bugs.webkit.org/show_bug.cgi?id=322394
- `6ba0c9f709` and `d6e6a0fc1f` (`wtf/EscapableByteSpan.h`),
`14d632bf1e`, `0d533fd7f0` and `4dbba08d80` (Xcode PGO settings),
`d6f958d63e`, `e13c60e3d5` and `5a1e7b740f` (a web preference),
`3f7093e05c` (a web preference). No net effect on JSC.
### WebCore-only or no effect on a JSC embedder
`0d729748ef`, `162c4db3f1`, `a91d249a05`, `bf4e2de4fd`, `4ebc2a99c1`,
`3e95a187a1`, `648bbc69d1`, `3e1e77d2ba`, `a0df39e48d`, `fa1ff79d59`,
`27621d5adf`, `56909e17f9`, `d49b603f37`, `55f5311df8`, `13d5142b78`,
`484abf80fd`, `e887d63b22`, `d07436ebd4`, `49649b12d8`, `6307d48da4`,
`1aa6a33856`, `d0755e594a`, `7c5bf4eb1f`, `6b34ce7a2b`, `9c43b4a109`,
`56677f10e9`, `e25f645b0f`, `5fa37cf1fa`, `12a60d1a39`, `88ebf35179`,
`fc260f4e1c`, `263f9383d1`, `a749c7f864`, `d9eaeec654`, `06c8bf6974`,
`1666648452`, `a7c26d671b`, `6c721682be`, `3a633e3e57`, `02ad1221be`,
`36a3ac72aa`, `3113b23fc2`, `9467789fc1`, `41a9dfe94e`, `0ac65b1a46`.
</details>
<details><summary>Upstream changes, ccdcb8a026..6b58d86abe (216 commits,
47 touch JavaScriptCore, WTF, bmalloc, cmake or JSTests)</summary>
#42666 has the full list for this part of the range (runtime, GC,
RegExp, JIT, WebAssembly, WTF and build changes). These are its entries
that need an embedder-side change or a check.
Each entry says what a caller must change. Some entries need a check
only, and say so.
- `74b519d7f9` `WTF::String(std::span<const char>)` is now private, next
to `String(const char*)`, because `char` carries no encoding. Callers
name the encoding: `String::fromLatin1(std::span<const char>)` (new
overload), `String(std::span<const Latin1Character>)`,
`String::fromUTF8(...)` or `String(ASCIILiteral)`. In the same commit
`WTF::enumName()` and `WTF::enumTypeName()` (`wtf/EnumTraits.h`) return
`ASCIILiteral`. They returned `std::span<const char>` before, so callers
now test `isEmpty()` and not `empty()`.
https://bugs.webkit.org/show_bug.cgi?id=323650
- `7bd7b6dfad` `CString` gains `legacyCStringPointer()`, which returns
the same `const char*` as `data()`. Every upstream `utf8().data()` call
site moves to it. `CStringWithEncoding::characters()` (the `const char*`
accessor of `UTF8CString` and `ASCIICString` from `5f14e32e57`) is
renamed to `legacyCStringPointer()`. No type changes in this commit. It
is the mechanical half of the retype of `String::utf8()`. The retype
itself is `00130dc2f3`, the next entry.
https://bugs.webkit.org/show_bug.cgi?id=323722
- `00130dc2f3` `String::utf8()`, `StringImpl::utf8()`,
`StringView::utf8()` and `Identifier::utf8()` now return `UTF8CString`.
They returned `CString` before. `UTF8CString` is the alias
`CStringWithEncoding<char8_t>` (alias in `wtf/Forward.h`, class in
`wtf/text/CString.h`). The siblings are `Latin1CString`
(`Latin1Character`) and `ASCIICString` (`char`). `CStringWithEncoding`
is a final class that derives publicly from `CString` and adds no data
member. It hides the `CString` accessors so that the character type
carries the encoding. `data()` still exists, but for a `UTF8CString` it
returns `const char8_t*`. `span()` and `spanIncludingNullTerminator()`
return `std::span<const char8_t>`, and `mutableSpan()` returns
`std::span<char8_t>`. `legacyCStringPointer()` returns the same address
as `const char*`. It is the accessor for `%s` arguments and C functions,
and `Latin1CString` does not have it. `length()`, `isNull()`,
`isEmpty()`, `hash()` and `toStdString()` come from `CString` and do not
change. A call such as `s.utf8().data()` that feeds a `const char*`
parameter must become `s.utf8().legacyCStringPointer()`. The same
applies to `s.utf8().span().data()`. For a `std::span<const char>`,
write `byteCast<char>(utf8.span())`. A `const void*` parameter
(`fwrite`, `write`) still accepts `data()`. The `SAFE_PRINTF` and
`SAFE_FPRINTF` macros accept the `UTF8CString` itself. `PrintStream` has
no overload for `const char8_t*`, so `dataLog()` must get the
`UTF8CString` itself or the `String`. A `UTF8CString` converts
implicitly to `CString` (derived to base). So `CString c = s.utf8()`
still compiles and `c.data()` is `const char*`, but the encoding is
lost. `String` gains an implicit constructor from `const
CStringWithEncoding<CharacterType>&` that decodes by character type.
`CStringWithEncoding` gains explicit constructors from `const
std::string&` and from a null-terminated `const CharacterType*`.
`wtf/text/StringCommon.h` gains `unsafeSpan(const char8_t*)`.
https://bugs.webkit.org/show_bug.cgi?id=323846
- `9b09294076` Upstream removes about 850 `legacyCStringPointer()` call
sites where the destination already accepts a `String`. `LOG` with `%s`
becomes `LOG_WITH_STREAM`, `EXPECT_STREQ` becomes `EXPECT_EQ` in tests,
and `dataLog()` gets the `String`. Almost all edits are in WebCore,
WebKit and TestWebKitAPI. In JSC and WTF the commit edits two lines.
`Options::dumpAllOptions()` and the truncation path of
`printInternal(PrintStream&, const CString&)` now print a `String`
directly. No WTF or JSC function changes a parameter type or a return
type. No caller edit is needed.
https://bugs.webkit.org/show_bug.cgi?id=323859
- `7189f73167` `StringPrintStream::toCString()` is renamed to
`toUTF8CString()` and returns `UTF8CString`. The function template
`WTF::toCString(...)` is renamed to `WTF::toUTF8CString(...)` in the
same way. The old names have no alias. `printInternal(PrintStream&,
const CString&)` is now `= delete`, and the non-const `CString&`
overload is removed. So `out.print(cstring)`, `dataLog(cstring)` and
`dataLogLn(cstring)` do not compile for an untyped `CString`. New
overloads print `const UTF8CString&`, `const ASCIICString&` and `const
Latin1CString&`. UTF-8 and ASCII bytes go through unchanged, and Latin-1
is transcoded to UTF-8. To replace `out.print(someCString)`, keep the
typed value (`auto s = string.utf8()`, `toUTF8CString(...)`,
`string.ascii()`) and print that. Or print the `String` or `StringView`
itself, or pass `cstring.data()` as `const char*`. These bytecode
helpers now return `UTF8CString`: `CodeBlock::inferredName()`,
`CodeBlock::sourceCodeForTools()`, `CodeBlock::sourceCodeOnOneLine()`,
`InlineCallFrame::inferredName()`, `UnlinkedSourceCode::toUTF8()`,
`reduceWhitespace()`, `ArrayProfile::briefDescription()`,
`ValueProfile::briefDescription()`, `BytecodeDumper::registerName()` and
`constantName()`. These JIT and runtime helpers do the same:
`MacroAssemblerCodeRef::disassembly()`, `Compilation::disassembly()`,
`ExceptionScope::unexpectedExceptionMessage()`, `Air::Special::name()`,
`JITPlan::signpostMessage()`, `Wasm::Plan::signpostMessage()`,
`DFG::nodeListDump()`, `nodeMapDump()` and `nodeValuePairListDump()`. In
WTF, `sortedListDump()`, `sortedMapDump()`, `BackwardsGraph::dump()`,
`SingleRootGraph::dump()` and `StringHashDumpContext::brief()` return
`UTF8CString`. `Identifier::ascii()` and
`StringHashDumpContext::getID()` return `ASCIICString`, and
`Structure::dumpBrief()` takes `const ASCIICString&`. `PerfLog::log()`,
`GdbJIT::log()`, `Profiler::Database::logEvent()` and
`Profiler::Compilation::addDescription()` take `const UTF8CString&`, and
`DFG::validate()` takes a `UTF8CString`. As a side effect
`CodeBlock::inferredNameWithHash()`,
`SamplingProfiler::reportTopBytecodes()` and
`DebuggerCallFrame::functionName()` no longer decode UTF-8 function
names as Latin-1. https://bugs.webkit.org/show_bug.cgi?id=323960
- `25f7ce345a` `FileSystem::fileSystemRepresentation(const String&)`
returns `UTF8CString`. It returned `CString` before. A caller that
passed `.data()` to `open()`, `stat()` or a similar C function must call
`.legacyCStringPointer()`. On Windows the function now converts with
`CP_UTF8`. It converted with `CP_ACP` (the active ANSI code page)
before. The GLib functions `currentExecutablePath()`,
`currentExecutableName()` and `webkitTopLevelDirectory()` also return
`UTF8CString`, and Cocoa gains `currentExecutableName()`.
`createTemporaryFileInDirectory()` (Cocoa only) returns
`std::pair<FileHandle, String>`. `wtf/StdLibExtras.h` gains
`safeNSStringPrintfType()` and the `SAFE_WTFLOGALWAYS` macro.
`CStringWithEncoding` gains `createNSString()` for Objective-C++ code.
The JSC callers (`dumpJITMemory()`, `API/JSScript.mm`) move to
`legacyCStringPointer()`. https://bugs.webkit.org/show_bug.cgi?id=324034
- `8ae0649a80` `WeakGCMap<Key, Value>` now stores a raw `Value*` per
entry. It stored a `Weak<Value>` before, which is a pointer to a
separate `WeakImpl` that the heap reaps in each collection. `ValueType`
is `ValueArg*`. So `set(key, value)` takes a raw pointer, and the
`ensureValue()` functor returns a raw pointer. `find()->value` is a raw
pointer with no `.get()`. `isEmpty()` is removed. `pruneStaleEntries()`
is replaced by `reconcileWeakReferencesAtGCEnd(VM&, CollectionScope)`.
`WeakGCMap.h` no longer includes `Weak.h`, and `WeakGCMapInlines.h` no
longer includes `WeakInlines.h`. A caller that wrote `map.set(key,
Weak<T>(cell))` must write `map.set(key, cell)`. A file that got
`JSC::Weak` through `WeakGCMap.h` must include `<JavaScriptCore/Weak.h>`
itself. Old design: `WeakBlock::reap` cleared each `Weak<>` in every
collection, and `pruneStaleEntries()` removed the cleared entries in
full collections only. New design: `Heap::runEndPhase()` calls
`Heap::reconcileWeakGCHashTables()`, and each table tests its values
with `Heap::isMarked()`. A full collection visits every registered table
and removes each entry whose value is null or not marked. An eden
collection visits only the tables on the new list
`Heap::m_dirtyWeakGCHashTables`. `set()` and `ensureValue()` put the map
on that list through `WeakGCHashTable::markDirty(VM&)`. In an eden
collection the map only sets a dead value to null and does not rehash.
`get()`, `find()`, `contains()` and `ensureValue()` treat the null entry
as absent, and the next full collection removes it. A table that gained
no entry since the last collection is skipped. All its values are old,
and an eden collection cannot free them. `WeakGCHashTable`
(`runtime/WeakGCHashTable.h`) now derives from
`BasicRawSentinelNode<WeakGCHashTable>`. A subclass must override
`reconcileWeakReferencesAtGCEnd(VM&, CollectionScope)` in place of
`pruneStaleEntries()`. It must call `markDirty(vm)` when it adds an
entry, if eden collections must visit it.
`Heap::unregisterWeakGCHashTable()` also takes the table off the dirty
list. `WeakGCSet` keeps `Weak<>` entries and removes them in full
collections only, as before.
https://bugs.webkit.org/show_bug.cgi?id=323958
- `b8d7e24add` The MarkedBlock warm-up (prefault) supply moves from JSC
into libpas. The old code was `WarmUpBlockProvider` in
`heap/FastMallocAlignedMemoryAllocator.cpp`. It ran a `JSCWarmUp`
`AutomaticThread` that allocated blocks with
`tryFastCompactAlignedMalloc()` and wrote one byte per page. It worked
with every `fastMalloc` backend. The new code is
`bmalloc_prefault_supply.c` and `bmalloc_prefault_supply.h` in libpas,
and JSC calls it only under `#if USE(LIBPAS)`. So upstream, a build
whose `fastMalloc` is mimalloc or the system allocator gets no
prefaulted blocks. In that build `tryAllocateAlignedMemory()` calls
`tryFastCompactAlignedMalloc()` directly. With libpas,
`tryAllocateAlignedMemory()` returns
`bmalloc_prefault_supply_try_allocate()` for block-sized requests. The
supply is a fixed array of at most 64 slots
(`BMALLOC_PREFAULT_SUPPLY_MAX_BLOCKS`). Takers and the filler exchange
slots with atomic operations and no lock. A mutex and a condition
variable only wake or start the filler. The filler is a detached
pthread. It allocates with
`bmalloc_try_allocate_with_alignment_inline()` and touches pages with
the new `pas_page_malloc_populate()`. After one idle interval with no
demand it frees all blocks and exits, and a later take starts a new
thread. The options `useWarmUpMarkedBlocks` (true),
`warmUpMarkedBlockCount` (32) and `warmUpMarkedBlockIdleTimeout` (10
seconds) keep their names and defaults. JSC copies them once into
`bmalloc_prefault_supply_target` and
`bmalloc_prefault_supply_idle_timeout_in_milliseconds`.
`$vm.warmUpMarkedBlockState()` is removed.
`$vm.warmUpMarkedBlocksAreEnabled()` and `$vm.warmUpMarkedBlockCount()`
replace it, and `$vm.setWarmUpMarkedBlockAllocationShouldFail()` stays.
In C++, `warmUpMarkedBlockStateForTesting()`, `WarmUpMarkedBlockPhase`
and `WarmUpMarkedBlockState` are removed.
`warmUpMarkedBlocksAreEnabledForTesting()` and
`warmUpMarkedBlockCountForTesting()` are added, and without libpas they
return `false` and 0. `pas_thread.h` (the Windows pthread shim) gains
include guards, `PTHREAD_MUTEX_INITIALIZER`, `PTHREAD_COND_INITIALIZER`,
`extern "C"` and `PAS_API` exports. The new source file is listed in
`Source/bmalloc/CMakeLists.txt` and
`Source/bmalloc/libpas/CMakeLists.txt`.
https://bugs.webkit.org/show_bug.cgi?id=323480
- `2aedf51ba6` `WTF::UUID::emptyValue` and `UUID::deletedValue` become
private. The constructor `UUID(HashTableEmptyValueType)` becomes private
too. Only `HashTraits<UUID>` and `MarkableTraits<UUID>` (now friends)
can build the empty value. `UUID(HashTableDeletedValueType)` stays
public. `UUID(UInt128)` now release-asserts that the value is not 0
(empty) and not 1 (deleted), so `UUID { 0 }` crashes. `UUID(uint64_t
high, uint64_t low)` now rejects the empty value as well as the deleted
value. Code that needs "no UUID" must use `Markable<WTF::UUID>` or
`std::optional<WTF::UUID>`. `createVersion4()`, `createVersion4Weak()`,
`createVersion5()`, `parse()`, `parseVersion4()` and `toString()` do not
change. https://bugs.webkit.org/show_bug.cgi?id=323944
- `a371ed3141` A caller can no longer construct a `WTF::UUID` from raw
bits. `UUID(std::span<const uint8_t, 16>)` and `UUID(UInt128)` become
private. `UUID(std::span<const uint8_t>)` and `UUID(uint64_t, uint64_t)`
are removed. New factories replace them. `static std::optional<UUID>
tryCreate(std::span<const uint8_t>)` returns `std::nullopt` if the size
is not 16 or the value is reserved (0 or 1). `static std::optional<UUID>
tryCreate(uint64_t high, uint64_t low)` does the same for two halves.
`static consteval UUID createConstant(uint64_t high, uint64_t low)` is
for hardcoded constants, and a reserved value is a compile error. The
static `UUID::isValid(uint64_t, uint64_t)` is removed, and the member
`isValid()` stays. The only raw constructor call in JSC
(`jscJITNamespace` in `jit/ExecutableAllocator.cpp`, under
`HAVE(KDEBUG_H)`) moves to `createConstant()`. The random, parse and
string functions do not change. A caller that only uses
`createVersion4()`, `createVersion4UUIDString()`, `parse()` or
`toString()` needs no edit.
https://bugs.webkit.org/show_bug.cgi?id=324032
- `2d4a4717af` `wtf/UUID.h` gains the struct `UUIDCanonicalForm` (two
`uint64_t` fields, `high` and `low`) and
`StringTypeAdapter<UUIDCanonicalForm>`. The adapter holds the 8-4-4-4-12
lowercase hex layout. `StringTypeAdapter<UUID>` now derives from it and
passes `uuid.high()` and `uuid.low()`. The output of `makeString(uuid)`
does not change. The only new user is the FIDO AAGUID logging in WebKit.
No caller edit is needed. https://bugs.webkit.org/show_bug.cgi?id=324075
- `6103d1b95a` `makeStringByJoining(std::span<const String>, …
…inish, lifecycle) (oven-sh#43557) One pull request for the open `node:http` server pull requests. Each root cause is fixed once, and each pull request's tests are carried over. Node is the reference: every scenario was run under Node and under Bun from one script, and the outputs were compared. Fixes oven-sh#4733 Fixes oven-sh#18613 Fixes oven-sh#40350 Fixes oven-sh#43155 Fixes oven-sh#43297 Fixes oven-sh#43513 Fixes oven-sh#43527 Fixes oven-sh#25632 Fixes oven-sh#31301 Fixes oven-sh#43027 Fixes oven-sh#43163 Fixes oven-sh#43342 Fixes oven-sh#43344 Fixes oven-sh#43370 Fixes oven-sh#43490 Fixes oven-sh#43512 Fixes oven-sh#43519 Each of these has a repro that is wrong on Bun 1.4.3, right on this branch, and the same as Node. | Issue | Not closed by this PR, because | | --- | --- | | oven-sh#30501 (msal-node keeps Bun alive at exit) | Probably fixed. The repro copies the teardown of msal-node. The package itself was not run. | | oven-sh#14430 (yarn: "does not support SSL") | Probably fixed. `response.hasOwnProperty("socket")` is now `true`. yarn itself was not run. | | oven-sh#39681 (`server.setTimeout` callback after destroy) | Probably fixed. The repro is the deterministic case of oven-sh#39686. The script in the issue depends on timing and on Windows. | | oven-sh#43455 (`req.complete`, nine flows) | Partially addressed. Flows 1, 2, 3, 5 and 7 are fixed, and flow 6 was already right. Flow 8 (a socket timeout while the body of an Upgrade request arrives) and flow 9 (a request that `stream.pipeline()` destroyed never reports `complete`) are not. Flow 4 differs only in `_readableState.ended`. | ### What changes for users | Area | Before | After (same as Node) | | --- | --- | --- | | `req.pause()` | The socket stops at once. `req.complete` stays `false` for a small body. | The body is received until the buffer is full. Then the socket stops. | | `res.end()` before the body arrives | `req` gets `'end'` and `'close'` at once, and the body is lost | The request completes when its body really ends | | `res.destroy()` in the middle of a body | `'end'` with bytes missing | `aborted`, then `ECONNRESET` | | `socket.destroy()` inside the `'request'` listener | The body that came with the head is dropped | That body is still delivered | | `'finish'` and the `end()` callback | Fire when `end()` buffers the bytes | Fire when the last bytes have left the socket | | A response that closes the connection | The server half-closes and waits for the peer | The socket closes right behind the FIN | | `'drain'` after a later write flushed the backlog | Lost. `pipe(res)` could hang. | Emitted | | A pipelined request whose body continues after the previous response ends | Body dropped, no response, `server.close()` hangs | Delivered | | CONNECT and Upgrade tunnel sockets | Keep reading when paused or full | Stop reading. `_read()` starts them again. | | A tunnel write that waits for a drain when the client goes away | Its callback, the callbacks of the writes behind it and the `end()` callback never run | They run with an error before `'close'` | | Upgrade request with a body, paused in its listener | The body flows away | The request keeps its body | | `ws` on a reused keep-alive socket | Writes after the Upgrade could stall | Sent | | A raw `socket.write()` behind a response that still drains (the 400 for a bad pipelined request, the reply of a `'clientError'` listener) | Lands in the middle of that response | Sent after it | | `server.close()` | Could report closed while connections were open | Waits for every connection. An idle tunnel does not keep the process alive. | | `closeAllConnections()` on a listening server | Also stops the listener and destroys tunnels and WebSockets | Destroys only the HTTP connections | | `Proxy-Connection: close` (node:http only) | Ignored. The connection stays open. | Ends the connection, like `Connection: close` | | A response larger than 16 KB, also in `Bun.serve` and over TLS | Up to 4 `send()` calls for each chunk. Slower than Node in most cases. | One write for the writes of one tick. 1.1x to 2.7x the requests per second of main, and faster than Node. | | `socket.destroy()` and then `res.end()` in a listener | (this PR, earlier) `req` ended as if it were complete | `'aborted'`, then `ECONNRESET` | | `emit('connection')` or http2 `allowHTTP1`: the response ends while the listener still reads the body | The rest of the body is dropped | The body is complete | | `httpValidation: "relaxed"`, `Content-Length` or `Transfer-Encoding` in trailers | Accepted | `HPE_INVALID_CONTENT_LENGTH`, `HPE_INVALID_TRANSFER_ENCODING` | | `req.complete` inside `'connect'`, and inside `'upgrade'` without a body | `false` | `true` | | `optimizeEmptyRequests`: `socket.parser.incoming` after the response | Keeps the request alive on an idle connection | `null` | | A HEAD or OPTIONS request with `Content-Length` | The body is dropped, and `req.complete` is `true` before it comes | The request has its body | | `res.end(chunk)` after the client went away | `finished` and `writableEnded` stay `false`, no `'prefinish'` | The response ends | | An HTTP/1.0 request with an `Expect` header | `100 Continue`, `'checkContinue'`, `'checkExpectation'` or a 417 | A plain `'request'` | | The idle sweep of `close()` and `closeIdleConnections()` | Could destroy a connection that was still receiving a request, or whose response was still draining | Closes only idle connections | ### Design | Piece | What it is | | --- | --- | | Request body state | `None / Pending / Complete / Aborted / Upgraded / Detached`. Only the last chunk sets `Complete`. One function, `leave_pending`, is the only other way out of `Pending`. | | Read flow control | One path: `push()` returning false stops the socket, `_read()` starts it. Both native pause buffers are removed: no read is copied and replayed. | | "This read is parsed" signal | `notifyWhenReadParsed()` sets a uws state bit. uws delivers a `readParsed` event after the read. It replaces a `setImmediate`. | | Close during a parse | One uws bit defers a close to the end of the current message. | | Response finish | A response is finished when it has ended and the socket has fully drained. | | Idle connection | One rule, `HttpResponse::closeIfIdle()`. A connection is idle when it receives no request (head or body) and no response is in flight, queued or undrained. The sweep of `close()` and `closeIdleConnections()` both use it. | | Idle tunnel | A tunnel at read EOF with nothing left to send. uws reports it to the server through the connection filter (`-3`, `+3`, `-4`). It still counts for `'close'`, but it does not hold the event loop, like a libuv handle in that state. | | Server `'close'` | One native close promise per `listen()`. `close()` records whether its sweep left nothing open. Then a `listen()` in the same tick cannot hold `'close'` back, as in `net.Server._emitCloseIfDrained`. | | Raw socket writes | While uws holds response bytes (its buffer, the zero-copy tail of a `res.write()`, the cork buffer), a raw write goes through `AsyncSocket::write`, the path a 1xx line takes. So the order on the wire is the order of the calls. | | Upgrade verdict | One scanner and one verdict, shared by the parser and the dispatcher. | | llhttp | Updated from 9.3.0 to 9.4.2, as Node v26.5.0 vendors it, plus one local patch (see below). Node v26.5.1 and later vendor 9.4.3. That update is not in this PR. | The parser changes also tighten request framing so that it agrees with llhttp in more cases. There is no new API surface. ### A pause holds from the next read The copy of the rest of a read (`nodeHttpPausedSpill`), its replay from a posted task and the nested parse are removed. Like in Node, the rest of the read that caused a pause is still parsed, and the socket stops at the next read. usockets reads up to 512 KB in one call. libuv reads 64 KB. | One paused, unread request (client sends 64 MB) | Bytes held | | --- | --- | | Node 25.6 | 131,018 | | This pull request | 524,234 | The price is in one case. A client sends 512 KB of small pipelined requests (19,418 of them) and never reads. Each handler answers with its own 64 KB body: | Handler | Runtime | Requests dispatched | RSS | | --- | --- | --- | --- | | Answers at once | Node 26.3 | 2,425 | +177 MB | | Answers at once | main | 41 | +9 MB | | Answers at once | This PR | 2,425 | +171 MB | | Answers one tick later | Node 26.3 | 4,850 | +336 MB | | Answers one tick later | main | 2,426 | +181 MB | | Answers one tick later | This PR | 4,850 | +330 MB | Release builds on Linux x64. This PR now does what Node does. main held fewer responses, mostly for a handler that answers at once. On macOS one read can return all 512 KB. There, Bun 1.4.3 already reached +951 MB for the handler that answers one tick later, and Node reached +1,294 MB. `server.maxRequestsPerSocket` bounds it. ### Performance #### Responses larger than 16 KB are faster, and now faster than Node On main, a response that did not fit the 16 KB uWS cork buffer released the cork. After that, each piece was its own `send()`: the buffered head, the chunk-size line, the data, the `\r\n` and the last chunk. Over TLS, each 2-byte piece was also its own record. Two changes fix that, for `Bun.serve` and for node:http: | Change | Effect | | --- | --- | | A write that does not fit goes out with the cork buffer and its framing in one vectored write | No copy is added. Over TLS, the records of all the pieces share the write batch that one `SSL_write` loop already had. | | The cork buffer holds 128 KB, up from 16 KB. Only a write of 16 KB or less is copied into it, as before. | Several writes in one tick go out in one write, like in Node. A longer write still goes out without a copy. | The bytes on the wire are the same. The vectored write uses `sendmsg()` with the flags that `send()` uses. Write syscalls for one response: | Response | Node 26.3 | main | This PR | | --- | --- | --- | --- | | 4 x `res.write(16 KB)` | 1 | 16 | 1 | | 40 x `res.write(2 KB)` | 1 | 16 | 1 | | `res.end(64 KB)` | 1 | 2 | 1 | | 256 KB file, `.pipe(res)` | 4 | 16 | 5 | Throughput (req/s, the mean of 2 rounds). Node v26.3.0, main `97246d044e`, this PR `fe0ed1fbea`, with the method below: | Case | Node | main | This PR | main / Node | PR / Node | PR / main | | --- | --- | --- | --- | --- | --- | --- | | http, 4 x `res.write(16 KB)` | 17,735 | 6,983 | 19,160 | 0.39x | 1.08x | 2.74x | | https, 4 x `res.write(16 KB)` | 11,720 | 6,110 | 15,510 | 0.52x | 1.32x | 2.54x | | http, 40 x `res.write(2 KB)` | 9,879 | 6,140 | 14,980 | 0.62x | 1.52x | 2.44x | | https, 40 x `res.write(2 KB)` | 6,981 | 5,541 | 11,780 | 0.79x | 1.69x | 2.13x | | http, `res.end(64 KB)` | 18,535 | 16,528 | 19,889 | 0.89x | 1.07x | 1.20x | | http, 256 KB file `.pipe(res)` | 2,684 | 2,375 | 2,719 | 0.88x | 1.01x | 1.15x | | https, `res.end(64 KB)` | 11,894 | 14,586 | 16,426 | 1.23x | 1.38x | 1.13x | | http, GET hello (control) | 55,994 | 70,989 | 71,958 | 1.27x | 1.29x | 1.01x | main was slower than Node in six of these eight cases. This PR is faster than Node in all eight. `Bun.serve`, measured on `a771572a8d`, before the larger cork buffer (req/s, the mean of 2 rounds): | Case | main | PR | Change | | --- | --- | --- | --- | | Direct stream, 4 x 16 KB | 6,826 | 12,479 | +83% | | 64 KB string | 16,944 | 20,145 | +19% | | TLS, 64 KB string | 15,045 | 16,892 | +12% | | hello (control) | 83,957 | 83,137 | -1.0% | These runs are on loopback, where the kernel send buffer is 2.6 MB and the work of the receiver runs inside `send()`. That is the best case for fewer writes. A new connection over a real network takes about 46 KB in its first write on Linux. The rest waits in the socket buffer, as it would after separate writes. #### Small responses are unchanged A small response is already one `recvfrom` and one `sendto` on both builds. `perf` puts 66% of the time of a hello-world server in the kernel, on both builds. CI release builds on Linux x64: main `97246d044e` (the merge base) against this PR `8834cd0787`. Both use the same WebKit. The server runs on one pinned core. `oha` sends 64 connections for 5 s after a 2 s warm-up. There are 2 rounds, and the order of the builds alternates. "Change" compares the means of the two rounds. Framework servers from `bun-perf-tester` (req/s): | Server | main, round 1 | main, round 2 | PR, round 1 | PR, round 2 | Change | | --- | --- | --- | --- | --- | --- | | express | 49,803 | 51,103 | 49,968 | 50,263 | -0.7% | | fastify | 61,214 | 61,105 | 60,705 | 60,668 | -0.8% | | node:http | 70,934 | 71,405 | 73,178 | 71,053 | +1.3% | | elysia | 84,696 | 85,096 | 85,027 | 84,882 | +0.1% | | `Bun.serve` | 89,020 | 89,099 | 88,168 | 88,373 | -0.9% | node:http paths that this PR changes (req/s): | Case | main, round 1 | main, round 2 | PR, round 1 | PR, round 2 | Change | | --- | --- | --- | --- | --- | --- | | GET hello | 70,226 | 70,341 | 70,151 | 72,359 | +1.4% | | POST, 16 KB body | 47,446 | 47,789 | 48,191 | 48,785 | +1.8% | | 64 KB response in four writes | 6,885 | 6,894 | 6,834 | 6,868 | -0.6% | | Pipelined keep-alive, depth 8 | 94,063 | 93,294 | 92,909 | 93,809 | -0.3% | p99 latency (ms), the higher of the two rounds: | Server | main | PR | | --- | --- | --- | | express | 1.94 | 1.91 | | fastify | 1.52 | 1.55 | | node:http | 1.11 | 1.12 | | elysia | 0.98 | 0.96 | | `Bun.serve` | 0.82 | 0.83 | RSS (MB), one pass of 8 s of load: | Server | Build | Start | Under load | 5 s idle | 15 s idle | | --- | --- | --- | --- | --- | --- | | express | main | 39 | 94 | 61 | 57 | | express | PR | 40 | 92 | 60 | 57 | | fastify | main | 41 | 91 | 58 | 55 | | fastify | PR | 41 | 91 | 58 | 55 | | node:http | main | 20 | 64 | 43 | 40 | | node:http | PR | 20 | 65 | 45 | 41 | | elysia | main | 28 | 46 | 36 | 35 | | elysia | PR | 29 | 46 | 37 | 36 | | `Bun.serve` | main | 14 | 30 | 22 | 22 | | `Bun.serve` | PR | 14 | 30 | 22 | 22 | Every change is within 2%. fastify and `Bun.serve` hello are lower in both rounds, by about 1%. `Bun.serve` hello shows the same -1.0% in the control row above, so a small real cost there is possible. The RSS pass ran at the same time as the throughput runs, on other cores. The commits after `8834cd0787` change tests and add one version check to the node:http dispatcher. They were not measured. ### Supersedes | Theme | Pull requests | | --- | --- | | Request body | oven-sh#43592 oven-sh#43579 oven-sh#38196 oven-sh#43518 oven-sh#43602 oven-sh#43408 oven-sh#43427 oven-sh#43597 oven-sh#43555 oven-sh#43456 oven-sh#43466 | | Tunnels | oven-sh#43570 oven-sh#43485. oven-sh#43596 is a duplicate of oven-sh#43570. | | Parser | oven-sh#43182 oven-sh#43161 oven-sh#43326 oven-sh#43327 oven-sh#40505 oven-sh#43363 oven-sh#42532 oven-sh#42194 | | Response write | oven-sh#39386 oven-sh#43371 oven-sh#43548 oven-sh#43499 oven-sh#43496 oven-sh#43464 oven-sh#42008 oven-sh#43549 | | Response finish | oven-sh#40351 oven-sh#43021 oven-sh#41822 oven-sh#43473 oven-sh#42068 oven-sh#35207 oven-sh#43425 oven-sh#43503 | | Lifecycle | oven-sh#43413 oven-sh#39686 oven-sh#43028 oven-sh#42727 oven-sh#42622 oven-sh#42610 oven-sh#35837 oven-sh#35839 oven-sh#37825 oven-sh#37749 oven-sh#43376 oven-sh#35268 | | JS API | oven-sh#41691 oven-sh#41738 oven-sh#38036 oven-sh#42462 oven-sh#36527 oven-sh#39718 oven-sh#37964. oven-sh#42947 merged on its own. | The close drain, `resetAndDestroy()`, the pending write callback handling and the response `'close'` ordering come from oven-sh#42622 and oven-sh#42727 by @steipete. The diagnosis and the tests for the stalled `ws` writes come from his oven-sh#42610. Not included: | Pull request | Reason | | --- | --- | | oven-sh#33061 | main already enforces `headersTimeout` and `requestTimeout` | | oven-sh#41672 | It makes `http.createServer({ key, cert })` stop serving TLS. That needs a product decision. | | oven-sh#37543 | A type refactor with no tests and no user-visible change | | oven-sh#35465 | It makes `http.Server` extend `net.Server`. Only the prototype chains were joined. The `net.Server` constructor never ran, so `_handle` and `_connections` were `undefined`, and `_emitCloseIfDrained()` emitted `'close'` on a listening server. The server is backed by uWS, not `node:net`. | | The `AutoFlusher` removal in oven-sh#42622 | It makes `flushHeaders()` flush at once. That is a performance change with no relation to the rest. | ### Tests | Check | Result on a debug build (macOS arm64) | Head | | --- | --- | --- | | Every test file that this PR touches (28 files) | 1,866 pass, 2 fail. The 2 failures are `serve.test.ts` "bounds memory when proxying ... to a stalled client". They fail the same way on a debug build of main. | `83af4da4a3`, run before the last commit of main came in | | `test/js/third_party/express` (9 files) and the `body-parser` test | 299 pass, 0 fail | `83af4da4a3`, run before the last commit of main came in | | Node 25.6 against Bun, 32 scenarios from two scripts (event order, framing, lifecycle) | No regression against Bun 1.4.3 | `0ff1a23f61` | | Every vendored Node `test-http-*` and `test-https-*` file, plus the `test-net-*` and `test-tls-*` files for pause, write, end and close | 535 of 537 exit 0. `test-http-agent-keepalive.js` and `test-https-timeout.js` fail on that debug build. Both pass on every CI lane. | `daee05fcfd` (before the rebase) | | The tests that depend on what the kernel takes in one send, on Windows Server 2019 x64 and Windows 11 arm64 | pass | `3eef223328` (x64), `a29289bcc1` (arm64) | | CI build 120191 (Linux, macOS and Windows, release and ASAN) | every lane passed | `daee05fcfd` (before the rebase) | Each new test fails on Bun 1.4.3, or on the commit before its fix for a fault that this branch introduced. The two tests over the limit are `node-http-connect.test.ts` ("tests should run on bun") and `node-http-syscall-fault.test.ts` ("racing a queued drain"). Each starts a debug subprocess that needs more than 5 s on this machine. Both pass on CI. ### Changes in the last push The branch is rebased on main (`daee05fcfd` was the head before). It is now linear. Four regressions against main, each with a test that fails without its fix: | Case | main | Before this push | Now (same as Node) | | --- | --- | --- | --- | | `emit('connection')` or http2 `allowHTTP1`: `res.end()` on a request that nobody reads | `'end'`, `'close'` | No events | `'end'`, `'close'` | | The same server, an unread 32 MB body | 0 bytes held | 32 MB held | 0 bytes held | | A NUL in a header value with `httpValidation: "relaxed"` (client, `HTTPParser`, `emit('connection')` server) | Accepted | The process spins forever | `HPE_INVALID_HEADER_TOKEN` | | `Connection: close`, body in the same read as the head, a 20 KB response before the body is read | `'end'` with an empty body | No events on `req` | `'end'` with the body, `'close'` | | An empty line on an idle keep-alive connection, then `server.close()` | 0 s | About 6 s | 0 s | | Fix | Where | | --- | --- | | The finish listener of a fallback connection dumps an unread request, like Node's `resOnFinish` | `http1_server_fallback.ts` | | llhttp patch: `llhttp__internal__c_test_lenient_flags_20` is false for a NUL. The relaxed state does not consume a NUL, and the next state sent it back there. 9.4.3 has the same loop. | `llhttp.c`, noted in its `README.md` | | A node:http socket that `onData` is parsing gets the close gate of `onData`, also when a large write released the cork | `HttpResponse.h` `uncorkCompletedResponse()` | | A read that starts no message leaves an idle connection idle | `HttpContext.h` `onData` | The open review threads are fixed in `8834cd0787`: `closeAllConnections()`, `Proxy-Connection: close`, five comments cut to one line, and the test of two overlapping listeners, which now waits on events. With the generation gate in `emitCloseServer` removed, that test fails in both cases. `AsyncSocketData` keeps its bools together, which takes it from 56 to 48 bytes per socket. `http.Server` no longer extends `net.Server` (see "Not included"). The special case for it in `Ipc.ts` is gone too. `child.send(msg, httpServer)` still throws `ERR_INVALID_HANDLE_TYPE`, and its test stays. <details><summary>Changes since the first revision (2988a61)</summary> Merged with main at `c8e1f6fa5b`. The one conflict was oven-sh#43708 (`req.socket` emits `'end'` and `'error'`). Its state bit `HTTP_NODE_PEER_ENDED` moved to bit 22, because bit 19 is `HTTP_NODE_NOTIFY_READ_PARSED` here. Its 15 tests run in `node-http-server-abort-events.test.ts` next to the tests of this branch (103 pass). CI on `2988a610c` had ten red tests from four causes. They are fixed: - `ed882e5e99`: `write()` to a response without a body (HEAD, 204) does not wait for unsent bytes. - `811f817704`: an idle tunnel does not hold the event loop after `server.close()`. Four vendored Node tests timed out on every platform. - `0697deec11`, `d428824c08`, `7aec062d14`: the write callback tests use a body that backs up a loopback socket, and accept what Winsock does. - `c7af1c1615`: two tests from main asserted the old `close()` contract. Review findings, each reproduced against Node v26.3.0 and fixed with a test that fails without the fix: - `d4d2b783ea`, `2cc79939bb`, `45141abca9`, `9a63dbc470`, `80a23a1822`: the idle rule. A keep-alive connection is idle again when its body ends after its response. A connection that owes a queued pipelined response, that still receives a request head or body, or whose response still drains is not idle. - `87d8904aa3`, `7eca4f7806`: `close(cb)` followed by `listen()` in the same tick reports `'close'`, also for an https server whose only connection was idle. - `3fd7b25382`: a paused pipelined request behind a response that still drains stops the connection. The first revision read 512 MiB of 512 MiB into memory. - `2d1a5e2d8d`, `33e4683a8a`, `539cb41eb9`, `197c7dfc29`, `0490e3540b`: raw socket writes stay behind every unsent response byte. The cases were a CONNECT pipelined behind a response that still drains (its `200` landed at offset 2.6 MB of a 64 MiB body), a zero-length tunnel write (it hung the tunnel), the 400 replies above, the zero-copy tail of a large `res.write()`, the cork buffer, and Windows 11, where the kernel takes the whole response and refuses the next send. - `0abd39c133`: an upgrade from the request's `'end'` listener keeps the body bytes out of the WebSocket. The connection closed with 1006 right after the 101. - `5aafc61aa6`: the callback of a small `res.write()` that the kernel refuses at the uncork runs on the drain. Reproduced on Windows 11 only. - `a29289bcc1`: a tunnel write that waits for a drain settles its callbacks when the connection closes. Known differences from Node that this PR leaves: - A handler that calls `res.end()` and then `server.close()` closes its keep-alive connection at once. Node waits for the `keepAliveTimeout`. - A pipelined Upgrade behind a response that still drains is served as a plain request. - An `end()` on a tunnel with no write pending, while the response before the CONNECT still drains, closes both directions after the flush. Node half-closes. - A raw `req.socket.write(big)` and `req.socket.end()` with no `res.end()` sends every byte but no FIN. main loses bytes here. - A CONNECT socket that is given back with `server.emit('connection', socket)` answers only the first of several pipelined requests. main answers none. - A large write from an `'upgrade'` listener stalls while the body of that Upgrade request is still pending. A second `listen()` on a listening server does not throw. Both are the same on main. - A tunnel write that fails because the client went away fails its callbacks but emits no `'error'`. Node emits `ECONNRESET`. A new `'error'` could end a process that has no listener for it. </details> <!-- robobun:evidence:begin --> --- **no test proof** · iteration 8 · platform-specific test(s) that do not run on this machine, deferring to CI, which covers all platforms: test/js/web/fetch/fetch.stream.test.ts, test/js/node/url/url.test.ts, test/js/node/tls/tls-syscall-fault.test.ts, test/js/node/net/node-net-server.test.ts, test/js/node/http/node-http.test.ts, test/js/node/http/node-http-syscall-fault.test.ts, test/js/node/http/node-http-server-close-drain.test.ts, test/js/node/http/node-http-connect.test.ts, test/js/node/http/node-http-backpressure.test.ts, test/js/node/child_process/child_process_ipc_handle.test.ts, test/js/bun/http/serve.test.ts, test/js/bun/http/serve-syscall-fault.test.ts, test/js/bun/http/bun-server.test.ts <!-- robobun:evidence:end --> --------- Co-authored-by: Jarred Sumner <[email protected]> Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
… and the CI pipeline script (oven-sh#43976) Behaviour change: none ### Problem - Eleven files hold items that nothing reads or calls: write-only fields, an uncalled method, four unused types, and CI options that are parsed and dropped. - No tool reports them. C and C++ have no dead-code lint. TypeScript counts `x += n` as a read. The Rust types come from a macro. ### Fix - TypeScript: remove `DataViewReader.u16()`, `DataViewWriter.capacity`, the `totalCount` local in `updateBuildErrorOverlay`, and a commented-out block from 2024 in `src/js/node/dgram.ts`. - C and C++: remove `us_udp_socket_t.connected`, `us_quic_stream_s.headers_delivered` and `Http2ResponseData::totalSize` (each is only written), and `#undef FD_BITS` (nothing defines it). - Rust and CI: remove the opaque types `us_loop_t`, `us_socket_context_t`, `us_udp_socket_t`, `us_udp_packet_buffer_t` from `src/uws_sys/lib.rs`. In `.buildkite/ci.ts`, remove `dryRun`, `Platform.features`, four emoji entries, and the union members `"amazonlinux"` and `"eol"`. - Verified: `rg -w` for each symbol over `src`, `packages`, `scripts`, `test` and `build/debug/codegen` finds no other use. `bun bd`, `bun run rust:check-all` (12 targets) and `tsc` pass. Self-reviewed: 1 concern raised, 1 addressed. ### Background - `DataViewReader` and `DataViewWriter` decode and encode the binary messages between the dev server and its browser client. - `us_udp_socket_t` and `us_quic_stream_s` are private C structs of uSockets. Rust holds them as opaque pointers, so no Rust struct mirrors their layout. - `bun_core::opaque_extern!` declares a zero-sized Rust type for a C struct. Rust code names `Loop`, `udp::Socket` and `udp::PacketBuffer`, not the four removed types. ### Downsides - None found. Checked each removed symbol for users in Rust, C, C++, TypeScript, generated code, tests, and open pull requests. <details><summary>Notes</summary> **Evidence per removal** | Item | Evidence | | --- | --- | | `DataViewReader.u16()` | `rg '\.u16\('` over `src/runtime/bake`, `test/bake`, `test/cli/inspect`: no hit. | | `DataViewWriter.capacity` | The only hit of `.capacity` in the bake TypeScript is the assignment in the constructor. `initCapacity` is the only caller of the constructor. | | `totalCount` | Two hits: the declaration and one `+=`. | | `dgram.ts` block | `git blame`: 589f941, 2024-04-26. `replaceHandle` and `startListening` are not defined in the file. | | `us_udp_socket_t.connected` | Two hits, both `udp->connected = 0;`. | | `us_quic_stream_s.headers_delivered` | Two hits in `quic.c`: the field and one `= 1`. The struct is private to `quic.c`. | | `Http2ResponseData::totalSize` | One member access: `data.totalSize = totalSize;`. The other hits of `totalSize` are the function parameter. | | `#undef FD_BITS` | The only hit of `FD_BITS` in `src` and `packages`. | | Four opaque types | Each name has one non-comment hit in all Rust sources and generated Rust: the macro call. | | `dryRun` | Four hits in `ci.ts`: the field, two assignments, one destructure. Nothing reads the binding. | | `Platform.features` | One hit. | | Emoji, `Distro`, `Tier` entries | No platform in `ci.ts` or image in `scripts/build/ci-images/spec.ts` carries them. `Emoji` is `keyof typeof emojiMap`, so a remaining caller would fail `tsc -p scripts/tsconfig.json`. It passes. | **Taken out because an open pull request uses or removes the item** - `DataViewWriter.u8()`: dead on main, but oven-sh#42075 adds its first caller (`check.u8(IncomingMessageId.check_errors)` in `hmr-runtime-error.ts`). Git merges the two without a conflict, so the method stays. The tree that results from a merge of this branch with oven-sh#42075 has no type error for `u8`. - `declare module "bun:wrap"` in `bake.private.d.ts`: no importer, but oven-sh#39488 already has the same hunk. **Tests run with the debug build, all pass** `test/js/bun/udp/udp_socket.test.ts` (218), `test/js/bun/udp/dgram.test.ts` (62), `test/js/bun/http/serve-http2.test.ts` (93), `test/js/bun/http/serve-http3.test.ts` (73), `test/bake/dev/bundle.test.ts` (23), `test/bake/dev/esm.test.ts` (17), `test/bake/hmr-socket-protocol.test.ts` (4), `test/cli/inspect/BunFrontendDevServer.test.ts` (7). `test/js/node/dgram/node-dgram.test.js` passes 3 of 4: the IPv6 multicast test fails with `ENODEV` in the test container, with and without this change. `prettier` and `cargo fmt --check` report no change. **Overlap with open pull requests** Each removed line was compared with the diffs of the 35 open dead-code pull requests. None removes the same lines. Five files are also touched by an open pull request, in hunks more than 6 lines away: `internal.h` and `quic.c` (oven-sh#40294, oven-sh#42431), `dgram.ts` (oven-sh#42431), `overlay.ts` (oven-sh#43378, oven-sh#42075, oven-sh#39488), `src/uws_sys/lib.rs` (oven-sh#43010). The added lines of the 122 open pull requests that were updated since 2026-09-18 and touch the bake, uSockets, uWS, uws_sys, server, socket or CI sources name none of the removed symbols. **What was scanned** - C and C++: the debug binary was linked a second time with `--gc-sections`, and the two symbol tables were compared. 414 functions in bun's own C and C++ are unreachable on Linux. Open pull requests remove 263 of them. The remainder is in the list below, has a caller on Windows or macOS, or comes from a macro. - Rust: 37 `#[no_mangle]` exports are unreachable in the Linux link. Each has a caller on another platform, or oven-sh#40824, oven-sh#40232 or oven-sh#40557 removes it. A count of references for all 58,055 Rust definitions found no other item without a user. Of the 144 `allow` attributes for the unused and unreachable lints, each covers code that depends on `cfg` or is macro output. - Cargo: five dependency edges are unused on all 12 targets. oven-sh#40294 removes three. `bun_resolver -> bun_zstd` is used under `cfg(bun_codegen_embed)`. `bun_wyhash -> bstr` is used by unit tests. - Preprocessor: `USE(BIGINT32)` and `ENABLE(MALLOC_BREAKDOWN)` are never true. oven-sh#43644 and oven-sh#40557 remove those branches. - Also scanned and clean: `src/js`, `src/node-fallbacks`, `src/codegen`, `scripts/`, `misctools/`, `patches/` (every patch file has a user), `packages/` except `bun-types`. **Probably dead, left alone on purpose** - The `PerformanceResourceTiming` cluster under `src/jsc/bindings/webcore` (about 2,000 lines: `PerformanceResourceTiming`, `PerformanceServerTiming`, `ResourceTiming`, `NetworkLoadMetrics`, `ResourceLoadTiming`, `ServerTiming` and the two JS wrappers). The linker drops every constructor, so no instance can exist. The two globals are public and `test/js/web/web-globals.test.js` checks them. This needs a decision: keep it for a future resource-timing implementation, or reduce it to the two constructors. - `WEBCORE_GENERATED_CONSTRUCTOR_GETTER` (`ZigGlobalObject.cpp`) emits an `X_getter` function for 50 classes. 45 have no user. A removal needs a second macro and saves no source lines. - The WebIDL converters for `byte`, `short` and `long long`, and most `Clamp` and `EnforceRange` specializations in `JSDOMConvertNumbers.cpp`. No binding uses them, but `src/codegen/bindgen.ts` maps `t.i8`, `t.i16` and `t.i64` to them. - `src/js/bun/sql.ts`: the export properties `sql`, `Query`, `postgres` and the four error classes. Native code reads only `default` and `SQL`. It is not certain that no loader path exposes the module object. - `us_nq_settings_set_scid_len` and `us_nq_settings_set_delay_onclose` (`node_quic_shim.c`, declared in `src/lsquic_sys/lib.rs`): no caller. `node:quic` is under active work. - `Event::currentTargetIsInShadowTree()` and its bit: no reader. The lines sit next to a hunk of oven-sh#39929. - Bake client: `WebSocketWrapper.close()` and `[Symbol.dispose]()`, `streamingStarted`, the `line` and `column` bookkeeping and seven enum members in `JavaScriptSyntaxHighlighter.ts`, and `externals` in `src/node-fallbacks/build-fallbacks.ts`. Each sits next to a hunk of oven-sh#43378, oven-sh#40492, oven-sh#40122 or oven-sh#41385. - The `internal: true` property option of the class generator. A guard throws on it, so the branches behind it cannot run. Five open pull requests touch `generate-classes.ts`. - `H2App::getNativeHandle` (next to a hunk of oven-sh#41195) and `uws_app_listen_config_t` (its last user goes with oven-sh#42431). - `UWS_ALLOW_SHARED_AND_DEDICATED_COMPRESSOR_MIX`, `UWS_ALLOW_8_WINDOW_BITS` and `LIBUS_NO_SSL`: never defined, but they are documented opt-in switches of the upstream libraries. - `scripts/debug-coredump.ts`, `scripts/gamble.ts`, `scripts/github-metrics.ts`, `scripts/lldb-inline.sh` with `scripts/lldb-inline-tool.cpp`, and `packages/h3blast`: nothing references them. They read as tools that a person runs by hand. - oven-sh#40232 removes `napi_internal_get_version`. oven-sh#42556 renamed that function to `Bun__napi_get_version` on main, and it still has no caller. </details>
…n-sh#44054) ### Problem - `test/js/bun/s3/s3.test.ts` fails on each Linux x64 lane of main: `Failed to start service minio`, `failed to resolve reference "quay.io/minio/minio:latest"`, `401 Unauthorized` (build 120898). MinIO removed its images. - 306 of its tests need that container, so macOS, Windows and Linux arm64 never ran them. ### Fix - Add `test/packages/s3-server`: an S3 server on `Bun.serve` with no dependencies and the data in memory. It verifies each signature and answers like Amazon S3. - `s3.test.ts` starts it as a child process with the region `us-east-1`. The `minio` service is gone from the docker files and `harness.ts`. - Verified: `s3.test.ts` and `test/packages/s3-server/test/` (2056 tests), with `bun bd test` on Linux x64 and a release build on Windows x64. Also the AWS signature examples and 33 operations of the AWS SDK for JavaScript. ### Background - AWS Signature Version 4 is an HMAC-SHA256 over a canonical form of the request. The server builds the same form to check it. - oven-sh#44041 keeps MinIO and builds it from source in each machine image. This PR removes the service. - Considered the server in the process of `s3.test.ts`: it would share the thread with the client under test, for 1.3 GiB of uploads. ### Downsides - The 306 tests now run on each lane: 4.9 s for the file on Windows x64 (16 vCPU, release build, no R2 tests). - The server is an emulation. The Notes list each behaviour that no reference confirms. - `Bun.serve` removes `.` and `..` path segments, so a key with such a segment cannot be used. <details><summary>Notes</summary> **How to use it** ```ts import { serve, spawnServer, SigningClient } from "s3-server"; await using server = serve({ buckets: ["my-bucket"] }); // in the process of the test const client = new Bun.S3Client(server.clientOptions("my-bucket")); ``` - `serve()` runs the server in the process of the test. `spawnServer()` runs `cli.ts` in a child process. It has a deadline for the start, and the program sends the common requests to a second server before it reports its address. The child process stops when the caller calls `stop()` or ends. - `S3Server.fetch` is the server as a function. A test can put its own `Bun.serve` in front of it to inject a fault. - `server.requests` has the operation name, the status and the error code of each request. - `SigningClient` sends signed requests for operations that `Bun.S3Client` has no method for. - Options: `credentials` (more than one account), `region`, `domains`, `buckets` (each with its region, versioning and owner), `clock`, `tls`. - With the `region` option the server refuses a signature for another region. `s3.test.ts` uses it, so each of its requests must sign for `us-east-1`. The 1537 requests of the file have the same outcomes with and without the option. - The server does not share its port. A second server on a port that is in use gets `EADDRINUSE`. **Operations** - Service and bucket: ListBuckets, CreateBucket, HeadBucket, DeleteBucket, GetBucketLocation, ListObjects, ListObjectsV2, ListObjectVersions, ListMultipartUploads. - Object: PutObject, GetObject, HeadObject, DeleteObject, DeleteObjects, CopyObject, PostObject, GetObjectAttributes, RestoreObject, tagging, ACL, retention, legal hold. - Multipart: CreateMultipartUpload, UploadPart, UploadPartCopy, CompleteMultipartUpload, AbortMultipartUpload, ListParts. - Configuration with an effect: versioning, ACL, policy, CORS, tagging, request payment, ownership controls, public access block, object lock. - Configuration that the server only keeps: lifecycle, encryption, website, notification, logging, replication, accelerate. - Each other operation gets the error `NotImplemented`. **What was verified, and how** - The SigV4 examples of the AWS documentation, sent as HTTP requests with a fixed clock: 4 header signatures, 1 presigned URL, the chunked upload (seed and 3 chunk signatures), the signed trailer example, and the POST policy example. Each signature matches to the byte. - CRC32, CRC32C and CRC64NVME give the standard check values for `123456789`. - The AWS SDK for JavaScript 3.1141.0 ran against the server in scripts that are not in this PR: 33 operations of `@aws-sdk/client-s3`, `Upload` of `@aws-sdk/lib-storage` with 8 checksum settings, `getSignedUrl`, and `createPresignedPost`. - The S3 API model of the AWS SDK gave the names of headers, parameters and elements. The Ceph `s3-tests` suite gave expected status and error codes. - The tests of the package pass under `bun bd test`, also with the settings of the ASAN lane (`BUN_JSC_validateExceptionChecks=1`, `detect_leaks=1`, `BUN_DESTRUCT_VM_ON_EXIT=1`). - `s3.test.ts` passes under `bun bd test` with `--timeout=270000`, the per-test timeout of the ASAN lane. With the default of 5 s, the two tests that start a debug build of Bun as a child process time out on my machine (5.5 s and 6.5 s, load average above 400). - A debug build does not run 5 of the tests: 3 compute CRC32C or CRC64NVME over 5 MiB in JavaScript, and 2 move documents of 1000 keys. The release and the ASAN lanes run them. - Buildkite builds 120967 and 120976 (the first and the third commit of this PR) passed on each lane. **Measurements** | What | Where | Result | |---|---|---| | `s3.test.ts`, 307 tests, no R2 credentials | Windows x64, 16 vCPU, release build | 4.9 s | | `test/packages/s3-server/test/`, 2056 tests | Windows x64, 16 vCPU, release build | 3.2 s | | `s3.test.ts` | Linux x64, `bun bd` (debug, ASAN), machine with a high load | 167 s | | `test/packages/s3-server/test/`, 11 files | Linux x64, `bun bd`, same machine | 38 s to 73 s for each file | | Server CPU for the upload matrix of `s3.test.ts` (75 uploads, 645 MiB) | Linux x64, release build | 1.5 s user, 1.0 s system | `test/expected-durations.json` has 6.7 s (default), 20.1 s (asan) and 6.4 s (windows) for `s3.test.ts` before this change. The Linux machine of these measurements had a load average above 400, so its wall times are an upper limit. **Behaviour that no reference confirms** The server follows Amazon S3 where S3 and MinIO differ. For these cases the references did not agree or had nothing, and the choice is from knowledge of S3: - Signatures: the signature check comes before the clock skew and the expiry checks. `X-Amz-Expires` out of range is status 400 (`s3-tests` expects 403). `InvalidChunkSizeError` is status 403. - Objects: `If-None-Match` with an entity tag on PutObject is 501. 11 tags are `BadRequest` (`s3-tests`: `InvalidTag`). A `partNumber` above the count is 416 `InvalidPartNumber` (`s3-tests`: 400 `InvalidPart`). A read with the wrong SSE-C key is 403 (`s3-tests`: 400). - Multipart: a repeated CompleteMultipartUpload answers 200 while the object is there. The `Last-Modified` of the object is the time when the upload started. DeleteBucket removes a bucket that has only uploads in progress. - Lists: `encoding-type=url` writes a space as `+` (`s3-tests`: `%20`). An empty continuation token is `InvalidArgument` (`s3-tests`: a normal list). - Buckets and access: GetBucketPolicyStatus without a policy is 404 (`s3-tests`: 200). A grant for an email address is 405. An anonymous ListBuckets is 403, and S3 sends a redirect. - PostObject: a body that is not `multipart/form-data` is 412. A checksum field needs a condition in the policy (`s3-tests`: accepted). - Regions and CORS: a preflight request for a bucket of another region gets `PermanentRedirect`. A response with `PermanentRedirect` has no CORS headers. A request with a signature that the server refuses gets the CORS headers of its bucket. **Not implemented** - Signature Version 2 and Signature Version 4A. - The default CRC64NVME checksum of an upload that has no checksum. - The `x-amz-*` query parameters of a presigned URL are part of the signature. The server does not apply them. - Lifecycle rules, replication, notifications, website hosting, MFA delete, access points, directory buckets. - A restore from an archive storage class completes immediately. - The server is one endpoint. A bucket in another region than the server gets `PermanentRedirect` and no endpoint serves it. - A new bucket has ACLs enabled and no public access block, the default of S3 until April 2023. **Found during this work, not changed here** - A debug build of Bun adds `content-type: application/octet-stream` to a `Bun.serve` response without a body. A release build does not. `src/runtime/server/RequestContext.rs:3821` compares the address of `MimeType::OTHER.value`, and `OTHER` is a `const` (`src/http_types/MimeType.rs:278`), so the two addresses are equal only when the optimizer merges them. The tests of the package remove that header (`withoutDefaultType` in `test/helpers.ts`). - `Request.url` of `Bun.serve` has no `.` and `..` segments. `node:http` of Bun gives the path as the client sent it. - `test/js/bun/s3/s3.test.ts` has a test that sends a request to `s3.us-west-1.amazonaws.com` and expects `PermanentRedirect`. It ran for MinIO and for R2. For the new server it now uses a bucket in another region and needs no internet. For R2 it is as before. </details> --------- Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
oven-sh#44072) ### Problem - `test/js/bun/console/console-write.test.ts:134` fails on macOS with `- "caught EPIPE` / `+ "caught ENOTCONN`. - The case closes the reader while the child writes 8 MB. The macOS kernel fails the write that the close lands in with `ENOTCONN`, not `EPIPE`. - oven-sh#43649 added the case and expects `EPIPE` only. Builds 121009 and 120123 were red: each attempt failed with this or with the unhandled rejection that oven-sh#43679 fixes. ### Fix - On macOS the case accepts `caught EPIPE` or `caught ENOTCONN`. Other platforms accept `caught EPIPE` only. - The case still requires a rejected promise, no other stderr output, and exit code 0. - Verified on a CI Mac (macOS 26.6.1, M2), `main` canary, 150 runs of the file. `caught ENOTCONN` fails 7 runs of the old file and 0 runs of the new file. - `bun bd test test/js/bun/console/console-write.test.ts` passes on Linux. ### Background - `Bun.spawn` gives a child with `stdout: "pipe"` one end of an AF_UNIX socketpair. - XNU `sosend()` tests for `EPIPE`, then unlocks the socket to copy the bytes. `uipc_send()` then tests "connected" first and returns `ENOTCONN`. Each later write returns `EPIPE`. - Considered a retry in `try_write_with_write_fn` (`src/io/PipeWriter.rs:84`) so that the writer reports `EPIPE`. oven-sh#40935 decided that Bun passes the kernel errno through, as Node does. Node gave `ENOTCONN` in 65 of 150 runs of this scenario. - The unhandled rejection still fails 67 of those 150 runs. With oven-sh#43679 and this PR the file passes 100 of 100 runs. <details><summary>Notes</summary> **This PR changes one test.** No file under `src/` changes. **Kernel path** (xnu-12377, `bsd/kern`): - `sosendcheck()` (`uipc_socket.c`) tests `SS_CANTSENDMORE` first and returns `EPIPE`. - `sosend()` calls `socket_unlock()` before the `uiomove` copy and `socket_lock()` after it. It calls `pru_send` with no second state test. - `uipc_send()` (`uipc_usrreq.c`, `SOCK_STREAM` branch) tests `SS_ISCONNECTED` first (`ENOTCONN`) and `SS_CANTSENDMORE` second (`EPIPE`). - `soisdisconnected()` (`uipc_socket2.c`) clears `SS_ISCONNECTED` and sets `SS_CANTSENDMORE` in one step. - `write(2)` on a socket takes the same path (`soo_write()` calls `sosend()`). **C probe, no Bun and no Node.** An 8 MB write on an AF_UNIX socketpair with 512 KB buffers. The peer reads one chunk and closes. 500 runs each. | host | macOS | non-blocking `send()` | blocking `write()` | | --- | --- | --- | --- | | M2 mini | 26.6.1 arm64 | `ENOTCONN` 141 | `ENOTCONN` 396 | | M2 Ultra | 15.7.9 arm64 | `ENOTCONN` 442 | `ENOTCONN` 392 | | Intel i7 | 14.8.9 x64 | `ENOTCONN` 1 | `ENOTCONN` 287 | | Linux x64 | | `ENOTCONN` 0 of 300 | `ENOTCONN` 0 of 200 | All other runs gave `EPIPE`. So the errno is not specific to macOS 26 or to one machine. With the default socket buffer size the M2 mini gave `EPIPE` in 500 of 500 runs. One more write directly after the `ENOTCONN` returned `EPIPE` in 1659 of 1659 runs. A socket that was never connected returns `ENOTCONN` on each write. **The scenario of the test**, on the M2 mini (macOS 26.6.1), Bun `1.4.3-canary.1+37da174d5`, Node v26.3.0: | parent | child | `EPIPE` | `ENOTCONN` | | --- | --- | --- | --- | | bun | bun, `await console.write(big)` | 63 | 137 | | bun | bun, `process.stdout.write(big, cb)` | 66 | 84 | | bun | node, `process.stdout.write(big, cb)` | 145 | 55 | | node | node, `process.stdout.write(big, cb)` | 85 | 65 | On macOS 14.8.9 x64, node parent and node child: `ENOTCONN` in 18 of 200 runs. **Runs of the test file** on the M2 mini: | binary | test file | runs | failed | failures | | --- | --- | --- | --- | --- | | `main` canary | `main` | 150 | 76 | 7 `caught ENOTCONN` (one argument), 69 unhandled rejection (several arguments) | | `main` canary | this PR | 150 | 67 | 67 unhandled rejection (several arguments) | | oven-sh#43679 (4133870) | oven-sh#43679 | 100 | 3 | 3 `caught ENOTCONN` (one argument) | | oven-sh#43679 (4133870) | oven-sh#43679 merged with this PR | 100 | 0 | | The test on `main` stays flaky on macOS until oven-sh#43679 merges. **The decision in oven-sh#40935.** An earlier revision of oven-sh#40935 folded `ENOTCONN` into `EPIPE` in `write_to_socket`. The merged commit (118fdd2) dropped the fold: "The kernel errno is passed through unchanged." Node accepts both codes on macOS in its own test (`test/js/node/test/parallel/test-cluster-concurrent-disconnect.js:27-33`). At that time the race was not reproduced (1100 runs, all `EPIPE`). The probes above reproduce it. This PR keeps the decision. **`process.platform` and not `isMacOS`.** oven-sh#43679 changes the `harness` import line of this file. The test reads `process.platform` so that the two PRs merge in either order with no conflict (checked with `git merge-tree`). **The same errno in other tests.** In the annotations of the last 60 finished builds, `ENOTCONN` appears in the output of three test files: this one, `test/js/bun/util/filesink.test.ts` (oven-sh#43794 removes the race there) and `test/js/node/process/process-stdin.test.ts` (oven-sh#42260 ignores the code on macOS). </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/bun/console/console-write.test.ts <!-- robobun:evidence:end -->
…ocess as this (oven-sh#44057) ### Problem - `process.exit()` calls `process.reallyExit(code)`, as Node.js does. When `process.reallyExit` is not callable, Bun throws a `TypeError` with an empty message. Node.js throws `TypeError: process.reallyExit is not a function`. - A build with assertions aborts: `ASSERTION FAILED: !message.isEmpty()` at `vendor/WebKit/Source/JavaScriptCore/runtime/Error.cpp(71)` in `JSC::createTypeError`. - The cause is `JSC::call(globalObject, reallyExitVal, args, ""_s)` at `src/jsc/bindings/BunProcess.cpp:913`. The last argument is the message for a value that is not callable. This overload also passes the function as its own `this`. Node.js passes `process`. ### Fix - The call passes `process` as `this` and the message `process.reallyExit is not a function`. - Correct because Node.js runs `process.reallyExit(process.exitCode || 0)` in JavaScript. That is a method call on `process`, and V8 gives that message. - Verified: two new tests in `test/js/node/process/process.test.js`. Both fail on release 1.4.3-canary.1. Also ran the other `process.exit()` tests and 12 exit tests from `test/js/node/test/parallel/`. ### Background - `process.reallyExit` is the raw exit of Node.js: it emits no `'exit'` event. Libraries such as signal-exit replace it. - `JSC::call` is the JavaScriptCore helper that calls a JS function from C++. - No other design applies: the two wrong values are arguments of one call. No other `JSC::call` in `src/` has an empty message. ### Downsides - A function that replaces `process.reallyExit` now sees `this === process` when `process.exit()` calls it. Before, `this` was the function itself. - Size: +53 bytes in the `BunProcess.cpp` object (`-O3`, no LTO): 37 for the message, 16 of code. Per call: no new allocation, branch, or syscall. <details><summary>Notes</summary> Repro: ```js process.reallyExit = "str"; process.exit(0); ``` | | stderr | exit code | |---|---|---| | Bun 1.4.3-canary.1+367d939d9 (release) | `TypeError: ` | 1 | | Bun 1.4.3-debug+367d939d9 | `ASSERTION FAILED: !message.isEmpty()` | 134 | | this branch (debug) | `TypeError: process.reallyExit is not a function` | 1 | | Node.js v26.3.0 | `TypeError: process.reallyExit is not a function` | 0 | The same result for each value tried: `"str"`, `undefined`, `null`, `1`, `{}`, `Symbol("x")`, and `delete process.reallyExit`. The `this` value, with `process.reallyExit = function () { console.log(this === process) }` and `process.exit(3)`: `false` before, `true` on this branch and on Node.js v26.3.0. Not changed by this PR: when nothing catches the `TypeError`, Node.js exits with the code given to `process.exit()` (0 above, 5 for `process.exit(5)`). Bun exits 1. A replaced `process.reallyExit` that throws shows the same difference. For an entry point that throws, `uncaught_exception` (`src/jsc/VirtualMachine.rs:2161`) and `exit_with_unhandled_note` (`src/runtime/cli/run_command.rs:1638`) both set exit code 1. Related to oven-sh#42032, which changes the first place for an `'exit'` listener that throws. The new test catches the error in the child, so it does not depend on that exit code. History: oven-sh#16026 added the call with the comment `// process.reallyExit(exitCode);`. Search for other call sites: `JSC::call`, `call`, `profiledCall` and `construct` with an empty message literal in `src/` and `packages/`. `BunProcess.cpp:913` is the only one. Size measurement: compiled `BunProcess.cpp` from `origin/main` and from this branch with the release flags of the build (`-O3 -march=nehalem`), without `-flto=thin` so that the object is native code. `size -A`: `.text` of `Bun::Process_functionExit` 712 to 728 bytes, `.rodata.str1.1` 10594 to 10631 bytes, `.data` and `.bss` unchanged. On a debug build without the fix, the first new test fails: the child exits with code 134 and the assertion is in its stderr. Tests run on the debug build of this branch: - `test/js/node/process/process.test.js -t "process.exit\(\)"`: 6 pass. - `test/js/node/process/process.test.js`, whole file: 179 pass, 5 skip, 3 fail. `process` fails because the container sets no `USER`. `signal > simple case works` and `signal > process.emit will call signal events` time out at 5 s in the whole-file run, with and without the fix. Each passes in 2.5 s when it runs alone. - `test/js/node/test/parallel/`: `test-process-exit-code-validation.js`, `test-process-exit-code.js`, `test-process-exit-from-before-exit.js`, `test-process-exit-handler.js`, `test-process-exit-recursive.js`, `test-process-exit.js`, `test-process-really-exit.js`, `test-worker-exit-code.js`, `test-worker-nested-on-process-exit.js`, `test-worker-on-process-exit.js`, `test-worker-process-exit-async-module.js`, `test-crypto-op-during-process-exit.js`: all exit 0. Not run: macOS, Windows. The changed line has no platform-specific code. </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/node/process/process.test.js <!-- robobun:evidence:end -->
…et _ = x and allow(...) (oven-sh#44086) ### What does this PR do? Cleans up how the Rust code says "this only exists on one platform". No behaviour change is intended and no exported symbol changes. Since oven-sh#43650 made `bun_runtime` a private crate, rustc's `dead_code` lint sees everything in it, and a lot of what it saw was code standing in for another platform: stub functions, placeholder types, `let _ = x;` and `allow(...)`. This says the platform once, with a real `#[cfg]`, and deletes what only existed to keep the other platforms compiling. | in `src/**/*.rs` | main | this PR | | --- | --- | --- | | item-level `allow(dead_code)` escapes | 77 | 0 | | `#[cfg(...)]` attributes | 5,217 | 5,063 | | single-name `let _ = x;` | 385 | 302 | **The changes**, by theme (later review commits are folded into the theme they belong to) 1. **spawn: a memfd stdio exists where memfd does.** `Stdio::Memfd` and the `Memfd` variants of the subprocess and shell `Readable` / `Writable` are Linux/Android-only, with `can_use_memfd`, `use_memfd` and `take_memfd`. Gone: `#[cfg(windows)] Self::Memfd(_) => panic!("This should never happen")`, `panic!("memfd is only supported on Linux")`, the `return false` stub bodies. `Bun.spawn`'s memfd cleanup guard goes too: `stdio` is an owned `[Stdio; 3]` that is never moved, and `Stdio`'s `Drop` closes a memfd, so the guard repeated that. 2. **napi, collections.** `NapiStatus` was listed in full under `allow(dead_code)` because two extern declarations typed a C++-produced status as the Rust enum. They take `napi_status` (the integer), and the enum keeps the values Rust produces, with the rest listed as comments. `multi_array_columns!` accessors name their field in an `offset_of!`, a use the lint can see. 3. **dead_code escapes: say where the item exists, or delete it.** Stale attributes in the macOS-only CoreGraphics backend, a real `#[cfg]` on nine items, `FileCloner` gated as a module, the shell `PipeReader.stdio_result` as a POSIX field. Deleted: a single-use alias, a hand-declared `setenv`, a `debug_assert!` on the constant `true`. 4. **Attributes that repeat an enclosing gate, and code under a contradictory one.** Inside something that already exists only under a predicate, repeating the predicate does nothing, and an item under the opposite predicate is never compiled. `WindowsNamedPipe.rs` alone had 36 repeats and 7 `not(windows)` stand-ins inside a Windows-only module. A `#[cfg(p)] { … }` block is unwrapped where it was the last thing in its enclosing block, so scopes and drop order are the same; the two exceptions, in `WindowsNamedPipe.rs`, hold only raw pointers and a temporary. 5. **Stubs for platforms whose callers never reach them.** `bun_sys::{writev, readv, preadv, statfs}` are unix functions (Windows reaches these through `sys_uv`). Deleted: the non-macOS `clonefileat`, the non-Linux `can_use_memfd`, the Windows `us_socket_t::write_fd` (`unreachable!`). `snapshot_children` and `kill_subreaper_adoptees` are Linux functions like their callers, without stub arms. 6. **`let _ = x;` statements that silence nothing.** Every single-name one (363, outside proc-macro crates) was removed and the compiler asked which it needs; 75 stay removed. Five more looked unneeded only because they sit in arms no checked target builds (`wasm32`, neither unix nor Windows); those are back. A single name under a `_` pattern is not moved, so removing one cannot change when anything is dropped. 7. **Placeholders for another platform's types.** `windows: ()` / `pseudoconsole: ()` in the POSIX spawn options, `PidFdType = ()` off Linux, Windows `struct WaitPidResult {}` and `enum WaiterThread {}`, the event loop's `signal_handler: ()`, `ExceptionValidationScope._scope: ()`, `MemoryAccessor._mem: ()`. The POSIX signal ring is a unix type. 8. **A rename flag nobody sets and a Windows `dup2` nobody calls.** Without `nofollow`, `Renameat2Flags` wrapped one field, so `renameat2` takes the `RenameMode`. 9. **`allow` attributes that allow nothing.** Every single-line `allow` outside proc-macro crates and macro bodies was rewritten as `expect`, and rustc and clippy asked on five targets which expectations are unfulfilled. 334 lints never fire where they are written (214 attributes go entirely): naming lints on names that already follow the convention, and `clippy::not_unsafe_ptr_arg_deref`, which only checks exported functions: these are `pub(crate)` since oven-sh#43650. The comments that justified a removed allowance go with it. Two of the 334 were needed after all, by test code, which the experiment did not compile: `clippy::disallowed_types` in `bun_ptr` and `bun_sys` is back as `#![cfg_attr(test, allow(...))]`. Nothing is left as `expect`. 10. **`dead_code` escapes inside macros do nothing.** rustc does not report `dead_code` for an item another crate's macro generated, only for one from a macro in the same crate, and every use of `opaque_ffi!`, `multi_array_columns!`, `comptime_string_map!`, the css derives and `jsc_macros`' `Gc` enum is from another crate. With all 18 removed nothing fires on any target or profile, test targets included. A nineteenth was on a test's struct, which the test now also reads directly. 11. **The last platform-only items behind escapes.** `posix_spawn.rs` is a unix module and says so where it is mounted (31 repeats of `#[cfg(unix)]` go with `Attr`'s four escapes; `bun_spawn`'s re-export of it had no users). With Windows out of the file, a forwarding helper and two aliases go, and `spawn_bun` borrows its request. `patch::ApplyState` is `#[cfg(windows)]`, down to `apply_patch`'s parameter. `WindowsNamedPipe` writes its two Windows writer-parent impls by hand, as `Terminal` does, in place of a macro that also stamps a POSIX impl; the field that existed only to be named there goes. `InternalSocket::Pipe` no longer exists on POSIX: its only constructor was one of the stand-ins removed in 4. 12. **`Style::JavascriptDefined` does not keep a function nothing calls.** A style function is still accepted and the route scan still panics with `TODO: customizable Style`. The `Strong` the variant held is gone, so `Style` is a plain `Copy` enum and the hand-written `Clone`, with its own copy of the panic, goes. The dev server and production build reached that copy first; they now reach the scan's. 13. **The escape inventory is a ban.** `dead-code-escape-limits.json` is deleted and the test asserts there are no item-level escapes. **Left alone on purpose** - Whole-module `#![allow(dead_code)]`, which the test does not count. `generated_classes.rs` needs its one: the generator emits the full accessor set for every class and each class uses a subset. The five `h2/*.rs` files hide the unused outbound half of a rewrite in progress. - `allow` attributes inside `macro_rules!` bodies, other than the `dead_code` in 10: an expectation there is judged per expansion. - File-level `#![cfg(windows)]` that repeat the `mod` declaration's gate: they tell a reader of the file what it is. - Arms for a target that is neither unix nor Windows. - `let _ = x;` statements the compiler does need somewhere. Those silence a value that really is unused on some platform, and the fix is a `#[cfg]` on the parameter or binding. ### How did you verify your code works? All with warnings as errors, on the branch merged with main: - `cargo check --workspace` on x86_64 Linux, x86_64 Windows, arm64 macOS, x86_64 FreeBSD and x86_64 Android, in the dev and release profiles. Release matters here: code under `debug_assertions` is not compiled there, so something used only by it is unused. - `cargo check --workspace --all-targets` on the same five targets, and `cargo clippy --workspace --no-deps` on Linux. `cargo clippy --workspace --all-targets` reports the same set of findings as on main. - For commits 6 and 9, before the merge: the same check with the build's own cfgs on (`bun_debug`, `bun_asan`, `socket_fault_injection`; `bun_codegen_embed` in release). - `test/internal/source-lints/dead-code-escapes.test.ts` passes, and fails naming the file when an escape is added. - A Linux x64 debug build: the binary checks pass with 0 duplicate strong symbols. `Bun.spawn` with a `Blob` stdin (the memfd path), `Bun.spawnSync` with a buffer stdin, a shell pipeline and repeated `SIGUSR1` handling work. A function as `style` panics with the same message as before and an invalid `style` throws the same error. `spawn-stdin-readable-stream.test.ts` (37), `spawn-maxbuf.test.ts` (16), `process-signal-listener-count.test.ts` (3), `framework-router.test.ts` (35), `patch.test.ts` (27), `socket.test.ts` (104) and `no-orphans.test.ts` (18) pass. - CI's binaries for this branch against main's build of its base commit, function by function (sizes from the symbol table or linker map, then instructions with padding and addresses ignored): | | functions | differ | | --- | --- | --- | | linux-x64 | 76,856 | 115 | | darwin-aarch64 | 66,159 | 186 | | windows-x64 | 90,616 | 85 | The differences are in spawn (`Memfd` and `pidfd` gone where they cannot exist, the cleanup guard), bake (`Style` and what contains it, mostly drop glue), everything on POSIX that matches on `InternalSocket` (about 100 networking functions recompiled for four variants instead of five; the removed arms were unreachable), field offsets on Windows shifted by the removed fields, and two Windows startup functions without the waiter-thread env lookup. On macOS about 30 more differ only in `nop` padding or in the addresses of constants. A function that changed while keeping its exact size would not show. - Not run locally: a build or tests on macOS or Windows (only `cargo check` for those), and the `mordant` job. No benchmark was run.
…sion (oven-sh#44091) ### What does this PR do? Configure fails if clang's LLVM and rustc's LLVM are not the same major version, and everything that existed to cope with a mismatch is deleted. ``` error: clang is LLVM 22.1.8 and rustc's LLVM is 23.1.1; they have to be the same major version hint: The link reads LLVM bitcode from both compilers. pins.llvm.version (scripts/build/ci-images/spec.ts) and the nightly in rust-toolchain.toml move together, and so do BUN_TOOLCHAIN_LLVM and BUN_TOOLCHAIN_RUST. ``` **Why.** The link reads LLVM bitcode from both compilers with clang's LLVM, and an LLVM cannot read bitcode from a newer one. Since oven-sh#43650 that holds for every release build but ASan's, with or without `lto`: the crates reach the link as ThinLTO bitcode, and `rust.ts` said this "rests on rustc's LLVM and clang's being the same major version" without anything checking it. A newer clang is refused too: rustc's [linker-plugin-lto documentation](https://doc.rust-lang.org/rustc/linker-plugin-lto.html#toolchain-compatibility) recommends the same LLVM in both, and no CI build mixes them. **Who sees the error.** clang is already required to be the pinned 23.1.x, and rustc is pinned by `rust-toolchain.toml`, so a normal checkout cannot reach it. It fires when one pin is bumped without the other, and when `BUN_TOOLCHAIN_LLVM` / `BUN_TOOLCHAIN_RUST` name toolchains that do not match (the override skips clang's version range, but the version is still read). **Deleted**, all dormant while the versions match, as they do today (both 23.1.1): - The swap of `cfg.ld` to rustc's bundled `rust-lld`, in its ELF, Mach-O (`gcc-ld/ld64.lld`) and COFF (`gcc-ld/lld-link`) forms, `findRustLld()`'s search for it, `Toolchain.rustLld`, `Config.rustLld`, `Config.rustLlvmNewer`, the `msvcLinker` fallback that kept rustc-driven links off the swapped linker, and the configure-time assert for a swap that could not find its linker. - What `rust-lld` being built without zlib needed: the musl CRT decompress shim (`shim_crt_decompress`, its `-B` search path, its `workarounds.ts` entry) and the post-link `llvm-objcopy --compress-debug-sections` step. `--compress-debug-sections=zlib` is a plain ELF link flag again. - The duplicate-symbol scan's lookup of rustc's own `llvm-nm` / `llvm-objdump`. The `llvm-tools` component stays in `rust-toolchain.toml` and the CI images, as tools to have at hand; the build no longer uses it, so the configure-time `rustup toolchain install` no longer asks for it. - `Config.crossLangLto`. Whether the crates are bitcode is `rustLtoInLink()`'s decision; the field's one other reader is an ELF-only rustflag, and on ELF it always equalled `lto` (its two exceptions were a native Windows host and a native macOS host). - `Config.rustLlvmVersion`, which has no reader left, and `ShimLinkOpts`, which wrapped one field once `ldflags` went: `emitShims()` returns the implicit inputs. `findRustLld()` is `probeRustToolchain()`: it still asks the pinned rustc for its LLVM version, sysroot and host triple. ### How did you verify your code works? - Generated `build.ninja` and the other configure outputs, `main` against this branch, with checkout paths and line wrapping normalised: identical for debug, release, release-asan, release `--lto=off`, and the macOS arm64 and x64 cross targets, on a Linux x64 host. (Run before three last edits that do not reach the output: two comments, the `emitShims()` return type and the unread `Config` field.) - A real mismatch: configuring with `BUN_TOOLCHAIN_LLVM` pointing at a clang 22.1.8 install prints the error above. `main` configures with the same toolchain. - New tests in `test/internal/source-lints/build-rust.test.ts`: different majors fail whichever is newer, with and without LTO, naming both versions; the same major configures; an unknown version is not compared. The tests of the swap are replaced by tests that the link uses the LLVM toolchain's linker and compresses debug sections at link time, with and without LTO. - All 17 files under `test/internal` that import the build system pass. `tsc` on `scripts/build` and `scripts`, and prettier, are clean. - Not run locally: configure for musl, Windows, FreeBSD and Android (no sysroots on the machine), and a full build.
Merge oven-sh/bun main a4f1429 (39 commits since 29d9638) into the fork at 8282146. All 13 conflicts were in node:http and the uWS HTTP server, where upstream oven-sh#43557 reworked request completion, queued handles and handoff tracking over code the fork had patched. Upstream's state machine and IncomingMessage-owned buffering are adopted; fork fixes that upstream does not cover are kept (TLS-wrapped injected sockets, PFX default roots, async listen lookup and callback generations, cork ownership, immediate header flush, idle-state updates at body fin). Where upstream landed the same fix (pre-handshake connection counting, native socket reset, the pipeline-callbacks test) its version replaces the fork copy. Two interactions surfaced as failing existing tests and are fixed here: closeIfIdle no longer treats a completed chunked upload as incomplete while the parser sentinel is still set inside the fin callback, and an already-aborted listen signal that cancels the fork's asynchronous DNS lookup now emits close.
# Conflicts: # CHANGELOG.md
|
Hi! I'm the It looks like you correctly set up a CI job that uses the autofix.ci GitHub Action, but the autofix.ci GitHub App has not been installed for this repository. This means that autofix.ci unfortunately does not have the permissions to fix this pull request. If you are the repository owner, please install the app and then restart the CI workflow! 😃 |
This was referenced Sep 28, 2026
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.
What does this PR do?
Brings the fork up to date with upstream Bun: it merges
oven-sh/bunmainata4f1429148114ddc3bccc13764781be27a7a9523(39 commits since the last sync base29d9638) intoopenclaw/bunmain. Land it with a merge commit so upstream and contributor history stay intact (see.github/UPSTREAM_SYNC.md).The daily
sync-upstream.ymlrun could not do this itself. On 2026-09-26 GitHub denied the merge API call, because upstream changes.github/workflows/rust-lints.ymland the defaultGITHUB_TOKENcannot write workflow files. That run leftautomation/sync-upstreamat the old fork head9e3414b3f7. The 2026-09-27 run then refused to adopt that branch. This PR follows the documented recovery: the merge was made and resolved by hand onautomation/sync-upstream, fast-forwarding it from9e3414b3f7. After this merges, the branch head is the merged PR head and an ancestor ofmain, so the daily run can reuse it. Future imports that touch workflow files will still need an owner-provisionedUPSTREAM_SYNC_TOKEN(Contents, Pull requests and Workflows write). This PR changes no secrets or settings.Commits:
4ef2ad6de8merges upstreama4f1429148into forkmain828214650aand resolves the conflicts.5954c97307merges forkmainccae1e46de(fix(terminal): preserve signal masks across concurrent worker spawns #20, landed meanwhile) on top; only the changelog conflicted.0b741d6a08applies the import order Prettier's organize-imports wants in the mergednode-http-req-socket-pause.test.ts; that was the only diff in the Format check.Conflicts and how they were resolved
All 13 conflicts were in node:http and the uWS HTTP server. There, upstream (notably oven-sh#43557) reworked request completion, queued handles and handoff tracking over code the fork had patched. The rule was to keep both intents. Where upstream landed the fork's own fix, upstream's copy replaces the fork's; otherwise the fork fix stays.
packages/bun-uws/src/HttpContext.h,HttpResponseData.h: upstream parse-close deferral, handoff and queued-response ownership, and listen-address plumbing are adopted. The fork's idle-state update at body fin and parser tail (9e3414b) is kept, along with its upload and tunnel exclusions.src/js/internal/http.ts,src/js/node/_http_incoming.ts: upstream's explicit aborted body state andIncomingMessage-owned buffering with stream backpressure are adopted, replacing the fork's separate native pause buffer. The fork's secure-context symbol and its regression cases are kept.src/js/node/_http_server.ts,src/js/node/net.ts: upstream's completion, abort, drain and close sequencing, handoff tracking, max headers,listeninggetter,drainedAtCloseand sharedAbortSignalhandling are adopted. The fork keeps:Upstream's removal of a forced
rejectUnauthorized=falseis applied inside the relocated fork helper (the automatic merge missed it).src/jsc/bindings/node/JSNodeHTTPServerSocket.cpp: equals upstream, which already includes the fork'sreset().src/runtime/server/NodeHTTPResponse.rs,mod.rs: upstream's Pending/Complete/Aborted/Upgraded/Detached state machine, conditional native drain registration and pre-handshake connection counting are adopted; the counting subsumes fork 747299f. The fork's immediateflush_headers(true)and its guards around abort, resume, promise settlement, close and end are kept.Tests:
node-http-pipeline-callbacks.test.tswas added by both sides with the same content, and one copy is kept.node-http-req-socket-pause,node-http-with-wsandnode-http.test.tsnow contain both sides' cases. No fork regression case was dropped. Where upstream had a stronger version of the same test, it was used (the overlapping-TLS ordering test, and theConnection: closefour-case matrix).Two interactions between the sides showed up as failing existing tests, and the merge fixes them:
closeIfIdletreated a finished chunked upload as incomplete while the parser sentinel was still set inside the fin callback. It now checks the message state.listensignal that cancels the fork's asynchronous DNS lookup never emittedclose. It now does.Ride-along audit: the 587 changed paths versus fork
mainare upstream's 586 plusCHANGELOG.md. Two upstreamCLAUDE.mdchanges land in the fork'sAGENTS.mdequivalents. The fork's remaining delta over upstream introduces no path that wasn't already fork-only before the merge. There is no lockfile churn.How did you verify your code works?
macOS arm64 release builds of the merged tree.
Qualification on the resolved merge, 35 files covering every conflicted area plus terminal, spawn, sqlite, diagnostics_channel and
bun run: 2,352 pass, 3 fail, 54 skip, 5 todo.The three failures are not from this merge:
signalCodecases intest/cli/install/bun-run.test.tsfail identically on a build of forkmain828214650awithout the merge. Stock Bun 1.4.2 passes them, so they predate this sync. This fork has issues disabled, so the details are recorded below under "Known pre-existing failure".node-http-req-complete.test.tshas a Node-reference subprocess assertion that fails because the host's Node v26.9.0 reportswritableFinished=false. All 26 Bun cases in that file pass.The fault-injection suites skip on release builds because they need a testing build.
Final head
5954c97307(after merging #20), rebuilt and rerun:terminal-spawn.test.tsterminal.test.tsnode-http-req-socket-pause.test.tsnode-http.test.tsnode-http-pipeline-callbacks.test.tsnode-http-with-ws.test.tsnode-http-req-complete.test.tsnode-sqlite.test.tsbun-run.test.ts--silentSIGILL cases)Checks: lint clean; sync automation tests 24 pass; source lints 176 pass; the TypeScript checks for scripts, built-in JS, src and bake pass;
cargo fmt --all --checkandactionlint sync-upstream.ymlpass.clang-formatwas not available locally.git diff --checkonly flags whitespace in upstream's generatedllhttp.c. An independent review of the full fork delta against upstream found no issues.Known pre-existing failure (not from this sync)
bun --silent run bash -c "ulimit -c 0; kill -4 $$"should end withsignalCodeSIGILL, like the non-silent form and like stock Bun. On fork builds on macOS arm64 it ends withsignalCodenullinstead.Failing cases in
test/cli/install/bun-run.test.ts(line 148, "exit signal works"):bun run > bun run > should work with . > --silent > exit signal worksbun run > bun > should work with . > --silent > exit signal worksEvidence (macOS arm64 release builds, 2026-09-28):
main828214650a: the four exit-signal cases give 2 pass, 2 fail. The--silentvariants fail; the non-silent variants pass.mainmerged with upstreama4f1429148): same two failures.1.4.2+744846f84running the same test file: 4 pass, 0 fail.So this predates the upstream sync and comes from fork changes or the fork's build setup, not from upstream. Likely suspects are the fork's changes to how
bun runre-raises a child's terminating signal, and to the crash handler (src/crash_handler/lib.rsdiffers from upstream). Not yet bisected.