From a036e06c53619caa811896c96a485b39d10c4ca1 Mon Sep 17 00:00:00 2001 From: Tiago Neves Date: Sat, 17 Oct 2026 20:04:46 +0100 Subject: [PATCH] Face worker: retry once when the process is killed by a signal Node reports a signal kill as exit code null, so the in-flight request failed as "face worker exited (null)" with an empty stderr. Retry that request on a new process, and keep the signal name if it dies again. Closing the worker is not reported as that crash. Paperclip-Agent: Bug Squasher (urlKey bug-squasher; id 4669adc7-6368-43ef-bf27-5a601a6b7b83) Paperclip-Issue: BIT-31393 Paperclip-Run: 16662666-cc93-4b3c-9b85-cf591a921062 --- apps/api/src/lib/line-process.ts | 94 +++++++++++++++++++++++------- apps/api/test/line-process.test.ts | 60 +++++++++++++++++++ 2 files changed, 133 insertions(+), 21 deletions(-) create mode 100644 apps/api/test/line-process.test.ts diff --git a/apps/api/src/lib/line-process.ts b/apps/api/src/lib/line-process.ts index 09650c2..0e84e0c 100644 --- a/apps/api/src/lib/line-process.ts +++ b/apps/api/src/lib/line-process.ts @@ -1,11 +1,14 @@ import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process"; import { createInterface } from "node:readline"; +import { AppError } from "./errors.js"; /** * A long-running helper process that speaks JSON lines over stdin/stdout (the Rust workers): it prints * `{"ready": true, ...}` once, then answers each `{"id": ..., ...}` request with a line carrying the same id. * Requests are serialised (the helpers are single-threaded; run several for parallelism). The process is * restarted after a crash; a request that hangs is failed after `timeoutMs` and the process killed. + * A signal death (Node reports exit code `null`) is retried once on a new process. `close()` is an + * intentional stop and is not reported as that crash. */ export class LineProcess { private child: ChildProcessWithoutNullStreams | undefined; @@ -13,11 +16,13 @@ export class LineProcess { private pending = new Map) => void; reject: (e: Error) => void; timer: NodeJS.Timeout }>(); private queue: Promise = Promise.resolve(); private seq = 0; + private stopping = false; constructor(private readonly opts: { name: string; bin: string; args?: string[]; timeoutMs?: number }) {} /** Starts the process if needed and resolves with its ready line. */ start(): Promise> { + if (this.stopping) return Promise.reject(new AppError(503, "engine_unavailable")); if (this.ready) return this.ready; const child = spawn(this.opts.bin, this.opts.args ?? [], { stdio: ["pipe", "pipe", "pipe"] }); this.child = child; @@ -29,7 +34,7 @@ export class LineProcess { child.stderr.on("data", (d: Buffer) => { stderr = (stderr + d.toString()).slice(-2000); }); - this.ready = new Promise((resolve, reject) => { + const ready = new Promise>((resolve, reject) => { const lines = createInterface({ input: child.stdout }); let started = false; lines.on("line", (line) => { @@ -52,37 +57,44 @@ export class LineProcess { if (typeof msg.error === "string") waiting.reject(new Error(msg.error)); else waiting.resolve(msg); }); - child.on("exit", (code) => { - const err = new Error(`${this.opts.name} exited (${code}): ${stderr.trim()}`); + child.on("exit", (code, signal) => { + const err = this.exitError(code, signal, stderr); + // Drop this process before rejecting so a retry can spawn the replacement + // synchronously from the rejection handler without inheriting the dead child. + const waiting = [...this.pending.entries()]; + for (const [id] of waiting) this.pending.delete(id); + if (this.child === child) { + this.child = undefined; + this.ready = undefined; + } if (!started) reject(err); - for (const [, p] of this.pending) { + for (const [, p] of waiting) { clearTimeout(p.timer); p.reject(err); } - this.pending.clear(); - this.child = undefined; - this.ready = undefined; }); child.on("error", (e) => { if (!started) reject(e); }); }); - return this.ready; + // `close()` may drop the only other reference while the process is still starting. + ready.catch(() => undefined); + this.ready = ready; + return ready; } request(payload: Record): Promise> { const run = async () => { - await this.start(); - const id = String(++this.seq); - return new Promise>((resolve, reject) => { - const timer = setTimeout(() => { - this.pending.delete(id); - reject(new Error(`${this.opts.name} timed out`)); - this.child?.kill(); - }, this.opts.timeoutMs ?? 120_000); - this.pending.set(id, { resolve, reject, timer }); - this.child?.stdin.write(JSON.stringify({ ...payload, id }) + "\n"); - }); + let last: unknown; + for (let attempt = 0; attempt < 2; attempt++) { + try { + return await this.exchange(payload); + } catch (err) { + last = err; + if (this.stopping || attempt === 1 || !(err instanceof WorkerExit)) throw err; + } + } + throw last; }; const result = this.queue.then(run, run); this.queue = result.catch(() => undefined); @@ -90,10 +102,50 @@ export class LineProcess { } async close(): Promise { + this.stopping = true; + const ready = this.ready; this.child?.stdin.end(); this.child?.kill(); - this.child = undefined; - this.ready = undefined; + await ready?.catch(() => undefined); + } + + private exchange(payload: Record): Promise> { + return this.start().then( + () => + new Promise>((resolve, reject) => { + if (this.stopping) { + reject(new AppError(503, "engine_unavailable")); + return; + } + if (!this.child) { + reject(new WorkerExit(`${this.opts.name} exited (before request): `)); + return; + } + const id = String(++this.seq); + const timer = setTimeout(() => { + this.pending.delete(id); + reject(new Error(`${this.opts.name} timed out`)); + this.child?.kill(); + }, this.opts.timeoutMs ?? 120_000); + this.pending.set(id, { resolve, reject, timer }); + this.child.stdin.write(JSON.stringify({ ...payload, id }) + "\n"); + }), + ); + } + + /** Signal exits are `code === null` in Node; keep the signal name so the report is not just "(null)". */ + private exitError(code: number | null, signal: NodeJS.Signals | null, stderr: string): Error { + if (this.stopping) return new AppError(503, "engine_unavailable"); + const how = signal ? `signal ${signal}` : String(code); + return new WorkerExit(`${this.opts.name} exited (${how}): ${stderr.trim()}`); + } +} + +/** A helper process died. One in-flight request is retried on a new process; a second death is reported. */ +class WorkerExit extends Error { + constructor(message: string) { + super(message); + this.name = "WorkerExit"; } } diff --git a/apps/api/test/line-process.test.ts b/apps/api/test/line-process.test.ts new file mode 100644 index 0000000..16aed41 --- /dev/null +++ b/apps/api/test/line-process.test.ts @@ -0,0 +1,60 @@ +import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { describe, expect, it } from "vitest"; +import { LineProcess } from "../src/lib/line-process.js"; + +/** + * Fake JSON-line worker. `die-once` exits with SIGTERM on the first process only + * (Node reports that as exit code null). `die-always` does it on every process. + */ +const WORKER = ` +import { createInterface } from "node:readline"; +import { existsSync, writeFileSync } from "node:fs"; +const marker = process.argv[2]; +const mode = process.argv[3]; +process.stdout.write(JSON.stringify({ ready: true }) + "\\n"); +if ((mode === "die-once" && !existsSync(marker)) || mode === "die-always") { + if (mode === "die-once") writeFileSync(marker, "1"); + process.kill(process.pid, "SIGTERM"); +} else { + const lines = createInterface({ input: process.stdin }); + lines.on("line", (line) => { + const msg = JSON.parse(line); + process.stdout.write(JSON.stringify({ id: msg.id, width: 2 }) + "\\n"); + }); +} +`; + +describe("line process", () => { + it("retries a signal death once and names the signal if it dies again", async () => { + const dir = await mkdtemp(path.join(tmpdir(), "pr-lp-")); + const script = path.join(dir, "worker.mjs"); + const marker = path.join(dir, "died"); + await writeFile(script, WORKER); + const once = new LineProcess({ name: "face worker", bin: process.execPath, args: [script, marker, "die-once"], timeoutMs: 5_000 }); + const always = new LineProcess({ name: "face worker", bin: process.execPath, args: [script, marker, "die-always"], timeoutMs: 5_000 }); + try { + await expect(once.request({ path: "a.jpg" })).resolves.toMatchObject({ width: 2 }); + await expect(always.request({ path: "a.jpg" })).rejects.toThrow(/face worker exited \(signal SIGTERM\)/); + } finally { + await once.close(); + await always.close(); + await rm(dir, { recursive: true, force: true }); + } + }); + + it("does not report an intentional close as a worker crash", async () => { + const dir = await mkdtemp(path.join(tmpdir(), "pr-lp-")); + const script = path.join(dir, "worker.mjs"); + await writeFile(script, WORKER); + const proc = new LineProcess({ name: "face worker", bin: process.execPath, args: [script, path.join(dir, "m"), "stay"], timeoutMs: 5_000 }); + try { + await expect(proc.request({ path: "a.jpg" })).resolves.toMatchObject({ width: 2 }); + await proc.close(); + await expect(proc.request({ path: "b.jpg" })).rejects.toThrow(/engine_unavailable/); + } finally { + await rm(dir, { recursive: true, force: true }); + } + }); +});