diff --git a/tests/cli-compile-define.test.ts b/tests/cli-compile-define.test.ts index 4423fdf59..3f0c6a26a 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 new file mode 100644 index 000000000..ad4967e7a --- /dev/null +++ b/tests/compile-working-directory.test.ts @@ -0,0 +1,493 @@ +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"; + +/** + * 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"; + +/** + * 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)$/; + +/** Identifiers that conventionally hold the checkout root. */ +const CHECKOUT_NAMES = + /^(?:ROOT|REPO|REPO_ROOT|REPOSITORY|repo|repository|repoRoot|checkout|CHECKOUT|checkoutRoot|CHECKOUT_ROOT)$/; + +/** 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 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 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; + } + 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; + } + 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; + } + } + } + return null; +} + +/** 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 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` 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 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; + 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()})`); + } + }; + /** `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) && + node.elements.some((element) => stringText(element) === "--compile") + ) { + 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); + } + } 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()})`); + } + } + return; + } else if ( + ts.isCallExpression(node) && + node.expression.getText() === "Bun.build" && + hasCompileProperty(node) + ) { + checked += 1; + 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 ( + 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)) { + const call = receivingCall(node); + if (call !== null && SPAWNERS.test(calleeName(call))) { + checked += 1; + judgeCall(node, call); + } + } + } + ts.forEachChild(node, visit); + }; + visit(source); + 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, + 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 || path === SELF || 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, + "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, 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) => + 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", + ]); +}); + +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", + ]); + expect(scan("tests/fixtures/b.ts", inProcess)).toEqual([ + "tests/fixtures/b.ts:1 compiles in its process's cwd without process.chdir first", + ]); + 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] });") + ).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/daemon-systemd-cli.test.ts b/tests/daemon-systemd-cli.test.ts index 91450ebf0..51b702057 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/doctor-fix-noninteractive.test.ts b/tests/doctor-fix-noninteractive.test.ts index 6a6556e2a..9313a2adf 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/env-migration-journal.test.ts b/tests/env-migration-journal.test.ts index c2ee71af9..8c32b6e1d 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/cli-renderer-loading.ts b/tests/fixtures/cli-renderer-loading.ts index ef93c540c..1a3acd649 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/fixtures/tty-cancellation.py b/tests/fixtures/tty-cancellation.py index 8bb40c620..fee6a5c47 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 7f2391de6..e95ca4c7b 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 02f075a5b..50fd5158e 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 ac9ac1a97..6d488bbc7 100644 --- a/tests/native-interactive-exec.test.ts +++ b/tests/native-interactive-exec.test.ts @@ -111,9 +111,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"), @@ -132,15 +158,7 @@ test.skipIf(process.platform !== "linux" && process.platform !== "darwin")( ]; for (const cmd of commands) { const child = Bun.spawn(cmd, { - env: { - ...env, - ...Object.fromEntries( - [...HACK_KEY_MATERIAL_VARIABLES].map((name) => [ - name, - "synthetic-parent-key-canary", - ]) - ), - }, + env, stdin: "ignore", stdout: "pipe", stderr: "pipe", @@ -152,11 +170,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/prerelease-plan.test.ts b/tests/prerelease-plan.test.ts index 002e33f39..4b39aec23 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-")); @@ -2008,7 +2015,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 +2023,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/step-store.test.ts b/tests/step-store.test.ts index 1bb4ed63b..76e63e9e9 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(); diff --git a/tests/sync-spawn-bound.test.ts b/tests/sync-spawn-bound.test.ts index 574fd2bad..bf40975ff 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 3262d0e81..c728c0cba 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",