Skip to content

chore(sync): merge upstream Bun through ba3f27d1d1 - #26

Merged
steipete merged 18 commits into
mainfrom
claude/sync-upstream-20260929
Sep 30, 2026
Merged

steipete merged 18 commits into
mainfrom
claude/sync-upstream-20260929

Conversation

@steipete

@steipete steipete commented Sep 30, 2026 •

Copy link
Copy Markdown

Merge upstream Bun through ba3f27d1d1ce359d4eed842c135f0f6fba1acb00 into fork main, retaining upstream and contributor history. Land with a merge commit to retain upstream ancestry. All fork fixes #15, #7, #14, and #27 are incorporated and qualified.

The five conflict resolutions preserve the fork’s behavior while integrating upstream changes:

  • Keep macOS ProcessRetry alongside upstream’s Tty event-loop flag.
  • Keep the richer worker execArgv record and parser for preloads, TLS trust, CPU profiling, and addon/FFI restrictions; incorporate upstream’s invalid process-only flag reporting and its C++ error channel.
  • Keep literal ? file-URL handling in the module loader alongside upstream’s string-code-generation guards.
  • Retain one upstream-positioned ERR_WORKER_INVALID_EXEC_ARGV mapping; both histories added it, and the automatic merge initially duplicated it.

The fork fixes landed since the previous sync ee83b78b18 remain present: file-URL preloads (#22), response-finish diagnostics (#23), and macOS silent-run signal/stdio handling (#24). Earlier fork changes are retained by the merge. Upstream’s addon/FFI worker restrictions overlap the fork’s broader implementation; the shared behavior is retained in one parser, with upstream’s new invalid-flag handling added.

WebKit remains f20ce7744553c910bcf16a33faf976af208de091 on both sides. Direct source inspection confirms that DFGSSALoweringPhase.cpp lowers StringAt, StringCharCodeAt, and StringCodePointAt to independent CheckInBounds nodes, and the pin includes JSTests/stress/string-index-dce-bounds-check.js. This is the upstream replacement for closed oven-sh/WebKit#578, so no pin rollback is needed. The release documentation now reflects that fix.

Final integration also retained both sides of the changelog conflict and added contributor credit for @SebTardif and @RomneyDa. The runtime plugin cache format remains version 34; the frozen upstream uses 33.

Native qualification exposed a pre-existing fork mismatch with two new upstream idle-sweep tests: cached idle state stays false until message timing clears, even after a bodyless response ends inside its handler. Explicit Node HTTP idle sweeps now derive response availability while preserving incomplete TLS handshakes, application-owned parser-error sockets, request bodies, partial heads, queued responses, and tunnels. Both upstream one-read/split-head tests pass unchanged, as does the existing parser-error ownership test. A TLS 1.2 relay control proves a sweep cannot close a handshake in progress. Node 26.10.0 confirms the bodyless close behavior.

Qualified head: 41dffc47212456d5ac80fc6fdddda08c4e4bfccc, macOS arm64 release build (Bun 1.4.3, WebKit f20ce7744553c910bcf16a33faf976af208de091). No local SDK signpost patch was needed. Binary, hardening, duplicate-symbol, formatting, and applicable hosted checks passed. Codex review has no remaining accepted/actionable P0–P2 findings; the rejected non-regular-copy concern is ruled out by unchanged regular-file guards and eight matching baseline/candidate FIFO/device controls.

File Pass Skip Todo Fail
test/js/bun/terminal/terminal.test.ts 97 2 0 0
test/js/bun/terminal/terminal-spawn.test.ts 23 2 0 0
test/js/bun/spawn/spawn.test.ts 165 24 0 0
test/js/node/child_process/child-process-stdio.test.js 9 0 0 0
test/js/node/http/node-http.test.ts 277 1 0 0
test/js/node/diagnostics_channel/diagnostics_channel.test.ts 26 0 3 0
test/js/node/sqlite/node-sqlite.test.ts 143 4 0 0
test/js/node/worker_threads/worker_threads.test.ts 172 0 0 0
test/cli/run/preload-test.test.js 2 0 3 0
test/cli/run/no-orphans.test.ts 15 9 0 0
test/cli/install/bun-install-lifecycle-scripts.test.ts 70 0 0 0
test/js/node/fs/fs.test.ts 660 16 0 0
test/js/node/fs/cp.test.ts 54 6 0 0
test/cli/run/transpiler-cache.test.ts 27 0 0 0
test/cli/test/isolation.test.ts 41 0 0 0
test/js/bun/plugin/plugins.test.ts 47 0 0 0
test/js/bun/plugin/plugin-namespace-drive-letter.test.ts 1 0 0 0
test/js/node/disallow-code-generation-from-strings.test.ts 28 0 0 0
test/js/node/http/node-http-server-abort-events.test.ts 105 0 0 0
test/js/node/http/node-http-server-close-drain.test.ts 31 0 0 0
test/js/node/http/node-http-connect.test.ts 80 1 2 0
test/js/node/http/node-http-upgrade-body.test.ts 11 2 0 0
test/js/node/http/node-http-req-socket-pause.test.ts 40 0 0 0
test/js/node/tls/node-tls-server.test.ts 99 0 0 0
test/js/node/tls/node-tls-wrapped-socket-close.test.ts 15 0 0 0
test/cli/install/bun-install-patch.test.ts 32 0 0 0
test/js/bun/io/bun-write.test.js (stream fallback only) 1 0 0 0
test/bundler/compile-argv.test.ts (compiled code-generation flags) 3 0 0 0
Total 2274 67 8 0

Filesystem and isolation suites used outer concurrency 2; nested stress work, assertions, and timeouts were unchanged. Lifecycle, TLS, and compiled-argument tests enabled the existing internal-test API at process startup (BUN_FEATURE_FLAG_INTERNAL_FOR_TESTING=1, BUN_GARBAGE_COLLECTOR_LEVEL=0). Initial lifecycle/TLS invocations without those startup flags could not load bun:internal-for-testing.

Earlier runs encountered recursive-readdir and copy-stress timeouts; the same readdir workload exceeded its deadline on the pre-sync baseline. Both full filesystem suites passed on the final head. The terminal ESRCH test missed its real kernel race window once (its path-reached assertion failed); the unchanged complete file passed on retry. The known broader Bun.write Response timeout was reproduced on a separately built pre-change baseline during #27 qualification and is not claimed as a passing full-suite run here; the added stream-fallback regression passes.

Additional proof: normal/strict data/blob imports and Workers behaved as expected in all 16 probes; the compiled-argument tests preserve quoted strict-mode floors. OpenClaw smoke with the built runtime passed: OpenClaw 2026.9.6 (23ad3a5). No tag or release is part of this PR.

robobun and others added 15 commits September 28, 2026 19:01
Fixes oven-sh#43666

### Problem
- With `linker = "isolated"` and `globalStore = true`, a project that
depends on `@types/bun` fails to type-check. tsc reports `error TS2307:
Cannot find module 'undici-types' or its corresponding type
declarations` seven times, from `bun.d.ts:701`, `fetch.d.ts:24-30` and
`globals.d.ts:56`.
- `packages/bun-types/package.json` declares only `@types/node`. The
`import("undici-types")` in those files resolved only because the
hoisted linker put `undici-types` next to `bun-types`. In the global
store, `bun-types` lives under `<cache>/links/` and can reach only the
packages it declares.

### Fix
- Add `"undici-types": "*"` to the dependencies of `bun-types`. The
range is `*` for the same reason `@types/node` uses `*`: bun dedupes it
to the copy that the project's `@types/node` already pins when both are
in the same major.
- Update the root `bun.lock` for the workspace entry. It dedupes to the
`[email protected]` that `@types/[email protected]` already pins.
- Verified: `test/integration/bun-types/bun-types.test.ts`, new block
"isolated install with the global store". It installs the packed
`bun-types` with the isolated linker and the global store, then runs
tsc. Without the fix it reports the seven TS2307 errors. The full file
passes with `bun bd test` and with the release binary.

### Background
- The global store (`docs/pm/global-store.mdx`) links every package from
one shared `<cache>/links/<name>@<version>-<hash>/node_modules/`
directory. Inside that directory, the package sees only the dependencies
it declares. TypeScript resolves symlinks, so a walk-up from a
`bun-types` file never reaches the project's `node_modules`.
- `undici-types` is the type package behind the `fetch` globals in
`@types/node` (`Headers`, `Request`, `Response`, `EventSource`).
`bun-types` imports those types as the fallback when `lib.dom` is not
loaded.
- The six remaining `TS2688: Cannot find type definition file for
'node'` errors in the issue come from `/// <reference types="node" />`
inside `undici-types` itself, which declares no `@types/node`
dependency. That is an upstream phantom dependency. A direct
`@types/node` devDependency in the project, or `publicHoistPattern =
["@types/*"]`, resolves it today.

<details><summary>Notes</summary>

- Version range: `@types/node` pins `undici-types` with a `~X.Y.0` range
per release. When a fresh install resolves `bun-types`'s `*` before
`@types/node`'s tilde range, bun keeps two copies (for example `8.10.2`
and `8.9.0`). Both are in the same major, and tsc output is unchanged in
that case. I compared tsc diagnostics for the hoisted linker with
`@types/node@20` and with `@types/node@26`, with and without this
change: identical.
- A pinned range (`~8.9.0`) would dedupe today but would drift from
`@types/node` at its next pin bump, so every `bun-types` release would
need a manual bump.
- The reporter's suggestion to special-case `undici-types` in the
installer is not part of this change. The global store behaviour is
documented as intentional.
- Suites run: `test/integration/bun-types/bun-types.test.ts` (22 tests,
release binary, all pass; debug binary, 9 pass and 13 skip as designed).
</details>

<!-- robobun:evidence:begin -->

---

**[policy-decision:dep]** gate passed · iteration 0 · 3 files touched

<details><summary>fails on main (without fix)</summary>

```console
ASAN without fix: 1 failed, 13 skipped
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/pr_gate.xml" test/integration/bun-types/bun-types.test.ts
bun test v1.4.3 (367d939)

test/integration/bun-types/bun-types.test.ts:
(pass) @types/bun integration test > building and packing bun-types leaves packages/bun-types untouched [2.09ms]
(pass) @types/bun integration test > packed bun-types includes CLAUDE.md [5.52ms]
(skip) @types/bun integration test > basic type checks > checks without lib.dom.d.ts
(skip) @types/bun integration test > TypeScript latest > checks without lib.dom.d.ts
(skip) @types/bun integration test > TypeScript 7.1 > checks the fixture and import attributes through ts7.1/index.d.ts
(pass) @types/bun integration test > Bun.mmap > MMapOptions accepts offset and size [676.14ms]
(pass) @types/bun integration test > TextDecoder > accepts the encoding labels the runtime supports [654.45ms]
(pass) @types/bun integration test > TextDecoder > the fixture label table matches the runtime [33.70ms]
(pass) @types/bun integration test > Event and EventTarget > lib.dom's composedPath() declaration wins when lib.dom is loaded [680.19ms]
... (truncated)

release without fix: 1 FAILED
bun test v1.4.3-canary.1 (367d939)

test/integration/bun-types/bun-types.test.ts:
(pass) @types/bun integration test > building and packing bun-types leaves packages/bun-types untouched [0.10ms]
(pass) @types/bun integration test > packed bun-types includes CLAUDE.md [0.38ms]
(pass) @types/bun integration test > basic type checks > checks without lib.dom.d.ts [2976.19ms]
(pass) @types/bun integration test > TypeScript latest > checks without lib.dom.d.ts [502.41ms]
(pass) @types/bun integration test > TypeScript 7.1 > checks the fixture and import attributes through ts7.1/index.d.ts [402.25ms]
(pass) @types/bun integration test > Bun.mmap > MMapOptions accepts offset and size [60.25ms]
(pass) @types/bun integration test > TextDecoder > accepts the encoding labels the runtime supports [67.48ms]
(pass) @types/bun integration test > TextDecoder > the fixture label table matches the runtime [0.87ms]
(pass) @types/bun integration test > Event and EventTarget > lib.dom's composedPath() declaration wins when lib.dom is loaded [90.81ms]
(pass) @types/bun integration test > Event and EventTarget > the Node-style composedPath() tuple applies without lib.dom [68.97ms]
(pass)
... (truncated)
```

</details>

<details><summary>passes on PR (with fix)</summary>

