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:
morluto
2026-10-11 00:03:21 +08:00
parent a01148553e
commit d1235fadc9
24 changed files with 688 additions and 120 deletions
+20 -11
View File
@@ -1,6 +1,6 @@
import { createHash } from "node:crypto";
import { constants } from "node:fs";
import { lstat, open, readdir, writeFile } from "node:fs/promises";
import { lstat, open, opendir, writeFile } from "node:fs/promises";
import { isAbsolute, join } from "node:path";
import { TextDecoder } from "node:util";
import {
@@ -138,18 +138,27 @@ export const inventoryRecoveryFiles = async (
OPERATION,
`Unsafe staging directory: ${directory}`,
);
for (const entry of await readdir(directory, { withFileTypes: true })) {
const handle = await opendir(directory);
const children: string[] = [];
try {
for await (const entry of handle) {
checkRecoveryCancellation(signal);
entries++;
if (entries > RECOVERY_LIMITS.outputEntries)
throw new AnalysisOutputError(
OPERATION,
"Recovery staging exceeds the 10000-entry resource limit",
);
children.push(entry.name);
}
} finally {
await handle.close().catch(() => undefined);
}
for (const name of children) {
checkRecoveryCancellation(signal);
entries++;
const relativePath =
prefix === "" ? entry.name : `${prefix}/${entry.name}`;
const path = join(directory, entry.name);
const relativePath = prefix === "" ? name : `${prefix}/${name}`;
const path = join(directory, name);
const info = await lstat(path);
if (entries > RECOVERY_LIMITS.outputEntries)
throw new AnalysisOutputError(
OPERATION,
"Recovery staging exceeds the 10000-entry resource limit",
);
if (info.isSymbolicLink() || (!info.isDirectory() && !info.isFile()))
throw new AnalysisOutputError(
OPERATION,
+33 -7
View File
@@ -33,6 +33,31 @@ export type WakaruLauncher = (
options: OwnedProviderProcessSpawnOptions,
) => Promise<SpawnedOwnedProviderProcess>;
/** Cleanup failure carrying the live supervisor so the provider can retry it. */
export class WakaruCleanupFailure extends ProviderCleanupError {
constructor(
readonly cleanupOwner: ProviderProcessSupervisor,
readonly runId: string,
readonly cwd: string,
reason: string,
previousError: unknown,
snapshot: ReturnType<ProviderProcessSupervisor["snapshot"]>,
) {
super(
"wakaru",
[runId, cwd],
{
reason,
previous_error:
previousError instanceof Error ? previousError.message : null,
exit_code: snapshot.exitCode ?? null,
signal: snapshot.signal ?? null,
},
{ operation: OPERATION, cause: previousError },
);
}
}
/** Resolve and fingerprint explicitly configured tools; acquire nothing at startup. */
export const resolveWakaruCommand = async (
environment: Readonly<Record<string, string | undefined>>,
@@ -158,14 +183,15 @@ export const runWakaruCommand = async (context: WakaruCommandContext) => {
}
const stopped = await supervisor.stop();
const snapshot = supervisor.snapshot();
supervisor.dispose();
if (stopped.status === "incomplete")
throw new ProviderCleanupError("wakaru", [runId, context.cwd], {
reason: stopped.reason,
previous_error: failure instanceof Error ? failure.message : null,
exit_code: snapshot.exitCode ?? null,
signal: snapshot.signal ?? null,
});
throw new WakaruCleanupFailure(
supervisor,
runId,
context.cwd,
stopped.reason,
failure,
snapshot,
);
if (failure !== undefined) throw failure;
if (context.signal?.aborted === true)
throw new AnalysisCancelledError(OPERATION);
+148 -11
View File
@@ -20,14 +20,30 @@ import {
recoveryInputFailure,
snapshotRecoveryInput,
} from "./RecoveryFiles.js";
import { resolveWakaruCommand, type WakaruLauncher } from "./WakaruCommand.js";
import {
resolveWakaruCommand,
type WakaruLauncher,
WakaruCleanupFailure,
} from "./WakaruCommand.js";
import type { ProviderProcessSupervisor } from "../../process/ProviderProcess.js";
import { prepareWakaruExecution } from "./WakaruExecution.js";
import { RECOVERY_LIMITS } from "./WakaruRelease.js";
const OPERATION = "recover_javascript_sources";
/** Stateless adapter; each recovery owns its snapshot, process and publication. */
/** Serialized recovery adapter retaining failed process, workspace and publication cleanup. */
export class WakaruProvider implements JavaScriptRecoveryPort {
#tail: Promise<void> = Promise.resolve();
#closing = false;
#closePromise: Promise<void> | undefined;
#pendingCleanup:
| {
root: string | undefined;
process: ProviderProcessSupervisor | undefined;
tree: SafeOutputTree | undefined;
}
| undefined;
constructor(
readonly environment: Readonly<
Record<string, string | undefined>
@@ -36,10 +52,46 @@ export class WakaruProvider implements JavaScriptRecoveryPort {
) {}
/** Recover one script using validated upstream reports and verified output bytes. */
async recover(
recover(
input: JavaScriptRecoveryInput,
options?: ExecutionOptions,
): Promise<Result<AnalysisExecution, AnalysisError>> {
if (this.#closing)
return Promise.resolve(
err(
new ProviderCleanupError(
"wakaru",
[],
{ reason: "Provider is closing" },
{ operation: OPERATION },
),
),
);
const operation = this.#tail.then(() =>
this.#closing
? err(
new ProviderCleanupError(
"wakaru",
[],
{ reason: "Provider is closing" },
{ operation: OPERATION },
),
)
: this.#recover(input, options),
);
this.#tail = operation.then(
() => undefined,
() => undefined,
);
return operation;
}
async #recover(
input: JavaScriptRecoveryInput,
options?: ExecutionOptions,
): Promise<Result<AnalysisExecution, AnalysisError>> {
const pending = await this.#retire();
if (pending !== undefined) return err(pending);
let root: string | undefined;
let tree: SafeOutputTree | undefined;
let failure: unknown;
@@ -88,20 +140,42 @@ export class WakaruProvider implements JavaScriptRecoveryPort {
}
if (failure !== undefined) {
const residuals: string[] = [];
const cleanupOwner =
failure instanceof WakaruCleanupFailure
? failure.cleanupOwner
: undefined;
let failedTree: SafeOutputTree | undefined;
try {
await tree?.rollback();
} catch {
if (tree !== undefined) residuals.push(tree.outputRoot);
if (tree !== undefined) {
failedTree = tree;
residuals.push(tree.outputRoot);
}
}
if (cleanupOwner !== undefined)
residuals.push(cleanupOwner.launch.ownership?.runId ?? "wakaru-worker");
if (root !== undefined && cleanupOwner === undefined) {
const failedRoot = root;
try {
await rm(failedRoot, { recursive: true, force: true });
root = undefined;
} catch {
residuals.push(failedRoot);
}
}
if (
root !== undefined &&
!(failure instanceof AnalysisError && failure.cleanupIncomplete)
cleanupOwner !== undefined ||
failedTree !== undefined ||
root !== undefined
) {
try {
await rm(root, { recursive: true, force: true });
} catch {
residuals.push(root);
}
this.#pendingCleanup = {
root,
process: cleanupOwner,
tree: failedTree,
};
if (root !== undefined) residuals.push(root);
root = undefined;
}
if (residuals.length > 0)
return err(
@@ -124,4 +198,67 @@ export class WakaruProvider implements JavaScriptRecoveryPort {
)
: ok(execution);
}
async close(): Promise<void> {
this.#closing = true;
this.#closePromise ??= this.#tail
.then(async () => {
const failure = await this.#retire();
if (failure !== undefined) throw failure;
})
.catch((cause: unknown) => {
this.#closePromise = undefined;
throw cause;
});
return this.#closePromise;
}
async #retire(): Promise<ProviderCleanupError | undefined> {
const pending = this.#pendingCleanup;
if (pending === undefined) return undefined;
if (pending.process !== undefined) {
const stopped = await pending.process.stop();
if (stopped.status === "incomplete")
return new ProviderCleanupError(
"wakaru",
[
pending.process.launch.ownership?.runId ?? "wakaru-worker",
...(pending.root === undefined ? [] : [pending.root]),
],
{ reason: stopped.reason },
{ operation: OPERATION },
);
pending.process = undefined;
}
if (pending.tree !== undefined) {
const tree = pending.tree;
try {
await tree.rollback();
pending.tree = undefined;
} catch (cause: unknown) {
return new ProviderCleanupError(
"wakaru",
[tree.outputRoot],
{ reason: recoveryFailureMessage(cause) },
{ operation: OPERATION, cause },
);
}
}
if (pending.root !== undefined) {
const root = pending.root;
try {
await rm(root, { recursive: true, force: true });
pending.root = undefined;
} catch (cause: unknown) {
return new ProviderCleanupError(
"wakaru",
[root],
{ reason: recoveryFailureMessage(cause) },
{ operation: OPERATION, cause },
);
}
}
this.#pendingCleanup = undefined;
return undefined;
}
}