Repository navigation
chore(sync): merge upstream Bun through 29d9638 - #4
Merged
Merged
Conversation
…2582) ### Problem - `class Sub extends StringDecoder {}; new Sub("utf8")` returns the class `Sub` itself. `s.write` is `undefined`, and `Sub` gains an own `encoding` property. `Reflect.construct(StringDecoder, ["utf8"], Object)` returns `Object`. Node returns an instance. - `JSStringDecoderConstructor` registers one native function for [[Call]] and [[Construct]] (`src/jsc/bindings/JSStringDecoder.h:118`). JSC passes new.target in the `this` slot of a native constructor, so the branch for `StringDecoder.call(receiver, encoding)` (`JSStringDecoder.cpp:592`) takes `Sub` as the receiver. - Found by an audit. No issue reports it. ### Fix - Register separate `call` and `construct` functions that share one `createDecoder` body. For a [[Construct]] it takes the structure from new.target with `InternalFunction::createSubclassStructure`, as `JSHash` and the generated classes do. `call` keeps the receiver branch unchanged. - The Node.js compatibility page no longer lists this gap. Not in this PR: `JSMockFunction.cpp:459` has the same cause, and oven-sh#34575 and oven-sh#41398 carry it. - `new StringDecoder()` costs the same as before (ThinLTO A/B in the notes). - Verified: `test/js/node/string_decoder/string-decoder.test.js` (143 pass, released bun fails the 45 new cases), Node's `test-string-decoder*.js`, `express-body-parser-test.test.ts`. Self-reviewed: 4 concerns raised, 4 addressed. ### Background - [[Call]] is `f()`. [[Construct]] is `new f()` or `Reflect.construct`. A JSC `InternalFunction` takes one native function for each. - new.target is the constructor that `new` was applied to: `Sub` for `new Sub()`. The new object takes its prototype from it. - A JSC `Structure` holds the prototype of an object. `createSubclassStructure` returns the base structure with the prototype of new.target. - The receiver branch serves iconv-lite 0.4 (under express body-parser), which runs `StringDecoder.call(this, enc)` on a plain object. It stores the native decoder on that object. <details><summary>Notes</summary> **Repro** ```js const { StringDecoder } = require("string_decoder"); class Sub extends StringDecoder {} const s = new Sub("utf8"); console.log(s === Sub, typeof s, s instanceof Sub, Reflect.ownKeys(Sub)); // bun 1.4.3: true function false [ "length", "name", "prototype", "encoding" ] // node v26.3.0: false object true [ 'length', 'name', 'prototype' ] // this branch: false object true [ "length", "name", "prototype" ] ``` **Sibling sites** (every place that registers one function for both [[Call]] and [[Construct]]) - `src/jsc/bindings/JSMockFunction.cpp:459`: `jsMockFunctionCall` reads `thisValue()`, so `new mockFn()` sees new.target as `this`. Same root cause. Excluded here because oven-sh#34575 and oven-sh#41398 already change that function. This PR does not fix `mock()` or `spyOn()`. - These never read `this` or new.target, so the confusion cannot happen there: the seven sink constructors from `src/codegen/generate-jssink.ts:59` (`js_construct` ignores the frame), `JSDOMConstructorNotConstructable` (throws on both paths), the `ObjectTemplate` `DummyCallback` in the V8 shim, `jsNodeVmWasmDisallowed` (`NodeVM.cpp:1046`, throws on both paths), `vm.createContext` (`NodeVM.cpp:1714`), and `SlowBuffer`. - oven-sh#42528 makes other native constructors honor new.target. It does not cover `StringDecoder`. **Cost of `new StringDecoder()`** A first version had a parse helper and called `JSStringDecoder::create` from both `call` and `construct`. With two call sites, `allocateCell<JSStringDecoder>` went out of line and `new StringDecoder()` got slower. One shared `createDecoder` keeps a single call site for the allocation, and `construct` compiles to 9 instructions that end in `jmp createDecoder`. ThinLTO release build, only this translation unit replaced, one pinned core, 300 reps of 200000 constructions, p50 in ns over 5 alternating rounds: | variant | `new StringDecoder()` | `new StringDecoder("utf8")` | | --- | --- | --- | | main | 11.6 to 12.3 | 19.5 to 21.1 | | first version | 14.9 to 16.1 | 19.8 to 20.9 | | this PR | 11.4 to 12.6 | 18.0 to 19.3 | **Behavior details** - Order matches Node: the `prototype` of new.target is read before the encoding is parsed (probed with a Proxy new.target and an encoding object with a `toString`). - `call` is unchanged, including the `thisValue != constructor` check, so `StringDecoder.call(StringDecoder, enc)` still returns a fresh decoder. The two `putDirect` lines in the receiver branch are textually untouched, so oven-sh#34609 and other work on that branch should merge without a conflict. - A new.target whose `prototype` is not an object gets `StringDecoder.prototype`, as for every JSC built-in class. Node gives `Object.prototype` there, because its `StringDecoder` is an ordinary function. - Cross-realm: a class defined in a `node:vm` context or a ShadowRealm can extend `StringDecoder`. The function realm of new.target is not always a `Zig::GlobalObject`, so the code goes through `defaultGlobalObject()`. A revoked Proxy as new.target throws a TypeError. - Remaining difference, not changed here: Node's `end(buf)` and `text()` call `this.write()`, so a subclass that overrides `write` sees those calls. Bun's native `end` and `text` call the native write directly. A plain instance with a patched `write` shows the same difference today. - Not changed here: `lastNeed`, `lastTotal` and `lastChar` throw on a `StringDecoder.call(this)` receiver, because the prototype accessors have a class check. Instances of a subclass are real `JSStringDecoder` cells, so the accessors work on them. **Suites run with the debug (ASAN) build** - `test/js/node/string_decoder/string-decoder.test.js`: 143 pass. The whole decode suite now also runs against `class SubStringDecoder extends StringDecoder`. Released bun 1.4.3: 98 pass, 45 fail. - The same file and a script of every throw path under `BUN_JSC_validateExceptionChecks=1`: clean. - `test/js/node/test/parallel/`: `test-string-decoder.js`, `test-string-decoder-end.js`, `test-string-decoder-fuzz.js`, `test-crypto-hash.js`, `test-fs-read-stream-encoding.js`, `test-readline-keys.js`, `test-stream-decoder-objectmode.js`, `test-stream-push-strings.js`, `test-stream-readable-setEncoding-existing-buffers.js`, `test-stream-readable-setEncoding-null.js`, `test-stream2-decode-partial.js`, `test-stream2-set-encoding.js`. - `test/js/third_party/body-parser/express-body-parser-test.test.ts`, and iconv-lite 0.4.24 (`StringDecoder.call(this, enc)` with `InternalDecoder.prototype = StringDecoder.prototype`) by hand. **Self-review** The review asked for four changes. All are in this PR: the stale docs line, the sibling-sites list, the slower `new StringDecoder()` of the first version, and multi-line comments in `src/`. </details> <!-- robobun:evidence:begin --> --- **[human-review]** gate passed · iteration 0 · 4 files touched <details><summary>fails on main (without fix)</summary> ```console ASAN without fix: 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/string_decoder/string-decoder.test.js ninja: Entering directory `/workspace/bun/build/debug' [1/164] cc obj/src/jsc/bindings/sqlite/sqlite3.c.o [2/164] 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/164] 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 ... (truncated) release without fix: 45 FAILED bun test v1.4.3-canary.1 (6a92015) test/js/node/string_decoder/string-decoder.test.js: (pass) require('string_decoder') [0.10ms] (pass) Bun.inspect(StringDecoder) [0.09ms] (pass) FakeStringDecoderCall > StringDecoder-utf8 [1.88ms] (pass) FakeStringDecoderCall > StringDecoder-ucs-2 [0.94ms] (pass) FakeStringDecoderCall > StringDecoder-utf16le [0.04ms] (pass) FakeStringDecoderCall > StringDecoder-utf8-additional [0.11ms] (pass) FakeStringDecoderCall > StringDecoder-utf16le-additional [0.06ms] (pass) FakeStringDecoderCall > StringDecoder.end > base64 testbuf [0.18ms] (pass) FakeStringDecoderCall > StringDecoder.end > base64url testbuf [0.10ms] (pass) FakeStringDecoderCall > StringDecoder.end > hex testbuf [0.11ms] (pass) FakeStringDecoderCall > StringDecoder.end > utf8 testbuf [0.06ms] (pass) FakeStringDecoderCall > StringDecoder.end > utf16le testbuf [0.04ms] (pass) FakeStringDecoderCall > StringDecoder.end > ucs2 testbuf [0.05ms] (pass) FakeStringDecoderCall > StringDecoder.end > utf8 partial "�a" [0.03ms] (pass) FakeStringDecoderCall > StringDecoder.end > utf8 partial "��" (pass) FakeStringDecoderCall > StringDecoder.end > utf8 partial "��" (pass) FakeS ... (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/string_decoder/string-decoder.test.js bun test v1.4.3 (6a92015) test/js/node/string_decoder/string-decoder.test.js: (pass) require('string_decoder') [6.27ms] (pass) Bun.inspect(StringDecoder) [5.39ms] (pass) FakeStringDecoderCall > StringDecoder-utf8 [340.80ms] (pass) FakeStringDecoderCall > StringDecoder-ucs-2 [239.90ms] (pass) FakeStringDecoderCall > StringDecoder-utf16le [4.82ms] (pass) FakeStringDecoderCall > StringDecoder-utf8-additional [9.54ms] (pass) FakeStringDecoderCall > StringDecoder-utf16le-additional [8.09ms] (pass) FakeStringDecoderCall > StringDecoder.end > base64 testbuf [25.18ms] (pass) FakeStringDecoderCall > StringDecoder.end > base64url testbuf [17.47ms] (pass) FakeStringDecoderCall > StringDecoder.end > hex testbuf [13.70ms] (pass) FakeStringDecoderCall > StringDecoder.end > utf8 testbuf [15.44ms] (pass) FakeStringDecoderCall > StringDecoder.end > utf16le testbuf [11.48ms] (pass) FakeStringDecoderCall > StringDecoder.end > ucs2 testbuf [12.16ms] (pass) FakeStringDecoderCall > StringDecoder.end > utf ... (truncated) release with fix: all passed $ bun scripts/build.ts --profile=release [configured] bun-profile → bun (stripped) in 706ms (unchanged) ninja: Entering directory `/workspace/bun/build/release' [1/125] cc obj/src/jsc/bindings/sqlite/sqlite3.c.o [2/125] 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/125] 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 ... (truncated) ``` </details> <details><summary>diff hotspot</summary> ``` docs/runtime/nodejs-compat.mdx | 2 +- src/jsc/bindings/JSStringDecoder.cpp | 45 ++++++-- src/jsc/bindings/JSStringDecoder.h | 5 +- test/js/node/string_decoder/string-decoder.test.js | 114 ++++++++++++++++++++- 4 files changed, 151 insertions(+), 15 deletions(-) ``` </details> **gate history** · 1 passed · 0 rejected · iteration 0 <details><summary>evidence per changed file</summary> ``` file reads edits tests docs/runtime/nodejs-compat.mdx 1 1 18 src/jsc/bindings/JSStringDecoder.cpp 5 12 18 src/jsc/bindings/JSStringDecoder.h 1 1 18 test/js/node/string_decoder/string-decoder.test.js 2 5 18 ``` </details> <!-- robobun:evidence:end -->
…fieHellman, dns.Resolver, $.Shell, HTTPParser and ConnectionsList (oven-sh#42528) ### Problem - `class X extends C {}; new X()` returns an instance of `C`, not of `X`, for `Bun.Cookie`, `Bun.CookieMap`, `crypto.ECDH`, `crypto.DiffieHellman`, `dns.Resolver`, `$.Shell`, and `HTTPParser` and `ConnectionsList` of the `http_parser` binding. `new X() instanceof X` is `false` and the methods of `X` are missing. Node v26.3.0 returns an `X`. - The native constructors ignore `newTarget` and always use the base structure (`JSCookie.cpp`, `JSCookieMap.cpp`, `JSECDHConstructor.cpp:75`, `JSDiffieHellmanConstructor.cpp:193`, `JSHTTPParserConstructor.cpp:23`, `JSConnectionsListConstructor.cpp:23`). `$.Shell` (`shell.ts:344`) always sets `ShellPrototype.prototype`. - `dns.Resolver` (`dns.ts:694`) returns `new InternalResolver(options)`. So `new dns.Resolver() instanceof dns.Resolver` is `false` too, and a method patched on `dns.Resolver.prototype` never runs. ### Fix - `Bun.Cookie` and `Bun.CookieMap` call `setSubclassStructureIfNeeded`, like the other 22 `JSDOMConstructor` bindings. - `structureForNewTarget` (new, beside `defaultGlobalObject`) holds the `newTarget` block that `crypto.DiffieHellmanGroup` had. `ECDH`, `DiffieHellman`, `DiffieHellmanGroup`, `HTTPParser` and `ConnectionsList` call it. `$.Shell` uses `new.target.prototype`. - `dns.Resolver` is the class itself, like `dns.promises.Resolver`. `dns.Resolver()` without `new` now throws a `TypeError`, as in Node. The compat page drops its note about this class. - Verified: tests in `cookie-map.test.ts`, `ecdh.test.ts`, `node-crypto.test.js`, `node-http-parser.test.ts`, `bunshell-instance.test.ts` and `dns-resolver-class.test.ts`. 1.4.3-canary.1 fails 17 of them. ### Background - `newTarget` is the constructor that `new` was applied to. In `new X()`, `C` runs with `newTarget === X`. The object must get `X.prototype`. - A JSC `Structure` holds the prototype of an object. `InternalFunction::createSubclassStructure(newTarget, base)` returns the base structure with `newTarget.prototype`. - `getFunctionRealm(newTarget)` is the global of `newTarget`. For a class from a `node:vm` context it is not a Bun global, so the code passes it through `defaultGlobalObject`. <details><summary>Notes</summary> Repro: ```js const crypto = require("node:crypto"), dns = require("node:dns"), { HTTPParser, ConnectionsList } = process.binding("http_parser"); const T = [["Bun.Cookie", Bun.Cookie, ["a", "b"]], ["Bun.CookieMap", Bun.CookieMap, ["a=b"]], ["crypto.ECDH", crypto.ECDH, ["prime256v1"]], ["crypto.DiffieHellman", crypto.DiffieHellman, [Buffer.from("17", "hex")]], ["dns.Resolver", dns.Resolver, []], ["$.Shell", Bun.$.Shell, []], ["HTTPParser", HTTPParser, []], ["ConnectionsList", ConnectionsList, []], ["control crypto.DiffieHellmanGroup", crypto.DiffieHellmanGroup, ["modp14"]], ["control dns.promises.Resolver", dns.promises.Resolver, []], ["control URL", URL, ["http://a/"]]]; for (const [n, C, a] of T) { class X extends C { extra() { return 1; } } const r = new X(...a); console.log(n.padEnd(34), "instanceof X:", r instanceof X, "| instanceof C:", r instanceof C, "| extra:", typeof r.extra); } ``` | | 1.4.3-canary.1 | this branch | node v26.3.0 | | --- | --- | --- | --- | | `Bun.Cookie`, `Bun.CookieMap`, `$.Shell` | `false`, `true`, `undefined` | `true`, `true`, `function` | | | `crypto.ECDH`, `crypto.DiffieHellman`, `_http_common.HTTPParser` | `false`, `true`, `undefined` | `true`, `true`, `function` | `true`, `true`, `function` | | `ConnectionsList` | `false`, `true`, `undefined` | `true`, `true`, `function` | not reachable | | `dns.Resolver` | `false`, `false`, `undefined` | `true`, `true`, `function` | `true`, `true`, `function` | | the three controls | `true`, `true`, `function` | `true`, `true`, `function` | `true`, `true`, `function` | `dns.Resolver`: - The wrapper function is from the first `node:dns` implementation (2b1b897). `$toClass` gave it a prototype that inherits from `InternalResolver.prototype`, but the returned object had `InternalResolver.prototype` itself. No object ever had `dns.Resolver.prototype`. - dd-trace wraps `dns.Resolver.prototype.resolve`, `reverse` and the shorthands. On 1.4.3-canary.1 a wrapper installed there is never called on an instance. It is called on this branch and on Node. - Node declares `class Resolver extends ResolverBase {}`, so `dns.Resolver()` without `new` throws there too: `Class constructor Resolver cannot be invoked without 'new'`. No test in the repo called it without `new`. - The test is in a new file because `node-dns.test.js` resolves public hostnames. 29 of its tests fail in a sandbox with no outbound DNS, before and after this change (the same 29). - `docs/runtime/nodejs-compat.mdx` said "the callback-style `Resolver` class cannot be subclassed (`dns.promises.Resolver` can)" since oven-sh#38441. This PR removes that clause. `structureForNewTarget`: - It takes the lexical global, `newTarget`, and a pointer to the `LazyClassStructure` member of `Zig::GlobalObject`. It returns the base structure when `newTarget` is the constructor, and the subclass structure otherwise. - `DiffieHellmanGroup` calls it at the place where its block was, after the argument checks, so its behaviour does not change. Its `if (!newTarget)` branch is gone. A host `construct` function always has a `newTarget`. `callDiffieHellmanGroup` goes through `JSC::construct`, which sets it to the constructor. - In `ECDH` and `DiffieHellman` the call is at the top of the constructor. Node's `function ECDH(curve)` gets its `this` before `validateString(curve)` runs, so a `prototype` getter on `newTarget` runs before the argument error. `Reflect.construct(ECDH, [{}], proxyWithThrowingPrototypeGetter)` throws the getter's error on Node and on this branch. - The other constructors that have the same block by hand (`Hash`, `Hmac`, `Sign`, `X509Certificate`, `MIMEType`, `MIMEParams`, `Dirent`, `vm.Script`, `DatabaseSync`) already honor `newTarget`. This PR does not move them to the helper. That is a refactor with no change in behaviour. - One difference from Node remains, and `DiffieHellmanGroup`, `Hash`, `Hmac` and `Sign` already have it. For `Reflect.construct(ECDH, args, F)` where `F.prototype` does not inherit from `ECDH.prototype`, Node's `if (!(this instanceof ECDH)) return new ECDH(curve)` returns a plain `ECDH`. Bun returns an object with `F.prototype`. The tests only assert what is the same on Node. Other cases checked by hand on this branch, for all the classes. None crashes. `BUN_JSC_validateExceptionChecks=1` is clean on the subclass, revoked Proxy and throwing getter paths. - `Reflect.construct(C, args, F)` with a plain function, a bound function (no `prototype`, so the base prototype is used), a Proxy, and a function whose `prototype` is not an object. - A revoked Proxy as `newTarget` throws `TypeError: Cannot get function realm from revoked Proxy` (a `TypeError` on Node too). - A subclass declared in a `node:vm` context, and `Reflect.construct` with a `newTarget` from a context. The crypto tests cover the first case. - `ECDH("prime256v1")` and `DiffieHellman(prime)` without `new` still return a base instance. Census: I walked every constructible function reachable from `globalThis`, `Bun`, `node:*` and `bun:*` to depth 3 and constructed a subclass of each with a list of guessed arguments. 772 functions are constructible. 210 returned an object for the subclass. On this branch the ones that are still not an instance of the subclass are: - `string_decoder.StringDecoder`. It returns the subclass constructor itself. It has a separate change. - `Buffer` and `SlowBuffer`. Node also returns a plain `Buffer`. - `diagnostics_channel.Channel`. It overrides `Symbol.hasInstance`. The prototype is correct, and Node prints the same. - `module.Module`, `ShadowRealm` and `WebAssembly.Suspending`. Known, and the last two are in JavaScriptCore. The census has blind spots: - 506 of the 772 did not construct with any guessed argument list. - It skipped modules whose name starts with `_` and everything behind `process.binding`. A review found `HTTPParser` and `ConnectionsList` there, and this PR fixes them. - It did not report a constructor whose `extends` clause throws. `tls.SecureContext`, `Bun.ArrayBufferSink` and `Bun.SQL` have no `prototype` object, so `class X extends C` throws `The value of the superclass's prototype property is not an object or null`, and `new C() instanceof C` throws too. oven-sh#41696 (SecureContext) and oven-sh#39936 (the sinks) are open for the first two. `Bun.SQL` is a separate follow-up. - A class from a native addon that uses the V8 API directly is not reachable from JS globals. `FunctionTemplate::functionConstruct` (`src/jsc/bindings/v8/shim/FunctionTemplate.cpp`) takes the prototype from the callee and not from `newTarget`. That is a separate follow-up. `$.Shell` was not in the original report. The census found it. Separate from this PR: `Object.getPrototypeOf(Bun.Cookie)` and `Object.getPrototypeOf(Bun.CookieMap)` are `Object.prototype`, not `Function.prototype` (`prototypeForStructure` in both files). So `Bun.Cookie.bind` is `undefined`, also on a subclass. This PR does not change that. Suites run on the debug build: `test/js/bun/cookie/`, `test/js/node/crypto/node-crypto.test.js`, `ecdh.test.ts`, `crypto-invalid-this.test.ts`, `test/js/node/dns/dns-resolver-class.test.ts`, `node-dns.test.js`, `test/js/node/http/node-http-parser.test.ts`, `test/js/bun/shell/bunshell-instance.test.ts`, `bunshell-default.test.ts`, `env.positionals.test.ts`, and the Node tests `test-crypto-dh*.js` (13 files), `test-crypto-ecdh*.js`, `test-crypto-classes.js`, `test-dns*.js` (25 files), `test-worker-dns-terminate*.js`, `test-http-parser*.js`, `test-http-common.js`. </details> <!-- robobun:evidence:begin --> --- **[human-review]** gate passed · iteration 0 · 18 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/bun/cookie/cookie-map.test.ts test/js/bun/shell/bunshell-instance.test.ts test/js/node/crypto/ecdh.test.ts test/js/node/crypto/node-crypto.test.js test/js/node/dns/dns-resolver-class.test.ts test/js/node/http/node-http-parser.test.ts ninja: Entering directory `/workspace/bun/build/debug' [1/166] cc obj/src/jsc/bindings/sqlite/sqlite3.c.o [2/166] 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/166] 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/fil ... (truncated) release without fix: all passed bun test v1.4.3-canary.1 (138f46d) test/js/bun/cookie/cookie-map.test.ts: (pass) Bun.Cookie and Bun.CookieMap > can create a basic Cookie [0.08ms] (pass) Bun.Cookie and Bun.CookieMap > can create a Cookie with options [0.07ms] (pass) Bun.Cookie and Bun.CookieMap > Cookie.toString() formats properly [0.10ms] (pass) Bun.Cookie and Bun.CookieMap > can set Cookie expires as Date [7.65ms] (pass) Bun.Cookie and Bun.CookieMap > Cookie.isExpired() returns correct value [0.15ms] (pass) Bun.Cookie and Bun.CookieMap > Cookie.isExpired() gives Max-Age precedence over Expires [0.11ms] (pass) Bun.Cookie and Bun.CookieMap > Cookie.parse works with all attributes [0.10ms] (pass) Bun.Cookie and Bun.CookieMap > Cookie.parse keeps Expires when Max-Age comes first [0.12ms] (pass) Bun.Cookie and Bun.CookieMap > Cookie.parse takes the last value of a repeated attribute [0.04ms] (pass) Bun.Cookie and Bun.CookieMap > Cookie.parse reads every attribute in any order [0.17ms] (pass) Bun.Cookie and Bun.CookieMap > Cookie.serialize creates cookie string [0.09ms] (pass) Bun.Cookie and Bun.CookieMap > can create an empty CookieMap [0.06ms] (pass) Bun.Cookie and Bun.CookieMap > can create Cooki ... (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/cookie/cookie-map.test.ts test/js/bun/shell/bunshell-instance.test.ts test/js/node/crypto/ecdh.test.ts test/js/node/crypto/node-crypto.test.js test/js/node/dns/dns-resolver-class.test.ts test/js/node/http/node-http-parser.test.ts bun test v1.4.3 (6a92015) test/js/bun/cookie/cookie-map.test.ts: (pass) Bun.Cookie and Bun.CookieMap > can create a basic Cookie [4.56ms] (pass) Bun.Cookie and Bun.CookieMap > can create a Cookie with options [5.05ms] (pass) Bun.Cookie and Bun.CookieMap > Cookie.toString() formats properly [5.87ms] (pass) Bun.Cookie and Bun.CookieMap > can set Cookie expires as Date [160.37ms] (pass) Bun.Cookie and Bun.CookieMap > Cookie.isExpired() returns correct value [4.67ms] (pass) Bun.Cookie and Bun.CookieMap > Cookie.isExpired() gives Max-Age precedence over Expires [6.09ms] (pass) Bun.Cookie and Bun.CookieMap > Cookie.parse works with all attributes [6.01ms] (pass) Bun.Cookie and Bun.CookieMap > Cookie.parse keeps Expires when Max-Age comes first [8.01ms] (pass) Bun.Cookie and Bun.CookieMap > Cookie.parse ... (truncated) release with fix: all passed $ bun scripts/build.ts --profile=release [configured] bun-profile → bun (stripped) in 726ms (unchanged) ninja: Entering directory `/workspace/bun/build/release' [1/127] cc obj/src/jsc/bindings/sqlite/sqlite3.c.o [2/127] 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/127] 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 ... (truncated) ``` </details> <details><summary>diff hotspot</summary> ``` docs/runtime/nodejs-compat.mdx | 2 +- src/js/builtins/shell.ts | 3 +- src/js/node/dns.ts | 9 +--- src/jsc/bindings/ZigGlobalObject.cpp | 14 +++++ src/jsc/bindings/ZigGlobalObject.h | 3 ++ .../node/crypto/JSDiffieHellmanConstructor.cpp | 7 ++- .../crypto/JSDiffieHellmanGroupConstructor.cpp | 18 +------ src/jsc/bindings/node/crypto/JSECDHConstructor.cpp | 6 +-- .../node/http/JSConnectionsListConstructor.cpp | 3 +- .../bindings/node/http/JSHTTPParserConstructor.cpp | 3 +- src/jsc/bindings/webcore/JSCookie.cpp | 23 ++++---- src/jsc/bindings/webcore/JSCookieMap.cpp | 5 +- test/js/bun/cookie/cookie-map.test.ts | 61 ++++++++++++++++++++++ test/js/bun/shell/bunshell-instance.test.ts | 15 ++++++ test/js/node/crypto/ecdh.test.ts | 33 ++++++++++++ test/js/node/crypto/node-crypto.test.js | 34 ++++++++++++ test/js/node/dns/dns-resolver-class.test.ts | 34 ++++++++++++ test/js/node/http/node-http-parser.test.ts | 27 ++++++++++ 18 files changed, 253 insertions(+), 47 deletions(-) ``` </details> **gate history** · 2 passed · 0 rejected · iteration 0 <details><summary>evidence per changed file</summary> ``` file reads edits tests docs/runtime/nodejs-compat.mdx 1 1 29 src/js/builtins/shell.ts 1 1 29 src/js/node/dns.ts 2 0 29 src/jsc/bindings/ZigGlobalObject.cpp 0 0 29 src/jsc/bindings/ZigGlobalObject.h 3 2 29 …jsc/bindings/node/crypto/JSDiffieHellmanConstructor.cpp 0 0 29 …indings/node/crypto/JSDiffieHellmanGroupConstructor.cpp 0 0 29 src/jsc/bindings/node/crypto/JSECDHConstructor.cpp 1 1 29 …jsc/bindings/node/http/JSConnectionsListConstructor.cpp 0 0 29 src/jsc/bindings/node/http/JSHTTPParserConstructor.cpp 0 0 29 src/jsc/bindings/webcore/JSCookie.cpp 1 0 29 src/jsc/bindings/webcore/JSCookieMap.cpp 1 1 29 test/js/bun/cookie/cookie-map.test.ts 1 2 7 test/js/bun/shell/bunshell-instance.test.ts 1 2 6 test/js/node/crypto/ecdh.test.ts 0 0 9 test/js/node/crypto/node-crypto.test.js 0 0 9 (+ 2 more files) ``` </details> <!-- robobun:evidence:end -->
…esponse (oven-sh#42573) ### Problem - With the built-in `node-fetch` and `undici` shims, `res.body` emits `'error'` after a body method: `Invalid state: ReadableStream is locked` from `resume()`, `pipe()`, `for await`, and `Cannot cancel a locked ReadableStream` from `destroy()` (for example `finally { body.destroy() }`). Bun 1.4.2 and Node emit `'end'`, `'close'`. Regression from oven-sh#42116 (not released). No user reported it. - Cause: `ReadableFromWeb` (`src/js/internal/webstreams_adapters.ts`) calls `stream.getReader()` in the first `_read()` and `stream.cancel()` in `_destroy()`. Since oven-sh#42116 a body method keeps the web stream locked, so both throw. ### Fix - `ReadableFromWeb` takes a `responseBody` option. Both shims set it, `Readable.fromWeb()` does not. If the wrapper has not opened the web stream and the stream is locked, the Response took the body: `_read()` pushes `null`, `_destroy()` skips `cancel()`. - The check reads `stream.locked`, not `bodyUsed`: after an aborted `text()`, `bodyUsed` is `false` and the stream is locked. - `node-fetch`: the body methods no longer read `this.body` first, so the five overrides are deleted. `clone()` drops the cached node stream, because the body moves to a new web stream. - Verified: `test/js/node/http/node-fetch.test.js`, `test/js/first_party/undici/undici.test.ts` (27 new tests, 25 fail with main's `src/`). Self-reviewed: 3 concerns raised, 3 addressed. ### Background - Both shims hand out the body as a node `Readable` (`ReadableFromWeb`) around the web `ReadableStream` of a Bun `Response`. `text()`, `json()`, ... are the native methods and read the web stream directly. - `ReadableFromWeb` opens the web stream lazily, so a body method can take it while the wrapper has no reader. - Real `node-fetch` and `undici` read that node stream in `text()`, so it is ended afterwards. <details><summary>Notes</summary> **Origin.** Found during the review of oven-sh#42516. That PR lists this symptom as tracked separately. **Reproduction.** ```js import nodeFetch from "node-fetch"; await using server = Bun.serve({ port: 0, fetch: () => new Response("hello") }); const res = await nodeFetch(server.url); const body = res.body; await res.arrayBuffer(); body.on("error", e => console.log("error:", e.message)).on("end", () => console.log("end")); body.resume(); // 1.4.2: end // main: error: Invalid state: ReadableStream is locked ``` **Behaviour per case**, both shims, checked against a 1.4.2 binary. "clean" means `end`, `close` for `resume()`, `close` for `destroy()`, and no chunks for `for await`. | case | 1.4.2 | main | this PR | | --- | --- | --- | --- | | `body` taken, then `text()` / `json()` / `arrayBuffer()` / `blob()` / `formData()` / `buffer()` / `bytes()`, then `resume()`, `destroy()` or `for await` | clean | `error` | clean | | body method first, then `res.body` for the first time | clean (`bytes()` throws) | `error` | clean | | `text()` aborted by the signal (or `AbortSignal.timeout()`), then `resume()` / `destroy()` | clean | `error` | clean | | `formData()` rejects the content type, then `resume()` / `destroy()` | clean | `error` | clean | | `json()` rejects with a `SyntaxError`, then `resume()` / `destroy()` | clean | `error` | clean | | `text()` still pending, then `resume()` / `destroy()` | `error` (locked) | `error` | clean, and `text()` resolves with the full body | | `body` taken, then `res.clone()`, then read `res.body` | throws (locked by `tee()`) | throws | `res.body` is a new node stream and delivers the body. The old node stream ends. | | `res.body` streamed with `for await`, `on("data")`, `pipe()` | works | works | works | | `destroy()` on a body that nothing read | cancels the fetch | same | same | **Why `stream.locked`.** The first version of this change asked the Response for `bodyUsed`. That misses every body method that rejects after it took the stream: on main `bodyUsed` stays `false` there while the stream stays locked (node reports `true` and locked). The lock of the stream itself is what makes `getReader()` and `cancel()` throw, so the wrapper checks that. **Why the overrides are deleted.** oven-sh#6983 (for oven-sh#6200) made `text()`, `json()`, `arrayBuffer()`, `blob()`, `formData()` read `this.body` first, because a wrapper made after the consume crashed in the stream code of that time. Such a wrapper now ends without an error, and the test for each body method reads `res.body` for the first time after the method. Without the preload a plain `await res.json()` does not create a web stream and a node stream that nothing reads. **`clone()`.** `super.clone()` moves the body of the original to a new web stream (a `tee()` branch, or a fresh stream over the same bytes). The cached wrapper held the old stream, so `res.body` taken before `clone()` threw `ReadableStream is locked` on read after it, also on 1.4.2. With the lock check it would have ended without data instead. `clone()` now clears the cache. Real `node-fetch` also replaces `body` with a new `PassThrough` in `clone()`. **A body method that fails** (abort, network error, bad JSON) leaves the node stream ended without an error. The rejected promise of the body method carries the error. **Not in this PR.** On main `bodyUsed` is `false` after a body method that rejects when `.body` was read before it. That is native (`src/runtime/webcore/Body.rs`) and oven-sh#35847 covers the `formData()` part. **Suites run** on the debug build: `node-fetch.test.js`, `undici.test.ts`, `node-fetch-cjs.test.js`, `node-fetch-primordials.test.ts`, `undici-primordials.test.ts`, `node-stream.test.js`, `node-http-agent-free-socket.test.ts`, regression `26225`, `014865`, `04947`, and the Node `test-stream-readable-from-web-termination.js`, `test-readable-from-web-enqueue-then-close.js`, `test-whatwg-webstreams-adapters-to-*.js` files. </details> <!-- robobun:evidence:begin --> --- **[human-review]** gate passed · iteration 2 · 5 files touched <details><summary>fails on main (without fix)</summary> ```console ASAN without fix: 25 FAILED $ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/pr_gate.xml" test/js/first_party/undici/undici.test.ts test/js/node/http/node-fetch.test.js bun test v1.4.3 (6a92015) test/js/first_party/undici/undici.test.ts: (pass) undici > request > should make a GET request when passed a URL string [68.88ms] (pass) undici > request > should error when body has already been consumed [13.68ms] 97 | const url = new URL(method, server.url).href; 98 | 99 | for (const [action, expected] of bodyActions) { 100 | const { body } = await request(url); 101 | await body[method](); 102 | expect(await eventsUntilClose(body, () => body[action]())).toEqual([...expected]); ^ error: expect(received).toEqual(expected) [ - "end", + [TypeError: Invalid state: ReadableStream is locked], "close", ] - Expected - 1 + Received + 1 at <anonymous> (/workspace/bun/test/js/first_party/undici/undici.test.ts:102:72) (fail) undici > request > body stream when a body method took the r ... (truncated) release without fix: all passed bun test v1.4.3-canary.1 (7b5b9c1) test/js/first_party/undici/undici.test.ts: (pass) undici > request > should make a GET request when passed a URL string [2.61ms] (pass) undici > request > should error when body has already been consumed [0.37ms] (pass) undici > request > body stream when a body method took the response > ends without an error after arrayBuffer() consumed it [5.40ms] (pass) undici > request > body stream when a body method took the response > ends without an error after blob() consumed it [1.87ms] (pass) undici > request > body stream when a body method took the response > ends without an error after formData() consumed it [2.11ms] (pass) undici > request > body stream when a body method took the response > ends without an error after json() consumed it [2.05ms] (pass) undici > request > body stream when a body method took the response > ends without an error after text() consumed it [1.75ms] (pass) undici > request > body stream when a body method took the response > resume() leaves a body method that is still reading alone [2.04ms] (pass) undici > request > body stream when a body method took the response > destroy() leaves a body method that ... (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/first_party/undici/undici.test.ts test/js/node/http/node-fetch.test.js bun test v1.4.3 (6a92015) test/js/first_party/undici/undici.test.ts: (pass) undici > request > should make a GET request when passed a URL string [78.45ms] (pass) undici > request > should error when body has already been consumed [15.95ms] (pass) undici > request > body stream when a body method took the response > ends without an error after arrayBuffer() consumed it [258.02ms] (pass) undici > request > body stream when a body method took the response > ends without an error after blob() consumed it [57.58ms] (pass) undici > request > body stream when a body method took the response > ends without an error after formData() consumed it [50.54ms] (pass) undici > request > body stream when a body method took the response > ends without an error after json() consumed it [48.81ms] (pass) undici > request > body stream when a body method took the response > ends without an error after text() consumed it [48.04ms] (pass) undici > request > body stream when a bo ... (truncated) release with fix: all passed $ bun scripts/build.ts --profile=release [configured] bun-profile → bun (stripped) in 639ms (unchanged) ninja: Entering directory `/workspace/bun/build/release' [1/21] gen JS modules (bundle-modules) Preprocess modules (7038ms) Bundle modules (48ms) Postprocesss modules (24ms) Bundle Functions (489ms) Generate Code (42ms) [7.65s] Bundled "src/js" for production 2600 kb 197 internal modules 13 native modules 50 internal functions across 16 files [1/6] cargo bun_runtime → libbun_runtime.a �[1m�[92m Compiling�[0m bun_core v0.0.0 (/workspace/bun/src/bun_core) �[1m�[92m Compiling�[0m bun_errno v0.0.0 (/workspace/bun/src/errno) �[1m�[92m Compiling�[0m bun_ptr v0.0.0 (/workspace/bun/src/ptr) �[1m�[92m Compiling�[0m bun_boringssl_sys v0.0.0 (/workspace/bun/src/boringssl_sys) �[1m�[92m Compiling�[0m bun_safety v0.0.0 (/workspace/bun/src/safety) �[1m�[92m Compiling�[0m bun_base64 v0.0.0 (/workspace/bun/src/base64) �[1m�[92m Compiling�[0m bun_cares_sys v0.0.0 (/workspace/bun/src/cares_sys) �[1m�[92m Compiling�[0m bun_zlib_sys v0.0.0 (/workspace/bun/src/zlib_sys) �[1m�[92m Compiling�[0m bun_zstd v0.0.0 (/workspace/bun/src/zstd) �[1m�[92m Compili ... (truncated) ``` </details> <details><summary>diff hotspot</summary> ``` src/js/internal/webstreams_adapters.ts | 30 ++++-- src/js/thirdparty/node-fetch.ts | 36 +------ src/js/thirdparty/undici.js | 2 +- test/js/first_party/undici/undici.test.ts | 127 +++++++++++++++++++++++++ test/js/node/http/node-fetch.test.js | 150 ++++++++++++++++++++++++++++++ 5 files changed, 304 insertions(+), 41 deletions(-) ``` </details> **gate history** · 2 passed · 0 rejected · iteration 2 <details><summary>evidence per changed file</summary> ``` file reads edits tests src/js/internal/webstreams_adapters.ts 5 11 17 src/js/thirdparty/node-fetch.ts 3 3 17 src/js/thirdparty/undici.js 2 3 17 test/js/first_party/undici/undici.test.ts 1 1 12 test/js/node/http/node-fetch.test.js 2 3 17 ``` </details> <!-- robobun:evidence:end -->
…-sh#42737) ### Problem - A request for every export of a file (`import * as`, `export * from`, `import()`, `require()`) makes the bundler load the target of an import the parser dropped: an unused TypeScript import or a macro import. `import * as ns from "./a"` fails with `Could not resolve: "missing-pkg"` from a file that only a type import in `a.ts` names. A macro module that imports `bun` fails `--target=browser`: `Browser build cannot import Bun builtin: "bun"`. - The cause is `un_defer_record` (`src/bundler/barrel_imports.rs:296`). It clears `IS_UNUSED`, which barrel optimization uses to defer a re-export. The parser sets the same flag on imports it drops, and the request walks every record of the target file. - A failed build reported one or two errors for the same 6 files, by parse order. ### Fix - `apply_barrel_optimization` marks each record it defers with the new `ImportRecordFlags::IS_BARREL_DEFERRED`. `un_defer_record` acts only on that flag. - A file that fails to resolve drops the flag from its records: its imports are not followed. - Correct because the parser removes the statement of every other `IS_UNUSED` record. esbuild agrees on each repro. - Verified: `test/bundler/bundler_barrel.test.ts`, 8 new tests, each fails on main. Other suites in Notes. ### Background - A barrel is a `sideEffects: false` module whose exports are all re-exports. `apply_barrel_optimization` defers the re-exports nobody asked for: the record gets `IS_UNUSED`, so its target does not load. - `schedule_barrel_deferred_imports` runs for every file and un-defers what it requests from each target. A namespace request needs every export. - A file whose resolution fails stays in the graph as an empty row plus its import records. <details><summary>Notes</summary> Deterministic repro (1.4.2 and main fail, 1.3.9 and this branch build): ```sh printf 'import { T } from "./types";\nexport const value: T = 1;\n' > a.ts printf 'import "missing-pkg";\nexport type T = number;\n' > types.ts printf 'import * as ns from "./a";\nconsole.log(ns.value);\n' > entry.ts bun build --target=bun ./entry.ts # error: Could not resolve: "missing-pkg" at types.ts:1:8 # `import { value } from "./a"` builds on every version ``` Macro form: ```sh printf 'import { version } from "bun";\nexport function getValue() { return typeof version; }\n' > m.ts printf 'import { getValue } from "./m.ts" with { type: "macro" };\nexport const v = getValue();\n' > a.ts printf 'import * as ns from "./a.ts";\nconsole.log(ns.v);\n' > star.ts bun build --target=browser ./star.ts # error: Browser build cannot import Bun builtin: "bun" at m.ts:1:25 ``` The fuzz report that led here (same 6 files, 300 builds in one process, release build of 5fce36e): ``` e0.ts: await import("./f0.ts") f0.ts: export * from "./f2.ts" e1.ts: await import("./f2.ts") f2.ts: import { get5, C5 } from "./f5.ts"; import { fn } from "missing-pkg"; export const two = fn e2.ts: await import("./f7.ts") f5.ts: import "./f7.ts" f7.ts: import { fn } from "missing-pkg"; export const seven = fn entries e0 e1: 174x [f2.ts:2] 126x [f2.ts:2, f7.ts:1] entries e0 e1 e2: 207x [f2.ts:2, f7.ts:1] 93x [f2.ts:2, f7.ts:1, f7.ts:1] this branch: 60/60 [f2.ts:2] 60/60 [f2.ts:2, f7.ts:1] ``` Why it looked like a race. `f2.ts` fails to resolve `missing-pkg`, so `on_parse_task_complete` takes the `Err` arm and never calls `schedule_barrel_deferred_imports` for it. `run_resolution_for_parse_task` keeps the import records of a failed file on the graph (for pending plugin `onResolve` answers). When `f0.ts` (`export * from "./f2.ts"`) finishes after that, its request walks those records, clears `IS_UNUSED` on the dropped `./f5.ts` import, resolves it, and `f5.ts` and `f7.ts` load. When `f0.ts` finishes first, the row of `f2.ts` is still empty and nothing happens. With `f2.ts` free of its own error the walk always runs (from `f0.ts` or from the pass of `f2.ts` itself), so the `f7.ts` error appears in every build. That error is not a real error of the build: `f5.ts` and `f7.ts` sit behind an import TypeScript drops, and esbuild builds that tree. Why the same error twice. `resolve_barrel_records` reads `graph.ast.items_target()[idx]`. The row of a failed file is `JSAst::empty`, whose target is `browser`. The build target was `bun`, so `./f5.ts` resolved into the browser graph, and `f7.ts`, already parsed once through `e2.ts`, parsed again there. History. Barrel optimization landed in 1.3.10 (oven-sh#26892) and the `import * as` form fails from that release on. oven-sh#36838 (1.4.0) made `export * from` a full request as well. The report guessed oven-sh#41145 for the rise in frequency at 1.4.1. That PR changes the linker, which a failed build never reaches. I did not bisect what moved the rate. Why a flag and not a narrower walk. The walk could visit only the records that named exports refer to, which is the set `apply_barrel_optimization` can defer. Under HMR, `ConvertESMExportsForHmr` also marks the second of two `export { .. } from "./same.js"` records `IS_UNUSED`, and the named-export path of the BFS un-deferred it too. The flag is exact for all three call sites of `un_defer_record`. A record that is both an HMR duplicate and deferred still un-defers as before. `ImportRecordFlags` is a `u32` with bits 0 to 18 in use. Not fixed here. A barrel that first parses with every record deferred, and whose un-deferred record later fails to resolve, is not a failed file: `resolve_barrel_records` ignores `last_error`, and its other records can still un-defer. So a build that fails inside a barrel can still report a different set of additional errors from run to run. Making that deterministic means following the resolvable imports of a failed file, which is a larger change. Suites run on the debug build: `bundler_barrel` (70 pass), `bundler_splitting`, `bundler_dynamic_import_dce`, `bundler_cjs2esm`, `bundler_edgecase`, `bundler_plugin`, `esbuild/ts`, `esbuild/importstar`, `esbuild/importstar_ts`, `esbuild/dce`, `esbuild/default`, `regression/issue/40606`, `30493`, `28170`, and the barrel tests of `bake/dev/bundle.test.ts`. `bun-build-api` has two 5 s timeouts in bytecode tests under the debug build, the same on main. With `src/` at main, all 8 new tests fail on the debug build (6 of 6 runs for the three that bias parse order with a 4 MB comment) and on the release build. </details>
…he HTTP/3 engine (oven-sh#42732) ### Problem - HTTP/3 uses more than 100% CPU when UDP sends keep failing with an errno other than `EAGAIN`. Both `fetch()` and `Bun.serve({ http3: true })`. - Two triggers: an iptables DROP rule (`EPERM`), and an egress MTU below 1500, where each DPLPMTUD probe fails with `EMSGSIZE`. - The cause is the tail of `us_quic_packets_out` (`packages/bun-usockets/src/quic.c:316`). It reports every send errno as `EAGAIN` and arms `LIBUS_SOCKET_WRITABLE`. The socket is already writable, so `on_drain` fires at once and the send fails again. ### Fix - `us_quic_packets_out` passes `EMSGSIZE` through. lsquic retires that datagram with `ci_packet_too_large` and feeds DPLPMTUD. - Any other refused datagram counts as sent. To lsquic that is a packet lost on the wire, so its loss timer paces the retries and a timeout ends the connection. - Only `EAGAIN`, `EWOULDBLOCK` and `ENOBUFS` still return short and arm `WRITABLE`. quinn draws the same line. - Verified: `fetch-http3-syscall-fault.test.ts`, four new tests, three fail on stock bun. Also the other h3 suites and `node:quic`, on Linux and Windows. ### Background - lsquic calls `us_quic_packets_out` to send a batch of datagrams. One engine serves every HTTP/3 connection of the process, so one refused peer stalls the rest. - A short return with `EAGAIN` stops every send of that engine until `lsquic_engine_send_unsent_packets` runs. Bun runs it from `on_drain`, the callback of a writable UDP poll. - A short return with `EMSGSIZE` retires one datagram and leaves the engine running. - Any other errno closes the connection that owns the first unsent datagram. A pending ICMP error on the shared client socket belongs to no particular peer, so that does not fit. <details><summary>Notes</summary> **Reach: what was run, and what was simulated.** The unsendable-IP-literal trigger is real (`EACCES` from the kernel, no privileges needed). `EPERM` from a firewall rule is simulated two ways: a seccomp filter that fails `sendmsg`/`sendmmsg`, and `US_FAULT_SENDMSG`. The report this came from also saw it with a real `iptables -A OUTPUT -p udp --dport <port> -j DROP`. The low egress MTU is simulated with an `LD_PRELOAD` shim, because the container has no `CAP_NET_ADMIN` to set a link MTU. No user has reported this. The HTTP/3 API is experimental, so this is a low-priority fix. **Repro without privileges.** `fetch("https://255.255.255.255/", { protocol: "http3", signal: AbortSignal.timeout(1500) })`. An IP literal skips DNS and the connect-time route probe (`us_quic_socket_context_connect`), and `sendmsg` to the limited broadcast address fails every time on a socket without `SO_BROADCAST`. Unset `HTTPS_PROXY` first, a proxy makes fetch refuse HTTP/3 up front. Stock bun uses 2056 ms of CPU in a 1502 ms wait, and 1354 ms of it after the abort. With the fix: 69 ms, then 25 ms. **Tests.** - `a datagram the kernel refuses to send is dropped without spinning the HTTP thread` uses that address in a child process and compares `process.cpuUsage()` with the wall time of a 1 s wait. It needs no fault injection, so it runs on release builds too. Unfixed: 1365 ms CPU (release), 1033 ms (debug). Fixed: 34 ms. Skipped on Windows, where the dual-stack socket sends to `::ffff:255.255.255.255` without an error. - `Bun.serve: a send error on every datagram does not spin the server's event loop` arms `EPERM` on every send from inside a request handler and reads the server child's CPU time. Spin: 2124 ms CPU in 1050 ms. Fixed: 135 ms. - `Bun.serve: a refused version-negotiation reply does not spin the loop when no connection exists` sends one long-header datagram with version `0x0a0a0a0a`, built from a real Initial with its version bytes replaced. The server queues a Version Negotiation reply for a connection it does not have. The test first sends the datagram to an unfaulted server and checks that the reply is a Version Negotiation packet that offers QUIC v1, so the CPU check cannot pass without a reply to refuse. This is the only spin with no connection and no timeout to end it. Spin: 2129 ms CPU in 1052 ms. Fixed: 325 ms against a 150 ms idle baseline for a debug ASAN server. On the release binary under seccomp the old code uses 2637 ms in 2002 ms. - `a DPLPMTUD probe above the egress MTU does not stall the transfer` streams 2.5 s of body under an `LD_PRELOAD` shim that refuses any datagram above 1400 payload bytes, which is above lsquic's base packet size and below its first probe. Unfixed: the transfer delivers 32 KB, stalls for the remaining 11 s, and the next request on the same engine times out. Fixed: 3.1 MB delivered, no stall, 696 ms CPU in 4049 ms, and each probe refused once instead of twice. - The MTU shim declares `sendmmsg` with the flags type of the libc it builds against: `int` on glibc, `unsigned int` on musl. - An injected 0 from `US_FAULT_SENDMSG` (the `zero` action) now counts as one datagram sent in the `sendmmsg` path, as it already does in `us_quic_send_one`. Before, it left that loop without progress. Only the test hook can reach this. - The two `Bun.serve` tests pass on stock bun for a different reason: the old `sendmmsg` retry does not go through `US_FAULT_SENDMSG`, so an injected error cannot persist and the retry sends the datagram. This PR puts the retry behind the hook. The CPU numbers above come from a build with the hook and the old errno logic. **`IP_PMTUDISC_PROBE`.** The comment in `us_quic_set_dontfrag` claimed that this option lets DPLPMTUD probe without `EMSGSIZE`. It does not. It makes the kernel ignore its cached path MTU. The device MTU still bounds the datagram: on a 1500 MTU link, a 1472-byte payload is sent and 1473 bytes gives `EMSGSIZE`. The comment now says that, and names where the errno goes. **Prior art.** quinn waits for a writable socket only on `WouldBlock`. It logs every other send error and goes on (`UdpSenderHelper::poll_send` in `quinn/src/runtime/mod.rs`, with the test `non_would_block_send_errors_are_logged_and_ignored` using `PermissionDenied`). Its `quinn-udp` doc says UDP send errors are non-fatal "because higher-level protocols must employ retransmits and timeouts anyway". **Not in this change.** `node:quic`'s own `packets_out` (`src/runtime/node/quic/endpoint.rs:792-803`) has the same errno rewrite. It does not spin: `us_udp_socket_send` arms `WRITABLE` only for `EAGAIN`, so each failure costs one second through lsquic's failsafe. It also keeps `EMSGSIZE`, as this PR now does. A classifier change there belongs in its own PR, because oven-sh#40220 rewrites that file (+645/-1056). **Relation to oven-sh#42678.** Both change the same two `sendmmsg` calls, and oven-sh#42678 calls this behaviour "a separate bug". This PR is the smaller of the two, so it should land first. The conflict is mechanical: the call moves into `us_quic_sendmmsg`. **Other cases that stay as they are.** `ENOBUFS` remains backpressure, as oven-sh#35255 chose. That holds on Windows too: `us_quic_send_one` keeps `WSAENOBUFS` as `ENOBUFS`. Before, it became `EIO`, which the old tail still treated as backpressure and this PR would have dropped. A UDP socket that is already closed (`!ls->udp`) still returns short with no poll to arm, so lsquic's one-second failsafe paces it. **Self-reviewed:** 8 concerns raised, 5 addressed (the `EMSGSIZE` classifier and its false comment, the zero-connection spin, the `node:quic` twin note, the oven-sh#42678 note, the reach note). 3 rejected: folding the `node:quic` fix in (oven-sh#40220 rewrites that file), patching lsquic instead (the callback contract has no fourth outcome), and a client-side address-walk change (a separate behaviour, not this bug). </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-http3-syscall-fault.test.ts <!-- robobun:evidence:end -->
… the whole payload in memory (oven-sh#42731) ### Problem - Every S3 upload path (`Bun.write(s3file, Bun.file(path))`, `s3file.writer()`, streams) keeps the whole payload in memory. A 500 MB upload grows RSS by about 850 MB, and a process under a memory limit is OOM-killed. `fetch()` with the same `Bun.file` stays flat. Fixes oven-sh#42722. - The cause is `bun_io::StreamBuffer` (`src/io/PipeWriter.rs:1774`). `wrote(n)` only moves `cursor`, and `reset()` runs only when the buffer drains to empty. `MultiPartUpload::process_multi_part` (`src/runtime/webcore/s3/multipart.rs:907`) enqueues `partSize` slices and leaves the remainder behind. The file reader delivers chunks that never line up with `partSize`, so the buffer is never empty and every consumed byte stays in `list`. ### Fix - `StreamBuffer::compact` drops the consumed prefix. The write paths (`write`, `write_latin1`, `write_utf16`, `ensure_unused_capacity`) call it before they append, once the prefix is at least as large as the unread tail. That threshold keeps the memmove cost linear when one large backlog is drained a part at a time. - The node:http socket write buffer in `src/runtime/socket/uws_jsc.rs` is a separate mirror of the same type and never resets at all. It gets the same rule. - Correct because every byte before `cursor` is already consumed: the S3 path duplicates each part before it advances the cursor, and the socket paths have written those bytes. No caller holds a pointer into the buffer across a write. The one caller that reads `cursor` as state is the IPC send queue (`src/runtime/ipc.rs`), which treats `cursor == 0` on the first entry as "not started". It no longer appends a new message to a partially sent entry, so that entry keeps its cursor. - Verified: `test/js/bun/s3/s3-upload-memory.test.ts` (uploads 64 MiB and 192 MiB, asserts peak RSS grows by less than 64 MiB; on main it grows by 100 to 240 MiB). Also `test/js/bun/s3/`, `node-http-backpressure*`, `node-http-pinned-write`, `node-http-nested-cork`, `bun-write`, the spawn stdin suites, and the ipc suites (`spawn.ipc*`, `child_process_ipc*`). ### Background - `StreamBuffer` is a `{ list: Vec<u8>, cursor: usize }` write queue. Producers append to `list`, a consumer reads `list[cursor..]` and calls `wrote(n)` for the bytes it took. - An S3 multipart upload buffers incoming bytes in one `StreamBuffer`, cuts `partSize` slices from it, and sends up to `queueSize` parts at once. The bytes that do not fill a part wait for the next chunk. - The same buffer type backs pipe writers (spawn stdin, `FileSink`), the HTTP/2 and proxy tunnel write queues, and the node:http socket write path. <details><summary>Notes</summary> Reproduced with the issue's script on linux x64 (release 1.4.2): `fetch` delta 26 MB, `s3` delta 847 MB for a 477 MB payload. A writer fed `partSize` sized chunks stays flat, a writer fed `partSize + 1` sized chunks keeps the payload (368 MB for 300 MB). The debug log shows the per-chunk pattern `5242880 slice enqueued` then `262144 slice too small`. Peak RSS delta of the new test fixture, 64 MiB then 192 MiB payload: | build | `Bun.file` path | `.writer()` path | | --- | --- | --- | | main, release | 204 / 310 | 128 / 361 | | fixed, debug (ASAN, quarantine off) | 101 / 112 | 57 / 70 | | fixed, release | 107 / 130 | 40 / 52 | The steady state floor depends on the build and the file reader's read-ahead, so the test checks growth between the two sizes, not an absolute bound. The issue also points out that a direct `.writer()` returns a plain number from `write()` with no backpressure signal. That is a separate concern and the growth above happens even when the producer awaits `flush()` after every write. `test/js/bun/io/bun-write.test.js` "on large files" times out at 5 s under this debug build. It fills a 64M element typed array in a JS loop (2.7 s alone) and copies files, and does not touch `StreamBuffer`. Self-reviewed: 2 concerns raised, 2 addressed (the first draft applied the rule only at the S3 call site; it now lives in the shared type and covers the socket mirror). </details> <!-- robobun:evidence:begin --> --- **[human-review]** gate passed · iteration 1 · 4 files touched <details><summary>fails on main (without fix)</summary> ```console ASAN without fix: 2 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/s3/s3-upload-memory.test.ts" bun test v1.4.3 (09bb546) test/js/bun/s3/s3-upload-memory.test.ts: 105 | // parts in flight and their copies. That floor depends on the build, so the 106 | // check is that 128 MiB more payload does not add anything near 128 MiB of 107 | // resident memory. The unfixed build adds at least the payload. 108 | async function expectUploadMemoryNotToGrowWithPayload(upload: string) { 109 | const [small, large] = await Promise.all([uploadRssDeltaMiB(upload, 64), uploadRssDeltaMiB(upload, 192)]); 110 | expect(large - small, `peak RSS delta: 64 MiB upload ${small} MiB, 192 MiB upload ${large} MiB`).toBeLessThan(64); ^ error: peak RSS delta: 64 MiB upload 121 MiB, 192 MiB upload 253 MiB Expected: < 64 Received: 132 at expectUploadMemoryNotToGrowWithPayload (/workspace/bun/test/js/bun/s3/s3-upload-memory.test.ts:110:100) at async <anonymous> (/workspace/bun/test/js/bun/s3/s3-upload- ... (truncated) release without fix: all passed bun test v1.4.3-canary.1 (eb2f4eb) test/js/bun/s3/s3-upload-memory.test.ts: (pass) s3file.writer() fed chunks that do not line up with partSize releases sent bytes [326.06ms] (pass) Bun.write(s3file, Bun.file()) does not keep the whole file in memory [361.08ms] 2 pass 0 fail 10 expect() calls Ran 2 tests across 1 file. [423.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/s3/s3-upload-memory.test.ts" bun test v1.4.3 (09bb546) test/js/bun/s3/s3-upload-memory.test.ts: (pass) s3file.writer() fed chunks that do not line up with partSize releases sent bytes [1500.40ms] (pass) Bun.write(s3file, Bun.file()) does not keep the whole file in memory [2041.38ms] 2 pass 0 fail 10 expect() calls Ran 2 tests across 1 file. [3.98s] __F:0:S:0 release with fix: all passed $ bun scripts/build.ts --profile=release [configured] bun-profile → bun (stripped) in 611ms (unchanged) ninja: Entering directory `/workspace/bun/build/release' [1/6] gen generated_host_exports.rs generated_host_exports.rs: 122 exports (host=5, lazy=10, generic=107, rust=0); 243 extern-C blocks audited [1/6] cargo bun_runtime → libbun_runtime.a �[1m�[92m Compiling�[0m bun_core v0.0.0 (/workspace/bun/src/bun_core) �[1m�[92m Compiling�[0m bun_errno v0.0.0 (/workspace/bun/src/errno) �[1m�[92m Compiling�[0m bun_ptr v0.0.0 (/workspace/bun/src/ptr) �[1m�[92m Compiling�[0m bun_boringssl_sys v0.0.0 (/workspace/bun/src/boringssl_sys) �[1m�[92m Compiling�[0m bun_safety v0.0.0 (/workspace/bun/src/safety) �[1m�[92m Compiling�[0m bun_base64 v0.0.0 (/workspace/bun/src/base64) �[1m�[92m Compiling�[0m bun_cares_sys v0.0.0 (/workspace/bun/src/cares_sys) �[1m�[92m Compiling�[0m bun_zlib_sys v0.0.0 (/workspace/bun/src/zlib_sys) �[1m�[92m Compiling�[0m bun_zstd v0.0.0 (/workspace/bun/src/zstd) �[1m�[92m Compiling�[0m bun_picohttp v0.0.0 (/workspace/bun/src/picohttp) �[1m�[92m Compiling�[0m bun_paths v0.0.0 (/workspace/bun/src/paths) �[1m�[92m Compiling�[0m b ... (truncated) ``` </details> <details><summary>diff hotspot</summary> ``` src/io/PipeWriter.rs | 13 ++++ src/runtime/ipc.rs | 7 +- src/runtime/socket/uws_jsc.rs | 5 ++ test/js/bun/s3/s3-upload-memory.test.ts | 129 ++++++++++++++++++++++++++++++++ 4 files changed, 152 insertions(+), 2 deletions(-) ``` </details> **gate history** · 2 passed · 1 rejected · iteration 1 <details><summary>evidence per changed file</summary> ``` file reads edits tests src/io/PipeWriter.rs 3 3 20 src/runtime/ipc.rs 1 2 21 src/runtime/socket/uws_jsc.rs 1 1 20 test/js/bun/s3/s3-upload-memory.test.ts 4 8 20 ``` </details> **root cause** · written by the author bot S3 uploads grew without bound because the stream write buffers in the pipe writer and the socket encoding path only advanced a read cursor as data was sent and never reclaimed the consumed prefix, so under backpressure the entire payload accumulated in memory. The fix compacts the buffer whenever the consumed prefix is at least as large as the remaining unread data, moving the unsent bytes to the front and resetting the cursor before the buffer is reused, which keeps resident memory proportional to the in-flight parts rather than the file size. A related IPC send queue adjustment ensures a … <!-- robobun:evidence:end -->
…ide its own socket callback (oven-sh#42693) ### Problem - A `fetch()` with its own TLS context (for example `tls: { serverName }`) holds the last ref to that `HTTPContext` once the 60-entry context cache evicts it. When the server closes the connection, a debug ASAN build reports `AddressSanitizer: heap-use-after-free` in `us_internal_ssl_detach` (`packages/bun-usockets/src/crypto/openssl.c:1827`). A release build shows nothing. - The request drops its ref in the result callback (`src/http/AsyncHTTP.rs:745`), inside the close callback of the context's own socket. That frees the context and the socket group embedded in it. `us_internal_ssl_on_close` then reads `s->group->loop` (`openssl.c:2303`). - Found by fuzzing, no user report. It needs over 60 `tls` configs in one process, or a request older than the 30-minute cache TTL. ### Fix - The last deref of an `HTTPContext` no longer frees it in place. `#[ref_count(destroy = Self::destroy_between_ticks)]` queues it on the HTTP thread, and `process_events` frees it between `drain_events()` and the next `tick()`. - Correct because all work of the HTTP thread runs inside those two calls. No socket callback is on the stack between them, whoever dropped the last ref. - Verified: `test/js/web/fetch/fetch-http2-client.test.ts`. Two new ASAN-only tests (h2 and HTTP/1.1) fail with `src/` at main. A third checks that the context is still freed. ### Background - An `HTTPContext` embeds one uSockets socket group, and each socket points into it (`s->group`). - Custom TLS contexts are refcounted (oven-sh#29334). The cache holds one ref and each request holds one. Eviction drops only the cache ref. - `HttpThread::process_events` is the HTTP thread's loop. `drain_events()` starts and aborts requests. `tick()` runs the socket callbacks. - `WindowsNamedPipeContext` defers its free with the same hook. <details><summary>Notes</summary> ASAN report on main (3f7f046), HTTP/1.1 run, trimmed: ``` ERROR: AddressSanitizer: heap-use-after-free READ of size 8, 72 bytes inside of 208-byte region, thread T4 (HTTP Client) #0 us_internal_ssl_detach packages/bun-usockets/src/crypto/openssl.c:1827 #1 us_internal_ssl_on_close packages/bun-usockets/src/crypto/openssl.c:2303 #2 us_internal_socket_close_raw packages/bun-usockets/src/socket.c:328 #3 us_internal_ssl_on_end packages/bun-usockets/src/crypto/openssl.c:2393 freed by thread T4 (HTTP Client): #12 HTTPContext<true>::destroy #15 RefPtr<HTTPContext<true>>::drop #19 AsyncHTTP::on_async_http_callback_raw src/http/AsyncHTTP.rs:745 #21 HTTPClient::dispatch_result_and_reset src/http/lib.rs:1618 #22 HTTPClient::fail src/http/lib.rs:3970 #23 HTTPClient::on_close::<true> src/http/lib.rs:2163 #24 Handler<true>::on_close src/http/HTTPContext.rs:1341 #28 us_internal_ssl_on_close packages/bun-usockets/src/crypto/openssl.c:2301 ``` The h2 run frees through `fail_from_h2`, called by `ClientSession::fail_streams`, called by `ClientSession::on_close`. oven-sh#42647 fixed a different defect with the same trigger (a stream freed twice in the h2 deliver loop). With this change that trigger is gone too: the context's `Drop`, which closes the session's socket, no longer runs inside the deliver loop. One more path fails on main with the same report: a keep-alive socket that the server closes before it answers. The request dials again from inside the close callback, and the new context displaces the ref on the old one. A redirect, an idle timeout, a DNS failure, an abort and a normal end of the response on an evicted context show no report on main. Why the fix is in `HTTPContext` and not in uSockets. `HTTPContext` is the only socket group owner in bun that freed its group from inside a socket callback. `Listener` frees its group from a finalizer, and the other TLS users share per-VM groups. The safety contract on `SocketGroup::destroy` (`src/uws_sys/SocketGroup.rs`) already says that it must not run while the loop walks the group. A C-side change that passes `loop` into `us_internal_ssl_detach` also stops this report. It leaves the context free to die under Rust frames that still hold its raw pointer, and the next read of `s->group` after a dispatch brings the report back (that read came with oven-sh#31584, and `ssl_release_batch` after it). Two comments in uSockets said the opposite of the Rust contract: `us_socket_group_deinit` called a deinit from `on_close` fine. They now say what `SocketGroup::destroy` says. No C code changes. An earlier draft of this branch routed each holder (`AsyncHTTP::on_async_http_callback_raw`, `HttpThread::connect`) through a queue of refs. The hook replaces that: no holder can get it wrong, and only dead contexts are queued, not one ref per request. No wakeup is needed. A context that dies during `tick()` is freed as soon as that tick returns. One that dies during `drain_events()` (a request that fails at start, a cache eviction) is freed right after it. At process exit the queue is not drained, like the cache. Related history: oven-sh#31660 (closed) is a crash of the same class in the Zig implementation, where the last ref went away inside `onLongTimeout`. Tests: - The ASAN-only block from oven-sh#42647 now takes a protocol. The child holds a response open on a context made by `serverName`, runs 61 more TLS configs to evict it, and writes `evicted` to stderr. The two new tests then destroy the server side of the held TLS socket, over h2 and over HTTP/1.1. With `src/` at main both fail with the report above. - `an evicted custom TLS context is freed when its last request ends` runs on each build. It does not fail on main. It exists because the deferral adds a way to leak: if the queue is never drained, a dead context lives forever. The test keeps one request busy on a context, leaves a second connection idle in that context's keep-alive pool, evicts the context, ends the busy request, and waits for the server to see the idle connection close. With the `heap::destroy` call removed the test times out. Suites run on the debug ASAN build: `fetch-http2-client.test.ts` (70 pass), `fetch-http2-leak.test.ts` (7), `fetch-http2-adversarial.test.ts` (20), `fetch.tls.test.ts` (34), `fetch-redirect.test.ts` (30), `fetch-tls-abortsignal-timeout.test.ts` (6), `fetch-proxy-tls-intern-race.test.ts` (1), `tls-keepalive.test.ts` (4 pass, 2 skip), `fetch-abort-ssl-context-eviction.test.ts` (1), `regression/issue/27358.test.ts` (2). On a release build of this branch: `tls-keepalive.test.ts` 6 pass (same config: 20000 requests, 0 MB growth. 200 distinct configs: 1 MB growth), `fetch-http2-client.test.ts` 66 pass and 4 skip, `fetch-abort-ssl-context-eviction.test.ts` 1 pass. </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: 2 FAILED $ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/pr_gate.xml" "test/js/web/fetch/fetch-http2-client.test.ts" bun test v1.4.3 (b993710) test/js/web/fetch/fetch-http2-client.test.ts: (pass) fetch() over HTTP/2 (BUN_FEATURE_FLAG_EXPERIMENTAL_HTTP2_CLIENT) > GET: status, headers and body round-trip [1172.89ms] (pass) fetch() over HTTP/2 (BUN_FEATURE_FLAG_EXPERIMENTAL_HTTP2_CLIENT) > response body larger than one DATA frame [989.87ms] (pass) fetch() over HTTP/2 (BUN_FEATURE_FLAG_EXPERIMENTAL_HTTP2_CLIENT) > concurrent requests multiplex on one h2 session [1222.39ms] (pass) fetch() over HTTP/2 (BUN_FEATURE_FLAG_EXPERIMENTAL_HTTP2_CLIENT) > POST with ReadableStream body streams as raw DATA frames [467.33ms] (pass) fetch() over HTTP/2 (BUN_FEATURE_FLAG_EXPERIMENTAL_HTTP2_CLIENT) > POST: request body is delivered as DATA frames [1562.88ms] (pass) fetch() over HTTP/2 (BUN_FEATURE_FLAG_EXPERIMENTAL_HTTP2_CLIENT) > gzip content-encoding is decompressed [1655.77ms] (pass) fetch() over HTTP/2 (BUN_FEATURE_FLAG_EXPERIMENTAL_HTTP2_CLIENT) > POST with ReadableStream body larger than initial send window [960.24m ... (truncated) release without fix: 4 skipped bun test v1.4.3-canary.1 (722de17) test/js/web/fetch/fetch-http2-client.test.ts: (pass) fetch() over HTTP/2 (BUN_FEATURE_FLAG_EXPERIMENTAL_HTTP2_CLIENT) > GET: status, headers and body round-trip [73.34ms] (pass) fetch() over HTTP/2 (BUN_FEATURE_FLAG_EXPERIMENTAL_HTTP2_CLIENT) > response body larger than one DATA frame [65.19ms] (pass) fetch() over HTTP/2 (BUN_FEATURE_FLAG_EXPERIMENTAL_HTTP2_CLIENT) > gzip content-encoding is decompressed [89.92ms] (pass) fetch() over HTTP/2 (BUN_FEATURE_FLAG_EXPERIMENTAL_HTTP2_CLIENT) > POST: request body is delivered as DATA frames [102.83ms] (pass) fetch() over HTTP/2 (BUN_FEATURE_FLAG_EXPERIMENTAL_HTTP2_CLIENT) > connection-specific request headers are stripped before HPACK [74.16ms] (pass) fetch() over HTTP/2 (BUN_FEATURE_FLAG_EXPERIMENTAL_HTTP2_CLIENT) > multiple Set-Cookie response headers survive HPACK decode [74.43ms] (pass) fetch() over HTTP/2 (BUN_FEATURE_FLAG_EXPERIMENTAL_HTTP2_CLIENT) > concurrent requests multiplex on one h2 session [101.86ms] (pass) fetch() over HTTP/2 (BUN_FEATURE_FLAG_EXPERIMENTAL_HTTP2_CLIENT) > abort sends RST_STREAM; siblings on the session survive [107.88ms] (pass) fetch() over HTTP/2 (BUN_FE ... (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/web/fetch/fetch-http2-client.test.ts" bun test v1.4.3 (b993710) test/js/web/fetch/fetch-http2-client.test.ts: (pass) fetch() over HTTP/2 (BUN_FEATURE_FLAG_EXPERIMENTAL_HTTP2_CLIENT) > GET: status, headers and body round-trip [1119.35ms] (pass) fetch() over HTTP/2 (BUN_FEATURE_FLAG_EXPERIMENTAL_HTTP2_CLIENT) > response body larger than one DATA frame [988.06ms] (pass) fetch() over HTTP/2 (BUN_FEATURE_FLAG_EXPERIMENTAL_HTTP2_CLIENT) > concurrent requests multiplex on one h2 session [1222.20ms] (pass) fetch() over HTTP/2 (BUN_FEATURE_FLAG_EXPERIMENTAL_HTTP2_CLIENT) > POST with ReadableStream body streams as raw DATA frames [531.27ms] (pass) fetch() over HTTP/2 (BUN_FEATURE_FLAG_EXPERIMENTAL_HTTP2_CLIENT) > POST: request body is delivered as DATA frames [1925.52ms] (pass) fetch() over HTTP/2 (BUN_FEATURE_FLAG_EXPERIMENTAL_HTTP2_CLIENT) > gzip content-encoding is decompressed [2051.61ms] (pass) fetch() over HTTP/2 (BUN_FEATURE_FLAG_EXPERIMENTAL_HTTP2_CLIENT) > POST with ReadableStream body larger than initial send window [837.85m ... (truncated) release with fix: 4 skipped $ bun scripts/build.ts --profile=release [configured] bun-profile → bun (stripped) in 846ms (unchanged) ninja: Entering directory `/workspace/bun/build/release' [1/128] gen generated_host_exports.rs generated_host_exports.rs: 122 exports (host=5, lazy=10, generic=107, rust=0); 243 extern-C blocks audited [2/128] gen cpp.rs (cppbind) [3/128] gen JS modules (bundle-modules) Preprocess modules (9358ms) Bundle modules (81ms) Postprocesss modules (248ms) Bundle Functions (727ms) Generate Code (35ms) [10.46s] Bundled "src/js" for production 2600 kb 197 internal modules 13 native modules 50 internal functions across 16 files [3/127] cargo bun_runtime → libbun_runtime.a �[1m�[92m Compiling�[0m bun_threading v0.0.0 (/workspace/bun/src/threading) �[1m�[92m Compiling�[0m bun_react_compiler v0.0.0 (/workspace/bun/src/react_compiler) �[1m�[92m Compiling�[0m bun_io v0.0.0 (/workspace/bun/src/io) �[1m�[92m Compiling�[0m bun_watcher v0.0.0 (/workspace/bun/src/watcher) �[1m�[92m Compiling�[0m bun_crash_handler v0.0.0 (/workspace/bun/src/crash_handler) �[1m�[92m Compiling�[0m bun_event_loop v0.0.0 (/workspace/bun/src/event_loop) �[1m�[92m Compiling�[0m bun_ ... (truncated) ``` </details> <details><summary>diff hotspot</summary> ``` packages/bun-usockets/src/context.c | 10 ++- packages/bun-usockets/src/loop.c | 10 +-- src/http/HTTPContext.rs | 17 +++- src/http/HTTPThread.rs | 18 ++++ test/js/web/fetch/fetch-http2-client.test.ts | 125 ++++++++++++++++++++++----- 5 files changed, 151 insertions(+), 29 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/context.c 1 1 28 packages/bun-usockets/src/loop.c 1 1 28 src/http/HTTPContext.rs 4 5 28 src/http/HTTPThread.rs 5 15 28 test/js/web/fetch/fetch-http2-client.test.ts 4 11 28 ``` </details> <!-- robobun:evidence:end -->
oven-sh#42688) ### Problem - `statx(2)` unavailable (kernel before 4.11, or seccomp): `fs.stat` reports `birthtime` 1970-01-01. Node reports ctime. `stat_birthtime` (`src/sys/PosixStat.rs`) returned the epoch on Linux. - `faccessat2` answers EPERM or EINVAL: a hoisted `bun install` from a warm cache fails with `error: failed to install dep: the downloaded package was not found in the cache`. glibc 2.33+ `faccessat()` issues `faccessat2` first, even with flags 0, and falls back on ENOSYS only. `exists_at` (`src/sys/lib.rs`) called it. bun 1.3.14 passes. - `prlimit64` denied: every command dies with `panic: unreachable: Sys(EPERM)`, from `adjust_ulimit().expect("unreachable")` in `RealFS::init` (`src/resolver/lib.rs`). bun 1.3.14 does not. ### Fix - `stat_birthtime` returns ctime on Linux, as libuv `uv__to_stat` does. - `exists_at` and `faccessat` issue the flag-less `faccessat` syscall on Linux, through rustix. bun never passes flags. musl and older glibc do the same. - A failed `getrlimit(RLIMIT_NOFILE)` gives an fd budget of 0: the resolver keeps no fds open. `process.report` leaves out a limit it cannot read (it printed an uninitialized `rlimit`). Node does both. - Limit: with all of `prlimit64` denied, `bun install`, `bun build` and `bun run <script>` work again. JavaScript still cannot start, as on 1.3.14 (see notes). - Verified: `test/js/node/fs/fs-stat-seccomp-linux.test.ts`, 10 new tests, all fail on bun 1.4.2. Self-reviewed: 11 concerns, 9 addressed, 2 are follow-ups (notes). ### Background - seccomp is a per-process syscall filter. A filtered call fails with an errno that the profile chooses. - `statx` is the only Linux stat call with a birth time. - `faccessat2` (Linux 5.8) is `faccessat` plus a flags argument. - glibc implements `getrlimit` with `prlimit64`. <details><summary>Notes</summary> **Origin.** A sweep where one syscall answers ENOSYS, EPERM or EINVAL for the whole process tree (a seccomp filter), with node v26.3.0 as the reference. There is no GitHub issue. All three reproduce here on bun 1.4.2 and on a release build of main, with the seccomp launcher from the test file. **Versions.** The test file on three builds: this branch (release build) 15 pass. bun 1.4.2: the 10 new tests fail. bun 1.3.14: the `faccessat2`, `RLIMIT_NOFILE` and `bun build` tests pass, the birthtime and `process.report` tests fail. So the `faccessat2` and `prlimit64` members regressed in 1.4.0. The birthtime and `process.report` members were never right. **statx.** ENOSYS, EPERM and EINVAL behave the same. Every path that converts a plain `struct stat` goes through `PosixStat::init`, so the statx fallback, the node:fs path that skips statx (after `SUPPORTS_STATX_ON_LINUX` flips) and the stat watcher change together. When statx works but the filesystem does not report `STATX_BTIME`, bun still reports 0. libuv does the same (`uv__statx_to_stat` copies `stx_btime` as it is). **faccessat2.** ENOSYS already worked because glibc falls back by itself. `--linker isolated` worked because it uses `directory_exists_at` (fstatat). The `exists_at` contract is unchanged: it is a predicate and every failure is "no", like `fs.existsSync`. The cause is the syscall that glibc picks, not the errno folding. rustix `accessat` with empty flags goes straight to `__NR_faccessat` on its linux_raw backend (x64 and arm64, glibc and musl). On Android rustix uses its libc backend, and bionic `faccessat` is already flag-less. A realistic host for this is a seccomp profile that was patched for `clone3` but not for `faccessat2`. An unpatched old Docker host stops earlier, when `clone3` answers EPERM. **prlimit64.** - The strace line in the report shows `RLIMIT_STACK` because that is the first `getrlimit` glibc makes. The panic is the `RLIMIT_NOFILE` read in `adjust_ulimit`. - With an fd budget of 0, `--watch` and `--hot` only see the entry point. They register an imported module through its cached fd. This is only reachable with a filter that lets `RLIMIT_STACK` through. - With all of `prlimit64` denied, JSC stops in `VM::setLastStackTop` (RELEASE_ASSERT). glibc `pthread_getattr_np` needs `getrlimit(RLIMIT_STACK)` for the main thread, so `WTF::StackBounds` gets no bounds. bun 1.3.14 stops at the same place. There are two ways to close it, and neither is in this PR. One is a change to `StackBounds.cpp` in the WebKit fork. The other is link-time wraps (next to `__wrap_execve`) for `getrlimit` and `pthread_getattr_np`: the first falls back to the legacy `getrlimit` syscall (x64 only), the second derives the main thread stack from `__libc_stack_end`. An `LD_PRELOAD` simulation of both wraps lets bun run JavaScript under the filter. The `getrlimit` wrap alone does not. - The `RLIMIT_NOFILE` tests use a filter on the second syscall argument so that they also run under ASAN. The ASAN runtime aborts by itself when `getrlimit(RLIMIT_STACK)` fails (`sanitizer_posix_libcdep.cpp:88`). The `bun build` tests deny the whole syscall and skip under ASAN. **Same-class sites not changed here.** - `lchmod` on Linux (`src/sys/lib.rs`) issues `fchmodat2` and falls back on ENOSYS only. EPERM is also a real `chmod` error there, so it needs its own fix with a fallback that does not go through libc. Node has no `lchmod` on Linux. - `getcwd().expect("unreachable")` in `src/install/lockfile/Package/WorkspaceMap.rs` and `self_exe_path().expect("unreachable")` in `src/bun_core/util.rs` also unwrap an OS result. They are not about a newer syscall. **Self-review follow-ups not in this PR.** Move the seccomp launcher from the test file into the test harness. Add a test on a real 3.10 kernel. **Other suites run with the debug build.** `fs-birthtime-linux.test.ts`, `fs-stats-truncate.test.ts`, `fs-stats-constructor.test.ts`, `fs.test.ts`, `fs.watchFile.test.ts`, `bun-pm-version.test.ts`, `bun-install-offline.test.ts`, `bun-create.test.ts`, `hot.test.ts`, `bun-install.test.ts` (13 failures there need gitlab.com and bitbucket.org, and fail the same way on 1.4.2 in this sandbox). `cargo check -p bun_sys -p bun_resolver` passes for linux gnu and musl (x64, arm64), android (x64, arm64), macOS arm64, FreeBSD x64 and Windows x64. </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/fs/fs-stat-seccomp-linux.test.ts <!-- robobun:evidence:end -->
### Problem - `dockerhub/alpine/Dockerfile` builds `oven/bun:alpine` on `alpine:3.22`. Alpine 3.23 (2025-12-03) and Alpine 3.24 (2026-06-09) are out. `node:alpine` defaults to `alpine3.24`. - CI links the musl build against the libstdc++ of Alpine 3.23 (`alpine_sysroot_version` in `scripts/bootstrap.sh`) and tests it there. The image ships the libstdc++ of Alpine 3.22 (GCC 14.2), which is older than the one the binary links against (GCC 15.2). - The `machine:linux:alpine` script in `package.json` still names Alpine 3.22. CI moved to 3.23 in oven-sh#26667. ### Fix - Change both `FROM` lines to `alpine:3.24`. This supersedes oven-sh#25960, which stops at 3.23. - Point `machine:linux:alpine` at 3.23, the release that CI uses. - Correct because each package the Dockerfile installs has the same name in 3.24, and 3.24 ships the same GCC 15.2.0 libstdc++ that CI links against. The base changes are musl 1.2.5 to 1.2.6 and apk-tools 2 to 3. - Verified: `test/js/bun/test/parallel/test-docker-build-alpine.ts` builds this Dockerfile in CI. I also ran the released 1.4.2 musl binary against an Alpine 3.24.1 userland (see Notes). I did not run `docker build` locally. ### Background - The musl build of Bun links `libstdc++.so.6` dynamically. The final stage gets it from `apk add libgcc libstdc++`. So the base image decides which libstdc++ Bun runs with. - `alpine:3.24` is a floating tag. It follows the newest 3.24.x patch release. - The release workflow publishes `oven/bun:canary-alpine` each day and `oven/bun:alpine` on each release. This change needs no CI image bake. <details><summary>Notes</summary> **Other published images.** They are current, so this PR does not touch them. | Image | Base | State | | --- | --- | --- | | `dockerhub/debian` | `debian:trixie-slim`, `debian:trixie` | Debian 13.6, current stable | | `dockerhub/debian-slim` | `debian:trixie-slim` | current stable | | `dockerhub/distroless` | `debian:trixie-slim`, `gcr.io/distroless/base-nossl-debian13` | newest distroless | **Package versions** (from the `3.22-stable`, `3.23-stable` and `3.24-stable` branches of aports): | Package | 3.22 | 3.23 | 3.24 | | --- | --- | --- | --- | | musl | 1.2.5-r12 | 1.2.5-r23 | 1.2.6-r2 | | gcc (libstdc++, libgcc) | 14.2.0 | 15.2.0 | 15.2.0 | | apk-tools | 2.14.10 | 3.0.8 | 3.0.8 | | curl | 8.14.1 | 8.22.0 | 8.22.0 | | gnupg | 2.4.9 | 2.4.9 | 2.4.9 | | openssl | 3.5.8 | 3.5.8 | 3.5.8 | `ca-certificates`, `curl`, `dirmngr` (provided by `gnupg-dirmngr`), `gpg`, `gpg-agent`, `unzip`, `libgcc` and `libstdc++` all exist in 3.24 `main` with the same names. **Smoke test.** I extracted an Alpine 3.24.1 root filesystem that has `musl 1.2.6-r2`, `libstdc++ 15.2.0-r5` and `libgcc 15.2.0-r5` installed. These are the packages the final stage installs. I ran `bun-linux-x64-musl-baseline` from the 1.4.2 release through its `ld-musl-x86_64.so.1` with `--library-path` set to its `/lib` and `/usr/lib`. `bun --version` prints `1.4.2`. A script that uses `node:crypto`, `node:fs`, `node:zlib`, `bun:sqlite`, `Bun.serve` with `fetch`, `dns.lookup`, `Bun.spawnSync`, an HTTPS `fetch`, `Bun.Transpiler` and a `Worker` completes with the expected output. I did not test aarch64. **Related.** oven-sh#40649 asks for Alpine-versioned tags (`oven/bun:1.4-alpine3.24`). Its fallback ask is to move the unversioned tag with each Alpine stable release. This PR does only that. **Not changed.** The CI test platforms in `.buildkite/ci.mjs` stay on Alpine 3.23 and Ubuntu 25.04. A change there needs new CI images, and a newer musl sysroot raises the libstdc++ that release binaries link against. </details> <!-- robobun:evidence:begin --> --- **no test proof** · iteration 1 · no src or test change; test-proof not applicable <!-- robobun:evidence:end --> --------- Co-authored-by: Ziga Zajc <[email protected]>
…rinter (oven-sh#42708) ### Problem - mordant `generic_body_not_generic` flags `OutdatedCommand::print_outdated_info_table` (`src/runtime/cli/outdated_command.rs:302`): "is generic over `ENABLE_ANSI_COLORS` and is compiled 2 times in this crate, but one part of it, 497 of its 1872 statements (as MIR), does not use `ENABLE_ANSI_COLORS`". The baseline line is `"generic_body_not_generic:src/runtime/cli/outdated_command.rs" = 1`. - The first 240 lines of the function parse the name patterns, walk the lockfile and the cached manifests, and size the columns. Only the rendering after that reads the parameter. The compiler builds the whole body once for `true` and once for `false`. - `outdated_dispatch`, the caller, is generic over the same parameter only to pass it down. ### Fix - `collect_outdated` is a plain function that holds the part with no colors in it. It returns an `OutdatedTable` (the grouped rows, the five column widths, the two display flags), or `None` when there is nothing to list. - `print_outdated_info_table::<ENABLE_ANSI_COLORS>` takes the `OutdatedTable` and only renders. The `true` / `false` dispatch moves from `outdated()` down to that one call, so `outdated_dispatch` is no longer generic. - No behavior change. The statements and their order are the same. Both early `return Ok(())` exits become `None`, and the caller continues to `print_fetch_failures` as before. - Verified: the pinned mordant reports nothing for `bun_runtime` with the baseline line removed. The 18 `outdated` tests in `test/cli/install/bun-install-registry.test.ts` (9 table snapshots, color and `NO_COLOR`), plus the `outdated` cases in `bun-add-filter`, `minimum-release-age` and `bun-update-transitive`, pass on the debug build. ### Background - `bun outdated` prints a box table. `bun_core::fmt::Table<L, R, ENABLE_ANSI_COLORS>` takes the color switch as a const parameter, so the code that draws the table is generic over it. - `generic_body_not_generic` looks for a region of a generic function that uses no parameter. rustc compiles that region once per instantiation. The lint asks for a separate non-generic function. - `mordant-baseline.toml` is a ratchet: per lint and file, the number of accepted findings. A fixed finding lowers the entry. <details><summary>Notes</summary> The release-size effect is not measured. Mordant counts MIR statements before optimization, and a release link can fold identical functions. The two copies of this region are identical, so the linker can already fold part of it. `print_outdated_info_table` reads `cache_ctx`, `min_age_ms` and `excludes` from the manager again in place of sharing the scan's locals. `manifest_disk_cache_ctx()` opens the cache directory on first use and returns the stored descriptor after that. No `test/` change: the diff changes no behavior, so no test can fail before it and pass after it. The check that the finding is gone is the `mordant` job on this PR (advisory, so read its result directly). </details>
…n-sh#33584) ### Problem - A garbage collection can drop the VM's pending exception. A module whose evaluation throws then hits `ASSERTION FAILED: exception` in `JSPromise::rejectWithCaughtException` (assert builds) or segfaults at `0x8` in `JSPromise::reject <- rejectWithCaughtException <- CyclicModuleRecord::evaluate <- dynamicImportLoadSettled` (release, Sentry BUN-4R6E). `Bun.resolve()` hits `panic: A JavaScript exception was thrown, but it was cleared before it could be read.` in `rejected_promise_with_caught_exception`. - Cause: `computeErrorInfoWrapperToString` (`src/jsc/bindings/FormatStackTraceForJS.cpp`), the `onComputeErrorInfo` hook, runs in `Heap::runEndPhase` for live Errors whose frames died, and cleared whatever exception was pending. With concurrent GC it lands while the mutator is parked at an allocation with an exception pending. ### Fix - Wrap the hook body in JSC's `SuspendExceptionScope` (as `TypeProfilerLog::processLogEntries` does). The mutator's exception and trap bit are set aside and restored, so `tryClearException()` only swallows what the computation itself raised. - Add `DeferTerminationForAWhile`. A `terminate()` thrown inside the window survives the clear, and the restore then overwrites it with the trap bit still set. - Verified: `error-stack-finalizer-exception.test.ts` is the deterministic one (`slowPathAllocsBetweenGCs` fixes where the end phase lands): all three N values abort every run unfixed, all pass fixed, in about 6s. `dynamic-import-evaluation-error-gc.test.ts`, `resolve-error.test.ts` and `sourcetextmodule-link-gc.test.ts` cover the concurrent-GC faces and fail 3/3 unfixed. The terminate test fails 3/3 on a suspend-only build. `test-stream-writable-write-writev-finish.js` passes under `BUN_JSC_validateExceptionChecks=1`. ### Background - JSC keeps one pending exception per VM (`VM::m_exception`), mirrored by a trap bit. A callee that clears it drops the caller's exception. - `CyclicModuleRecord::evaluate` step 9 sees the module's error as the pending exception and step 9.d rejects by re-reading the slot. `Bun.resolve()` allocates its promise before it takes the exception. - With concurrent GC the end phase runs while the mutator is stopped at a safepoint, which is any allocation slow path. `ErrorInstance` keeps weak stack frames. When a frame's code dies, the end phase materializes the stack string through this hook. <details><summary>Notes</summary> Deterministic door (no concurrent collector): `BUN_JSC_slowPathAllocsBetweenGCs=7 bun -e 'const e = eval("(() => Object.assign(new Error(\"c\"), { code: 1 }))")(); throw e'`. Reported as 5/5 `Segmentation fault at address 0x8` on release 1.4.2, canary and a release build of main, and 5/5 `ASSERTION FAILED: exception` on an ASan build. Measured here on a debug+ASAN build of main: N of 3, 4 and 7 abort every run; 1, 2, 5, 6 and >= 8 print the error normally; with the fix all of 3, 4, 7 print `error: c` and exit 1 (9/9). The eval'd arrow matters: it makes the Error's frames garbage before the throw propagates, so the end phase has a stack to materialize. Reproduction (plain `import()`, no `node:vm`, no plugin), about 4 of 6 runs abort at 200 iterations and 6 of 6 at 300 on the unfixed assert build: ```js import { mkdirSync, writeFileSync } from "node:fs"; import { join } from "node:path"; for (let it = 0; it < 300; it++) { const d = join(import.meta.dir, "graphs", "g" + it); mkdirSync(d, { recursive: true }); writeFileSync(join(d, "bad.mjs"), `export const x = ${it};\nthrow new Error("boom ${it}");\n`); writeFileSync(join(d, "tla.mjs"), `await new Promise(r => setTimeout(r, 0));\nexport const t = ${it};\n`); writeFileSync(join(d, "leaf.mjs"), `export const l = ${it};\n`); writeFileSync(join(d, "mid.mjs"), `import { l } from "./leaf.mjs";\nimport "./bad.mjs";\nexport const m = l + 1;\n`); writeFileSync(join(d, "a.mjs"), `import { m } from "./mid.mjs";\nimport { t } from "./tla.mjs";\nexport const a = m + t;\n`); writeFileSync(join(d, "b.mjs"), `import { t } from "./tla.mjs";\nimport "./bad.mjs";\nexport const b = t;\n`); writeFileSync(join(d, "c.mjs"), `import { m } from "./mid.mjs";\nexport const c = m;\n`); await import(join(d, "a.mjs")).catch(() => {}); await import(join(d, "b.mjs")).catch(() => {}); await import(join(d, "c.mjs")).catch(() => {}); await import(`data:text/javascript,throw new Error('d${it}')`).catch(() => {}); } ``` `import(b)` reaches the already-errored `bad.mjs`, so `InnerModuleEvaluation` step 2 rethrows the stored error and the step 9 to 9.d window runs again. A data:-URL-only loop does not fire. A single iteration does not fire. State at the assert (gdb, conditional break on `exception == 0` at the assert line): the `Exception*` local captured at step 9 is non-null while `vm.m_exception` is null. The window between the two is straight-line C++ (`attachErrorInfo`, `setStatus`, `setEvaluationError`) with no JS and no microtask checkpoint, so the slot is cleared out of band. `BUN_JSC_useConcurrentGC=false`: 0/16 aborts (baseline 12/16 on the `vm.SourceTextModule` reproducer). `collectContinuously` also hides it (it moves the window). The `vm.SourceTextModule` reproducer (the first one found) needs `--smol` to fire reliably and a file-backed fixture (a `-e` script has no source URL, so the stack materializer takes a different path). Earlier iteration of this PR compared the pending exception before and after the computation and cleared only a new one. `SuspendExceptionScope` replaces that: it is the upstream pattern, it also restores `m_lastException` and the trap bit, and the computation runs against a clean slot. The first reports of this assert named a `Bun.plugin` `onResolve` recipe. That recipe cannot reach the state (its filter never matched), and the plugin is not part of the cause. The first push used `SuspendExceptionScope` alone. CI caught the termination interaction on the debian x64-asan lane (`worker.test.ts`, "terminate() while importing every builtin module"): `ASSERTION FAILED: !!(*scope).exception() == vm.traps().needHandling(JSC::VMTraps::NeedExceptionHandling)` in `TopExceptionScope__exceptionIncludingTraps`. A stress (the vm fixture inside a Worker terminated mid-run, 20 rounds) reproduced it 6/6 on that build and 0/6 with the deferral; it is now the third test in the vm file. `Bun.resolve()` face (the helper from oven-sh#41796): `Bun.resolve()` with no arguments from a fresh closure per iteration, rejection reasons kept in a 1024-entry ring, awaited one at a time, `BUN_JSC_collectContinuously=1`. Unfixed main 09bb546 (debug+ASAN): 9/9 panic after 2500 to 8500 iterations, trace `take_exception <- JSPromise::reject <- rejected_promise_with_caught_exception <- bun_object::resolve`. With the fix: 5/5 complete 80000 iterations. Batching 64 calls per tick never fires. Reported on a release build of main as well (panic within 0.2 s under collectContinuously). The same helper serves the early rejections of `fetch()`, `Bun.write()` and `server.fetch()`. The module-evaluation standalone above also segfaults shipped release builds on demand under `BUN_JSC_collectContinuously=1` (reported: 1.4.2 4/5, canary 4/5, release main 5/5 at N=400, SEGV at 0x8). </details> <!-- robobun:evidence:begin --> --- **no test proof** · iteration 4 · platform-specific test(s) that do not run on this machine, deferring to CI, which covers all platforms: test/js/node/vm/sourcetextmodule-link-gc.test.ts, test/js/bun/resolve/resolve-error.test.ts, test/js/bun/resolve/dynamic-import-evaluation-error-gc.test.ts <!-- robobun:evidence:end -->
…42719) ### Problem - `packages/bun-types/globals.d.ts:320` declares `encodeInto(src?: string, dest?: Bun.BufferSource)`. Both parameters are optional, so `new TextEncoder().encodeInto()` and `encodeInto("hi")` type-check. - The runtime requires both arguments. Each of those calls throws `TypeError [ERR_MISSING_ARGS]: Not enough arguments`. The declarations in lib.dom and `@types/node` already require both. ### Fix - Remove the two `?`. The declaration is now `encodeInto(src: string, dest: Bun.BufferSource)`. - The type of `dest` does not change here. oven-sh#34726 (open) narrows it to `Uint8Array` together with the runtime check. That PR edits the same line, so the PR that merges second has a one-line conflict. The merged line is `encodeInto(src: string, dest: Uint8Array<ArrayBufferLike>)`. - Verified: `test/integration/bun-types/bun-types.test.ts`, 21 pass. `fixture/text-encode-decoder.ts` has one valid call and two `@ts-expect-error` calls. With the old declaration, `tsc` reports `TS2578: Unused '@ts-expect-error' directive` at both, and 10 of the 21 tests fail. ### Background - `interface TextEncoder` in `globals.d.ts` extends the `@types/node` interface and merges with the lib.dom interface when lib.dom is loaded. Its own `encodeInto` member is wider than both, so a call with a missing argument matched it in every configuration. - The bun-types test runs `tsc` over `test/integration/bun-types/fixture/` with and without lib.dom. It compares the diagnostics to an expected list. An unused `@ts-expect-error` is a diagnostic, so it fails the test. <details><summary>Notes</summary> Runtime on a release build of main (`1.4.3-canary.1+09bb54630`), next to Node v26.3.0: ``` --- bun encodeInto() TypeError [ERR_MISSING_ARGS]: Not enough arguments encodeInto('hi') TypeError [ERR_MISSING_ARGS]: Not enough arguments encodeInto('hi', Uint8Array) {"read":2,"written":2} --- node encodeInto() TypeError [ERR_INVALID_ARG_TYPE]: The "src" argument must be of type string. Received undefined encodeInto('hi') TypeError [ERR_INVALID_ARG_TYPE]: The "dest" argument must be an instance of Uint8Array. Received undefined encodeInto('hi', Uint8Array) {"read":2,"written":2} ``` Without the `globals.d.ts` change, and with the new fixture lines, on a release build: ``` text-encode-decoder.ts(297,1): error TS2578: Unused '@ts-expect-error' directive. text-encode-decoder.ts(300,1): error TS2578: Unused '@ts-expect-error' directive. (fail) basic type checks > checks without lib.dom.d.ts (fail) TypeScript latest > checks without lib.dom.d.ts (fail) TypeScript 7.1 > checks the fixture and import attributes through ts7.1/index.d.ts (fail) Test Globals > checks without lib.dom.d.ts and test-globals references (fail) Test Globals > test-globals FAILS when the test-globals.d.ts is not referenced (fail) Bunland reaching for JSX > Bun.markdown.react() returns type compatible with React.ReactElement (fail) Bunland reaching for JSX > Bun.markdown.react() returns unknown if React is not installed (fail) lib configuration > checks with no lib at all (fail) lib configuration > fails with types: [] and no jsx (fail) lib configuration > checks with lib.dom.d.ts 11 pass 10 fail ``` The new fixture lines are in `text-encode-decoder.ts` and not in `spawn.ts`, because oven-sh#34726 edits the `encodeInto` lines in `spawn.ts`. </details>
…tions (oven-sh#42464) ### Problem - `CallSite.getFunction()` (the `Error.prepareStackTrace` API) returned the frame's callee unchecked. JSC has callees user code could never have called: a host function, a builtin, an async or generator body function, or no function at all (wasm and program frames). - Five shapes crash 1.4.2, canary and main. After one `await`, calling what `getFunction()` returns gives `panic(main thread): Segmentation fault at address 0x32`. A wasm frame faults at `0x5` on the read. - Cause: `CallSite::finishCreation` (`src/jsc/bindings/CallSite.cpp:34`) only checks the strictness of the frame's code block. `JSCStackFrame` leaves that null for host and hidden builtin frames. ### Fix - `getFunction()` reports `undefined` unless the callee is a function user code could have called. A user function gets itself, including the CommonJS wrapper. - Caller frames keep their function: hiding a callee does not set `Flags::IsStrict`. `isToplevel()` reads a new flag computed from the real callee, so its answers do not change. - Deleted: the function-inspecting block in `callSiteProtoFuncIsToplevel`, and its `JSBoundFunction.h` include. - Verified: four new blocks in `test/js/node/v8/capture-stack-trace.test.js`, all failing on 1.4.2 and with `src/` reverted. 627 pass across the stack-trace suites. ### Background - JSC compiles an async function or a generator into a wrapper (what the user named) and a body that takes five internal arguments. The synchronous prefix runs in the body too, so the wrapper is never a frame's callee. - `createCallSitesFromFrames` (`FormatStackTraceForJS.cpp:844`) copies `isStrict()` down the frame list. JSC shows host frames V8 omits (`Reflect.construct` under a transpiled `super()`), so a cascade from a hidden callee would blank callers node reports. - JSC frames carry no receiver, so `isToplevel()` judges by the callee. <details><summary>Notes</summary> #### The five crashes A fuzz ledger reported the async body and three native promise reactions. A review of the first draft of this patch found the wasm frame. Each crashes release 1.4.2 (exit 139), and each exits cleanly with this change. | shape | 1.4.2 | with this change | | --- | --- | --- | | async function body after `await` | SEGV `0x32` | `undefined` | | generator body after `next()` | SEGV `0x32` | `undefined` | | wasm frame, on read alone | SEGV `0x5` | `undefined` | | HTMLRewriter suspension reaction | SEGV `0x12` | `undefined` | | `Bun.serve` `error()` reaction, and the `Bun.plugin` onLoad reaction | SEGV `0x12` / `0x1A` | `undefined` | The first fixture, as CommonJS so that the top frame is sloppy: ```js async function f() { await 1; Error.prepareStackTrace = (e, sites) => sites; return new Error().stack[0].getFunction(); } f().then(g => { console.log(g === f, g.length); g(); }); ``` 1.4.2 prints `false 5` and then segfaults. `0x32` is an encoded `undefined` (`0xa`) plus `0x28`, the offset of a generator internal field. Under ASAN the frames are `llint_op_put_internal_field <- llint_op_call_ignore_result <- llint_call_javascript <- JSC::MicrotaskCall::tryCallWithArguments`, so the body function wrote a generator field into a plain `undefined`. The wasm crash has three more entry shapes. Each is the same null callee, each segfaults 1.4.2 at `0x5`, and each exits cleanly with this change, also under ASAN: the wasm frame as the first call site of a trap (`WebAssembly.RuntimeError`, which is what an error reporter walks), a wasm stack overflow whose `RangeError` carries only wasm frames, and a wasm frame that JSPI resumed. The test covers the import-callback shape. The reaction crashes all reach the same place. A handler from `Zig::GlobalObject::thenable()` runs user JS synchronously: a later HTMLRewriter element handler, `Bun.serve`'s `error()`, or a getter on a plugin's onLoad result. That user JS keeps the nameless native function `getFunction()` reported, and calls it. The handler then reads its trailing argument as a native context. 12 of the 54 `PromiseFunctions` handlers decode a raw pointer from a JS number, so the class is worse than a bad cast. The host-function arm closes all of them, because `getFunction()` is the only way user code could name one. #### How old each route is The unchecked hand-out itself is old. Release 1.3.14 has the same logic in `CallSite.cpp`, `thenable()` is already `ImplementationVisibility::Public` there, and `Bun__NativePromiseContext__take` already uses `uncheckedDowncast` (oven-sh#28613). The fuzz ledger reports that the wasm shape crashes 1.3.14 too. The HTMLRewriter route is new in 1.4.0, and the ledger measured it: 1.3.14 is clean, 1.4.0 to 1.4.2 crash at `0x12`. The cause is oven-sh#36733, not an engine upgrade. Before it, the rewriter handled an async handler with `vm.wait_for_promise()`, which spins the event loop in place, so no native reaction existed. oven-sh#36733 suspends the rewrite and resumes it through `Bun__HTMLRewriter__onHandlerResolve`, which put a reaction frame on the stack for the first time. The `Bun.serve` `error()` route and the `Bun.plugin` onLoad route use machinery that predates 1.3.14 (the onLoad reaction is from 2022), so they are probably older than that window. I read that from history and did not run it: I have no 1.3.14 binary here. #### What node returns Measured on node v26.3.0 with the same fixtures. | frame | node | 1.4.2 | with this change | | --- | --- | --- | --- | | sloppy user function | itself | itself | itself | | CommonJS module wrapper | itself | itself | itself | | `Array.prototype.map` | undefined | the `map` function | undefined | | program frame under `eval` | undefined | a non-function `JSCallee` object | undefined | | async or generator body | the wrapper | the body (length 5) | undefined | | wasm frame | a `Number` | crash | undefined | | any caller below the above | see 2. below | itself | itself | Two divergences remain, both deliberate: 1. Node returns the wrapper for an async or generator frame. JSC keeps no back pointer from a body function to its wrapper, so the wrapper cannot be recovered. `getFunctionName()` still reports the user's name. JSC applies the same policy in `callerGetter` (`FunctionPrototype.cpp`). 2. Node blanks the caller frames below a builtin frame, because V8 compiles its builtins strict. Bun does not, and this change does not start. I measured that trigger: it moves a 22-shape host and builtin probe from 4/22 to 22/22 against node. It also blanks callers that node reports wherever JSC shows a host frame V8 hides, and `Reflect.construct` under Babel's `_callSuper` is one of those. It is a separable hunk. Say so if you want it. #### isToplevel() `m_function` has two readers, `getFunction()` and `isToplevel()`. The first push of this PR narrowed what `m_function` holds and did not account for the second reader. A review comment about dead branches in `callSiteProtoFuncIsToplevel` made me measure it: on a 16-row probe, `isToplevel()` flipped from `false` to `true` on 5 rows, the `Array.prototype.map` frame and every async or generator frame. `isToplevel()` now reads `Flags::IsSloppyFunctionCall`, which `finishCreation` computes from the real callee: the frame is sloppy and its callee is a `JSFunction` that is not a host function. All 16 rows match 1.4.2 again, and four new `...IsToplevel=false` test rows pin it. Those rows fail on the first push of this PR. The replaced block had a `JSBoundFunction` arm, a host-function arm, a `jsExecutable()` arm and an `InternalFunction` arm. With `m_function` narrowed, only the `jsExecutable()` arm could still run. The `JSBoundFunction` arm never could: a bound-function thunk is `ImplementationVisibility::Private` and never gets a `CallSite`, which I checked on both the `prepareStackTrace` and the `captureStackTrace` path. #### Dropped from the first draft The first draft cascaded from every hidden callee and carried three hardening hunks. A review plus my own measurements cut all four: - The cascade blanked `getFunction()` for a plain sloppy caller that both node and 1.4.2 return. - `ImplementationVisibility::Private` on the `thenable()` handlers hides a useless `at unknown` frame. With `BUN_JSC_showPrivateScriptsInStackTraces=0` it also flips `typeof err.stack` from `"string"` to `"undefined"` for three `Bun.plugin` onLoad validation errors, whose only frame was the reaction. It needs the empty-frame-vector case to produce a header-only stack first, the way `FormatStackTraceForJS.cpp:234` already does for the `captureStackTrace` path. Worth doing, but not here. - A `dynamicDowncast` in `Bun__NativePromiseContext__take`. oven-sh#40203 is open and already touches that function. - Two `dynamicDowncast` guards in the module loader onLoad reactions. With this change nothing can reach them, and an unreachable, untested guard is not worth the lines. #### Suites run, on the debug ASAN build `capture-stack-trace.test.js` 50/50. The stack-trace set is 627 pass, 0 fail: `test/js/node/v8`, `vm.test.ts`, `vm-sourceUrl.test.ts`, `util.test.js`, `test/js/bun/sourcemap`, `reportError.test.ts`, `console-log.test.ts`, `23022-stack-trace-iterator`, `circular-error-stack`, `circular-error-stack-edge-cases`, `fix-bindings-stack-trace`, `prepare-stack-trace-crash`. `stack.test.ts` and `013880.test.ts` pass on their own. `node:test` `test-error-prepare-stack-trace.js`, `test-util-getcallsites-preparestacktrace.js` and `test-shadow-realm-prepare-stack-trace.js` exit 0. Earlier drafts, whose reach was wider, also cleared the html-rewriter (207), plugin and resolve (506), streams (549), serve (295) and `node:http` (372) suites. Two failures in that area are not from this change, and each now has its own session. `test/regression/issue/013880.test.ts` leaks a global `Error.prepareStackTrace` into the shared test process and breaks 21 tests in `capture-stack-trace.test.js`. It reproduces on release 1.4.2: that file alone passes, and the two files together fail 21. `test/js/node/vm/script-leak.test.ts` sets an `isASAN` RSS threshold but no `isASAN` timeout, so it needs 25s against a 5s default on any `bun bd` build. #### Flake check The four new blocks passed 5 runs in a row, and 3 more with 24 CPU burners running, to stand in for a slow ASAN lane. Each reaction fixture needs a genuinely pending promise to make the native reaction exist. An already-resolved promise and a `queueMicrotask`-resolved promise both fail to install the suspension, which I checked, so the fixtures use `setTimeout(resolve, 1)` inside the fixture process. The test itself only awaits the process exit. Each reaction fixture also asserts `reactionFrameSeen=true`, so `leaked=undefined` cannot pass because the frame stopped appearing. </details> <!-- robobun:evidence:begin --> --- **[human-review]** gate passed · iteration 1 · 4 files touched <details><summary>fails on main (without fix)</summary> ```console ASAN without fix: 4 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/v8/capture-stack-trace.test.js" bun test v1.4.3 (6a92015) test/js/node/v8/capture-stack-trace.test.js: (pass) Regular .stack [24.55ms] (pass) throw inside Error.prepareStackTrace doesnt crash [40.55ms] (pass) capture stack trace [12.79ms] (pass) capture stack trace with message [14.33ms] (pass) capture stack trace with constructor [11.08ms] (pass) capture stack trace limit [43.64ms] (pass) prepare stack trace [22.91ms] (pass) capture stack trace second argument [35.13ms] (pass) capture stack trace edge cases [23.74ms] (pass) Error.captureStackTrace installs .stack as non-enumerable [39.79ms] (pass) prepare stack trace call sites [24.06ms] (pass) sanity check [26.96ms] (pass) CallFrame isEval works as expected [16.18ms] (pass) CallFrame isTopLevel returns false for Function constructor [17.42ms] (pass) CallFrame.p.getThisgetFunction: strict/sloppy mode interaction [17.16ms] (pass) CallFrame.p.isConstructor [6.29ms] (pass) CallFrame.p.isNative [7.07ms] 726 | stderr: "pipe", 727 | }); 728 | 729 | const [stdout, st ... (truncated) release without fix: all passed bun test v1.4.3-canary.1 (8a7f62b) test/js/node/v8/capture-stack-trace.test.js: (pass) Regular .stack [0.14ms] (pass) throw inside Error.prepareStackTrace doesnt crash [0.09ms] (pass) capture stack trace [0.09ms] (pass) capture stack trace with message [0.06ms] (pass) capture stack trace with constructor [0.06ms] (pass) capture stack trace limit [0.19ms] (pass) prepare stack trace [0.11ms] (pass) capture stack trace second argument [0.17ms] (pass) capture stack trace edge cases [0.10ms] (pass) Error.captureStackTrace installs .stack as non-enumerable [0.22ms] (pass) prepare stack trace call sites [0.14ms] (pass) sanity check [0.11ms] (pass) CallFrame isEval works as expected [0.09ms] (pass) CallFrame isTopLevel returns false for Function constructor [0.09ms] (pass) CallFrame.p.getThisgetFunction: strict/sloppy mode interaction [0.10ms] (pass) CallFrame.p.isConstructor [0.03ms] (pass) CallFrame.p.isNative [0.03ms] (pass) CallFrame.p.getFunction does not expose the module loader reaction [9.47ms] (pass) CallFrame.p.getFunction does not expose the HTMLRewriter reaction [11.12ms] (pass) CallFrame.p.getFunction does not expose the serve reject reaction [11.29ms] (pass ... (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/v8/capture-stack-trace.test.js" bun test v1.4.3 (6a92015) test/js/node/v8/capture-stack-trace.test.js: (pass) Regular .stack [22.42ms] (pass) throw inside Error.prepareStackTrace doesnt crash [33.22ms] (pass) capture stack trace [9.60ms] (pass) capture stack trace with message [10.80ms] (pass) capture stack trace with constructor [8.87ms] (pass) capture stack trace limit [32.05ms] (pass) prepare stack trace [17.69ms] (pass) capture stack trace second argument [24.93ms] (pass) capture stack trace edge cases [18.24ms] (pass) Error.captureStackTrace installs .stack as non-enumerable [30.12ms] (pass) prepare stack trace call sites [19.79ms] (pass) sanity check [21.41ms] (pass) CallFrame isEval works as expected [11.96ms] (pass) CallFrame isTopLevel returns false for Function constructor [12.53ms] (pass) CallFrame.p.getThisgetFunction: strict/sloppy mode interaction [13.89ms] (pass) CallFrame.p.isConstructor [5.20ms] (pass) CallFrame.p.isNative [5.26ms] (pass) CallFrame.p.getFunction does not expose the serve reject reaction ... (truncated) release with fix: all passed $ bun scripts/build.ts --profile=release [configured] bun-profile → bun (stripped) in 710ms (unchanged) ninja: Entering directory `/workspace/bun/build/release' [1/9] cxx obj/src/jsc/bindings/ZigGlobalObject.cpp.o [2/9] cxx obj/unified/UnifiedSource-src_jsc_bindings-1.cpp.o [3/9] cxx obj/unified/UnifiedSource-src_jsc_bindings-0.cpp.o [4/9] gen cpp.rs (cppbind) [4/9] cargo bun_runtime → libbun_runtime.a ^[[1m^[[92m Compiling^[[0m bun_core v0.0.0 (/workspace/bun/src/bun_core) ^[[1m^[[92m Compiling^[[0m bun_errno v0.0.0 (/workspace/bun/src/errno) ^[[1m^[[92m Compiling^[[0m bun_ptr v0.0.0 (/workspace/bun/src/ptr) ^[[1m^[[92m Compiling^[[0m bun_boringssl_sys v0.0.0 (/workspace/bun/src/boringssl_sys) ^[[1m^[[92m Compiling^[[0m bun_safety v0.0.0 (/workspace/bun/src/safety) ^[[1m^[[92m Compiling^[[0m bun_base64 v0.0.0 (/workspace/bun/src/base64) ^[[1m^[[92m Compiling^[[0m bun_cares_sys v0.0.0 (/workspace/bun/src/cares_sys) ^[[1m^[[92m Compiling^[[0m bun_zlib_sys v0.0.0 (/workspace/bun/src/zlib_sys) ^[[1m^[[92m Compiling^[[0m bun_zstd v0.0.0 (/workspace/bun/src/zstd) ^[[1m^[[92m Compiling^[[0m bun_picohttp v0.0.0 (/workspace/bun/src/picohttp) ^[[1m^[[92m Compiling^[[0m bun_brotli v ... (truncated) ``` </details> <details><summary>diff hotspot</summary> ``` src/jsc/bindings/CallSite.cpp | 31 +++- src/jsc/bindings/CallSite.h | 2 + src/jsc/bindings/CallSitePrototype.cpp | 21 +-- test/js/node/v8/capture-stack-trace.test.js | 264 ++++++++++++++++++++++++++++ 4 files changed, 297 insertions(+), 21 deletions(-) ``` </details> **gate history** · 3 passed · 0 rejected · iteration 1 <details><summary>evidence per changed file</summary> ``` file reads edits tests src/jsc/bindings/CallSite.cpp 5 11 34 src/jsc/bindings/CallSite.h 2 3 33 src/jsc/bindings/CallSitePrototype.cpp 2 2 33 test/js/node/v8/capture-stack-trace.test.js 6 10 33 ``` </details> **root cause** · written by the author bot `CallSite` treated a frame as non-strict whenever it lacked a CodeBlock with a strict executable, so native frames, builtin JS frames, and the internal async/generator body functions that JSC runs after the first suspension all had their callee stored and handed back through `getFunction()`; calling one of those internal callees with caller-chosen arguments let plain JavaScript write generator internal fields into arbitrary objects, which segfaulted the interpreter. The fix narrows the callee exposure in one place: the function is only stored when it is a `JSFunction` whose `FunctionExecuta… <!-- robobun:evidence:end -->
…oven-sh#42548) ### Problem - A synchronous GC (`Bun.gc(true)`, a heap snapshot) inside `Error.prepareStackTrace` crashes the first `.stack` read of an error whose creating function is already garbage. Release: `panic(main thread): Segmentation fault at address 0x8`. Debug: `ASSERTION FAILED: !m_errorInfoMaterialized` in `ErrorInstance::computeErrorInfo` (`ErrorInstance.cpp:398`). - `materializeErrorInfoIfNeeded` (WebKit fork, `ErrorInstance.cpp:441`) sets `m_errorInfoMaterialized`, then calls Bun's formatter with `*m_stackTrace` still installed. A GC in there finds a dead frame, so `reconcileWeakReferencesAtGCEnd` renders the trace and frees the vector. The `m_stackTrace->clear()` that follows dereferences null. - A GC-stress fuzz run found this. There is no user report. ### Fix - `computeErrorInfoWrapperToJSValue` (`src/jsc/bindings/FormatStackTraceForJS.cpp`) roots every frame's callee and code block in a `MarkedArgumentBuffer` while it formats, as the lazy `Error.captureStackTrace` getter already does (oven-sh#31495). This covers the callback, a `message` getter and a `node:vm` `Error.prepareStackTrace` getter. - `Error.appendStackTrace` returns early for a destination flagged as materialized (the guard from oven-sh#37370). Inside the callback it appended unrooted frames to the vector being formatted. - The lazy getter can run re-entrantly for the error being formatted. It now copies the frames and leaves the vector installed. It freed the vector that the `node:vm` path still reads. - Verified: `test/js/node/v8/capture-stack-trace.test.js`, 6 new cases, all fail on 1.4.3 canary and on a debug build of main. Self-reviewed: 3 concerns raised, 3 addressed. ### Background - `error.stack` is lazy. `new Error()` stores a `Vector<StackFrame>`. The first read calls Bun's formatter, which builds `CallSite` objects and calls `Error.prepareStackTrace`. - The error holds each frame's callee and code block weakly. `reconcileWeakReferencesAtGCEnd` runs on every live error at the end of each GC. - A `MarkedArgumentBuffer` is a stack-allocated list of GC roots. <details><summary>Notes</summary> Minimal script (prints `formatted` on Node and with this change): ```js const e = new Function('"use strict"; function inner() { try { return new Error("x"); } finally {} } try { return inner(); } finally {}')(); Error.prepareStackTrace = (err, callSites) => { Bun.gc(true); return "formatted"; }; console.log(e.stack); ``` A more ordinary shape that crashes the same way (ESM): ```js import v8 from "node:v8"; Error.prepareStackTrace = (err, callSites) => { v8.getHeapStatistics(); return "formatted " + callSites.length; }; async function handler() { const e = (() => { try { return new Error("request failed"); } finally {} })(); await 1; return e.stack; } console.log(await handler()); ``` The `finally` blocks keep each `return` out of tail position. A `CallSite` for a strict-mode frame does not keep the function (the V8 rule for `getFunction()`), so nothing else keeps such a frame alive during the callback. A sloppy-mode trace does not crash, because its call sites retain the functions. `materializeErrorInfoIfNeeded` holds a `DeferGCForAWhile`, so only an explicit synchronous collection runs in the formatter. Calls that collect synchronously and reach this: `Bun.gc(true)`, `bun:jsc` `fullGC()` and `edenGC()`, `Bun.generateHeapSnapshot()`, `v8.writeHeapSnapshot()`. `v8.getHeapStatistics()` and `bun:jsc` `heapStats()` collect only while `vm.heap.size() == 0` (`src/jsc/modules/BunJSCModule.h:233`), so they reach this only before the first collection of the process. `Bun.gc(false)` and allocation pressure do not reach it. The lazy getter case needs no GC. `Error.captureStackTrace(e)` on an error from a `node:vm` context installs the lazy `stack` accessor. The first `e.stack` read runs `materializeErrorInfoIfNeeded`, whose formatter reads the context's `Error.prepareStackTrace`. If that is a getter that reads `e.stack` again, `materializeErrorInfoIfNeeded` returns at once (the flag is set) and the accessor runs `errorInstanceLazyStackCustomGetter` for the same error. It moved the frames out and called `setStackFrames(vm, {})`, which deleted the vector the outer formatter holds by reference. ASAN with `Malloc=1` reports `heap-use-after-free` in `Bun::formatStackTrace` (`FormatStackTraceForJS.cpp:168`). A release build reads a size of zero and prints a trace with no frames. `Reflect.get(otherError, "stack", e)` reaches the same getter with `e` as the receiver. This PR does not close every way to reach `ASSERT(!m_errorInfoMaterialized)`. oven-sh#37370 covers `Error.appendStackTrace` onto a destination whose `.stack` was read earlier, outside the callback, with its own tests, plus two other `appendStackTrace` crashes. The early return here is the same hunk. Whichever PR lands second needs a trivial rebase. Relation to oven-sh#40354 with oven-sh/WebKit#511: that change makes `ErrorInstance::visitChildren` mark the frames while `m_stackTrace` is installed. The vector is still installed during the callback, so it would also keep the frames marked there and make the buffer here redundant but harmless. It is a retention change with a WebKit pin bump, and it has no test for this crash. The cases here stay valid as its regression coverage. A change on the WebKit side alone is not enough. If `materializeErrorInfoIfNeeded` moves the vector out of the instance before the call, the GC end phase skips the error, but the frames are then unrooted and the `node:vm` path reads them after user JS ran. If `reconcileWeakReferencesAtGCEnd` skips materialized instances, `Bun.inspect(err)` inside the callback reads dead frames through `stackTrace()`. Both shapes still need the frames rooted for the duration of the call. Cost: one `MarkedArgumentBuffer` per first `.stack` read, two slots per frame. It spills to the heap above four frames. Suites run on the debug build: `capture-stack-trace.test.js` (52 pass, also with `BUN_JSC_validateExceptionChecks=1`), `stack.test.ts`, `prepare-stack-trace-crash.test.ts`, `fix-bindings-stack-trace.test.ts`, `inspect-error.test.js`, `node/vm/vm.test.ts`, `external-sourcemap-stack-leak.test.ts`, and the Node tests `test-error-prepare-stack-trace.js`, `test-util-getcallsites-preparestacktrace.js`, `test-shadow-realm-prepare-stack-trace.js`. </details>
…a JS error (oven-sh#42288) Fixes oven-sh#42282. Supersedes oven-sh#42251 (its commits are in this branch). ### Problem - A pipeline member that throws a JS error (`cmd | cat > ${new Response("r")}`) rejects the promise, but the process never exits. The members that already run keep running, the pipe ends of the failed member and of the members after it stay open, and a producer that writes more than the pipe buffer blocks forever. - A state that throws returned `Yield::Failed` with no node. The failed member never reported to its parent, so `Pipeline::child_done` (`src/runtime/shell/states/Pipeline.rs`) never ran for it, nothing released its `IO`, and the members after it were never started or freed. On main the trampoline also left the exception pending (`Yield.rs:134`), so after the first suspension the promise never settled. ### Fix - `Yield::Failed` carries the `NodeId`. The trampoline calls `Interpreter::fail(id)`: it takes the exception, kills every subprocess with SIGKILL, reports `id` to its parent as finished with exit code 1, and then rejects the promise. The rejection runs user JS, so it comes last. - The tree then winds down through the normal `child_done` path. The sequencing states stop on the `failed` flag (`interrupted()`), a pipeline frees the members it did not start (`release_unstarted`), a `Cmd` whose expansion completes later does not spawn, and an expansion stops after a failed command substitution. Each freed member drops its pipe ends, so the members that still run see EOF or EPIPE. - `finish` runs once every member has exited. It settles nothing when the script failed, but it still disables the keep-alive and drops the pending-activity count. No node is freed while a callback can still reach it, which is what oven-sh#33996 got wrong. - Verified: `test/js/bun/shell/yield.test.ts` (20 new cases, 17 hang or abort on 1.4.3) and `shell-worker-terminate-leak.test.ts` (1 new ASAN case). Also `bunshell`, `pipeline_stack`, `epipe`, `throw`, `lazy`, `shell-hang`, `exec`, `file-io`, `shell-worker-terminate-leak`, `commands/` and the rest of `test/js/bun/shell`. ### Background - The shell interpreter is a tree of state nodes in an arena (`Interpreter::nodes`). A node reports to its parent with `child_done`, and the parent frees it. `Yield::run` is the trampoline that steps nodes until one suspends. - A pipeline creates one socketpair per `|` and gives each member an `IOReader` (read end) and an `IOWriter` (write end). The fds close when the last `Arc` drops, that is, when the member node is freed. - `hasPendingActivity` keeps the `ShellInterpreter` wrapper alive until `finish`. A subprocess exit, a pipe read, or a thread-pool task can call back into the interpreter until then. <details><summary>Notes</summary> Relation to oven-sh#42251: that PR rejects the promise but leaves the failed pipeline's interpreter pinned and its members running, and names oven-sh#42282 as the follow-up. Landing it alone ships an interim design, landing this one alone strands it, so this PR carries its commits and oven-sh#42251 is closed. Here `reject_with_pending_exception` only takes the exception and rejects. The keep-alive and the pending-activity count are released by `finish`, as on the success path. Why kill instead of wait: `sleep 100 | bad > ${blob}` would keep the process open for 100 s. A member that does write the pipe gets EPIPE once the failed member's read end closes, so the kill only matters for members that do not touch the pipe. SIGKILL is what `Cmd::deinit` already uses. In-process tests check the mechanism, not only that the process exits: the member that does not touch the pipe writes its pid, the failing member waits for that file in a command substitution before it throws, and after the rejection the pid is gone (killed and reaped). Two members that fail reject with the first error, and a non-quiet pipeline rejects and leaves the shell usable. A worker that is terminated while a failed pipeline winds down runs clean under ASAN and LSan. Shapes covered by the tests: producer bigger than the pipe buffer, a member that never touches the pipe, members after the failed one, the failed member first, a glob-expanding member whose glob completes after the failure (`${bun} -e ... * | bad` spawned the command before the guard in `Cmd::next`), a subshell member, a command substitution in another member, a builtin producer on the thread pool, `(cmd; touch a) | bad; touch b` leaves no file, and a failed pipeline is collected by the GC. The other producers of `Yield::Failed` take the same path: a failed `dup()` for a subshell or command substitution, a failed write of the `command not found` message, an OOM pin of an `ArrayBuffer` redirect. oven-sh#40033 changes the `command not found` write failure to exit 1 instead of a throw; this PR keeps the throw. Self-review: 10 concerns raised, 3 addressed (the `Cmd::next` guard, `Fixes` line, fold oven-sh#42251). Rejected: a parse-time check of the redirect target instead of a runtime wind-down, because the other producers above reach the same path with no misuse of the API, and waiting instead of killing, because a member that does not touch the pipe would pin the process for its lifetime. Found while testing, not changed here: `ls -R dir | <consumer that exits early>` hangs on 1.4.3 because `IOWriter` reports a failed write once per child while `ls` queues one chunk per directory. oven-sh#37719 fixes that. The test here uses `ls dir` (one chunk). Probes on the ASAN debug build: `BUN_JSC_validateExceptionChecks=1` and `BUN_GARBAGE_COLLECTOR_LEVEL=2` over `yield.test.ts`, all green. `leak.test.ts` memleak cases and `shell-blocking-pipe.test.ts` time out the same way on a main build in this container. `commands/ls.test.ts` permission cases fail as root and the `node_modules` case needs the registry. `cargo check -p bun_runtime` passes for `x86_64-pc-windows-msvc` and `aarch64-apple-darwin`. </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/shell/yield.test.ts, test/js/bun/shell/shell-worker-terminate-leak.test.ts <!-- robobun:evidence:end --> --------- Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
…42245) ### Problem - `Bun.TOML.stringify` of a table nested about 20000 deep dies with SIGSEGV (exit 139, nothing printed) instead of throwing `RangeError: Maximum call stack size exceeded`. - The cause is `Stringifier::append_path` (`src/runtime/api/TOMLObject.rs:426`). It wrote a `[a.a.a…]` header by recursing once per path segment, unchecked. Its caller `stringify_table_body` already holds one checked frame per level, so the deepest header doubled the depth the check had allowed. ### Fix - `append_path` collects the parent-linked chain into a `SmallVec` and writes the segments root-first. The header costs no stack. - `StackCheck` reserves 384 KB more in sanitizer builds only. With `append_path` fixed, the ASAN build still died in a narrow band below the limit: a `StringBuilder` growth after the check goes through libpas, ~160 KB of ASAN frames against a 128 KB reserve. - Verified: `test/js/bun/toml/toml.test.ts` (the new limit test SIGSEGVs 5/5 on the unfixed ASAN build). Also the `yaml`, `json5`, `xml`, `jsonc`, `md`, `bun-inspect` and transpiler depth suites, debug+ASAN and release. ### Background - `TOML.stringify` emits a nested object as a `[parent.child]` section. `stringify_table_body` recurses once per level and threads a `Path { parent, key }` link through each frame: the header path is a linked list on the recursion stack. - `StackCheck::is_safe_to_recurse` (`src/bun_core/util.rs`) compares the stack pointer with the thread's stack end. It keeps a fixed reserve (128 KB POSIX, 256 KB Windows) for the work a frame does before the next check. ASAN pads every frame: the libpas reallocation path is a few KB in release and ~160 KB under ASAN. <details><summary>Notes</summary> - gdb on main showed 1439 copies of the `append_path` return address in the lowest 48 KB of the stack. - The two hunks were separated by experiment. With `append_path` fixed and the sanitizer reserve at 0, the debug+ASAN build still dies with SIGSEGV: 3 of 3 runs for a fresh process at depth 3190 or 3199, and about half of the runs of the new test (4 of 8 fixture runs, 3 of 4 test runs). The rate is below 100% in the test because the crash needs the allocator slow path to land on the deepest level, and earlier probes in the same process warm the allocator. With both hunks the test passed every run. On the unfixed build it failed 5 of 5. - Release build of this branch: the `{a:{a:…}}` limit is ~20594 levels, a sweep of depths 20500 to 21050 (step 50, 2 runs each) has no crash, and the bisection fixture runs in ~170 ms. Debug+ASAN: limit ~3046, sweep 2980 to 3100 clean, fixture ~3.5 s. Unfixed debug+ASAN: 3150 fine, 3190 SIGSEGV, 3201 `RangeError`. - The residual ASAN crash, from gdb: `stringify_table_body -> append_header -> append_key_segment -> BunString::appendToBuilder -> WTF::StringBuilder::extendBufferForAppending -> StringImpl::tryReallocate -> bmalloc -> pas_thread_local_cache_get_local_allocator_slow -> flush_deallocation_log -> __asan memcpy interceptor`, with `rsp` on the guard page. Frames 0 to 24 of that chain span 122832 bytes. - The limit test bisects for the recursion limit in a child process instead of using a fixed depth. The crash sits just under the limit, and the limit depends on the build's frame sizes and the platform's stack size, so a fixed depth that crashes one build is a clean `RangeError` or a success on another. Every probe near the limit exercises the crash. - `append_header` is the only caller of `append_path`. `stringify_inline_value` has its own check. No other helper in the file recurses on input depth. - Pre-existing failures seen with and without this diff: `XML.stringify > deep values are a catchable error` (5 s timeout while building 1M nested objects under ASAN) and the JSONL 4 GB tests. - Self-review of the diff raised three points, all addressed. The sanitizer reserve applies to all 64 `is_safe_to_recurse` call sites under ASAN. It is 384 KB, about 5% of an 8 MB main-thread stack and about 9% of a 4 MB worker stack, so the depth-sensitive suites above were run to confirm nothing that must succeed now fails. The limit test got a 60 s timeout and a search ceiling. It takes ~0.2 s on a release build, ~3.5 s on debug+ASAN, and ~6.6 s under the environment CI gives the ASAN lane (`BUN_JSC_validateExceptionChecks=1`, `BUN_DESTRUCT_VM_ON_EXIT=1`, `detect_leaks=1`), where the whole file passes with no leak report. The `SmallVec` holds 16 segments inline, and `append_path` runs once per emitted header. </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: 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/toml/toml.test.ts bun test v1.4.3 (5f55496) test/js/bun/toml/toml.test.ts: (pass) input types > string [3.35ms] (pass) input types > Buffer [2.32ms] (pass) input types > Uint8Array subarray respects byteOffset and length [2.14ms] (pass) input types > DataView [3.63ms] (pass) input types > ArrayBuffer [1.79ms] (pass) input types > SharedArrayBuffer [2.59ms] (pass) input types > Blob parses synchronously [2.02ms] (pass) input types > DataView over a SharedArrayBuffer [2.81ms] (pass) input types > non-string values are coerced via toString [5.94ms] (pass) input types > null and undefined throw [6.42ms] (pass) input types > invalid UTF-8 bytes throw SyntaxError [3.71ms] (pass) input types > lone surrogates: replaced in string input (USVString), rejected in byte input [3.39ms] (pass) input types > UTF-8 BOM is skipped in both string and byte input [2.65ms] (pass) JS value mapping > returns a plain object with Object.prototype [1.62ms] (pass) JS value mapping > __proto__ key becomes an own property, not the prototype [4.30ms] ( ... (truncated) release without fix: all passed bun test v1.4.3-canary.1 (d9ea68b10) test/js/bun/toml/toml.test.ts: (pass) input types > string [0.05ms] (pass) input types > Buffer [0.06ms] (pass) input types > Uint8Array subarray respects byteOffset and length [0.03ms] (pass) input types > DataView [0.05ms] (pass) input types > ArrayBuffer [0.02ms] (pass) input types > SharedArrayBuffer [1.42ms] (pass) input types > Blob parses synchronously [0.05ms] (pass) input types > DataView over a SharedArrayBuffer [0.04ms] (pass) input types > non-string values are coerced via toString [1.37ms] (pass) input types > null and undefined throw [0.07ms] (pass) input types > invalid UTF-8 bytes throw SyntaxError [0.06ms] (pass) input types > lone surrogates: replaced in string input (USVString), rejected in byte input [0.07ms] (pass) input types > UTF-8 BOM is skipped in both string and byte input [0.02ms] (pass) JS value mapping > returns a plain object with Object.prototype [0.02ms] (pass) JS value mapping > __proto__ key becomes an own property, not the prototype [0.05ms] (pass) JS value mapping > __proto__ table becomes an own property [0.02ms] (pass) JS value mapping > constructor and prototype keys are plain data propert ... (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/toml/toml.test.ts bun test v1.4.3 (5f55496) test/js/bun/toml/toml.test.ts: (pass) input types > string [3.50ms] (pass) input types > Buffer [2.87ms] (pass) input types > Uint8Array subarray respects byteOffset and length [2.12ms] (pass) input types > DataView [5.38ms] (pass) input types > ArrayBuffer [3.40ms] (pass) input types > SharedArrayBuffer [4.21ms] (pass) input types > Blob parses synchronously [3.00ms] (pass) input types > DataView over a SharedArrayBuffer [4.21ms] (pass) input types > non-string values are coerced via toString [10.01ms] (pass) input types > null and undefined throw [8.22ms] (pass) input types > invalid UTF-8 bytes throw SyntaxError [4.06ms] (pass) input types > lone surrogates: replaced in string input (USVString), rejected in byte input [3.52ms] (pass) input types > UTF-8 BOM is skipped in both string and byte input [2.94ms] (pass) JS value mapping > returns a plain object with Object.prototype [1.73ms] (pass) JS value mapping > __proto__ key becomes an own property, not the prototype [5.21ms] ... (truncated) release with fix: all passed $ bun scripts/build.ts --profile=release [configured] bun-profile → bun (stripped) in 689ms (unchanged) ninja: Entering directory `/workspace/bun/build/release' [1/31] gen generated_host_exports.rs generated_host_exports.rs: 122 exports (host=5, lazy=10, generic=107, rust=0); 243 extern-C blocks audited [2/31] gen cpp.rs (cppbind) [3/31] gen JS modules (bundle-modules) Preprocess modules (8633ms) Bundle modules (52ms) Postprocesss modules (165ms) Bundle Functions (502ms) Generate Code (41ms) [9.40s] Bundled "src/js" for production 2594 kb 197 internal modules 13 native modules 50 internal functions across 16 files [3/21] cargo bun_runtime → libbun_runtime.a �[1m�[92m Compiling�[0m bun_core v0.0.0 (/workspace/bun/src/bun_core) �[1m�[92m Compiling�[0m bun_errno v0.0.0 (/workspace/bun/src/errno) �[1m�[92m Compiling�[0m bun_ptr v0.0.0 (/workspace/bun/src/ptr) �[1m�[92m Compiling�[0m bun_boringssl_sys v0.0.0 (/workspace/bun/src/boringssl_sys) �[1m�[92m Compiling�[0m bun_safety v0.0.0 (/workspace/bun/src/safety) �[1m�[92m Compiling�[0m bun_base64 v0.0.0 (/workspace/bun/src/base64) �[1m�[92m Compiling�[0m bun_cares_sys v0.0.0 (/workspace/bun/src/ ... (truncated) ``` </details> <details><summary>diff hotspot</summary> ``` src/bun_core/util.rs | 24 +++++++++---------- src/runtime/api/TOMLObject.rs | 18 ++++++++++---- test/js/bun/toml/toml.test.ts | 55 +++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 80 insertions(+), 17 deletions(-) ``` </details> **gate history** · 1 passed · 0 rejected · iteration 0 <details><summary>evidence per changed file</summary> ``` file reads edits tests src/bun_core/util.rs 3 5 9 src/runtime/api/TOMLObject.rs 2 5 9 test/js/bun/toml/toml.test.ts 4 2 9 ``` </details> <!-- robobun:evidence:end --> --------- Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
…ng length limit (oven-sh#42202) ### Problem - An error message that embeds a string from JS has a user-controlled length. Building one past the string length limit aborts the process, also inside `try`/`catch`: `panic(main thread): abort() called`, exit code 134. Example: `bun -e 'try { Buffer.from("x", "q".repeat(2**31-10)) } catch {}'`. - The cause: `WTF::makeString` and a default-constructed `WTF::StringBuilder` call `CRASH()` when the result passes `String::MaxLength`. Every message builder in `src/jsc/bindings/ErrorCode.cpp` is one of the two. ### Fix - `Bun::MessageBuilder` (`ErrorCode.h`) records the overflow. Every builder in `ErrorCode.cpp` uses it, and `determineSpecificType` and `JSValueToStringSafe` accept only that type. `createError` and `throwError` report a message that did not fit as `RangeError: Out of memory`. - Five sinks outside `ErrorCode.cpp` build with `tryMakeString`: the `performance.measure` mark, the `ReadableStream` source `type`, three `MessageEvent` constructor messages. - Correct because JSC reports `RangeError: Out of memory` for a string it cannot create. Node v26.3.0 reports the same inputs as `RangeError: Invalid string length`. A message under the limit is unchanged. - Verified: `test/js/bun/util/error-message-string-length-limit.test.ts`, 8 cases in one child, which aborts on main. Also the buffer, streams, webcrypto and MessageEvent suites. Self-reviewed: 7 concerns raised, 6 addressed, 1 is a question for a maintainer (Notes). ### Background - `String::MaxLength` is 2^31 - 1 code units. A JS string can be that long. - `StringBuilder` takes an `OverflowPolicy`. The default crashes. `RecordOverflow` sets a flag that `hasOverflowed()` reports, and later appends do nothing. - `determineSpecificType` renders the `Received ...` part of `ERR_INVALID_ARG_TYPE`. It appends `constructor.name` with no bound. - JSC treats its own messages this way in `ExceptionHelpers.cpp`. <details><summary>Notes</summary> **The type guards its own reads.** `StringBuilder::toString()` and `length()` assert that the builder did not overflow, so on `MessageBuilder` they are private. `tryToString()` returns a null string on overflow, and `finish(globalObject, scope)` throws. No `hasOverflowed()` check is written by hand in `ErrorCode.cpp`. **Question for a maintainer.** This PR reports an over-long message as `RangeError: Out of memory` with no `.code`, like JSC and like Node. oven-sh#39481 (open) takes the other policy for the Rust-side error constructor: it keeps the error type and properties and uses a stand-in message. If that policy is preferred here too, the change is in two functions: `createError(ErrorCode, MessageBuilder&)` and `MessageBuilder::finish`. **Moved out of this PR.** The first revision also changed `process.execve` and `Error.stack`. Neither uses `MessageBuilder`, and each has its own question, so each has its own PR: - `process.execve`: oven-sh#42308 - `Error.stack` and the default `Error.prepareStackTrace`: oven-sh#42314 **Cases in the test.** All abort on main and on 1.4.2 with exit code 134. With this branch each one throws `RangeError: Out of memory`. ```js const long = "q".repeat(2 ** 31 - 10); class C {} Object.defineProperty(C, "name", { value: long }); Buffer.from("x", long); // UNKNOWN_ENCODING Buffer.from(new C()); // determineSpecificType Buffer.alloc(1).indexOf(new C()); // JSBuffer.cpp message new SocketAddress({ address: "1.2.3.4", port: new C() }); // Bun__ErrorCode__determineSpecificType, the entry Rust validators call performance.measure("m", long); // PerformanceUserTiming.cpp crypto.subtle.importKey(long, new Uint8Array(8), "AES-GCM", false, ["encrypt"]); // JSSubtleCrypto.cpp new ReadableStream({ type: long }); // JSReadableStream.cpp ReadableStream.from(Symbol(long)); // throwNotIterable ``` **Verified by hand, not in the test.** - The three `MessageEvent` messages: `new MessageEvent("m", { ports: long })`, `{ ports: [long] }`, `{ source: long }`. Each aborts on main and throws with this branch. They render the value through the inspector first, which takes about 20 s in a release build and about 9 minutes in a debug ASAN build for a 2 GiB string, so they cannot be a test. - The quoted `ERR_INVALID_ARG_VALUE` path (`Buffer.alloc(4).fill(long, "hex")`), `ERR_OUT_OF_RANGE` with a long name, and `NodeError.prototype.toString` with a long message throw with this branch. The quoted path appends one character at a time, about 8 minutes in a debug build. - The doors reported in the comments below (`Buffer.byteLength`, `fs.mkdirSync` mode, `process.kill` signal name, `child_process.spawn`) all go through `MessageBuilder`. - The whole fixture also passes under `BUN_JSC_validateExceptionChecks=1`. **Scope.** This does not cover every `makeString` call that can reach an error sink. A census at `4ff91937` counted 276 `makeString(` calls and 110 default-constructed `StringBuilder` locals under `src/jsc`. The `makeString` calls left in `ErrorCode.cpp` take an `ASCIILiteral` or an internal string, so the binary bounds their length. A different mechanism is also out of scope: `String::utf8()` aborts for a Latin-1 string of more than about 2^30 characters, at many call sites. **Cost of the test.** The length is what is under test, so the input is about 2 GiB. One child runs all 8 cases, so the string is allocated once. Peak RSS is 4.4 GB. The file takes 2 to 4 s in a debug ASAN build. It skips below 10 GiB of total memory, the gate `test/js/bun/transpiler/source-too-large.test.ts` uses. The one test keeps a 30 s ceiling, because the default 5 s is too close on a loaded machine. **Pre-existing failures** seen in the surrounding suites, which also fail with `src/` at `origin/main`: `error-gc-test.test.js` (timeouts in a debug build), `socket.test.ts > should not call drain before handshake`, and `process.test.js > process` (this container has no `USER` in the environment). </details>
…ing length limit (oven-sh#42314) ### Problem - Reading `.stack` of an error with a very long message aborts the process: `panic(main thread): abort() called`, exit code 134. Example: `bun -e 'new Error("q".repeat(2**31-10)).stack'`. The default `Error.prepareStackTrace`, which also runs before a user-defined one, aborts the same way. - Both formatters in `src/jsc/bindings/FormatStackTraceForJS.cpp` (`formatStackTrace` at :154, `formatStackTraceToJSValue` at :42) use a default-constructed `WTF::StringBuilder`. It calls `CRASH()` on the append that passes `String::MaxLength`. The message and each frame's source URL come from JS. ### Fix - Both builders record the overflow (`OverflowPolicy::RecordOverflow`). A trace that did not fit becomes the `name: message` header without the frames, or the message alone if the header does not fit either. - It degrades and does not throw, because `formatStackTrace` also runs from `ErrorInstance::finalizeUnconditionally`, inside a GC, where nothing can throw. `.stack` is then the same whether the GC or the getter computes it. - A trace under the limit is unchanged. A user `Error.prepareStackTrace` still runs and still gets the call sites. - Verified: `test/js/node/v8/capture-stack-trace.test.js`, one new test with both paths in one child. Each path aborts alone on 1.4.3. Also `stack.test.ts`, three stack-trace regression tests and `test-error-prepare-stack-trace.js`. ### Background - `String::MaxLength` is 2^31 - 1 code units. An error message can be that long. - `.stack` is computed lazily: `ErrorInstance::materializeErrorInfoIfNeeded` calls Bun's hook on the first read. If the GC finds dead frames first, `finalizeUnconditionally` calls the string variant of the same hook. - `RecordOverflow` makes the builder set a flag that `hasOverflowed()` reports. Later appends do nothing. <details><summary>Notes</summary> This is split out of oven-sh#42202, which is now only about error messages. Other policies for a trace that does not fit, and why this PR does not take them: - Throw, like Node. Node v26.3.0 throws `RangeError: Invalid string length` from the `.stack` read for the same input. In Bun the same text is also produced inside a GC, where a throw is not possible, so the two paths would differ. The getter runs under many operations on the error object (`Object.keys`, a property write), which would all start to throw. - Keep the frames and cut the message. That keeps more information, because the frames are small. It needs the header and the frames built apart, which is a larger change to a function that oven-sh#40354 and oven-sh#33584 also edit. The change is small on purpose: the builder policy and three return sites. It does not touch the parts of the file that oven-sh#40354 and oven-sh#33584 change, so any merge order works. Seen while testing, not caused by this change: `stack.test.ts > Async functions frame should be included in stack trace` fails when it runs in one process after the three regression files (two extra frames). It fails the same way with `src/` at `origin/main`, and it passes alone. Cost of the test: the length is what is under test, so the child needs a string of about 2 GiB. Both paths run in one child, so the string is allocated once. Each path copies the header once, so the child touches about 6 GB of pages. It takes about 5 s in a debug ASAN build, so it carries a 30 s ceiling. It skips below 10 GiB of total memory, the gate `test/js/bun/transpiler/source-too-large.test.ts` uses. </details>
…/ICU in the build graph (oven-sh#42556) ### What does this PR do? Re-lands the parts of oven-sh#41330 that do not depend on compiling JavaScriptCore and ICU inside bun's own build graph. bun keeps linking the prebuilt `bun-webkit-*` tarballs; nothing here changes how WebKit or ICU are obtained. One commit per topic, so any of them can be reverted alone. **Build graph** - Generated headers were one build late: a header that a depfile names by absolute path did not match its relative ninja output, so includers were recompiled on the *next* run. Every build-dir output is also declared under its absolute path. - Every build after a build-script edit configured twice (`[0/1] reconfigure`). Configure stamps the manifest and `ninja -t restat`s it. - `bun run build` never reached a no-op with an isolated-layout `node_modules`: the install edge's outputs made ninja pre-create `node_modules/<dep>/`, and bun's isolated linker then skipped the symlink. - The link is an ordinary edge instead of holding ninja's console pool. **Link-time checks** (`scripts/build/verify-binary.ts`, expectations per target in `binary-expectations.ts`), as ninja validations of bun's link in every mode that links: exported symbols against the lists in `src/`; the exact NEEDED / dylib / import-DLL set and symbol-version ceilings; forbidden imports; static initializers; nx-stack / no-RWX / PIE / DllCharacteristics; no symbol strongly defined by two link inputs. A check whose tool is missing is not emitted. `ninja_required_version` is 1.11 (validations); `rust-toolchain.toml` gains `llvm-tools`. - `bun.exe` links the prebuilt WebKit, whose bmalloc is compiled with `BEXPORT=__declspec(dllexport)`, so it exports 22 bmalloc symbols and `g_config`. They are a named temporary allowance in the PE export expectations, to be removed once oven-sh/WebKit builds bmalloc with `BEXPORT` empty. **Compiler policy, stated instead of inherited from the host compiler** - `-fno-stack-protector` on Linux, FreeBSD and Android (it was off with CI's clang, `-fstack-protector-strong` with Arch/Alpine/Fedora's). macOS states `-fstack-protector`, which every clang turns on for a Darwin target, so the macOS binaries keep their canaries. - Vendored deps follow bun's PIC policy instead of the building clang's default. - windows-arm64 without `-mtune=ampere1`. **Windows** - The exe's import library no longer overwrites the object archive (`obj/<exe>.import.lib`). - `bun.exe`'s manifest declares `supportedOS` (Windows 7 through 10/11) and `asInvoker`, so Windows stops running bun in the Vista compatibility context. Visible effect: `process.report`'s `header.osRelease` reads `10.0` instead of `6.1` on Windows 10/11. **Runtime symbols** - `napi_internal_*` → `Bun__napi_*`: the `napi*` glob in the version scripts exported them on Linux and FreeBSD. - `offsetOfWrapped()` in the generated classes is `constexpr`: 93 fewer static initializers in `-O0` builds. **CI** - Linux images are baked by a Buildkite job on a fresh machine of the target distro plus a `wait-for-image` step. Only `[build images]` / `[publish images]` runs change; ordinary runs generate the same pipeline. - `verify-baseline` and `trace-order` are drawn beside each target's build group; step keys and dependencies are unchanged. - verify-baseline-static: decoder resync. **Release is LTO by default**, locally as in CI; `--lto=off` for fast relinks. The `btg` and `ci-release` profiles are gone and fail with what to use instead. Not included from oven-sh#41330: JavaScriptCore/ICU in the build graph, the ccache environment change, any change to `bootstrap.sh` / `bootstrap.ps1`. **WebKit** is bumped from `cf1b36ec8703` to `9b02218df662`, oven-sh/WebKit `main` with oven-sh/WebKit#645 merged: oven-sh#636, oven-sh#634, oven-sh#632, oven-sh#652, oven-sh#646, oven-sh#649 (a direct tail call to a host function could return into freed JIT code) and oven-sh#645 (a parser `SyntaxError` with no JS frame on the stack has its `line`/`sourceURL` again; private builtins' source text stays out of error messages; a wasm-to-JS frame index fix). `test/js/bun/jsc/webkit-upgrade-9b02218df6.test.ts` covers what Bun can see of oven-sh#645. Against main's build of the same sources, every prebuilt lane differs only in the two JavaScriptCore objects oven-sh#645 changes. ### How did you verify your code works? - `test/internal` build tests pass (212/212), including new cases for the validations and for a missing tool; `scripts/build` typechecks apart from two files that already fail on main. - `--configure-only` for debug, release and each `--mode`: the link edge carries `|@ … binary-verified … duplicate-symbols-checked`; release resolves the `-lto` WebKit tarball, `--lto=off` the plain one, `--profile=btg` fails with the retired-profile message. - The verifier run by hand on existing binaries: passes on prebuilt-linked release and debug-asan ELF, and on the released Windows x64 `bun.exe` with the bmalloc allowance; the duplicate-symbol scan finds none over 1221 inputs including the prebuilt archives. - The Buildkite pipeline generated offline for seven scenarios: identical step keys, `depends_on` and dependency closure on ordinary runs; image runs match what oven-sh#41330 generated. - The rest is for CI on this PR.
### What does this PR do? `Database.setCustomSQLite()` selects one process-wide SQLite library, but each worker has a separate JavaScript global. After a parent selected a custom library, repeating that same selection from a worker threw `SQLite already loaded` even though the requested path matched the library already in use. This change serializes selection through the existing process-wide SQLite handle lock, records the path that successfully loaded the library, and makes later calls with that exact path idempotent. Calls after Bun loaded its default SQLite library or with a different custom path still fail. A rejected partial library load now preserves its loader error and releases the loader reference before a retry. This unblocks applications such as OpenClaw that validate a full SQLite build before starting worker-owned state leases and need worker globals to adopt that process-wide selection. AI assistance: This change was developed and reviewed with Codex. ### How did you verify your code works? - Confirmed the new worker regression fails on the shipping Bun runtime with `SQLite already loaded`. - Built Bun from this branch and ran the complete `test/js/node/sqlite/node-sqlite.test.ts` suite: 116 passed, 4 skipped, 0 failed. - Ran the new worker regression with JavaScriptCore exception validation enabled. - Repeated a loadable non-SQLite library failure twice, verified the missing-symbol error remained intact, then selected and opened the valid system SQLite library. - Ran clang-format, Prettier, and `git diff --check`.
…42748) ### Problem - A zero in a `numeric(p, s)` column reads as `"0"` on the binary path of `Bun.SQL` and as `"0.0000"` on the text path. node-postgres, postgres.js and psql return `"0.0000"` on every path. - The cause is the zero shortcut in `parse_binary_numeric` (`src/sql_jsc/postgres/DataCell.rs:1053`): `if ndigits == 0 { return "0" }`. It ignores `dscale`. ### Fix - For `ndigits == 0` and `dscale > 0`, the decoder writes `"0."` and then `dscale` `'0'` characters. `dscale <= 0` keeps the static `"0"`. - Correct because the formatter below the shortcut already pads non-zero values to `dscale`, as `get_str_from_var` in Postgres does. Only the shortcut skipped that step. - Verified: `test/js/sql/postgres-binary-numeric.test.ts` gets two real-server cases (`"0.0000"`, `"0.00000000000000000000"`) that return `"0"` on main. Four assertions in `test/js/sql/sql.test.ts` pinned `"0"` for a scaled zero and now expect the scale. A full `sql.test.ts` run on both builds changes only those tests. - Self-reviewed: checked the `dscale` range and the sign of a zero. oven-sh#34435 edits a separate hunk of the same function. No change needed. Supersedes oven-sh#29773 (same source change, no mock-server test file). Refs oven-sh#29772. ### Background - Binary NUMERIC on the wire is `{ndigits, weight, sign, dscale, digits[]}`. Each digit is a base-10000 group. `dscale` is the count of decimal places to display. - The server strips leading and trailing zero groups. A zero has no groups, so its scale lives only in `dscale`. - `Bun.SQL` asks for binary NUMERIC (OID 1700) once it knows the result columns of a prepared statement. Before that, and with `prepare: false`, the server sends text. <details><summary>Notes</summary> Reproduction on 1.4.3-canary.1 (09bb546) against Postgres on 127.0.0.1: ```ts import { SQL } from "bun"; const sql = new SQL({ url: process.env.DATABASE_URL, max: 1 }); await sql.unsafe(`CREATE TEMP TABLE t (v numeric(10, 4) NOT NULL)`); await sql.unsafe(`INSERT INTO t VALUES (0), (1), (1.5), (10)`); (await sql.unsafe(`SELECT v FROM t ORDER BY v`)).map(r => r.v); // text path: ["0.0000", "1.0000", "1.5000", "10.0000"] (await sql.unsafe(`SELECT v FROM t ORDER BY v LIMIT $1`, [10])).map(r => r.v); // binary path: ["0", "1.0000", "1.5000", "10.0000"] (now "0.0000") for (let i = 1; i <= 3; i++) (await sql`SELECT '0.0000'::numeric AS n`)[0].n; // "0.0000", then "0", "0" (now "0.0000" each time) ``` Fail before, pass after: - `USE_SYSTEM_BUN=1 bun test test/js/sql/postgres-binary-numeric.test.ts`: 13 pass, 2 fail (`Expected: "0.0000"`, `Received: "0"`). - `bun bd test test/js/sql/postgres-binary-numeric.test.ts`: 15 pass. - `sql.test.ts -t numeric`: 3 of 29 tests fail on the release build (the tests that hold the four updated assertions). All 29 pass with the fix. - Full `sql.test.ts` (854 tests) against the same server on both builds. The only tests whose result changes because of this diff are the three that hold the four updated assertions: `should handle numeric values with many digits`, `numeric > handles standard decimal numbers`, `numeric > handles zero values`. - Also ran `postgres-binary-numeric-digit-range.test.ts`, `postgres-binary-float-nan-box.test.ts` and `postgres-binary-array-bounds.test.ts` with the debug build: 17 pass. Other clients, checked against the same server under Node 26.3.0: node-postgres 8.11.1 returns `"0.0000"` for a `numeric(10,4)` zero on a simple query, a parameterized query, and a named statement run twice. postgres.js 3.3.5 returns `"0.0000"` on `unsafe()` with and without parameters and on three runs of the same tagged query. `psql` prints `0.0000`, and `0` for `0::numeric`. Parity probe. For 15 expressions, one row selects the value as `numeric` (binary decode) and as `::text` (server rendering). With the fix all 15 match. The release build differs on 10: `0::numeric(10,1)`, `0::numeric(10,4)`, `0::numeric(1000,999)`, `'-0.000'::numeric`, `round(0::numeric, 5)`, `0::numeric(10,2) * 0::numeric(10,3)`, `0.0 * 0.00`, `1.50 - 1.50`, `trunc(0.00049::numeric, 3)`, and a zero with the maximum `dscale` of 16383. `0::numeric` and `0::numeric(10,0)` stay `"0"` on both builds. Range of `dscale`. `numeric_recv` rejects a `dscale` above `0x3FFF` (16383), so a real server sends 0 to 16383. The decoder reads the field as `i16`. A negative value takes the `dscale <= 0` arm, the same rule the non-zero path uses (`if dscale > 0`). The output is at most 2 + 32767 bytes. Sign. The server forces a zero to a positive sign (`make_result`), so `'-0.000'::numeric` arrives as a plain zero with `dscale = 3`. The shortcut ignored the sign before this change and still does. oven-sh#34435 edits the integer-part loop of the same function and leaves the `ndigits == 0` shortcut alone. The two diffs touch separate hunks and merge in either order. Workarounds on released versions: `prepare: false` on the connection, or `SELECT v::text`. </details> <!-- robobun:evidence:begin --> --- **[auto-merge]** gate passed · iteration 0 · 3 files touched <details><summary>fails on main (without fix)</summary> ```console ASAN without fix: 2 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-binary-numeric.test.ts test/js/sql/sql.test.ts bun test v1.4.3 (09bb546) test/js/sql/postgres-binary-numeric.test.ts: Container ready via docker-compose: postgres_plain at 127.0.0.1:5432 (pass) postgres > binary NUMERIC decodes 0.000000001 [221.53ms] (pass) postgres > binary NUMERIC decodes 0.000000000001 [19.05ms] (pass) postgres > binary NUMERIC decodes 0.00000000123 [14.40ms] (pass) postgres > binary NUMERIC decodes 0.0000000000001 [11.85ms] (pass) postgres > binary NUMERIC decodes -0.000000001 [12.83ms] (pass) postgres > binary NUMERIC decodes 0.00000000000000012345 [12.57ms] (pass) postgres > binary NUMERIC decodes 0.00000001 [11.06ms] (pass) postgres > binary NUMERIC decodes 0.0001 [11.33ms] (pass) postgres > binary NUMERIC decodes 123.456 [14.25ms] (pass) postgres > binary NUMERIC decodes 1000000 [12.61ms] (pass) postgres > binary NUMERIC decodes 0 [12.55ms] (pass) postgres > binary NUMERIC decodes 0.123456789012345 [23.20ms] (pass) postgres > binary NUMERIC decodes 12345678.000000009 [13.71ms] 45 | aw ... (truncated) release without fix: 2 FAILED bun test v1.4.3-canary.1 (09bb546) test/js/sql/postgres-binary-numeric.test.ts: Container ready via docker-compose: postgres_plain at 127.0.0.1:5432 (pass) postgres > binary NUMERIC decodes 0.000000001 [7.83ms] (pass) postgres > binary NUMERIC decodes 0.000000000001 [3.55ms] (pass) postgres > binary NUMERIC decodes 0.00000000123 [2.44ms] (pass) postgres > binary NUMERIC decodes 0.0000000000001 [2.65ms] (pass) postgres > binary NUMERIC decodes -0.000000001 [3.00ms] (pass) postgres > binary NUMERIC decodes 0.00000000000000012345 [2.93ms] (pass) postgres > binary NUMERIC decodes 0.00000001 [3.04ms] (pass) postgres > binary NUMERIC decodes 0.0001 [2.06ms] (pass) postgres > binary NUMERIC decodes 123.456 [2.70ms] (pass) postgres > binary NUMERIC decodes 1000000 [2.47ms] (pass) postgres > binary NUMERIC decodes 0 [2.02ms] (pass) postgres > binary NUMERIC decodes 0.123456789012345 [2.09ms] (pass) postgres > binary NUMERIC decodes 12345678.000000009 [1.91ms] 45 | await using sql = new SQL({ 46 | url: `postgres://bun_sql_test@${container.host}:${container.port}/bun_sql_test`, 47 | max: 1, 48 | }); 49 | const [row] = await sql`SELECT ${literal}::num ... (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-binary-numeric.test.ts test/js/sql/sql.test.ts bun test v1.4.3 (09bb546) test/js/sql/postgres-binary-numeric.test.ts: Container ready via docker-compose: postgres_plain at 127.0.0.1:5432 (pass) postgres > binary NUMERIC decodes 0.000000001 [218.12ms] (pass) postgres > binary NUMERIC decodes 0.000000000001 [18.71ms] (pass) postgres > binary NUMERIC decodes 0.00000000123 [12.98ms] (pass) postgres > binary NUMERIC decodes 0.0000000000001 [11.32ms] (pass) postgres > binary NUMERIC decodes -0.000000001 [12.34ms] (pass) postgres > binary NUMERIC decodes 0.00000000000000012345 [12.68ms] (pass) postgres > binary NUMERIC decodes 0.00000001 [12.11ms] (pass) postgres > binary NUMERIC decodes 0.0001 [12.08ms] (pass) postgres > binary NUMERIC decodes 123.456 [13.31ms] (pass) postgres > binary NUMERIC decodes 1000000 [12.63ms] (pass) postgres > binary NUMERIC decodes 0 [12.58ms] (pass) postgres > binary NUMERIC decodes 0.123456789012345 [13.54ms] (pass) postgres > binary NUMERIC decodes 12345678.000000009 [12.24ms] (pass) post ... (truncated) release with fix: all passed $ bun scripts/build.ts --profile=release [configured] bun-profile → bun (stripped) in 859ms (unchanged) ninja: Entering directory `/workspace/bun/build/release' [1/85] gen ErrorCode+*.h [2/31] gen JSBuffer.lut.h Generating /workspace/bun/build/release/codegen/JSBuffer.lut.h from /workspace/bun/src/jsc/bindings/JSBuffer.cpp [3/31] gen generated_host_exports.rs generated_host_exports.rs: 122 exports (host=5, lazy=10, generic=107, rust=0); 243 extern-C blocks audited [4/31] gen BunProcess.lut.h Generating /workspace/bun/build/release/codegen/BunProcess.lut.h from /workspace/bun/src/jsc/bindings/BunProcess.cpp [5/31] gen cpp.rs (cppbind) [6/31] gen JS modules (bundle-modules) Preprocess modules (6745ms) Bundle modules (51ms) Postprocesss modules (19ms) Bundle Functions (484ms) Generate Code (26ms) [7.34s] Bundled "src/js" for production 2600 kb 197 internal modules 13 native modules 50 internal functions across 16 files [6/21] cargo bun_runtime → libbun_runtime.a �[1m�[92m Compiling�[0m bun_sys v0.0.0 (/workspace/bun/src/sys) �[1m�[92m Compiling�[0m bun_perf v0.0.0 (/workspace/bun/src/perf) �[1m�[92m Compiling�[0m bun_threading v0.0.0 (/workspace/bun/ ... (truncated) ``` </details> <details><summary>diff hotspot</summary> ``` src/sql_jsc/postgres/DataCell.rs | 12 +++++++++++- test/js/sql/postgres-binary-numeric.test.ts | 3 +++ test/js/sql/sql.test.ts | 10 +++++----- 3 files changed, 19 insertions(+), 6 deletions(-) ``` </details> **gate history** · 1 passed · 0 rejected · iteration 0 <details><summary>evidence per changed file</summary> ``` file reads edits tests src/sql_jsc/postgres/DataCell.rs 2 1 17 test/js/sql/postgres-binary-numeric.test.ts 1 1 6 test/js/sql/sql.test.ts 1 1 13 ``` </details> <!-- robobun:evidence:end -->
…ven-sh#42729) ### Problem - In a CSS module, `::view-transition-group(.overlay)` prints as `::view-transition-group(.overlay_-MSaAA)`, but the JS exports object is `{}`. The JS side cannot set `view-transition-class` to the hashed name, so the rule matches nothing. Same for `::view-transition-old`, `::view-transition-new` and `::view-transition-image-pair`. Fixes oven-sh#42726. - The cause: `ViewTransitionPartName::Class` held a plain `CustomIdent` (`src/css/selectors/parser.rs:4149`). It printed through `Printer::write_ident`, which hashes the name, but it never called `add_symbol_for_name`. The exports object is built from `local_scope` (`src/bundler/linker_context/generateCodeForLazyExport.rs:73`), so the class was missing. ### Fix - `ViewTransitionPartName::Class` now holds a `LocalIdentifier`, parsed through `SelectorParser::new_local_identifier` with `CssRefTag::CLASS`, the same path a plain `.class` selector uses. It prints through `write_ident_or_ref`. Outside CSS modules the output is unchanged. - `ParseTask.rs` now passes `source.path.pretty` as the CSS modules filename instead of its basename. The link step hashes symbols with `path.pretty` (`src/bundler/LinkerContext.rs:2599`). Names hashed at print time (`view-transition-class`, `animation-name`, `@keyframes`) used the basename. For a module file in a nested directory the two hashes differed. Root-level files keep the same hashes. - `bun build --no-bundle` and `Bun.Transpiler` print a module file with no link step. The printer got an empty symbol map, so a class symbol panicked in `lookup_symbol` (`src/css/printer.rs:189`). This was already the case for a plain `.class` on main. The transpiler now hands the parser's symbols to the printer, and `write_ident_or_ref` hashes the original name when no local names exist, like keyframes. That path also hashes with the relative path now, so two nested files with the same basename get different names. - Verified: `test/bundler/css/css-modules.test.ts` (four new cases). Also `test/bundler/css/`, `test/bundler/esbuild/css.test.ts`, `test/bundler/bundler_loader.test.ts`, `test/bundler/cli.test.ts`, `test/bundler/transpiler/`, `test/js/bun/css/`. ### Background - CSS modules in the bundler keep two name tables. Class and id selectors become symbols in `local_scope` at parse time. The link step renames them (`local_names`) and builds the exports object from that table. - Other scoped names (keyframes, `animation-name`, `view-transition-name`, `view-transition-class`) are hashed at print time by `Printer::write_ident` from the filename in `ParserOptions`. They are not exported. - `IdentOrRef` (`src/css/values/ident.rs`) is the `LocalIdentifier` type. It holds either a raw ident (no CSS modules) or a symbol `Ref`. <details><summary>Notes</summary> Self-reviewed: 8 concerns raised, 2 addressed in the first push (the nested-directory hash mismatch and its test). A later review found that the `--no-bundle` panic, which I had called pre-existing, became reachable for a module file whose only classes are inside `::view-transition-*()`. The third commit fixes that path for all class symbols. Repro of the nested-directory mismatch, with `src/deep/styles.module.css` and only the first commit applied: the declaration printed `view-transition-class: slide_-MSaAA` (basename hash), the selector printed `::view-transition-old(.slide_rJRN2Q)` (path hash) and the export was `slide_rJRN2Q`. The second commit makes all three `slide_rJRN2Q`. `::view-transition-group(.a.b)` and `::view-transition-group(hero.slide)` still fail to parse. That is the existing grammar, not touched here. `view-transition-name: hero` is still hashed but not exported, as on main. </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 $ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/pr_gate.xml" test/bundler/css/css-modules.test.ts bun test v1.4.3 (09bb546) test/bundler/css/css-modules.test.ts: (pass) css > css-module/GlobalPseudoFunction [496.74ms] (pass) css > css-module/BundleTwoFilesWithoutCodeSplitting [123.47ms] (pass) css > css-module/BundleTwoFilesWithCodeSplitting [103.20ms] (pass) css > css-module/AnimationNameScopedToKeyframes [136.50ms] (pass) css > css-module/RepeatedClassAndIdReferences [228.15ms] (pass) css > css-module/ViewTransitionNamesScoped [129.79ms] 309 | color: red; 310 | } 311 | `); 312 | 313 | const js = api.readFile("/out/entry.js"); 314 | expect(js).toEqualIgnoringWhitespace(` ^ error: expect(received).toEqualIgnoringWhitespace(expected) Expected: "\n // styles.module.css\n var styles_module_default = {\n overlay: \"overlay_-MSaAA\",\n pair: \"pair_-MSaAA\",\n \"slide-out\": \"slide-out_-MSaAA\",\n \"slide-in\": \"slide-in_-MSaAA\",\n plain: \"plain_-MSaAA\"\n };\n\n ... (truncated) release without fix: 2 FAILED bun test v1.4.3-canary.1 (d245059) test/bundler/css/css-modules.test.ts: (pass) css > css-module/GlobalPseudoFunction [22.17ms] (pass) css > css-module/BundleTwoFilesWithoutCodeSplitting [6.02ms] (pass) css > css-module/BundleTwoFilesWithCodeSplitting [5.06ms] (pass) css > css-module/AnimationNameScopedToKeyframes [5.25ms] (pass) css > css-module/RepeatedClassAndIdReferences [5.45ms] (pass) css > css-module/ViewTransitionNamesScoped [5.23ms] (pass) css > css-module/ViewTransitionClassExported [4.85ms] (pass) css > css-module/ViewTransitionClassNestedDirectory [4.31ms] (pass) css > css-module/ViewTransitionUnparsedValuesNotScoped [4.44ms] (pass) css > css-module/ExportsMapMultipleClassesAndComposes [4.98ms] 462 | stdout: "pipe", 463 | stderr: "pipe", 464 | }); 465 | const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); 466 | const card = stdout.match(/\.card_([A-Za-z0-9_-]+)\s*\{/); 467 | expect(card, ".card should be scoped").not.toBeNull(); ^ error: .card should be scoped Received: null at <anonymous> (/workspace/bun/test/bundler/css/ ... (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/css/css-modules.test.ts bun test v1.4.3 (09bb546) test/bundler/css/css-modules.test.ts: (pass) css > css-module/GlobalPseudoFunction [513.99ms] (pass) css > css-module/BundleTwoFilesWithoutCodeSplitting [136.72ms] (pass) css > css-module/BundleTwoFilesWithCodeSplitting [127.62ms] (pass) css > css-module/AnimationNameScopedToKeyframes [157.40ms] (pass) css > css-module/RepeatedClassAndIdReferences [261.86ms] (pass) css > css-module/ViewTransitionNamesScoped [129.17ms] (pass) css > css-module/ViewTransitionClassExported [117.93ms] (pass) css > css-module/ViewTransitionClassNestedDirectory [127.06ms] (pass) css > css-module/ViewTransitionUnparsedValuesNotScoped [108.30ms] (pass) css > css-module/ExportsMapMultipleClassesAndComposes [114.17ms] (pass) css-module/NoBundleHashesClassSymbols [156.23ms] (pass) css-module/NoBundleHashesByRelativePath [218.90ms] 12 pass 0 fail 4 snapshots, 45 expect() calls Ran 12 tests across 1 file. [5.23s] __F:0:S:0 release with fix: all passed $ bun scripts/build.ts --profile=release [configured] bun-profile → bun (stripped) in 846ms (unchanged) ninja: Entering directory `/workspace/bun/build/release' [0/4] cargo bun_runtime → libbun_runtime.a �[1m�[92m Compiling�[0m bun_css v0.0.0 (/workspace/bun/src/css) �[1m�[92m Compiling�[0m bun_bundler v0.0.0 (/workspace/bun/src/bundler) �[1m�[92m Compiling�[0m bun_standalone_graph v0.0.0 (/workspace/bun/src/standalone_graph) �[1m�[92m Compiling�[0m bun_transpiler v0.0.0 (/workspace/bun/src/transpiler) �[1m�[92m Compiling�[0m bun_bunfig v0.0.0 (/workspace/bun/src/bunfig) �[1m�[92m Compiling�[0m bun_install v0.0.0 (/workspace/bun/src/install) �[1m�[92m Compiling�[0m bun_jsc v0.0.0 (/workspace/bun/src/jsc) �[1m�[92m Compiling�[0m bun_js_parser_jsc v0.0.0 (/workspace/bun/src/js_parser_jsc) �[1m�[92m Compiling�[0m bun_http_jsc v0.0.0 (/workspace/bun/src/http_jsc) �[1m�[92m Compiling�[0m bun_semver_jsc v0.0.0 (/workspace/bun/src/semver_jsc) �[1m�[92m Compiling�[0m bun_ast_jsc v0.0.0 (/workspace/bun/src/ast_jsc) �[1m�[92m Compiling�[0m bun_sourcemap_jsc v0.0.0 (/workspace/bun/src/sourcemap_jsc) �[1m�[92m Compiling�[0m bun_bundler_jsc v0.0.0 ( ... (truncated) ``` </details> <details><summary>diff hotspot</summary> ``` src/bundler/ParseTask.rs | 2 +- src/bundler/transpiler.rs | 8 +- src/css/printer.rs | 11 ++ src/css/selectors/parser.rs | 35 ++++-- test/bundler/css/css-modules.test.ts | 199 +++++++++++++++++++++++++++++++++++ 5 files changed, 240 insertions(+), 15 deletions(-) ``` </details> **gate history** · 2 passed · 0 rejected · iteration 0 <details><summary>evidence per changed file</summary> ``` file reads edits tests src/bundler/ParseTask.rs 1 1 14 src/bundler/transpiler.rs 1 0 14 src/css/printer.rs 1 1 14 src/css/selectors/parser.rs 4 4 14 test/bundler/css/css-modules.test.ts 2 3 14 ``` </details> **root cause** · written by the author bot The view-transition pseudo-element parser read the class argument of `::view-transition-group(.x)` and friends as a plain identifier, so CSS modules hashed it at print time but never registered it as a local symbol, leaving it out of the exports object. The fix threads the `SelectorParser` context into the view-transition part parsing so the class becomes a proper local identifier that is recorded as a module symbol and serialized through the CSS module-aware printer, which puts the hashed name in both the CSS and the exported JS object. The same change makes `ParseTask` and the `--no-bundl… <!-- robobun:evidence:end -->
…t-in npm package replacements (oven-sh#42718) ### Problem - `docs/guides/http/hot.mdx:7` says "When any module or file changes, Bun re-runs the file." `bun --hot` watches only the entry file and the files it imports. An edit to `.env`, `bunfig.toml`, or `tsconfig.json` triggers no reload. - `docs/runtime/watch-mode.mdx:124` shows `Reloaded 1 times` first. The sample logs before it increments, so the first line is `Reloaded 0 times`. - No docs page says that Bun resolves `undici`, `node-fetch`, `ws`, and other npm specifiers to built-in modules, even when the package is installed. ### Fix - `hot.mdx`: say what `--hot` watches, name three files it does not watch, and say to restart Bun for those. - `watch-mode.mdx`: the output sample starts at `Reloaded 0 times`. - `module-resolution.mdx`: new section "Built-in replacements for npm packages". It lists every third-party specifier in the alias table (`src/resolve_builtins/HardcodedModule.rs:746-799`), what each loads, how subpaths and `require.resolve()` behave, and what `bun build` does per target. - Verified: I ran every claim on a release build of main (`1.4.3-canary.1+09bb54630`). Output is in Notes. `prettier --check` passes. ### Background - `--hot` adds a file to the watcher when the module loader loads it, and skips `node_modules`. Bun reads `.env` and `bunfig.toml` at startup, outside the module loader. - The alias table maps a specifier to a built-in module before the resolver looks at `node_modules`. It applies when the target is `bun`: the runtime and `bun build --target=bun`. - oven-sh#36102 (open) makes bare `undici` prefer the installed package. If it lands, the `undici` row changes with it. <details><summary>Notes</summary> No hunk overlaps oven-sh#30912 (`watch-mode.mdx` lines 91-99 and 146-153) or oven-sh#38408 (`module-resolution.mdx` line 309 and below). **`--hot` triggers.** `server.ts` is the sample from `watch-mode.mdx:104-116`, with `.env`, `tsconfig.json`, and `bunfig.toml` in the same directory. A driver script edits one file, waits, and counts the `Reloaded` lines. ``` [after start] lines=1 [after .env edit] lines=1 [after tsconfig edit] lines=1 [after bunfig edit] lines=1 [after server.ts edit 1] lines=2 [after server.ts edit 2] lines=3 --- out.log Reloaded 0 times Reloaded 1 times Reloaded 2 times ``` **Resolution.** `node_modules/{undici,node-fetch,ws,isomorphic-fetch}` each hold a stub package that exports `{ fromNodeModules: true }`. ``` $ bun b.cjs undici resolve: undici fromNodeModules: false node-fetch resolve: node-fetch fromNodeModules: false ws resolve: ws fromNodeModules: false isomorphic-fetch resolve: isomorphic-fetch fromNodeModules: false undici/package.json -> /tmp/dv/undici-check/node_modules/undici/package.json $ node b.cjs undici resolve: /tmp/dv/undici-check/node_modules/undici/index.js fromNodeModules: true ... ``` `require.resolve()` for every specifier in the table: ``` @vercel/fetch -> @vercel/fetch isomorphic-fetch -> isomorphic-fetch node-fetch -> node-fetch undici -> undici utf-8-validate -> utf-8-validate ws -> ws ws/lib/websocket -> ws abort-controller -> abort-controller abort-controller/polyfill -> abort-controller next/dist/compiled/ws -> ws next/dist/compiled/node-fetch -> node-fetch next/dist/compiled/undici -> undici undici/package.json -> /tmp/dv/undici-check/node_modules/undici/package.json ws/package.json -> /tmp/dv/undici-check/node_modules/ws/package.json ``` `import.meta.resolve("undici")` and `import.meta.resolve("node-fetch")` return `undici` and `node-fetch`. **What the built-in modules do.** A local `Bun.serve` answers `direct:<path>`. ``` undici.Request/Response/Headers/FormData/File/WebSocket === the globals: true (each) undici.fetch === Bun.fetch: true undici.fetch with dead ProxyAgent -> 200 direct:/x global fetch after setGlobalDispatcher(dead proxy) -> direct:/x Agent has dispatch/close/destroy/compose: undefined,undefined,undefined,undefined undici.request -> 200 body is Readable: true direct:/x undici.stream() / pipeline() / connect() / upgrade() -> This function is not yet implemented in Bun node-fetch res instanceof Response: true | body is Readable: true | buffer(): function | headers.raw(): function abort-controller default === AbortController: true, .AbortSignal === AbortSignal: true utf-8-validate: function, returns true for Buffer.from("hi") ``` `ws`: `WebSocket` wraps the global `WebSocket` (`src/js/thirdparty/ws.js:312`). `WebSocketServer` uses `node:http` and `server.upgrade()` (`ws.js:1373`, `ws.js:1566`). `utf-8-validate` exports `jsBufferConstructorFunction_isUtf8` (`src/jsc/modules/UTF8ValidateModule.h:16`), the function behind `isUtf8` in `node:buffer`. **`bun build`.** The entry imports `fetch` from `undici` and the default export of `node-fetch`, with the stub packages installed. ``` --target=bun keeps import { fetch as f1 } from "undici"; import f2 from "node-fetch"; --target=node bundles node_modules/undici/index.js and node_modules/node-fetch/index.js --target=browser bundles node_modules/undici/index.js and node_modules/node-fetch/index.js ``` The `bun test` rewrite of `@jest/globals` and `vitest` to `bun:test` uses the same table. It is already in `docs/guides/test/migrate-from-jest.mdx:19` and is not repeated here. </details>
…#42489) ### Problem - `NumberRenamer.names` is `names[source_index][inner_index]`. Each chunk has a 24-byte slot per file of the bundle: 215 MB of the 405 MB peak for 800 entry points x 13 modules. Every chunk's renamer is alive until its chunk is printed. - A row grows to the inner index of each symbol it names, and a chunk also names the bindings it imports (`pin_top_level_symbol`, `src/js_printer/renamer.rs:886`). 800 chunks import one function declared after 200,000 constants: 2,121 MB peak RSS. A `require_*` wrapper is the last symbol of its file. ### Fix - A symbol of another chunk's file already has one name in the linker's `cross_chunk_names`. `pin_top_level_symbol` only reserves it in the root scope, and `name_for_symbol` reads it from the linker. No copy per chunk. - `names` has one row per file of the chunk. A `u32` table maps a source index to its row. With `--splitting` each file is in one chunk, so the linker builds one table for all chunks. - 2,121 MB is now 276 MB, 405 MB is now 200 MB. `diff -r` of 4,933 output files: no difference. One intended change: a chunk no longer reserves a name for a binding it imports and never uses. - Verified: two new tests in `test/bundler/bundler_splitting.test.ts`. More in Notes. ### Background - The linker makes one renamer per chunk before it prints a chunk. `NumberRenamer` is the one for builds without `--minify-identifiers`. - A `Ref` is a source index plus an inner index: a file and a position in its symbol table. - `cross_chunk_names` (oven-sh#40518) gives each binding that crosses chunks one bundle-wide name. - oven-sh#41861 sized the `ids` and `slots` tables from the chunk, not `names`. <details><summary>Notes</summary> **History of this PR.** The first version kept the per-chunk names of imported symbols in a `HashMap<Ref, NameStr>` and left the per-file slots alone. Review asked for no per-chunk copy at all, for a dense `names`, and for a structural test. This is that rework. Earlier comments refer to the first version. **Numbers.** Release builds of the same commit with and without the change, Linux x64, peak RSS from `getrusage`. The project from the report: `big.js` with 200,000 `export const` and one `export function pick`, and N entry points that each import `pick`. | entry chunks | `pick` last, before | `pick` last, after | `pick` first, after | | --- | --- | --- | --- | | 100 | 463 MB | 232 MB | 215 MB | | 200 | 700 MB | 241 MB | | | 400 | 1,172 MB | 251 MB | 235 MB | | 800 | 2,121 MB | 276 MB | 261 MB | | 1,600 | 4,054 MB | 328 MB | 312 MB | The CommonJS case: `big.cjs` with `module.exports = { pick, ... }` and 50,000 other symbols, 200 entry points that import `pick`, `--splitting`. Before 160 MB, after 47 MB. Other builds, median of 9 runs (15 for `typescript.js`), before and after: | build | peak RSS | wall (median) | | --- | --- | --- | | 800 entry points x 13 own modules, `--splitting` | 405 MB, 200 MB | 0.26 s, 0.21 s | | the same, no `--splitting` | 404 MB, 195 MB | 0.26 s, 0.21 s | | the same, `--splitting --minify-identifiers` (`MinifyRenamer`, not changed) | 169 MB | | | 3,000 modules, one chunk | 711 MB, 711 MB | 445 ms, 455 ms | | 3,000 modules, 300 entry points, `--splitting` (562 files) | 840 MB, 700 MB | 487 ms, 449 ms | | 3,000 modules, 300 entry points, no `--splitting` | 802 MB, 785 MB | 452 ms, 445 ms | | `typescript.js`, one file | 127 MB, 129 MB | 324 ms, 329 ms | The machine is shared, so medians of wall time move by a few percent between runs. A second set of 21 runs of the 3,000-module single chunk gave 446 ms and 445 ms. **The lookup.** `row_of_source[source_index] - first_row` is the row if it is less than `names.len()`. Rows are numbered in chunk order and then in `files_in_chunk_order`, so the rows of a chunk are consecutive and one subtraction tells if a file is in the chunk. `renamer_rows` returns `None` when a file is in two chunks (several entry points without `--splitting` that share a file, for example the runtime). Then each renamer has a `hashbrown` map from source index to row that holds only its own files. 800 entry points x 13 own modules plus one file that all of them import, no `--splitting`: 401 MB before, 202 MB after. 300 entry points that share 3,000 modules, no `--splitting`, median of 15 runs: 471 ms before, 472 ms after. **The output change.** `add_top_level_symbol` returns early for a symbol of another chunk's file. An imported binding that the chunk uses is pinned before that, as before. A binding that a file of the chunk imports and never uses (or uses only in code that tree shaking removes) reserved its name on main. Now it does not: ```js // shared.js (its own chunk) // a-helper.js (chunk of a.js) // a.js export const x = 1; import { y } from "./shared.js"; import "./a-helper.js"; export const y = 2; console.log("helper"); import { x } from "./shared.js"; const y = 5; console.log(x, y); ``` main prints `var y2 = 5` in the chunk of `a.js`. This branch prints `var y = 5`. The unused `y` of `shared.js` is not printed in that chunk, so nothing can collide with it. **Links.** `name_for_symbol` looks an imported symbol up by the ref its links lead to. `assign_unminified` keys `cross_chunk_names` by the export's ref. The two differ for `export var x = 1; var x = 2;`, where the parser links the first `x` to the second (oven-sh#42409 describes it). So `assign_unminified` also adds the followed ref. `splitting/CrossChunkNameOfRedeclaredExport` covers it: without that insert it fails with `"x" has already been declared`. **Tests.** `splitting/ChunkRenamerTablesHoldOnlyTheChunksOwnFiles` builds two entry points that import from an ES module and from a CommonJS module, each with 1,000 other symbols. With `BUN_DEBUG_ChunkRenamer=1` a debug build logs, per chunk, the file count, the row count and the name slot count of its renamer. The test asserts that each entry chunk has 1 row and fewer than 50 name slots (it has 4). The log is a scoped debug log, so the test is skipped on release builds, like `test/js/bun/resolve/tsconfig-extends-leak.test.ts`. The RSS test of the first version is gone. **Suites run with the debug build.** All of `test/bundler/bundler_splitting.test.ts`, `test/bundler/esbuild/{splitting,default,importstar,importstar_ts,dce,ts}.test.ts`, `test/bundler/bundler_{edgecase,regressions,cjs2esm,naming,minify,compile_splitting,html}.test.ts`, `test/bake/dev/{bundle,esm}.test.ts`. `test/bundler/bun-build-api.test.ts` has three tests that time out on this loaded debug build, so I ran it with the two release builds: 66 pass on both. **Not changed.** The mimalloc heap that each renamer owns (`arena`). `MinifyRenamer`. </details> <!-- robobun:evidence:begin --> --- **[human-review]** gate passed · iteration 0 · 6 files touched <details><summary>fails on main (without fix)</summary> ```console ASAN without fix: 1 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 (09bb546) test/bundler/bundler_splitting.test.ts: (pass) bundler > splitting/DynamicImportCSSFile [1256.76ms] (pass) bundler > splitting/DynamicImportMultipleCSSImports [808.91ms] (pass) bundler > splitting/StaticAndDynamicCSSImports [763.80ms] (pass) bundler > splitting/NestedDynamicImportWithCSS [734.52ms] (pass) bundler > splitting/SharedCSSBetweenChunks [699.30ms] (pass) bundler > splitting/DynamicImportChainWithCSS [936.04ms] (pass) bundler > splitting/ConditionalDynamicImportWithCSS [727.08ms] (pass) bundler > splitting/MultipleEntryPointsWithSharedCSS [1087.03ms] (pass) bundler > splitting/DynamicImportWithOnlyCSSNoJS [777.53ms] (pass) bundler > splitting/CircularDynamicImportsWithCSS [711.07ms] (pass) bundler > splitting/DeadDynamicImportTargetGetsNoChunk-cli [753.99ms] (pass) bundler > splitting/DeadDynamicImportTargetGetsNoChunk-api [592.91ms] (pass) bundler > splitting/DeadDynamicImportTargetNoSplittingReference [684.20ms] (pass) bundler > splitting/DeadDynamicImportTa ... (truncated) release without fix: 4 skipped bun test v1.4.3-canary.1 (6bec1ef) test/bundler/bundler_splitting.test.ts: (pass) bundler > splitting/DynamicImportCSSFile [26.43ms] (pass) bundler > splitting/DynamicImportMultipleCSSImports [14.04ms] (pass) bundler > splitting/StaticAndDynamicCSSImports [14.61ms] (pass) bundler > splitting/NestedDynamicImportWithCSS [13.20ms] (pass) bundler > splitting/SharedCSSBetweenChunks [15.64ms] (pass) bundler > splitting/DynamicImportChainWithCSS [14.41ms] (pass) bundler > splitting/ConditionalDynamicImportWithCSS [14.44ms] (pass) bundler > splitting/MultipleEntryPointsWithSharedCSS [19.35ms] (pass) bundler > splitting/DynamicImportWithOnlyCSSNoJS [13.03ms] (pass) bundler > splitting/CircularDynamicImportsWithCSS [15.17ms] (pass) bundler > splitting/DeadDynamicImportTargetGetsNoChunk-cli [11.63ms] (pass) bundler > splitting/DeadDynamicImportTargetGetsNoChunk-api [13.74ms] (pass) bundler > splitting/DeadDynamicImportTargetNoSplittingReference [13.31ms] (pass) bundler > splitting/DeadDynamicImportTargetKeptWithoutTreeShaking [12.21ms] (pass) bundler > splitting/LiveDynamicImportTargetStillGetsChunk [16.91ms] (pass) bundler > splitting/DynamicImportChainLiveness [17.31ms] ( ... (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 (09bb546) test/bundler/bundler_splitting.test.ts: (pass) bundler > splitting/DynamicImportCSSFile [1234.67ms] (pass) bundler > splitting/DynamicImportMultipleCSSImports [657.65ms] (pass) bundler > splitting/StaticAndDynamicCSSImports [621.68ms] (pass) bundler > splitting/NestedDynamicImportWithCSS [666.60ms] (pass) bundler > splitting/SharedCSSBetweenChunks [821.23ms] (pass) bundler > splitting/DynamicImportChainWithCSS [851.81ms] (pass) bundler > splitting/ConditionalDynamicImportWithCSS [707.22ms] (pass) bundler > splitting/MultipleEntryPointsWithSharedCSS [918.65ms] (pass) bundler > splitting/DynamicImportWithOnlyCSSNoJS [607.51ms] (pass) bundler > splitting/CircularDynamicImportsWithCSS [725.79ms] (pass) bundler > splitting/DeadDynamicImportTargetGetsNoChunk-cli [711.70ms] (pass) bundler > splitting/DeadDynamicImportTargetGetsNoChunk-api [505.03ms] (pass) bundler > splitting/DeadDynamicImportTargetNoSplittingReference [608.86ms] (pass) bundler > splitting/DeadDynamicImportTar ... (truncated) release with fix: 4 skipped $ bun scripts/build.ts --profile=release [configured] bun-profile → bun (stripped) in 990ms (unchanged) ninja: Entering directory `/workspace/bun/build/release' [0/5] cargo bun_runtime → libbun_runtime.a �[1m�[92m Compiling�[0m bun_core v0.0.0 (/workspace/bun/src/bun_core) �[1m�[92m Compiling�[0m bun_errno v0.0.0 (/workspace/bun/src/errno) �[1m�[92m Compiling�[0m bun_ptr v0.0.0 (/workspace/bun/src/ptr) �[1m�[92m Compiling�[0m bun_boringssl_sys v0.0.0 (/workspace/bun/src/boringssl_sys) �[1m�[92m Compiling�[0m bun_safety v0.0.0 (/workspace/bun/src/safety) �[1m�[92m Compiling�[0m bun_base64 v0.0.0 (/workspace/bun/src/base64) �[1m�[92m Compiling�[0m bun_cares_sys v0.0.0 (/workspace/bun/src/cares_sys) �[1m�[92m Compiling�[0m bun_zlib_sys v0.0.0 (/workspace/bun/src/zlib_sys) �[1m�[92m Compiling�[0m bun_zstd v0.0.0 (/workspace/bun/src/zstd) �[1m�[92m Compiling�[0m bun_picohttp v0.0.0 (/workspace/bun/src/picohttp) �[1m�[92m Compiling�[0m bun_brotli v0.0.0 (/workspace/bun/src/brotli) �[1m�[92m Compiling�[0m bun_output v0.0.0 (/workspace/bun/src/output) �[1m�[92m Compiling�[0m bun_collections v0.0.0 (/workspace/bun/src/collections) �[1m�[92m Co ... (truncated) ``` </details> <details><summary>diff hotspot</summary> ``` src/bundler/LinkerContext.rs | 5 +- src/bundler/linker_context/crossChunkNames.rs | 5 + .../linker_context/generateChunksInParallel.rs | 7 ++ src/bundler/linker_context/renameSymbolsInChunk.rs | 57 +++++++++-- src/js_printer/renamer.rs | 111 ++++++++++++++++----- test/bundler/bundler_splitting.test.ts | 67 +++++++++++++ 6 files changed, 218 insertions(+), 34 deletions(-) ``` </details> **gate history** · 2 passed · 0 rejected · iteration 0 <details><summary>evidence per changed file</summary> ``` file reads edits tests src/bundler/LinkerContext.rs 0 0 34 src/bundler/linker_context/crossChunkNames.rs 1 0 34 src/bundler/linker_context/generateChunksInParallel.rs 1 0 34 src/bundler/linker_context/renameSymbolsInChunk.rs 1 1 34 src/js_printer/renamer.rs 6 7 34 test/bundler/bundler_splitting.test.ts 5 4 34 ``` </details> <!-- robobun:evidence:end -->
…mises in a weak set (oven-sh#43208) ### Problem - N promises that reject and get a handler in the same turn cost O(N^2). `Promise.allSettled` over 100,000 async calls that throw takes 24 s on main. Node takes 0.5 s. - The cause is `promiseRejectionTracker` (`src/jsc/bindings/ZigGlobalObject.cpp:1190`). Each `Handle` searched the queue with `Vector::removeFirstMatching`, then shifted every entry behind the hit. It also walked the batch that `handleRejectedPromises()` reports. ### Fix - `Handle` only needs to know if the promise was reported. `handleRejectedPromises()` adds a promise to a `JSWeakSet` right before it reports it, and `Handle` asks that set. Nothing searches the queue. The design is @alii's, from review. - The queue is append-only, in `src/jsc/bindings/RejectedPromiseQueue.{h,cpp}`. `Handle` pops the promise if it is the newest entry, with the handled entries before it. A full vector drops its handled entries before it grows. - Verified: `test/js/node/process/process.test.js` (4 timing tests fail on main), and a differential fuzz with identical event logs. ### Background - JSC calls `promiseRejectionTracker` with `Reject` when a promise rejects with no handler, and with `Handle` when it gets one. Bun reports what is left after the microtask drain. A handler after the report gets `rejectionHandled`. - A `JSWeakSet` is the GC-managed set behind `WeakSet`. The GC removes a promise from it when the promise dies. ### Downsides - A handled promise that is not the newest entry stays queued until it is at the end, the vector fills, or the drain. A loop that awaits each rejection one step late keeps up to 60 alive. Main keeps 2. - While a reported promise is alive, each `Handle` of a promise that is not the newest entry pays a weak-set lookup: 67.5 ns against 64.8 ns per promise in batches of 64 (main: 82.8). <details><summary>Notes</summary> `append()` and `didHandle()` are `ALWAYS_INLINE` in the header: main inlines the old pair into the tracker, and the file split had stopped that (the +84 instructions per caught async throw of the cost report). Release builds of the same commit (main 6d504dd), linux x64, one pinned core, concurrent JIT off, min of 5 interleaved runs. "previous head" is e457ee9 of this PR (holes, the next-in-order check, a scan of 256, a `JSWeakMap` index). Nanoseconds per promise for `Promise.reject(i)` then `.catch(noop)`, K rejections per turn: | shape | main | previous head | this PR | | --- | --- | --- | --- | | K = 1 | 148.9 | 148.2 | 147.9 to 150.4 | | oldest first, K = 17 | 84.5 | 84.9 | 69.0 | | oldest first, K = 64 | 83.2 | 83.2 | 64.4 | | oldest first, K = 300 | 92.6 | 81.6 | 64.4 | | oldest first, K = 1,000 | 1,781 | 82.5 | 64.8 | | newest first, K = 300 | 122.8 | 79.3 | 79.6 | | random, K = 64 | 84.1 | 87.9 | 64.9 | | random, K = 256 | 107.4 | 115.6 | 64.9 | | random, K = 512 | 138.8 | 170.1 | 64.3 | | random, K = 1,000 | 596.0 | 163.6 | 64.8 | | oldest first behind one unhandled rejection, K = 300 | 93.2 | 81.6 | 63.6 | | `allSettled` loop, N = 100, reused Error | 310.2 | 307.9 | 296.5 | | `allSettled` loop, N = 1,000, reused Error | 2,017 | 302.5 | 291.5 | | `try { await f() } catch {}`, reused Error | 552.8 | 554.9 | 551.9 | | `try { await f() } catch {}`, new Error | 809.6 | 810.8 | 813.7 | K = 1 measured 147.9 without the full-vector check and 149.5 to 150.4 with a first version of it. The check is now the vector's own capacity check (`makeRoom()` runs where `Vector::append` would grow), and a later run measured main 160.4, previous head 158.6, this PR 159.3 on a busier host. The `try` rows are equal within noise. Large N on this PR: `allSettled` over 100,000 throwing calls takes 148 ms (main 24,009, node 475). Attaching `.catch` to 160,000 rejected promises takes 24 ms oldest first, 36 ms in random order, 25 ms newest first (previous head 27 / 69 / 27, main 83 s / 49 s / 6.5 s as reported). An `unhandledRejection` listener that calls `promise.catch()` on 160,000 rejections takes 88 ms (previous head 99 ms, 12.7 s before). Memory, the row that decided the full-vector sweep. One turn, 1,000,000 steps, each rejection (a new `Error`) awaited one step late: | build | time | peak RSS growth | | --- | --- | --- | | main | 963 ms | 60 MB | | previous head | 957 ms | 61 MB | | append-only, handled entries leave only from the end | 3,360 ms | 1,165 MB | | this PR (handled entries also leave when the vector is full) | 1,014 ms | 62 MB | The sweep runs only where the vector would otherwise grow, from a capacity of 64 up, and the vector doubles when the sweep freed less than half. So `append()` stays amortized O(1), also for a burst of rejections that nobody handles. Behaviour: a differential fuzz (random interleavings of rejections and handles in one turn, oldest-first, newest-first and mixed styles with strays, batches of 1 to 900, a listener that handles promises later in the batch or the one being reported, late handles, forced GC) gives byte-identical `unhandledRejection` / `rejectionHandled` logs on main and on this PR: 24 seeds on release builds, 8 more plus 3 with forced GC on the debug ASAN and UBSan build, which is clean. The behaviour test of the previous head passed unchanged on the new internals before I extended it. Tests: the behaviour test pins the event order for rejections handled one step late, oldest first with stragglers, newest first, a few in no order, a long queue that shrinks and grows again, handles from the listener of the batch that is being reported (later promises get neither event, an already reported one gets `rejectionHandled`), and late handles while other rejections wait. Two GC checks, both through `heapStats().objectTypeCounts.Date` after `Bun.gc(true)`: the 143 reasons that only the queue can reach must all be alive (with a `visit()` that stops after 10 entries the child crashes, on debug with `ASSERTION FAILED: decontaminate()`, on release with a crash report), and a loop that awaits each rejection one step late must not keep more than 200 of 2,000 handled reasons alive (2,001 without the full-vector sweep, 47 to 60 with it, 2 on main). Five timing tests: oldest first, no particular order and from the listener at N = 100,000 (`ms < max(limit, 20 * baseline)` against the same calls on handled promises), and two ratio tests (batches of 17, 64 and 300 oldest first, and the `allSettled` loop at 100 and 1,000). On a release build of main four of them fail (killed at 20 s, 14,248 ms, 4,236 ms, and a ratio of 5.6). One behaviour is different in a case the fuzz does not reach: a promise that is rejected in one global object and handled from another. Main asks the queue of the handler's global, does not find the promise, and emits `rejectionHandled` from there, also for a promise that was never reported. Now that global emits it only for a promise it reported itself. `node:vm` contexts are not affected: they send both operations to the main global. Bun's semantics are unchanged where they differ from Node: a listener that handles a promise later in the batch suppresses both events for it (pinned by the existing test from oven-sh#32554). Node v26 still reports it as unhandled. History of this PR: the first version removed the search with holes and a hash index. A cost report showed 36 to 48 % more per promise in batches of 17 to 256, which led to the next-in-order check and inline fast paths. @Jarred-Sumner asked for a GC map instead of raw cell keys, and for a separate file. @alii then proposed this design, which needs neither the index nor the scan. Found on the way and reported separately: `abort()` on a signal with N `{ once: true }` listeners is O(N^2) in `EventTarget` (80,000 listeners: 9.1 s, node 44 ms). It is not part of this change. Other suites run on the debug build: all of `test/js/node/process/process.test.js`, the 20 node `parallel` tests whose names contain `unhandled` or `rejection`, `test/js/bun/module-graph/module-graph.test.ts`, `module-graph-gc.test.ts`. </details> <!-- robobun:evidence:begin --> --- **no test proof** · iteration 1 · platform-specific test(s) that do not run on this machine, deferring to CI, which covers all platforms: test/js/node/process/process.test.js <!-- robobun:evidence:end --> Co-authored-by: Alistair Smith <[email protected]>
…sh#43019) ### Problem - `bun pm view` and `bun info` abort when the registry sends a packument whose matched `versions` entry is not an object, for example `{"name":"evil","dist-tags":{"latest":"1.0.0"},"versions":{"1.0.0":5}}`. Release builds print `panic: internal error: entered unreachable code`. Debug builds print `assertion failed: matches!(self.data, Data::EObject(_))`. - The cause is `src/runtime/cli/pm_view_command.rs:229`. It takes `versions[v]` from the response as is. Line 291 then calls `Expr::set` on it (`src/ast/expr.rs:496`). `Expr::set` requires an object and reaches `unreachable!()` for any other JSON type. ### Fix - Check the value where `view()` reads it. An entry that is not an object prints `error: failed to parse package manifest: version "1.0.0" is not an object` and exits with 1. `--json` and property lookups take the same path. - Correct because `view()` is the only caller of `Expr::set`. Every other read of the entry (`get`, `get_object`, `get_string_cloned`) already returns `None` for a non-object. - Verified: `test/cli/install/bun-info.test.ts` (6 new tests against a local registry, all end with SIGABRT on 1.4.3). Also `redacted-config-logs.test.ts` and `test/cli/bun.test.ts`. ### Background - A packument is the registry document for a package: root metadata plus `versions`, a map from version string to that version's `package.json`. - `view()` reads the response two times. `PackageManifest::parse` (`src/install/npm.rs`) resolves the requested tag or range. It accepts a non-object entry as a version with no fields. `JSON::parse_utf8` builds the AST that `view()` prints. - `Expr::set` replaces or appends one property of an object expression. `view()` uses it to put the list of all version strings under the `versions` key of the entry. <details><summary>Notes</summary> - Shapes tried on 1.4.3-canary (c6b7fcb): number, string, `null`, array and boolean all abort, through the dist-tag lookup and through the range lookup. An object entry, `{}` included, works. - 1.3.14 has the same defect with a different failure: the number form ends with `Segmentation fault at address 0x0`, the string form reads the string as an object and prints a view. The behavior was never correct, so the test is in the existing file for this command. - A probe of 3,480 runs found no other abort in `bun pm view` on the release build. The probe sets hostile types on root fields, version fields, `dist`, `dist-tags`, `time`, `maintainers`, `keywords` and dependency values, with 5 specs and 8 argument sets. On the debug build the same probe reaches only debug-only assertions in `src/install/npm.rs`. A separate change handles those. - `bun install` on the same packument does not abort. It resolves the version and requests the default tarball URL. - oven-sh#42052 rewrites `view()` and removes the `Expr::set` call. The one that lands second needs a small rebase. </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: 6 FAILED $ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/pr_gate.xml" test/cli/install/bun-info.test.ts bun test v1.4.3 (c6b7fcb) test/cli/install/bun-info.test.ts: (pass) bun info > bun info (main command) > should display package info for latest version [359.35ms] (pass) bun info > bun info (main command) > should handle missing arguments [301.95ms] (pass) bun info > bun info (main command) > should display package info for specific version [367.06ms] (pass) bun info > bun pm view (alias) > should display package info for latest version [327.98ms] (pass) bun info > bun info (main command) > should display specific property [459.95ms] (pass) bun info > bun pm view (alias) > should display package info for specific version [284.24ms] (pass) bun info > bun pm view (alias) > should display specific property [339.86ms] (pass) bun info > bun pm view (alias) > should display nested property [339.81ms] (pass) bun info > bun pm view (alias) > should handle non-existent package [278.93ms] (pass) bun info > bun pm view (alias) > should output JSON format with --json flag [492.98ms] (pass) bun info > bun pm view ... (truncated) release without fix: 6 failed, 1 skipped bun test v1.4.3-canary.1 (c6b7fcb) test/cli/install/bun-info.test.ts: (pass) bun info > bun info (main command) > should display package info for latest version [78.59ms] (pass) bun info > bun info (main command) > should display package info for specific version [88.25ms] (pass) bun info > bun info (main command) > should handle missing arguments [85.92ms] (pass) bun info > bun info (main command) > should display specific property [87.96ms] (pass) bun info > bun pm view (alias) > should display package info for specific version [84.50ms] (pass) bun info > bun pm view (alias) > should display nested property [84.47ms] (pass) bun info > bun pm view (alias) > should display package info for latest version [92.17ms] (pass) bun info > bun pm view (alias) > should output JSON format with --json flag [83.61ms] (pass) bun info > bun pm view (alias) > should display specific property [91.93ms] (pass) bun info > bun pm view (alias) > should handle non-existent package [83.04ms] (pass) bun info > bun pm view (alias) > should handle non-existent property [84.37ms] (pass) bun info > bun pm view (alias) > should handle non-existent version [88.66ms] (pass) bun info > bun pm ... (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/install/bun-info.test.ts bun test v1.4.3 (c6b7fcb) test/cli/install/bun-info.test.ts: (pass) bun info > bun info (main command) > should display package info for latest version [304.51ms] (pass) bun info > bun info (main command) > should handle missing arguments [253.72ms] (pass) bun info > bun pm view (alias) > should display package info for latest version [305.46ms] (pass) bun info > bun info (main command) > should display package info for specific version [383.18ms] (pass) bun info > bun info (main command) > should display specific property [385.05ms] (pass) bun info > bun pm view (alias) > should display package info for specific version [270.60ms] (pass) bun info > bun pm view (alias) > should display specific property [336.12ms] (pass) bun info > bun pm view (alias) > should display nested property [283.27ms] (pass) bun info > bun pm view (alias) > should handle non-existent package [255.92ms] (pass) bun info > bun pm view (alias) > should output JSON format with --json flag [324.13ms] (pass) bun info > bun pm view ... (truncated) release with fix: 1 skipped $ bun scripts/build.ts --profile=release [configured] bun-profile → bun (stripped) in 777ms (unchanged) ninja: Entering directory `/workspace/bun/build/release' [1/7] gen generated_host_exports.rs generated_host_exports.rs: 121 exports (host=5, lazy=10, generic=106, rust=0); 242 extern-C blocks audited [1/7] cargo bun_runtime → libbun_runtime.a �[1m�[33mwarning�[0m�[1m: binary `bun_shim_impl` should have a kebab-case name�[0m �[1m�[94m|�[0m �[1m�[94m 1�[0m �[1m�[94m|�[0m /workspace/bun/build/release/rust-target/.../bun_shim_impl �[1m�[94m|�[0m �[1m�[33m^^^^^^^^^^^^^�[0m �[1m�[94m|�[0m �[1m�[94m= �[0m�[1mnote�[0m: `cargo::non_kebab_case_bins` is set to `warn` by default �[1m�[96mhelp�[0m: to change the binary name to `bun-shim-impl`, convert `bin.name` �[1m�[94m--> �[0msrc/install/windows-shim/Cargo.toml:41:8 �[1m�[94m|�[0m �[1m�[94m41�[0m �[91m- �[0mname = �[91m"bun_shim_impl"�[0m �[1m�[94m41�[0m �[92m+ �[0mname = �[92m"bun-shim-impl"�[0m �[1m�[94m|�[0m �[1m�[33mwarning�[0m: `bun_shim_impl` (manifest) generated 1 warning �[1m�[33mwarning�[0m�[1m: `feature(generic_const_exprs)` is not supported with ... (truncated) ``` </details> <details><summary>diff hotspot</summary> ``` src/runtime/cli/pm_view_command.rs | 11 +++++++- test/cli/install/bun-info.test.ts | 52 +++++++++++++++++++++++++++++++++++++- 2 files changed, 61 insertions(+), 2 deletions(-) ``` </details> **gate history** · 1 passed · 0 rejected · iteration 0 <details><summary>evidence per changed file</summary> ``` file reads edits tests src/runtime/cli/pm_view_command.rs 2 2 9 test/cli/install/bun-info.test.ts 1 0 9 ``` </details> <!-- robobun:evidence:end -->
…ven-sh#43011) ### Problem - Nine crafted bytes make `v8.deserialize()` return an `X509Certificate` with no certificate inside. `cert.publicKey.equals(cert.publicKey)` then crashes with `panic(main thread): Segmentation fault at address 0x10`. `cert.toLegacyObject()` returns an empty `JSValue`. `typeof` on it crashes at address 0x5. - The cause is `readX509Certificate()` (`src/jsc/bindings/webcore/SerializedScriptValue.cpp:3392`). For a zero-length DER it called the cell-only `JSX509Certificate::create(vm, structure)`, which leaves `m_x509` null. No constructor produces this state: `new X509Certificate(Buffer.alloc(0))` throws. - Only code that deserializes untrusted bytes is exposed: `node:v8`, `bun:jsc`, IPC with `serialization: "advanced"`. ### Fix - Remove the zero-length branch. `d2i_X509` now receives the empty buffer and fails, so the reader calls `fail()` as for any malformed DER. Both entry points throw `TypeError: Unable to deserialize data.` - Correct because the serializer never wrote a zero-length DER. Since oven-sh#16173 it aborts the clone when `i2d_X509` returns `size <= 0`. - Make the `JSX509Certificate` constructor and `create(vm, structure)` private. Only the `create()` overloads that set `m_x509` call them. - Verified: `test/js/web/workers/structured-clone.test.ts` (8 new tests, canary c6b7fcb fails 3). Also `x509.test.ts`, `x509-subclass.test.ts`, `structuredClone-classes.test.ts`. Self-reviewed: 1 should-fix concern (no spawned crash fixture), addressed. ### Background - Structured clone writes each value as a tag byte and a payload. Bun adds host tags for its own classes. Tag 253 is `X509Certificate`: a `u32` length, then the certificate in DER (binary ASN.1). - `JSX509Certificate` is the JS wrapper. Its `m_x509` field owns the BoringSSL `X509`. Every accessor assumes the field is set. - `fail()` marks the payload invalid. The deserializer then throws `Unable to deserialize data.` <details><summary>Notes</summary> **History.** This replaces oven-sh#33943. The stale-PR sweep closed it on 2026-09-13 because it had conflicts and a red CI run, not because of the change. oven-sh#33945 was an earlier duplicate. The fix is the same idea, redone on current main. The difference: the old PR kept the `size() == 0` branch and called `fail()` in it. This PR deletes the branch, so one decoder validates every record. **Duplicate.** oven-sh#43012 fixed the same crash and is closed in favor of this PR. It kept the `size() == 0` check and called `fail()` there. Two parts of it are folded in here: the private constructor (7de11cd) and the subprocess test that runs the real crash (41a0ecd). Its reachability probe and its `equals` findings are in the two sections below, run again for this PR. **Reproduction** (canary 1.4.3-canary.1+c6b7fcb5b, release, Linux x64): ```js import * as v8 from "node:v8"; // wire version 14, X509Certificate tag 253, u32 derLength = 0 const cert = v8.deserialize(Buffer.from([14, 0, 0, 0, 253, 0, 0, 0, 0])); console.log(Object.prototype.toString.call(cert)); // [object X509Certificate] cert.publicKey.equals(cert.publicKey); // Segmentation fault at address 0x10 ``` With this change the `v8.deserialize` line throws `TypeError: Unable to deserialize data.` Node.js rejects the same bytes at `deserialize`. **Reachability over IPC.** All three entry points use the same `CloneDeserializer`, so one reader change covers them. I checked the IPC path on the canary. The parent spawned plain `sh` with `serialization: "advanced"`. The child wrote one raw 14-byte frame to `$NODE_CHANNEL_FD`: type `2`, a `u32` length of 9, then the record. The parent's `message` handler received an `X509Certificate`, called `publicKey.equals`, and the parent exited 139. With this change the parent reports `TypeError: Unable to deserialize data.`, the same result the canary already gives for a record with an undecodable DER. **Crash 1, `publicKey.equals`.** `ncrypto::X509View::getPublicKey()` returns a successful `Result` that holds an empty `EVPKeyPointer` when the view is null. `JSX509Certificate::computePublicKey()` checks `!result` only, so it wraps the null key in a `JSPublicKeyObject`. `KeyObject::equals` hands it to `EVP_PKEY_cmp` (`KeyObject.cpp:913`). BoringSSL goes `EVP_PKEY_eq`, `EVP_PKEY_parameters_eq`, `EVP_PKEY_id`, and `EVP_PKEY_id` reads `impl->ameth` with no null check (`evp.cc:167`). The null key crashes on either side: `nullKey.equals(nullKey)`, `nullKey.equals(realKey)` and `realKey.equals(nullKey)` all stop at address 0x10. After this change a view is never null, so that path has no caller that can reach it. **Crash 2, `toLegacyObject`.** The method returns `nullptr` when the view is null. The host function encodes that as an empty `JSValue` and throws nothing. A script that ignores the result survives. `typeof result` reads the cell type byte at offset 5 of a null cell. **Accessor probe.** I ran each accessor of the certificate-less object in its own process on the canary. Two crash (above). `raw`, `fingerprint*`, `validFrom*`, `validTo*` and `serialNumber` throw `ERR_CRYPTO_OPERATION_FAILED`. `publicKey.export()` throws or returns an empty buffer. `v8.serialize(cert)` throws `DataCloneError`. The others return `undefined` or `false`. **`d2i_X509` on an empty buffer.** `buffer.begin()` is null for an empty `Vector`. BoringSSL's `D2IFromCBS` calls `CBS_init(&cbs, nullptr, 0)`, and `x509_parse` fails on its first `CBS_get_asn1`. Nothing reads through the pointer. `ClearErrorOnReturn` already sits above the call and clears the error queue. **Bytes after the DER.** `d2i_X509` accepts a valid certificate that has more bytes after it, and the reader does not compare `data` with `buffer.end()`. This PR leaves that as it is. The object is valid (`m_x509` is set, and `v8.serialize()` gives the canonical bytes again). `new X509Certificate(der + junk)` also succeeds in Bun and in Node.js v26.3.0. A strict check is a small follow-up if a maintainer wants it. **Other ways to get a null `m_x509`.** None found. `Bun__X509__toJS` takes `&mut X509` on the Rust side, so it never passes null. The JS constructor goes through `X509Pointer::Parse` and throws on failure. `m_x509` is still a public field, like the other members of the class, because the serializer reads it directly. So the private constructor stops a new cert-less cell, and the field itself is not guarded. **Other host-tag readers.** `readKeyObject()` validates the key type byte and calls `fail()` on every parse error. **Test design.** Six in-process tests cover both entry points with three DER shapes: empty, not a certificate, truncated. The helper reports only `Object.prototype.toString.call(value)` for a returned value. The unfixed build then fails with a short diff (`returned: "[object X509Certificate]"`), and the runner never inspects the broken object. The last test rebuilds a real certificate through the same `record()` helper and expects byte equality with `serialize()`, so the rejected payloads differ from a valid one only in the DER. The header and the tag byte come from that real `serialize()` call, so a wire version bump cannot turn the rejections into a test of the wrong record. One more test runs the crash input itself in a subprocess: the child deserializes the empty-DER record through both entry points and calls `publicKey.equals` on the result. On the canary the child dies with `SIGSEGV` (exit 139). With this change it prints the `deserialize` error twice and exits 0. The two malformed-DER cases and the round trip pass on the canary too. They pin the failure path that the empty DER now shares, and the record layout. **Suites run with the debug build:** `structured-clone.test.ts` (243 pass), `x509.test.ts` (33 pass), `x509-subclass.test.ts` (12 pass), `structuredClone-classes.test.ts` (57 pass). `bun-connect-x509.test.ts`: 2 pass. Its third test dials `example.com` and fails in this sandbox with `getaddrinfo EAI_AGAIN`. </details> <!-- robobun:evidence:begin --> --- **[human-review]** gate passed · iteration 6 · 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/web/workers/structured-clone.test.ts bun test v1.4.3 (c6b7fcb) test/js/web/workers/structured-clone.test.ts: (pass) structuredClone > primitive undefined [4.05ms] (pass) structuredClone > primitive null [0.52ms] (pass) structuredClone > primitive true [0.74ms] (pass) structuredClone > primitive false [0.35ms] (pass) structuredClone > primitive string, empty string [0.29ms] (pass) structuredClone > primitive string, lone high surrogate [0.28ms] (pass) structuredClone > primitive string, lone low surrogate [0.28ms] (pass) structuredClone > primitive string, NUL [0.29ms] (pass) structuredClone > primitive string, astral character [0.44ms] (pass) structuredClone > primitive number, 0.2 [0.33ms] (pass) structuredClone > primitive number, 0 [0.29ms] (pass) structuredClone > primitive number, -0 [0.30ms] (pass) structuredClone > primitive number, NaN [0.30ms] (pass) structuredClone > primitive number, Infinity [0.35ms] (pass) structuredClone > primitive number, -Infinity [0.59ms] (pass) structuredClone > primitive number, 9007199254 ... (truncated) release without fix: all passed bun test v1.4.3-canary.1 (8139779) test/js/web/workers/structured-clone.test.ts: (pass) structuredClone > primitive undefined [0.09ms] (pass) structuredClone > primitive null (pass) structuredClone > primitive true (pass) structuredClone > primitive false (pass) structuredClone > primitive string, empty string (pass) structuredClone > primitive string, lone high surrogate (pass) structuredClone > primitive string, lone low surrogate (pass) structuredClone > primitive string, NUL (pass) structuredClone > primitive string, astral character (pass) structuredClone > primitive number, 0.2 (pass) structuredClone > primitive number, 0 (pass) structuredClone > primitive number, -0 (pass) structuredClone > primitive number, NaN (pass) structuredClone > primitive number, Infinity (pass) structuredClone > primitive number, -Infinity (pass) structuredClone > primitive number, 9007199254740992 (pass) structuredClone > primitive number, -9007199254740992 [0.02ms] (pass) structuredClone > primitive number, 9007199254740994 (pass) structuredClone > primitive number, -9007199254740994 (pass) structuredClone > primitive BigInt, 0n (pass) structuredClone > primitive BigInt, -0n (pa ... (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/web/workers/structured-clone.test.ts bun test v1.4.3 (c6b7fcb) test/js/web/workers/structured-clone.test.ts: (pass) structuredClone > primitive undefined [4.65ms] (pass) structuredClone > primitive null [0.55ms] (pass) structuredClone > primitive true [0.74ms] (pass) structuredClone > primitive false [0.32ms] (pass) structuredClone > primitive string, empty string [0.27ms] (pass) structuredClone > primitive string, lone high surrogate [0.29ms] (pass) structuredClone > primitive string, lone low surrogate [0.29ms] (pass) structuredClone > primitive string, NUL [0.27ms] (pass) structuredClone > primitive string, astral character [0.40ms] (pass) structuredClone > primitive number, 0.2 [0.32ms] (pass) structuredClone > primitive number, 0 [0.30ms] (pass) structuredClone > primitive number, -0 [0.39ms] (pass) structuredClone > primitive number, NaN [0.31ms] (pass) structuredClone > primitive number, Infinity [0.31ms] (pass) structuredClone > primitive number, -Infinity [0.61ms] (pass) structuredClone > primitive number, 9007199254 ... (truncated) release with fix: all passed $ bun scripts/build.ts --profile=release [configured] bun-profile → bun (stripped) in 908ms (unchanged) ninja: Entering directory `/workspace/bun/build/release' [1/11] gen cpp.rs (cppbind) [1/11] 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 (/workspa ... (truncated) ``` </details> <details><summary>diff hotspot</summary> ``` src/jsc/bindings/JSX509Certificate.h | 13 ++-- src/jsc/bindings/webcore/SerializedScriptValue.cpp | 5 -- test/js/web/workers/structured-clone.test.ts | 83 ++++++++++++++++++++++ 3 files changed, 89 insertions(+), 12 deletions(-) ``` </details> **gate history** · 2 passed · 0 rejected · iteration 6 <details><summary>evidence per changed file</summary> ``` file reads edits tests src/jsc/bindings/JSX509Certificate.h 4 6 34 src/jsc/bindings/webcore/SerializedScriptValue.cpp 5 4 34 test/js/web/workers/structured-clone.test.ts 4 8 33 ``` </details> <!-- robobun:evidence:end -->
…ot (oven-sh#43179) ### Problem - `bun build` panics when a relative import joins to the filesystem root, for example `import "../.."` in `/tmp/app/entry.js`: `panic: unreachable`, top frame `Resolver::check_relative_path` (`src/resolver/resolver.rs:2064`). - Before the "browser" map lookup, `check_relative_path` takes the parent of the joined path with `bun_paths::dirname(abs_path).expect("unreachable")`. The root has no parent, so `dirname("/")` is `None`. - Only a build that reads the "browser" field reaches this line (`--target=browser`, the default). `--target=bun`, the runtime, and an absolute `import "/"` report `Could not resolve`. ### Fix - When `dirname` returns `None`, use the root itself as the directory. esbuild does the same: Go's `filepath.Dir("/")` is `"/"`. - Correct because the lookup needs the directory whose `package.json` scope applies, and for the root that is the root. Resolution then continues to `load_as_file_or_directory`, which reports `Could not resolve`. - Verified: new test in `test/js/bun/resolve/resolve.test.ts`. Release 1.4.3-canary fails it with `panic: unreachable`. Also ran all of `resolve.test.ts`, `bundler_browser.test.ts` and `esbuild/packagejson.test.ts`. ### Background - The "browser" field of a `package.json` maps files and packages to browser replacements. The resolver checks it for each import of a browser build. - `check_relative_path` joins the importer's directory and the specifier. The join collapses `..` segments, and enough of them give `/` (or `C:\`). - `bun_paths::dirname` returns `None` for a root and for a path with no separator. The joined path is absolute, so the root is the only `None` case here. <details><summary>Notes</summary> - A fuzzer found this (ledger row 16184). No user reported it. - Not a regression: the Zig resolver had `orelse unreachable` on the same line, so the test is in the module's test file and not in `test/regression/issue/`. - Other shapes reached the same panic and now report `Could not resolve`: `require("../..")`, `import("../../")`, `require.resolve("../../.")`, CSS `@import "../.."` and `url(../..)`. - Manual check with a `/package.json` that has `"browser": {"./index.js": "./browser.js"}` next to a `/index.js`: `import "../.."` bundles `/browser.js`. The "browser" map of a root package still applies through the main-file lookup. - The test uses 64 `../` segments, so the specifier names the root from a temp directory of any depth, on POSIX and on Windows. - Repro: ```console $ mkdir -p /tmp/app && cd /tmp/app && echo 'import "../..";' > entry.js $ bun build entry.js --outdir=out panic: unreachable ``` With this change: ```console $ bun build entry.js --outdir=out 1 | import "../.."; ^ error: Could not resolve: "../.." at /tmp/app/entry.js:1:8 ``` </details> <!-- robobun:evidence:begin --> --- **no test proof** · iteration 2 · platform-specific test(s) that do not run on this machine, deferring to CI, which covers all platforms: test/js/bun/resolve/resolve.test.ts <!-- robobun:evidence:end -->
… above 4 GiB (oven-sh#37243) ### Problem - `await (await fetch(url)).arrayBuffer()` or `.bytes()` aborts the process when the body exceeds 2^32 bytes. A 4 MiB gzip response is enough. Debug builds print `ASSERTION FAILED: m_sizeInBytes <= (1ull << 32)` in `JSC::ArrayBufferContents::ArrayBufferContents`. `text()` rejects. - A `Response` string body with more than 2^32 bytes of utf8 aborts the same way. - Cause: `JSArrayBuffer__fromDefaultAllocator` and `JSUint8Array__fromDefaultAllocator` (`src/jsc/bindings/Uint8Array.cpp`) call `ArrayBuffer::createFromBytes`, which asserts above `MAX_ARRAY_BUFFER_SIZE`. ### Fix - Both functions first call `Bun::rejectBytesNoCopyAboveArrayBufferLimit`. It frees the bytes and throws the `RangeError: Out of memory` that `new ArrayBuffer(2 ** 32 + 1)` throws. oven-sh#39558 and oven-sh#39564 added it to the other four adopting functions. - `ArrayBuffer::from_default_allocator` wraps its `ArrayBuffer` arm in `call_zero_is_throw`, so callers get an `Err`. - Verified: `test/js/web/fetch/blob-oom.test.ts` (three new cases). Without the fix, every child dies with SIGABRT. The whole file passes. ### Background - JSC caps an `ArrayBuffer` at 2^32 bytes. Constructors that allocate throw above it. `createFromBytes` adopts bytes the caller owns, and asserts. - A natively buffered body reaches JSC through `Any::to_array_buffer_view` (`Blob.rs`) and `from_default_allocator`, without a copy. - Considered a check in each Rust caller, and a utf8 length pre-scan. The first misses the next caller. The second adds a pass over the input. ### Downsides - Per adopted buffer: +1 length comparison and +1 exception check. No allocation, no pass over the bytes. Text: +144 bytes before LTO (no `bloaty`, method in Notes). - A body above 4 GiB is still buffered in full before the rejection. - The two fetch cases cost about 15 s each under ASAN. The string case is release-only (7 s). <details><summary>Notes</summary> **Who reaches the two functions.** Every caller of `ArrayBuffer::from_default_allocator` and `JSUint8Array::from_bytes`: - `Any::to_array_buffer_view`, `InternalBlob` arm: a fetch response (read while it streams, or after it is buffered), a `Bun.serve` request body when `maxRequestBodySize` allows more than 4 GiB, a native stream read through `new Response(stream)` or `Bun.readableStreamToArrayBuffer` / `ToBytes`, HTMLRewriter output. - The same function, `WTFStringImpl` arm: a string body whose utf8 encoding is owned (not ASCII). - `TextEncoderStream` chunks. For fetch the path is `FetchTasklet::on_body_received` -> `Body::Value::resolve` -> `AnyBlob::to_array_buffer_transfer` / `to_uint8_array_transfer` -> `Any::to_array_buffer_view` -> `from_default_allocator`. **Repro for the fetch case** (about 7 GiB of free memory). On bun 1.4.3 and on main it exits 134. With this PR it prints the RangeError. `text()` rejects with `ERR_STRING_TOO_LONG` and `blob()` resolves with 4362076160 bytes, before and after. ```js const member = Bun.gzipSync(Buffer.alloc(64 * 1024 * 1024)); const body = Buffer.concat(Array(65).fill(member)); // 4 MiB, inflates to 2^32 + 64 MiB const server = Bun.serve({ port: 0, fetch: () => new Response(body, { headers: { "Content-Encoding": "gzip" } }) }); await (await fetch(server.url)).arrayBuffer(); ``` **Repro for the string case.** `await new Response("\u20ac".repeat(1431655766)).arrayBuffer()` (3 utf8 bytes per character, 2^32 + 2 bytes). It aborts on main and on 1.4.3, and rejects with the RangeError here, for `arrayBuffer()` and `bytes()`. It is a test, for release builds only: one call takes 28 s in a debug ASAN build (65 s for the case) and about 2 s in a release build (7 s for the case). **The tests.** One fetch case per guarded function, at exactly 2^32 + 1 bytes. The body is 64 gzip members of 64 MiB of zeros and one member of a single byte, so the child builds it in 0.3 s (`Bun.gzipSync` once per member size) where a streamed level 9 gzip of 4 GiB takes 70 s in a debug build. If fetch ever stops at the first gzip member, the call resolves and the test fails on `unexpectedByteLength`. Measured here under ASAN: 15 s to 18 s per case, 6.6 GiB to 8.8 GiB of peak RSS, so the cases stay out of the concurrent batch and use the same 10 GiB gate as the 4 GiB file cases. In a release build a case takes about 11 s and 4.5 GiB to 6.1 GiB. **The boundary.** The comparison is in `rejectBytesNoCopyAboveArrayBufferLimit`, and the two functions only call it. The file cases already pin both sides of that comparison (exactly 2^32 bytes is returned whole, 2^32 + 1 rejects). Through fetch, by hand with this build: a body of exactly 2^32 bytes resolves from `arrayBuffer()` and from `bytes()` with `byteLength` 4294967296, and 2^32 + 1 rejects from both. The at-limit side is not a test here. Each case is one more 4 GiB transfer (11 s in release, 16 s under ASAN, up to 9 GiB of RSS) on a shared agent. **Size number.** `ninja -C build/release obj/unified/UnifiedSource-src_jsc_bindings-4.cpp.o` with this PR's and main's `Uint8Array.cpp`, each lowered with `clang++ -O3 -c -x ir`: text 162942 against 162798. The two functions grow from 387 to 480 bytes and from 442 to 488 bytes. **The other callers of `createFromBytes` / `createAdopted`.** - Guarded by the helper already: `Bun__makeArrayBufferWithBytesNoCopy`, `Bun__makeTypedArrayWithBytesNoCopy`, `JSBuffer__bufferFromPointerAndLengthAndDeinit`, `JSBuffer__fromMmap`. `ArrayBuffer__fromSharedMemfd` has its own length check. - Cannot reach the cap: `BunObject.cpp` (heap snapshot as `arraybuffer`) and `SerializedScriptValue::toArrayBuffer` pass a `WTF::Vector<uint8_t>`, whose capacity is 31 bits. `DirectByteBuffer::tryGrowTo` refuses to grow above `MAX_ARRAY_BUFFER_SIZE`. `JSX509Certificate.cpp` passes the DER bytes of one certificate. - Still unguarded, not in this PR: `napi.cpp` (external arraybuffer and buffer, the length comes from the addon) and `NodeSqlite.cpp` (`adoptSqliteBuffer`, a `serialize()` above 4 GiB). The helper frees the bytes before it throws, which is wrong for napi, where the caller keeps ownership on failure. Those two need their own error contract and are tracked separately. **Earlier shapes of this PR.** The first version checked the size at three Rust and C++ call sites, before the shared helper existed. A later one also computed the utf8 length of a string ahead of encoding, which was removed at review because it is an extra pass over the input. Rebases over oven-sh#39558, oven-sh#39564, oven-sh#40410 and oven-sh#40962 moved the Rust plumbing and the test helpers to main, so the PR is now the guard in `Uint8Array.cpp`, one wrapped arm in `array_buffer.rs`, and the tests. The last rebase conflict was in `blob-oom.test.ts` only (oven-sh#40962 rewrote its helpers). The new cases use those helpers. </details> <!-- robobun:evidence:begin --> --- **no test proof** · iteration 5 · platform-specific test(s) that do not run on this machine, deferring to CI, which covers all platforms: test/js/web/fetch/blob-oom.test.ts <!-- robobun:evidence:end -->
…ven-sh#30623) Fixes oven-sh#30621 ## Repro ```css /* style.css */ a{background:url(data:)} ``` ```sh bun build style.css --outdir out # panic: index out of bounds: the len is 0 but the index is 0 # bun_bundler::linker_context_mod::LinkerContext::create_exports_for_file # src/bundler/linker_context/doStep5.rs:659 ``` Also reproduces with `<link rel="icon" href="data:">` in an HTML entry point and `import "data:"` in JS. ## Cause `url(data:)` is a malformed data URL (no comma, which `DataURL::parse` requires). The resolver returns `ResultUnion::Failure(InvalidDataURL)` without touching any log. `resolve_import_records` only records that in `last_error` (its non-`ModuleNotFound` arm is commented "assume other errors are already in the log", which is not true here), `run_resolution_for_parse_task` converts the parse result to `Err` with an empty log, and `on_parse_task_complete` skips logging because `process_log` is cleared. With `transpiler.log.errors == 0` the build proceeds past the `has_errors()` gate, the importer's AST slot stays at the empty placeholder (`parts.len() == 0`), and `create_exports_for_file` indexes `parts[NAMESPACE_EXPORT_PART_INDEX]`. ## Fix `src/resolver/resolver.rs`: when `DataURL::parse` fails and the import is a `url()`-kind (CSS `url()`/`@import`, HTML asset attributes, all of which share `ImportKind::is_from_css()`), mark the URL external and pass it through verbatim, matching the adjacent handling of `http://`, `https://`, and `//`. `src/bundler/bundle_v2.rs`: a new `log_unhandled_resolve_error` helper formats the diagnostic for resolver errors the resolver does not log itself. `run_resolver` (plugin fallback) and `resolve_import_records` (main path) both route their non-`ModuleNotFound` arm through it, so `import "data:"` in JS now reports `Could not resolve data URL: "data:"` and aborts before linking. `HANDLES_IMPORT_ERRORS` is honoured the same way it is for `ModuleNotFound`. ## Tests `test/regression/issue/30621.test.ts` spawns `bun build` for four cases: CSS entry with `url(data:)`, HTML entry with `<link rel="icon" href="data:">`, JS entry importing that CSS, and `import "data:"` in JS. All four crash with the panic above on an unfixed build and pass with the fix. `test/js/bun/resolve/resolve-error.test.ts`, `test/bundler/bundler_edgecase.test.ts`, `test/bundler/esbuild/css.test.ts`, and `test/bundler/esbuild/loader.test.ts` still pass. <!-- robobun:evidence:begin --> --- **[review]** gate passed · iteration 10 · 3 files touched <details><summary>fails on main (without fix)</summary> ```console ASAN without fix: 4 FAILED $ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/mechgate.xml" "test/regression/issue/30621.test.ts" info: syncing channel updates for nightly-2026-05-06-x86_64-unknown-linux-gnu info: latest update on 2026-05-06 for version 1.97.0-nightly (e95e73209 2026-05-05) info: component rust-src is up to date info: checking for self-update (current version: 1.29.0) bun test v1.4.0 (2147fd9) test/regression/issue/30621.test.ts: (fail) CSS url(data:) with no comma should not crash [5007.56ms] ^ this test timed out after 5000ms. (fail) HTML favicon href=data: with no comma should not crash [5007.78ms] ^ this test timed out after 5000ms. (fail) JS importing CSS with url(data:) should not crash [5000.17ms] ^ this test timed out after 5000ms. (fail) JS import of malformed data URL reports a resolve error [5000.20ms] ^ this test timed out after 5000ms. 0 pass 4 fail Ran 4 tests across 1 file. [7.22s] error: script "bd" exited with code 1 __F:4:S:0 release without fix: 4 FAILED bun test v1.4.0-canary.1 (1498d7b) test/regression/issue/30621.test.ts: 51 | test.concurrent("JS import of malformed data URL reports a resolve error", async () => { 52 | using dir = tempDir("30621-js", { 53 | "index.js": `import "data:";`, 54 | }); 55 | const { stderr, exitCode } = await build(String(dir), "index.js"); 56 | expect(stderr).toContain(`Could not resolve data URL: "data:"`); ^ error: expect(received).toContain(expected) Expected to contain: "Could not resolve data URL: \"data:\"" Received: "============================================================\nBun Canary v1.4.0-canary.1 (1498d7b) Linux x64\nLinux Kernel v6.17.0 | glibc v2.41\nCPU: sse42 popcnt avx avx2 avx512\nArgs: \"/workspace/bun/build/release/bun\" \"build\" \"index.js\" \"--outdir=out\"\n\nElapsed: 3ms | User: 0ms | Sys: 4ms\nRSS: 46.73 MB | Peak: 50.81 MB | Commit: 46.73 MB | Faults: 0\n\npanic: index out of bounds: the len is 0 but the index is 0\noh no: Bun has crashed. This indicates a bug in Bun, not your code.\n\nTo send a redacted crash report to Bun's team,\nplease file a GitHub issue using the link below:\n\n https://bun.report/1.4.0/l_21498 ... (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/mechgate.xml" "test/regression/issue/30621.test.ts" info: syncing channel updates for nightly-2026-05-06-x86_64-unknown-linux-gnu info: latest update on 2026-05-06 for version 1.97.0-nightly (e95e73209 2026-05-05) info: component rust-src is up to date info: checking for self-update (current version: 1.29.0) bun test v1.4.0 (2147fd9) test/regression/issue/30621.test.ts: (pass) JS import of malformed data URL reports a resolve error [210.90ms] (pass) HTML favicon href=data: with no comma should not crash [295.25ms] (pass) CSS url(data:) with no comma should not crash [400.19ms] (pass) JS importing CSS with url(data:) should not crash [340.86ms] 4 pass 0 fail 10 expect() calls Ran 4 tests across 1 file. [2.52s] __F:0:S:0 release with fix: all passed $ bun scripts/build.ts --profile=release info: syncing channel updates for nightly-2026-05-06-x86_64-unknown-linux-gnu info: latest update on 2026-05-06 for version 1.97.0-nightly (e95e73209 2026-05-05) info: component rust-src is up to date info: checking for self-update (current version: 1.29.0) [configured] bun-profile → bun (stripped) target linux-x64-gnu build type Release build dir ./build/release revision 2147fd9 features (none) 22 deps, 106 codegen, 1168 objects in 822ms ninja: Entering directory `/workspace/bun/build/release' [1/1231] install /workspace/bun bun install v1.4.0-canary.1 (1498d7b) Checked 124 installs across 170 packages (no changes) [12.00ms] [2/1231] install /workspace/bun/packages/bun-error bun install v1.4.0-canary.1 (1498d7b) Checked 1 install across 2 packages (no changes) [2.00ms] [3/1231] gen bindgenv2 [4/1231] fetch libjpeg-turbo [libjpeg-turbo] up to date [5/1231] gen ErrorCode+*.h [6/1231] install /workspace/bun/src/node-fallbacks bun install v1.4.0-canary.1 (1498d7b) Checked 129 installs across 147 packages (no changes) [7.00ms] [7/1231] gen ProcessBindingConstants.lut.h Generating /work ... (truncated) ``` </details> <details><summary>diff hotspot</summary> ``` src/bundler/bundle_v2.rs | 63 +++++++++++++++++++++++++++++++++++-- src/resolver/resolver.rs | 20 ++++++++++++ test/regression/issue/30621.test.ts | 58 ++++++++++++++++++++++++++++++++++ 3 files changed, 138 insertions(+), 3 deletions(-) ``` </details> **gate history** · 2 passed · 0 rejected · iteration 10 <details><summary>evidence per changed file</summary> ``` file reads edits tests src/bundler/bundle_v2.rs 1 2 8 src/resolver/resolver.rs 1 1 8 test/regression/issue/30621.test.ts 0 2 8 ``` </details> **root cause** · written by the author bot The crash happened because the resolver treated any string starting with "data:" as a valid data URL and immediately indexed into its parsed components, so a malformed URL like url(data:) with no media type or payload produced an empty component list and an out-of-bounds access. The fix makes the resolver return a dedicated InvalidDataURL error for malformed data URLs instead of assuming parsing succeeded, and the bundler now handles that error by logging a normal "Could not resolve data URL" resolve diagnostic through the same import-error gating as other resolution failures. As a result, … <!-- robobun:evidence:end -->
oven-sh#34732) ### Problem - `write_bind` (`src/sql_jsc/postgres/PostgresRequest.rs:52`) writes into `connection.write_buffer` and calls JS per parameter. When a parameter fails (a throwing `toString`, since oven-sh#41889 a bad `bytea` value), the query rejects but the partial Bind stays: `42 00 00 00 00` (length 0). - The next flush sends it, even with nothing queued: `P D S B(len=0)`, or `P D B(len=0)` with `prepare: false`. PostgreSQL drops the connection. The next query, pipelined siblings and open transactions get `ERR_POSTGRES_CONNECTION_CLOSED`. ### Fix - `NewWriter::atomically` records `offset()`, runs the body, and truncates back on failure. It wraps the three batch writers that reach `write_bind`: a rejected query writes nothing. - It truncates only when `write_epoch` is unchanged. The connection bumps it for every `Writer` it hands out and every drain or free of `write_buffer`. A conversion that starts a query with `.execute()` changes it, and the connection then fails as on main. - `Writer::pwrite` now adds `head` (the bytes already sent) to the index, like `offset()`. - Verified: `postgres-bind-encode-throw.test.ts`, `postgres-bytea-bind.test.ts` (unfixed main fails 4/5 and 6/12). Other suites: Notes. ### Background - `prepare: false` writes Parse, Describe, Bind, Execute, Flush, Sync as one batch, so the rollback drops them too. - This is the interim fix for 1.4.3. The follow-up converts every parameter before the first write, so no rollback is needed. ### Downsides - Success path, per batch: two reads and one branch. Per `Writer`: one increment. Per length patch: one add. - A conversion that dispatches a query and then fails still loses the connection, as on main. Without the failure both hang (oven-sh#38231). The follow-up fixes both. <details><summary>Notes</summary> **Wire captures on unfixed main (367d939), byte-capturing mock server.** Each line is the list of frontend messages after the startup packet. - Lone rejected query, named statement: `P D S B(len=0)`. The bytes: `42 00 00 00 00 00 50 73 65 6c 65 63 74 ...` (Bind, length 0, empty portal name, then the statement name). - Lone rejected query, `prepare: false`: `P D B(len=0)`. The bytes: `42 00 00 00 00 00 00 00 02 00 00 00 00 00 02 00 00 00 01 61`. The Parse and Describe have no Sync behind them. - Nothing is queued behind the rejected query in both captures. The auto-flusher sends the buffer at the end of the tick. - With the fix: the named case sends `P D S` and no Bind. The `prepare: false` case sends nothing for the rejected query. **Paths covered by the tests.** - `bind_and_execute` from `advance` (the Bind follows the statement's Parse/Describe round trip): both files, real server and mock. - `bind_and_execute` from `run` (statement already prepared, Bind written at query time): `postgres-bytea-bind.test.ts` runs each rejected query twice. The second run takes this path. - `parse_and_bind_and_execute` (`prepare: false`): real server with a queued sibling, real server with a lone query and a backend pid check, and the mock that asserts the exact message list. - `prepare_and_query_with_signature` has no parameters, so no parameter can throw there. It is wrapped for the `TooManyParameters` path. - The bytea case (oven-sh#41889): a `number[]` bound to `bytea` rejects with `ERR_INVALID_ARG_TYPE`. On unfixed main the next query, the pipelined siblings and the open transaction then fail with `ERR_POSTGRES_CONNECTION_CLOSED`. **The mock server** in `postgres-bind-encode-throw.test.ts` drops the connection when it reads a length below 4, as PostgreSQL does. On unfixed main the mock tests fail at once with `["B(len=0)"]`. They do not wait for a timeout. **Nested dispatch from inside a conversion (found in review, confirmed on a real PostgreSQL).** `query.execute()` calls into the connection synchronously (`await`/`.then()` defer by one microtask and are not affected). When a parameter's `toString` creates a query for a prepared statement on the same connection and calls `.execute()` on it, the nested query writes its Bind/Execute/Sync inside the outer query's open Bind. - Conversion does not throw, main and this PR: the outer query never settles, the nested one rejects with `08P01 insufficient data left in message`, and later queries on the connection hang. oven-sh#38231 is the open fix. - Conversion throws after the nested dispatch, main and this PR: `B(len=0)` goes out, the server drops the connection, the nested query rejects with `ERR_POSTGRES_CONNECTION_CLOSED`, the pool reconnects and the next query resolves. - An earlier head of this PR (9812be4) rolled back without the `write_epoch` check. It removed the nested query's frames too: the nested query hung, or a later query's row resolved it (`nested: resolved [{"nested":"LATER-VALUE"}]`). The test `a query dispatched from inside a conversion that then fails never gets another query's row` times out on that head and passes now. - Checked 5 cells against main on a real server (outer statement already prepared or on its first execution, nested query prepared, new, simple, or `unsafe` with parameters): the outcomes are the same as on main in every cell. A sixth cell (first execution, nested new statement) aborts the debug build with `panic: pending_requests underflow`, a debug assertion that this diff does not touch. The release build of main has no panic in that cell. **`head` in `pwrite` and `truncate`.** `offset()` is relative to `head`, so both now add `head`. No test reaches `head != 0` during a write, and the public API does not reach it without a flush from inside a conversion. `OffsetByteList::consume` leaves `head > 0` only when a socket write accepted less than half of the pending bytes. That write sets `HAS_BACKPRESSURE`. Under backpressure `advance()` does not run its loop, and every write gate in `do_run` needs `!has_query_running()` or `can_pipeline()`, which are both false while a request with pending bytes is in the queue. A flush from inside a conversion bumps `write_epoch`, so no rollback follows it. **Follow-up.** A design review of six candidates picked a different long-term shape: convert every parameter before the first byte of the batch is written (no user code runs while a frame is open), plus a guard so that a query dispatched during a conversion only enqueues. It is planned as three PRs. This PR is the interim fix. See oven-sh#34732 (comment). **Suites run with the debug build:** the `test/js/sql/postgres-*.test.ts` files, `sql-prepare-false.test.ts`, `sql-pool-transaction-isolation.test.ts`, `wire-frames.test.ts` and `sql.test.ts` (29 files): 236 of 236 tests pass, with `postgres-string-leak.test.ts` run apart. The two tests in `postgres-string-leak.test.ts` time out at the default 5 s in this environment: the fixture alone takes 8.6 s under the debug ASAN build here (0.46 s under release). Its RSS delta is 9.65 MiB, inside the test's 80 MiB bound. **History.** The July version of this PR had the same design. It was refreshed on current main after the `ArrayList` writer context was removed. The test file `postgres-bind-throw-torn-frame.test.ts` was replaced by `postgres-bind-encode-throw.test.ts`. The head now also carries the `postgres-bytea-bind.test.ts` additions from the branch `robobun/44cd9150/postgres-bind-rollback`. MySQL is not affected. `bind_and_execute_impl` converts every parameter to a native `Vec<Value>` before it touches the writer. </details> <!-- robobun:evidence:begin --> --- **[human-review]** gate passed · iteration 2 · 4 files touched <details><summary>fails on main (without fix)</summary> ```console ASAN without fix: 3 FAILED $ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/pr_gate.xml" test/js/sql/postgres-bind-encode-throw.test.ts bun test v1.4.3 (f42e980) test/js/sql/postgres-bind-encode-throw.test.ts: Container ready via docker-compose: postgres_plain at 127.0.0.1:5432 204 | return `{${values.map(arrayValueSerializer.bind(this, type, isPostgresNumericType(type), isPostgresJsonType(type))).join(delimiter)}}`; 205 | } 206 | function wrapPostgresError(error) { 207 | if (Error.isError(error)) { 208 | return error; 209 | return new PostgresError(error.message, error); ^ PostgresError: Connection closed code: "ERR_POSTGRES_CONNECTION_CLOSED" at wrapPostgresError (internal:sql/postgres:209:10) at handleClose (internal:sql/shared:463:27) (fail) postgres > a parameter that throws while encoded does not break the queries pipelined behind it [308.18ms] 204 | return `{${values.map(arrayValueSerializer.bind(this, type, isPostgresNumericType(type), isPostgresJsonType(type))).join(delimiter)}}`; 205 | } 206 | function wrapPostgresError(error) { 207 | if (Error.isError(error)) { 208 | ... (truncated) release without fix: 3 FAILED bun test v1.4.3-canary.1 (f42e980) test/js/sql/postgres-bind-encode-throw.test.ts: Container ready via docker-compose: postgres_plain at 127.0.0.1:5432 171 | let delimiter = type === "BOX" ? ";" : ","; 172 | return `{${values.map(arrayValueSerializer.bind(this, type, isPostgresNumericType(type), isPostgresJsonType(type))).join(delimiter)}}`; 173 | } 174 | function wrapPostgresError(error) { 175 | if (Error.isError(error)) 176 | return new PostgresError(error.message, error); ^ PostgresError: Connection closed code: "ERR_POSTGRES_CONNECTION_CLOSED" at wrapPostgresError (internal:sql/postgres:176:10) at handleClose (internal:sql/shared:372:27) (fail) postgres > a parameter that throws while encoded does not break the queries pipelined behind it [13.17ms] 171 | let delimiter = type === "BOX" ? ";" : ","; 172 | return `{${values.map(arrayValueSerializer.bind(this, type, isPostgresNumericType(type), isPostgresJsonType(type))).join(delimiter)}}`; 173 | } 174 | function wrapPostgresError(error) { 175 | if (Error.isError(error)) 176 | return new PostgresError(error.message, error); ^ PostgresError: Connection cl ... (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 bun test v1.4.3 (f42e980) test/js/sql/postgres-bind-encode-throw.test.ts: Container ready via docker-compose: postgres_plain at 127.0.0.1:5432 (pass) postgres > a parameter that throws while encoded does not break the queries pipelined behind it [297.21ms] (pass) postgres > a throwing parameter on the first execution of a statement does not break the next query [38.94ms] (pass) postgres bind encode failure (mock server) > no partial Bind reaches the wire when a parameter throws [368.75ms] 3 pass 0 fail 6 expect() calls Ran 3 tests across 1 file. [3.42s] __F:0:S:0 release with fix: all passed $ bun scripts/build.ts --profile=release [configured] bun-profile → bun (stripped) in 771ms (unchanged) ninja: Entering directory `/workspace/bun/build/release' [1/38] gen generated_host_exports.rs generated_host_exports.rs: 122 exports (host=5, lazy=10, generic=107, rust=0); 242 extern-C blocks audited [2/38] 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 ... (truncated) ``` </details> <details><summary>diff hotspot</summary> ``` src/sql/postgres/protocol/NewWriter.rs | 15 ++ src/sql_jsc/postgres/PostgresRequest.rs | 192 +++++++++++++------------ src/sql_jsc/postgres/PostgresSQLConnection.rs | 12 ++ test/js/sql/postgres-bind-encode-throw.test.ts | 182 +++++++++++++++++++++++ 4 files changed, 308 insertions(+), 93 deletions(-) ``` </details> **gate history** · 2 passed · 0 rejected · iteration 2 <details><summary>evidence per changed file</summary> ``` file reads edits tests src/sql/postgres/protocol/NewWriter.rs 2 4 0 src/sql_jsc/postgres/PostgresRequest.rs 2 3 1 src/sql_jsc/postgres/PostgresSQLConnection.rs 2 1 0 test/js/sql/postgres-bind-encode-throw.test.ts 0 0 0 ``` </details> <!-- robobun:evidence:end -->
…with nothing sent (oven-sh#43898) ### Problem - Regression from oven-sh#34732 (73df7bb). With `prepare: false`, a script whose last query is rejected while a parameter is encoded never exits, when that query runs from a later tick than the last reply (in a timer, in a request handler). - `PostgresSQLQuery::do_run` takes the connection's event loop ref when it enqueues the request, then calls `advance_and_flush()`. With `prepare: false` the batch is encoded inside that `advance()`. Since oven-sh#34732 a failed encode leaves nothing to send, so no reply arrives, and only the idle check at the end of `on_data` releases the ref. Before oven-sh#34732 the server's close released it. ### Fix - The idle check of `on_data` moves to `PostgresSQLConnection::update_poll_ref()`: unref when the connection is connected, nothing is in flight and the write buffer is empty, else ref. - `do_run` calls it after `advance_and_flush()`. - Verified: new test `a script whose last query was rejected exits on its own` in `postgres-bind-encode-throw.test.ts`. Without the fix the `prepare: false` case times out. Also the `test/js/sql/postgres-*` files, `sql-prepare-false`, `sql-pool-transaction-isolation`, `wire-frames`, `sql.test.ts`: 238 tests pass. ### Background - `poll_ref` is a `KeepAlive`: while it is active, the process does not exit. A connection holds it only while a query is in flight, so an idle pool does not keep a script alive. - Named statements do not hit this. Their Bind is encoded from `on_data`, or in `do_run` before the ref is taken. ### Downsides - Per `do_run` that did not write (`prepare: false` with parameters, or a busy connection): one more idle check (4 flag and field reads). No allocation, no syscall.
…UT, bytecodeOrderStats()) (oven-sh#43811) ### What does this PR do? A `--compile --bytecode` executable maps its bytecode from disk and decodes functions lazily, so the pages it touches at startup are scattered over the whole payload: a large application keeps most of its bytecode resident after reading a small part of it. This adds order files: ```sh bun build --compile --bytecode ./app.ts --outfile myapp BUN_BYTECODE_ORDER_OUT=./myapp.order ./myapp # record what a run reads; written at exit (%p = pid) bun build --compile --bytecode --bytecode-order=./myapp.order ./app.ts --outfile myapp ``` also `Bun.build({ compile: { bytecodeOrder: string | string[] | false | null } })` (`false`, `null`, `[]` = none; several files are merged, first file first). There is no environment variable for consuming one. Requires oven-sh/WebKit#718. How it works - Order file: text, `v2`, then `F <hash>` function decoded to be run, `S` string read (both in first-use order), `M` module evaluated, `N` module present and not evaluated, `K` function present and not run. No source in it. A byte order mark and blank or `#` lines before the version line are skipped; malformed lines are ignored; a missing file is a build error; an unusable one (other version, UTF-16, lists nothing, none of its functions in the build) is a warning that says why. - Names are computed by Bun, not JavaScriptCore: `src/js_parser/function_identities.rs` parses the PRINTED chunk (parse only, no visit) and hashes each function's syntax. Locals, labels and private names are numbered by declaration, captured bindings by frame depth and index, module-level bindings by first mention, so minifier renames do not matter; property names and numbers count; the property a function is the value of is part of its name (`{ a: () => a, b: () => b }` are two); string VALUES and the paths chunks import each other by are left out (they change with every build); a nested function contributes its own name; a default constructor is named by its class's members; what is nested deeper than a fixed count in ONE function is a fixed tag. Nested functions are walked from a worklist, so nesting depth costs no stack. The parser records the three starts JavaScriptCore uses that are not AST locations (async arrow parameters, class element, expression body). - The same walker runs in the build (names handed to `JSC::BytecodeLinkEncoder` as `(start, kind) → name` tables) and in the recording run at exit (JavaScriptCore reports raw `(payload, entry offset, start, kind)` events; Bun names the text the executable embeds). Taking the recording ends it, so `BUN_BYTECODE_DIGEST_OUT`'s decode-everything pass is not recorded. A module whose bytecode the runtime rejected is listed neither as evaluated nor as not. A text that does not parse gets no names, with a warning; the file is written through temp + rename. - With an order file the linker writes ONE payload in regions: heads of evaluated modules · HOT · UNKNOWN (new or changed since the recording) · heads of never-evaluated modules · COLD · expression info; startup read-ahead covers the front through HOT. Internal modules are modules of the link too. `bytecodeOrderStats()` in `bun:jsc` returns decodes per region and region sizes (`null` without an ordered payload). - Without an order file the build path is the old one and the executable's module graph is byte-identical. Measured on a large compiled TUI application (≈2,000 chunks, ≈142k functions, 82 MB of bytecode), linux x64, 64 KB fault-around, n=3, MB of the embedded payload resident: | | at its idle prompt | after one interaction | decodes after the interaction (hot / unknown / cold) | |---|---|---|---| | no order file | 59.5 | 62.3 | | | order file from the same build | **20.5** (20.0–21.1) | **25.9** | 18,274 / 0 / 12 | | order file from the previous day's build | **23.2** (23.0–23.4) | **28.1** | 18,085 / 171 / 28 | Two merged entry points were measured with the previous naming scheme only (21.0 / 26.3; the second entry point 61.8 → 25.6 MB). Cold start to the first prompt (page cache dropped for the executable only, n=6 interleaved, final binary; median [min–max]): | | first prompt | major faults | read from disk | RssFile at the prompt | |---|---|---|---|---| | main | 1.01 s [0.96–1.12] | 598 | 76 MB | 105 MB | | no order file | 0.99 s [0.97–1.16] | 606 | 76 MB | 104 MB | | order file from the same build | **0.53 s** [0.48–0.57] | 185 | 22 MB | 65 MB | | order file from the previous day's build | **0.55 s** [0.52–0.68] | 202 | 24 MB | 68 MB | Warm start: main-thread instructions equal to main (1212 M vs 1208 M, n=5). A recording run's exit: 0.011 s → 0.25 s. The application's full build, n=3 interleaved on a shared box (load average 45–64 of 64 cores), final binary: | | wall | user CPU | peak RSS | |---|---|---|---| | main | 2:49 2:44 2:38 | 168–173 s | 4.93 GB | | no order file | 2:47 2:44 2:40 | 170–175 s | 4.89 GB | | with the same-build order file | 2:53 2:43 2:44 | 174–182 s | 5.37 GB | Wall time is unchanged (median 2:44 in all three); an order file costs about 3 s of CPU (naming on up to 8 threads, placement) and +0.47 GB peak RSS, because unlinked code stays alive until the payload is written. Normal parses pay three `Option` branches for the recorded starts. The recording lists 16,971 run and 104,894 not-run functions, no function without a name. ### How did you verify your code works? - No order file: executables byte-identical across builds (byte-identical to a build from main was checked earlier on this branch, on the large application and a 360-module test app); same order file: byte-identical executables. - `BUN_BYTECODE_DIGEST_OUT` (decode ALL embedded bytecode, one digest per module): unordered == same-build order file == day-old order file on the large application (2,104 modules, 149,415 code blocks, 0 undecodable), and in the tests. - Round trips (build → record → rebuild → run): an all-syntax fixture that runs every kind of function JavaScriptCore compiles (hashbang, non-ASCII banner, a JSON chunk without bytecode): 0 unknown, 0 cold, no unnamed function; sloppy CommonJS; `Bun.ModuleGraph` modules; a build whose SHARED chunk is edited between recording and layout: a second recording shows exactly one function and one module renamed; typescript.js (21.5k functions): 1,541 hot / 0 unknown / 0 cold; rejected bytecode (patched executable, Linux). - The invariant "build and run derive identical names from identical inputs": every round trip sets `BUN_BYTECODE_ORDER_NAMES_OUT` for the build and for a recording run of the same executable and asserts the two dumps EQUAL (module name and every start, kind, name, for every chunk and internal module): single chunk, `--splitting` with an entry in a subdirectory, CommonJS, `--minify`, a non-ASCII banner. - Unit tests of the walker through `bun:internal-for-testing`: renames (bindings, labels, private names, minifier), string edits, property keys, class fields and static blocks, default constructors, 600 nested arrows, 200,000-term expressions, two hand-derived golden hashes. - 42 order-file tests pass on release and on debug + ASAN with `BUN_JSC_validateExceptionChecks=1`; the new ones fail on the previous binary. Limitations - An order file's names come from the walker of the Bun that built the recording executable. A Bun upgrade that changes what the walker hashes bumps the order-file version (`v2` → `v3`), so a stale file is rejected with "was recorded by another version of Bun: record it again" instead of silently matching nothing; two hand-derived golden hashes in the tests are the tripwire for an accidental change. - A name follows the bundler's PRINTED output: platform/`define` differences and printer or minifier upgrades re-name the code they touch (it lands in UNKNOWN, next to HOT); record and build with the same minify settings. Functions with identical syntax share a name and hotness. - Not ordered: the prelinked module graph and module-info tables, source text. Expression info is ordered by code, not by what throws. - Run on linux x64 only locally (CI runs the round trips on every platform). A Windows-target build cannot be run on Linux: the test asserts that it names every chunk and internal module exactly as the host-target build does. A public path does not reach a compiled executable's chunk import paths (CLI or `Bun.build`), so there is no such variant to test. --------- Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
…ven-sh#43880) Behaviour change: none ### Problem - Three declarations have no reference anywhere in the tree, on any platform. - A link of the debug build with `--gc-sections` drops the two C++ functions. A `#[deprecated]` probe on the Rust struct gives zero use warnings on all 12 CI targets. ### Fix - Remove `createBuffer(JSGlobalObject*, const Vector<uint8_t>&)` (`JSBuffer.cpp`, `JSBuffer.h`). All 9 call sites pass a `std::span` or a pointer and a length. - Remove `expectedEnumerationValues<BufferEncodingType>()` (`JSBufferEncodingType.cpp`, `JSBufferEncodingType.h`). Nothing converts `IDLEnumeration<BufferEncodingType>`, so nothing instantiates it. - Remove the `#[cfg(windows)]` stub `struct WaitPidResult {}` (`src/spawn/process.rs`). Each user of the name, and the re-export in `src/spawn/lib.rs`, is `#[cfg(unix)]`. - Verified: `bun run rust:check-all` (12 targets ok), `cargo fmt --all --check`, `bun bd`, and with the debug build `test/js/node/buffer.test.js` (683 pass), `test/js/node/vm/vm.test.ts` (306 pass), `test/js/web/websocket/websocket-client.test.ts` (37 pass). ### Background - This sweep used two whole-program checks, not name searches. The linker reports each function section that no root reaches. The compiler reports each use of an item marked `#[deprecated]`, with exact name resolution, for each target. - The probe covered 11,196 Rust items (functions, extern declarations, constants, statics, structs, enums, aliases). It ran on 12 targets, and also with tests, with `--release`, and with the `bun_asan`, `bun_debug` and `socket_fault_injection` cfgs. 145 items have zero uses. Open PRs already delete 134 of them, so this PR leaves those out. ### Downsides - None found. Checked each textual reference of the three names in `src/`, `packages/`, `scripts/`, `build/debug/codegen/` and the export lists (`src/symbols.txt`, `src/symbols.def`, `src/linker.lds`). <details><summary>Notes</summary> Areas scanned in this run - Rust: the whole workspace. Functions with no live symbol in a `--gc-sections` link of the debug build (whole-archive over every `bun_*` rlib), every `extern` block declaration, constants, statics, structs, enums, unions and type aliases with few outside references. Items under a platform `cfg` were evaluated against the cfg set of each CI target and probed on the targets where they are active. The crate-level `allow(deprecated)` in `bun_jsc` and `bun_ptr` was off during the probe. - C and C++: every function in `src/`, `packages/bun-usockets` and `packages/bun-uws` that the `--gc-sections` link drops (298 source locations). Open PRs already delete 183 of them. - `src/js/`: no file is unloaded, no internal export is unused, no builtin is unreferenced (outside files that open PRs cover). - Headers that nothing includes, `.rs` files outside every module tree, `.cpp` files outside the build, `#if 0` blocks, unreferenced top-level TS/JS definitions, unused `[workspace.dependencies]` entries: none found outside files that open PRs cover. Candidates that the checks flagged and this PR keeps - `Bun__napi_get_version` (`napi.cpp`): no caller, but oven-sh#40232 already removes it under its earlier name `napi_internal_get_version`. - `host_fn::host_fn_this_value`, `host_fn::host_fn_setter` (`src/jsc/host_fn.rs`): no use today, but `src/codegen/generate-classes.ts` emits both names for a class that is not shared. - `JsClass::estimated_size` default (`src/jsc/lib.rs`): a documented hook that generated code resolves by method syntax. - `bun_zstd::inflate_embedded`, `inflate_embedded_nul`: used by `embed_compressed!` under `cfg(bun_codegen_embed)`, which only release builds set. - `bun_core::strings::split_once`: no caller, but `clippy.toml` names it as the replacement in three `disallowed-methods` reasons. - `src/runtime/api/bun/h2/connection.rs` (`send_header_block`, `send_data`, `send_push_promise`, `encode_header`, `begin_header_block`): only unit tests call them, and the engine is still under construction. - `_ASSERT`, `_FITS`, `_ALIGN_CHECK`, `_NOT_SEND`, `_NOT_SYNC`: static assertions. - `PerformanceResourceTiming::create`, `ResourceTiming`, `NetworkLoadMetrics` and related classes: nothing creates an instance, but `PerformanceResourceTiming`, `PerformanceServerTiming` and `PerformanceTiming` are globals, so the classes are API surface. - Unused integer specializations in `JSDOMConvertNumbers.cpp`, unused `toJS`/`toWrapped` overloads in generated-style WebCore wrappers, unused special members in `ncrypto.cpp`, constants in the `sys`, `libuv_sys` and `errno` tables: each is part of a complete table or a class shape. </details> <!-- robobun:evidence:begin --> --- **no test proof** · iteration 0 · the description declares no behaviour change, so there is no failing test to prove; the existing suite in CI is the check <!-- robobun:evidence:end -->
…ndings, NodeVMModule, and the build scripts (oven-sh#43914) Behaviour change: none ### Problem - 38 lines in 23 files have no reader: 14 type aliases, one enum, three locals, three build-script leftovers, nine stale config entries. - The sweep found no other free dead code. The 37 open dead-code PRs already delete each larger item. This PR shares no deletion with them. ### Fix - Remove `using DOMWrapped` from 14 wrapper headers (`JSAbortSignal.h`, `JSBroadcastChannel.h`, `JSCloseEvent.h`, `JSCustomEvent.h`, `JSErrorEvent.h`, `JSMessageEvent.h`, `JSMessagePort.h`, `JSPerformance.h`, `JSPerformanceMark.h`, `JSPerformanceMeasure.h`, `JSPerformanceResourceTiming.h`, `JSWebSocket.h`, `JSWorker.h`, `JSWebView.h`). - Remove `NodeVMModule::Type` and three locals that nothing reads: `contents` (`CryptoPrimes.cpp`), `dataString` and `encodingString` (`JSCipherPrototype.cpp`). - Remove `ToolSpec.versionArg` (`scripts/build/tools.ts`), the `sys/Error.rs` key of `rustIdentifierPaths` (`generate-js2native.ts`), and the `internalRegistry` field that `createInternalModuleRegistry` returns. Remove eight entries of `.gitattributes`, `.prettierignore` and `oxlint.json` that name paths that do not exist, and one duplicate pattern. - Verified: `rg` finds no other use of each name in `src/`, `packages/`, `scripts/`, `test/` and `build/debug/codegen/`. `bun bd` passes. With the debug build: `abort.test.ts`, `broadcast-channel.test.ts`, `websocket-client.test.ts`, `perf_hooks.test.ts`, `vm.test.ts`, `test-crypto-prime.js`, `test/internal/source-lints/`. ### Background - `DOMWrapped` names the C++ class that a JS wrapper class wraps. `JSDOMWrapper<T>` defines it for each wrapper. Only `JSDOMIterator.h` reads it, for `JSFetchHeaders`, `JSDOMFormData`, `JSURLSearchParams` and `JSCookieMap`. None of those four declares its own alias. - `ToolSpec` describes a tool that the build looks for on the PATH. `versionArg` was for a tool that prints its version with `version` and not `--version`. No tool spec sets it. ### Downsides - None found. Checked each name with `rg`, the debug build, and the suites above. <details><summary>Notes</summary> How this sweep searched - Rust: a rust-analyzer reference index of the whole workspace (49,127 items), then a mark and sweep from these roots: FFI and test attributes, trait items, macro-generated items, names that the generated code uses, and names with a textual occurrence that the index did not resolve. After the false positives were removed (macro dispatch such as `any_dispatch!`, `comptime_string_map!` statics, struct field shorthand, the codegen name `r#ref`), no unreferenced item was left outside the open PRs. - C, C++ and Rust: a relink of the debug build with `--gc-sections --print-gc-sections`. The debug build has no inlining, so a dropped function section has no caller on linux-x64. The relink dropped 337 C-named functions and 166 plain C++ functions from Bun's own objects. The open PRs already delete them, except the items under "Kept" below. - `src/js/`: every builtin export has a `CodeGenerator` reference, every internal module has a loader, and no module-local binding is unused. - `.rs` files outside every module tree, headers that nothing includes, `.cpp` files outside the build, unused Cargo dependencies (`cargo` reports 9 on linux. Open PRs already remove 4. The other 5 have a use on another target or in tests): nothing to remove. Kept, with the reason - `WEBCORE_GENERATED_CONSTRUCTOR_GETTER` (`ZigGlobalObject.cpp`) defines a `<Name>_getter` for 51 classes. Only 15 have a user. To remove the other 36 needs a second macro, which adds lines. - `PerformanceResourceTiming`, `ResourceTiming`, `NetworkLoadMetrics`, `ResourceLoadTiming`: nothing creates an instance, but `PerformanceResourceTiming` is a global constructor, so the class is API surface. - `bun_core::strings::split_once`: no caller, but `clippy.toml` names it as the replacement for `str::split_once`. - `StringPrintStream pathOut` (`BunJSCModule.h`): an unread local, but oven-sh#41137 already removes that line in its rewrite of `startSamplingProfiler`. - `jsFunctionAppendOnLoadPluginNode` and three sibling host functions, `Process_defaultSetter`, `Bun__napi_get_version`: no caller, already removed by oven-sh#40232. - `completions/bun-cli.json` and `misctools/generate-cli-completions.ts`: nothing reads the JSON, but feature PRs keep it up to date by hand. - `scripts/lldb-inline-tool.cpp`, `scripts/lldb-inline.sh`, `scripts/github-metrics.ts`, `scripts/gamble.ts`: nothing references them, but they are manual developer tools. - `HiveBitSet::_FITS` (`src/collections/hive_array.rs`): a static assertion, so it stays. It has a defect outside the scope of this PR: it is an associated const of a generic impl and nothing references it, so rustc never evaluates it. A reference such as `let () = Self::_FITS;` in `init_empty()` makes it run. - The defaulted special members in `ncrypto.cpp`, and the `CMAKE_*` exports in `flake.nix` and `shell.nix` (not testable here). </details> <!-- robobun:evidence:begin --> --- **no test proof** · iteration 0 · the description declares no behaviour change, so there is no failing test to prove; the existing suite in CI is the check <!-- robobun:evidence:end -->
### What does this PR do? `AbortHandle` becomes the one way native code listens to an `AbortSignal`. It keeps its owner alive before the owner's code runs. | | Before | After | |---|---|---| | Native listeners on a signal | `AbortHandle`, plus three callers of the raw `listen` / `add_listener` API | `AbortHandle` only | | fetch `Response`, HTTP/2 stream, `fs.watch` | raw `ctx` pointer | `AbortHandle::follow_owner` | | Owner kept alive during the callback | each callback did it by hand | `AbortHandleOwner::keep_alive`, taken by the trampoline first | | `add_listener`, `clean_native_bindings` | `pub` | `pub(crate)` | | Cost | | no new allocation; one non-atomic ref for `Response`, nothing for other owners | ### How did you verify your code works? | Test | 1.4.3-canary | This change (debug + ASAN) | |---|---|---| | `module-graph-gc.test.ts` "aborting a signal whose fetch responses are garbage" | fail | pass | | `fetch-abort-stream-body`, `fetch-abort-queued`, `fetch-abort-socket-close-race` | | pass | | `abort-signal-leak`, `abort-signal-event-listener-leak`, `abort.test.ts` | | pass | | `fs.watch.test.ts` signal tests | | pass | | `node-http2.test.js` abort tests | | pass |
…oven-sh#43879) Fixes oven-sh#43875 ### Problem - `child.stdin.end(cb)` with no data fires `cb` and `'finish'` on the next tick while earlier writes still wait behind pipe backpressure. Node waits for the drain. A parent that exits in `cb` truncates the child's input. - `child.stdin` is a fast-path `fs.WriteStream` (`src/js/internal/fs/streams.ts:474`). `writeFast` hands chunks to the native `FileSink` and never updates `_writableState`, so `end()` sees nothing pending. oven-sh#28635 fixed this for `process.stdout` only, with a per-instance `_final`. ### Fix - Install `finalFast` as `_final` where the constructor installs the fast path. It awaits `fileSink.flush()`, which returns the backlog's promise when writes are pending. - Delete the copy in `getStdioWriteStream`. `process.stdout` and `process.stderr` now get it from the constructor. - Suppress `'drain'` from the fast-path sites once the stream is ending or destroyed, as `Writable`'s `afterWrite` does. The stream now stays alive while the backlog drains, which made that late `'drain'` visible. - Verified: `test/js/node/child_process/child_process.test.ts` and `test/js/node/tty.test.ts` (one new case each, both fail on 1.4.3). Also `test/regression/issue/25432.test.ts`, the `process` and `child_process` suites, and the stdio cases in `test/js/node/test/parallel`. - Self-reviewed: 1 concern raised, 1 addressed (the tty test held the backlog with a `sleep`. It now gates the read on an IPC message). ### Background - The fast path (`$fastPath: true`) has three callers: `child.stdin`, `process.stdout`/`stderr`, and `tty.WriteStream`. It replaces `write` with `writeFast`, which skips the `Writable` bookkeeping. `Writable` emits `'finish'` when `_final(cb)` calls back, or at once when there is no `_final`. - Considered a `_final` on `child.stdin` alone: it repeats oven-sh#28635 and leaves `tty.WriteStream` broken. Considered routing `writeFast` through `Writable.prototype.write`: it adds bookkeeping to every `process.stdout.write`. ### Downsides - `child.stdin` and `tty.WriteStream` gain one own property: 16 to 17 and 15 to 16 own keys (`Object.getOwnPropertyNames`, 1.4.3 vs this build). - Each `end()` on those streams makes one `flush()` host call. On an empty buffer that is 0 syscalls (`IOWriter::flush` returns `Wrote(0)`, `src/io/PipeWriter.rs:969`). `strace` is not installed here, so the count is from the code. - Code that relied on `'finish'` from `child.stdin` firing before the pipe drained now sees it later. - On Windows a single in-flight `uv_write` is not reported by `flush()` (`src/io/PipeWriter.rs:2099`), so one unsent chunk can still be lost when `cb` exits. This PR fixes the multi-chunk backlog. The single-chunk case is pre-existing and needs a change in `FileSink`. <details><summary>Notes</summary> Ordering on the repro (3 untracked writes, `write(chunk, cb)`, `'finish'` listener, `end(cb)`): ``` bun 1.4.3: end(cb) 1ms, 'finish' 1ms, write(cb) 243ms this PR: write(cb), end(cb), 'finish' (same order as node) ``` `FileSink.flush()` (`src/runtime/webcore/FileSink.rs:983`) returns the pending write promise when one exists, and a number when the buffer is empty. Open PR oven-sh#36316 makes `child.stdin` a `net.Socket` subclass whose `_write` goes through `Duplex`, which would also fix this for `child.stdin`. It is a larger parity change and leaves `tty.WriteStream` on the fast path. This PR does not depend on it. Related issues with the same shape in other layers: oven-sh#43155 (`http.ServerResponse`, fix in oven-sh#41822) and oven-sh#43874 (`TLSSocket` over a `Duplex`). `bun x tsc --noEmit -p src/js/tsconfig.json` reports the same 385 pre-existing errors with and without this change. Two tests in the `child_process` suite fail on main in this container without the change: "should allow us to spawn in the default shell" and "extra stdio pipes are not double-closed on GC". </details> <!-- robobun:evidence:begin --> --- **no test proof** · iteration 1 · platform-specific test(s) that do not run on this machine, deferring to CI, which covers all platforms: test/js/node/tty.test.ts, test/js/node/child_process/child_process.test.ts <!-- robobun:evidence:end -->
…oven-sh#43886) Bumps the actions group with 6 updates in the / directory: | Package | From | To | | --- | --- | --- | | [anthropics/claude-code-action/base-action](https://github.com/anthropics/claude-code-action) | `1.0.215` | `1.0.228` | | [vmactions/freebsd-vm](https://github.com/vmactions/freebsd-vm) | `1.5.5` | `1.5.7` | | [docker/setup-qemu-action](https://github.com/docker/setup-qemu-action) | `4.3.0` | `4.4.0` | | [docker/setup-buildx-action](https://github.com/docker/setup-buildx-action) | `4.3.0` | `4.4.1` | | [docker/build-push-action](https://github.com/docker/build-push-action) | `7.3.0` | `7.4.0` | | [ruby/setup-ruby](https://github.com/ruby/setup-ruby) | `1.321.0` | `1.324.0` | Updates `anthropics/claude-code-action/base-action` from 1.0.215 to 1.0.228 <details> <summary>Release notes</summary> <p><em>Sourced from <a href="https://github.com/anthropics/claude-code-action/releases">anthropics/claude-code-action/base-action's releases</a>.</em></p> <blockquote> <h2>v1.0.228</h2> <p><strong>Full Changelog</strong>: <a href="https://github.com/anthropics/claude-code-action/compare/v1.0.227...v1.0.228">https://github.com/anthropics/claude-code-action/compare/v1.0.227...v1.0.228</a></p> <h2>v1.0.227</h2> <p><strong>Full Changelog</strong>: <a href="https://github.com/anthropics/claude-code-action/compare/v1.0.226...v1.0.227">https://github.com/anthropics/claude-code-action/compare/v1.0.226...v1.0.227</a></p> <h2>v1.0.226</h2> <p><strong>Full Changelog</strong>: <a href="https://github.com/anthropics/claude-code-action/compare/v1.0.225...v1.0.226">https://github.com/anthropics/claude-code-action/compare/v1.0.225...v1.0.226</a></p> <h2>v1.0.225</h2> <p><strong>Full Changelog</strong>: <a href="https://github.com/anthropics/claude-code-action/compare/v1.0.224...v1.0.225">https://github.com/anthropics/claude-code-action/compare/v1.0.224...v1.0.225</a></p> <h2>v1.0.224</h2> <p><strong>Full Changelog</strong>: <a href="https://github.com/anthropics/claude-code-action/compare/v1.0.223...v1.0.224">https://github.com/anthropics/claude-code-action/compare/v1.0.223...v1.0.224</a></p> <h2>v1.0.223</h2> <p><strong>Full Changelog</strong>: <a href="https://github.com/anthropics/claude-code-action/compare/v1.0.222...v1.0.223">https://github.com/anthropics/claude-code-action/compare/v1.0.222...v1.0.223</a></p> <h2>v1.0.222</h2> <p><strong>Full Changelog</strong>: <a href="https://github.com/anthropics/claude-code-action/compare/v1.0.221...v1.0.222">https://github.com/anthropics/claude-code-action/compare/v1.0.221...v1.0.222</a></p> <h2>v1.0.221</h2> <p><strong>Full Changelog</strong>: <a href="https://github.com/anthropics/claude-code-action/compare/v1.0.220...v1.0.221">https://github.com/anthropics/claude-code-action/compare/v1.0.220...v1.0.221</a></p> <h2>v1.0.220</h2> <p><strong>Full Changelog</strong>: <a href="https://github.com/anthropics/claude-code-action/compare/v1.0.219...v1.0.220">https://github.com/anthropics/claude-code-action/compare/v1.0.219...v1.0.220</a></p> <h2>v1.0.219</h2> <p><strong>Full Changelog</strong>: <a href="https://github.com/anthropics/claude-code-action/compare/v1.0.218...v1.0.219">https://github.com/anthropics/claude-code-action/compare/v1.0.218...v1.0.219</a></p> <h2>v1.0.218</h2> <p><strong>Full Changelog</strong>: <a href="https://github.com/anthropics/claude-code-action/compare/v1.0.217...v1.0.218">https://github.com/anthropics/claude-code-action/compare/v1.0.217...v1.0.218</a></p> <h2>v1.0.217</h2> <p><strong>Full Changelog</strong>: <a href="https://github.com/anthropics/claude-code-action/compare/v1.0.216...v1.0.217">https://github.com/anthropics/claude-code-action/compare/v1.0.216...v1.0.217</a></p> <h2>v1.0.216</h2> <p><strong>Full Changelog</strong>: <a href="https://github.com/anthropics/claude-code-action/compare/v1.0.215...v1.0.216">https://github.com/anthropics/claude-code-action/compare/v1.0.215...v1.0.216</a></p> </blockquote> </details> <details> <summary>Commits</summary> <ul> <li><a href="https://github.com/anthropics/claude-code-action/commit/2261fcfc88e7de1b55f179edd588805e12de71f2"><code>2261fcf</code></a> chore: bump Claude Code to 2.1.275 and Agent SDK to 0.3.275</li> <li><a href="https://github.com/anthropics/claude-code-action/commit/3b8197d3d486006dd4af54613517f21ac6ac625e"><code>3b8197d</code></a> chore: bump Claude Code to 2.1.274 and Agent SDK to 0.3.274</li> <li><a href="https://github.com/anthropics/claude-code-action/commit/7b0b255830a1fab6e602658672acad11c12d841d"><code>7b0b255</code></a> chore: bump Claude Code to 2.1.273 and Agent SDK to 0.3.273</li> <li><a href="https://github.com/anthropics/claude-code-action/commit/bf38e86e58df9ebf3420326d019f955bb3be64dd"><code>bf38e86</code></a> chore: bump Claude Code to 2.1.272 and Agent SDK to 0.3.272</li> <li><a href="https://github.com/anthropics/claude-code-action/commit/51db78a4b844e144f8d02425cb280435c04a3474"><code>51db78a</code></a> chore: bump Claude Code to 2.1.271 and Agent SDK to 0.3.271</li> <li><a href="https://github.com/anthropics/claude-code-action/commit/9cdae7f0d995e3ba7c33f226087fdf82a59cd520"><code>9cdae7f</code></a> chore: bump Claude Code to 2.1.270 and Agent SDK to 0.3.270</li> <li><a href="https://github.com/anthropics/claude-code-action/commit/56cf60fde42f7b19c3abfd5c9c48b69a1288461f"><code>56cf60f</code></a> chore: bump Claude Code to 2.1.269 and Agent SDK to 0.3.269</li> <li><a href="https://github.com/anthropics/claude-code-action/commit/0a8d3c9443bbff909ab973b6a17a340b913f229f"><code>0a8d3c9</code></a> chore: bump Claude Code to 2.1.268 and Agent SDK to 0.3.268</li> <li><a href="https://github.com/anthropics/claude-code-action/commit/19dda84776b3518d98b8798e591daee763049ed3"><code>19dda84</code></a> chore: bump Claude Code to 2.1.267 and Agent SDK to 0.3.267</li> <li><a href="https://github.com/anthropics/claude-code-action/commit/5ccc3a35a6367cdb8e6fbd0728287467540ecfe2"><code>5ccc3a3</code></a> chore: bump Claude Code to 2.1.266 and Agent SDK to 0.3.266</li> <li>Additional commits viewable in <a href="https://github.com/anthropics/claude-code-action/compare/ef8bb1e43bf303cff727a1dd0b8837029fe982a2...2261fcfc88e7de1b55f179edd588805e12de71f2">compare view</a></li> </ul> </details> <br /> Updates `vmactions/freebsd-vm` from 1.5.5 to 1.5.7 <details> <summary>Release notes</summary> <p><em>Sourced from <a href="https://github.com/vmactions/freebsd-vm/releases">vmactions/freebsd-vm's releases</a>.</em></p> <blockquote> <h2>v1.5.7</h2> <p>FreeBSD 10.4 and 11.4, and a fix for "Unsupported OS: freebsd"</p> <h2>New releases</h2> <p>FreeBSD 10.4 and 11.4 on x86_64, from image builder 2.2.8. The action now offers 15 releases; the default is still 15.1.</p> <ul> <li>uses: vmactions/freebsd-vm@v1 with: release: "10.4"</li> </ul> <p>The leading-part form works too: release: "10" and release: "11" pick the newest matching release, so the action now ships 10, 11, 12, 13, 14 and 15.</p> <p>pkg.FreeBSD.org dropped its FreeBSD 10, 11 and 12 repositories long ago, so these images take their packages from the preserved SGGS mirror (<a href="https://mirror.sg.gs/freebsd-pkg/">https://mirror.sg.gs/freebsd-pkg/</a>), which keeps FreeBSD's original repository signatures; pkg verifies them against the fingerprint shipped in the base system. Two things the VM runtime had to learn to run them: 10.x and 11.x boot via SeaBIOS, since their images have no EFI system partition, and 10.4 runs on QEMU's qemu64 CPU model, because FreeBSD 10's signal delivery panics when -cpu host exposes modern XSAVE features.</p> <h2>12.4 x86_64 gains rsync and sshfs</h2> <p>The same mirror reaches 12.4 x86_64: the image now ships rsync and fusefs-sshfs, so all five sync methods work there instead of nfs, scp and tar only. 12.4 aarch64 stays base-only; no aarch64 packages exist for FreeBSD 12.</p> <h2>Fixed: a lost network probe no longer fails as "Unsupported OS"</h2> <p><a href="https://redirect.github.com/vmactions/freebsd-vm/issues/163">#163</a>: a job with release: '14.0' failed after three minutes with</p> <p>Error: Unsupported OS: freebsd. Builder repository anyvm-org/freebsd-builder not found.</p> <p>although the image exists. A single failed probe of the release download URL sent the run down the GitHub REST API. The action never passed a token, so that request was unauthenticated and shared the 60/hour per-IP limit with every other job on the runner IP; the 403 was retried for three minutes and then reported as an unsupported OS. Two changes close this:</p> <!-- raw HTML omitted --> </blockquote> <p>... (truncated)</p> </details> <details> <summary>Commits</summary> <ul> <li><a href="https://github.com/vmactions/freebsd-vm/commit/4469451fe39bee80be4066836c5170362e9349f3"><code>4469451</code></a> Update vmactions/freebsd-vm from base-vm</li> <li><a href="https://github.com/vmactions/freebsd-vm/commit/a1432a54a2181871355b8d17230abf4710bcd45a"><code>a1432a5</code></a> Generated from base-vm</li> <li><a href="https://github.com/vmactions/freebsd-vm/commit/95e5c028ae049b6f30197f838319b8844d6402b0"><code>95e5c02</code></a> Update vmactions/freebsd-vm from base-vm</li> <li><a href="https://github.com/vmactions/freebsd-vm/commit/7c33c6461009a7333727710ea51fe0cbe28e5d01"><code>7c33c64</code></a> Generated from base-vm</li> <li><a href="https://github.com/vmactions/freebsd-vm/commit/92f7fa445ab24de0564a09d1a6415e8bd309b7d2"><code>92f7fa4</code></a> Bump versions from upstream releases</li> <li><a href="https://github.com/vmactions/freebsd-vm/commit/c0e53c390d0a2c41c80508ca0a624804fa1c1349"><code>c0e53c3</code></a> Update vmactions/freebsd-vm from base-vm</li> <li><a href="https://github.com/vmactions/freebsd-vm/commit/11feb8f3e746f94cb5a33e5bbd44119ab75ea25e"><code>11feb8f</code></a> Generated from base-vm</li> <li><a href="https://github.com/vmactions/freebsd-vm/commit/224f1aca6eb7c4f220c94cc78d307db34c9d8b24"><code>224f1ac</code></a> Update version to v1.5.6</li> <li><a href="https://github.com/vmactions/freebsd-vm/commit/e97817815cd2052751ee28aa67e4a4911ff25391"><code>e978178</code></a> Update vmactions/freebsd-vm from base-vm</li> <li><a href="https://github.com/vmactions/freebsd-vm/commit/2e173697f85b21cfc051bf47e32ff81a4b4ff7ad"><code>2e17369</code></a> Generated from base-vm</li> <li>Additional commits viewable in <a href="https://github.com/vmactions/freebsd-vm/compare/f0552d3b69211736abd97f02ff3d4674c56b73b1...4469451fe39bee80be4066836c5170362e9349f3">compare view</a></li> </ul> </details> <br /> Updates `docker/setup-qemu-action` from 4.3.0 to 4.4.0 <details> <summary>Release notes</summary> <p><em>Sourced from <a href="https://github.com/docker/setup-qemu-action/releases">docker/setup-qemu-action's releases</a>.</em></p> <blockquote> <h2>v4.4.0</h2> <ul> <li>Use the shared error helper for Docker commands by <a href="https://github.com/crazy-max"><code>@crazy-max</code></a> in <a href="https://redirect.github.com/docker/setup-qemu-action/pull/345">docker/setup-qemu-action#345</a></li> <li>Bump <code>@docker/actions-toolkit</code> from 0.96.0 to 0.100.0 in <a href="https://redirect.github.com/docker/setup-qemu-action/pull/344">docker/setup-qemu-action#344</a></li> <li>Bump <code>@humanfs/node</code> from 0.16.7 to 0.16.8 in <a href="https://redirect.github.com/docker/setup-qemu-action/pull/340">docker/setup-qemu-action#340</a></li> <li>Bump js-yaml from 4.3.1 to 4.3.2 in <a href="https://redirect.github.com/docker/setup-qemu-action/pull/342">docker/setup-qemu-action#342</a></li> <li>Bump postcss-selector-parser from 7.1.1 to 7.1.5 in <a href="https://redirect.github.com/docker/setup-qemu-action/pull/337">docker/setup-qemu-action#337</a></li> </ul> <p><strong>Full Changelog</strong>: <a href="https://github.com/docker/setup-qemu-action/compare/v4.3.0...v4.4.0">https://github.com/docker/setup-qemu-action/compare/v4.3.0...v4.4.0</a></p> </blockquote> </details> <details> <summary>Commits</summary> <ul> <li><a href="https://github.com/docker/setup-qemu-action/commit/99012661954931238ded8c8b007157a8430204e1"><code>9901266</code></a> Merge pull request <a href="https://redirect.github.com/docker/setup-qemu-action/issues/342">#342</a> from docker/dependabot/npm_and_yarn/js-yaml-4.3.2</li> <li><a href="https://github.com/docker/setup-qemu-action/commit/9364d8b005eaf92e44e311ad68698e0e4d1fc775"><code>9364d8b</code></a> Merge pull request <a href="https://redirect.github.com/docker/setup-qemu-action/issues/340">#340</a> from docker/dependabot/npm_and_yarn/humanfs/node-0.16.8</li> <li><a href="https://github.com/docker/setup-qemu-action/commit/95c3240fd1cc4bb767d163c4336f203f1f98c8c1"><code>95c3240</code></a> Merge pull request <a href="https://redirect.github.com/docker/setup-qemu-action/issues/337">#337</a> from docker/dependabot/npm_and_yarn/postcss-selector-...</li> <li><a href="https://github.com/docker/setup-qemu-action/commit/c24671a9f635f27130098a37aaa28a0fe899c1f8"><code>c24671a</code></a> Merge pull request <a href="https://redirect.github.com/docker/setup-qemu-action/issues/338">#338</a> from docker/dependabot/github_actions/codeql-actions-...</li> <li><a href="https://github.com/docker/setup-qemu-action/commit/fa83965153d27e053b76aa86ad2b4753aad68c34"><code>fa83965</code></a> Merge pull request <a href="https://redirect.github.com/docker/setup-qemu-action/issues/345">#345</a> from crazy-max/shared-error-helpers</li> <li><a href="https://github.com/docker/setup-qemu-action/commit/f396a658a52c1a0725759b74ea48a6fb8e0e575e"><code>f396a65</code></a> build(deps): bump the codeql-actions group across 1 directory with 2 updates</li> <li><a href="https://github.com/docker/setup-qemu-action/commit/a63df2fb68af6df486c0bcef37b58fa32674f8da"><code>a63df2f</code></a> chore: update generated content</li> <li><a href="https://github.com/docker/setup-qemu-action/commit/3e4165fc6d948cdd283528a2da5d91dca944f777"><code>3e4165f</code></a> use the shared error helper for Docker commands</li> <li><a href="https://github.com/docker/setup-qemu-action/commit/18c52d952150b11a3c9f65b4b5b751ba623d1fd5"><code>18c52d9</code></a> Merge pull request <a href="https://redirect.github.com/docker/setup-qemu-action/issues/344">#344</a> from docker/dependabot/npm_and_yarn/docker/actions-to...</li> <li><a href="https://github.com/docker/setup-qemu-action/commit/896cbedb64417124655bfd0b9a72fac2f0140044"><code>896cbed</code></a> [dependabot skip] chore: update generated content</li> <li>Additional commits viewable in <a href="https://github.com/docker/setup-qemu-action/compare/1f40c72289eff860ee54a304f1438e3cff362e0a...99012661954931238ded8c8b007157a8430204e1">compare view</a></li> </ul> </details> <br /> Updates `docker/setup-buildx-action` from 4.3.0 to 4.4.1 <details> <summary>Release notes</summary> <p><em>Sourced from <a href="https://github.com/docker/setup-buildx-action/releases">docker/setup-buildx-action's releases</a>.</em></p> <blockquote> <h2>v4.4.1</h2> <ul> <li>Skip BuildKit image pre-pulls for explicit endpoints by <a href="https://github.com/crazy-max"><code>@crazy-max</code></a> in <a href="https://redirect.github.com/docker/setup-buildx-action/pull/624">docker/setup-buildx-action#624</a></li> </ul> <p><strong>Full Changelog</strong>: <a href="https://github.com/docker/setup-buildx-action/compare/v4.4.0...v4.4.1">https://github.com/docker/setup-buildx-action/compare/v4.4.0...v4.4.1</a></p> <h2>v4.4.0</h2> <ul> <li>Use official Buildx releases for cloud driver by <a href="https://github.com/crazy-max"><code>@crazy-max</code></a> in <a href="https://redirect.github.com/docker/setup-buildx-action/pull/606">docker/setup-buildx-action#606</a></li> <li>Pull BuildKit image before builder creation by <a href="https://github.com/crazy-max"><code>@crazy-max</code></a> in <a href="https://redirect.github.com/docker/setup-buildx-action/pull/609">docker/setup-buildx-action#609</a></li> <li>Use shared error helpers for Buildx and Docker commands by <a href="https://github.com/crazy-max"><code>@crazy-max</code></a> in <a href="https://redirect.github.com/docker/setup-buildx-action/pull/620">docker/setup-buildx-action#620</a></li> <li>Bump <code>@docker/actions-toolkit</code> from 0.95.0 to 0.100.0 in <a href="https://redirect.github.com/docker/setup-buildx-action/pull/610">docker/setup-buildx-action#610</a> <a href="https://redirect.github.com/docker/setup-buildx-action/pull/618">docker/setup-buildx-action#618</a> <a href="https://redirect.github.com/docker/setup-buildx-action/pull/619">docker/setup-buildx-action#619</a></li> <li>Bump <code>@humanfs/node</code> from 0.16.7 to 0.16.8 in <a href="https://redirect.github.com/docker/setup-buildx-action/pull/614">docker/setup-buildx-action#614</a></li> <li>Bump js-yaml from 5.3.0 to 5.4.2 in <a href="https://redirect.github.com/docker/setup-buildx-action/pull/608">docker/setup-buildx-action#608</a> <a href="https://redirect.github.com/docker/setup-buildx-action/pull/617">docker/setup-buildx-action#617</a></li> <li>Bump postcss-selector-parser from 7.1.1 to 7.1.5 in <a href="https://redirect.github.com/docker/setup-buildx-action/pull/611">docker/setup-buildx-action#611</a></li> </ul> <p><strong>Full Changelog</strong>: <a href="https://github.com/docker/setup-buildx-action/compare/v4.3.0...v4.4.0">https://github.com/docker/setup-buildx-action/compare/v4.3.0...v4.4.0</a></p> </blockquote> </details> <details> <summary>Commits</summary> <ul> <li><a href="https://github.com/docker/setup-buildx-action/commit/f87e5991a6d7451dcb8d9637bfbc97413f497069"><code>f87e599</code></a> Merge pull request <a href="https://redirect.github.com/docker/setup-buildx-action/issues/624">#624</a> from crazy-max/skip-pull-with-endpoint</li> <li><a href="https://github.com/docker/setup-buildx-action/commit/e7002743e035c0054da46ca559364576b2fce022"><code>e700274</code></a> chore: update generated content</li> <li><a href="https://github.com/docker/setup-buildx-action/commit/3061c919c67ba542099ba309c9181d1900cecc07"><code>3061c91</code></a> skip BuildKit image pre-pulls for explicit endpoints</li> <li><a href="https://github.com/docker/setup-buildx-action/commit/594f3bf4285d9ea8dc53c9a0c9c4092420091003"><code>594f3bf</code></a> Merge pull request <a href="https://redirect.github.com/docker/setup-buildx-action/issues/609">#609</a> from crazy-max/pull-buildkit-image-before-create</li> <li><a href="https://github.com/docker/setup-buildx-action/commit/bd6e702fc33b636671900d5b5edfab64698c9c25"><code>bd6e702</code></a> chore: update generated content</li> <li><a href="https://github.com/docker/setup-buildx-action/commit/6268c9da9abbd1309c8a16a75f92a878715c3032"><code>6268c9d</code></a> pull BuildKit image before builder creation</li> <li><a href="https://github.com/docker/setup-buildx-action/commit/e8235251b82e23c90e6fad50016f0a78b7f28f11"><code>e823525</code></a> Merge pull request <a href="https://redirect.github.com/docker/setup-buildx-action/issues/621">#621</a> from docker/dependabot/github_actions/codeql-actions-...</li> <li><a href="https://github.com/docker/setup-buildx-action/commit/533ed8ed095b0b133ef16fb495aad119524e220d"><code>533ed8e</code></a> build(deps): bump the codeql-actions group with 2 updates</li> <li><a href="https://github.com/docker/setup-buildx-action/commit/bedaf135699075c88620cd30772b9b6eadc9ba99"><code>bedaf13</code></a> Merge pull request <a href="https://redirect.github.com/docker/setup-buildx-action/issues/620">#620</a> from crazy-max/shared-error-helpers</li> <li><a href="https://github.com/docker/setup-buildx-action/commit/d5079fba84d5edd23d25ba7f3045122175ca6ee2"><code>d5079fb</code></a> chore: update generated content</li> <li>Additional commits viewable in <a href="https://github.com/docker/setup-buildx-action/compare/37fe631027851001ddb9b187196cc803df7f5f0e...f87e5991a6d7451dcb8d9637bfbc97413f497069">compare view</a></li> </ul> </details> <br /> Updates `docker/build-push-action` from 7.3.0 to 7.4.0 <details> <summary>Release notes</summary> <p><em>Sourced from <a href="https://github.com/docker/build-push-action/releases">docker/build-push-action's releases</a>.</em></p> <blockquote> <h2>v7.4.0</h2> <ul> <li>Use the shared error helper for Buildx commands by <a href="https://github.com/crazy-max"><code>@crazy-max</code></a> in <a href="https://redirect.github.com/docker/build-push-action/pull/1620">docker/build-push-action#1620</a></li> <li>Prevent workflow command injection in metadata logs by <a href="https://github.com/crazy-max"><code>@crazy-max</code></a> in <a href="https://redirect.github.com/docker/build-push-action/pull/1617">docker/build-push-action#1617</a></li> <li>Bump <code>@docker/actions-toolkit</code> from 0.92.0 to 0.100.0 in <a href="https://redirect.github.com/docker/build-push-action/pull/1614">docker/build-push-action#1614</a> <a href="https://redirect.github.com/docker/build-push-action/pull/1618">docker/build-push-action#1618</a> <a href="https://redirect.github.com/docker/build-push-action/pull/1621">docker/build-push-action#1621</a></li> <li>Bump <code>@humanfs/node</code> from 0.16.7 to 0.16.8 in <a href="https://redirect.github.com/docker/build-push-action/pull/1609">docker/build-push-action#1609</a></li> <li>Bump brace-expansion from 1.1.13 to 1.1.18 in <a href="https://redirect.github.com/docker/build-push-action/pull/1592">docker/build-push-action#1592</a></li> <li>Bump csv-parse from 7.0.0 to 7.0.2 in <a href="https://redirect.github.com/docker/build-push-action/pull/1613">docker/build-push-action#1613</a></li> <li>Bump js-yaml from 4.3.0 to 4.3.2 in <a href="https://redirect.github.com/docker/build-push-action/pull/1605">docker/build-push-action#1605</a> <a href="https://redirect.github.com/docker/build-push-action/pull/1615">docker/build-push-action#1615</a></li> <li>Bump nanoid from 3.3.16 to 3.3.18 in <a href="https://redirect.github.com/docker/build-push-action/pull/1611">docker/build-push-action#1611</a></li> <li>Bump postcss from 8.5.10 to 8.5.25 in <a href="https://redirect.github.com/docker/build-push-action/pull/1590">docker/build-push-action#1590</a></li> <li>Bump postcss-selector-parser from 7.1.1 to 7.1.5 in <a href="https://redirect.github.com/docker/build-push-action/pull/1606">docker/build-push-action#1606</a></li> <li>Bump sigstore from 4.1.0 to 4.1.1 in <a href="https://redirect.github.com/docker/build-push-action/pull/1577">docker/build-push-action#1577</a></li> <li>Bump undici from 6.27.0 to 6.28.0 in <a href="https://redirect.github.com/docker/build-push-action/pull/1594">docker/build-push-action#1594</a></li> </ul> <p><strong>Full Changelog</strong>: <a href="https://github.com/docker/build-push-action/compare/v7.3.0...v7.4.0">https://github.com/docker/build-push-action/compare/v7.3.0...v7.4.0</a></p> </blockquote> </details> <details> <summary>Commits</summary> <ul> <li><a href="https://github.com/docker/build-push-action/commit/c3c9e263c25d99ce0380d002d59b67737d91b0dc"><code>c3c9e26</code></a> Merge pull request <a href="https://redirect.github.com/docker/build-push-action/issues/1621">#1621</a> from docker/dependabot/npm_and_yarn/docker/actions-t...</li> <li><a href="https://github.com/docker/build-push-action/commit/459b6741834dcd35f946352017e7675bd2089d42"><code>459b674</code></a> [dependabot skip] chore: update generated content</li> <li><a href="https://github.com/docker/build-push-action/commit/4dedcb23c91d79c1629bf53ec2c3bcfffef5b34e"><code>4dedcb2</code></a> chore(deps): Bump <code>@docker/actions-toolkit</code> from 0.99.0 to 0.100.0</li> <li><a href="https://github.com/docker/build-push-action/commit/379bf63a979bd70751945601fa04c50674509952"><code>379bf63</code></a> Merge pull request <a href="https://redirect.github.com/docker/build-push-action/issues/1620">#1620</a> from crazy-max/buildx-error-message</li> <li><a href="https://github.com/docker/build-push-action/commit/9877975c9e0b0b661592ff61049069507f9bc2f6"><code>9877975</code></a> chore: update generated content</li> <li><a href="https://github.com/docker/build-push-action/commit/7ed0556ffafb8eb312463411ef0a84a1dfe24d94"><code>7ed0556</code></a> use the shared Buildx error summary helper</li> <li><a href="https://github.com/docker/build-push-action/commit/91670ba5a4df99a24efff8637a78c83fd1b0f6b1"><code>91670ba</code></a> Merge pull request <a href="https://redirect.github.com/docker/build-push-action/issues/1618">#1618</a> from docker/dependabot/npm_and_yarn/docker/actions-t...</li> <li><a href="https://github.com/docker/build-push-action/commit/80dbc8614a5c0ce4356740f69179cf829ecdc79a"><code>80dbc86</code></a> [dependabot skip] chore: update generated content</li> <li><a href="https://github.com/docker/build-push-action/commit/50cac3a3b6f55e6015d6483d1dd72a3ecb90d20d"><code>50cac3a</code></a> chore(deps): Bump <code>@docker/actions-toolkit</code> from 0.98.0 to 0.99.0</li> <li><a href="https://github.com/docker/build-push-action/commit/03b4d6cac0163b44733e1fa60adfd6da560ee4d1"><code>03b4d6c</code></a> Merge pull request <a href="https://redirect.github.com/docker/build-push-action/issues/1617">#1617</a> from crazy-max/fix-metadata-workflow-commands</li> <li>Additional commits viewable in <a href="https://github.com/docker/build-push-action/compare/53b7df96c91f9c12dcc8a07bcb9ccacbed38856a...c3c9e263c25d99ce0380d002d59b67737d91b0dc">compare view</a></li> </ul> </details> <br /> Updates `ruby/setup-ruby` from 1.321.0 to 1.324.0 <details> <summary>Release notes</summary> <p><em>Sourced from <a href="https://github.com/ruby/setup-ruby/releases">ruby/setup-ruby's releases</a>.</em></p> <blockquote> <h2>v1.324.0</h2> <h2>What's Changed</h2> <ul> <li>Add truffleruby-40.0.0,truffleruby+graalvm-40.0.0 by <a href="https://github.com/ruby-builder-bot"><code>@ruby-builder-bot</code></a> in <a href="https://redirect.github.com/ruby/setup-ruby/pull/938">ruby/setup-ruby#938</a></li> </ul> <p><strong>Full Changelog</strong>: <a href="https://github.com/ruby/setup-ruby/compare/v1.323.0...v1.324.0">https://github.com/ruby/setup-ruby/compare/v1.323.0...v1.324.0</a></p> <h2>v1.323.0</h2> <h2>What's Changed</h2> <ul> <li>Update CRuby releases on Windows by <a href="https://github.com/ruby-builder-bot"><code>@ruby-builder-bot</code></a> in <a href="https://redirect.github.com/ruby/setup-ruby/pull/937">ruby/setup-ruby#937</a></li> </ul> <p><strong>Full Changelog</strong>: <a href="https://github.com/ruby/setup-ruby/compare/v1.322.0...v1.323.0">https://github.com/ruby/setup-ruby/compare/v1.322.0...v1.323.0</a></p> <h2>v1.322.0</h2> <h2>What's Changed</h2> <ul> <li>Add ruby-4.0.7 by <a href="https://github.com/ruby-builder-bot"><code>@ruby-builder-bot</code></a> in <a href="https://redirect.github.com/ruby/setup-ruby/pull/936">ruby/setup-ruby#936</a></li> </ul> <p><strong>Full Changelog</strong>: <a href="https://github.com/ruby/setup-ruby/compare/v1.321.0...v1.322.0">https://github.com/ruby/setup-ruby/compare/v1.321.0...v1.322.0</a></p> </blockquote> </details> <details> <summary>Commits</summary> <ul> <li><a href="https://github.com/ruby/setup-ruby/commit/a0102e0972be65f351c307e2d64b9314a57c8073"><code>a0102e0</code></a> Add truffleruby-40.0.0,truffleruby+graalvm-40.0.0</li> <li><a href="https://github.com/ruby/setup-ruby/commit/984c0c890880bbf811283d6f09c4607c62d210a4"><code>984c0c8</code></a> Update CRuby releases on Windows</li> <li><a href="https://github.com/ruby/setup-ruby/commit/bec3f19a76460dbe12f60def7d1a77585f07516c"><code>bec3f19</code></a> Add ruby-4.0.7</li> <li>See full diff in <a href="https://github.com/ruby/setup-ruby/compare/95ef2b042f9d7a56d8268cba8559e2842e2ad01b...a0102e0972be65f351c307e2d64b9314a57c8073">compare view</a></li> </ul> </details> <br /> Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`. [//]: # (dependabot-automerge-start) [//]: # (dependabot-automerge-end) --- <details> <summary>Dependabot commands and options</summary> <br /> You can trigger Dependabot actions by commenting on this PR: - `@dependabot rebase` will rebase this PR - `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it - `@dependabot show <dependency name> ignore conditions` will show all of the ignore conditions of the specified dependency - `@dependabot ignore <dependency name> major version` will close this group update PR and stop Dependabot creating any more for the specific dependency's major version (unless you unignore this specific dependency's major version or upgrade to it yourself) - `@dependabot ignore <dependency name> minor version` will close this group update PR and stop Dependabot creating any more for the specific dependency's minor version (unless you unignore this specific dependency's minor version or upgrade to it yourself) - `@dependabot ignore <dependency name>` will close this group update PR and stop Dependabot creating any more for the specific dependency (unless you unignore this specific dependency or upgrade to it yourself) - `@dependabot unignore <dependency name>` will remove all of the ignore conditions of the specified dependency - `@dependabot unignore <dependency name> <ignore condition>` will remove the ignore condition of the specified dependency and ignore conditions </details> Signed-off-by: dependabot[bot] <[email protected]> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
… the build scripts (oven-sh#43778) ### Problem - A few C++ and TypeScript items have no caller, no producer, or no effect. - `BUN_MESSAGEPORT_USES_PIPE` (`src/jsc/bindings/webcore/MessagePort.h`) is always `1`. The `#if` around all of `MessagePortPipe.cpp` never excludes anything. ### Fix - WebView: remove `WebViewProto::Reader::u16()` and `f32()` (`ipc_protocol.h`), which have no caller. Remove the CDP `Method` values `RuntimeEnable`, `TargetCloseTarget` and `InputDispatchScrollEvent` with their `case` labels (`ChromeBackend.{h,cpp}`). No pending entry carries them. - WebCore bindings: remove the `BUN_MESSAGEPORT_USES_PIPE` define and guard, the self-alias of `ExtendedDOMClientIsoSubspaces`, the forward declaration of `URLPatternUtilities::URLPatternInit` (no such type), the enumerators `PerformanceEntry::Type::Paint` and `CastedThisErrorBehavior::ReturnEarly`, and 13 lines of commented-out WebKit code. - Build scripts: remove `getBuildNumber()` (`.buildkite/ci.ts`) and `BunOutput.rustObjects` (`scripts/build/bun.ts`). Nothing reads either. - Verified: `rg -w` for each symbol over `src`, `packages`, `scripts`, `test` and `build/debug/codegen` finds no other use. `bun bd` passes. The Notes list the tests. ### Background - `ipc_protocol.h` is the wire format between bun and the WebView host process. `Reader` decodes frames. Every caller uses `u8`, `u32`, `bytes` and `str` only. - `ChromeBackend` tags each pending Chrome DevTools Protocol command with a `Method`, so that the response handler knows which promise to settle. A value that no pending entry carries cannot reach the `switch`. - oven-sh#29937 added the guard so that `MessagePortPipe.cpp` compiled to nothing while a verification step reverted `MessagePort.h`. Both files are on main now. ### Downsides - None found. Checked each removed symbol for users in C++, Rust, generated code and `src/symbols.*`. The removed enum values are in-memory tags or template arguments. Rust mirrors neither enum. <details><summary>Notes</summary> Smoke tests with the debug build, all pass: `test/js/web/workers/message-port-pipe.test.ts`, `message-channel.test.ts`, `performance-observer-leak.test.ts`, `test/js/node/perf_hooks/perf_hooks.test.ts`, `test/js/web/urlpattern/`, `test/js/bun/webview/webview-chrome-pipe.test.ts`. `clang-format` and `prettier` report no change on the touched files. `.buildkite/ci.ts` still transpiles. Each removal was checked against the diffs of the 34 open dead-code PRs. None of them removes the same lines. `MessagePort.h` is also touched by oven-sh#40525, in a different hunk. How the Rust side was scanned, and why this PR has no Rust in it: - `cargo mordant` at the revision pinned in `.github/workflows/rust-lints.yml`, over the Linux, Windows and macOS targets, with the `unused_pub` entries taken out of the baseline. It reports 188 `pub` items that nothing in the workspace uses. Every function, method and struct in that list is in one of four groups: an open PR already removes it, a `cfg` that the run does not build uses it (`bun_zstd::inflate_embedded*` under `bun_codegen_embed`, `StoredTrace::from` in `PackageInstall.rs`), only a unit test uses it (`CowSliceZ::init_dupe`), or oven-sh#42119 left it on purpose (`host_fn_this_value`, `host_fn_setter`, `JsClass::estimated_size`). The constants are flag, errno and syscall-tag tables. - A rust-analyzer SCIP index for five targets (Linux, Windows, macOS, FreeBSD, Android) plus a reachability closure over it. Two blind spots make it unreliable alone: rust-analyzer sets `cfg(test)` by default, which hides `src/runtime/bin_entry`, and references that come from a `macro_rules!` body are not indexed (`comptime_string_map!`, the CSS `to_css` bridges). With those corrected, it agrees with mordant and adds nothing. - Cargo's own `unused_dependencies` warnings: 9 edges. Each is used on another target, or oven-sh#40294 already removes it. - Rust files outside every module tree: none. Headers that nothing includes: none (the remaining ones come in through `GeneratedJS2Native.h`, `NativeModuleImpl.h` or `include_bytes!`). Also scanned and clean: `src/js/{node,internal,bun,thirdparty}` and `src/js/builtins` (all 50 builtins and all 177 private names have a user), `scripts/`, `misctools/`, `.buildkite/ci.ts`, and the C++ under `webcore/`, `webcrypto/`, `node/` and `src/runtime/` that no open PR touches. Probably dead, left alone on purpose: - `bun_core::strings::split_once` (`src/bun_core/string/immutable.rs`): no caller on any target. It sits next to the hunk in which oven-sh#40824 removes `rsplit_once`, so a removal here would conflict with that PR. - The raw-list `myersDiff` export of `src/js/internal/assert/myers_diff.ts` and the `Output::List` path behind it in `src/runtime/node/node_assert.rs` (about 115 lines): nothing consumes it. oven-sh#39924 kept the export on purpose, and Node's own `test-assert-myers-diff.js` needs it if that test is vendored. - `BuiltinName::{redirect, asyncIterator, name, default, fatal, ignoreBOM}` (`src/jsc/lib.rs`, mirrored by position in `bindings.cpp`): never constructed. A removal conflicts with oven-sh#40232. - `FetchHeaders` guard handling (`removePrivilegedNoCORSRequestHeaders` and the `Guard::Immutable` checks): every construction site passes `Guard::None`, and oven-sh#43644 removes `setGuard`. This is unreachable code, not unreferenced code. - `ServerTiming`'s constructor and its `durationSet` / `descriptionSet` fields: nothing constructs a `ServerTiming`. oven-sh#40122 and oven-sh#41385 touch the same cluster. - The `$isPromiseFulfilled`, `$isPromiseRejected` and `$alwaysInline` codegen macros: no user since 92459cd. - `scripts/build/config.ts` flags `logs` and `baseline`: parsed and printed, never read since the Rust rewrite. `NestedCmakeBuild.{extraCFlags, extraCxxFlags, libSubdir, sourceSubdir, pic}`: no dependency sets them, but `scripts/build/deps/README.md` documents them as the API for future dependencies. - `misctools/gen-unicode-table.ts` and `unicode-generator.ts` emit Zig. Nothing references them, but `src/bun_core/string/identifier.rs` still names the generator as the way to rebuild its tables. - `completions/bun-cli.json` and `misctools/generate-cli-completions.ts`: nothing in the repository reads the JSON. It is still updated by hand, so something outside the repository may use it. </details>
### Problem - `hasExportStar` in `src/runtime/bake/hmr-module.ts` has no caller. Its only call site is a block that oven-sh#18109 commented out on 2025-03-14. The `availableExportKeys` local above that block is read only by the commented-out code. - `firstConnection` in `src/runtime/bake/client/websocket.ts` is assigned once and never read. - No lint reports them. Earlier sweeps ran `tsc --noUnusedLocals` over `src/js` and `scripts` only, not over `src/runtime/bake`. ### Fix - Delete `hasExportStar`, the commented-out check, `availableExportKeys`, and `firstConnection`. 2 files, 40 lines removed. - Correct because the bundler already drops `hasExportStar`. The generated `bake.client.js`, `bake.server.js` and `bake.error.js` differ from `main` only by the two removed local declarations. - Verified: `tsc -p src/runtime/bake/tsconfig.json --noUnusedLocals` no longer reports either file. `test/bake/dev/esm.test.ts` (17 pass), `hot.test.ts` (11 pass) and `bundle.test.ts` (23 pass) with the debug build. Behaviour change: none ### Background - `hmr-module.ts` is the module loader that the dev server sends to the browser and to the SSR realm. `parseEsmDependencies` walks the dependency list of an ES module. Each entry carries the export names that the importer uses. - The removed check compared those names with the exports of the dependency and threw a `SyntaxError` for a missing one. It has been off for 18 months. A missing export fails at the use site. - A deletion has one possible place, so no other design was weighed. ### Downsides - The commented-out check was the only sketch of export verification in the HMR runtime. A person who wants to build it starts from the history of oven-sh#18109. <details><summary>Notes</summary> #### Why this run is small Every other hit of this run is live, is platform code with a user on another target, or is a line that one of the 34 open dead-code pull requests already deletes. Each removed line here was checked against those diffs. oven-sh#40492 and oven-sh#43378 touch `websocket.ts` in other hunks. #### Scans of this run, all clean or already claimed - Debug objects linked again with `--gc-sections --print-gc-sections`, then `llvm-symbolizer` for `file:line`. 20,668 discarded functions in bun's objects. The Rust ones outside macros and trait impls are Windows or macOS helpers, or claimed (oven-sh#40824, oven-sh#40557, oven-sh#40232). The C++ ones are claimed, are template instantiations, or have a Rust caller on another target (`bsd_socket_export`, `posix_spawnattr_reset_signals`). - Rust functions that never get a symbol (generic or `#[inline]`, never instantiated), found by comparing every `fn` line with the DWARF declaration lines of all emitted functions. 86 hits outside `cfg`, trait impls and `#[inline(always)]`. All are Windows-only, test-only (the outbound half of `api/bun/h2/connection.rs`), or claimed. - `clang -fsyntax-only -Wunused-function -Wunused-macros -Wunused-template -Wunused-member-function` over 588 translation units and the 69 unified ones (the build passes `-Wno-unused-function`). 3 functions and 6 macros. `formatStackTraceToJSValueWithoutPrepareStackTrace`, `hostName`, `G_TRUE`, `G_FALSE`, `MAX_LABELS` and `us_ioctl` are claimed (oven-sh#40367, oven-sh#43378, oven-sh#40492, oven-sh#40294). `us_quic_send_one` is used under the non-Linux `#if` branch. - A whole-program C++ reference index (`c-index-test -index-file`, 657 translation units, 32,018 symbols declared in bun's tree). 8,711 have no recorded reference. After filters for template-dependent uses, `extern "C"`, virtual methods and names that WebKit headers use, 78 remain. All are index artifacts (typedef struct tags, primary templates with used specializations, `requires` clauses) or one-line getters in files that open pull requests rewrite. - `tsc --noUnusedLocals` over `src/js`, `scripts`, `src/codegen`, `src/runtime/bake`, `src/node-fallbacks` and the sources of each package. The hits outside this change are claimed (oven-sh#40122, oven-sh#41169, oven-sh#41385, oven-sh#40492, oven-sh#43778) or are loop variables. - Regex scans for struct fields with no read and for `bool` or `Option` fields that only ever get one constant. Nothing new after oven-sh#43745. - Exports of `src/js` modules and builtin functions with no mention in another file: none. - Files that nothing includes, imports or names: none outside `.idl` copies (oven-sh#41064). `src/symbols.txt`, `symbols.def` and the `package.json` scripts name nothing that is gone. No `#if 0`. </details> <!-- robobun:evidence:begin --> --- **no test proof** · iteration 1 · the description declares no behaviour change, so there is no failing test to prove; the existing suite in CI is the check <!-- robobun:evidence:end -->
…ven-sh#43943) Bumps mordant to 193abda, where `cargo mordant` exits 101 when any crate has more findings than mordant-baseline.toml allows, so the job drops its separate over-baseline.txt check.
Backport upstream commit ef6f44f (oven-sh#42767), retaining the original runtime regression test. Derive the position from the current output buffer so reused printers do not accumulate a signed counter across modules.
(cherry picked from commit fd2c567)
Preserve the captured compatibility patch histories and canonical upstream printer fixes. Reconcile ModuleGraph ownership with timer hooks, encoded CommonJS cache keys, and HTTP/TLS transport lifecycles; retain raw Buffer Dirents. Keep fork instruction naming and add focused integration regressions.
… test files The tmpdir test in os.test.js set TMPDIR to /boop and restored it by assigning the saved value. When TMPDIR was unset, the assignment stored the string "undefined". In a plain multi-file bun test run, os.tmpdir() then returned "undefined" for every later file, and each test that uses tmpdirSync() failed with ENOENT on realpath 'undefined'. Remove the mutation. The check of os.tmpdir() against the live environment stays. test/js/node/test/parallel/test-os.js covers os.tmpdir() following process.env (precedence, empty values, trailing slash) in its own process. rejectUnauthorizedScope() in harness.ts restored NODE_TLS_REJECT_UNAUTHORIZED the same way. It now deletes the variable when it was unset. (cherry picked from commit 1f554d1)
Resolve each worker graph module relative to its own module URL so inherited relative preloads retain the test runner working directory. Keep the graph identity and error assertions, and terminate the worker in finally on both success and failure.
Pair the live onwritable setter with the existing native drain shim after caching its async-context callback. Preserve done/null handling and pinned-write drainage. Replace kernel-buffer-size assumptions with isolated syscall-fault regressions that prove pending native bytes before success or peer reset.
vincentkoc
marked this pull request as ready for review
September 25, 2026 07:24
steipete
pushed a commit
to fuller-stack-dev/bun
that referenced
this pull request
Oct 20, 2026
…module-graph.test.ts (oven-sh#45674) ### What does this PR do? Fixes the flaky "50 graphs alive at once, each with its own state, then all exit and are collected" in `test/js/bun/module-graph/module-graph.test.ts`. It failed in 2 of 31 builds of main, 125686 to 127114 (Ubuntu 25.04 x64, Windows 11 aarch64) and passed on the retry. The test registered one array, `graphs[25].big`, with a `FinalizationRegistry` and failed if 100 collections did not finalize it. It now tracks the array of every one of the 50 graphs with `Lifetimes` from `module-graph-lifetimes.ts`, as `module-graph-gc.test.ts` does. There, an object that is not finalized counts as kept alive only if a root reaches it in the debugging heap snapshot, and the failure message is the path from that root. Two things change with the helper, and the first is what makes the runs below pass: 1. **Where the collection runs.** The helper calls `Bun.gc(true)` from a timer callback, main's `collected()` from the continuation of the async test. The `runInternalMicrotask` frame that holds the stale word (artifact 2) is not on the stack in a timer callback. In 240 of 240 runs all 50 arrays were finalized by the first collection. 2. **What is asserted if one is left.** Not that it was finalized, but that no root reaches it. ### Why it failed On main one of the 50 graphs outlives the collections in almost every run, and the test fails when that one is number 25. Whole file, CI's environment, 840 runs: | graphs left after the collections | 0 | 1 | 2 | 3 | |---|---|---|---|---| | runs | 2 | 802 | 3 | 33 | 12 of the 840 failed. In the failing runs looked at (9 heap snapshots, 12 stack dumps) nothing in the heap holds the one that is left, and one word on the native stack points at it. All of what follows is the Linux x64 binary that CI built for main at 7f3bc6a, with `BUN_GARBAGE_COLLECTOR_LEVEL=1 BUN_RUNTIME_TRANSPILER_CACHE_PATH=0` as in `scripts/runner.node.ts`. The failure needs both that environment and the whole file: 0 of 240 without the environment, 0 of 1600 with the test alone. I did not look at the Windows failure. <details><summary>Artifact 1: the heap snapshot</summary> `generateHeapSnapshotForDebugging()` right after the 100 collections. These are the array and every cell from which it can be reached: ``` snapshot: 27033 cells, 99750 edges, 586 roots; arrays named `big` still in it: 1 cell 1532 Promise 0x34cf520fa40 incoming edges 0 in `roots` no a root reaches it no cell 1555 ModuleRecord 0x34cf527e980 incoming edges 3 in `roots` no a root reaches it no cell 1573 ModuleNamespaceObject 0x34cef51dd50 incoming edges 3 in `roots` no a root reaches it no cell 1591 JSModuleEnvironment 0x34cf5278950 incoming edges 3 in `roots` no a root reaches it no cell 1626 Array 0x34cef3755a0 incoming edges 2 in `roots` no a root reaches it no cell 1631 Function 0x34cef45a100 incoming edges 2 in `roots` no a root reaches it no cell 1653 Function 0x34cef45a0e0 incoming edges 2 in `roots` no a root reaches it no ``` The snapshots of 8 other failing runs have the same seven kinds of cell, with the `Promise` (fulfilled with the `ModuleRecord`) as the only one without an incoming edge. </details> <details><summary>Artifact 2: the stack word and the frame that owns it (gdb, same run as artifact 1)</summary> The test writes the snapshot and sends itself SIGUSR2, and gdb stops there. ``` Thread 1 "bun-profile" received signal SIGUSR2, User defined signal 2. (gdb) info registers rsp rbp rsp 0x7fffffffa0c8 rbp 0x7fffffffa240 words in [rsp, end of stack) = [0x7fffffffa0c8, 0x7ffffffff000) that point into one of those cells: 1 0x7fffffffa8a0 holds 0x34cf520fa40 = Promise+0; it lies in the frame with rbp 0x7fffffffa8f0, at rbp-0x50 (gdb) x/gx 0x7fffffffa8a0 0x7fffffffa8a0: 0x0000034cf520fa40 (gdb) info symbol 0x1bccee0 # where that frame's callee returns to JSC::runInternalMicrotask(...) + 6976 rbp chain openclaw#3 rbp 0x7fffffffa540 Bun::Process_functionKill openclaw#4 rbp 0x7fffffffa550 (JIT code) openclaw#5 rbp 0x7fffffffa5d0 op_call_ignore_result_return_location openclaw#6 rbp 0x7fffffffa680 llint_call_javascript openclaw#7 rbp 0x7fffffffa7e0 JSC::asyncFunctionGeneratorBodyCall openclaw#8 rbp 0x7fffffffa8f0 JSC::runInternalMicrotask <- owns 0x7fffffffa8a0 openclaw#9 rbp 0x7fffffffab70 JSC::MicrotaskQueue::drainWithUseCallOnEachMicrotask openclaw#10 rbp 0x7fffffffac00 JSC::VM::drainMicrotasks openclaw#11 rbp 0x7fffffffac20 Zig::GlobalObject::drainMicrotasks openclaw#12 rbp 0x7fffffffac50 <bun_jsc::event_loop::EventLoop>::exit openclaw#13 rbp 0x7fffffffacf0 TimerObjectInternals::fire ``` 12 failing runs that dumped their own stack from `/proc/self/mem` show the same: one word, `Promise+0`, at `rbp-0x50` of `runInternalMicrotask`. In the 5 of them where I looked for it, the frame's callee returns to the same `0x1bccee0`, which is `JSMicrotask.cpp:2053`. **Who wrote it.** A hardware watchpoint on `0x7fffffffa8a0`, set at the first line of the test, sees 10 writes. The last one is the `Promise`: `pushq %r14` in the prologue of `JSC::ModuleGraphLoadingState::create` (`ModuleGraphLoadingState.cpp:71`, rbp `0x7fffffffa8b0`), which saves a register of its caller. **Why it stays.** The 100 collections run in the continuation of an async function, so each runs under a `runInternalMicrotask` frame at that same address. In the disassembly the function has 9 stores to `-0x50(%rbp)`. Following the jump table and every branch, only case 14 of the switch (resume an async function) reaches the call at `JSMicrotask.cpp:2053`, and none of the 9 stores is on a way to it. The slot is inside a live frame, so stack sanitizing does not cover it. So the graph that is left is the one whose load called `create` last at that depth. </details> ### How did you verify your code works? **Failure rate.** Whole file, 12 copies side by side, main and this PR in alternating rounds: | | main | this PR | |---|---|---| | runs that failed | 12 of 1200 (all this test) | 0 of 1200 | **What the snapshot says about a survivor.** With this PR there was none to ask about: in those 240 runs, with a logging copy of the helper, the snapshot was never taken. So this is main's test as it is, followed by the helper's `Heap` asked about the 50 addresses, 1080 runs. The old assertion failed in 12 of them. In 11 the array was in the snapshot with no root reaching it, in 1 it was gone by then, in 0 a root reached it. In 7 of the 1080 runs a root did reach two other arrays. In the one run whose paths were printed, both start at `root(JITWorkList)`, a compilation that is still running. `stillAlive` goes on collecting while a root reaches something. **Real references must fail.** One line added before `graphs.length = 0`. All 9 fail, with these messages: | graph 25 is held by | message | |---|---| | a global, the namespace | `root(ProtectedValues) GlobalObject -Property:held-> ModuleNamespaceObject -> ModuleRecord -> JSModuleEnvironment -> Array` | | a global closure over `inc` | `root(ProtectedValues) GlobalObject -Property:held-> Function -> JSLexicalEnvironment -Variable:inc-> Function(inc) -> JSModuleEnvironment -> Array` | | a local of the suspended test | `root(Output) FunctionCodeBlock -> ... -Variable:pendingHeap-> Promise -> AsyncFunctionGenerator -> ...` | | `setInterval(inc)` | `root(StrongHandles) StrongRootBlock -> Timeout -Property:callback-> Function(inc) -> JSModuleEnvironment -Variable:big-> Array` | | `process.on(..., inc)` | `root(ProtectedValues) GlobalObject -> Process -> Function(inc) -> JSModuleEnvironment -Variable:big-> Array` | | a reaction of a pending promise | `root(ProtectedValues) GlobalObject -Property:held-> Promise -> Function(inc) -> JSModuleEnvironment -Variable:big-> Array` | | a `FinalizationRegistry` held value | `root(ProtectedValues) GlobalObject -Property:held-> FinalizationRegistry -> Array` | | a `WeakMap` value of a live key | `root(Output) Array` | | an `AbortSignal` listener | `root(WeakSets) AbortSignal -> Function(inc) -> JSModuleEnvironment -Variable:big-> Array` | With `globalThis.held = graphs[7]` instead, main's test passes 5 of 5 and this PR's fails 5 of 5. **Debug build**, default timeout: the test passes 6 of 6 alone and in 6 of 6 runs of the whole file.
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?
Merge upstream Bun through
29d9638into the fork, preserving the existing 19 compatibility patches, their two worker/query prerequisites, and contributor history. The merge starts from9d7a822, so it also contains the printer backport and the Buffer Dirent backport.The integration preserves these contracts:
Conflict resolution combines the new ModuleGraph lifecycle and stricter builtin types with the retained behavior. It also updates the resolver's embedded-query normalization and the TLS registry call to their current upstream owners. The fork keeps its
AGENTS.mdconvention, including the new CI-image guidance.Qualification found one additional callback defect: uncorking could buffer bytes after
write()cleared the native drain hook. The liveonwritablesetter cached its callback without registering the native shim. The five-line repair pairs those registrations while preserving done/null, pinned-buffer, async-context, and reentrant behavior. Two kernel-capacity-dependent tests are replaced with isolated syscall-fault cases that prove actual pending bytes.The test-only follow-ups retain the credited environment-restoration fix and resolve worker graph fixtures relative to their own module URL, with termination in
finally.A post-publication static-analysis follow-up removes the unused UTF-16 NT-path conversion chain left after the Windows mkdir caller changed. It also moves primary TLS configuration replacement into
ServerConfig, keeping the validated configuration type and the existing post-native-success assignment/drop order. No lint baseline or suppression changes are included.Size attribution: the upstream import is 249 commits, 1,447 files, +116,229/-41,123 lines. Relative to upstream, the retained fork delta is production +3,645/-939 and tests +5,586/-75; this includes the existing compatibility patches. The new callback repair itself is production +5 and tests +98/-83.
How did you verify your code works?
Linux x86_64; LLVM/LLD 23.1.3 accepted by the native version validator; pinned Rust nightly-2026-09-15; debug ASAN and the default release ThinLTO build. Source, package manifests, and lockfiles were verified unchanged during qualification.
Final refactor head
bb9f7db6b5e55ac37c88eb289bd241fc4d851875:1.4.3-debug+bb9f7db6b.setSecureContext|PFX CAscases passed: 5 tests, 25 assertions, covering repeated swaps, an existing connection, pending DNS, and PFX/default-CA lifecycles. The PFX reference case used system Node 24.18.1.cargo test -p bun_paths: 29 passed, 0 failed; 2 documentation examples ignored.bun run rust:check-all: all 12 targets passed, none failed or skipped.49cbeb28was also clean at P0/P1.Qualified callback checkpoint
49cbeb2825b5d6ba128c1734ad8d04e0163c1945:bun run build:release run test:release js/node/http/node-http.test.ts— 187 passed, 1 skipped, 0 failed, 480 assertions. The explicittest:releasebinding selects the release executable.bun run rust:check-all: 12 targets passed, none failed or skipped. Native Clippy and workspace--all-targets --keep-goingpassed.1.4.3-canary.1+49cbeb282; SHA-256:39b07f9f09bd507ca0adedf082862d0807201e6f1790f06ccd52bd24e54e2259.Carried proof for unchanged inputs: at
f3382c7b, the original ten-file module order passed 1,402 tests with the default preload enabled; same-VM OS→perf passed 71 tests, standalone OS passed, and scoped TLS environment disposal passed all six cases. At compiled mergeaa8909b2, code generation, all five TypeScript configurations, and lint passed; direct release printer/Dirent tests passed 59 cases, including the executed 2 GiB printer regression. The callback checkpoint changes one HTTP Rust owner, two HTTP test files, and the changelog; the final refactor touches the four Rust files described above. These carried results are not presented as reruns on the final head.Known limits: the plain-HTTP Worker case reported the same 1,507,584-byte request-pool leak at prior
9d7a822and sync checkpointf3382c7bunder equivalent LSan validation. It remains tracked by upstream #37513; no suppression or teardown rewrite is included. Upstream #43499 covers a distinct later-write/owed-drain defect. Darwin and Windows runtime behavior was not executed; cross-target Rust results are compile proof. This PR does not claim every runtime test is green or that a deployment occurred.