```console
ASAN with fix: 13 skipped
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/pr_gate.xml" test/integration/bun-types/bun-types.test.ts
bun test v1.4.3 (367d939)

test/integration/bun-types/bun-types.test.ts:
(pass) @types/bun integration test > building and packing bun-types leaves packages/bun-types untouched [2.42ms]
(pass) @types/bun integration test > packed bun-types includes CLAUDE.md [5.40ms]
(skip) @types/bun integration test > basic type checks > checks without lib.dom.d.ts
(skip) @types/bun integration test > TypeScript latest > checks without lib.dom.d.ts
(skip) @types/bun integration test > TypeScript 7.1 > checks the fixture and import attributes through ts7.1/index.d.ts
(pass) @types/bun integration test > Bun.mmap > MMapOptions accepts offset and size [749.59ms]
(pass) @types/bun integration test > TextDecoder > accepts the encoding labels the runtime supports [652.20ms]
(pass) @types/bun integration test > TextDecoder > the fixture label table matches the runtime [35.07ms]
(pass) @types/bun integration test > Event and EventTarget > lib.dom's composedPath() declaration wins when lib.dom is loaded [702.93ms]
... (truncated)

release with fix: all passed
$ bun scripts/build.ts --profile=release
[configured] bun-profile → bun (stripped) in 723ms (unchanged)
ninja: Entering directory `/workspace/bun/build/release'
[1/6] rustc bun_runtime → libbun_runtime.a
[2/6] link bun-profile
ld.lld: warning: Linking two modules of different target triples: 'obj/unified/UnifiedSource-src_jsc_bindings-0.cpp.o' is 'x86_64-pc-linux-gnu' whereas '../../../../root/.bun/build-cache/webkit-63a807e88ce0f37e-lto/lib/libJavaScriptCore.a(UnifiedSource-inspector-2.cpp.o at 102507718)' is 'x86_64-unknown-linux-gnu'


ld.lld: warning: Linking two modules of different target triples: 'obj/unified/UnifiedSource-src_jsc_bindings-1.cpp.o' is 'x86_64-pc-linux-gnu' whereas '../../../../root/.bun/build-cache/webkit-63a807e88ce0f37e-lto/lib/libJavaScriptCore.a(UnifiedSource-inspector-2.cpp.o at 102507718)' is 'x86_64-unknown-linux-gnu'


ld.lld: warning: Linking two modules of different target triples: 'obj/vendor/mimalloc/src/static.c.o' is 'x86_64-pc-linux-gnu' whereas '../../../../root/.bun/build-cache/webkit-63a807e88ce0f37e-lto/lib/libJavaScriptCore.a(UnifiedSource-inspector-2.cpp.o at 102507718)' is 'x86_64-unknown-linux-gnu'


ld.lld: warning
... (truncated)
```

</details>

<details><summary>diff hotspot</summary>

```
bun.lock                                     |  2 +-
 packages/bun-types/package.json              |  3 +-
 test/integration/bun-types/bun-types.test.ts | 77 +++++++++++++++++++++++++++-
 3 files changed, 78 insertions(+), 4 deletions(-)
```

</details>

**gate history** · 1 passed · 0 rejected · iteration 0

<details><summary>evidence per changed file</summary>

```
file                                          reads  edits  tests
bun.lock                                          0      0      7
packages/bun-types/package.json                   1      2      8
test/integration/bun-types/bun-types.test.ts      1      3      7
```

</details>

**root cause** · written by the author bot

The `bun-types` package imported from `undici-types` in several
declaration files but only declared `@types/node` as a dependency, a gap
that the hoisted linker masked by making `undici-types` resolvable
anyway. Under the isolated linker with the global store, `bun-types` is
placed in the cache links directory and can resolve only what it
declares, so TypeScript reported TS2307 errors for every
`import("undici-types")`. The fix adds `"undici-types": "*"` to
`packages/bun-types/package.json` so the import resolves in all install
layouts, with the separate TS2688 errors left as an upstream is…

<!-- robobun:evidence:end -->
…every way a string becomes code (oven-sh#44171)

### What does this PR do?

Adds `--disallow-code-generation-from-strings`, at two levels.

| Flag | What it refuses |
|---|---|
| `--disallow-code-generation-from-strings` | `eval()` and the
`Function` constructors. Node.js's flag, with Node.js's behaviour. |
| `--disallow-code-generation-from-strings=strict` | Every way a string
becomes code in the process. Bun only. |

A refusal is a synchronous, catchable `EvalError: Code generation from
strings disallowed for this context`, which is Node.js's message.
`import()` of a refused URL rejects with it. A value other than `strict`
is a startup error.

The use is a long-running server, usually a `bun build --compile`
executable, that wants a guarantee that no string becomes code after
startup: in any `Worker`, any realm, and any `Bun.ModuleGraph`.

#### The level is the process's

It is set at startup and is only ever raised.

- There is no API that lowers it.
- Every `Worker` has it, whatever `execArgv` the `Worker` is given. A
`Worker` whose `execArgv` contains the flag throws as in Node.js: an
`Error` with the code `ERR_WORKER_INVALID_EXEC_ARGV` and Node.js's
message, whether or not the process has the flag, so `execArgv:
process.execArgv` throws in a process that does. The check is in
`parse_worker_exec_argv_flags`, with the other flags a Worker's
`execArgv` can carry.
- Every global object Bun makes later has it: `ShadowRealm`, `bun test`
isolation, and under `=strict` every `node:vm` context, including one
made with `codeGeneration: { strings: true }`.
- The level a compiled executable is built with (`--compile-exec-argv`)
is a floor. The argument parser keeps an option's last value and reads
`BUN_OPTIONS` after the embedded flags, so on its own it would let the
environment lower it. Bun raises the level from the embedded flags
themselves, read as the parser is given them (after `append_options_env`
has taken quotes and backslashes off).

Given more than once on a command line, the last one counts, as for any
option. There is no change to the argument parser: `--flag` and
`--flag=strict` are what its existing optional value (`<STR>?`, as
`--inspect` uses) already reads.

#### What each level refuses

| A string becomes code through | Flag | `=strict` |
|---|---|---|
| `eval()`, direct and indirect | refused | refused |
| `Function`, and the async, generator and async generator constructors,
reached any way | refused | refused |
| `ShadowRealm.prototype.evaluate()`, and `eval()` inside a
`ShadowRealm` | refused | refused |
| `vm.Script`, `runInThisContext`, `runInContext`, `runInNewContext`,
`compileFunction`, `SourceTextModule` | allowed | refused |
| `eval()` inside a `node:vm` context | allowed | refused |
| `module._compile()`, and a `require.extensions` handler that calls it
| allowed | refused |
| Assigning a different `Module.wrapper` | allowed | refused |
| `import`, `import()` and `require()` of a `data:` or `blob:` URL |
allowed | refused |
| A `Worker` from a `data:` or `blob:` URL, or with `eval: true` |
allowed | refused |
| A plugin that returns `contents` for the `js`, `jsx`, `ts` or `tsx`
loader | allowed | refused |
| `inspector.open()`, `bun:jsc`'s `startRemoteDebugger()` | allowed |
refused |
| `napi_run_script()` | allowed | refused |
| `$vm`, JavaScriptCore's debugging global (`BUN_JSC_useDollarVM=1`) |
not defined | not defined |

The debugger evaluates what its client sends and turns the engine's eval
setting back on to do it, so `=strict` refuses it. Asking for it with
`--inspect`, `--inspect-wait`, `--inspect-brk` or `BUN_INSPECT` is a
startup error. `BUN_INSPECT_CONNECT_TO` is ignored with a warning and
the program runs: Bun's VS Code extension sets it in every integrated
terminal by default, so it does not mean that anybody asked to debug
this process. Nothing connects.

`$vm` evaluates strings (`evaluateWithScopeExtension`, `createBuiltin`)
and makes global objects that are not Bun's, where `eval()` is on.
Release builds are not affected: Bun's WebKit compiles it in only with
assertions (`BUN_ENABLE_JSDOLLARVM` is `ASSERT_ENABLED`), and on 1.4.0
`BUN_JSC_useDollarVM=1` sets the option and defines nothing. In a debug
build it ran strings at both levels, so `useDollarVM` is forced off
after the `BUN_JSC_*` overrides are applied, which makes a debug build
behave as a release build does.

`node:inspector`'s in-process `Session` needs no gate: it does not
implement `Runtime.evaluate`, `compileScript`, `runScript`,
`callFunctionOn` or `Debugger.evaluateOnCallFrame`, and its other
`Debugger` methods need `inspector.open()`. Nothing else in `bun:jsc`,
`bun:internal-for-testing` or the other `bun:` modules runs source text.

Not affected at either level: importing files (literal or computed
specifiers, and modules embedded in a compiled executable), `new
Worker(file)`, `require()` of files and builtins, `Bun.ModuleGraph`,
`JSON.parse`, `RegExp`, `eval()` of a non-string, WebAssembly, native
addons, `vm.createContext()`, `vm.SyntheticModule`, and a plugin that
returns an `exports` object or `contents` for a data loader.

#### How it works

- `bun_core::CodeGenerationFromStrings` is one process-wide atomic,
raised with `fetch_max`. C++ reads it through
`Bun__codeGenerationFromStrings()`.
- `Zig::GlobalObject::finishCreation` calls JavaScriptCore's existing
`setEvalEnabled(false, message)` when the level is not `Allowed`. That
covers `eval`, the `Function` constructors and `ShadowRealm` for the
main global, Workers, `ShadowRealm` globals and `bun test` isolation
globals. No WebKit change.
- A `node:vm` context keeps its own `codeGeneration.strings` under the
bare flag, as in Node.js, and is forced off under `=strict`.
- What Bun compiles from a string itself asks
`Bun::mayNotMakeScriptFromStrings()`. `data:` and `blob:` modules are
refused where module source is fetched (`fetchESMSourceCode`,
`fetchCommonJSModule`), so `import`, `import()` and `require()` share
one check.

#### Also in this PR

- `bun:ffi` `cc()` built its wrapper for a symbol that returns a
`cstring` with `new Function`, so it would have thrown at both levels.
The generated function only called through and wrapped the result, which
the fixed-arity closures beside it now do.
- `process.execArgv` treated a flag with an optional value (`--inspect`,
this one) as taking the next argument, so `bun
--disallow-code-generation-from-strings script.js` listed `script.js`.
An optional value is only ever written `--name=value`.
- `ERR_WORKER_INVALID_EXEC_ARGV` is new to Bun, and only this flag
produces it. What `web_worker.rs` refuses reaches script through an
`ExceptionCode`, which already has entries for Node.js codes
(`EVENT_RECURSION`). This adds `WORKER_INVALID_EXEC_ARGV`, and
`WebWorker__create` has an out-parameter that says when it applies.
- The flag has no help text, which hides it from `bun --help`, like the
other long Node.js flags: its name is wider than the 30 columns that
names are printed in. It is documented in
`docs/runtime/code-generation-from-strings.mdx`.

#### What stops working in Bun itself

I searched all of `src/js` for `eval`, the `Function` constructors,
`node:vm` and `_compile`.

| Part of Bun | Flag | `=strict` |
|---|---|---|
| The development server: `import()` with import attributes of a module
outside the bundle (`new Function` in `hmr-module.ts`) | throws | throws
|
| `node:repl`: `repl.start()`, `REPLServer` | works | throws |
| `node:worker_threads`: `eval: true` | works | throws |

Every built-in module still loads under `=strict`. I required each entry
of `builtinModules` and read every own property: `repl.REPLServer` is
the only public one that throws, so `import { REPLServer } from
"node:repl"` is the one import that fails. `bun test` runs under it,
including `mock.module()` and inline snapshots.

#### Outside the flag

- A program that writes a file and imports it runs that file.
- `BUN_OPTIONS` is still read by a compiled executable. It cannot lower
the level, but `--preload` in it loads a file before the entry point.
- `BUN_BE_BUN=1` makes a compiled executable run as the `bun` CLI. The
embedded program does not start and the flags embedded with it do not
apply. A compile-time option to ignore both variables is a separate
change.
- A literal `data:` import is resolved by the bundler at build time, so
in a compiled executable it is part of the program. A `data:` URL
computed at run time is refused.

### How did you verify your code works?

macOS arm64, debug build.

Node.js v25.9.0 with `--disallow-code-generation-from-strings`, which
the bare flag matches:

```
direct eval                  REFUSED EvalError: Code generation from strings disallowed for this context
indirect eval                REFUSED EvalError: Code generation from strings disallowed for this context
new Function                 REFUSED EvalError: Code generation from strings disallowed for this context
fn.constructor               REFUSED EvalError: Code generation from strings disallowed for this context
AsyncFunction                REFUSED EvalError: Code generation from strings disallowed for this context
vm.runInThisContext          ALLOWED 2
vm.runInNewContext           ALLOWED 2
new vm.Script                ALLOWED object
vm.compileFunction           ALLOWED 2
eval inside vm new context   ALLOWED 2
module._compile              ALLOWED 2
import(data:)                ALLOWED 2
WebAssembly.compile          ALLOWED ok

