|
| 1 | +import { fork } from "node:child_process"; |
| 2 | +import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs"; |
| 3 | +import { tmpdir } from "node:os"; |
| 4 | +import path from "node:path"; |
| 5 | +import { fileURLToPath } from "node:url"; |
| 6 | +import { expectDefined } from "@openclaw/normalization-core"; |
| 7 | +import { expect, it } from "vitest"; |
| 8 | +import { parse } from "yaml"; |
| 9 | +import { waitForChildClose } from "../helpers/process-wait.js"; |
| 10 | + |
| 11 | +type ProcessRecord = { pid: number; role: string; attempt: number }; |
| 12 | +type Boundary = { name: string; alive: ProcessRecord[]; sentinelAlive: boolean }; |
| 13 | +type Report = { |
| 14 | + code: number | null; |
| 15 | + error?: string; |
| 16 | + boundaries: Boundary[]; |
| 17 | + readyAttempts: number[]; |
| 18 | + cleanupRemaining: ProcessRecord[]; |
| 19 | + commands: { cwd: string; args: string[] }[]; |
| 20 | + output: string; |
| 21 | +}; |
| 22 | + |
| 23 | +const fixture = fileURLToPath(new URL("./fixtures/ci-platform-checkout.mjs", import.meta.url)); |
| 24 | + |
| 25 | +// Execute both workflow policies against the same owned tree fixture. A leader's |
| 26 | +// exit must not authorize workspace deletion, Git reuse, or final success. |
| 27 | +const platformCases = [ |
| 28 | + { scenario: "timeouts-exhausted", attempts: 3, code: 124, checkout: false }, |
| 29 | + { scenario: "recovery", attempts: 4, code: 0, checkout: true }, |
| 30 | + { scenario: "early-leader-exit", attempts: 2, code: 0, checkout: true }, |
| 31 | + { scenario: "harness-timeout", attempts: 2, code: 124, checkout: true }, |
| 32 | + { scenario: "git-failure", attempts: 1, code: 23, checkout: false }, |
| 33 | + { scenario: "git-exit-124", attempts: 1, code: 124, checkout: false }, |
| 34 | + // Windows has no POSIX signals/ps boundary; native Job cancellation proof is separate. |
| 35 | + ...(process.platform === "win32" ? [] : ["SIGTERM", "SIGINT", "SIGHUP"]).map((signal, index) => ({ |
| 36 | + scenario: `cancel-${signal}`, |
| 37 | + attempts: 1, |
| 38 | + code: [143, 130, 129][index], |
| 39 | + checkout: false, |
| 40 | + })), |
| 41 | + ...(process.platform === "win32" |
| 42 | + ? [] |
| 43 | + : [{ scenario: "cleanup-failure", attempts: 1, code: 125, checkout: false }]), |
| 44 | +]; |
| 45 | +const linuxCases = |
| 46 | + process.platform === "win32" |
| 47 | + ? [] |
| 48 | + : [ |
| 49 | + { scenario: "timeouts-exhausted", attempts: 5, code: 1, checkout: false, deletions: 5 }, |
| 50 | + { scenario: "recovery", attempts: 4, code: 0, checkout: true, deletions: 3 }, |
| 51 | + { scenario: "early-leader-exit", attempts: 2, code: 0, checkout: true, deletions: 1 }, |
| 52 | + { scenario: "git-failure", attempts: 5, code: 1, checkout: false, deletions: 5 }, |
| 53 | + { scenario: "checkout-failure", attempts: 5, code: 1, checkout: true, deletions: 5 }, |
| 54 | + { scenario: "harness-recovery", attempts: 4, code: 0, checkout: true, deletions: 2 }, |
| 55 | + { scenario: "cancel-SIGTERM", attempts: 1, code: 143, checkout: false, deletions: 1 }, |
| 56 | + { scenario: "cleanup-failure", attempts: 1, code: 125, checkout: false, deletions: 1 }, |
| 57 | + { scenario: "non-executable-git", attempts: 0, code: null, checkout: false, deletions: 0 }, |
| 58 | + { scenario: "non-executable-find", attempts: 0, code: null, checkout: false, deletions: 0 }, |
| 59 | + ]; |
| 60 | + |
| 61 | +it.each([ |
| 62 | + ...platformCases.map((entry) => Object.assign(entry, { linux: false, deletions: 0 })), |
| 63 | + ...linuxCases.map((entry) => Object.assign(entry, { linux: true })), |
| 64 | +])( |
| 65 | + "preserves checkout ownership and fixture isolation (Linux=$linux, $scenario)", |
| 66 | + async ({ scenario, attempts, code, checkout, linux, deletions }) => { |
| 67 | + const setupFailure = scenario.startsWith("non-executable-"); |
| 68 | + const workflow = parse(readFileSync(".github/workflows/ci.yml", "utf8")) as { |
| 69 | + jobs: Record<string, { steps: { name?: string; run?: string }[] }>; |
| 70 | + }; |
| 71 | + const run = workflow.jobs[linux ? "checks-fast-core" : "checks-windows"]?.steps.find( |
| 72 | + (step) => step.name === "Checkout", |
| 73 | + )?.run; |
| 74 | + expect(run).toBeTypeOf("string"); |
| 75 | + if (!run) { |
| 76 | + throw new Error("Missing shared platform checkout shell"); |
| 77 | + } |
| 78 | + |
| 79 | + const root = realpathSync(mkdtempSync(path.join(tmpdir(), "ci platform checkout "))); |
| 80 | + const workspace = path.join(root, "workspace"); |
| 81 | + mkdirSync(workspace); |
| 82 | + if (linux) { |
| 83 | + writeFileSync(path.join(workspace, ".previous-checkout"), "stale\n"); |
| 84 | + } |
| 85 | + // Advance the test clock, not the real OS teardown budget: a subsecond |
| 86 | + // cleanup deadline races process scheduling instead of testing ownership. |
| 87 | + const accelerated = run |
| 88 | + .replace(/fetch_timeout_seconds = [^\n]+/u, "fetch_timeout_seconds = 2") |
| 89 | + .replace("kill_at = deadline - cleanup_seconds / 2", "kill_at = time.monotonic()") |
| 90 | + .replace(/retry_at = time\.monotonic\(\) \+ [^\n]+/u, "retry_at = time.monotonic() + 0.05") |
| 91 | + // Keep the original GNU timeout path executable for the pre-fix regression. |
| 92 | + .replace("120s git", "2s git") |
| 93 | + .replace("sleep $((attempt * 5))", "sleep 0.05"); |
| 94 | + expect(accelerated).not.toBe(run); |
| 95 | + // A broken preflight must never let these negative fixture tests run real Git. |
| 96 | + writeFileSync( |
| 97 | + path.join(root, "checkout.sh"), |
| 98 | + setupFailure ? "printf 'unexpected workflow invocation\\n' >&2\nexit 99\n" : accelerated, |
| 99 | + ); |
| 100 | + |
| 101 | + const supervisor = fork(fixture, ["supervise", root, `${linux ? "linux:" : ""}${scenario}`], { |
| 102 | + detached: true, |
| 103 | + execArgv: [], |
| 104 | + stdio: ["ignore", "ignore", "pipe", "ipc"], |
| 105 | + }); |
| 106 | + let stderr = ""; |
| 107 | + supervisor.stderr?.on("data", (data) => (stderr += String(data))); |
| 108 | + const closed = waitForChildClose(supervisor, 50_000); |
| 109 | + try { |
| 110 | + const result = await closed; |
| 111 | + const report = JSON.parse(readFileSync(path.join(root, "report.json"), "utf8")) as Report; |
| 112 | + // Emit evidence before assertions; it remains available even for this deliberately red test. |
| 113 | + console.log(`${scenario}: ${JSON.stringify(report)}`); |
| 114 | + expect(report.cleanupRemaining, "fixture cleanup left owned processes").toEqual([]); |
| 115 | + if (setupFailure) { |
| 116 | + expect(report.error, report.output).toContain( |
| 117 | + "Fixture setup: mock command resolution failed", |
| 118 | + ); |
| 119 | + expect(report.error).toContain(scenario.slice("non-executable-".length)); |
| 120 | + expect(result, stderr).toEqual({ code: 1, signal: null }); |
| 121 | + expect(report.code).toBeNull(); |
| 122 | + expect(report.output).toBe(""); |
| 123 | + expect(report.commands).toEqual([]); |
| 124 | + expect(report.boundaries).toEqual([]); |
| 125 | + return; |
| 126 | + } |
| 127 | + expect(result, stderr).toEqual({ code: 0, signal: null }); |
| 128 | + expect(report.error, stderr).toBeUndefined(); |
| 129 | + const leaks = report.boundaries |
| 130 | + .filter((entry) => entry.alive.length > 0) |
| 131 | + .map(({ name, alive }) => ({ boundary: name, survivors: alive })); |
| 132 | + expect( |
| 133 | + leaks, |
| 134 | + "Git descendants must be dead BEFORE workspace deletion, reuse or exit", |
| 135 | + ).toEqual([]); |
| 136 | + expect(report.code).toBe(code); |
| 137 | + expect(report.readyAttempts).toEqual(Array.from({ length: attempts }, (_, i) => i + 1)); |
| 138 | + expect(report.boundaries.filter((entry) => entry.name.startsWith("fetch:"))).toHaveLength( |
| 139 | + attempts, |
| 140 | + ); |
| 141 | + expect(report.boundaries.some((entry) => entry.name === "checkout")).toBe(checkout); |
| 142 | + expect(report.boundaries.filter((entry) => entry.name === "delete")).toHaveLength(deletions); |
| 143 | + expect(report.boundaries.at(-1)?.name).toBe("exit"); |
| 144 | + expect(report.output.includes("refusing reuse or retry")).toBe( |
| 145 | + scenario === "cleanup-failure", |
| 146 | + ); |
| 147 | + if (code === 0) { |
| 148 | + const fetches = report.commands.filter(({ args }) => args.includes("fetch")); |
| 149 | + const candidateFetch = expectDefined(fetches[0], "candidate fetch"); |
| 150 | + expect(candidateFetch.args).toContain( |
| 151 | + `+${"a".repeat(40)}:refs/remotes/origin/${linux ? "ci-target" : "checkout"}`, |
| 152 | + ); |
| 153 | + expect( |
| 154 | + candidateFetch.args.includes(`+${"c".repeat(40)}:refs/remotes/origin/ci-ratchet-base`), |
| 155 | + ).toBe(linux && scenario === "early-leader-exit"); |
| 156 | + if (linux) { |
| 157 | + expect( |
| 158 | + report.commands.filter( |
| 159 | + ({ args }) => args.join(" ") === `config --global --add safe.directory ${workspace}`, |
| 160 | + ), |
| 161 | + ).toHaveLength(deletions); |
| 162 | + expect( |
| 163 | + report.commands |
| 164 | + .filter(({ cwd, args }) => cwd === workspace && args[0] === "checkout") |
| 165 | + .every( |
| 166 | + ({ args }) => args.join(" ") === `checkout --force --detach ${"a".repeat(40)}`, |
| 167 | + ), |
| 168 | + ).toBe(true); |
| 169 | + } |
| 170 | + expect(candidateFetch.cwd).toBe(workspace); |
| 171 | + expect(fetches.at(-1)?.cwd).toBe(path.join(workspace, ".ci-harness")); |
| 172 | + for (const { args } of fetches) { |
| 173 | + expect(args).toEqual( |
| 174 | + expect.arrayContaining(["--no-tags", "--no-recurse-submodules", "--depth=1"]), |
| 175 | + ); |
| 176 | + } |
| 177 | + expect(fetches.at(-1)?.args).toContain(`+${"b".repeat(40)}:refs/remotes/origin/ci-harness`); |
| 178 | + expect( |
| 179 | + report.commands.some( |
| 180 | + ({ args }) => args.join(" ") === "sparse-checkout set .github/actions", |
| 181 | + ), |
| 182 | + ).toBe(true); |
| 183 | + expect(report.commands.at(-1)?.args).toEqual([ |
| 184 | + "checkout", |
| 185 | + "--force", |
| 186 | + "--detach", |
| 187 | + "b".repeat(40), |
| 188 | + ]); |
| 189 | + } |
| 190 | + expect( |
| 191 | + report.boundaries.every((entry) => entry.sentinelAlive), |
| 192 | + "unrelated sentinel killed", |
| 193 | + ).toBe(true); |
| 194 | + } finally { |
| 195 | + // IPC loss also triggers cleanup if Vitest is canceled or its worker is killed. |
| 196 | + if (supervisor.connected) { |
| 197 | + supervisor.disconnect(); |
| 198 | + } |
| 199 | + await closed; |
| 200 | + rmSync(root, { recursive: true, force: true }); |
| 201 | + } |
| 202 | + }, |
| 203 | + 55_000, |
| 204 | +); |
0 commit comments