From ca7e980d49e8f1db03c7cdd26506620e82bac768 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Wed, 14 Oct 2026 02:59:15 +0800 Subject: [PATCH] fix(ci): clean up native Pascal verifier processes --- scripts/lib/canonical-temporary-directory.mjs | 17 +++ scripts/verify-native-pascal-calls.mjs | 98 +++++++++-------- .../filesystem/nativePascalVerifier.test.ts | 100 ++++++++++++++++++ 3 files changed, 173 insertions(+), 42 deletions(-) create mode 100644 scripts/lib/canonical-temporary-directory.mjs create mode 100644 tests/boundary/filesystem/nativePascalVerifier.test.ts diff --git a/scripts/lib/canonical-temporary-directory.mjs b/scripts/lib/canonical-temporary-directory.mjs new file mode 100644 index 000000000..84dd749c5 --- /dev/null +++ b/scripts/lib/canonical-temporary-directory.mjs @@ -0,0 +1,17 @@ +import { mkdtemp, realpath, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +/** Allocate under a caller-selected parent and return the host's canonical spelling. */ +export const createCanonicalTemporaryDirectory = async ( + prefix, + parent = tmpdir(), +) => { + const allocatedPath = await mkdtemp(join(parent, prefix)); + try { + return { path: await realpath(allocatedPath), allocatedPath }; + } catch (cause) { + await rm(allocatedPath, { recursive: true, force: true }); + throw cause; + } +}; diff --git a/scripts/verify-native-pascal-calls.mjs b/scripts/verify-native-pascal-calls.mjs index 79def6c87..5a9a56b15 100644 --- a/scripts/verify-native-pascal-calls.mjs +++ b/scripts/verify-native-pascal-calls.mjs @@ -1,54 +1,49 @@ import assert from "node:assert/strict"; -import { execFile } from "node:child_process"; -import { mkdtemp, readFile, rm } from "node:fs/promises"; -import { tmpdir } from "node:os"; +import { randomUUID } from "node:crypto"; +import { readFile, rm } from "node:fs/promises"; import { isAbsolute, join } from "node:path"; import { fileURLToPath } from "node:url"; +import { runOwnedCommand } from "../dist/process/OwnedCommand.js"; import { artifactCli, artifactMcpResult, withArtifactMcp, } from "./lib/artifact-e2e.mjs"; +import { createCanonicalTemporaryDirectory } from "./lib/canonical-temporary-directory.mjs"; -const execute = (command, arguments_, { timeout }) => - new Promise((resolve, reject) => { - let timedOut = false; - const child = execFile( +const cancellation = new AbortController(); +let shutdownSignal; +const signalExitCodes = { SIGINT: 130, SIGTERM: 143 }; +const forwardCancellation = (signal) => { + if (shutdownSignal !== undefined) return; + shutdownSignal = signal; + cancellation.abort(new Error(`Verification cancelled by ${signal}`)); +}; +const signalHandlers = Object.fromEntries( + Object.keys(signalExitCodes).map((signal) => [ + signal, + () => forwardCancellation(signal), + ]), +); +for (const [signal, handler] of Object.entries(signalHandlers)) + process.on(signal, handler); + +const execute = async (command, arguments_, { timeout }) => { + const result = await runOwnedCommand( + { command, - arguments_, - { detached: true, encoding: "utf8" }, - (error, stdout, stderr) => { - clearTimeout(deadline); - if (timedOut) { - const failure = new Error(`Command timed out after ${timeout} ms`); - Object.assign(failure, { - code: "ETIMEDOUT", - killed: true, - signal: "SIGKILL", - stdout, - stderr, - }); - reject(failure); - } else if (error !== null) { - reject(error); - } else { - resolve({ stdout, stderr }); - } - }, - ); - const deadline = setTimeout(() => { - timedOut = true; - if (child.pid === undefined) return; - try { - // This script only runs on macOS. detached:true gives the owned - // compiler invocation its own process group, inherited by FPC tools. - process.kill(-child.pid, "SIGKILL"); - } catch (cause) { - if (cause.code !== "ESRCH") child.kill("SIGKILL"); - } - }, timeout); - }); + arguments: arguments_, + runId: `rea-verify-pascal-${randomUUID()}`, + expectedCommand: null, + cwd: process.cwd(), + env: process.env, + }, + { timeoutMs: timeout, diagnosticBytes: 1024 * 1024 }, + { signal: cancellation.signal }, + ); + return { stdout: result.stdout.text, stderr: result.stderr.text }; +}; const compiler = process.env.REA_VERIFY_FPC_COMMAND; if (process.platform !== "darwin" || !isAbsolute(compiler ?? "")) throw new Error( @@ -67,7 +62,10 @@ const callerLines = new Set( return matches[0]; }), ); -const directory = await mkdtemp(join(tmpdir(), "rea-pascal-calls-")); +const allocatedDirectory = await createCanonicalTemporaryDirectory( + "rea-pascal-calls-", +); +let directory = allocatedDirectory.path; const input = { breakpoints: [{ kind: "function", name: "rea_pascal_call" }], argument_registers: 1, @@ -162,6 +160,22 @@ try { "bounded native call entries and compiler-provided source coordinates; no typed Pascal locals or interactive stepping", }), ); +} catch (cause) { + if (shutdownSignal === undefined) throw cause; + const cleanupFailure = cause?.cleanupFailure; + if (cleanupFailure !== undefined && cleanupFailure !== null) { + console.error( + `Verification cancelled by ${shutdownSignal}; owned compiler cleanup is incomplete: ${cleanupFailure}`, + ); + process.exitCode = 1; + } else { + console.error( + `Verification cancelled by ${shutdownSignal}; owned compiler process group was stopped.`, + ); + process.exitCode = signalExitCodes[shutdownSignal]; + } } finally { - await rm(directory, { recursive: true, force: true }); + for (const signal of Object.keys(signalExitCodes)) + process.off(signal, signalHandlers[signal]); + await rm(allocatedDirectory.allocatedPath, { recursive: true, force: true }); } diff --git a/tests/boundary/filesystem/nativePascalVerifier.test.ts b/tests/boundary/filesystem/nativePascalVerifier.test.ts new file mode 100644 index 000000000..9271835c3 --- /dev/null +++ b/tests/boundary/filesystem/nativePascalVerifier.test.ts @@ -0,0 +1,100 @@ +import { spawn } from "node:child_process"; +import { + chmod, + readFile, + readdir, + realpath, + rm, + symlink, + writeFile, +} from "node:fs/promises"; +import { basename, join } from "node:path"; +import { expect, it } from "vitest"; +import { createCanonicalTemporaryDirectory } from "../../../scripts/lib/canonical-temporary-directory.mjs"; +import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; + +it("uses the canonical spelling for a verifier directory allocated through a symlink", async () => { + const root = await createTestTempDirectory("rea-pascal-verifier-path-"); + const alias = join(root, "alias"); + await symlink( + root, + alias, + process.platform === "win32" ? "junction" : "dir", + ); + const allocated = await createCanonicalTemporaryDirectory( + "rea-pascal-calls-", + alias, + ); + try { + expect(allocated.path).toBe(await realpath(allocated.allocatedPath)); + expect(allocated.path).not.toBe( + join(alias, basename(allocated.allocatedPath)), + ); + } finally { + await rm(allocated.allocatedPath, { recursive: true, force: true }); + } +}); + +it.skipIf(process.platform !== "darwin")( + "forwards verifier SIGTERM to the owned compiler group and removes its temporary directory", + async () => { + const root = await createTestTempDirectory("rea-pascal-verifier-cancel-"); + const fakeCompiler = join(root, "fake-fpc"); + const pidFile = join(root, "compiler-pids.txt"); + await writeFile( + fakeCompiler, + '#!/usr/bin/env node\nimport { spawn } from "node:child_process";\nimport { writeFileSync } from "node:fs";\nconst child = spawn(process.execPath, ["-e", "setInterval(() => undefined, 1000)"], { stdio: "ignore" });\nwriteFileSync(process.env.REA_VERIFY_TEST_PID_FILE, `${process.pid} ${child.pid}\\n`);\nawait new Promise(() => undefined);\n', + ); + await chmod(fakeCompiler, 0o700); + const verifier = spawn( + process.execPath, + ["scripts/verify-native-pascal-calls.mjs"], + { + cwd: process.cwd(), + env: { + ...process.env, + TMPDIR: root, + REA_VERIFY_FPC_COMMAND: fakeCompiler, + REA_VERIFY_TEST_PID_FILE: pidFile, + }, + stdio: "ignore", + }, + ); + try { + const deadline = Date.now() + 10_000; + let pids: number[] | undefined; + while (Date.now() < deadline) { + try { + pids = (await readFile(pidFile, "utf8")) + .trim() + .split(/\s+/u) + .map(Number); + break; + } catch (cause) { + if (cause.code !== "ENOENT") throw cause; + await new Promise((resolve) => setTimeout(resolve, 20)); + } + } + expect(pids, "the fake compiler started").toHaveLength(2); + verifier.kill("SIGTERM"); + const result = await new Promise<{ + code: number | null; + signal: NodeJS.Signals | null; + }>((resolve, reject) => { + verifier.once("error", reject); + verifier.once("close", (code, signal) => resolve({ code, signal })); + }); + expect(result).toEqual({ code: 143, signal: null }); + for (const pid of pids ?? []) + expect(() => process.kill(pid, 0)).toThrow(); + expect( + (await readdir(root)).filter((name) => + name.startsWith("rea-pascal-calls-"), + ), + ).toEqual([]); + } finally { + verifier.kill("SIGKILL"); + await rm(root, { recursive: true, force: true }); + } + }, +);