Worker, no execArgv           REFUSED EvalError execArgv=["--disallow-code-generation-from-strings"]
Worker, execArgv: []          REFUSED EvalError execArgv=[]
Worker, execArgv: [the flag]  ERR_WORKER_INVALID_EXEC_ARGV
```

Tests:

- `test/js/node/disallow-code-generation-from-strings.test.ts` (new, 28
tests). One fixture runs every route in the tables above, plus Workers
and a `Bun.ModuleGraph` with a `globals` overlay (inside `run()`, called
by the host directly, and after `dispose()`), with no flag, the bare
flag, and `=strict`. Also: given more than once, the last counts, in
four orders and sources; the flag after the script's name is the
script's argument; an unknown value, and each way of asking for the
inspector under `=strict`, is a startup error; `BUN_INSPECT_CONNECT_TO`
is ignored with a warning and nothing connects to a listener that a
process without `=strict` does connect to; `BUN_JSC_useDollarVM=1` does
not define `$vm` with the flag (and, in a debug build, does without it);
a Worker's `execArgv` with the flag throws, at each level of the
process, and the same script run under Node.js gives the same output
with no flag and with the bare flag; `bun test` runs its files at each
level in one process, with `--isolate` and with `--parallel` (the
`--parallel` cases fail when the flag is not passed on to the processes
it starts).
- Passes with the debug build. With `USE_SYSTEM_BUN=1` (1.4.0), 23 of
the 28 fail. The five that pass check things that were already so: the
flag after the script's name is the script's argument, a release build
has no `$vm`, and `bun test` with no flag in its three modes.
- `test/bundler/compile-argv.test.ts`: three new cases compile an
executable with the flag in `compile.execArgv` and check the refusals
and `process.execArgv` on the main thread, in a Worker, and in a Worker
given `execArgv: []`, twice with `BUN_OPTIONS` set to the bare flag, one
of those with the embedded flag in quotes. All three also pass the bare
flag on the executable's own command line, which is not read as flags,
and set `BUN_JSC_useDollarVM=1`. The first of those fails when the floor
is disabled, and the quoted one fails on the commit before its fix.
- `test/napi/napi.test.ts -t napi_run_script` (6, two new). The new
tests load the real addon from their own fixture, because the shared
`main.js` reads its arguments with `eval()`. With the bare flag,
`eval()` throws and `napi_run_script` returns its result, in Bun and in
Node.js alike. With `=strict`, the same call throws the `EvalError`.
- `test/cli/bun.test.ts -t help` (26) and the `bun-run.test.ts` cases
that pass `-c=` (4) pass.
- `test/js/node/module/node-module-module.test.js` (50),
`test/js/node/no-addons.test.ts` (2) and
`test/js/node/process/process.test.js -t execArgv` (2) pass.

Not verified:

- The two new `bun:ffi` tests in `test/js/bun/ffi/cc.test.ts` are
skipped on an ASAN build, as the rest of that file's `cc()` tests are,
so they did not run locally. They ran and passed in CI on Linux. The
same script, run by hand on macOS, works with no flag, the bare flag and
`=strict`.
- The development-server row comes from reading `hmr-module.ts`, not
from running the dev server.
- Linux and Windows: not built or run locally. In CI at 7964abc, the
last commit that changes code, every test shard passed on Debian 13
(x64, aarch64 and x64 with ASAN), Ubuntu 25.04 and Alpine 3.23 (x64 and
aarch64 each), Windows (2019 x64 and 11 aarch64) and macOS aarch64. The
logs show `disallow-code-generation-from-strings.test.ts` running in
shards that passed on Debian 13 x64, Debian 13 aarch64 and Windows 2019
x64. The two macOS x64 jobs had not finished when this was written. The
one commit since then changes only the docs page.
…ven-sh#44032)

### What does this PR do?

Two `node:http` server fixes that follow oven-sh#43557, plus four Node tests
that now pass. The second `listen()` was listed as a known difference in
oven-sh#43557 and came up in its review.

| Area | Before | After (same as Node) |
| --- | --- | --- |
| `listen()` on a server that is already listening | Starts a second
native listener. The first keeps accepting requests and holds the
process after `close()`. | Throws `ERR_SERVER_ALREADY_LISTEN`, before
the callback or the abort signal is registered. |
| `close()` and `closeIdleConnections()` with a connection that has sent
no request | The connection is not idle, so `close()` waits for it. |
The connection is closed, like Node since nodejs/node@417aacbc365. For
TLS this holds from the end of the handshake. A connection that has sent
part of a request head is left alone. |
| The same, for a connection from `emit('connection')` or http2
`allowHTTP1` | A connection that has sent nothing is kept. A partial
head is protected only on the first request. | The same rule as above:
busy from the first byte of a request to its end. |

Known difference: two `listen(port, host)` calls in the same tick throw
in Bun. Node 26.5 does not throw there, because its handle is still null
during the DNS lookup, and it emits `'listening'` once. Bun binds at
once. Without a host, both throw.

Code that calls `listen()` twice by accident now throws at startup, like
in Node. One test in this repository did (`fetch-leak.test.ts`).

Vendored Node tests (v26.5.0):

| Test | main before oven-sh#43557 | Now |
| --- | --- | --- |
| `test-http-server-close-idle-connections-pre-request.js` | fail | pass
(needs this PR) |
| `test-http-raw-headers.js` | fail | pass (since oven-sh#43557) |
| `test-http-agent-free-socket-data-guard.js` | fail | pass (since
oven-sh#43557) |
| `test-http-response-drain-cork.js` | pass | pass (was never vendored)
|

### How did you verify your code works?

Local runs are on a macOS arm64 debug build. The accept order on Linux
was traced on a Linux x64 CI build of this branch.

| Check | Result |
| --- | --- |
| 7 new tests in `node-http-server-close-drain.test.ts` | Pass. Each
fails without its fix. |
| Four connection states on the `emit('connection')` path (fresh,
partial first head, idle keep-alive, partial second head) | The same as
Node 26.5 |
| `node-http-connect.test.ts`: the test that re-emits a CONNECT socket |
It calls `close()` before the re-emit now. In the old order Node 26.4
and 26.5 destroy the socket at once, and so does this branch. |
| The vendored pre-request test | Passes. Fails without the fix. |
| Every file in `test/js/node/http`, plus node-http2, ws, bun-server,
serve, express `res.send`, socket.io-close (40 files) | 39 pass.
`serve.test.ts` has 2 failures ("bounds memory when proxying ... to a
stalled client") that also fail on a debug build of main. |
| 101 vendored Node server, close, keep-alive, listen and timeout tests
| 101 exit 0 |
| Every test that uses `emit('connection')`, `allowHTTP1` or
`closeIdleConnections` (48 test files) | Pass |
…44169)

### Problem

- An assert-enabled build (debug, ASAN) aborts with `panic: assertion
failed: self.cap > 0` in `StringBuilder::writable()`. `bun install`
reaches it with a hosted-git shortcut that ends at the colon, like
`"overrides": { "zz": "github:" }`.
- `allocate()` stores a pointer also for a count of 0 bytes.
`writable()` and `allocated_slice()`
(`src/bun_core/string/StringBuilder.rs:201-226`) asserted `cap > 0` for
each builder with a pointer.

### Fix

- `writable()` asserts `len <= cap`, the precondition of its pointer
arithmetic. This removes the abort.
- `allocated_slice()` loses the same assert. The Postgres call site
drops its oven-sh#22558 guard and reads `written_slice()`. No path on main
fails there.
- Verified: `test/cli/install/hosted-git-info/`. On a debug build of
main, 5 install tests and the guard of 13 parser rows fail (timeouts).
All 18 pass with the fix. Two unit tests cover both views (Miri).
- Self-reviewed: 2 concerns raised, 2 addressed.

### Background

- `StringBuilder` counts each slice, allocates one buffer, then appends
into it.
- `HostedGitInfo` mirrors npm's hosted-git-info. Both return `project:
""` for `github:`. The tests record that output, not a new contract.
- Considered a guard in `HostedGitInfo::copy_from`. It adds a release
branch and leaves the assert false. Bake `computeChunks` (oven-sh#20998) and
Postgres `ErrorResponse` (oven-sh#22558) hit it before.

### Downsides

- Assert-enabled builds lose the `cap > 0` check. A builder that counted
nothing and appends bytes still panics on the bounds check.
- Release: 0 bytes changed in 4 `StringBuilder` symbols and 3 callers.
Only `error_response_jsc::to_js` changes: 4412 -> 4400 B.

<details><summary>Notes</summary>

**Origin.** A fuzzer found the abort on an assert-enabled build. No
issue exists. Only linux x64 was run.

**Proof runs (debug build).**

- Source of main (a4f1429): 5 of 5 new install tests fail. The
`beforeAll` hook of the 13 parser rows fails too, so these rows do not
run. Each failure shows `timed out after 5000ms`, not an assertion diff.
The child that aborts needs 5 s or more to print its stack trace. The
late output has `panic: assertion failed: self.cap > 0`.
- This PR: 18 of 18 pass.
- The new tests pass on a release build of main, because a release build
has no assert. `USE_SYSTEM_BUN=1` cannot show the failure.
-
`test/regression/issue/postgres-stringbuilder-assertion-aggressive.test.ts`
passes on main and on this PR. It does not tell the two apart.
- No caller reaches `allocated_slice()` with a zero-capacity buffer now.
The Postgres call site was the one caller that could, and it reads
`written_slice()`. `allocated_slice()` makes a slice over the whole
capacity, and only the first `len` bytes are written.
- Two unit tests in `StringBuilder.rs` take an empty builder through
`writable()`, `allocated_slice()`, `append()`, `written_slice()` and
`move_to_slice()`. `cargo miri test -p bun_core --lib string_builder`
runs them: 2 pass. With one of the old asserts back, 2 fail. CI does not
run them. `cargo test -p bun_core` does not link, and the Miri job does
not list `bun_core`, because other tests of that crate call foreign
functions.

**Measurements.** Release builds of main (a4f1429) and of this PR,
same toolchain.

- release code, 4 StringBuilder symbols and 3 inlining callers: 0 bytes
changed, 0 instructions differ (objdump). The symbols are
`StringBuilder::allocate`, `append`, `append_count`, `add_concat`,
`HostedGitInfo::from_url`, `HTTPClient::clone_metadata` and
`bun_picohttp::Response::clone`.
- release .text: +0 B (readelf, 58,143,477 B on main and on the PR).
`error_response_jsc::to_js`: 4412 -> 4400 B. It is the only one of
78,610 text symbols that changes size.
- from_url instructions per call (`github:user/repo#main`): 2596 -> 2596
(gdb `stepi` count over the call, JIT off). valgrind is not installed in
the container.
- allocator calls per from_url call: malloc 7, zalloc 1, realloc 0, free
7 on PR (main: 7, 1, 0, 7).
- syscalls, `bun install` on the override fixture: file 67 -> 67, read
18 -> 18, write 3 -> 3, network 0 -> 0 (gdb `catch syscall`). strace is
not installed in the container.
- assert-enabled checks per view call: `allocated_slice` 1 -> 0,
`writable` 1 -> 1.
- `len <= cap` in `writable()`: 0 assertion failures in 8 existing test
files on the debug build. The files are the three in
`test/cli/install/hosted-git-info/`,
`test/cli/install/overrides.test.ts`,
`test/bundler/bundler_compile.test.ts`,
`test/js/web/fetch/fetch.test.ts`, `test/js/bun/spawn/spawn.test.ts` and
the Postgres test above. `fetch.test.ts` has the same 25 failures on
main and on the PR. On the PR run, 2 more tests of
`bundler_compile.test.ts` and 4 more tests of `spawn.test.ts` reached
the 5000 ms timeout. All 6 pass with a longer timeout. The host had a
load average above 250 during the runs.

**Callers.** `bun_core::StringBuilder` has 27 construction sites in 18
files: 19 direct and 8 through `HeaderBuilder::default()`. `writable()`
has 10 callers outside the builder. Each one indexes the returned slice
with bounds checks and adds to `len` only what it wrote. So `len <= cap`
holds for them.

**Sites left as they are.**

- `src/runtime/valkey_jsc/js_valkey.rs:657-675` and
`src/bundler/linker_context/computeChunks.rs:551-555` skip the builder
when there is nothing to build. They also skip work, so they stay.
- Open PR oven-sh#43942 sizes a buffer above the exact sum because of this
assert. It can use the exact sum after this PR.

**Tests.**

- The install tests are in
`hosted-git-info/boundary-conditions.test.ts`, not in
`overrides.test.ts`. That file installs from the public npm registry,
and these tests are about the spec parser.
- The `dependency github:` test records what release bun does for that
spec today. It sends one `GET /repos//tarball/` and exits with code 1.
The test uses a local server through `GITHUB_API_URL`.
- The expected objects in `from-url.test.ts` are the output of
hosted-git-info 9.0.0 on node 26.3.0 for the same 13 inputs.
- The 13 parser rows call the parser in the test process. A `beforeAll`
hook runs `bun install` with the override `github:` in a child process
first. An abort in the parser fails the hook, and the rows do not run. A
child process that imports `bun:internal-for-testing` needs 2 s to 5 s
on a debug build under load. That is too near the 5000 ms default.
- The `bun.lock` test compares each stderr line that names the lockfile.
`bun install` prints `Ignoring lockfile` and continues when it cannot
load `bun.lock`.
- One `bun install` covers the override values of all five providers.

**Differences from hosted-git-info 9.0.0 that this PR does not change.**

- `github:user/repo%2Egit`: the reference returns project `repo`, bun
returns `repo.git`.
- `github:%`: the reference returns `undefined`, `hostedGitInfo.fromUrl`
in bun throws `Invalid Git URL: InvalidURL`.
- `github:/.git`: the reference returns project `""`, bun returns `git`.
`new URL("github:/.git").pathname` is `git` in bun. Open PR oven-sh#39457
covers that.

</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: 6 failed, 32 skipped
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/pr_gate.xml" test/cli/install/hosted-git-info/boundary-conditions.test.ts test/cli/install/hosted-git-info/from-url.test.ts
bun test v1.4.3 (367d939)

