From 25752a276f26c3a950e745a90b67a3761a46ebd4 Mon Sep 17 00:00:00 2001 From: Dimitri Kennedy <344842+roodboi@users.noreply.github.com> Date: Thu, 26 Nov 2026 16:17:44 -0500 Subject: [PATCH 1/4] test: make parallel-flaky files safe to run together (HACK-2727) Five test compiles ran `bun build --compile` with the checkout as their working directory. Bun stages the executable as a transient `..bun-build` there, so every other file's checkout write guard that read `git status` meanwhile failed its run. Compile in the test's own directory, and add a scan that keeps it that way. Give the in-process env migration cases, the SIGKILL boundary case, the sync-spawn scan and the five-CLI extra-hosts case load budgets, with the measured reasons written next to each. Make the TTY fixture signal only after its worker has finished all input and output. Co-Authored-By: Claude Opus 5.5 --- tests/compile-working-directory.test.ts | 188 ++++++++++++++++++++ tests/daemon-systemd-cli.test.ts | 4 +- tests/env-migration-journal.test.ts | 35 +++- tests/fixtures/tty-cancellation.py | 6 +- tests/host-exec-tty.test.ts | 7 +- tests/internal-extra-hosts-worktree.test.ts | 8 +- tests/native-interactive-exec.test.ts | 4 + tests/prerelease-plan.test.ts | 6 +- tests/sync-spawn-bound.test.ts | 8 +- tests/v4-upgrade.test.ts | 6 +- 10 files changed, 260 insertions(+), 12 deletions(-) create mode 100644 tests/compile-working-directory.test.ts diff --git a/tests/compile-working-directory.test.ts b/tests/compile-working-directory.test.ts new file mode 100644 index 0000000000..2552d415ae --- /dev/null +++ b/tests/compile-working-directory.test.ts @@ -0,0 +1,188 @@ +import { expect, test } from "bun:test"; +import { readFile } from "node:fs/promises"; +import { resolve } from "node:path"; +import { runFixtureGitSync } from "./helpers/fixture-git.ts"; + +/** + * `bun build --compile` stages its executable as a transient + * `.-00000000.bun-build` file in its working directory before renaming + * it to `--outfile`. A test that compiles with the checkout as its working + * directory, named or inherited, puts that file in the checkout for the + * length of the compile. When test files run in parallel, every other file's + * checkout write guard (HACK-1343) that reads `git status` in that window + * sees an untracked file and fails a run whose cases all passed (HACK-2727). + * Each compile must run in a directory the test owns. + */ + +const REPO = resolve(import.meta.dir, ".."); + +/** How far after its `"--compile"` a spawn's own options may name `cwd`. */ +const OPTIONS_WINDOW = 30; + +/** A `"--compile"` argv element, not a mention in a string or a call. */ +const COMPILE_ELEMENT = /(?:^|[[,])\s*"--compile"\s*[,\]]/; + +/** A `cwd:` option key. */ +const CWD_OPTION = /\bcwd:\s*/; + +/** + * The value expression of the `cwd:` option on `line`, up to its top-level + * `,` or `}` or the line's end; null when the line names no `cwd`. + */ +function cwdValue(line: string): string | null { + const match = CWD_OPTION.exec(line); + if (!match) { + return null; + } + let depth = 0; + let value = ""; + for (const char of line.slice(match.index + match[0].length)) { + if (depth === 0 && (char === "," || char === "}")) { + break; + } + if (char === "(" || char === "[") { + depth += 1; + } else if (char === ")" || char === "]") { + depth -= 1; + } + value += char; + } + return value.trim(); +} + +/** Working-directory expressions that name the checkout itself. */ +const CHECKOUT_CWD = + /^(?:REPO|REPO_ROOT|ROOT|repository|repoRoot|process\.cwd\(\)|import\.meta\.dir|resolve\(import\.meta\.dir, "\.\."\)|join\(import\.meta\.dir, "\.\."\))$/; + +/** + * Compile sites that may use the checkout. The release build compiles from + * the repository root as a release step; no test runs it. + */ +const RELEASE_ONLY = new Set(["scripts/build-release.ts"]); + +function isComment(line: string): boolean { + const trimmed = line.trim(); + return ( + trimmed.startsWith("//") || + trimmed.startsWith("*") || + trimmed.startsWith("/*") + ); +} + +/** + * `path:line` and reason of each compile in `text` whose spawn names no + * working directory or names the checkout. + */ +function checkoutCompiles(opts: { + readonly path: string; + readonly text: string; +}): { readonly checked: number; readonly found: readonly string[] } { + const lines = opts.text.split("\n"); + const found: string[] = []; + let checked = 0; + for (const [index, line] of lines.entries()) { + if (isComment(line) || !COMPILE_ELEMENT.test(line)) { + continue; + } + checked += 1; + let cwd: string | null = null; + for ( + let at = index; + at < Math.min(lines.length, index + OPTIONS_WINDOW); + at += 1 + ) { + const candidate = lines[at] ?? ""; + if (at > index && COMPILE_ELEMENT.test(candidate)) { + break; + } + if (isComment(candidate)) { + continue; + } + cwd = cwdValue(candidate); + if (cwd !== null) { + break; + } + } + if (cwd === null) { + found.push(`${opts.path}:${index + 1} inherits the runner's directory`); + } else if (CHECKOUT_CWD.test(cwd)) { + found.push(`${opts.path}:${index + 1} runs in the checkout (${cwd})`); + } + } + return { checked, found }; +} + +test("no test or script compiles with the checkout as its working directory", async () => { + const listed = runFixtureGitSync({ + cwd: REPO, + args: ["ls-files", "-z", "--", "tests/*.ts", "scripts/*.ts"], + }); + expect(listed.exitCode).toBe(0); + const found: string[] = []; + let checked = 0; + for (const path of listed.stdout.split("\0")) { + if (path.length === 0 || RELEASE_ONLY.has(path)) { + continue; + } + const text = await readFile(resolve(REPO, path), "utf8"); + const result = checkoutCompiles({ path, text }); + checked += result.checked; + found.push(...result.found); + } + expect( + found, + "Run bun build --compile in a directory the test owns: its transient .bun-build lands in the working directory (HACK-2727)." + ).toEqual([]); + // The scan reached the known compile sites in tests and scripts. + expect(checked).toBeGreaterThanOrEqual(9); +}); + +test("the scan tells an owned working directory from the checkout", () => { + const owned = [ + "const build = Bun.spawn(", + ' [process.execPath, "build", entry, "--compile", "--outfile", out],', + ' { cwd: root, stdout: "pipe" }', + ");", + ].join("\n"); + expect(checkoutCompiles({ path: "a.ts", text: owned })).toEqual({ + checked: 1, + found: [], + }); + const inherited = [ + "Bun.spawn(", + " [", + " process.execPath,", + ' "build",', + ' "index.ts",', + ' "--compile",', + " ],", + ' { stdout: "pipe" }', + ");", + ].join("\n"); + expect(checkoutCompiles({ path: "b.ts", text: inherited }).found).toEqual([ + "b.ts:6 inherits the runner's directory", + ]); + const checkout = [ + 'Bun.spawn([process.execPath, "build", "--compile", entry], {', + ' cwd: resolve(import.meta.dir, ".."),', + "});", + ].join("\n"); + expect(checkoutCompiles({ path: "c.ts", text: checkout }).found).toEqual([ + 'c.ts:1 runs in the checkout (resolve(import.meta.dir, ".."))', + ]); + // A neighbouring compile's cwd does not stand in for a missing one. + const neighbours = [ + 'run(["build", "--compile", a]);', + 'run(["build", "--compile", b], { cwd: root });', + ].join("\n"); + expect(checkoutCompiles({ path: "d.ts", text: neighbours }).found).toEqual([ + "d.ts:1 inherits the runner's directory", + ]); + // Mentions in strings, calls and comments are not compiles. + const mentions = [ + 'if (line.includes("--compile")) {}', + "const text = ' \"--compile\",';", + '// ["build", "--compile"]', + ].join("\n"); + expect(checkoutCompiles({ path: "e.ts", text: mentions }).checked).toBe(0); +}); diff --git a/tests/daemon-systemd-cli.test.ts b/tests/daemon-systemd-cli.test.ts index 91450ebf02..51b7020571 100644 --- a/tests/daemon-systemd-cli.test.ts +++ b/tests/daemon-systemd-cli.test.ts @@ -172,7 +172,9 @@ async function compileHack(f: Fixture): Promise { outfile, ], { - cwd: REPO_ROOT, + // The compiler stages a transient `..bun-build` in its working + // directory: the fixture root, never the checkout (HACK-2727). + cwd: f.root, env: privateCliEnv({ root: f.root }), stdin: "ignore", stdout: "ignore", diff --git a/tests/env-migration-journal.test.ts b/tests/env-migration-journal.test.ts index c2ee71af9a..8c32b6e1db 100644 --- a/tests/env-migration-journal.test.ts +++ b/tests/env-migration-journal.test.ts @@ -1,4 +1,10 @@ -import { afterEach, beforeEach, expect, test } from "bun:test"; +import { + afterEach, + beforeEach, + expect, + setDefaultTimeout, + test, +} from "bun:test"; import { chmod, lstat, @@ -46,6 +52,24 @@ import { fixtureChildren } from "./helpers/fixture-children.ts"; import { runFixtureGit } from "./helpers/fixture-git.ts"; import { privateCliEnv } from "./helpers/private-cli-env.ts"; +/** + * Bun timeout for every case and hook here that sets none of its own. The + * cases wait on no timer: each drives the migration in process through a + * fixed chain of preview, apply, run proof, cleanup and rollback steps, and + * every step re-probes git (`ls-files`, `rev-parse`, `check-ignore`) for each + * env file. One case makes about 60 sequential `git` spawns plus private-file + * reads and atomic writes, so its wall time is process-spawn and file-system + * latency, which grows with host load. On a 16-CPU Mac the slowest case takes + * 1.7 s alone; with 12 test files running at once cases took 4.4 s and others + * crossed Bun's 5 s default while their assertions held (HACK-2727). A case + * that times out keeps running after `afterEach` removes its root, so its + * stranded migration then throws refusals into the next case. This is a hang + * guard, not a speed assertion, and `setDefaultTimeout` is scoped to this + * file, so it changes no other file's budget. + */ +const MIGRATION_CASE_BUDGET_MS = 60_000; +setDefaultTimeout(MIGRATION_CASE_BUDGET_MS); + const SENTINEL = "synthetic-upgrade-journal-value"; const QA = "synthetic-upgrade-qa-value"; const isolated = [ @@ -1755,6 +1779,13 @@ test("rollback retains a new shared key used by another checkout", async () => { ).toBe(QA); }); +// Budget (300 s, below): for every journal and publication boundary of three +// scenarios this case copies a fresh project, starts a cold Bun child, kills +// it at the boundary and resumes in process. It waits on no timer, so its wall +// time is that many process starts and migrations under the host's load: 33 s +// alone on a 16-CPU Mac, up to 106 s with 12 test files running at once +// (within 14 s of its old 120 s budget) and 123 s with more load beside it +// (HACK-2727). A hang guard, not a speed assertion. test("SIGKILL at every journal/publication boundary resumes without losing an overlay value", async () => { const composePath = join(project.projectDir, "docker-compose.yml"); const originalCompose = await readFile(composePath, "utf8"); @@ -1921,4 +1952,4 @@ test("SIGKILL at every journal/publication boundary resumes without losing an ov } } } -}, 120_000); +}, 300_000); diff --git a/tests/fixtures/tty-cancellation.py b/tests/fixtures/tty-cancellation.py index 8bb40c6209..fee6a5c47b 100644 --- a/tests/fixtures/tty-cancellation.py +++ b/tests/fixtures/tty-cancellation.py @@ -40,6 +40,10 @@ def worker(root, behavior): (root / 'input.txt').write_text(sys.stdin.readline()) print('child stdout', flush=True) print('child stderr', file=sys.stderr, flush=True) + # Published only after every input and output above is complete: the + # probe signals on this, so a slow worker is never cancelled between + # creating input.txt and printing (HACK-2727). + (root / 'io.done').write_text('yes') if behavior == 'normal': sys.exit(7) while True: @@ -147,7 +151,7 @@ def wait_for(names, seconds=8): raise RuntimeError('Command did not resume after fg') if behavior in ['normal', 'io', 'pipe']: os.write(fd, b'hello tty\n') - if not wait_for(['input.txt']): + if not wait_for(['io.done']): raise RuntimeError('Command did not read terminal stdin') if behavior != 'normal': if mode == 'paused': diff --git a/tests/host-exec-tty.test.ts b/tests/host-exec-tty.test.ts index 7f2391de66..e95ca4c7b8 100644 --- a/tests/host-exec-tty.test.ts +++ b/tests/host-exec-tty.test.ts @@ -166,14 +166,17 @@ test.skipIf(!Bun.which("python3"))( [ process.execPath, "build", - "index.ts", + resolve(import.meta.dir, "../index.ts"), "--compile", ...CLI_COMPILE_DEFINE_ARGS, "--outfile", binary, ], { - cwd: resolve(import.meta.dir, ".."), + // `bun build --compile` stages a transient `..bun-build` in + // its working directory. Keep it in this test's directory, never in + // the checkout another file's write guard is reading (HACK-2727). + cwd: directory, stdin: "ignore", stdout: "pipe", stderr: "pipe", diff --git a/tests/internal-extra-hosts-worktree.test.ts b/tests/internal-extra-hosts-worktree.test.ts index 02f075a5b7..50fd5158e2 100644 --- a/tests/internal-extra-hosts-worktree.test.ts +++ b/tests/internal-extra-hosts-worktree.test.ts @@ -161,6 +161,12 @@ test("malformed inherited alias data fails rather than silently removing aliases ); }); +// Budget (60 s, below): this case waits on no timer. It starts the CLI from +// source five times in a row, so its wall time is five cold Bun starts of the +// whole CLI, which grows with host load. It reached 4.5 s of Bun's 5 s default +// with 12 test files running at once on a 16-CPU Mac and passed it under more +// load beside it, where the CLI still running at the timeout was killed into +// the next case (HACK-2727). A hang guard, not a speed assertion. test("CLI list provenance, unset tombstone, and set affect only the linked checkout", async () => { const f = await fixture(); for (const dir of [f.primary, f.branch]) { @@ -212,7 +218,7 @@ test("CLI list provenance, unset tombstone, and set affect only the linked check ).toEqual({ "search.test": "host-gateway" }); await cli("set", "search.test", "127.0.0.2"); expect(JSON.parse(await cli("list"))).toEqual({ "search.test": "127.0.0.2" }); -}); +}, 60_000); test("CI and slim runners do not read primary aliases", async () => { const f = await fixture(); diff --git a/tests/native-interactive-exec.test.ts b/tests/native-interactive-exec.test.ts index 7330f21ab6..be05ac16bb 100644 --- a/tests/native-interactive-exec.test.ts +++ b/tests/native-interactive-exec.test.ts @@ -101,6 +101,10 @@ test.skipIf(process.platform !== "linux" && process.platform !== "darwin")( ]; for (const cmd of commands) { const child = Bun.spawn(cmd, { + // The compile stages a transient `..bun-build` in its working + // directory: this test's root, never the checkout (HACK-2727). The + // Python harness already runs its children in `root`. + cwd: root, env: { ...env, ...Object.fromEntries( diff --git a/tests/prerelease-plan.test.ts b/tests/prerelease-plan.test.ts index 002e33f399..f7396c2f88 100644 --- a/tests/prerelease-plan.test.ts +++ b/tests/prerelease-plan.test.ts @@ -2008,7 +2008,7 @@ test("compiled CLI reports the embedded candidate version and ordinary source re [ process.execPath, "build", - "index.ts", + join(import.meta.dir, "..", "index.ts"), "--compile", ...CLI_COMPILE_DEFINE_ARGS, "--define", @@ -2016,7 +2016,9 @@ test("compiled CLI reports the embedded candidate version and ordinary source re "--outfile", executable, ], - { stdout: "pipe", stderr: "pipe" } + // The compiler stages a transient `..bun-build` in its working + // directory: this test's root, never the checkout (HACK-2727). + { cwd: root, stdout: "pipe", stderr: "pipe" } ); const errors = await new Response(build.stderr).text(); expect(await build.exited).toBe(0); diff --git a/tests/sync-spawn-bound.test.ts b/tests/sync-spawn-bound.test.ts index 574fd2badd..bf40975ff7 100644 --- a/tests/sync-spawn-bound.test.ts +++ b/tests/sync-spawn-bound.test.ts @@ -193,6 +193,12 @@ test("the scanner tells bounded from unbounded synchronous spawns", () => { expect(countUnboundedSyncSpawns('spawnSyncBounded(["true"])')).toBe(0); }); +// Budget (60 s, below): the scan waits on no timer. It reads and +// TypeScript-parses every file the patterns match (about a thousand), so its +// wall time is CPU and file-system work that grows with host load: about 1 s +// alone, up to 3.6 s with 12 test files running at once on a 16-CPU Mac, and +// past Bun's 5 s default under more load beside it (HACK-2727). A hang guard, +// not a speed assertion. test("no new synchronous spawn without a timeout in tests/ or scripts/check-*.ts", async () => { const found = await scan(); const added: string[] = []; @@ -217,4 +223,4 @@ test("no new synchronous spawn without a timeout in tests/ or scripts/check-*.ts lowered, "Fewer unbounded spawns than listed: lower KNOWN_UNBOUNDED in tests/sync-spawn-bound.test.ts." ).toEqual([]); -}); +}, 60_000); diff --git a/tests/v4-upgrade.test.ts b/tests/v4-upgrade.test.ts index 3262d0e815..c728c0cba1 100644 --- a/tests/v4-upgrade.test.ts +++ b/tests/v4-upgrade.test.ts @@ -23,7 +23,7 @@ beforeAll(async () => { process.execPath, "--no-env-file", "build", - "tests/fixtures/v4-upgrade-cli.ts", + join(repository, "tests/fixtures/v4-upgrade-cli.ts"), "--compile", ...CLI_COMPILE_DEFINE_ARGS, "--no-compile-autoload-dotenv", @@ -34,7 +34,9 @@ beforeAll(async () => { binary, ], { - cwd: repository, + // The compiler stages a transient `..bun-build` in its working + // directory: the build root, never the checkout (HACK-2727). + cwd: buildRoot, env: privateCliEnv({ root: buildRoot }), stdout: "pipe", stderr: "pipe", From aa0324901a8ca2fed499b7c006531d80113fb098 Mon Sep 17 00:00:00 2001 From: Dimitri Kennedy <344842+roodboi@users.noreply.github.com> Date: Thu, 26 Nov 2026 16:35:47 -0500 Subject: [PATCH 2/4] test: keep in-process compiles out of the checkout and harden the guard (HACK-2727) Bun.build({ compile }) also stages its .bun-build in the compiling process's working directory. step-store compiled in the test runner's process and the renderer-loading control compiled in a child started in the checkout. Spawn the step-store compile in its own root and move the control to its outfile's directory before it compiles. Rewrite the compile scan over the TypeScript syntax tree: tie cwd to the call that runs the argv, recognize more names for the checkout, cover command strings, Bun shell and Bun.build({ compile }), and skip the scan's own samples. Give doctor-fix-noninteractive a file-scoped 30 s budget, with the measured reason written next to it. Co-Authored-By: Claude Opus 5.5 --- tests/compile-working-directory.test.ts | 503 ++++++++++++++++++------ tests/doctor-fix-noninteractive.test.ts | 17 + tests/fixtures/cli-renderer-loading.ts | 6 +- tests/native-interactive-exec.test.ts | 52 ++- tests/step-store.test.ts | 35 +- 5 files changed, 466 insertions(+), 147 deletions(-) diff --git a/tests/compile-working-directory.test.ts b/tests/compile-working-directory.test.ts index 2552d415ae..f0de0eb7c1 100644 --- a/tests/compile-working-directory.test.ts +++ b/tests/compile-working-directory.test.ts @@ -1,114 +1,291 @@ import { expect, test } from "bun:test"; import { readFile } from "node:fs/promises"; import { resolve } from "node:path"; +import ts from "typescript"; import { runFixtureGitSync } from "./helpers/fixture-git.ts"; /** - * `bun build --compile` stages its executable as a transient - * `.-00000000.bun-build` file in its working directory before renaming - * it to `--outfile`. A test that compiles with the checkout as its working - * directory, named or inherited, puts that file in the checkout for the - * length of the compile. When test files run in parallel, every other file's - * checkout write guard (HACK-1343) that reads `git status` in that window - * sees an untracked file and fails a run whose cases all passed (HACK-2727). - * Each compile must run in a directory the test owns. + * Every Bun compile in `tests/` and `scripts/` runs in a working directory + * its test owns (HACK-2727). + * + * `bun build --compile` and `Bun.build({ compile })` stage the executable as + * a transient `.-.bun-build` file in the compiling process's working + * directory before renaming it to the outfile. A compile that runs with the + * checkout as that directory, named or inherited, puts the file in the + * checkout for the length of the compile. When test files run in parallel, + * every other file's checkout write guard (HACK-1343) that reads `git status` + * in that window sees an untracked file and fails a run whose cases all + * passed. + * + * The check parses each file and finds: + * - an argv array with a `"--compile"` element, or a single command string + * such as `"bun build x --compile"` passed to a spawn: the spawn call that + * receives it must name `cwd` in its own options, and that `cwd` must not + * name the checkout; + * - a Bun shell `` $`bun build ... --compile` ``: it must chain `.cwd(...)` + * to a directory that is not the checkout; + * - `Bun.build({ compile })`: it compiles in its own process. A test file or + * helper runs in the test runner's process, whose working directory is the + * checkout, so it must spawn the compile instead; a fixture or script run + * as its own process must `process.chdir` to an owned directory first. */ const REPO = resolve(import.meta.dir, ".."); +const SELF = "tests/compile-working-directory.test.ts"; -/** How far after its `"--compile"` a spawn's own options may name `cwd`. */ -const OPTIONS_WINDOW = 30; +/** + * Compile sites that may use the checkout. The release build compiles from + * the repository root as a release step; no test runs it. + */ +const RELEASE_ONLY = new Set(["scripts/build-release.ts"]); + +/** Calls that run a command string as a child process. */ +const SPAWNERS = + /^(?:spawn|spawnSync|spawnSyncBounded|exec|execSync|execFile|execFileSync|run|runCommand)$/; -/** A `"--compile"` argv element, not a mention in a string or a call. */ -const COMPILE_ELEMENT = /(?:^|[[,])\s*"--compile"\s*[,\]]/; +/** Identifiers that conventionally hold the checkout root. */ +const CHECKOUT_NAMES = + /^(?:ROOT|REPO|REPO_ROOT|REPOSITORY|repo|repository|repoRoot|checkout|CHECKOUT|checkoutRoot|CHECKOUT_ROOT)$/; -/** A `cwd:` option key. */ -const CWD_OPTION = /\bcwd:\s*/; +/** Expressions that resolve inside the checkout or to the runner's cwd. */ +const CHECKOUT_REFERENCE = + /import\.meta\.(?:dir|dirname|path|url)|process\.cwd\(\)|__dirname/; + +/** A command string that compiles with Bun. */ +const COMMAND_COMPILE = /\bbuild\b[\s\S]*--compile\b/; + +function stringText(node: ts.Node): string | null { + if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) { + return node.text; + } + if (ts.isTemplateExpression(node)) { + return node.getText(); + } + return null; +} + +/** Whether `expression` names the checkout or a directory inside it. */ +function namesCheckout(expression: ts.Node): boolean { + if (CHECKOUT_REFERENCE.test(expression.getText())) { + return true; + } + let found = false; + const visit = (node: ts.Node): void => { + if (ts.isIdentifier(node) && CHECKOUT_NAMES.test(node.text)) { + found = true; + } + if (!found) { + ts.forEachChild(node, visit); + } + }; + visit(expression); + return found; +} + +/** The last name of a call's callee: `spawn` for `Bun.spawn` or `cp.spawn`. */ +function calleeName(call: ts.CallExpression): string { + const callee = call.expression; + if (ts.isIdentifier(callee)) { + return callee.text; + } + if (ts.isPropertyAccessExpression(callee)) { + return callee.name.text; + } + return ""; +} /** - * The value expression of the `cwd:` option on `line`, up to its top-level - * `,` or `}` or the line's end; null when the line names no `cwd`. + * The call that receives `node` as an argument, directly, as a property of + * an object literal argument (`{ cmd: [...] }`), or as an element of an array + * argument (`["sh", "-c", "bun build ..."]`); null when `node` is not passed + * straight to a call. */ -function cwdValue(line: string): string | null { - const match = CWD_OPTION.exec(line); - if (!match) { +function receivingCall(node: ts.Node): ts.CallExpression | null { + let current = node; + for (let depth = 0; depth < 4; depth += 1) { + const parent = current.parent; + if (!parent) { + return null; + } + if ( + ts.isCallExpression(parent) && + parent.arguments.some((argument) => argument === current) + ) { + return parent; + } + if ( + ts.isParenthesizedExpression(parent) || + ts.isAsExpression(parent) || + ts.isSpreadElement(parent) || + ts.isArrayLiteralExpression(parent) + ) { + current = parent; + continue; + } + if ( + ts.isPropertyAssignment(parent) && + ts.isObjectLiteralExpression(parent.parent) + ) { + current = parent.parent; + continue; + } return null; } - let depth = 0; - let value = ""; - for (const char of line.slice(match.index + match[0].length)) { - if (depth === 0 && (char === "," || char === "}")) { - break; + return null; +} + +/** The `cwd` option a call names in its own object literal arguments. */ +function cwdOption(call: ts.CallExpression): ts.Node | null { + for (const argument of call.arguments) { + if (!ts.isObjectLiteralExpression(argument)) { + continue; } - if (char === "(" || char === "[") { - depth += 1; - } else if (char === ")" || char === "]") { - depth -= 1; + for (const property of argument.properties) { + if ( + ts.isPropertyAssignment(property) && + property.name.getText() === "cwd" + ) { + return property.initializer; + } + if ( + ts.isShorthandPropertyAssignment(property) && + property.name.text === "cwd" + ) { + return property.name; + } } - value += char; } - return value.trim(); + return null; } -/** Working-directory expressions that name the checkout itself. */ -const CHECKOUT_CWD = - /^(?:REPO|REPO_ROOT|ROOT|repository|repoRoot|process\.cwd\(\)|import\.meta\.dir|resolve\(import\.meta\.dir, "\.\."\)|join\(import\.meta\.dir, "\.\."\))$/; - -/** - * Compile sites that may use the checkout. The release build compiles from - * the repository root as a release step; no test runs it. - */ -const RELEASE_ONLY = new Set(["scripts/build-release.ts"]); +/** The directory a Bun shell command chains with `.cwd(...)`, if any. */ +function shellCwd(node: ts.TaggedTemplateExpression): ts.Node | null { + let current: ts.Node = node; + for (;;) { + const parent = current.parent; + if ( + parent && + ts.isPropertyAccessExpression(parent) && + parent.expression === current + ) { + const call = parent.parent; + if (!(call && ts.isCallExpression(call) && call.expression === parent)) { + return null; + } + if (parent.name.text === "cwd") { + return call.arguments[0] ?? null; + } + current = call; + continue; + } + return null; + } +} -function isComment(line: string): boolean { - const trimmed = line.trim(); - return ( - trimmed.startsWith("//") || - trimmed.startsWith("*") || - trimmed.startsWith("/*") +function hasCompileProperty(call: ts.CallExpression): boolean { + return call.arguments.some( + (argument) => + ts.isObjectLiteralExpression(argument) && + argument.properties.some( + (property) => + (ts.isPropertyAssignment(property) || + ts.isShorthandPropertyAssignment(property)) && + property.name.getText() === "compile" && + !( + ts.isPropertyAssignment(property) && + property.initializer.kind === ts.SyntaxKind.FalseKeyword + ) + ) ); } /** - * `path:line` and reason of each compile in `text` whose spawn names no - * working directory or names the checkout. + * `path:line` and reason of each compile in `text` that runs, or may run, + * with the checkout as its working directory. */ function checkoutCompiles(opts: { readonly path: string; readonly text: string; }): { readonly checked: number; readonly found: readonly string[] } { - const lines = opts.text.split("\n"); + const source = ts.createSourceFile( + opts.path, + opts.text, + ts.ScriptTarget.Latest, + true + ); + const ownProcess = !( + opts.path.endsWith(".test.ts") || opts.path.startsWith("tests/helpers/") + ); const found: string[] = []; let checked = 0; - for (const [index, line] of lines.entries()) { - if (isComment(line) || !COMPILE_ELEMENT.test(line)) { - continue; + const at = (node: ts.Node, reason: string): void => { + const line = + source.getLineAndCharacterOfPosition(node.getStart(source)).line + 1; + found.push(`${opts.path}:${line} ${reason}`); + }; + const judgeCall = (node: ts.Node, call: ts.CallExpression): void => { + const cwd = cwdOption(call); + if (cwd === null) { + at(node, "names no cwd, so it inherits the runner's directory"); + } else if (namesCheckout(cwd)) { + at(node, `runs in the checkout (${cwd.getText()})`); } - checked += 1; - let cwd: string | null = null; - for ( - let at = index; - at < Math.min(lines.length, index + OPTIONS_WINDOW); - at += 1 + }; + const visit = (node: ts.Node): void => { + if ( + ts.isArrayLiteralExpression(node) && + node.elements.some((element) => stringText(element) === "--compile") ) { - const candidate = lines[at] ?? ""; - if (at > index && COMPILE_ELEMENT.test(candidate)) { - break; + checked += 1; + const call = receivingCall(node); + if (call === null) { + at( + node, + "is not passed straight to its spawn, so its cwd cannot be checked" + ); + } else { + judgeCall(node, call); } - if (isComment(candidate)) { - continue; + } else if (ts.isTaggedTemplateExpression(node)) { + if (COMMAND_COMPILE.test(node.template.getText())) { + checked += 1; + const cwd = shellCwd(node); + if (cwd === null) { + at(node, "is a Bun shell compile without .cwd(...)"); + } else if (namesCheckout(cwd)) { + at(node, `runs in the checkout (${cwd.getText()})`); + } } - cwd = cwdValue(candidate); - if (cwd !== null) { - break; + return; + } else if ( + ts.isCallExpression(node) && + node.expression.getText() === "Bun.build" && + hasCompileProperty(node) + ) { + checked += 1; + if (!ownProcess) { + at( + node, + "compiles in the test runner's process, whose cwd is the checkout" + ); + } else if ( + !opts.text.slice(0, node.getStart(source)).includes("process.chdir(") + ) { + at(node, "compiles in its process's cwd without process.chdir first"); + } + } else { + const text = stringText(node); + if (text !== null && text !== "--compile" && COMMAND_COMPILE.test(text)) { + const call = receivingCall(node); + if (call !== null && SPAWNERS.test(calleeName(call))) { + checked += 1; + judgeCall(node, call); + } } } - if (cwd === null) { - found.push(`${opts.path}:${index + 1} inherits the runner's directory`); - } else if (CHECKOUT_CWD.test(cwd)) { - found.push(`${opts.path}:${index + 1} runs in the checkout (${cwd})`); - } - } + ts.forEachChild(node, visit); + }; + visit(source); return { checked, found }; } @@ -121,7 +298,7 @@ test("no test or script compiles with the checkout as its working directory", as const found: string[] = []; let checked = 0; for (const path of listed.stdout.split("\0")) { - if (path.length === 0 || RELEASE_ONLY.has(path)) { + if (path.length === 0 || path === SELF || RELEASE_ONLY.has(path)) { continue; } const text = await readFile(resolve(REPO, path), "utf8"); @@ -131,58 +308,144 @@ test("no test or script compiles with the checkout as its working directory", as } expect( found, - "Run bun build --compile in a directory the test owns: its transient .bun-build lands in the working directory (HACK-2727)." + "Compile in a directory the test owns: Bun stages a transient .bun-build in the compiling process's working directory (HACK-2727)." ).toEqual([]); - // The scan reached the known compile sites in tests and scripts. - expect(checked).toBeGreaterThanOrEqual(9); + // The scan reached the known compile sites in tests, fixtures and scripts. + expect(checked).toBeGreaterThanOrEqual(11); }); -test("the scan tells an owned working directory from the checkout", () => { - const owned = [ - "const build = Bun.spawn(", - ' [process.execPath, "build", entry, "--compile", "--outfile", out],', - ' { cwd: root, stdout: "pipe" }', - ");", - ].join("\n"); - expect(checkoutCompiles({ path: "a.ts", text: owned })).toEqual({ - checked: 1, - found: [], - }); - const inherited = [ - "Bun.spawn(", - " [", - " process.execPath,", - ' "build",', - ' "index.ts",', - ' "--compile",', - " ],", - ' { stdout: "pipe" }', - ");", - ].join("\n"); - expect(checkoutCompiles({ path: "b.ts", text: inherited }).found).toEqual([ - "b.ts:6 inherits the runner's directory", +test("the scan binds cwd to the spawn that runs the compile", () => { + const scan = (text: string) => + checkoutCompiles({ path: "tests/a.test.ts", text }).found; + expect( + scan( + 'Bun.spawn([process.execPath, "build", e, "--compile"], { cwd: root });' + ) + ).toEqual([]); + expect( + scan( + 'children.run({ cmd: [process.execPath, "build", e, "--compile"], cwd: opts.fixture });' + ) + ).toEqual([]); + expect(scan('Bun.spawn(["bun", "build", "index.ts", "--compile"]);')).toEqual( + ["tests/a.test.ts:1 names no cwd, so it inherits the runner's directory"] + ); + // A later spawn's cwd does not stand in for this one's. + expect( + scan( + [ + 'Bun.spawn(["bun", "build", a, "--compile"], { stdout: "pipe" });', + 'Bun.spawn(["true"], { cwd: root });', + ].join("\n") + ) + ).toEqual([ + "tests/a.test.ts:1 names no cwd, so it inherits the runner's directory", + ]); + // Options passed as a variable are not followed. + expect( + scan('Bun.spawn(["bun", "build", a, "--compile"], options);') + ).toHaveLength(1); + // An argv held in a variable cannot be tied to its spawn. + expect(scan('const commands = [["bun", "build", a, "--compile"]];')).toEqual([ + "tests/a.test.ts:1 is not passed straight to its spawn, so its cwd cannot be checked", ]); - const checkout = [ - 'Bun.spawn([process.execPath, "build", "--compile", entry], {', - ' cwd: resolve(import.meta.dir, ".."),', - "});", - ].join("\n"); - expect(checkoutCompiles({ path: "c.ts", text: checkout }).found).toEqual([ - 'c.ts:1 runs in the checkout (resolve(import.meta.dir, ".."))', +}); + +test("the scan recognizes every name of the checkout", () => { + const scan = (cwd: string) => + checkoutCompiles({ + path: "tests/a.test.ts", + text: `Bun.spawn(["bun", "build", a, "--compile"], { cwd: ${cwd} });`, + }).found; + for (const cwd of [ + "REPO", + "REPO_ROOT", + "ROOT", + "repository", + "repoRoot", + "checkout", + "process.cwd()", + "import.meta.dir", + "dirname(import.meta.dir)", + 'resolve(import.meta.dir, "..")', + 'resolve(import.meta.dir, "../..")', + 'join(import.meta.dir, "fixtures")', + 'join(REPO, "tests")', + 'new URL("..", import.meta.url).pathname', + ]) { + expect(scan(cwd)).toEqual([ + `tests/a.test.ts:1 runs in the checkout (${cwd})`, + ]); + } + for (const cwd of [ + "root", + "f.root", + "dirname(target)", + "buildRoot", + "directory", + ]) { + expect(scan(cwd)).toEqual([]); + } +}); + +test("the scan covers command strings, Bun shell and Bun.build", () => { + const scan = (path: string, text: string) => + checkoutCompiles({ path, text }).found; + expect( + scan( + "tests/a.test.ts", + 'execSync("bun build index.ts --compile --outfile x");' + ) + ).toHaveLength(1); + expect( + scan( + "tests/a.test.ts", + 'spawnSyncBounded(["sh", "-c", "bun build index.ts --compile"], { cwd: REPO, timeout: 1 });' + ) + ).toEqual(["tests/a.test.ts:1 runs in the checkout (REPO)"]); + expect( + scan( + "tests/a.test.ts", + "await $`bun build index.ts --compile --outfile ${out}`;" + ) + ).toEqual(["tests/a.test.ts:1 is a Bun shell compile without .cwd(...)"]); + expect( + scan( + "tests/a.test.ts", + "await $`bun build index.ts --compile`.quiet().cwd(root);" + ) + ).toEqual([]); + expect( + scan( + "tests/a.test.ts", + "await $`bun build index.ts --compile`.cwd(import.meta.dir);" + ) + ).toEqual(["tests/a.test.ts:1 runs in the checkout (import.meta.dir)"]); + const inProcess = + "await Bun.build({ entrypoints: [e], compile: { outfile: o } });"; + expect(scan("tests/a.test.ts", inProcess)).toEqual([ + "tests/a.test.ts:1 compiles in the test runner's process, whose cwd is the checkout", ]); - // A neighbouring compile's cwd does not stand in for a missing one. - const neighbours = [ - 'run(["build", "--compile", a]);', - 'run(["build", "--compile", b], { cwd: root });', - ].join("\n"); - expect(checkoutCompiles({ path: "d.ts", text: neighbours }).found).toEqual([ - "d.ts:1 inherits the runner's directory", + expect(scan("tests/fixtures/b.ts", inProcess)).toEqual([ + "tests/fixtures/b.ts:1 compiles in its process's cwd without process.chdir first", ]); - // Mentions in strings, calls and comments are not compiles. - const mentions = [ - 'if (line.includes("--compile")) {}', - "const text = ' \"--compile\",';", - '// ["build", "--compile"]', - ].join("\n"); - expect(checkoutCompiles({ path: "e.ts", text: mentions }).checked).toBe(0); + expect( + scan("tests/fixtures/b.ts", `process.chdir(dirname(o));\n${inProcess}`) + ).toEqual([]); + // A bundle without compile writes no .bun-build. + expect( + scan("tests/a.test.ts", "await Bun.build({ entrypoints: [e] });") + ).toEqual([]); + // Mentions in prose, assertions and comments are not compiles. + expect( + checkoutCompiles({ + path: "tests/a.test.ts", + text: [ + 'const reason = "bun build --compile of index.ts";', + 'expect(text).toContain("bun build index.ts --compile");', + 'if (line.includes("--compile")) {}', + '// Bun.spawn(["bun", "build", "--compile"])', + ].join("\n"), + }).checked + ).toBe(0); }); diff --git a/tests/doctor-fix-noninteractive.test.ts b/tests/doctor-fix-noninteractive.test.ts index 6a6556e2a6..9313a2adf0 100644 --- a/tests/doctor-fix-noninteractive.test.ts +++ b/tests/doctor-fix-noninteractive.test.ts @@ -4,6 +4,7 @@ import { beforeAll, beforeEach, expect, + setDefaultTimeout, test, } from "bun:test"; import { existsSync } from "node:fs"; @@ -48,6 +49,22 @@ import { registerScopedModuleMock } from "./helpers/scoped-module-mock.ts"; * Follows the module-mock pattern from tests/global-command.macos.test.ts. */ +/** + * Bun timeout for every case and hook here that sets none of its own, the + * same 30 s most cases below already name. The cases wait on no timer: each + * runs `hack doctor --fix` in process against a fixture project, with Docker + * mocked, so its wall time is the doctor's file-system work and real `git` + * probes, which grows with host load. The HACK-1695 contract migration case + * takes 1.05 s alone on a 16-CPU Mac; with 12 test files running at once it + * passed at up to 4.94 s and timed out at Bun's 5 s default in several runs, + * while its assertions held. The timed-out case kept running after its + * fixture was removed and failed the next case with an ENOENT from its + * ingress-generation rename (HACK-2727). A hang guard, not a speed assertion; + * `setDefaultTimeout` is scoped to this file. + */ +const DOCTOR_CASE_BUDGET_MS = 30_000; +setDefaultTimeout(DOCTOR_CASE_BUDGET_MS); + const runCalls: string[][] = []; const runEnvs: (Record | undefined)[] = []; const execCalls: string[][] = []; diff --git a/tests/fixtures/cli-renderer-loading.ts b/tests/fixtures/cli-renderer-loading.ts index ef93c540cb..1a3acd6493 100644 --- a/tests/fixtures/cli-renderer-loading.ts +++ b/tests/fixtures/cli-renderer-loading.ts @@ -1,4 +1,4 @@ -import { resolve } from "node:path"; +import { dirname, resolve } from "node:path"; import { rendererCanary } from "./cli-renderer-canary.ts"; declare const __RENDERER_CONTROL_COMPILED__: boolean | undefined; @@ -10,6 +10,10 @@ if (!root) { } if (mode === "build") { + // The compiler stages a transient `..bun-build` in this process's + // working directory. The test starts this control in the checkout, so move + // to the outfile's owned directory first (HACK-2727). + process.chdir(dirname(root)); const result = await Bun.build({ entrypoints: [import.meta.path], target: "bun", diff --git a/tests/native-interactive-exec.test.ts b/tests/native-interactive-exec.test.ts index be05ac16bb..1564469111 100644 --- a/tests/native-interactive-exec.test.ts +++ b/tests/native-interactive-exec.test.ts @@ -80,9 +80,35 @@ test.skipIf(process.platform !== "linux" && process.platform !== "darwin")( ); const source = resolve("tests/fixtures/native-interactive-frontend.ts"); const compiled = join(root, "frontend"); - const env = privateCliEnv({ root }); - const commands = [ + const env = { + ...privateCliEnv({ root }), + ...Object.fromEntries( + [...HACK_KEY_MATERIAL_VARIABLES].map((name) => [ + name, + "synthetic-parent-key-canary", + ]) + ), + }; + const build = Bun.spawn( [process.execPath, "build", "--compile", source, "--outfile", compiled], + { + // The compiler stages a transient `..bun-build` in its working + // directory: this test's root, never the checkout (HACK-2727). + cwd: root, + env, + stdin: "ignore", + stdout: "pipe", + stderr: "pipe", + timeout: 90_000, + } + ); + const [buildOut, buildErr, buildCode] = await Promise.all([ + new Response(build.stdout).text(), + new Response(build.stderr).text(), + build.exited, + ]); + expect(buildCode, buildErr + buildOut).toBe(0); + const commands = [ [ python, resolve("tests/fixtures/native-interactive-frontend.py"), @@ -101,19 +127,7 @@ test.skipIf(process.platform !== "linux" && process.platform !== "darwin")( ]; for (const cmd of commands) { const child = Bun.spawn(cmd, { - // The compile stages a transient `..bun-build` in its working - // directory: this test's root, never the checkout (HACK-2727). The - // Python harness already runs its children in `root`. - cwd: root, - env: { - ...env, - ...Object.fromEntries( - [...HACK_KEY_MATERIAL_VARIABLES].map((name) => [ - name, - "synthetic-parent-key-canary", - ]) - ), - }, + env, stdin: "ignore", stdout: "pipe", stderr: "pipe", @@ -125,11 +139,9 @@ test.skipIf(process.platform !== "linux" && process.platform !== "darwin")( child.exited, ]); expect(code, err + out).toBe(0); - if (cmd[0] === python) { - expect(out).toBe( - "Frontend PTY: nine lifetime and five selection cases passed\n" - ); - } + expect(out).toBe( + "Frontend PTY: nine lifetime and five selection cases passed\n" + ); } } finally { await rm(root, { recursive: true, force: true }); diff --git a/tests/step-store.test.ts b/tests/step-store.test.ts index 1bb4ed63b5..76e63e9e95 100644 --- a/tests/step-store.test.ts +++ b/tests/step-store.test.ts @@ -422,12 +422,35 @@ describe("step store build", () => { source, `import { stepStoreBuild } from ${JSON.stringify(location)};\nconsole.log(String(stepStoreBuild()));\n` ); - const build = await Bun.build({ - entrypoints: [source], - compile: { outfile: executable }, - ...(define ? { define } : {}), - }); - expect(build.success).toBe(true); + // Compile in a child whose working directory is this root: the compiler + // stages a transient `..bun-build` in its process's working + // directory, which in process would be the checkout (HACK-2727). + const build = Bun.spawn( + [ + process.execPath, + "build", + source, + "--compile", + ...Object.entries(define ?? {}).flatMap(([key, value]) => [ + "--define", + `${key}=${value}`, + ]), + "--outfile", + executable, + ], + { + cwd: root, + stdin: "ignore", + stdout: "ignore", + stderr: "pipe", + timeout: 60_000, + } + ); + const [buildExit, buildErrors] = await Promise.all([ + build.exited, + new Response(build.stderr).text(), + ]); + expect(buildExit, buildErrors).toBe(0); const child = spawnSyncBounded([executable], { timeout: 30_000 }); expect(child.exitCode).toBe(0); return child.stdout.toString().trim(); From b525bda8f85640b434fb56d4cc187352f540c261 Mon Sep 17 00:00:00 2001 From: Dimitri Kennedy <344842+roodboi@users.noreply.github.com> Date: Thu, 26 Nov 2026 16:55:13 -0500 Subject: [PATCH 3/4] test: load budgets for the MCP packaging case and the compile scan (HACK-2727) Both wait on no timer and crossed Bun's 5 s default beside the suite's compile-heavy files; the measured reasons sit next to each budget. Co-Authored-By: Claude Opus 5.5 --- tests/compile-working-directory.test.ts | 7 ++++++- tests/prerelease-plan.test.ts | 9 ++++++++- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/tests/compile-working-directory.test.ts b/tests/compile-working-directory.test.ts index f0de0eb7c1..bc636be297 100644 --- a/tests/compile-working-directory.test.ts +++ b/tests/compile-working-directory.test.ts @@ -289,6 +289,11 @@ function checkoutCompiles(opts: { return { checked, found }; } +// Budget (60 s, below): the scan waits on no timer. It reads and parses every +// tracked TypeScript file under tests/ and scripts/ (over a thousand), so its +// wall time is CPU and file-system work that grows with host load: about 1 s +// alone, and past Bun's 5 s default once in ten rounds beside the suite's +// compile-heavy files (HACK-2727). A hang guard, not a speed assertion. test("no test or script compiles with the checkout as its working directory", async () => { const listed = runFixtureGitSync({ cwd: REPO, @@ -312,7 +317,7 @@ test("no test or script compiles with the checkout as its working directory", as ).toEqual([]); // The scan reached the known compile sites in tests, fixtures and scripts. expect(checked).toBeGreaterThanOrEqual(11); -}); +}, 60_000); test("the scan binds cwd to the spawn that runs the compile", () => { const scan = (text: string) => diff --git a/tests/prerelease-plan.test.ts b/tests/prerelease-plan.test.ts index f7396c2f88..4b39aec23b 100644 --- a/tests/prerelease-plan.test.ts +++ b/tests/prerelease-plan.test.ts @@ -1530,6 +1530,13 @@ test("packages exactly the native payload members despite macOS source extended } }); +// Budget (60 s, below): this case waits on no timer of its own. It packages +// and verifies the prerelease several times, and each pass hashes and archives +// the bundle and starts every MCP executable's capability probe, so its wall +// time is file and process-start work that grows with host load. It takes +// 0.66 s alone and at most 0.58 s in 12-file batches, but 4.7 s, and past +// Bun's 5 s default in every round, beside the suite's other compile-heavy +// files (HACK-2727). A hang guard, not a speed assertion. test("packages a verified MCP selection with exact nested checksums and inventory", async () => { const root = await mkdtemp(join(tmpdir(), "hack-prerelease-mcp-")); try { @@ -1616,7 +1623,7 @@ test("packages a verified MCP selection with exact nested checksums and inventor } finally { await rm(root, { recursive: true, force: true }); } -}); +}, 60_000); test("local dry-run has no publishing effects and refuses SHA mismatch and injected input", async () => { const root = await mkdtemp(join(tmpdir(), "hack-prerelease-plan-")); From db572f76bc10cff24801b3431ff0b5cb69a4a1d6 Mon Sep 17 00:00:00 2001 From: Dimitri Kennedy <344842+roodboi@users.noreply.github.com> Date: Thu, 26 Nov 2026 18:15:17 -0500 Subject: [PATCH 4/4] test: keep the compile scan's samples out of the define scan; check chdir targets (HACK-2727) cli-compile-define read compile-working-directory's sample code as real CLI compiles; list it with the other description-only files. The Bun.build rule now also refuses a process.chdir into the checkout before the compile. Co-Authored-By: Claude Opus 5.5 --- tests/cli-compile-define.test.ts | 2 ++ tests/compile-working-directory.test.ts | 47 ++++++++++++++++++++++--- 2 files changed, 44 insertions(+), 5 deletions(-) diff --git a/tests/cli-compile-define.test.ts b/tests/cli-compile-define.test.ts index 4423fdf59e..3f0c6a26a2 100644 --- a/tests/cli-compile-define.test.ts +++ b/tests/cli-compile-define.test.ts @@ -22,6 +22,8 @@ const DESCRIPTIONS_ONLY = new Set([ "tests/cli-spawn-env-isolation.test.ts", // Matches compile lines as text; its own compile builds a probe, not the CLI. "tests/cli-compile-flags.test.ts", + // Its compile samples are scanner inputs (HACK-2727); it compiles nothing. + "tests/compile-working-directory.test.ts", ]); /** How far a TypeScript argv may extend before or after its `--compile`. */ diff --git a/tests/compile-working-directory.test.ts b/tests/compile-working-directory.test.ts index bc636be297..ad4967e7a8 100644 --- a/tests/compile-working-directory.test.ts +++ b/tests/compile-working-directory.test.ts @@ -231,6 +231,8 @@ function checkoutCompiles(opts: { at(node, `runs in the checkout (${cwd.getText()})`); } }; + /** `process.chdir` targets in source order, as the walk reaches them. */ + const chdirTargets: (ts.Node | null)[] = []; const visit = (node: ts.Node): void => { if ( ts.isArrayLiteralExpression(node) && @@ -263,16 +265,28 @@ function checkoutCompiles(opts: { hasCompileProperty(node) ) { checked += 1; - if (!ownProcess) { + if (ownProcess) { + // The latest `process.chdir` earlier in the file sets the directory. + const target = chdirTargets.at(-1); + if (target === undefined) { + at(node, "compiles in its process's cwd without process.chdir first"); + } else if (target === null || namesCheckout(target)) { + at( + node, + `changes into the checkout (${target?.getText() ?? "no target"}) before compiling` + ); + } + } else { at( node, "compiles in the test runner's process, whose cwd is the checkout" ); - } else if ( - !opts.text.slice(0, node.getStart(source)).includes("process.chdir(") - ) { - at(node, "compiles in its process's cwd without process.chdir first"); } + } else if ( + ts.isCallExpression(node) && + node.expression.getText() === "process.chdir" + ) { + chdirTargets.push(node.arguments[0] ?? null); } else { const text = stringText(node); if (text !== null && text !== "--compile" && COMMAND_COMPILE.test(text)) { @@ -437,6 +451,29 @@ test("the scan covers command strings, Bun shell and Bun.build", () => { expect( scan("tests/fixtures/b.ts", `process.chdir(dirname(o));\n${inProcess}`) ).toEqual([]); + expect( + scan( + "tests/fixtures/b.ts", + `process.chdir(resolve(import.meta.dir, ".."));\n${inProcess}` + ) + ).toEqual([ + 'tests/fixtures/b.ts:2 changes into the checkout (resolve(import.meta.dir, "..")) before compiling', + ]); + // The latest chdir before the compile decides; a later one does not count. + expect( + scan( + "tests/fixtures/b.ts", + `process.chdir(REPO);\nprocess.chdir(dirname(o));\n${inProcess}\nprocess.chdir(REPO);` + ) + ).toEqual([]); + expect( + scan( + "tests/fixtures/b.ts", + `process.chdir(dirname(o));\nprocess.chdir(REPO);\n${inProcess}` + ) + ).toEqual([ + "tests/fixtures/b.ts:3 changes into the checkout (REPO) before compiling", + ]); // A bundle without compile writes no .bun-build. expect( scan("tests/a.test.ts", "await Bun.build({ entrypoints: [e] });")