From bec72da0e462a9b9446d397e73660d2bca8971f8 Mon Sep 17 00:00:00 2001 From: Dotta Date: Thu, 12 Nov 2026 02:18:54 -0600 Subject: [PATCH] Fix retained Photon sender cleanup retries --- .../configuration-retained.postgres.test.ts | 91 +++++++++++++++++++ .../__tests__/photon/external-owner.test.ts | 29 +++++- .../imessage-photon/external-runtime.ts | 52 +++++++---- server/src/services/photon/adapter.ts | 17 +++- server/src/services/photon/useful-client.ts | 26 +++--- tests/runner-e2e/process-tree.ts | 14 +-- 6 files changed, 188 insertions(+), 41 deletions(-) diff --git a/server/src/__tests__/photon/configuration-retained.postgres.test.ts b/server/src/__tests__/photon/configuration-retained.postgres.test.ts index 968b8cca354..3c0b944c8c2 100644 --- a/server/src/__tests__/photon/configuration-retained.postgres.test.ts +++ b/server/src/__tests__/photon/configuration-retained.postgres.test.ts @@ -29,6 +29,7 @@ import * as photonClients from "../../services/photon/owned-client.js"; import * as cloudConnectors from "../../services/paperclip-cloud-connector.js"; import { createDeliveryWorkCoordinator } from "../../services/delivery-work-coordinator.js"; import { idleWorkSnapshot } from "../../services/task-admission.js"; +import { notifyChatReceiver } from "../../services/chat-channels/runtime/receiver-work-notifications.js"; import { createPhotonExternalStore } from "../../services/chat-channels/imessage-photon/external-store.js"; import { createPhotonExternalOwner, PhotonLocalResources } from "../../services/chat-channels/imessage-photon/external-owner.js"; @@ -759,6 +760,96 @@ describe.skipIf(!external)("Photon normal configuration and retained receiver au await expect(c.service.configure(c.endpoint.id, { action: "remove" }, f.userId)).rejects.toMatchObject({ status: 409 }); }); + + async function unrecordedSenderFixture() { + const persistenceFailure = new Error("controlled sender debt transaction rollback"); + const closeFailure = new Error("controlled exact useful close failure"); + let failDebtWrite = false, closeFails = false; + const debtWrites: number[] = [], normalStore = photonStores.createPhotonExternalStore; + vi.spyOn(photonStores, "createPhotonExternalStore").mockImplementation(database => { + const store = normalStore(database), retained = store.retained.bind(store); + return { ...store, retained: async (...args: Parameters) => retained(args[0], current => { + const next = args[1](current); + if (failDebtWrite && next.failure?.code === "sender_close") { debtWrites.push(Date.now()); throw persistenceFailure; } + return next; + }, args[2]) }; + }); + const c = await managedConfiguration(), control = photonFixture();await c.reconstructExternal(control); + const runtime = c.runtime.get(c.endpoint.id);if (!runtime) throw new Error("normal retained sender runtime absent"); + const adapter = runtime.getProviderAdapter();if (!(adapter instanceof PhotonChatAdapter)) throw new Error("normal Photon adapter absent"); + control.client.close.mockImplementation(async () => { if (closeFails) throw closeFailure; }); + const text = "Controlled successful useful result before unrecorded close debt",messageId = randomUUID(); + const action = vi.fn(async (client: ReturnType["adapter"]["client"]) => client.messages.sendText(control.chat.guid,text,{clientMessageId:messageId})); + return { c, control, adapter, action, text, debtWrites, persistenceFailure, + arm(){failDebtWrite=true;closeFails=true;},restorePersistence(){failDebtWrite=false;},restoreClose(){closeFails=false;}, + invoke:()=>adapter.withClient(action), + assertSingleSend(){expect(action).toHaveBeenCalledTimes(1);expect(control.client.messages.sendText.mock.calls.filter(call=>call[1]===text)).toHaveLength(1);}, + }; + } + it("normal receiver recovers unrecorded sender close debt after SQL restoration without repeating its successful provider action", async () => { + // Normal service/Runtime/adapter/client queue and locked SQL transaction. + // Only unary provider result, local close and transaction failure are controlled. + const t=await unrecordedSenderFixture();let primary:{error:unknown}|undefined,coordinator:ReturnType|undefined; + try { + vi.useFakeTimers({toFake:["Date","setTimeout","clearTimeout","setInterval","clearInterval"],shouldAdvanceTime:true}); + coordinator=createDeliveryWorkCoordinator({owner:db,canRun:()=>true,onError:()=>{}});coordinators.push(coordinator); + await t.c.service.registerReceiverWork(coordinator,()=>true).ready; + await vi.waitFor(()=>{expect(idleWorkSnapshot().active).toBe(0);expect(coordinator!.nextWakeAt()).toBeNull();},{timeout:5000}); + t.arm();const result=await t.invoke();expect(result.guid).toBeTruthy();t.assertSingleSend(); + expect(t.debtWrites.length).toBeGreaterThan(0);expect(readPhotonExternalState(await t.c.state.read(PHOTON_EXTERNAL_STATE))?.failure).toBeNull(); + const original=readPhotonExternalState(await t.c.state.read(PHOTON_EXTERNAL_STATE));if(!original?.senderResource)throw new Error("normal prebirth sender descriptor absent"); + const failedCloses=t.control.client.close.mock.calls.length; + t.restorePersistence();t.restoreClose(); + // Restore only the controlled fault. No new message, action, explicit + // reconcile, notify, Retry or shutdown drives this recovery. + await vi.advanceTimersByTimeAsync(30_000); + await vi.waitFor(async()=>{ + expect(t.control.client.close.mock.calls.length,"unrecorded cleanup must retry through the already-idle normal receiver owner after SQL restoration").toBeGreaterThan(failedCloses); + expect(readPhotonExternalState(await t.c.state.read(PHOTON_EXTERNAL_STATE))?.failure).toBeNull(); + expect(idleWorkSnapshot().active).toBe(0);expect(coordinator!.nextWakeAt()).toBeNull(); + },{timeout:5000}); + const after=readPhotonExternalState(await t.c.state.read(PHOTON_EXTERNAL_STATE));expect(after?.senderResource?.id).toBe(original.senderResource.id); + expect(after?.identity).toEqual(original.identity);expect(after?.binding).toEqual(original.binding);t.assertSingleSend(); + }catch(error){primary={error};} + finally{ + t.restorePersistence();t.restoreClose();const cleanup:unknown[]=[]; + try{await coordinator?.stop();}catch(error){cleanup.push(error);}vi.useRealTimers(); + try{await t.c.runtime.removeEndpoint(t.c.endpoint.id);}catch(error){cleanup.push(error);} + try{await t.control.adapter.disconnect();}catch(error){cleanup.push(error);} + if(cleanup.length)throw new AggregateError([...(primary?[primary.error]:[]),...cleanup],"normal unrecorded sender cleanup remains owned"); + } + if(primary)throw primary.error; + }); + + + it("unrecorded sender debt respects normal worker error backoff and a future durable failure deadline", async () => { + const t=await unrecordedSenderFixture();let primary:{error:unknown}|undefined,coordinator:ReturnType|undefined; + try{ + vi.useFakeTimers({toFake:["Date","setTimeout","clearTimeout","setInterval","clearInterval"],shouldAdvanceTime:true}); + const errors:unknown[]=[];coordinator=createDeliveryWorkCoordinator({owner:db,canRun:()=>true,onError:error=>errors.push(error)});coordinators.push(coordinator); + await t.c.service.registerReceiverWork(coordinator,()=>true).ready; + await vi.waitFor(()=>{expect(idleWorkSnapshot().active).toBe(0);expect(coordinator!.nextWakeAt()).toBeNull();},{timeout:5000}); + t.arm();await t.invoke(); + await vi.waitFor(()=>{expect(errors.length).toBeGreaterThan(0);expect(t.debtWrites.length).toBeGreaterThan(1);},{timeout:5000}); + const attempts=t.debtWrites.length,failedCloses=t.control.client.close.mock.calls.length; + await vi.advanceTimersByTimeAsync(2000);expect(t.debtWrites).toHaveLength(attempts);expect(t.control.client.close).toHaveBeenCalledTimes(failedCloses); + t.restorePersistence();const state=readPhotonExternalState(await t.c.state.read(PHOTON_EXTERNAL_STATE));if(!state)throw new Error("normal sender state absent"); + const deadline=new Date(Date.now()+60_000).toISOString();await t.c.state.update(PHOTON_EXTERNAL_STATE,()=>({...state,failure:{code:"sender_close" as const,attempts:4,nextAttemptAt:deadline}})); + await db.transaction(tx=>notifyChatReceiver(tx,t.c.endpoint));t.restoreClose();await vi.advanceTimersByTimeAsync(30_000); + expect(t.control.client.close).toHaveBeenCalledTimes(failedCloses);expect(readPhotonExternalState(await t.c.state.read(PHOTON_EXTERNAL_STATE))?.failure).toEqual({code:"sender_close",attempts:4,nextAttemptAt:deadline}); + await vi.advanceTimersByTimeAsync(30_001); + await vi.waitFor(async()=>{expect(t.control.client.close.mock.calls.length).toBeGreaterThan(failedCloses);expect(readPhotonExternalState(await t.c.state.read(PHOTON_EXTERNAL_STATE))?.failure).toBeNull();expect(coordinator!.nextWakeAt()).toBeNull();},{timeout:5000});t.assertSingleSend(); + }catch(error){primary={error};} + finally{ + t.restorePersistence();t.restoreClose();const cleanup:unknown[]=[]; + try{await coordinator?.stop();}catch(error){cleanup.push(error);}vi.useRealTimers(); + try{await t.c.runtime.removeEndpoint(t.c.endpoint.id);}catch(error){cleanup.push(error);} + try{await t.control.adapter.disconnect();}catch(error){cleanup.push(error);} + if(cleanup.length)throw new AggregateError([...(primary?[primary.error]:[]),...cleanup],"normal sender backoff cleanup remains owned"); + } + if(primary)throw primary.error; + }); + it("normal receiver retries the same useful sender close without another message and replacement never treats absence as closure", async () => { // Actual Runtime/adapter/useful-client, service callback and retained SQL; // unary result/close failures and durable unknown image are controlled ports. diff --git a/server/src/__tests__/photon/external-owner.test.ts b/server/src/__tests__/photon/external-owner.test.ts index 486216ed355..c3bdde23adc 100644 --- a/server/src/__tests__/photon/external-owner.test.ts +++ b/server/src/__tests__/photon/external-owner.test.ts @@ -3,7 +3,9 @@ import type { ProcessProbe } from "../../services/owner-proof.js"; import { randomUUID } from "node:crypto"; import { queryObjects } from "node:v8"; import { isDeepStrictEqual } from "node:util"; -import { describe, expect, it } from "vitest"; +import { describe, expect, it, vi } from "vitest"; +import { photonFixture } from "./fixture.js"; +import * as photonClients from "../../services/photon/owned-client.js"; import type { ChatSdkStatePersistence, ChatSdkStateRecord } from "../../services/chat-sdk-state.js"; import { PhotonState } from "../../services/photon/state.js"; import { PhotonUsefulClient } from "../../services/photon/useful-client.js"; @@ -287,6 +289,31 @@ describe("Photon actual resource join and useful-channel owner", () => { await owner.run(async () => "first-useful-result"); await owner.run(async () => "second-useful-result"); expect({ opens, closes }).toEqual({ opens: 2, closes: 2 }); await owner.close(); expect(closes).toBe(2); }); + it("lazy useful ownership joins its original client and commits the held receipt before constructing or running later useful work", async () => { + const f = photonFixture(); + const laterClient = { ...f.client, close: vi.fn(async () => {}) }; + const create = vi.spyOn(photonClients, "createOwnedPhotonClient").mockReturnValue(laterClient as unknown as ReturnType); + let enterReceipt = () => {}, releaseReceipt = () => {}; + const entered = new Promise(resolve => { enterReceipt = resolve; }); + const receipt = new Promise(resolve => { releaseReceipt = resolve; }); + const order: string[] = [], providerAction = vi.fn(async () => { order.push("provider"); return "known-later-result"; }); + let drain: Promise | undefined, useful: Promise | undefined; + try { + // Start with the real adapter's original local client and no useful queue. + // Drain must adopt that same object without allocating an SDK replacement. + drain = f.adapter.drainUsefulClient(async () => { order.push("receipt-entered"); enterReceipt(); await receipt; order.push("receipt-committed"); }); + await entered; + expect(f.client.close).toHaveBeenCalledTimes(1); expect(create).not.toHaveBeenCalled(); + useful = f.adapter.withClient(providerAction); await Promise.resolve(); + expect(create).not.toHaveBeenCalled(); expect(providerAction).not.toHaveBeenCalled(); expect(laterClient.close).not.toHaveBeenCalled(); + releaseReceipt(); await drain; expect(await useful).toBe("known-later-result"); + expect(order).toEqual(["receipt-entered", "receipt-committed", "provider"]); + expect(create).toHaveBeenCalledTimes(1); expect(providerAction).toHaveBeenCalledTimes(1); expect(laterClient.close).toHaveBeenCalledTimes(1); + } finally { + releaseReceipt(); await Promise.allSettled([...(drain ? [drain] : []), ...(useful ? [useful] : [])]); + try { await f.adapter.disconnect(); } finally { create.mockRestore(); f.allocation.mockRestore(); } + } + }); it("known provider receipt survives cleanup refusal and old physical resource retries before new send", async () => { let opens = 0, closes = 0, sends = 0, debt = 0; const owner = new PhotonUsefulClient(() => { opens++; return { close: async () => { if (++closes === 1) throw new Error("cleanup refused"); } }; }, undefined, async () => { debt++; }); diff --git a/server/src/services/chat-channels/imessage-photon/external-runtime.ts b/server/src/services/chat-channels/imessage-photon/external-runtime.ts index 4a361113616..1daa5654462 100644 --- a/server/src/services/chat-channels/imessage-photon/external-runtime.ts +++ b/server/src/services/chat-channels/imessage-photon/external-runtime.ts @@ -359,7 +359,13 @@ export function createPhotonExternalRuntimeOwner(db: Db, options: { external = (await createPhotonExternalOwner({ store, broker, resources, notify: value => options.notify(value.endpointId) }).repair(external)).state; } const adapter = options.currentRuntime(id)?.getProviderAdapter(); - if (adapter instanceof PhotonChatAdapter) await adapter.drainUsefulClient(); + const drainedState = external; + if (adapter instanceof PhotonChatAdapter) await adapter.drainUsefulClient(async () => { + if (drainedState.failure?.code !== "sender_close") return; + // This exact pre-drain receipt cannot erase a concurrent future hold, + // authority/allocation/checkpoint update or a different failure. + await store.retained(drainedState, value => ({ ...value, failure: null })); + }); else if (external.failure?.code === "sender_close") { const removed = await options.removeRuntime(id); const owner = createPhotonExternalOwner({ store, broker, resources, notify: value => options.notify(value.endpointId) }); @@ -370,7 +376,8 @@ export function createPhotonExternalRuntimeOwner(db: Db, options: { throw new Error("Photon original sender physical closure is unknown"); } } - if (external.failure?.code === "sender_close") await store.retained(external, value => ({ ...value, failure: null })); + if (!(adapter instanceof PhotonChatAdapter) && external.failure?.code === "sender_close") + await store.retained(external, value => ({ ...value, failure: null })); return; } const runtime = await options.runtimeFor(record.endpoint, { requireDiscordOwnership: true }); @@ -430,21 +437,22 @@ export function createPhotonExternalRuntimeOwner(db: Db, options: { } }; async function senderDebt(id: string, context?: RuntimeContext) { - const record = await options.endpointRecord(id); - if (!record) throw new Error("Photon sender debt has no retained endpoint"); - const runtime = options.currentRuntime(id); - context ??= runtime ? options.context(runtime) : undefined; - const external = await store.read({ companyId: record.endpoint.companyId, endpointId: id }); - // Debt is cleanup authority for the exact original runtime, including after - // pause/archive fences business and the registry moves it to retiring. - if (!external || !["external", "retiring"].includes(external.phase) - || !context?.endpointRuntime || options.context(context.endpointRuntime) !== context - || external.identity.runtimeGeneration !== context.generation - || external.identity.credentialReferences !== context.credentialFingerprint - || external.senderResource && !resources.owns(external.senderResource.id, context.endpointRuntime)) - throw new Error("Photon sender debt has no exact retained owner"); - await store.retained(external, value => ({ ...value, failure: { code: "sender_close", attempts: (value.failure?.attempts ?? 0) + 1, nextAttemptAt: new Date().toISOString() } })); - options.notify(id); + try { + const record = await options.endpointRecord(id); + if (!record) throw new Error("Photon sender debt has no retained endpoint"); + const runtime = options.currentRuntime(id); + context ??= runtime ? options.context(runtime) : undefined; + const external = await store.read({ companyId: record.endpoint.companyId, endpointId: id }); + // Debt is cleanup authority for the exact original runtime, including after + // pause/archive fences business and the registry moves it to retiring. + if (!external || !["external", "retiring"].includes(external.phase) + || !context?.endpointRuntime || options.context(context.endpointRuntime) !== context + || external.identity.runtimeGeneration !== context.generation + || external.identity.credentialReferences !== context.credentialFingerprint + || external.senderResource && !resources.owns(external.senderResource.id, context.endpointRuntime)) + throw new Error("Photon sender debt has no exact retained owner"); + await store.retained(external, value => ({ ...value, failure: { code: "sender_close", attempts: (value.failure?.attempts ?? 0) + 1, nextAttemptAt: new Date().toISOString() } })); + } finally { options.notify(id); } } async function retire(id: string, cleanup?: { responsibleUserId?: string | null; reauthorize(): Promise }) { const record = await options.endpointRecord(id), broker = options.broker(); @@ -502,10 +510,18 @@ export function createPhotonExternalRuntimeOwner(db: Db, options: { const closedOriginalProcess = !changedExternal && state.phase === "external" && state.failure === null && state.localClosureConfirmed !== true && state.localResourceDebt?.nextAttemptAt === null && await photonResourceProcessEnded(state); + // In-memory retry hint is ONLY the exact current sender whose debt + // has not yet reached SQL. Existing durable failure/debt deadlines win. + const runtime = options.currentRuntime(row.endpointId), context = runtime ? options.context(runtime) : undefined; + const adapter = runtime?.getProviderAdapter(); + const unrecordedSenderDebt = state.phase === "external" && !!state.senderResource && !state.senderResource.closed + && !!runtime && !!context && context.endpointRuntime === runtime && options.context(runtime) === context + && context.generation === state.identity.runtimeGeneration && context.credentialFingerprint === state.identity.credentialReferences + && resources.owns(state.senderResource.id, runtime) && adapter instanceof PhotonChatAdapter && adapter.hasUnrecordedUsefulClientDebt(); values.push({ id: row.endpointId, companyId: row.companyId, connectionId: row.connectionId, dueAt: changedExternal || restoredRetirementPort || closedOriginalProcess ? 0 : state.failure ? (state.failure.nextAttemptAt ? Date.parse(state.failure.nextAttemptAt) : null) : state.localResourceDebt ? (state.localResourceDebt.nextAttemptAt ? Date.parse(state.localResourceDebt.nextAttemptAt) : null) - : state.phase === "external" ? null : 0 }); + : unrecordedSenderDebt ? 0 : state.phase === "external" ? null : 0 }); } return values; } diff --git a/server/src/services/photon/adapter.ts b/server/src/services/photon/adapter.ts index 09cbcfe0d8d..3bd937a93c1 100644 --- a/server/src/services/photon/adapter.ts +++ b/server/src/services/photon/adapter.ts @@ -105,7 +105,10 @@ export class PhotonChatAdapter implements Adapter { private localClient?: GrpcAdvancedIMessage; private usefulClient?: PhotonUsefulClient; onUsefulClientDebt?: () => Promise; - async drainUsefulClient(): Promise { await this.usefulClient?.drain(); } + async drainUsefulClient(afterClose?: () => Promise): Promise { + await this.externalClientOwner().drain(afterClose); + } + hasUnrecordedUsefulClientDebt(): boolean { return this.usefulClient?.hasUnrecordedCleanupDebt() ?? false; } private makeClient(): GrpcAdvancedIMessage { return createOwnedPhotonClient({ address: this.authentication.address, token: () => this.authentication.token(), tls: true, retry: false, autoIdempotency: false, timeout: 25_000, @@ -116,10 +119,16 @@ export class PhotonChatAdapter implements Adapter { if (!this.localClient) throw new Error("Photon local client is closed"); return this.localClient; } + private externalClientOwner(): PhotonUsefulClient { + if (!this.usefulClient) { + if (!this.localClient) throw new Error("Photon useful cleanup has no original client owner"); + this.usefulClient = new PhotonUsefulClient(() => this.makeClient(), this.localClient, async () => { if (!this.onUsefulClientDebt) throw new Error("Photon physical debt owner is unavailable"); await this.onUsefulClientDebt(); }); + this.localClient = undefined; + } + return this.usefulClient; + } async useExternalIntake(): Promise { - this.usefulClient ??= new PhotonUsefulClient(() => this.makeClient(), this.localClient, async () => { if (!this.onUsefulClientDebt) throw new Error("Photon physical debt owner is unavailable"); await this.onUsefulClientDebt(); }); - this.localClient = undefined; - await this.usefulClient.drain(); + await this.externalClientOwner().drain(); } withClient(action: (client: GrpcAdvancedIMessage) => Promise): Promise { return this.usefulClient ? this.usefulClient.run(action) : action(this.client); diff --git a/server/src/services/photon/useful-client.ts b/server/src/services/photon/useful-client.ts index 9ca1e793721..ad73131bb9a 100644 --- a/server/src/services/photon/useful-client.ts +++ b/server/src/services/photon/useful-client.ts @@ -15,20 +15,22 @@ export class PhotonUsefulClient | void }> { this.client = initial; this.unregister = registerIdleLocalWorkProbe(() => this.failed || this.unrecordedDebt ? "unknown" : this.pending || this.client ? "present" : "none"); } - private async closeCurrent() { + private async closeCurrent(afterClose?: () => Promise) { const client = this.client; - if (!client) { - if (this.unrecordedDebt) { await this.recordDebt(); this.unrecordedDebt = false; } - return; + if (client) { + try { await client.close(); this.client = undefined; this.failed = false; } + catch (error) { + this.failed = true; this.unrecordedDebt = true; + try { await this.recordDebt(); this.unrecordedDebt = false; } catch { /* Exact resource stays owned and the probe remains unknown. */ } + throw error; + } } - try { await client.close(); this.client = undefined; this.failed = false; } - catch (error) { - this.failed = true; this.unrecordedDebt = true; - try { await this.recordDebt(); this.unrecordedDebt = false; } catch { /* Exact resource stays owned and the probe remains unknown. */ } - throw error; - } - if (this.unrecordedDebt) { await this.recordDebt(); this.unrecordedDebt = false; } + // The exact cleanup receipt substitutes for recording debt after an actual + // successful close. A failed receipt stays pending and is not a close error. + if (afterClose) { await afterClose(); this.unrecordedDebt = false; } + else if (this.unrecordedDebt) { await this.recordDebt(); this.unrecordedDebt = false; } } + hasUnrecordedCleanupDebt(): boolean { return this.unrecordedDebt; } private enqueue(action: () => Promise): Promise { this.pending += 1; const result = this.tail.then(action); @@ -53,7 +55,7 @@ export class PhotonUsefulClient | void }> { return value; }); } - drain(): Promise { return this.enqueue(() => this.closeCurrent()); } + drain(afterClose?: () => Promise): Promise { return this.enqueue(() => this.closeCurrent(afterClose)); } close(): Promise { this.stopped = true; return this.enqueue(async () => { await this.closeCurrent(); this.unregister(); }); diff --git a/tests/runner-e2e/process-tree.ts b/tests/runner-e2e/process-tree.ts index 7a21642d9cd..8352b812ed7 100644 --- a/tests/runner-e2e/process-tree.ts +++ b/tests/runner-e2e/process-tree.ts @@ -185,29 +185,31 @@ export async function readProcessTable(startInspector?: () => ChildProcess): Pro let output = ""; let settled = false; let truncated = false; - const finish = (value: ProcessObservation[] | null) => { + const finish = (value: ProcessObservation[] | null, reason?: "timeout" | "output_limit" | "spawn_error" | "nonzero_exit", code?: string | number | null, signal?: NodeJS.Signals | null) => { if (settled) return; settled = true; clearTimeout(inspectionTimeout); + if (reason) console.error("[runner-process-inspector] " + JSON.stringify({ reason, pid: inspector.pid ?? null, code: code ?? null, signal: signal ?? null, outputLength: output.length })); resolve(value); }; const inspectionTimeout = setTimeout(() => { inspector.kill("SIGKILL"); - finish(null); + finish(null, "timeout"); }, 5_000); inspectionTimeout.unref(); inspector.stdout?.setEncoding("utf8").on("data", (chunk: string) => { if (output.length + chunk.length > 1024 * 1024) { truncated = true; inspector.kill("SIGKILL"); - finish(null); + finish(null, "output_limit"); return; } output += chunk; }); - inspector.once("error", () => finish(null)); - inspector.once("close", (code) => { - if (code !== 0 || truncated) { finish(null); return; } + inspector.once("error", (error: NodeJS.ErrnoException) => finish(null, "spawn_error", + ["EAGAIN", "EMFILE", "ENFILE", "ENOENT", "EACCES", "EPERM"].includes(error.code ?? "") ? error.code : "other")); + inspector.once("close", (code, signal) => { + if (code !== 0 || truncated) { finish(null, truncated ? "output_limit" : "nonzero_exit", code, signal); return; } const observations = output .split(/\r?\n/) .map((line) =>