test/cli/install/hosted-git-info/from-url.test.ts:
killed 1 dangling process
(fail) fromUrl > shortcuts with an empty user, project and committish > (unnamed) [5008.49ms]
  ^ a beforeEach/afterEach hook timed out for this test.
(pass) fromUrl > valid urls > bitbucket > parses bitbucket:foo/bar [11.72ms]
(pass) fromUrl > valid urls > bitbucket > parses bitbucket:foo/bar#branch [4.62ms]
(pass) fromUrl > valid urls > bitbucket > parses bitbucket:user@foo/bar [3.28ms]
(pass) fromUrl > valid urls > bitbucket > parses bitbucket:user@foo/bar#branch [1.22ms]
(pass) fromUrl > valid urls > bitbucket > parses bitbucket:user:password@foo/bar [1.26ms]
(pass) fromUrl > valid urls > bitbucket > parses bitbucket:user:password@foo/bar#branch [3.13ms]
(pass) fromUrl > valid urls > bitbucket > parses bitbucket::password@foo/bar [0.94ms]
(pass) fromUrl > valid urls > bitbucket > parses bitbucket::password@foo/bar#branc
... (truncated)

release without fix: 32 skipped
bun test v1.4.3-canary.1 (6780601)

test/cli/install/hosted-git-info/from-url.test.ts:
(pass) fromUrl > shortcuts with an empty user, project and committish > parses github: [2.39ms]
(pass) fromUrl > shortcuts with an empty user, project and committish > parses gitlab: [0.07ms]
(pass) fromUrl > shortcuts with an empty user, project and committish > parses bitbucket:
(pass) fromUrl > shortcuts with an empty user, project and committish > parses gist:
(pass) fromUrl > shortcuts with an empty user, project and committish > parses sourcehut: [1.02ms]
(pass) fromUrl > shortcuts with an empty user, project and committish > parses github:.git [0.01ms]
(pass) fromUrl > shortcuts with an empty user, project and committish > parses github:/
(pass) fromUrl > shortcuts with an empty user, project and committish > parses github:// [0.01ms]
(pass) fromUrl > shortcuts with an empty user, project and committish > parses github:#
(pass) fromUrl > shortcuts with an empty user, project and committish > parses github:?x
(pass) fromUrl > shortcuts with an empty user, project and committish > parses github:@
(pass) fromUrl > shortcuts with an empty user, project and committish > parses
... (truncated)
```

</details>

<details><summary>passes on PR (with fix)</summary>

```console
ASAN with fix: 32 skipped
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/pr_gate.xml" test/cli/install/hosted-git-info/boundary-conditions.test.ts test/cli/install/hosted-git-info/from-url.test.ts
bun test v1.4.3 (367d939)

test/cli/install/hosted-git-info/from-url.test.ts:
(pass) fromUrl > shortcuts with an empty user, project and committish > parses github: [4.28ms]
(pass) fromUrl > shortcuts with an empty user, project and committish > parses gitlab: [1.19ms]
(pass) fromUrl > shortcuts with an empty user, project and committish > parses bitbucket: [0.91ms]
(pass) fromUrl > shortcuts with an empty user, project and committish > parses gist: [0.75ms]
(pass) fromUrl > shortcuts with an empty user, project and committish > parses sourcehut: [0.82ms]
(pass) fromUrl > shortcuts with an empty user, project and committish > parses github:.git [1.52ms]
(pass) fromUrl > shortcuts with an empty user, project and committish > parses github:/ [2.71ms]
(pass) fromUrl > shortcuts with an empty user, project and committish > parses github:// [0.98ms]
(pass) fromUrl > shortcuts with an empty user, project and committish > parses git
... (truncated)

release with fix: 32 skipped
$ bun scripts/build.ts --profile=release
[configured] bun-profile → bun (stripped) in 6641ms (unchanged)
ninja: Entering directory `/workspace/bun/build/release'
[1/89] build.rs build_script_build
[2/89] rustc bun_platform 
[3/89] rustc bun_core 
[4/89] rustc bun_boringssl_sys 
[5/89] rustc bun_safety 
[6/89] rustc bun_cares_sys 
[7/89] rustc bun_zlib_sys 
[8/89] rustc bun_errno 
[9/89] rustc bun_picohttp 
[10/89] rustc bun_brotli 
[11/89] rustc bun_zstd 
[12/89] rustc bun_base64 
[13/89] rustc bun_ptr 
[14/89] rustc bun_output 
[15/89] rustc bun_valkey 
[16/89] rustc bun_clap 
[17/89] rustc bun_lsquic_sys 
[18/89] rustc bun_paths 
[19/89] rustc bun_tcc_sys 
[20/89] rustc bun_collections 
[21/89] rustc bun_shell_parser 
warning: `feature(generic_const_exprs)` is not supported with the next-generation trait solver
 --> src/shell_parser/lib.rs:1:30
  |
1 | #![feature(adt_const_params, generic_const_exprs, allocator_api)]
  |                              ^^^^^^^^^^^^^^^^^^^
  |
  = note: `-Znext-solver=globally` is currently enabled by default for testing
  = note: reverted the setting to `-Znext-solver=coherence` for this crate
  = note: the currently stable trait s
... (truncated)
```

</details>

<details><summary>diff hotspot</summary>

```
src/bun_core/string/StringBuilder.rs               | 30 +++++++-
 .../postgres/protocol/error_response_jsc.rs        |  8 +-
 .../hosted-git-info/boundary-conditions.test.ts    | 89 ++++++++++++++++++++++
 test/cli/install/hosted-git-info/from-url.test.ts  | 47 +++++++++++-
 4 files changed, 164 insertions(+), 10 deletions(-)
```

</details>

**gate history** · 1 passed · 0 rejected · iteration 1

<details><summary>evidence per changed file</summary>

```
file                                                      reads  edits  tests
src/bun_core/string/StringBuilder.rs                          2      1     35
src/sql_jsc/postgres/protocol/error_response_jsc.rs           2      2     27
…cli/install/hosted-git-info/boundary-conditions.test.ts      5      4     20
test/cli/install/hosted-git-info/from-url.test.ts             6      6     24
```

</details>

<!-- robobun:evidence:end -->
…in the global store check (oven-sh#44189)

Follow-up to oven-sh#43668.

### Problem
- The test `isolated install with the global store` fails when the path
of `os.tmpdir()` contains a symlink. macOS has one: `/var` links to
`/private/var`. The failure is `expect(received).toStartWith(expected)`
at `test/integration/bun-types/bun-types.test.ts:675`.
- The cause: the test compares `realpath(node_modules/bun-types)` with
`join(cacheDir, "links")`. `cacheDir` comes from `os.tmpdir()` and keeps
the symlink.
- The same assertion fails when the shell exports
`BUN_INSTALL_GLOBAL_STORE=0`. That variable overrides `globalStore =
true` in `bunfig.toml`
(`src/install/PackageManager/PackageManagerOptions.rs:606`).

### Fix
- Compare with `realpath(join(cacheDir, "links"))`, so both sides are
real paths.
- Set `BUN_INSTALL_GLOBAL_STORE: "1"` for the install, next to the
`BUN_INSTALL_CACHE_DIR` pin.
- The test still detects the original bug. Without `undici-types` in
`packages/bun-types/package.json`, it reports the seven TS2307 errors.
- Verified: `bun bd test test/integration/bun-types/bun-types.test.ts`
gives 9 pass, 13 skip. The release binary gives 22 pass.

### Background
- The global store links each package from `<cache>/links/`. The
assertion proves that the install used the store.
- `realpath` resolves every symlink in a path. `join` does not. When a
parent directory is a symlink, the two strings differ for one directory.
- CI does not show these failures. Buildkite excludes this file
(`.buildkite/ci.ts:887`), and the `bun-types` workflow runs it on
`ubuntu-latest` only.

<details><summary>Notes</summary>

Each run below uses `-t "isolated install with the global store"` on
`test/integration/bun-types/bun-types.test.ts`.

| Environment | main (3bdec20) | This change |
| --- | --- | --- |
| Plain | 1 pass | 1 pass |
| `TMPDIR=/tmp/link-tmp` (a symlink to `/tmp/real-tmp`) | 1 fail | 1
pass |
| `BUN_INSTALL_GLOBAL_STORE=0` | 1 fail | 1 pass |
| Both, debug build | 1 fail | 1 pass |

- With the symlinked tmpdir, main expects a path that starts with
`/tmp/link-tmp/bun-types-test-*/global-store-check/.bun-cache/links` and
receives `/tmp/real-tmp/...`.
- With `BUN_INSTALL_GLOBAL_STORE=0`, main receives
`.../global-store-check/node_modules/.bun/bun-types@.../node_modules/bun-types`.
The install did not use the store.
- I did not run the test on macOS. The symlinked tmpdir on Linux gives
the same condition.

</details>

<!-- robobun:evidence:begin -->

---

**[auto-merge]** gate passed · iteration 1 · 1 files touched

<details><summary>passes on PR (with fix)</summary>

```console
Test-only change.

Debug/ASAN (expected pass):
$ bun bd test 'test/integration/bun-types/bun-types.test.ts'
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test test/integration/bun-types/bun-types.test.ts
bun test v1.4.3 (367d939)

test/integration/bun-types/bun-types.test.ts:
(pass) @types/bun integration test > building and packing bun-types leaves packages/bun-types untouched [7.61ms]
(pass) @types/bun integration test > packed bun-types includes CLAUDE.md [18.37ms]
(skip) @types/bun integration test > basic type checks > checks without lib.dom.d.ts
(skip) @types/bun integration test > TypeScript latest > checks without lib.dom.d.ts
(skip) @types/bun integration test > TypeScript 7.1 > checks the fixture and import attributes through ts7.1/index.d.ts
(pass) @types/bun integration test > Bun.mmap > MMapOptions accepts offset and size [1528.71ms]
(pass) @types/bun integration test > TextDecoder > accepts the encoding labels the runtime supports [1469.45ms]
(pass) @types/bun integration test > TextDecoder > the fixture label table matches the runtime [126.63ms]
(pass) @types/bun integration test > Event and EventTarget > lib.dom's composedPath() declaration wins when lib.dom is loaded [1722.95ms]
(pass) @types/bun integration test > Event and EventTarget > the Node-style composedPath() tuple applies without lib.dom [1461.59ms]
(pass) @types/bun integration test > process event methods with @types/node@24 > removeListener and off accept other event names [4025.12ms]
(pass) @types/bun integration test > isolated install with the global store > bun-types resolves undici-types through its own dependencies [4424.13ms]
(skip) @types/bun integration test > Test Globals > checks without lib.dom.d.ts and test-globals references
(skip) @types/bun integration test > Test Globals > test-globals FAILS when the test-globals.d.ts is not referenced
(skip) @types/bun integration test > bun:bundle feature() > Registry augmentation restricts feature() to known flags
(skip) @types/bun integration test > bun:bundle feature() > Registry augmentation pro
... (truncated)
Exit: 0
```

</details>

<details><summary>diff hotspot</summary>

```
test/integration/bun-types/bun-types.test.ts | 8 +++++---
 1 file changed, 5 insertions(+), 3 deletions(-)
```

</details>

**gate history** · 2 passed · 0 rejected · iteration 1

<details><summary>evidence per changed file</summary>

```
file                                          reads  edits  tests
test/integration/bun-types/bun-types.test.ts      2      1     16
```

</details>

<!-- robobun:evidence:end -->
…40556)

### What does this PR do?

Fixes a debug assertion failure in `BunString__toErrorInstance`
(`src/jsc/bindings/BunString.cpp`). The fuzzer found it with
`expect.unreachable("")`.

```
ASSERTION FAILED: !message.isEmpty()
vendor/WebKit/Source/JavaScriptCore/runtime/Error.cpp(41) : JSObject *JSC::createError(JSGlobalObject *, const String &, ErrorInstance::SourceAppender)
```

`BunString__toErrorInstance` is the shared path for
`String::to_error_instance` and its TypeError, SyntaxError, and
RangeError siblings. It called `JSC::createError` and friends. Those JSC
helpers assert that the message is not empty. An empty `BunString`
converts to a null `WTF::String`, so any caller that forwards an empty
string aborts a debug build. `expect.unreachable(reason)` forwards the
user's string as is, so `expect.unreachable("")` reached the assertion.

The fix constructs the `ErrorInstance` directly, with the error
structure for the requested type. `JSC::createError(globalObject,
message)` is exactly `ErrorInstance::create(vm,
globalObject->errorStructure(type), message, JSValue(), nullptr,
TypeNothing, type, true)` plus the assertion, so the result is the same
object for a non-empty message. The napi bindings already use this
pattern for the same reason (`createErrorWithCode` in
`src/jsc/bindings/napi.cpp`).

Release builds do not compile the assertion, so their behavior does not
change. `expect.unreachable("")` throws an `UnreachableError` with an
empty `message` there before and after this change.

### How did you verify your code works?

