fix(providers): retain worker cleanup owners through shutdown
Validation: integrated changes passed formatting, typecheck, lint, resolved module-boundary verification and git diff --check. Tests and real-provider workflows were not run.
This commit is contained in:
@@ -113,6 +113,7 @@ export const runFirmwareCommand = async (context: {
|
||||
launcher?: FirmwareLauncher;
|
||||
outputBudget?: { root: string; bytes: number; entries: number };
|
||||
acceptReportedExtractionFailure?: boolean;
|
||||
retainCleanup(supervisor: ProviderProcessSupervisor): void;
|
||||
}) => {
|
||||
const { engine, operation, signal } = context;
|
||||
signal.throwIfAborted();
|
||||
@@ -141,16 +142,43 @@ export const runFirmwareCommand = async (context: {
|
||||
NO_COLOR: "1",
|
||||
},
|
||||
});
|
||||
const supervisor = new ProviderProcessSupervisor({
|
||||
...spawned,
|
||||
ownsProcessLifetime: true,
|
||||
cleanup:
|
||||
spawned.cleanup ?? (() => cleanupOwnedProcessGroup(spawned.ownership)),
|
||||
});
|
||||
let diagnosticTruncated = false;
|
||||
const supervisor = new ProviderProcessSupervisor(
|
||||
{
|
||||
...spawned,
|
||||
ownsProcessLifetime: true,
|
||||
cleanup:
|
||||
spawned.cleanup ?? (() => cleanupOwnedProcessGroup(spawned.ownership)),
|
||||
},
|
||||
{
|
||||
maxDiagnosticBytes: FIRMWARE_LIMITS.diagnosticBytes,
|
||||
onDiagnostic: (event) => {
|
||||
if (event.type === "output" && event.truncated === true)
|
||||
diagnosticTruncated = true;
|
||||
},
|
||||
},
|
||||
);
|
||||
const checkDiagnostics = () => {
|
||||
if (diagnosticTruncated) {
|
||||
const snapshot = supervisor.snapshot();
|
||||
throw new AnalysisOutputError(
|
||||
operation,
|
||||
`Tool diagnostics exceeded the ${FIRMWARE_LIMITS.diagnosticBytes}-byte capture budget`,
|
||||
{
|
||||
capturedOutput: {
|
||||
stdout: snapshot.stdout.text,
|
||||
stderr: snapshot.stderr.text,
|
||||
truncated: true,
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
};
|
||||
let failure: unknown;
|
||||
try {
|
||||
const deadline = Date.now() + FIRMWARE_LIMITS.timeoutMs;
|
||||
while (!(await supervisor.waitForExit(100))) {
|
||||
while (!(await supervisor.waitForOutputClose(100))) {
|
||||
checkDiagnostics();
|
||||
if (signal.aborted) throw new AnalysisCancelledError(operation);
|
||||
if (Date.now() >= deadline)
|
||||
throw new AnalysisTimeoutError(operation, FIRMWARE_LIMITS.timeoutMs);
|
||||
@@ -163,14 +191,15 @@ export const runFirmwareCommand = async (context: {
|
||||
signal,
|
||||
);
|
||||
}
|
||||
checkDiagnostics();
|
||||
if (signal.aborted) throw new AnalysisCancelledError(operation);
|
||||
} catch (cause: unknown) {
|
||||
failure = cause;
|
||||
}
|
||||
const stopped = await supervisor.stop();
|
||||
const snapshot = supervisor.snapshot();
|
||||
supervisor.dispose();
|
||||
if (stopped.status === "incomplete")
|
||||
if (stopped.status === "incomplete") {
|
||||
context.retainCleanup(supervisor);
|
||||
throw new ProviderCleanupError(engine, [runId, context.cwd], {
|
||||
reason: stopped.reason,
|
||||
leader_pid: spawned.ownership.leaderPid,
|
||||
@@ -183,6 +212,7 @@ export const runFirmwareCommand = async (context: {
|
||||
stderr_bytes: snapshot.stderr.bytes,
|
||||
previous_error: failure instanceof Error ? failure.message : null,
|
||||
});
|
||||
}
|
||||
if (failure !== undefined) throw failure;
|
||||
if (
|
||||
snapshot.exitCode !== 0 &&
|
||||
|
||||
@@ -3,8 +3,8 @@ import { constants, createReadStream, createWriteStream } from "node:fs";
|
||||
import {
|
||||
chmod,
|
||||
lstat,
|
||||
opendir,
|
||||
open,
|
||||
readdir,
|
||||
readlink,
|
||||
realpath,
|
||||
} from "node:fs/promises";
|
||||
@@ -29,6 +29,13 @@ export interface FirmwareEntry {
|
||||
readonly linkTarget: string | null;
|
||||
}
|
||||
|
||||
const throwIfFirmwareInventoryCancelled = (
|
||||
signal: AbortSignal | undefined,
|
||||
operation: string,
|
||||
): void => {
|
||||
if (signal?.aborted === true) throw new AnalysisCancelledError(operation);
|
||||
};
|
||||
|
||||
/** Hash a regular tool or extracted file without retaining its bytes in memory. */
|
||||
export const hashFirmwareFile = async (
|
||||
path: string,
|
||||
@@ -184,7 +191,7 @@ export const inventoryFirmwareOutput = async (
|
||||
let bytes = 0;
|
||||
let count = 0;
|
||||
while (pending.length > 0) {
|
||||
if (signal?.aborted === true) throw new AnalysisCancelledError(operation);
|
||||
throwIfFirmwareInventoryCancelled(signal, operation);
|
||||
const directory = pending.pop();
|
||||
if (directory === undefined) break;
|
||||
const directoryStat = await lstat(directory).catch((cause: unknown) => {
|
||||
@@ -198,18 +205,28 @@ export const inventoryFirmwareOutput = async (
|
||||
directoryStat.isSymbolicLink()
|
||||
)
|
||||
continue;
|
||||
const names = await readdir(directory).catch((cause: unknown) => {
|
||||
const handle = await opendir(directory).catch((cause: unknown) => {
|
||||
if (cause instanceof Error && "code" in cause && cause.code === "ENOENT")
|
||||
return [];
|
||||
return undefined;
|
||||
throw cause;
|
||||
});
|
||||
if (handle === undefined) continue;
|
||||
const names: string[] = [];
|
||||
try {
|
||||
for await (const entry of handle) {
|
||||
throwIfFirmwareInventoryCancelled(signal, operation);
|
||||
count++;
|
||||
if (count > maxEntries)
|
||||
throw new AnalysisOutputError(
|
||||
operation,
|
||||
`Staging entry budget exceeded (${maxEntries})`,
|
||||
);
|
||||
names.push(entry.name);
|
||||
}
|
||||
} finally {
|
||||
await handle.close().catch(() => undefined);
|
||||
}
|
||||
for (const name of names.sort()) {
|
||||
count++;
|
||||
if (count > maxEntries)
|
||||
throw new AnalysisOutputError(
|
||||
operation,
|
||||
`Staging entry budget exceeded (${maxEntries})`,
|
||||
);
|
||||
const path = join(directory, name);
|
||||
const stat = await lstat(path).catch((cause: unknown) => {
|
||||
if (
|
||||
|
||||
@@ -20,6 +20,7 @@ import { ProviderAdapterError } from "../domain/providerAdapterError.js";
|
||||
import { ProviderCleanupError } from "../domain/providerCleanupError.js";
|
||||
import { err, ok } from "../domain/result.js";
|
||||
import { PrivateRuntimeRoot } from "../process/PrivateRuntimeRoot.js";
|
||||
import type { ProviderProcessSupervisor } from "../process/ProviderProcess.js";
|
||||
import { publishFirmwareExtraction } from "./FirmwarePublication.js";
|
||||
import {
|
||||
FIRMWARE_LIMITS,
|
||||
@@ -65,6 +66,15 @@ const limitations = [
|
||||
/** Queued bring-your-own firmware adapters with private snapshots and owned cleanup. */
|
||||
export class FirmwareProvider implements FirmwareAnalysisPort {
|
||||
#tail: Promise<void> = Promise.resolve();
|
||||
#closed = false;
|
||||
#pendingCleanup:
|
||||
| {
|
||||
supervisor?: ProviderProcessSupervisor;
|
||||
root: PrivateRuntimeRoot;
|
||||
engine: string;
|
||||
operation: string;
|
||||
}
|
||||
| undefined;
|
||||
constructor(
|
||||
readonly environment: Readonly<
|
||||
Record<string, string | undefined>
|
||||
@@ -77,6 +87,7 @@ export class FirmwareProvider implements FirmwareAnalysisPort {
|
||||
request: FirmwareRequest,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Outcome> {
|
||||
if (this.#closed) return err(new AnalysisCancelledError(request.operation));
|
||||
const predecessor = this.#tail;
|
||||
let release = () => {};
|
||||
this.#tail = new Promise<void>((resolve) => {
|
||||
@@ -94,12 +105,57 @@ export class FirmwareProvider implements FirmwareAnalysisPort {
|
||||
);
|
||||
}
|
||||
try {
|
||||
if (this.#closed)
|
||||
return err(new AnalysisCancelledError(request.operation));
|
||||
try {
|
||||
await this.#retryCleanup();
|
||||
} catch (cause: unknown) {
|
||||
return err(
|
||||
cause instanceof AnalysisError
|
||||
? cause
|
||||
: new ProviderCleanupError("firmware", [], {
|
||||
reason: cause instanceof Error ? cause.message : String(cause),
|
||||
}),
|
||||
);
|
||||
}
|
||||
return await this.#execute(request, options);
|
||||
} finally {
|
||||
release();
|
||||
}
|
||||
}
|
||||
|
||||
/** Retry identity-bound cleanup before relinquishing private workspaces. */
|
||||
async close(): Promise<void> {
|
||||
this.#closed = true;
|
||||
await this.#tail;
|
||||
await this.#retryCleanup();
|
||||
}
|
||||
|
||||
async #retryCleanup(): Promise<void> {
|
||||
const pending = this.#pendingCleanup;
|
||||
if (pending === undefined) return;
|
||||
const stopped = await pending.supervisor?.stop();
|
||||
if (stopped?.status === "incomplete")
|
||||
throw new ProviderCleanupError(
|
||||
pending.engine,
|
||||
[pending.root.path],
|
||||
{ reason: stopped.reason },
|
||||
{ operation: pending.operation },
|
||||
);
|
||||
delete pending.supervisor;
|
||||
try {
|
||||
await pending.root.close();
|
||||
} catch (cause: unknown) {
|
||||
throw new ProviderCleanupError(
|
||||
pending.engine,
|
||||
[pending.root.path],
|
||||
{ reason: cause instanceof Error ? cause.message : String(cause) },
|
||||
{ operation: pending.operation, cause },
|
||||
);
|
||||
}
|
||||
this.#pendingCleanup = undefined;
|
||||
}
|
||||
|
||||
async #execute(
|
||||
request: FirmwareRequest,
|
||||
options?: ExecutionOptions,
|
||||
@@ -121,6 +177,7 @@ export class FirmwareProvider implements FirmwareAnalysisPort {
|
||||
request.operation,
|
||||
);
|
||||
root = await PrivateRuntimeRoot.create({ prefix: "rea-firmware-" });
|
||||
const ownedRoot = root;
|
||||
const target = await snapshotFirmware(request, root.path, signal);
|
||||
const run = (
|
||||
args: readonly string[],
|
||||
@@ -134,6 +191,14 @@ export class FirmwareProvider implements FirmwareAnalysisPort {
|
||||
cwd: root?.path ?? "",
|
||||
environment: this.environment,
|
||||
signal,
|
||||
retainCleanup: (supervisor) => {
|
||||
this.#pendingCleanup = {
|
||||
supervisor,
|
||||
root: ownedRoot,
|
||||
engine: engineName,
|
||||
operation: request.operation,
|
||||
};
|
||||
},
|
||||
...(this.launcher === undefined ? {} : { launcher: this.launcher }),
|
||||
...(outputBudget === undefined
|
||||
? {}
|
||||
@@ -315,10 +380,19 @@ export class FirmwareProvider implements FirmwareAnalysisPort {
|
||||
}),
|
||||
);
|
||||
}
|
||||
// Never remove a workspace while process ownership remains uncertain.
|
||||
// A leaked root stays recorded on this result and is not deleted. The next
|
||||
// operation may create a new root; this failure is not replayed for it.
|
||||
return finishFirmwareWorkspace(root, outcome, engineName, request);
|
||||
const finished = await finishFirmwareWorkspace(
|
||||
root,
|
||||
outcome,
|
||||
engineName,
|
||||
request,
|
||||
);
|
||||
if (!finished.ok && finished.error.cleanupIncomplete && root !== undefined)
|
||||
this.#pendingCleanup ??= {
|
||||
root,
|
||||
engine: engineName,
|
||||
operation: request.operation,
|
||||
};
|
||||
return finished;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -29,6 +29,7 @@ export const UNBLOB_PROVIDER_IDENTITY = {
|
||||
export const FIRMWARE_LIMITS = {
|
||||
inputBytes: 128 * 1024 * 1024,
|
||||
reportBytes: 8 * 1024 * 1024,
|
||||
diagnosticBytes: 8 * 1024 * 1024,
|
||||
addressSpaceBytes: 1024 * 1024 * 1024,
|
||||
timeoutMs: 120_000,
|
||||
} as const;
|
||||
|
||||
Reference in New Issue
Block a user