|
| 1 | +import { ChildProcess } from "node:child_process"; |
| 2 | +import { createHash } from "node:crypto"; |
| 3 | +import fs from "node:fs/promises"; |
| 4 | +import os from "node:os"; |
| 5 | +import path from "node:path"; |
| 6 | +import { PassThrough } from "node:stream"; |
| 7 | +import { createDeferred } from "openclaw/plugin-sdk/extension-shared"; |
| 8 | +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; |
| 9 | +import { terminateCodexAppServerOrphan } from "./transport-process-containment.js"; |
| 10 | +import { |
| 11 | + createCodexAppServerProcessReaperService, |
| 12 | + prepareCodexAppServerProcessRegistration, |
| 13 | +} from "./transport-process-registration.js"; |
| 14 | +import { |
| 15 | + readCodexAppServerProcess, |
| 16 | + readCodexAppServerProcessCommand, |
| 17 | + readCodexAppServerProcessSnapshot, |
| 18 | + type PosixProcess, |
| 19 | +} from "./transport-process-snapshot.js"; |
| 20 | + |
| 21 | +vi.mock("./transport-process-snapshot.js", async (importOriginal) => ({ |
| 22 | + ...(await importOriginal<typeof import("./transport-process-snapshot.js")>()), |
| 23 | + readCodexAppServerProcessSnapshot: vi.fn(), |
| 24 | + readCodexAppServerProcess: vi.fn(), |
| 25 | + readCodexAppServerProcessCommand: vi.fn(), |
| 26 | +})); |
| 27 | + |
| 28 | +vi.mock("./transport-process-containment.js", async (importOriginal) => ({ |
| 29 | + ...(await importOriginal<typeof import("./transport-process-containment.js")>()), |
| 30 | + terminateCodexAppServerOrphan: vi.fn(), |
| 31 | +})); |
| 32 | + |
| 33 | +const observer: PosixProcess = { |
| 34 | + pid: process.pid, |
| 35 | + ppid: process.ppid, |
| 36 | + pgid: process.pid, |
| 37 | + state: "S", |
| 38 | + startedAt: "Sat Aug 29 10:00:00 2026", |
| 39 | +}; |
| 40 | +const parent = { pid: process.pid + 1, pgid: process.pid + 1, startedAt: observer.startedAt }; |
| 41 | +const child = { pid: process.pid + 2, pgid: process.pid + 2, startedAt: observer.startedAt }; |
| 42 | +const liveChild: PosixProcess = { ...child, ppid: 1, state: "S" }; |
| 43 | +const command = "/opt/codex app-server --listen stdio://"; |
| 44 | +const commandFingerprint = createHash("sha256").update(command).digest("hex"); |
| 45 | + |
| 46 | +async function openStore() { |
| 47 | + const { createPluginStateSyncKeyedStore } = |
| 48 | + await import("openclaw/plugin-sdk/plugin-state-store-runtime"); |
| 49 | + return createPluginStateSyncKeyedStore<{ |
| 50 | + parent: typeof parent; |
| 51 | + child: typeof child & { commandFingerprint?: string }; |
| 52 | + }>("codex", { |
| 53 | + namespace: "app-server-processes", |
| 54 | + maxEntries: 512, |
| 55 | + overflowPolicy: "reject-new", |
| 56 | + }); |
| 57 | +} |
| 58 | + |
| 59 | +describe("Codex process registration", () => { |
| 60 | + let root: string; |
| 61 | + let store: Awaited<ReturnType<typeof openStore>>; |
| 62 | + |
| 63 | + beforeEach(async () => { |
| 64 | + root = await fs.mkdtemp(path.join(os.tmpdir(), "codex-process-registration-")); |
| 65 | + vi.stubEnv("OPENCLAW_STATE_DIR", root); |
| 66 | + vi.spyOn(process, "platform", "get").mockReturnValue("darwin"); |
| 67 | + store = await openStore(); |
| 68 | + vi.mocked(readCodexAppServerProcessSnapshot).mockResolvedValue([ |
| 69 | + observer, |
| 70 | + { ...parent, ppid: 1, state: "Z" }, |
| 71 | + liveChild, |
| 72 | + ]); |
| 73 | + vi.mocked(readCodexAppServerProcessCommand).mockResolvedValue(command); |
| 74 | + vi.mocked(terminateCodexAppServerOrphan).mockResolvedValue(true); |
| 75 | + }); |
| 76 | + |
| 77 | + afterEach(async () => { |
| 78 | + store.clear(); |
| 79 | + vi.restoreAllMocks(); |
| 80 | + vi.resetAllMocks(); |
| 81 | + vi.unstubAllEnvs(); |
| 82 | + await fs.rm(root, { recursive: true, force: true }); |
| 83 | + }); |
| 84 | + |
| 85 | + it("never kills a same-second replacement process running a different command", async () => { |
| 86 | + store.register("orphan", { parent, child: { ...child, commandFingerprint } }); |
| 87 | + vi.mocked(readCodexAppServerProcessCommand).mockResolvedValue("/usr/bin/unrelated-worker"); |
| 88 | + |
| 89 | + await expect(prepareCodexAppServerProcessRegistration()).resolves.toBeTypeOf("function"); |
| 90 | + |
| 91 | + expect(terminateCodexAppServerOrphan).not.toHaveBeenCalled(); |
| 92 | + expect(store.lookup("orphan")).toBeUndefined(); |
| 93 | + }); |
| 94 | + |
| 95 | + it.for(["legacy", "matching command"])("reaps a %s registration", async (mode) => { |
| 96 | + const registeredChild = mode === "legacy" ? child : { ...child, commandFingerprint }; |
| 97 | + store.register("orphan", { parent, child: registeredChild }); |
| 98 | + |
| 99 | + await expect(prepareCodexAppServerProcessRegistration()).resolves.toBeTypeOf("function"); |
| 100 | + |
| 101 | + expect(terminateCodexAppServerOrphan).toHaveBeenCalledExactlyOnceWith(registeredChild); |
| 102 | + expect(store.lookup("orphan")).toBeUndefined(); |
| 103 | + expect(readCodexAppServerProcessCommand).toHaveBeenCalledTimes(mode === "legacy" ? 0 : 1); |
| 104 | + }); |
| 105 | + |
| 106 | + it.for(["gone", "replaced"])( |
| 107 | + "lets containment settle a %s child after command inspection fails", |
| 108 | + async (mode) => { |
| 109 | + store.register("orphan", { parent, child: { ...child, commandFingerprint } }); |
| 110 | + vi.mocked(readCodexAppServerProcessCommand).mockResolvedValue(undefined); |
| 111 | + vi.mocked(readCodexAppServerProcess).mockResolvedValue( |
| 112 | + mode === "gone" ? undefined : { ...liveChild, startedAt: "a later start" }, |
| 113 | + ); |
| 114 | + |
| 115 | + await expect(prepareCodexAppServerProcessRegistration()).resolves.toBeTypeOf("function"); |
| 116 | + |
| 117 | + expect(terminateCodexAppServerOrphan).toHaveBeenCalledExactlyOnceWith({ |
| 118 | + ...child, |
| 119 | + commandFingerprint, |
| 120 | + }); |
| 121 | + expect(store.lookup("orphan")).toBeUndefined(); |
| 122 | + }, |
| 123 | + ); |
| 124 | + |
| 125 | + it("refuses a spawn and retains the row when the matching child's command is unreadable", async () => { |
| 126 | + const registration = { parent, child: { ...child, commandFingerprint } }; |
| 127 | + store.register("orphan", registration); |
| 128 | + vi.mocked(readCodexAppServerProcessCommand).mockResolvedValue(undefined); |
| 129 | + vi.mocked(readCodexAppServerProcess).mockResolvedValue(liveChild); |
| 130 | + |
| 131 | + await expect(prepareCodexAppServerProcessRegistration()).rejects.toThrow( |
| 132 | + `Cannot inspect registered Codex process ${child.pid} command. Check process command inspection permissions (/proc on Linux, ps on macOS), then retry.`, |
| 133 | + ); |
| 134 | + |
| 135 | + expect(store.lookup("orphan")).toEqual(registration); |
| 136 | + expect(terminateCodexAppServerOrphan).not.toHaveBeenCalled(); |
| 137 | + }); |
| 138 | + |
| 139 | + it.for(["gone", "zombie", "replaced"])( |
| 140 | + "skips command inspection when the snapshot child is %s", |
| 141 | + async (mode) => { |
| 142 | + store.register("orphan", { parent, child: { ...child, commandFingerprint } }); |
| 143 | + vi.mocked(readCodexAppServerProcessSnapshot).mockResolvedValue([ |
| 144 | + observer, |
| 145 | + ...(mode === "gone" |
| 146 | + ? [] |
| 147 | + : [{ ...liveChild, ...(mode === "zombie" ? { state: "Z" } : { startedAt: "later" }) }]), |
| 148 | + ]); |
| 149 | + |
| 150 | + await prepareCodexAppServerProcessRegistration(); |
| 151 | + |
| 152 | + expect(readCodexAppServerProcessCommand).not.toHaveBeenCalled(); |
| 153 | + expect(terminateCodexAppServerOrphan).toHaveBeenCalledOnce(); |
| 154 | + expect(store.lookup("orphan")).toBeUndefined(); |
| 155 | + }, |
| 156 | + ); |
| 157 | + |
| 158 | + it("leaves a live parent's child registered without inspecting its command", async () => { |
| 159 | + const registration = { parent, child: { ...child, commandFingerprint } }; |
| 160 | + store.register("owned", registration); |
| 161 | + vi.mocked(readCodexAppServerProcessSnapshot).mockResolvedValue([ |
| 162 | + observer, |
| 163 | + { ...parent, ppid: 1, state: "S" }, |
| 164 | + liveChild, |
| 165 | + ]); |
| 166 | + |
| 167 | + await prepareCodexAppServerProcessRegistration(); |
| 168 | + |
| 169 | + expect(readCodexAppServerProcessCommand).not.toHaveBeenCalled(); |
| 170 | + expect(terminateCodexAppServerOrphan).not.toHaveBeenCalled(); |
| 171 | + expect(store.lookup("owned")).toEqual(registration); |
| 172 | + }); |
| 173 | + |
| 174 | + it.for(["live", "unreadable command", "exited during inspection"])( |
| 175 | + "registers only a live child with its command: %s", |
| 176 | + async (mode, ctx) => { |
| 177 | + const stdin = new PassThrough(); |
| 178 | + const stdout = new PassThrough(); |
| 179 | + const stderr = new PassThrough(); |
| 180 | + // The typed stdio tuple makes this fixture structurally a |
| 181 | + // ChildProcessWithoutNullStreams without widening casts. |
| 182 | + const spawned = Object.assign(new ChildProcess(), { |
| 183 | + pid: child.pid, |
| 184 | + stdin, |
| 185 | + stdout, |
| 186 | + stderr, |
| 187 | + stdio: [stdin, stdout, stderr, null, null] as [ |
| 188 | + PassThrough, |
| 189 | + PassThrough, |
| 190 | + PassThrough, |
| 191 | + null, |
| 192 | + null, |
| 193 | + ], |
| 194 | + }); |
| 195 | + ctx.onTestFinished(() => { |
| 196 | + spawned.stdin.destroy(); |
| 197 | + spawned.stdout.destroy(); |
| 198 | + spawned.stderr.destroy(); |
| 199 | + spawned.removeAllListeners(); |
| 200 | + }); |
| 201 | + const kill = vi.spyOn(spawned, "kill").mockReturnValue(true); |
| 202 | + vi.mocked(readCodexAppServerProcessSnapshot).mockResolvedValue([ |
| 203 | + observer, |
| 204 | + { ...liveChild, ppid: process.pid }, |
| 205 | + ]); |
| 206 | + vi.mocked(readCodexAppServerProcessCommand).mockImplementation(async () => { |
| 207 | + if (mode === "exited during inspection") { |
| 208 | + Object.defineProperty(spawned, "exitCode", { value: 0, configurable: true }); |
| 209 | + spawned.emit("exit", 0, null); |
| 210 | + } |
| 211 | + return mode === "unreadable command" ? undefined : command; |
| 212 | + }); |
| 213 | + const register = await prepareCodexAppServerProcessRegistration(); |
| 214 | + const registered = register(spawned); |
| 215 | + spawned.emit("spawn"); |
| 216 | + |
| 217 | + if (mode === "live") { |
| 218 | + await registered; |
| 219 | + expect(store.entries().map((entry) => entry.value)).toEqual([ |
| 220 | + { |
| 221 | + parent: { pid: observer.pid, pgid: observer.pgid, startedAt: observer.startedAt }, |
| 222 | + child: { ...child, commandFingerprint }, |
| 223 | + }, |
| 224 | + ]); |
| 225 | + // Durable rows must never expose the raw argv (appServer.args can carry secrets). |
| 226 | + expect(JSON.stringify(store.entries())).not.toContain(command); |
| 227 | + expect(kill).not.toHaveBeenCalled(); |
| 228 | + spawned.emit("exit", 0, null); |
| 229 | + expect(store.entries()).toEqual([]); |
| 230 | + } else { |
| 231 | + await expect(registered).rejects.toThrow("Cannot register the Codex child process command"); |
| 232 | + expect(kill).toHaveBeenCalledExactlyOnceWith("SIGKILL"); |
| 233 | + expect( |
| 234 | + [spawned.stdin, spawned.stdout, spawned.stderr].every((stream) => stream.destroyed), |
| 235 | + ).toBe(true); |
| 236 | + expect(store.entries()).toEqual([]); |
| 237 | + } |
| 238 | + }, |
| 239 | + ); |
| 240 | + |
| 241 | + it.for(["success", "failure", "win32"])( |
| 242 | + "starts a nonblocking best-effort boot sweep: %s", |
| 243 | + async (mode) => { |
| 244 | + store.register("orphan", { parent, child: { ...child, commandFingerprint } }); |
| 245 | + const warn = vi.fn(); |
| 246 | + const service = createCodexAppServerProcessReaperService(); |
| 247 | + const sweep = createDeferred<boolean>(); |
| 248 | + vi.mocked(terminateCodexAppServerOrphan).mockReturnValue(sweep.promise); |
| 249 | + if (mode === "win32") { |
| 250 | + vi.spyOn(process, "platform", "get").mockReturnValue("win32"); |
| 251 | + } |
| 252 | + |
| 253 | + expect( |
| 254 | + service.start({ |
| 255 | + config: {}, |
| 256 | + stateDir: root, |
| 257 | + logger: { debug: vi.fn(), info: vi.fn(), warn, error: vi.fn() }, |
| 258 | + }), |
| 259 | + ).toBeUndefined(); |
| 260 | + |
| 261 | + if (mode === "win32") { |
| 262 | + expect(readCodexAppServerProcessSnapshot).not.toHaveBeenCalled(); |
| 263 | + expect(terminateCodexAppServerOrphan).not.toHaveBeenCalled(); |
| 264 | + expect(store.lookup("orphan")).toBeDefined(); |
| 265 | + expect(warn).not.toHaveBeenCalled(); |
| 266 | + return; |
| 267 | + } |
| 268 | + await expect.poll(() => vi.mocked(terminateCodexAppServerOrphan).mock.calls.length).toBe(1); |
| 269 | + if (mode === "failure") { |
| 270 | + sweep.reject(new Error("inspection unavailable")); |
| 271 | + await expect |
| 272 | + .poll(() => warn.mock.calls) |
| 273 | + .toEqual([["Codex app-server orphan cleanup failed: Error: inspection unavailable"]]); |
| 274 | + expect(store.lookup("orphan")).toBeDefined(); |
| 275 | + } else { |
| 276 | + sweep.resolve(true); |
| 277 | + await expect.poll(() => store.lookup("orphan")).toBeUndefined(); |
| 278 | + expect(warn).not.toHaveBeenCalled(); |
| 279 | + } |
| 280 | + }, |
| 281 | + ); |
| 282 | +}); |
0 commit comments