- Reproduced the abort with the debug fuzz build:
`Bun.jest().expect.unreachable("")`.
- With the fix, the same script throws `UnreachableError` and exits with
code 1. The debug build now matches the release build for an empty, a
custom, and an omitted message.
- Added a test to `test/js/bun/test/expect-unreaachable.test.ts`. On the
unfixed debug build the test process aborts with the assertion. With the
fix it passes (`bun bd test`). The release build has no assertions, so
the test also passes with `USE_SYSTEM_BUN=1`. The failure is only
visible in a debug build.
- `bun bd test test/js/bun/test/expect.test.js`: 415 pass, 0 fail.
- Ran the regression test under `BUN_JSC_validateExceptionChecks=1`:
pass.
- Ran a Worker whose script has a parse error, on the release build and
on the fixed debug build. The error event is the same on both: `message`
is `SyntaxError: Unexpected ;` and `error instanceof SyntaxError` is
false. I did not confirm that this run reaches
`to_syntax_error_instance`, so it is not coverage of the SyntaxError
kind. Only the `Error` kind is exercised, through `expect.unreachable`.

<!-- robobun:evidence:begin -->

---

**[auto-merge]** gate passed · iteration 2 · 2 files touched

<details><summary>fails on main (without fix)</summary>

```console
ASAN without fix: 1 FAILED
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/pr_gate.xml" test/js/bun/test/expect-unreaachable.test.ts
bun test v1.4.3 (367d939)

test/js/bun/test/expect-unreaachable.test.ts:
(pass) expect.unreachable() [33.32ms]
26 |     stderr: "pipe",
27 |   });
28 | 
29 |   const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);
30 | 
31 |   expect(stdout).toBe('{"name":"UnreachableError","message":"","isError":true}\n');
                      ^
error: expect(received).toBe(expected)

- "{"name":"UnreachableError","message":"","isError":true}
- "
+ ""

- Expected  - 2
+ Received  + 1

      at <anonymous> (/workspace/bun/test/js/bun/test/expect-unreaachable.test.ts:31:18)
(fail) expect.unreachable('') throws an UnreachableError with an empty message [631.99ms]

 1 pass
 1 fail
 5 expect() calls
Ran 2 tests across 1 file. [3.70s]
error: script "bd" exited with code 1
__F:1:S:0

release without fix: all passed
bun test v1.4.3-canary.1 (367d939)

test/js/bun/test/expect-unreaachable.test.ts:
(pass) expect.unreachable() [0.12ms]
(pass) expect.unreachable('') throws an UnreachableError with an empty message [8.73ms]

 2 pass
 0 fail
 7 expect() calls
Ran 2 tests across 1 file. [69.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/test/expect-unreaachable.test.ts
bun test v1.4.3 (367d939)

test/js/bun/test/expect-unreaachable.test.ts:
(pass) expect.unreachable() [49.99ms]
(pass) expect.unreachable('') throws an UnreachableError with an empty message [430.10ms]

 2 pass
 0 fail
 7 expect() calls
Ran 2 tests across 1 file. [3.00s]
__F:0:S:0

release with fix: all passed
$ bun scripts/build.ts --profile=release
[configured] bun-profile → bun (stripped) in 1064ms (unchanged)
ninja: Entering directory `/workspace/bun/build/release'
[1/25] cxx obj/src/jsc/bindings/BunObject.cpp.o
[2/25] cxx obj/unified/UnifiedSource-src_jsc_bindings-2.cpp.o
[3/25] cxx obj/unified/UnifiedSource-src_jsc_bindings-4.cpp.o
[4/25] cxx obj/unified/UnifiedSource-src_jsc_bindings-0.cpp.o
[5/25] gen cpp.rs (cppbind)
[6/24] rustc bun_install 
[7/24] rustc bun_jsc 
[8/24] rustc bun_ast_jsc 
[9/24] rustc bun_sys_jsc 
[10/24] rustc bun_bundler_jsc 
[11/24] rustc bun_patch_jsc 
[12/24] rustc bun_semver_jsc 
[13/24] rustc bun_css_jsc 
[14/24] rustc bun_js_parser_jsc 
[15/24] rustc bun_sourcemap_jsc 
[16/24] rustc bun_install_jsc 
[17/24] rustc bun_http_jsc 
[18/24] rustc bun_sql_jsc 
[19/24] rustc bun_runtime 
[20/24] link bun-profile
ld.lld: warning: Linking two modules of different target triples: 'obj/unified/UnifiedSource-src_jsc_bindings-0.cpp.o' is 'x86_64-pc-linux-gnu' whereas '../../../../root/.bun/build-cache/webkit-564ac2a6cad8da6a-lto/lib/libJavaScriptCore.a(UnifiedSource-inspector-2.cpp.o at 102508190)' is 'x86_64-unknown-linux-gnu'


ld.lld: warning: Li
... (truncated)
```

</details>

<details><summary>diff hotspot</summary>

```
src/jsc/bindings/BunString.cpp               | 12 +++++++-----
 test/js/bun/test/expect-unreaachable.test.ts | 25 +++++++++++++++++++++++++
 2 files changed, 32 insertions(+), 5 deletions(-)
```

</details>

**gate history** · 2 passed · 0 rejected · iteration 2

<details><summary>evidence per changed file</summary>

```
file                                          reads  edits  tests
src/jsc/bindings/BunString.cpp                    1      1     12
test/js/bun/test/expect-unreaachable.test.ts      2      2     12
```

</details>

<!-- robobun:evidence:end -->
### Problem
- On Windows, a worker can use the stdin `FileSink` of a `Bun.spawn`
child after it is freed. It needs `stdin: "pipe"`, a live child, and a
script that never read `proc.stdin`. Debug build: `panic: misaligned
pointer dereference: address must be a multiple of 0x8 but is
0xdfdfdfdfdfdf`. A release build reads freed memory silently.
- `FileSink::on_close` (`src/runtime/webcore/FileSink.rs:528`) calls
`source.close()`. That reaches `Writable::on_close`
(`src/runtime/api/bun/subprocess/Writable.rs:114`), which drops the only
ref on the sink. `on_close` then continues on freed memory.

### Fix
- `FileSink::on_close` holds a ref on the sink until it returns.
`on_write` and `run_pending` already use this guard.
- A testing hook, `subprocessInternals.closeStdinWriter(proc)`, does the
same close as the Windows stop phase, on every platform.
- Verified with the hook, in `test/js/bun/util/filesink.test.ts`.
Without the guard, the Linux ASAN build reports `heap-use-after-free` in
`settle_stream_done`, and a Windows debug build panics. With the guard
both pass. The worker test in
`test/js/web/workers/worker-terminate-lifetime.test.ts` can fail only on
a Windows debug build.
- Self-reviewed: 3 concerns raised, 2 addressed (see Notes).

### Background
- A `FileSink` is a refcounted writer. For `stdin: "pipe"` the
Subprocess holds one ref. The `proc.stdin` getter moves it to a JS
wrapper. `source.close()` tells that owner that the sink closed, and the
owner drops its ref.
- The stop phase is the first step of worker teardown (oven-sh#37075). On
Windows it closes each libuv pipe of the worker through its writer,
which calls `FileSink::on_close`.

### Downsides
- None found for the guard. `on_close` never runs while the sink is
destroyed, so the guard never takes a ref from zero.
- Still open: the stream-fed stdin leak in the Notes.

<details><summary>Notes</summary>

**Repro** (windows-x64, debug build, 5 of 5 runs on main at b7ea95a):

```js
import { Worker } from "node:worker_threads";
const w = new Worker(`
  const { parentPort } = require("node:worker_threads");
  globalThis.keep = Bun.spawn({ cmd: [process.execPath, "-e", "setTimeout(() => {}, 4000)"], stdin: "pipe", stdout: "ignore", stderr: "ignore" });
  setTimeout(() => parentPort.postMessage("go"), 300);
`, { eval: true });
await new Promise(r => w.once("message", r));
await w.terminate();
console.log("survived");
```

**Symbolized stack** (llvm-symbolizer with the PDB, ASLR off, line
numbers at b7ea95a):

```
bun_jsc::strong::Impl::get                                   src/jsc/Strong.rs:179
bun_jsc::strong::Optional::get                               src/jsc/Strong.rs:92
webcore::streams::PipeCell::take_done                        src/runtime/webcore/streams.rs:908
FileSink::settle_stream_done                                 src/runtime/webcore/FileSink.rs:552
FileSink::on_close                                           src/runtime/webcore/FileSink.rs:530
<FileSink as WindowsStreamingWriterParent>::on_close         src/io/PipeWriter.rs:2734
WindowsStreamingWriter<FileSink>::on_close_source            src/io/PipeWriter.rs:2010
WindowsStreamingWriter<FileSink>::close                      src/io/PipeWriter.rs:1212
WindowsStreamingWriter<FileSink>::stop_for_vm_teardown       src/io/PipeWriter.rs:1130
open_handles::stop_all_for_vm_teardown                       src/libuv_sys/open_handles.rs:172
VirtualMachine::stop_phase_sweep                             src/jsc/VirtualMachine.rs:2554
VirtualMachine::teardown                                     src/jsc/VirtualMachine.rs:2401
WebWorker::shutdown / spin / thread_main                     src/jsc/web_worker.rs
```

The address matches. `Strong::get` masks the handle to 48 bits, and
`0xdfdfdfdfdfdfdfdf & ((1 << 48) - 1)` is `0xdfdfdfdfdfdf`. `0xdf` is
the fill that a debug mimalloc writes into a freed block.

**Linux ASAN report** (debug ASAN build with the hook and without the
guard, from the new test in `filesink.test.ts`):

```
ERROR: AddressSanitizer: heap-use-after-free ... READ of size 8
    #0 bun_jsc::strong::Optional::get                  src/jsc/Strong.rs:91
    #1 webcore::streams::PipeCell::take_done           src/runtime/webcore/streams.rs:908
    #2 FileSink::settle_stream_done                    src/runtime/webcore/FileSink.rs
    #3 FileSink::on_close                              src/runtime/webcore/FileSink.rs
    #5 PosixStreamingWriter<FileSink>::close           src/io/PipeWriter.rs:1048
    #7 PollOrFd::close_impl                            src/io/pipes.rs:118
   #10 testing_apis::close_stdin_writer                src/runtime/api/bun/subprocess.rs
freed by thread T0 here:
   #12 <FileSink as CellRefCounted>::destroy           src/ptr/ref_count.rs:448
   #15 <RefPtr<FileSink> as Drop>::drop                src/ptr/ref_count.rs:522
   #19 JsCell<Writable>::set                           src/ptr/js_cell.rs:94
   #20 Writable::on_close                              src/runtime/api/bun/subprocess/Writable.rs:114
   #22 SourceHandle::close                             src/runtime/webcore/streams.rs:1043
   #23 FileSink::on_close                              src/runtime/webcore/FileSink.rs
