Skip to content

Commit bff882d

Browse files
authored
refactor(test): share CI checkout fixture lifecycle (#132308)
1 parent 56c2083 commit bff882d

3 files changed

Lines changed: 117 additions & 156 deletions

File tree

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
import { fork } from "node:child_process";
2+
import { readFileSync, rmSync } from "node:fs";
3+
import path from "node:path";
4+
import { fileURLToPath } from "node:url";
5+
import { expect } from "vitest";
6+
import { parse } from "yaml";
7+
import { waitForChildClose } from "../helpers/process-wait.js";
8+
9+
type Step = { name?: string; run?: string; env?: Record<string, string | number> };
10+
type ProcessRecord = { pid: number; role: string; attempt: number };
11+
type Report = {
12+
code: number | null;
13+
cancelledDuringCleanup: boolean;
14+
error?: string;
15+
boundaries: { name: string; alive: ProcessRecord[]; sentinelAlive: boolean }[];
16+
readyAttempts: number[];
17+
cleanupRemaining: ProcessRecord[];
18+
ownedProcesses: ProcessRecord[];
19+
commands: { tool: string; cwd: string; args: string[] }[];
20+
output: string;
21+
};
22+
23+
export const ciCheckoutFixture = fileURLToPath(
24+
new URL("./fixtures/ci-platform-checkout.mjs", import.meta.url),
25+
);
26+
const workflow = parse(readFileSync(".github/workflows/ci.yml", "utf8")) as {
27+
jobs: Record<string, { steps: Step[] }>;
28+
};
29+
30+
export function readCiCheckoutStep(job: string, name = "Checkout"): Step & { run: string } {
31+
const step = workflow.jobs[job]?.steps.find((entry) => entry.name === name);
32+
if (!step?.run) {
33+
throw new Error(`Missing executable workflow step ${job}/${name}`);
34+
}
35+
return { ...step, run: step.run };
36+
}
37+
38+
export function expectCiCheckoutCleanup(report: Report) {
39+
expect(report.cleanupRemaining, "fixture cleanup left owned processes").toEqual([]);
40+
expect(report.boundaries.at(-1)?.name).toBe("exit");
41+
expect(
42+
report.boundaries.every((entry) => entry.sentinelAlive),
43+
"unrelated process killed",
44+
).toBe(true);
45+
expect(
46+
report.boundaries.filter((entry) => entry.alive.length > 0),
47+
"Git descendants survived BEFORE deletion, reuse, consumption, or exit",
48+
).toEqual([]);
49+
}
50+
51+
export async function withCiCheckoutFixture<T>(
52+
root: string,
53+
scenario: string,
54+
inspect: (
55+
report: Report,
56+
result: Awaited<ReturnType<typeof waitForChildClose>>,
57+
stderr: string,
58+
) => T,
59+
): Promise<T> {
60+
const supervisor = fork(ciCheckoutFixture, ["supervise", root, scenario], {
61+
detached: true,
62+
execArgv: [],
63+
stdio: ["ignore", "ignore", "pipe", "ipc"],
64+
});
65+
let stderr = "";
66+
supervisor.stderr?.on("data", (data) => (stderr += String(data)));
67+
const closed = waitForChildClose(supervisor, 50_000);
68+
try {
69+
const result = await closed;
70+
const report = JSON.parse(readFileSync(path.join(root, "report.json"), "utf8")) as Report;
71+
return await inspect(report, result, stderr);
72+
} finally {
73+
// IPC loss triggers fixture cleanup; never remove its root before joining it.
74+
if (supervisor.connected) {
75+
supervisor.disconnect();
76+
}
77+
await closed;
78+
rmSync(root, { recursive: true, force: true });
79+
}
80+
}

‎test/scripts/ci-linux-git.test.ts‎

Lines changed: 20 additions & 86 deletions
Original file line numberDiff line numberDiff line change
@@ -1,41 +1,27 @@
1-
import { fork } from "node:child_process";
21
import {
32
existsSync,
43
mkdirSync,
54
mkdtempSync,
65
readFileSync,
76
realpathSync,
8-
rmSync,
97
writeFileSync,
108
} from "node:fs";
119
import { tmpdir } from "node:os";
1210
import path from "node:path";
13-
import { fileURLToPath } from "node:url";
1411
import { expect, it } from "vitest";
15-
import { parse } from "yaml";
16-
import { waitForChildClose } from "../helpers/process-wait.js";
12+
import {
13+
expectCiCheckoutCleanup,
14+
readCiCheckoutStep,
15+
withCiCheckoutFixture,
16+
} from "./ci-checkout.test-support.js";
1717

18-
type Step = { name?: string; run?: string; env?: Record<string, string | number> };
19-
type ProcessRecord = { pid: number; role: string; attempt: number };
20-
type Command = { tool: string; cwd: string; args: string[] };
21-
type Report = {
22-
code: number | null;
23-
cancelledDuringCleanup: boolean;
24-
error?: string;
25-
boundaries: { name: string; alive: ProcessRecord[]; sentinelAlive: boolean }[];
26-
readyAttempts: number[];
27-
cleanupRemaining: ProcessRecord[];
28-
commands: Command[];
29-
output: string;
30-
};
3118
type FetchResult = number | "hang" | "cleanup-failure";
3219

3320
const candidate = "a".repeat(40);
3421
const harness = "b".repeat(40);
3522
const base = "c".repeat(40);
3623
const moved = "d".repeat(40);
3724
const merge = "e".repeat(40);
38-
const fixture = fileURLToPath(new URL("./fixtures/ci-platform-checkout.mjs", import.meta.url));
3925
const linuxIt = it.skipIf(process.platform !== "linux");
4026
const defaults: Record<string, string> = {
4127
CHECKOUT_REPO: "fixture/checkout",
@@ -67,18 +53,10 @@ const defaults: Record<string, string> = {
6753
RATCHET_PR_HEAD_SHA: candidate,
6854
};
6955

70-
function workflowStep(job: string, name: string): Step & { run: string } {
71-
const workflow = parse(readFileSync(".github/workflows/ci.yml", "utf8")) as {
72-
jobs: Record<string, { steps: Step[] }>;
73-
};
74-
const step = workflow.jobs[job]?.steps.find((entry) => entry.name === name);
75-
if (!step?.run) {
76-
throw new Error(`Missing executable workflow step ${job}/${name}`);
77-
}
78-
return { ...step, run: step.run };
79-
}
80-
81-
function stepEnvironment(step: Step, supplied: Record<string, string>) {
56+
function stepEnvironment(
57+
step: ReturnType<typeof readCiCheckoutStep>,
58+
supplied: Record<string, string>,
59+
) {
8260
const resolved = { ...defaults, ...supplied };
8361
for (const [key, value] of Object.entries(step.env ?? {})) {
8462
if (String(value).startsWith("${{")) {
@@ -128,7 +106,7 @@ async function runStep(options: {
128106
revisions?: Record<string, string>;
129107
poisonPython?: boolean;
130108
}) {
131-
const step = workflowStep(options.job, options.step ?? "Checkout");
109+
const step = readCiCheckoutStep(options.job, options.step ?? "Checkout");
132110
const env = stepEnvironment(step, options.env ?? {});
133111
const root = realpathSync(mkdtempSync(path.join(tmpdir(), "ci linux git ")));
134112
const workspace = path.join(root, "workspace");
@@ -171,37 +149,18 @@ async function runStep(options: {
171149
const readyFile = options.cancelDuringCleanup ? path.join(root, "ready-1.json") : undefined;
172150
let run = accelerate(step.run, readyFile);
173151
if (options.prepare) {
174-
const prepare = workflowStep("security-fast", "Prepare Git owner");
152+
const prepare = readCiCheckoutStep("security-fast", "Prepare Git owner");
175153
const prepareEnv = stepEnvironment(prepare, {});
176154
writeFileSync(path.join(root, "prepare.sh"), accelerate(prepare.run, readyFile));
177155
// Run the actual prepare body in its own shell: its exec must not replace the caller.
178156
run = `CHECKOUT_KIND=${prepareEnv.CHECKOUT_KIND} bash --noprofile --norc -eo pipefail "$TMPDIR/prepare.sh"\n${run}`;
179157
}
180158
writeFileSync(path.join(root, "checkout.sh"), run);
181-
const supervisor = fork(fixture, ["supervise", root, "linux:configured"], {
182-
detached: true,
183-
execArgv: [],
184-
stdio: ["ignore", "ignore", "pipe", "ipc"],
185-
});
186-
let stderr = "";
187-
supervisor.stderr?.on("data", (data) => (stderr += String(data)));
188-
const closed = waitForChildClose(supervisor, 50_000);
189-
try {
190-
const result = await closed;
191-
const report = JSON.parse(readFileSync(path.join(root, "report.json"), "utf8")) as Report;
159+
return withCiCheckoutFixture(root, "linux:configured", (report, result, stderr) => {
192160
console.log(`${options.job}/${options.step ?? "Checkout"}: ${JSON.stringify(report)}`);
193161
expect(result, stderr).toEqual({ code: 0, signal: null });
194162
expect(report.error, stderr).toBeUndefined();
195-
expect(report.cleanupRemaining, "fixture cleanup left owned processes").toEqual([]);
196-
expect(report.boundaries.at(-1)?.name).toBe("exit");
197-
expect(
198-
report.boundaries.every((entry) => entry.sentinelAlive),
199-
"unrelated process killed",
200-
).toBe(true);
201-
expect(
202-
report.boundaries.filter((entry) => entry.alive.length > 0),
203-
"Git descendants survived BEFORE deletion, reuse, consumption, or exit",
204-
).toEqual([]);
163+
expectCiCheckoutCleanup(report);
205164
expect(readFileSync(protectedFile, "utf8")).toBe("not checkout-owned\n");
206165
expect(
207166
existsSync(path.join(root, "python-injected")),
@@ -219,13 +178,7 @@ async function runStep(options: {
219178
({ tool, args }) => tool === "git" && args[0] === "checkout",
220179
),
221180
};
222-
} finally {
223-
if (supervisor.connected) {
224-
supervisor.disconnect();
225-
}
226-
await closed;
227-
rmSync(root, { recursive: true, force: true });
228-
}
181+
});
229182
}
230183

231184
const resetProfiles = [
@@ -379,11 +332,11 @@ linuxIt.each(
379332
);
380333

381334
linuxIt(
382-
"preflight refetches a moved exact SHA before fetching its parent metadata",
335+
"preflight pins a moved exact SHA and retries only its parent metadata",
383336
async () => {
384337
const report = await runStep({
385338
job: "preflight",
386-
fetchResults: [0, 0, 0],
339+
fetchResults: [0, 0, 23, 0],
387340
env: { GITHUB_EVENT_NAME: "workflow_dispatch" },
388341
poisonPython: true,
389342
});
@@ -392,10 +345,11 @@ linuxIt(
392345
"+refs/heads/main:refs/remotes/origin/checkout",
393346
`+${candidate}:refs/remotes/origin/checkout`,
394347
candidate,
348+
candidate,
395349
]);
396-
expect(report.fetches[2]?.args).toEqual(
397-
expect.arrayContaining(["--depth=2", "--filter=blob:none"]),
398-
);
350+
for (const fetch of report.fetches.slice(2)) {
351+
expect(fetch.args).toEqual(expect.arrayContaining(["--depth=2", "--filter=blob:none"]));
352+
}
399353
expect(report.checkouts.map(({ args }) => args)).toEqual([
400354
["checkout", "--detach", "refs/remotes/origin/checkout"],
401355
]);
@@ -421,26 +375,6 @@ linuxIt(
421375
55_000,
422376
);
423377

424-
linuxIt(
425-
"preflight retries parent metadata without refetching the selected tree",
426-
async () => {
427-
const report = await runStep({ job: "preflight", fetchResults: [0, 23, 0] });
428-
expect(report.code).toBe(0);
429-
expect(report.fetches.map(({ args }) => args.at(-1))).toEqual([
430-
`+${candidate}:refs/remotes/origin/checkout`,
431-
candidate,
432-
candidate,
433-
]);
434-
for (const fetch of report.fetches.slice(1)) {
435-
expect(fetch.args).toEqual(expect.arrayContaining(["--depth=2", "--filter=blob:none"]));
436-
}
437-
expect(report.checkouts.map(({ args }) => args)).toEqual([
438-
["checkout", "--detach", "refs/remotes/origin/checkout"],
439-
]);
440-
},
441-
55_000,
442-
);
443-
444378
linuxIt(
445379
"preflight rejects a fallback that cannot satisfy the requested exact SHA",
446380
async () => {

0 commit comments

Comments
 (0)