From 0f382d91762e04800b64d8ff693c53ead05c3912 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 5 May 2026 10:00:29 +0000 Subject: [PATCH 1/8] Register all top-level symbols before walking nested scopes in bundler renamer MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The ESM bundler renamer used to interleave two operations per part: 1. register the part's top-level symbols in the root scope, and 2. walk the part's nested scopes to rename collisions. Because nested-scope walking for part N ran before part M>N's top-level symbols were registered, a local binding in part N could be renamed to a name that later became a top-level symbol in part M, shadowing it. Minimal repro — after bundling, `r2()` inside typecheck called the `Expression` instance from `let r2` (renamed from `let r`) instead of the top-level `r2` function: // conflict.js export function r() { return "top-level r"; } // module.js function typecheck(node) { let r, t, c; // bundler renames r -> r2 (conflict with top-level r) /* ... */ return r2().bo4(d, n, s).a(); // resolves to local r2, not top-level } function r2() { /* ... */ } // main.js import * as conflict from "./conflict.js"; import { run } from "./module.js"; conflict.r(); // forces "r" into the root scope run(); Fix: split the single-pass loop into two passes. Pass 1 adds every top-level symbol (across all files in the chunk) into r.root. Pass 2 walks each file's nested scopes. By the time findUnusedName runs, r.root is fully populated, so r2 is recognized as taken and a free name is chosen instead. Matches esbuild's structure. Fixes #30269 --- .../linker_context/renameSymbolsInChunk.zig | 54 ++++++++- test/regression/issue/30269.test.ts | 110 ++++++++++++++++++ 2 files changed, 159 insertions(+), 5 deletions(-) create mode 100644 test/regression/issue/30269.test.ts diff --git a/src/bundler/linker_context/renameSymbolsInChunk.zig b/src/bundler/linker_context/renameSymbolsInChunk.zig index 0e88ef97ae9e..0dcb460556cc 100644 --- a/src/bundler/linker_context/renameSymbolsInChunk.zig +++ b/src/bundler/linker_context/renameSymbolsInChunk.zig @@ -145,6 +145,30 @@ pub fn renameSymbolsInChunk( var sorted = &sorted_; defer sorted.deinit(); + // Two passes are required so that every top-level symbol is registered in + // `r.root` before any nested scope is visited. Without this, a local + // binding in file/part N could collide-rename into a name that is later + // claimed by a top-level symbol in file/part M (M > N), silently shadowing + // it in the output. See https://github.com/oven-sh/bun/issues/30269. + // + // Pass 1 adds all top-level symbols for the chunk (across every file). + // Pass 2 recurses into the nested scopes; by then `r.root` is fully + // populated so `findUnusedName` sees every potential top-level collision. + // + // `nested_scopes` stores the scopes to walk in pass 2, one entry per file + // in the same order as `files_in_order`. For ESM/no-wrap the entry is the + // concatenation of `part.scopes` for every live part. For CJS-wrapped + // files the entry is the single module scope (the whole module body lives + // inside the wrapper closure, so it's all "nested"). + var nested_scopes: std.array_list.Managed([]const *js_ast.Scope) = try .initCapacity(r.temp_allocator, files_in_order.len); + defer nested_scopes.deinit(); + + // Scratch buffer reused across files to accumulate `part.scopes`. + var scopes_scratch = std.array_list.Managed(*js_ast.Scope).init(r.temp_allocator); + defer scopes_scratch.deinit(); + + // Pass 1: add all top-level symbols across the whole chunk, and stash the + // nested scopes that pass 2 will visit. for (files_in_order) |source_index| { const wrap = all_flags[source_index].wrap; const parts: []const Part = all_parts[source_index].slice(); @@ -213,7 +237,13 @@ pub fn renameSymbolsInChunk( } } } - r.assignNamesRecursiveWithNumberScope(&r.root, &all_module_scopes[source_index], source_index, sorted); + + // Pass 2 will walk the module scope itself (the module body is + // inside the CJS wrapper closure, so everything in it is nested + // from the renamer's point of view). + const one = try r.temp_allocator.alloc(*js_ast.Scope, 1); + one[0] = &all_module_scopes[source_index]; + nested_scopes.appendAssumeCapacity(one); continue; }, @@ -238,15 +268,29 @@ pub fn renameSymbolsInChunk( else => {}, } + scopes_scratch.clearRetainingCapacity(); for (parts) |*part| { if (!part.is_live) continue; r.addTopLevelDeclaredSymbols(part.declared_symbols); - for (part.scopes) |scope| { - r.assignNamesRecursiveWithNumberScope(&r.root, scope, source_index, sorted); - } - r.number_scope_pool.hive.used = @TypeOf(r.number_scope_pool.hive.used).initEmpty(); + try scopes_scratch.appendSlice(part.scopes); + } + + const stashed = try r.temp_allocator.dupe(*js_ast.Scope, scopes_scratch.items); + nested_scopes.appendAssumeCapacity(stashed); + } + + // Pass 2: now that `r.root` has every top-level symbol in the chunk, + // recurse into each file's nested scopes to rename collisions. + for (files_in_order, nested_scopes.items) |source_index, scopes| { + for (scopes) |scope| { + r.assignNamesRecursiveWithNumberScope(&r.root, scope, source_index, sorted); } + // Bulk-release every NumberScope we borrowed from the pool while + // processing this file. The recursive walk has already put each scope + // back individually; this is just a defensive reset that matches the + // previous per-part behavior. + r.number_scope_pool.hive.used = @TypeOf(r.number_scope_pool.hive.used).initEmpty(); } return r.toRenamer(); diff --git a/test/regression/issue/30269.test.ts b/test/regression/issue/30269.test.ts new file mode 100644 index 000000000000..cca8c8d570ba --- /dev/null +++ b/test/regression/issue/30269.test.ts @@ -0,0 +1,110 @@ +// https://github.com/oven-sh/bun/issues/30269 +// +// The ESM bundler renamer used to interleave two operations per part: +// 1. register that part's top-level symbols in the root scope, and +// 2. walk that part's nested scopes to rename collisions with the root. +// +// Because nested-scope walking for part N happened before part M>N's +// top-level symbols had been registered, a local binding in part N could be +// renamed to a name (`r` → `r2`) that later became a top-level symbol in +// part M (here the `r2` function). The local `r2` then shadowed the +// top-level `r2`, and callers inside `typecheck` invoked an `Expression` +// instance instead of the function. +// +// Fix: split the single-pass interleaved loop into two passes — register +// all top-level symbols for the whole chunk first, then walk nested scopes. +// Matches esbuild's structure. +import { test, expect } from "bun:test"; +import { bunEnv, bunExe, tempDir } from "harness"; + +test("#30269 bundler doesn't rename a nested local into another top-level symbol's name", async () => { + using dir = tempDir("bun-issue-30269", { + // Importing this forces Bun's ESM renamer to treat `r` as a conflicting + // name at the chunk's root scope. Removing `conflict.r()` from main.js + // hides the bug. + "conflict.js": ` + export function r() { + return "top-level r"; + } + `, + // `typecheck` has a nested \`let r\`. The renamer picks \`r2\` for it — + // but \`r2\` is already a top-level function in the same file. + "module.js": ` + class Expression {} + + export function run() { + const result = typecheck({ left: new Expression(), op: {}, right: {} }); + if (result !== true) throw new Error("expected true"); + return result; + } + + function typecheck(node) { + let r, t, c; + block: { + let k = node.left; + let I = node.op; + let q = node.right; + r = k; + t = I; + c = q; + break block; + } + + let d = r; + let n = t; + let s = c; + return r2().bo4(d, n, s).a(); + } + + function r2() { + return { + bo4() { + return { + a() { + return true; + }, + }; + }, + }; + } + `, + "main.js": ` + import * as conflict from "./conflict.js"; + import { run } from "./module.js"; + + conflict.r(); + console.log("ok:", run()); + `, + }); + + // Bundle, then run the bundled file. The renamer bug is triggered during + // bundling; executing the bundle is what surfaces the TypeError. + await using build = Bun.spawn({ + cmd: [bunExe(), "build", "--outfile", "out.js", "main.js"], + env: bunEnv, + cwd: String(dir), + stdout: "pipe", + stderr: "pipe", + }); + { + const [stdout, stderr, exitCode] = await Promise.all([build.stdout.text(), build.stderr.text(), build.exited]); + expect(stderr).not.toContain("error"); + expect(exitCode).toBe(0); + // `stdout` carries the "Bundled N modules" banner; referenced to keep it. + expect(stdout).toContain("out.js"); + } + + await using run = Bun.spawn({ + cmd: [bunExe(), "out.js"], + env: bunEnv, + cwd: String(dir), + stdout: "pipe", + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([run.stdout.text(), run.stderr.text(), run.exited]); + // On the buggy build this stderr contains: + // TypeError: r2 is not a function. (In 'r2()', 'r2' is an instance of Expression) + expect(stderr).toBe(""); + expect(stdout).toBe("ok: true\n"); + expect(exitCode).toBe(0); +}); From a763847c6cf4162763b6e2840403972ca3697a40 Mon Sep 17 00:00:00 2001 From: "autofix-ci[bot]" <114827586+autofix-ci[bot]@users.noreply.github.com> Date: Tue, 5 May 2026 10:02:41 +0000 Subject: [PATCH 2/8] [autofix.ci] apply automated fixes --- test/regression/issue/30269.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/regression/issue/30269.test.ts b/test/regression/issue/30269.test.ts index cca8c8d570ba..c1900e3e79be 100644 --- a/test/regression/issue/30269.test.ts +++ b/test/regression/issue/30269.test.ts @@ -14,7 +14,7 @@ // Fix: split the single-pass interleaved loop into two passes — register // all top-level symbols for the whole chunk first, then walk nested scopes. // Matches esbuild's structure. -import { test, expect } from "bun:test"; +import { expect, test } from "bun:test"; import { bunEnv, bunExe, tempDir } from "harness"; test("#30269 bundler doesn't rename a nested local into another top-level symbol's name", async () => { From fbd9cb6d430df263ac85935387ff6be227ed4fb9 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 5 May 2026 10:17:16 +0000 Subject: [PATCH 3/8] review: simplify two-pass, drop brittle stderr assertion MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Eliminate the intermediate nested_scopes/scopes_scratch buffers. Pass 1 over files_in_order adds top-level symbols only, pass 2 over the same order walks each file's nested scopes. No per-file slice allocations, no duplicated buffers for coderabbit to flag as potential leaks. - Regression test: stop asserting stderr is literally empty. The TypeError signature is implied by stdout + exit code; stderr can hold benign debug-build warnings (MADV_DONTNEED) that we don't want to flake on. The behavior is unchanged — every top-level symbol still lands in r.root before the first nested-scope walk. --- .../linker_context/renameSymbolsInChunk.zig | 54 ++++++++----------- test/regression/issue/30269.test.ts | 3 +- 2 files changed, 25 insertions(+), 32 deletions(-) diff --git a/src/bundler/linker_context/renameSymbolsInChunk.zig b/src/bundler/linker_context/renameSymbolsInChunk.zig index 0dcb460556cc..ad906d34307d 100644 --- a/src/bundler/linker_context/renameSymbolsInChunk.zig +++ b/src/bundler/linker_context/renameSymbolsInChunk.zig @@ -154,21 +154,8 @@ pub fn renameSymbolsInChunk( // Pass 1 adds all top-level symbols for the chunk (across every file). // Pass 2 recurses into the nested scopes; by then `r.root` is fully // populated so `findUnusedName` sees every potential top-level collision. - // - // `nested_scopes` stores the scopes to walk in pass 2, one entry per file - // in the same order as `files_in_order`. For ESM/no-wrap the entry is the - // concatenation of `part.scopes` for every live part. For CJS-wrapped - // files the entry is the single module scope (the whole module body lives - // inside the wrapper closure, so it's all "nested"). - var nested_scopes: std.array_list.Managed([]const *js_ast.Scope) = try .initCapacity(r.temp_allocator, files_in_order.len); - defer nested_scopes.deinit(); - - // Scratch buffer reused across files to accumulate `part.scopes`. - var scopes_scratch = std.array_list.Managed(*js_ast.Scope).init(r.temp_allocator); - defer scopes_scratch.deinit(); - - // Pass 1: add all top-level symbols across the whole chunk, and stash the - // nested scopes that pass 2 will visit. + + // Pass 1: add every top-level symbol in the chunk to `r.root`. for (files_in_order) |source_index| { const wrap = all_flags[source_index].wrap; const parts: []const Part = all_parts[source_index].slice(); @@ -237,13 +224,10 @@ pub fn renameSymbolsInChunk( } } } - - // Pass 2 will walk the module scope itself (the module body is - // inside the CJS wrapper closure, so everything in it is nested - // from the renamer's point of view). - const one = try r.temp_allocator.alloc(*js_ast.Scope, 1); - one[0] = &all_module_scopes[source_index]; - nested_scopes.appendAssumeCapacity(one); + // The module body is inside the CJS wrapper closure, so all + // of its symbols are treated as nested by the renamer; pass 2 + // will walk `all_module_scopes[source_index]`. No per-part + // top-level symbols to add here. continue; }, @@ -268,23 +252,31 @@ pub fn renameSymbolsInChunk( else => {}, } - scopes_scratch.clearRetainingCapacity(); for (parts) |*part| { if (!part.is_live) continue; - r.addTopLevelDeclaredSymbols(part.declared_symbols); - try scopes_scratch.appendSlice(part.scopes); } - - const stashed = try r.temp_allocator.dupe(*js_ast.Scope, scopes_scratch.items); - nested_scopes.appendAssumeCapacity(stashed); } // Pass 2: now that `r.root` has every top-level symbol in the chunk, // recurse into each file's nested scopes to rename collisions. - for (files_in_order, nested_scopes.items) |source_index, scopes| { - for (scopes) |scope| { - r.assignNamesRecursiveWithNumberScope(&r.root, scope, source_index, sorted); + for (files_in_order) |source_index| { + const wrap = all_flags[source_index].wrap; + switch (wrap) { + .cjs => { + // For CJS-wrapped modules, the entire module scope is nested + // (it lives inside the wrapper closure). Walk it directly. + r.assignNamesRecursiveWithNumberScope(&r.root, &all_module_scopes[source_index], source_index, sorted); + }, + else => { + const parts: []const Part = all_parts[source_index].slice(); + for (parts) |*part| { + if (!part.is_live) continue; + for (part.scopes) |scope| { + r.assignNamesRecursiveWithNumberScope(&r.root, scope, source_index, sorted); + } + } + }, } // Bulk-release every NumberScope we borrowed from the pool while // processing this file. The recursive walk has already put each scope diff --git a/test/regression/issue/30269.test.ts b/test/regression/issue/30269.test.ts index c1900e3e79be..f502a0ea0334 100644 --- a/test/regression/issue/30269.test.ts +++ b/test/regression/issue/30269.test.ts @@ -104,7 +104,8 @@ test("#30269 bundler doesn't rename a nested local into another top-level symbol const [stdout, stderr, exitCode] = await Promise.all([run.stdout.text(), run.stderr.text(), run.exited]); // On the buggy build this stderr contains: // TypeError: r2 is not a function. (In 'r2()', 'r2' is an instance of Expression) - expect(stderr).toBe(""); + // Asserting on stdout + exit code is enough; stderr can hold unrelated + // debug-build warnings (e.g. MADV_DONTNEED) that we don't want to flake on. expect(stdout).toBe("ok: true\n"); expect(exitCode).toBe(0); }); From c7d0a7f17b4aa1374b418b77fec1df35ebaedc9c Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 5 May 2026 10:19:15 +0000 Subject: [PATCH 4/8] review: drop weak stderr substring check, stdout before exitCode MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Follows the CLAUDE.md convention for subprocess tests — negative substring checks on stderr are fragile, and asserting stdout before exitCode gives a more useful error message on test failure. Pass stderr through as the exitCode assertion's message so build failures surface the actual output. --- test/regression/issue/30269.test.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/test/regression/issue/30269.test.ts b/test/regression/issue/30269.test.ts index f502a0ea0334..269244bc41ae 100644 --- a/test/regression/issue/30269.test.ts +++ b/test/regression/issue/30269.test.ts @@ -88,10 +88,10 @@ test("#30269 bundler doesn't rename a nested local into another top-level symbol }); { const [stdout, stderr, exitCode] = await Promise.all([build.stdout.text(), build.stderr.text(), build.exited]); - expect(stderr).not.toContain("error"); - expect(exitCode).toBe(0); - // `stdout` carries the "Bundled N modules" banner; referenced to keep it. + // `stdout` carries the "Bundled N modules" banner; assert on it before + // the exit-code check so a build failure shows what bun actually printed. expect(stdout).toContain("out.js"); + expect(exitCode, stderr).toBe(0); } await using run = Bun.spawn({ From c1839e905a72fb8fdd8c3189de4b9dd7f30d6c0f Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 5 May 2026 10:33:00 +0000 Subject: [PATCH 5/8] review: correct the hive.used reset comment MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The linear-chain while loop inside assignNamesRecursiveWithNumberScope can get() several NumberScopes but its single defer only put()s the final one back. Intermediate slots stay marked used in the 128-slot hive until the bulk reset here reclaims them. The reset is load-bearing, not defensive — claude[bot] flagged the misleading wording on review. --- src/bundler/linker_context/renameSymbolsInChunk.zig | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/bundler/linker_context/renameSymbolsInChunk.zig b/src/bundler/linker_context/renameSymbolsInChunk.zig index ad906d34307d..0bb758e2210e 100644 --- a/src/bundler/linker_context/renameSymbolsInChunk.zig +++ b/src/bundler/linker_context/renameSymbolsInChunk.zig @@ -278,10 +278,12 @@ pub fn renameSymbolsInChunk( } }, } - // Bulk-release every NumberScope we borrowed from the pool while - // processing this file. The recursive walk has already put each scope - // back individually; this is just a defensive reset that matches the - // previous per-part behavior. + // Bulk-reclaim hive slots for NumberScopes that the linear-chain walk + // in `assignNamesRecursiveWithNumberScope` acquired but did not put + // back individually — the single `defer put(s)` there only returns the + // final scope in each chain, so without this reset intermediate slots + // stay marked used and the 128-slot hive eventually spills to the + // arena fallback. r.number_scope_pool.hive.used = @TypeOf(r.number_scope_pool.hive.used).initEmpty(); } From 4f5290477b10100d364116c2af07da7c17f562ed Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 5 May 2026 10:34:42 +0000 Subject: [PATCH 6/8] review: use house-style if-pattern for exitCode assertion expect(exitCode, stderr).toBe(0) passes stderr as a custom message but the repo convention is to use an if-check immediately before the exitCode assertion so stderr shows up in the diff when the exit code is non-zero. --- test/regression/issue/30269.test.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/test/regression/issue/30269.test.ts b/test/regression/issue/30269.test.ts index 269244bc41ae..8f7b3d54207d 100644 --- a/test/regression/issue/30269.test.ts +++ b/test/regression/issue/30269.test.ts @@ -91,7 +91,8 @@ test("#30269 bundler doesn't rename a nested local into another top-level symbol // `stdout` carries the "Bundled N modules" banner; assert on it before // the exit-code check so a build failure shows what bun actually printed. expect(stdout).toContain("out.js"); - expect(exitCode, stderr).toBe(0); + if (exitCode !== 0) expect(stderr).toBe(""); + expect(exitCode).toBe(0); } await using run = Bun.spawn({ @@ -107,5 +108,6 @@ test("#30269 bundler doesn't rename a nested local into another top-level symbol // Asserting on stdout + exit code is enough; stderr can hold unrelated // debug-build warnings (e.g. MADV_DONTNEED) that we don't want to flake on. expect(stdout).toBe("ok: true\n"); + if (exitCode !== 0) expect(stderr).toBe(""); expect(exitCode).toBe(0); }); From 3a661ffda25c6808d2fa95c5996c93969675931d Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 5 May 2026 11:08:05 +0000 Subject: [PATCH 7/8] =?UTF-8?q?ci:=20retry=20=E2=80=94=20flaky=20Windows?= =?UTF-8?q?=20tests=20unrelated=20to=20bundler=20renamer?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Build 51718 failed on the well-known Windows flakes: - test-http-should-emit-close-when-connection-is-aborted (100% of recent failed builds hit this) - jsc-stress.test.ts ipint-bbq-osr-with-try3 'mprotect failed: 487' (57% rate) - spawn-ipc-gc.test.ts GC-count timing - bake/dev-and-prod.test.ts 'hmr handles rapid consecutive edits' - bun-install-registry.test.ts hoisting peer 1.0.10 None of these touch bundler code. The PR's sole code change is in src/bundler/linker_context/renameSymbolsInChunk.zig. From b117b7fadfea1ab809edfab46f072e6040dfa8ad Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 5 May 2026 11:35:01 +0000 Subject: [PATCH 8/8] ci: retry #2 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Build 51726 still hit test-http-should-emit-close-when-connection-is-aborted (100% base rate on recent Windows builds — it failed 3 attempts in a row via runner.node.mjs's per-file retries). Windows-11 aarch64 passed this round; retrying to shake the x64 agents.