```

The use and the free are in the same `FileSink::on_close` call. For this
proof I removed only the guard line and kept the hook. With the `src/`
of main the new `filesink.test.ts` test also fails, but for a weaker
reason: the hook does not exist there.

**Why only this path.** Every other path that closes this sink keeps it
alive or detaches the source first:
- `Subprocess::on_process_exit` clears `source` before
`on_attached_process_exit`, which also holds a ref.
- `Writable::finalize` and `on_close_io` clear `source` before they drop
the ref.
- The `proc.stdin` getter takes the pipe out of the `stdin` slot and
clears `source`, so `Writable::on_close` is not reached.
- POSIX has no stop-phase close of the pipe. The sink dies in
`Subprocess::finalize`. A poll HUP with an empty buffer reports
`Drained`, not a close.

**Variants** (windows-x64 debug, before and after the fix):

| worker ends by | stdin | before | after |
| --- | --- | --- | --- |
| `terminate()` | `"pipe"`, never read | panic | ok |
| `process.exit()` in the worker | `"pipe"`, never read | panic | ok |
| loop drains (`proc.unref()`) | `"pipe"`, never read | panic | ok |
| `terminate()`, `stdout: "pipe"` too | `"pipe"`, never read | panic |
ok |
| `terminate()` | `"pipe"`, `proc.stdin.write()` pending | ok | ok |
| no worker, `closeStdinWriter(proc)` hook | `"pipe"`, never read |
panic | ok |

After the fix, `fileSinkInternals.liveCount()` is back at the baseline
after the `exit` event of the worker in each row.

**Suites run with the fix.**
- windows-x64 debug: `worker-terminate-lifetime.test.ts` (24 pass, 2
skip), `worker_destruction.test.ts` (5 pass), `spawn.test.ts` (126
pass), `spawn-stdin-readable-stream.test.ts` (36 pass),
`spawn-stdin-destroy.test.ts`, `spawn-stdin-pipe-fd-leak.test.ts`,
`child_process.test.ts` (53 pass), `filesink.test.ts` (33 pass, 1 fail,
see below). The hook test passes 5 of 5 runs and the worker test 3 of 3.
- linux-x64 debug ASAN: both new tests, `filesink.test.ts` (70 pass),
`spawn-stdin-readable-stream.test.ts` (37 pass),
`spawn-stdin-destroy.test.ts`, `worker_destruction.test.ts` (5 pass with
`--timeout 120000`).

**Self-review.**
- Addressed: no CI lane could fail the worker test. The Windows lanes
run release builds, where the stale reads do not crash, and Linux does
not reach the path. The hook test now fails on an ASAN build of any
platform without the guard. The worker test stays, because it is the
real trigger, and its comment says which build can fail it.
- Addressed: the comment before `clear_keep_alive_ref` said that call
can free the sink. With the guard it cannot, so the sentence is gone.
- Not changed: the sink keeps its stale `source` after the owner is
told. Nothing reads it again on this path, because a later write needs
the JS wrapper, and the getter that creates the wrapper clears `source`.
- Checked and fine: no caller of `on_close` touches the writer or the
sink after the call returns (`on_close_source`, the tail of `close`,
`stop_all_for_vm_teardown`, and `PollOrFd::close` on POSIX, where the
callback is last). Both writer `Drop` impls close without a report, so
`on_close` never runs while the sink is destroyed.

**Not in this PR.** On Windows, a worker that ends while `Bun.spawn({
stdin: new ReadableStream({ pull(c) { c.enqueue(new Uint8Array(1024));
return new Promise(() => {}); } }) })` still pumps leaves one `FileSink`
alive. `liveCount()` stays at +1, before and after this change. Linux
returns to the baseline. The cause is different: the ref that
`assign_to_js_stream` takes for the reactions of the pump promise is not
released, because the reactions never run after script is forbidden.
oven-sh#43729 adds a flag that tracks that ref.

**Local failures that this diff does not cause.**
- windows-x64 (Server 2019): `test/js/bun/util/filesink.test.ts`
"Bun.spawn stdin pipe with an unref'd child" fails 3 of 3 runs with the
`src/` of main, with this fix, and with the release canary.
- linux-x64 debug ASAN in my container: "terminate() while dns.lookup()
is in flight" in the same test file reports a 16 byte LeakSanitizer leak
from `node_fs_binding::Binding::new`. No `FileSink` is involved.

</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/workers/worker-terminate-lifetime.test.ts,
test/js/bun/util/filesink.test.ts

<!-- robobun:evidence:end -->
…vesTo and rejectsTo chains (oven-sh#34646)

### Problem
- `expect.not.any(Ctor)`, `expect.resolvesTo.any(Ctor)` and
`expect.rejectsTo.any(Ctor)` lose the constructor type of the matcher.
An asserts build aborts on the first match: `ASSERTION FAILED: Invalid
constructor type` in `matchAsymmetricMatcherAndGetFlags`
(`src/jsc/bindings/bindings.cpp:449`).
- A release build gives the wrong verdict for primitives.
`expect(5).toEqual(expect.not.any(Number))` passes.
`expect(Promise.resolve("s")).toEqual(expect.resolvesTo.any(String))`
fails.
- The cause is `ExpectStatic::create_asymmetric_matcher_with_flags`
(`src/runtime/test_runner/expect.rs:1884`). `ExpectAny::call` stores the
constructor type in the flags of the new matcher. The function then
replaced those flags with the chain flags, which have constructor type
`None`.

### Fix
- Copy only `not` and `promise` from the chain onto the flags of the
matcher. The constructor type stays.
- Correct because the chain can only set `not` and `promise`, and
`ExpectAny` is the only matcher that sets anything else. The other
matchers start from `Flags::default()`, so they behave as before.
- Verified: three new tests in `test/js/bun/test/expect.test.js`.
Without the fix the debug build aborts on them, and bun 1.4.3-canary.1
fails two of the three. The full file passes.

### Background
- An asymmetric matcher (`expect.any(Number)`) is an object that
`toEqual` and similar matchers call to decide a match.
- `Flags` is one packed byte on each matcher: `promise`, `not`, and for
`expect.any` the constructor type. The C++ matcher switches on that type
to match primitives with `typeof` semantics. With `None` it only calls
`hasInstance`, which is false for a primitive.
- `ExpectStatic` is the object that `expect.not`, `expect.resolvesTo`
and `expect.rejectsTo` return. It holds the chain flags.

<details><summary>Notes</summary>

Repro:

```js
import { test, expect } from "bun:test";
test("repro", () => {
  expect(5).not.toEqual(expect.not.any(Number)); // release: fails, debug: abort
  expect(Promise.resolve("s")).toEqual(expect.resolvesTo.any(String)); // release: fails, debug: abort
});
```

- Affected constructors: `Number`, `String`, `Boolean`, `BigInt`,
`Symbol`. `Object` also lost its type:
`expect(null).not.toEqual(expect.not.any(Object))` fails on release,
because `any(Object)` is `typeof other === "object"` and the fallthrough
only calls `hasInstance`. `Array` gives the same verdict either way for
the ordinary cases I tried. Boxed values (`new Number(5)`) and class
instances were already correct.
- The same shapes fail when the matcher is nested in an object or passed
to `toHaveBeenCalledWith`. The new async test covers both.
- Fail-before on the debug build at `f04caca828`: `bun bd test
test/js/bun/test/expect.test.js -t "resolvesTo.any"` aborts at
`bindings.cpp(449)`.
- Fail-before on release: `USE_SYSTEM_BUN=1 bun test
test/js/bun/test/expect.test.js -t "expect.not.any|resolvesTo.any"`
gives 1 pass, 2 fail. The passing one is the user class test, which was
already correct through `hasInstance`.
- Full file on the debug build with the fix: 419 pass, 2 todo, 0 fail.
- The two `expect.not.any` tests are inside `if (isBun)`, because the
file also runs under Jest and Vitest and their `expect.not` has no
`any()`.
- Also ran `test/js/bun/test/jest-extended.test.js` on the first
revision: 57 pass.
- The branch was rebased from `a227ad991b` to `f04caca828`.

</details>
### Problem
- `bun build --no-bundle --minify` and `Bun.Transpiler`
(`minify.identifiers`) can give a parameter, a local or an import the
name of an export. `export const t = ...; export function label(item) {
return t(item.name) }` prints `label(t){return t(t.name)}` and throws
`TypeError: t is not a function`.
- Cause: `print_ast` (`src/js_printer/lib.rs:7734` on main) computes the
reserved names, then pins the exports, and only the ref each export
recorded. `export var t = 1; var t = 2` prints `export var r = 1`.
- Bundles have the same gap for a `var` that a `with` body reads:
`function f(o) { var t = 1; with (o) { return t } }` prints `function
f(t){var t=1;with(t)return t}`.

### Fix
- `print_ast` pins the exports first, through their link chains.
- `Scope.contains_with` marks a `with` scope and each scope around it.
`compute_reserved_names_for_scope` walks into them.
- The `with` pin follows the link chain of a `var` declared twice.
- Verified: 11 new cases in `test/bundler/bundler_minify.test.ts`. Main
fails all 11. `test/bundler/` has no new failure.

### Background
- The minifier picks one name per slot and skips `reserved_names`. A
pinned symbol (`must_not_be_renamed`) keeps its name and gets no slot.
- `--no-bundle` pins the exports, because other files import them by
name.
- `compute_reserved_names_for_scope` makes pinned names reserved. The
minifier, the renamer for bundles without `--minify`, and cross-chunk
naming call it.

### Downsides
- `--no-bundle`: 145 of 35,082 real files get other slot names, +533
bytes in total. Main's output does not parse for 49 of them.
- Bundles: a name that a `with` body reads is reserved for the whole
chunk, as for a direct eval. Without `--minify`, `function total` prints
as `total2` when such a body reads `total`.
- Binary: `.text` is 256 bytes smaller than on main. `Scope` stays 128
bytes.

<details><summary>Notes</summary>

The numbers compare two release builds on linux x64, made on one
machine: main at a4f1429 and this branch at ca7d303 on top of it. Two
results are from one commit earlier (aebaeff) and were not repeated.
They are marked. ca7d303 changes `print_ast` only.

**The export cases**

- Reported example: `bun build --no-bundle --minify` of `export const t
= (key) => "tr:" + key; export function label(item) { return
t(item.name) + " #" + item.id }`. Main prints `export const
t=(t)=>"tr:"+t;export function label(t){return t(t.name)+" #"+t.id}`.
This branch prints `export const t=(n)=>"tr:"+n;export function
label(n){return t(n.name)+" #"+n.id}`. Both are 80 bytes.
- An export that a later `var` declares again: `export var t = 1; var t
= 2;`. Main prints `export var r = 1; var r = 2;` and an importer fails
with `SyntaxError: Export named 't' not found`. The second `var`
replaces the first symbol in the module scope and the first links to it.
The renamer names the symbol at the end of that link.
- The pin walks the link chain with the checked `get_mut`.
`symbol::Map::follow` reads through `get_const`, which does not check
the index, and an empty source or a data loader has a `module_ref` with
no symbol.
- Measured at aebaeff, not repeated: a matrix through `transformSync` of
7 export forms, 13 places a name can come from and 54 one-character
export names, 4914 modules. Bun 1.4.3-canary breaks 257 of them (125
return a wrong value, 110 do not load, 22 throw). The branch breaks 0.
- The doors are `bun build --no-bundle --minify`,
`--minify-identifiers`, `transformSync` and `transform`. All of them
print through `print_ast`. Bundled output does not use this path.
- `export { local as t }` is not affected, because the pinned name is
`local`. `export { t as local }` is affected. That is the shape of a
file that was minified before.

**Real files**

- Corpus: every `.js`, `.mjs`, `.cjs`, `.ts`, `.tsx` and `.jsx` file
under `test/node_modules`, `node_modules`, `packages`, `src/js` and
`bench`, without `.d.ts` files and without symlinks, through
`transformSync` with `minify.identifiers`. 35,082 files from 1099
packages, 285.2 MB of source. 17 files give a transform error on both
builds.
- 145 outputs differ. 27 of them grow and 118 keep their length. None
shrinks. Total output: 210,157,582 bytes on main, 210,158,115 bytes on
this branch. The largest growth of one file is 152 bytes.
- On main, the output of 49 of the 145 files does not parse, for example
`"R" has already been declared` for `preact/compat/dist/compat.mjs`. The
files come from 24 packages, among them preact, zod, socket.io,
react-router and @astrojs/compiler. On this branch all 145 outputs
parse.
- Measured at aebaeff, not repeated: bundles of `import * as everything
from "<package>"` for 39 packages, `--target=node`, `esm` and `cjs`,
with and without `--minify`. All 156 bundles are byte-identical on the
two builds.

**The `with` cases**

- Pinned symbols are unbound globals, the members of scopes with a
direct eval, symbols read or hoisted through a `with` body, and the
exports of a `--no-bundle` build. On main,
`compute_reserved_names_for_scope` (`src/js_printer/renamer.rs:1458`)
only reads the pinned names of the module scope and of direct eval
scopes.
- A `var` declared twice in one function is two symbols. Hoisting links
the inner one to the function-level one, and the renamer follows the
link before it reads the flag. On main the `with` pin lands on the
linked ref (`src/js_parser/p.rs:3671`,
`src/js_parser/scan/scan_symbols.rs:150`).
- `var t = 1; with (obj) { var t = 2 } return [t, obj.t]` gives `[2, 9]`
for `{ t: 9 }` on main and not `[1, 2]`. `var t = 1; { var t = 2; with
(obj) { return t } }` gives 2 and not 9. Both print `var n` for the
pinned `t`.
- `with (obj) var t = 2` without braces declares `t` in the `with`
scope, which the hoisting walk starts above. `with (obj) var t = 2;
return [t, obj.t]` gives `[2, 9]` for `{ t: 9 }` on main and not
`[undefined, 2]`.
- esbuild 0.25.1 has the parameter case and the brace-less case too.
- The implicit `arguments` symbol of each function on the marked path is
pinned and lands in the reserved set. The minifier never produces a nine
character name, and a direct eval reserves it the same way.
- Why bundles without `--minify` need the reserved name: that renamer
numbers a nested binding which meets an outer name that its scope
references. In a CommonJS file, `function (require_dep, obj) { var
require_dep2 = 1; var seen = require_dep + require("./dep.cjs").value;
with (obj) { return [seen, require_dep2] } }` calls the wrapper
`require_dep`, so the parameter is numbered. Main prints it as
`require_dep2`, the name of the `var`, and `seen` starts with `1`. This
branch prints `require_dep3`.
- The cost of that reserved name: `legacy.cjs` with `module.exports =
function read(obj) { var total = 1; with (obj) { return total } }`, and
an entry file with `function total() {}`. Main prints `function
total()`. This branch prints `function total2()`, so `total.name` is
`"total2"`. With `return eval(code)` in place of the `with`, main prints
`total2` already.
- The `f_` functions in the `with` test pin all 54 one-character names,
one function each, so the test does not depend on which name the
character frequency puts first. The export tests use the same idea: they
export all 54 names and declare 54 other names.
- Not changed here: `const u = 1; with (obj) { return u }` is folded to
`return 1` by the constant substitution of the parser, under `--minify`
and under `bun run`. That is a different mechanism and needs its own
change.

**Cost**

- `size -A` of the release binaries: `.text` is 58,143,477 bytes on main
and 58,143,221 bytes on this branch. The file size is 80,827,976 bytes
on both.
- `size_of::<Scope>()` is 128 bytes on both, checked with a `const`
assertion. The new `bool` uses padding.
- Files with no `with` and no `--no-bundle` export: one more `bool` test
for each scope that `hoist_symbols` and
`compute_reserved_names_for_scope` visit, and one more branch for each
hoisted member. `print_ast` has one loop in place of two, with one
`has_link` test for each pinned ref. No allocation is added.
- Time for the corpus, user CPU, 10 interleaved runs for each build:
7735 ms to 10,356 ms on main, 7524 ms to 9869 ms on this branch. The
spread of one build is larger than the difference. `perf`, `valgrind`
and `strace` are not available on the build machine, so there is no
instruction count.

**Suites**

- Debug build with ASAN: `bundler_minify`, `bundler_edgecase`,
`bundler_splitting`, `bundler_minify_symbol_for`, `bundler_regressions`,
`bundler_cjs`, `bundler_cjs2esm`, `esbuild/default`, `esbuild/dce`,
`esbuild/importstar`, `transpiler/transpiler`,
`transpiler/runtime-transpiler`.
- Release build: all of `test/bundler/` on both builds, and
`test/internal/source-lints/` on this branch. At that time 5 of the 11
cases were in `bundler_edgecase.test.ts` and
`transpiler/transpiler.test.js`. They moved to `bundler_minify.test.ts`
with no other change. Four tests fail on both builds: three bytecode
tests and `native-plugins`. Each other failure of the branch run is a 5
second timeout or the resolver cache test `direct file deleted then
recreated`. Each one passes when its file runs alone. The main run has
timeouts of the same kind in other tests.
</details>

<!-- robobun:evidence:begin -->

---

**[human-review]** gate passed · iteration 1 · 6 files touched

<details><summary>fails on main (without fix)</summary>

```console
ASAN without fix: 11 FAILED
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/pr_gate.xml" test/bundler/bundler_minify.test.ts
bun test v1.4.3 (367d939)

