-
Notifications
You must be signed in to change notification settings - Fork 266
test: reduce suite latency with safe sharding #832
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
benvinegar
wants to merge
6
commits into
main
Choose a base branch
from
perf/test-suite-sharding
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
7315181
test: reduce suite latency with safe sharding
benvinegar 0671fbd
fix: keep test sharding Linux-only
benvinegar 8e95b3b
fix: omit orphan tracking on Windows
benvinegar 2cfb074
test: tolerate Windows subprocess topology
benvinegar e76abdb
test: widen scrollbar timer margins on Windows
benvinegar 4dd64cc
test: clean up sharded session daemons
benvinegar File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,2 @@ | ||
| --- | ||
| --- |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,79 @@ | ||
| import { describe, expect, test } from "bun:test"; | ||
| import { | ||
| buildTestShardCommand, | ||
| DEFAULT_TEST_PATTERNS, | ||
| resolveTestShardCount, | ||
| terminateTestShardProcesses, | ||
| } from "./run-test-suite"; | ||
|
|
||
| describe("test suite sharding", () => { | ||
| test("uses the available CPUs up to the automatic Linux cap", () => { | ||
| expect(resolveTestShardCount(1, undefined, "linux")).toBe(1); | ||
| expect(resolveTestShardCount(2, undefined, "linux")).toBe(2); | ||
| expect(resolveTestShardCount(32, undefined, "linux")).toBe(2); | ||
| }); | ||
|
|
||
| test("accepts an explicit positive shard count on Linux", () => { | ||
| expect(resolveTestShardCount(32, "1", "linux")).toBe(1); | ||
| expect(resolveTestShardCount(2, "16", "linux")).toBe(16); | ||
| }); | ||
|
|
||
| test("keeps non-Linux suites serial", () => { | ||
| expect(resolveTestShardCount(32, undefined, "win32")).toBe(1); | ||
| expect(resolveTestShardCount(32, "16", "darwin")).toBe(1); | ||
| }); | ||
|
|
||
| test("rejects malformed or excessive Linux shard overrides", () => { | ||
| expect(() => resolveTestShardCount(8, "0", "linux")).toThrow( | ||
| "HUNK_TEST_SHARDS must be a positive safe integer", | ||
| ); | ||
| expect(() => resolveTestShardCount(8, "2.5", "linux")).toThrow( | ||
| "HUNK_TEST_SHARDS must be a positive safe integer", | ||
| ); | ||
| expect(() => resolveTestShardCount(8, "999999999999999999999999", "linux")).toThrow( | ||
| "HUNK_TEST_SHARDS must be a positive safe integer", | ||
| ); | ||
| expect(() => resolveTestShardCount(8, "65", "linux")).toThrow( | ||
| "HUNK_TEST_SHARDS cannot exceed 64", | ||
| ); | ||
| }); | ||
|
|
||
| test("builds serial and sharded Bun commands", () => { | ||
| expect(buildTestShardCommand("/opt/bun", 1, 1, [], "linux")).toEqual([ | ||
| "/opt/bun", | ||
| "test", | ||
| "--no-orphans", | ||
| ...DEFAULT_TEST_PATTERNS, | ||
| ]); | ||
| expect(buildTestShardCommand("/opt/bun", 2, 4, ["--rerun-each=2"], "linux")).toEqual([ | ||
| "/opt/bun", | ||
| "test", | ||
| "--no-orphans", | ||
| "--shard=2/4", | ||
| ...DEFAULT_TEST_PATTERNS, | ||
| "--rerun-each=2", | ||
| ]); | ||
| expect(buildTestShardCommand("C:\\bun.exe", 1, 1, [], "win32")).toEqual([ | ||
| "C:\\bun.exe", | ||
| "test", | ||
| ...DEFAULT_TEST_PATTERNS, | ||
| ]); | ||
| }); | ||
|
|
||
| test("forwards termination while tolerating an already stopped shard", () => { | ||
| const signals: Array<NodeJS.Signals> = []; | ||
| terminateTestShardProcesses( | ||
| [ | ||
| { kill: (signal) => signals.push(signal as NodeJS.Signals) }, | ||
| { | ||
| kill: () => { | ||
| throw new Error("already stopped"); | ||
| }, | ||
| }, | ||
| ], | ||
| "SIGTERM", | ||
| ); | ||
|
|
||
| expect(signals).toEqual(["SIGTERM"]); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,166 @@ | ||
| #!/usr/bin/env bun | ||
|
|
||
| /** | ||
| * Runs Hunk's default tests concurrently without Bun's isolated parallel worker mode. | ||
| * | ||
| * Bun 1.3.14's `--parallel` implies `--isolate`, which makes OpenTUI's native FFI | ||
| * renderer fail to initialize with "Cannot access 'default' before initialization." | ||
| * Independent `--shard=N/M` processes avoid that failure, but Bun runs only the one | ||
| * requested shard, so this module launches and supervises every shard. Sharding stays | ||
| * Linux-only because the complete multi-process suite is validated and benchmarked there. | ||
| */ | ||
|
|
||
| import { availableParallelism } from "node:os"; | ||
|
|
||
| export const DEFAULT_TEST_PATTERNS = [ | ||
| "./src", | ||
| "./packages", | ||
| "./scripts", | ||
| "./test/cli", | ||
| "./test/session", | ||
| ] as const; | ||
|
|
||
| const MAX_AUTOMATIC_TEST_SHARDS = 2; | ||
| const MAX_EXPLICIT_TEST_SHARDS = 64; | ||
| const SHARD_TERMINATION_GRACE_MS = 1_000; | ||
|
|
||
| type KillableProcess = { | ||
| kill(signal?: number | NodeJS.Signals): void; | ||
| }; | ||
|
|
||
| /** Resolve a Linux shard override or choose a bounded count from the available CPUs. */ | ||
| export function resolveTestShardCount( | ||
| cpuCount: number, | ||
| override?: string, | ||
| platform: NodeJS.Platform = process.platform, | ||
| ) { | ||
| if (platform !== "linux") return 1; | ||
|
|
||
| if (override !== undefined) { | ||
| const count = Number(override); | ||
| if (!/^\d+$/.test(override) || !Number.isSafeInteger(count) || count < 1) { | ||
| throw new Error("HUNK_TEST_SHARDS must be a positive safe integer"); | ||
| } | ||
| if (count > MAX_EXPLICIT_TEST_SHARDS) { | ||
| throw new Error(`HUNK_TEST_SHARDS cannot exceed ${MAX_EXPLICIT_TEST_SHARDS}`); | ||
| } | ||
| return count; | ||
| } | ||
|
|
||
| return Math.min(MAX_AUTOMATIC_TEST_SHARDS, Math.max(1, Math.floor(cpuCount))); | ||
| } | ||
|
|
||
| /** Build one Bun test command for an independent file shard. */ | ||
| export function buildTestShardCommand( | ||
| bunExecutable: string, | ||
| shard: number, | ||
| shardCount: number, | ||
| forwardedArgs: string[] = [], | ||
| platform: NodeJS.Platform = process.platform, | ||
| ) { | ||
| return [ | ||
| bunExecutable, | ||
| "test", | ||
| ...(platform === "win32" ? [] : ["--no-orphans"]), | ||
| ...(shardCount > 1 ? [`--shard=${shard}/${shardCount}`] : []), | ||
| ...DEFAULT_TEST_PATTERNS, | ||
| ...forwardedArgs, | ||
| ]; | ||
| } | ||
|
|
||
| /** Forward a termination signal to every live shard, tolerating shards that already exited. */ | ||
| export function terminateTestShardProcesses(processes: KillableProcess[], signal: NodeJS.Signals) { | ||
| for (const proc of processes) { | ||
| try { | ||
| proc.kill(signal); | ||
| } catch { | ||
| // Another shard or the terminal process group may already have stopped it. | ||
| } | ||
| } | ||
| } | ||
|
|
||
| /** Run the default suite in independent Bun processes without enabling Bun's isolate mode. */ | ||
| export async function main(args = Bun.argv.slice(2)) { | ||
| const shardCount = resolveTestShardCount(availableParallelism(), process.env.HUNK_TEST_SHARDS); | ||
| const bunExecutable = process.execPath; | ||
|
|
||
| console.error(`Running the test suite in ${shardCount} shard${shardCount === 1 ? "" : "s"}...`); | ||
|
|
||
| const shards: Array<{ proc: ReturnType<typeof Bun.spawn>; shard: number }> = []; | ||
| try { | ||
| for (let index = 0; index < shardCount; index += 1) { | ||
| const shard = index + 1; | ||
| const proc = Bun.spawn( | ||
| buildTestShardCommand(bunExecutable, shard, shardCount, args, process.platform), | ||
| { | ||
| cwd: process.cwd(), | ||
| env: { ...process.env, npm_execpath: bunExecutable }, | ||
| stdin: "inherit", | ||
| stdout: "inherit", | ||
| stderr: "inherit", | ||
| }, | ||
| ); | ||
| shards.push({ proc, shard }); | ||
| } | ||
| } catch (error) { | ||
| const spawnedProcesses = shards.map(({ proc }) => proc); | ||
| terminateTestShardProcesses(spawnedProcesses, "SIGTERM"); | ||
| const forceKillTimer = setTimeout(() => { | ||
| terminateTestShardProcesses(spawnedProcesses, "SIGKILL"); | ||
| }, SHARD_TERMINATION_GRACE_MS); | ||
| forceKillTimer.unref(); | ||
| try { | ||
| await Promise.allSettled(shards.map(({ proc }) => proc.exited)); | ||
| } finally { | ||
| clearTimeout(forceKillTimer); | ||
| } | ||
| throw error; | ||
| } | ||
|
|
||
| const processes = shards.map(({ proc }) => proc); | ||
| let interruptedExitCode: number | null = null; | ||
| let forceKillTimer: ReturnType<typeof setTimeout> | null = null; | ||
| const handleSignal = (signal: NodeJS.Signals, exitCode: number) => { | ||
| if (interruptedExitCode !== null) return; | ||
| interruptedExitCode = exitCode; | ||
| terminateTestShardProcesses(processes, signal); | ||
| forceKillTimer = setTimeout(() => { | ||
| terminateTestShardProcesses(processes, "SIGKILL"); | ||
| }, SHARD_TERMINATION_GRACE_MS); | ||
| forceKillTimer.unref(); | ||
| }; | ||
| const handleSigint = () => handleSignal("SIGINT", 130); | ||
| const handleSigterm = () => handleSignal("SIGTERM", 143); | ||
| process.once("SIGINT", handleSigint); | ||
| process.once("SIGTERM", handleSigterm); | ||
|
|
||
| let results: Array<{ exitCode: number; shard: number }>; | ||
| try { | ||
| results = await Promise.all( | ||
| shards.map(async ({ proc, shard }) => ({ exitCode: await proc.exited, shard })), | ||
| ); | ||
| } finally { | ||
| process.off("SIGINT", handleSigint); | ||
| process.off("SIGTERM", handleSigterm); | ||
| if (forceKillTimer) clearTimeout(forceKillTimer); | ||
| } | ||
|
|
||
| if (interruptedExitCode !== null) return interruptedExitCode; | ||
| const failedShards = results.filter(({ exitCode }) => exitCode !== 0); | ||
|
|
||
| if (failedShards.length > 0) { | ||
| console.error( | ||
| `Test shard failure: ${failedShards | ||
| .map(({ exitCode, shard }) => `${shard}/${shardCount} (exit ${exitCode})`) | ||
| .join(", ")}`, | ||
| ); | ||
| return 1; | ||
| } | ||
|
|
||
| console.error(`All ${shardCount} test shard${shardCount === 1 ? "" : "s"} passed.`); | ||
| return 0; | ||
| } | ||
|
|
||
| if (import.meta.main) { | ||
| process.exitCode = await main(); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The new supervisor reads
HUNK_TEST_SHARDSdirectly fromprocess.envand also spreadsprocess.envinto each child at line 87, bypassing the repository-prescribed type-safe environment interface and establishing an inconsistent configuration-access pattern.Context Used: guidelines.mdc Cursor rule (source)
Prompt To Fix With AI
Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!