|
| 1 | +// A detached descendant can retain stdio after forced settlement. Callers |
| 2 | +// finalize output hashes after wait(), so no later output may reach them. |
| 3 | +import crypto from "node:crypto"; |
| 4 | +import { statSync } from "node:fs"; |
| 5 | +import { writeFile } from "node:fs/promises"; |
| 6 | +import path from "node:path"; |
| 7 | +import { afterEach, describe, expect, it } from "vitest"; |
| 8 | +import { waitForDead, waitForPidFile } from "../../../test/helpers/process-wait.js"; |
| 9 | +import { createTempDirTracker } from "../../../test/helpers/temp-dir.js"; |
| 10 | +import { killPidIfAlive } from "../../test-utils/process-tree.js"; |
| 11 | +import { createProcessSupervisor } from "./supervisor.js"; |
| 12 | + |
| 13 | +// SIGTERM plus the adapter's kill-wait fallback is a fixed ~9s production window. |
| 14 | +const FORCED_SETTLEMENT_TEST_TIMEOUT_MS = 60_000; |
| 15 | +const LATE_OUTPUT_OBSERVATION_MS = 500; |
| 16 | +const CLEANUP_PID_RESOLVE_MS = 250; |
| 17 | + |
| 18 | +const activePids = new Set<number>(); |
| 19 | +const activePidFiles = new Set<string>(); |
| 20 | +const tempDirs = createTempDirTracker(); |
| 21 | + |
| 22 | +afterEach(async () => { |
| 23 | + try { |
| 24 | + for (const pidFile of activePidFiles) { |
| 25 | + const pid = await waitForPidFile(pidFile, CLEANUP_PID_RESOLVE_MS).catch(() => undefined); |
| 26 | + if (pid !== undefined) { |
| 27 | + activePids.add(pid); |
| 28 | + } |
| 29 | + } |
| 30 | + for (const pid of activePids) { |
| 31 | + killPidIfAlive(pid); |
| 32 | + } |
| 33 | + await Promise.all([...activePids].map((pid) => waitForDead(pid, 5_000).catch(() => {}))); |
| 34 | + } finally { |
| 35 | + activePidFiles.clear(); |
| 36 | + activePids.clear(); |
| 37 | + tempDirs.cleanup(); |
| 38 | + } |
| 39 | +}); |
| 40 | + |
| 41 | +async function createLeakedPipeScope() { |
| 42 | + const cwd = tempDirs.make("openclaw-forced-settlement-"); |
| 43 | + const leakPath = path.join(cwd, "leak.cjs"); |
| 44 | + const leakPidPath = path.join(cwd, "leak.pid"); |
| 45 | + const leakTickPath = path.join(cwd, "leak.ticks"); |
| 46 | + const rootPath = path.join(cwd, "root.cjs"); |
| 47 | + await writeFile( |
| 48 | + leakPath, |
| 49 | + ` |
| 50 | + const { appendFileSync, writeFileSync } = require("node:fs"); |
| 51 | + // Adapter disposal closes the parent-side pipes. Keep the escaped process |
| 52 | + // alive so its independent tick file proves output attempts continue. |
| 53 | + process.stdout.on("error", () => {}); |
| 54 | + process.stderr.on("error", () => {}); |
| 55 | + let tick = 0; |
| 56 | + setInterval(() => { |
| 57 | + tick += 1; |
| 58 | + appendFileSync(process.argv[3], "."); |
| 59 | + process.stdout.write("leaked-stdout-" + tick + "\\n"); |
| 60 | + process.stderr.write("leaked-stderr-" + tick + "\\n"); |
| 61 | + }, 50); |
| 62 | + writeFileSync(process.argv[2], String(process.pid)); |
| 63 | + `, |
| 64 | + "utf8", |
| 65 | + ); |
| 66 | + await writeFile( |
| 67 | + rootPath, |
| 68 | + ` |
| 69 | + const { spawn } = require("node:child_process"); |
| 70 | + process.stdout.write("live-stdout\\n"); |
| 71 | + process.stderr.write("live-stderr\\n"); |
| 72 | + // Inherit this root's stdout/stderr so the pipes outlive it, and detach so |
| 73 | + // the supervisor's process-group kill cannot reach the descendant. This is |
| 74 | + // the shipped CLI shape that would leave stdio open without terminal disposal. |
| 75 | + const leak = spawn( |
| 76 | + process.execPath, |
| 77 | + [${JSON.stringify(leakPath)}, ${JSON.stringify(leakPidPath)}, ${JSON.stringify(leakTickPath)}], |
| 78 | + { stdio: ["ignore", "inherit", "inherit"], detached: true }, |
| 79 | + ); |
| 80 | + leak.unref(); |
| 81 | + setInterval(() => {}, 1_000); |
| 82 | + `, |
| 83 | + "utf8", |
| 84 | + ); |
| 85 | + return { cwd, rootPath, leakPidPath, leakTickPath }; |
| 86 | +} |
| 87 | + |
| 88 | +function readTickCount(tickPath: string): number { |
| 89 | + try { |
| 90 | + return statSync(tickPath).size; |
| 91 | + } catch { |
| 92 | + return 0; |
| 93 | + } |
| 94 | +} |
| 95 | + |
| 96 | +describe.skipIf(process.platform === "win32")("supervisor forced settlement output fence", () => { |
| 97 | + it( |
| 98 | + "delivers nothing after forced settlement with inherited pipes held by a descendant", |
| 99 | + async () => { |
| 100 | + const { cwd, rootPath, leakPidPath, leakTickPath } = await createLeakedPipeScope(); |
| 101 | + activePidFiles.add(leakPidPath); |
| 102 | + const stdoutHash = crypto.createHash("sha256"); |
| 103 | + const stderrHash = crypto.createHash("sha256"); |
| 104 | + const delivered: string[] = []; |
| 105 | + // Production crashes uncaught inside the stream "data" handler; recording |
| 106 | + // the failure keeps the fence regression assertable instead of killing |
| 107 | + // the worker, and an empty list is the shipped contract. |
| 108 | + const hashFailures: string[] = []; |
| 109 | + const consume = (hash: crypto.Hash, label: string) => (chunk: string) => { |
| 110 | + delivered.push(`${label}:${chunk.trim()}`); |
| 111 | + try { |
| 112 | + hash.update(chunk); |
| 113 | + } catch (error) { |
| 114 | + hashFailures.push(`${label}:${(error as NodeJS.ErrnoException).code ?? String(error)}`); |
| 115 | + } |
| 116 | + }; |
| 117 | + |
| 118 | + const supervisor = createProcessSupervisor(); |
| 119 | + const run = await supervisor.spawn({ |
| 120 | + mode: "child", |
| 121 | + argv: [process.execPath, rootPath], |
| 122 | + sessionId: "forced-settlement-real", |
| 123 | + backendId: "forced-settlement-real", |
| 124 | + cwd, |
| 125 | + captureOutput: false, |
| 126 | + onStdout: consume(stdoutHash, "stdout"), |
| 127 | + onStderr: consume(stderrHash, "stderr"), |
| 128 | + onStdoutRaw: (raw) => delivered.push(`stdout-raw:${raw.toString("utf8").trim()}`), |
| 129 | + onStderrRaw: (raw) => delivered.push(`stderr-raw:${raw.toString("utf8").trim()}`), |
| 130 | + }); |
| 131 | + if (run.pid !== undefined) { |
| 132 | + activePids.add(run.pid); |
| 133 | + } |
| 134 | + |
| 135 | + const leakedPid = await waitForPidFile(leakPidPath, 15_000); |
| 136 | + activePidFiles.delete(leakPidPath); |
| 137 | + activePids.add(leakedPid); |
| 138 | + run.cancel("manual-cancel"); |
| 139 | + |
| 140 | + const exit = await run.wait(); |
| 141 | + // Exactly what the CLI runner does with the terminal result it just read. |
| 142 | + const digests = [stdoutHash.digest("hex"), stderrHash.digest("hex")]; |
| 143 | + const settledDelivered = [...delivered]; |
| 144 | + const settledOutputAtMs = supervisor.getRecord(run.runId)?.lastOutputAtMs; |
| 145 | + const settledTicks = readTickCount(leakTickPath); |
| 146 | + await new Promise<void>((resolve) => { |
| 147 | + setTimeout(resolve, LATE_OUTPUT_OBSERVATION_MS); |
| 148 | + }); |
| 149 | + |
| 150 | + expect(exit.reason).toBe("manual-cancel"); |
| 151 | + expect(digests.every((digest) => digest.length === 64)).toBe(true); |
| 152 | + expect(settledDelivered).toContain("stdout:live-stdout"); |
| 153 | + expect(settledDelivered).toContain("stderr-raw:live-stderr"); |
| 154 | + // The descendant stayed alive and attempted output across the terminal |
| 155 | + // boundary even though adapter disposal closed the parent-side pipes. |
| 156 | + expect(readTickCount(leakTickPath)).toBeGreaterThan(settledTicks); |
| 157 | + expect(hashFailures).toEqual([]); |
| 158 | + expect(delivered).toEqual(settledDelivered); |
| 159 | + expect(supervisor.getRecord(run.runId)?.lastOutputAtMs).toBe(settledOutputAtMs); |
| 160 | + }, |
| 161 | + FORCED_SETTLEMENT_TEST_TIMEOUT_MS, |
| 162 | + ); |
| 163 | +}); |
0 commit comments