test/bundler/bundler_minify.test.ts:
(pass) bundler > minify/DirectEvalKeepsTopLevelNamesOfWrappedFile [959.30ms]
runtime failed file: /tmp/bun-build-tests/bun-3qer3A/minify/WithStatementPinnedNameNotReusedByEnclosingScope/out.js
stdout output:
["t","hoisted","merged","braceless"]
---
expected stdout:
[]
---
1923 |               console.log(`---`);
1924 |               console.log(`expected ${name}:`);
1925 |               console.log(expected);
1926 |               console.log(`---`);
1927 |             }
1928 |             expect(result).toBe(expected);
                                  ^
error: expect(received).toBe(expected)

Expected: "[]"
Received: "["t","hoisted","merged","braceless"]"

      at <anonymous> (/workspace/bun/test/bundler/expectBundled.ts:1928:28)
(fail) bundler > minify/WithStatementPinnedNameNotReusedByEnclosingScope [1237.59ms]
runtime failed file: /tmp/bun-build-tests/bun-3qer3A/minify/WithStatementPinnedNameNotReusedByEnclosingScopeNoBundle/out.js
... (truncated)

release without fix: all passed
bun test v1.4.3-canary.1 (db2774f)

test/bundler/bundler_minify.test.ts:
(pass) bundler > minify/DirectEvalKeepsTopLevelNamesOfWrappedFile [50.93ms]
(pass) bundler > minify/WithStatementPinnedNameNotReusedByEnclosingScope [28.56ms]
(pass) bundler > minify/WithStatementPinnedNameNotReusedByEnclosingScopeNoBundle [30.88ms]
(pass) bundler > minify/WithStatementPinnedNameNotReusedWithoutMinify [21.69ms]
(pass) bundler > minify/NoBundleExportNameNotReusedByLocal [20.37ms]
(pass) bundler > minify/NoBundleExportNameNotReusedInFunction [76.84ms]
(pass) bundler > minify/NoBundleExportNameNotReusedAtTopLevel [21.58ms]
(pass) bundler > minify/NoBundleExportNameKeptWhenDeclaredAgain [21.09ms]
(pass) bundler > minify/TemplateStringFolding [6.32ms]
(pass) bundler > minify/StringAdditionFolding [6.03ms]
(pass) bundler > minify/FunctionExpressionRemoveName [6.97ms]
(pass) bundler > minify/KeepNamesPreservesNames [6.15ms]
(pass) bundler > minify/KeepNamesWithMinifyIdentifiers [5.11ms]
(pass) bundler > minify/PrivateIdentifiersNameCollision [20.48ms]
(pass) bundler > minify/MergeAdjacentVars [17.72ms]
(pass) bundler > minify/UnusedCommaAndStrictEqChains [17.16ms]
(pass) bundler > m
... (truncated)
```

</details>

<details><summary>passes on PR (with fix)</summary>

```console
ASAN with fix: all passed
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/pr_gate.xml" test/bundler/bundler_minify.test.ts
bun test v1.4.3 (367d939)

test/bundler/bundler_minify.test.ts:
(pass) bundler > minify/DirectEvalKeepsTopLevelNamesOfWrappedFile [1456.20ms]
(pass) bundler > minify/WithStatementPinnedNameNotReusedByEnclosingScope [1253.76ms]
(pass) bundler > minify/WithStatementPinnedNameNotReusedByEnclosingScopeNoBundle [1225.51ms]
(pass) bundler > minify/WithStatementPinnedNameNotReusedWithoutMinify [833.64ms]
(pass) bundler > minify/NoBundleExportNameNotReusedByLocal [949.36ms]
(pass) bundler > minify/NoBundleExportNameNotReusedInFunction [1246.93ms]
(pass) bundler > minify/NoBundleExportNameNotReusedAtTopLevel [1290.60ms]
(pass) bundler > minify/NoBundleExportNameKeptWhenDeclaredAgain [718.30ms]
(pass) bundler > minify/TemplateStringFolding [330.94ms]
(pass) bundler > minify/StringAdditionFolding [314.64ms]
(pass) bundler > minify/FunctionExpressionRemoveName [168.32ms]
(pass) bundler > minify/KeepNamesPreservesNames [209.71ms]
(pass) bundler > minify/KeepNamesWithMinifyIdentifiers [187.80ms]
(pass) bundler > 
... (truncated)

release with fix: all passed
$ bun scripts/build.ts --profile=release
[configured] bun-profile → bun (stripped) in 2542ms (unchanged)
ninja: Entering directory `/workspace/bun/build/release'
[1/212] gen ErrorCode+*.h
[2/212] gen NodeModuleModule.lut.h
Generating /workspace/bun/build/release/codegen/NodeModuleModule.lut.h from /workspace/bun/src/jsc/modules/NodeModuleModule.cpp
[3/212] gen generated_host_exports.rs
generated_host_exports.rs: 121 exports (host=5, lazy=10, generic=106, rust=0); 248 extern-C blocks audited
[4/212] gen cpp.rs (cppbind)
[5/212] gen JS modules (bundle-modules)
Preprocess modules (11196ms)
Bundle modules (211ms)
Postprocesss modules (235ms)
Bundle Functions (852ms)
Generate Code (85ms)

[12.61s] Bundled "src/js" for production
  2612 kb
  198 internal modules
  13 native modules
  50 internal functions across 16 files
[6/177] cxx obj/unified/UnifiedSource-src_jsc_bindings_node-0.cpp.o
[7/177] cxx obj/unified/UnifiedSource-src_jsc_bindings_node_crypto-1.cpp.o
[8/177] cxx obj/unified/UnifiedSource-src_jsc_bindings-4.cpp.o
[9/177] cxx obj/unified/UnifiedSource-src_jsc_bindings-1.cpp.o
[10/177] cxx obj/unified/UnifiedSource-src_jsc_bindings-3.cpp.o
[11/177] cxx obj/unifi
... (truncated)
```

</details>

<details><summary>diff hotspot</summary>

```
src/ast/scope.rs                    |   4 +
 src/js_parser/p.rs                  |  36 ++++++-
 src/js_parser/scan/scan_symbols.rs  |   2 +-
 src/js_printer/lib.rs               |  32 +++---
 src/js_printer/renamer.rs           |   7 +-
 test/bundler/bundler_minify.test.ts | 204 ++++++++++++++++++++++++++++++++++++
 6 files changed, 263 insertions(+), 22 deletions(-)
```

</details>

**gate history** · 2 passed · 1 rejected · iteration 1

<details><summary>evidence per changed file</summary>

```
file                                 reads  edits  tests
src/ast/scope.rs                         2      4     49
src/js_parser/p.rs                       7     10     49
src/js_parser/scan/scan_symbols.rs       1      2     49
src/js_printer/lib.rs                    5      6     49
src/js_printer/renamer.rs                4      4     49
test/bundler/bundler_minify.test.ts      7      6     49
```

</details>

<!-- robobun:evidence:end -->
…oven-sh#42351)

### Problem

- `Bun.listen({ tls })`: `socket.pause()` on a connection that waits in
the TLS handshake queue does not hold. The queue drain arms the reads
again, and `handshake` and `data` fire on a socket whose `pause()`
returned. In a burst of 32 connections, all 27 queued sockets get both
callbacks (1.4.2, canary, main).
- The cause is `us_internal_handle_low_priority_sockets`
(`packages/bun-usockets/src/loop.c:320`). It calls
`us_poll_change(events | LIBUS_SOCKET_READABLE)` for each socket it
takes out of the queue and does not check `s->flags.is_paused`.

### Fix

- The drain links a paused socket back into its group, leaves its reads
off, and sets `low_prio_state` to 0. It is an ordinary paused socket
again.
- `us_socket_resume` arms the reads. The readable dispatch then limits
the socket like any other handshaking socket, so a burst of `resume()`
calls cannot run all the delayed handshakes in one iteration.
- Verified: new test in `test/js/bun/net/socket-syscall-fault.test.ts`
(fixture `tls-pause-parked-handshake-fixture.ts`). Also `socket.test.ts`
and the `node:tls` suites.

### Background

- uSockets reads at most 5 handshaking TLS sockets per loop iteration. A
socket over the budget is parked: unlinked from its group, linked into
`loop->data.low_prio_head`, reads off. Each later iteration starts with
a drain that takes 5 sockets out and switches their reads on.
- `low_prio_state`: 0 is normal, 1 is parked, 2 is taken out by the
drain. State 2 is read on its next readable event with no charge to the
budget.
- `us_socket_pause` switches the readable poll off and sets `is_paused`.
On a parked socket the poll is off already, so only the flag changes.
`us_socket_resume` undoes both.

<details><summary>Notes</summary>

Reported from a fuzz run as a two-process script: N TCP connections,
then all ClientHellos in one tick, and a control byte in that same tick
that makes the server pause every accepted socket. N=40 gave 12 to 30
sockets with callbacks after `pause()` on 1.4.2, 23 on canary d316760,
15 to 72 of 200 on main 6b394bf (ASAN). N=5 (nothing queues) gave 0
in every run. With this change the same script gives 0 for N=5, 40 and
200.

`resume()` on a parked socket was handled already: the "already parked"
arm in the readable dispatch (`loop.c:627`). This is the `pause()`
direction.

The fixture is deterministic because server and clients share one loop,
so the loop iteration counter (`getEventLoopStats().iteration`, the
counter of `us_internal_loop_pre`) is an exact clock. It parks sockets
with the recipe of `tls-close-all-sibling-fixture.ts`: pause every
accepted socket in `open`, then resume all of them at once, so the next
iteration reads 5 ClientHellos and parks the rest. An immediate of that
iteration pauses all 32 again. The loop then turns 36 iterations,
several times what the queue needs to drain.

Fixture output, release 1.4.3-canary.1 and a debug+ASAN build of main
without the change:

```
{"opened":32,"whilePaused":{"handshake":27,"data":27},"clientHandshakesWhilePaused":32,"serverHandshakes":32,"serverData":32,"pongs":32,"errors":0}
```

With the change (20 of 20 runs, 4 at a time):

```
{"opened":32,"whilePaused":{"handshake":0,"data":0},"clientHandshakesWhilePaused":5,"serverHandshakes":32,"serverData":32,"pongs":32,"errors":0}
```

`clientHandshakesWhilePaused: 5` is the budget: the 5 ClientHellos read
before the pause. It also proves that the other 27 sockets were parked
when `pause()` ran. The last three numbers are taken after `resume()`:
every socket that the drain left paused comes back.

A paused socket still pays one unit of the iteration's budget when the
drain takes it out, the same as a closed socket in that loop. Other
handshakes are then parked for one more iteration and go first in the
next drain (the queue is LIFO), so nothing starves.

Related open PRs do not touch the drain: oven-sh#42285 (`App::closeIdle` marks
parked sockets), oven-sh#36403 (timeout sweep for parked sockets), oven-sh#37099
(`pause()` arms writable interest).

Suites run on a debug+ASAN build: `socket-syscall-fault.test.ts`,
`socket.test.ts`, `tcp-server.test.ts`, `node-tls-server.test.ts`,
`node-tls-connect.test.ts`, `node-net-server.test.ts`,
`fetch.tls.test.ts`, `tls-keepalive.test.ts`, and the 245 vendored
`test-tls-*.js` and `test-https-*.js` files. Failures that are the same
without the change: `socket.test.ts` "should not call drain before
handshake" (needs DNS for `www.example.com`), "an unref'd Bun.listen()
... across GC" (over 5 s on a debug build), `node-tls-server.test.ts`
"SNICallback runs even when..." (`localhost` resolution in this
container), vendored `test-https-timeout.js` (hangs on a debug build of
main as well) and `test-tls-client-allow-partial-trust-chain.js` (uses
`describe` outside the test runner).

</details>

<!-- robobun:evidence:begin -->

---

**no test proof** · iteration 0 · platform-specific test(s) that do not
run on this machine, deferring to CI, which covers all platforms:
test/js/bun/net/socket-syscall-fault.test.ts

<!-- robobun:evidence:end -->
…#43900)

### Problem
- `test/js/bun/spawn/spawn-stdio-syscall-error.test.ts` is red on
alpine: `"lost": -82000`, not `0` (build 120303). oven-sh#43739 added the case,
not the bug.
- `read_loop` (`src/io/PipeReader.rs:766`) delivers the bytes read
before a failed read, then the error. The consumer asks for more inside
that delivery, and the reader reads the fd past the error. The error
comes late, or never.

### Fix
- `read_once` sets `PosixFlags::READ_FAILED` on a fatal error, and
`begin_read` does not read while it is set. The request parks, then
`on_reader_error` rejects it. Nothing clears the flag.
- Correct: libuv `uv__read` clears `UV_HANDLE_READABLE` before it
reports a read error.
- Verified: `test/js/bun/spawn/spawn-stdio-syscall-error.test.ts`, 17
pass. The four new cases fail without the fix. Suites: Notes.
- Self-reviewed: 15 concerns raised, 14 addressed. Not taken: a flag
reset in `start()`, which nothing on main needs.

### Background
- `PosixBufferedReader` reads the fd behind subprocess stdio, file
streams and the shell. Its parent gets `on_read_chunk`, then
`on_reader_done` or `on_reader_error`.
- `FileReader` is the parent behind a `ReadableStream`. `on_read_chunk`
resolves the parked `pull()`, and the reaction runs before it returns.
- Considered: a repeating shim failure hides the lost error. An error
stored in `FileReader` first needs a callback in every parent.
- oven-sh#43920 is a newer PR with the same change. Its test trigger is here.

### Downsides
- After a read error, a stream that ended with `'end'` now ends with
`'error'`, as in Node. With no listener the process stops.
- After a read error, `bun run --filter` no longer drains that pipe at
exit.
- Reads that do not fail pay nothing: `begin_read` tests one more bit.

<details><summary>Notes</summary>

**Trace without the fix** (bun 1.4.3-canary.1+367d939d9, shim logs each
`recv()`, writer `dd bs=1025`). The debug build of main at 8d36bff
does the same: 3 of 8 runs, two with no `'error'` and `lost` -7714150:

```
recv #5 len=262144 -> 95325
recv #6 len=166819 -> EIO (injected)      same fill_scratch call as #5
JS data 95325
recv #7 len=65536 -> 65536                 pull from inside the delivery, read_into
recv #8 .. #116                            to EOF
{"received":452025,"got":8000125,"lost":-7548100,"events":["stdout.close","close"]}
```

No `'error'` event: the reads reached EOF before `on_reader_error` ran,
and a stored error is only returned by a later pull. When the reads park
first, `on_reader_error` rejects that pull and `'error'` comes late.
That is the CI signature: the events match and `lost` is a negative
multiple of 1025.

**Why alpine.** In CI the failure is injected: the shim fails only the
Nth `recv()`, so a later `recv()` succeeds and the extra bytes show. The
failing `recv()` must follow bytes in the same wakeup. BusyBox `head`
writes 1025 bytes at a time, so a wakeup often holds a short `recv()`
and then the failing one. coreutils `head` fills the buffer in one
`recv()`. The same run fails on debian when the writer is slow. With a
writer that copies BusyBox `head` (stdio, 1024-byte buffer), the
`RECV_AT=6` case fails 7 of 40 runs on bun 1.4.3-canary (release), and
36 of 40 when the writer also spins between chunks. This branch (debug):
0 of 120, and 0 of 60 with `dd bs=1025`.

**With no shim.** A child with one AF_UNIX socket as fd 0 and fd 1
writes a line to stdout and reads stdin. The peer leaves that line
unread, sends 8192 bytes and closes. The kernel gives the child 8192
bytes, then `ECONNRESET`, then EOF.

| Runtime | stdin events |
|---|---|
| Node v26.3.0 | `'error'` `ECONNRESET` after 8192 bytes |
| bun 1.4.3-canary.1+367d939d9 | `'end'` after 8192 bytes, no error |
| this branch | `'error'` `ECONNRESET` after 8192 bytes |

**The new cases.** Each one reaches the reader from inside the delivery
in a different way. Whole-file runs of the describe block:

| Case | Entry | Release, no fix | Debug, no fix | Debug, guard in
`read_into` only | Debug, this branch |
|---|---|---|---|---|---|
| `child_process`, `'data'` listener | pull, `read_into` | fails 6 of 6
| fails 5 of 5 | passes | passes |
| `child_process`, `'readable'` and `read()` | `set_flowing(true)`,
`read` | fails 6 of 6 | fails 5 of 5 | fails 3 of 3 | passes |
| `Bun.spawn`, `lazy` | pull, `read_into` | fails 6 of 6 | fails 5 of 5
| passes | passes |
| `Bun.spawn`, reader started at spawn | pull, `read_into` | fails 6 of
6 | fails 5 of 5 | passes | passes |

- The first three use counts: `SPAWN_FAULT_RECV_CAP=4096` makes every
`recv()` short, so `fill_scratch` calls `recv()` again in the same
wakeup. `SPAWN_FAULT_RECV_EAGAIN_AT=2` ends the first read loop, so the
consumer's read parks and the next read is poll-driven.
`SPAWN_FAULT_RECV_AT` then fails after bytes in that wakeup. For the
`'readable'` case it is 19: #3 to #18 return 64 KiB, the highWaterMark,
so the reader is stopped and `read()` starts it again.
- The fourth uses state, and comes from oven-sh#43920: the writer waits for a
line on stdin, so the first read is parked when the bytes arrive.
`SPAWN_FAULT_RECV_MID_FILL=1` fails the `recv()` that follows one that
returned bytes, and `SPAWN_FAULT_READS_AFTER` counts the `recv()` calls
after it. Without the fix it is 1.
- With a count-based trigger and the reader started at spawn, the case
passed without the fix on a debug build: the buffered reader that runs
before JS reads `.stdout` took the bytes and the error. That is why this
case uses state.
- With the BusyBox-like writer at four speeds, the whole file passes 20
of 20 on this branch.

**With the fix**, `CAP=4096 EAGAIN_AT=2 RECV_AT=5`:

```
recv #3 -> 4096, recv #4 -> 4096, recv #5 -> EIO
JS data 8192
close(fd)
JS error EIO
```

**Node.** libuv `uv__read` (`src/unix/stream.c`): on a read error other
than `EAGAIN` it clears `UV_HANDLE_READABLE | UV_HANDLE_WRITABLE`, calls
`read_cb` with the error, then stops the watcher. It calls `read_cb`
once for each `read()`, so it never holds bytes and an error from one
batch.

**Placement.** EOF and the `maxBuffer` stop have the same guard at this
site: `close_if_final` closes the reader before the final chunk is
delivered. An error cannot use it, because a closed reader with no
stored error reads as a clean end. For the same reason `READ_FAILED` is
not part of `is_done()`.

**Parents** (14 `BufferedReaderParent` implementations, what each does
in `on_reader_error`):

- 3 release the fd: `FileReader`, `SubprocessPipeReader`, `Terminal`.
- 2 drop the reader: `FileResponseStream`, shell `subproc.rs`.
- 8 only do accounting: `filter_run.rs`, `multi_run.rs`,
`lifecycle_script_runner.rs`, `security_scanner.rs`, `git_runner.rs`,
both cron jobs, test `Worker.rs`. `lifecycle_script_runner.rs` and
`cron.rs` build a new reader with `init()` for each spawn.
- 1 is shared and can restart: the shell `IOReader`.

Only two read the same reader after an error. `filter_run.rs`
`drain_and_close_pipes` reads once more at exit. That read is now a
no-op, and `deinit()` follows. Before, it could reach a second terminal
callback and decrement `remaining_fds` twice. The shell
`IOReader::start()` does not restart a reader after a failed read on
main, because the fired one-shot poll still counts as registered. The
Windows reader gets one libuv callback for each read, so it has no
bytes-then-error batch.

**Left open.**

- The flag is permanent. oven-sh#39638 and oven-sh#37901 change `IOReader::start()` to
restart the shell's stdin reader. After this PR they must clear
`READ_FAILED` there, or a `cat` that follows a stdin read error gets no
data, no EOF and no error.
- Not in this PR: a batch that stops because the buffer is full is
labelled `ReadState::Eof` when the poll event carries the hangup
(`read_state`, `None if received_hup`). `Bun.write(file, proc.stdout)`
then writes 262144 of 400000 pending bytes and resolves. It is on main
and in 1.4.3-canary, and this PR does not change it. It needs its own
change.
- Not in this PR: release the fd on a read error once, in
`PosixBufferedReader::on_error`. oven-sh#41456 names it as a follow-up. oven-sh#41420,
oven-sh#41456 and oven-sh#42150 did it for one parent each.

**Suites run on the debug build:** `test/js/web/streams/streams.test.js`
(624 pass), `test/js/node/stream/node-stream.test.js` (112 pass),
`test/js/bun/spawn/spawn-streaming-stdout.test.ts` (pass),
`test/js/node/child_process/child_process.test.ts` (81 pass, 2 fail in
my container for reasons outside this change: "spawn in the default
shell" reads an empty `$SHELL`, and "extra stdio pipes are not
double-closed on GC" needs 5.0 s in a debug build against the 5 s
timeout, its script prints `OK`). With this branch's build, the test
file of oven-sh#43920 passes 17 of 17 in 3 runs.

oven-sh#43790 is open and edits the comment above the failing case. It changes
the event order in `native-readable.ts`, not the reader.

</details>

<!-- robobun:evidence:begin -->

---

**no test proof** · iteration 0 · platform-specific test(s) that do not
run on this machine, deferring to CI, which covers all platforms:
test/js/bun/spawn/spawn-stdio-syscall-error.test.ts

<!-- robobun:evidence:end -->
…rop console output on EAGAIN (oven-sh#43868)

### What does this PR do?

Same model as Node/libuv for `process.stdout` / `process.stderr` on
POSIX: a pipe or socket behind fd 1/2 is `O_NONBLOCK` (libuv's
`uv_pipe_open` does this too) and written asynchronously; TTYs and files
are synchronous. `O_NONBLOCK` lives on the shared open file description,
so it leaked in two places that Node covers and Bun did not:

| | before | after |
|---|---|---|
| `stdio: "inherit"` child runs `head -c 1000000` after parent used
`process.stdout` | `EAGAIN`, short output, exit 1 | full output, exit 0
|
| fd 1/2 flags seen by an inherit child | `O_NONBLOCK` | blocking |
| `console.log(1 MiB line)` after `process.stdout.isTTY`, piped | 720896
bytes | 1048577 bytes |
| `process.stdout.write(1 MiB)` to a full pipe | `false` + `'drain'` |
`false` + `'drain'` (unchanged) |
| same, after an inherit spawn (socket any OS / pipe Linux) | would
block like Node | `false` + `'drain'` |

- `spawn` clears `O_NONBLOCK` on the fds that become the child's 0–2, as
libuv's `uv__process_child_init` does. Done parent-side before
`posix_spawn` (same effect, since the description is shared, and macOS
file actions cannot `fcntl`).
- The native console writer waits for `POLLOUT` on `EAGAIN` instead of
dropping the rest of the line. Node does not need this because
`console.*` goes through the stdout stream there.

Supersedes oven-sh#33560 and oven-sh#33827.

### How did you verify your code works?

`test/js/node/process/process-stdio.test.ts` gains 9 tests (fd-flag
probe in an inherit child, `head -c` through inherited stdout, 1 MiB
`console.log`/`console.error`, 1 MiB through a real `pipe(2)` via `sh`,
and the `false` + `'drain'` contract over both a socketpair and a real
pipe). 6 fail on 1.4.3 (the post-spawn ones guard this PR's own spawn
change), all pass here; also ran `process-stdin`, `spawn`,
`child-process-stdio`, `console-log` locally on macOS.

<!-- robobun:evidence:begin -->

---

**no test proof** · iteration 0 · platform-specific test(s) that do not
run on this machine, deferring to CI, which covers all platforms:
test/js/node/process/process-stdio.test.ts

<!-- robobun:evidence:end -->
@socket-security

Copy link
Copy Markdown

Dependency limit exceeded — report not shown.

This pull request scan exceeded the 10,000-dependency limit applied to this scan, so the results are incomplete and may be inaccurate. To avoid reporting false positives, Socket has not posted a report.

Upgrade your plan to raise the dependency limit and get complete reports, or view the partial scan in the dashboard.

Socket is always free for open source. If this is a non-commercial open source project, contact us to request a free Team account.

@steipete
steipete marked this pull request as ready for review September 30, 2026 05:19
@steipete
steipete merged commit 7862bb3 into main Sep 30, 2026
10 checks passed
@steipete
steipete deleted the claude/sync-upstream-20260929 branch September 30, 2026 05:20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants