Files
reverse-engineering-anything/src/process/OwnedWorkerRuntime.test.ts
T
548fc2c811 fix(process): settle worker, scope, and capture retries against close (#14779)
* fix(process): settle worker, scope, and capture retries against close

- Return before posting a regex job that was cancelled before dispatch, and
  report a stop failure even when the match itself succeeded.
- Keep a worker runtime closed when start races a cleanup retry, and let
  sibling retries wait instead of reporting runtime_closing.
- Ignore owners a concurrent release settled while a scope drained.
- Check scope closure before waiting on a drain, and send SIGKILL once.
- Share one ASAR snapshot open across concurrent readers so a cancelled
  reader cannot close a peer's descriptor.
- Keep a verified staged-output identity across close retries, and stop the
  stdio transport from counting or reading after close or repeating its
  input end and onclose on retry.
- Clear a file deadline's timer when it ends.

* fix(artifacts): close a cancelled ASAR snapshot handle before publishing it

Snapshot acquisition is already serialized by the operation queue. The shared
open published the descriptor and then returned cancellation without closing
it, so the boundary test still saw a live fd. Close that handle before it is
published and drop the duplicate waiter state.

* fix(process): end the capture wait when a direct SIGKILL throws

The direct kill paths recorded killSent and then called unobservedExit, which
returned while finalization had not started. Settle that wait as unobserved
with the initiating reason and no exit code or finalization record, including
the zero-interval deadline path.

* fix(process): notify stdio close once after a natural server exit

Exit and output-close called onclose without the close flag, so a later
close() sent it again. Route exit, output close, and explicit close through
one notifier.

* test(process): cover post-acquisition abort and drain-time release

Abort after an idle worker is acquired and before dispatch, and fail a scope
owner during drain before a concurrent release succeeds. Those are the paths
the close-against-retry fixes change.

* fix(domain): remember sealed JSON identities weakly

The per-call completed set retained every finished row, so sealing an
object-heavy Evidence tree exceeded the ancestry budget. A WeakSet still
seals a shared subtree once, and the strong set stays the active ancestry.

* test(resources): release the drain gate if an assertion fails

The drain regression held owner2 until after its assertions. A failed
barrier left close waiting. Release the gate and join close in finally.

Co-authored-by: morluto <morluto@users.noreply.github.com>

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: morluto <morluto@users.noreply.github.com>
2026-11-26 18:19:27 +00:00

424 lines
14 KiB
TypeScript

import { access } from "node:fs/promises";
import { randomUUID } from "node:crypto";
import { expect, it, vi } from "vitest";
import { withVerifierCleanup } from "../../scripts/lib/verifier-cleanup.mjs";
import { phaseGate } from "../../tests/support/lifecycleHarness.js";
import { ProviderCleanupError } from "../domain/providerCleanupError.js";
import { cleanupOwnedProcessGroup } from "./ProcessOwnership.js";
import {
OwnedWorkerRuntime,
OwnedWorkerRuntimeCleanupError,
type OwnedWorkerRuntimeOptions,
} from "./OwnedWorkerRuntime.js";
import {
spawnOwnedProviderProcess,
type ProviderProcessSupervisor,
} from "./ProviderProcess.js";
const runtimeOptions = (
overrides: Partial<OwnedWorkerRuntimeOptions> = {},
): OwnedWorkerRuntimeOptions => ({
rootPrefix: "rea-owned-worker-test-",
...overrides,
});
const startOptions = () => ({
command: process.execPath,
arguments: ["-e", "process.stdin.resume(); setInterval(() => {}, 1000);"],
runId: `rea-owned-worker-test-${randomUUID()}`,
stdin: "pipe" as const,
});
it("waits for an admitted late handshake before closing its process and root", async () => {
const runtime = new OwnedWorkerRuntime(runtimeOptions());
const initialization = phaseGate<ProviderProcessSupervisor>();
const starting = runtime.start(startOptions(), initialization.hold);
let closing: Promise<void> | undefined;
await withVerifierCleanup(async () => {
const supervisor = await initialization.reached(
starting,
"worker initialization",
);
const rootPath = runtime.rootPath;
if (rootPath === undefined) throw new Error("Worker root was not admitted");
const stop = vi.spyOn(supervisor, "stop");
closing = runtime.close();
await new Promise<void>((resolve) => setImmediate(resolve));
expect(stop).not.toHaveBeenCalled();
await access(rootPath);
initialization.release();
await expect(starting).rejects.toThrow("closing");
await closing;
expect(stop).toHaveBeenCalledTimes(1);
expect(runtime.supervisor).toBeUndefined();
expect(runtime.rootPath).toBeUndefined();
await expect(access(rootPath)).rejects.toThrow();
}, [
initialization.release,
async () => {
await starting.catch(() => undefined);
},
async () => {
await closing;
},
() => runtime.close(),
]);
});
it("resolves a bound cleanup error after shared pending-owner retry succeeds", async () => {
let failCleanup = true;
const runtime = new OwnedWorkerRuntime(
runtimeOptions({
launcher: async (options) => {
const spawned = await spawnOwnedProviderProcess(options);
return {
...spawned,
cleanup: async () => {
if (failCleanup) {
failCleanup = false;
return { cleaned: false, reason: "controlled cleanup retry" };
}
return spawned.cleanup === undefined
? cleanupOwnedProcessGroup(spawned.ownership)
: spawned.cleanup();
},
};
},
}),
);
await withVerifierCleanup(async () => {
await runtime.start(startOptions());
const rootPath = runtime.rootPath;
const error = new ProviderCleanupError("owned-worker-test", [], {
reason: "controlled cleanup retry",
});
await expect(runtime.stop()).resolves.toMatchObject({
status: "incomplete",
});
runtime.bindCleanupFailure(error);
expect(error.cleanupIncomplete).toBe(true);
expect(error.cleanupResources).toContain(rootPath);
await OwnedWorkerRuntime.retryPending();
expect(error.cleanupIncomplete).toBe(false);
expect(error.cleanupResources).toEqual([]);
expect(runtime.rootPath).toBeUndefined();
await expect(access(rootPath as string)).rejects.toThrow();
}, [
() => {
failCleanup = false;
},
() => runtime.close(),
]);
});
it("observes request-stream errors and resets them for a fresh child", async () => {
const runtime = new OwnedWorkerRuntime(runtimeOptions());
try {
await runtime.start(startOptions());
const stdin = runtime.supervisor?.launch.process.stdin;
expect(stdin).toBeDefined();
const failure = new Error("controlled request pipe failure");
stdin?.emit("error", failure);
expect(runtime.inputFailure).toBe(failure);
const stopped = await runtime.stop();
expect(stopped.status).not.toBe("incomplete");
await runtime.start(startOptions());
expect(runtime.inputFailure).toBeUndefined();
} finally {
await runtime.close();
}
});
it("retains pending ownership when best-effort stdin.end throws after an incomplete stop", async () => {
let failCleanup = true;
const runtime = new OwnedWorkerRuntime(
runtimeOptions({
launcher: async (options) => {
const spawned = await spawnOwnedProviderProcess(options);
return {
...spawned,
cleanup: async () => {
if (failCleanup)
return { cleaned: false, reason: "controlled incomplete stop" };
return spawned.cleanup === undefined
? cleanupOwnedProcessGroup(spawned.ownership)
: spawned.cleanup();
},
};
},
}),
);
await runtime.start(startOptions());
const rootPath = runtime.rootPath;
const stdin = runtime.supervisor?.launch.process.stdin;
if (stdin === undefined || stdin === null)
throw new Error("Owned child request stream is unavailable");
const originalEnd = stdin.end.bind(stdin);
Object.defineProperty(stdin, "end", {
configurable: true,
value: () => {
throw new Error("controlled stdin.end failure");
},
});
try {
await expect(runtime.stop()).resolves.toMatchObject({
status: "incomplete",
});
expect(runtime.hasPendingCleanup).toBe(true);
failCleanup = false;
Object.defineProperty(stdin, "end", {
configurable: true,
value: originalEnd,
});
await OwnedWorkerRuntime.retryPending();
expect(runtime.hasPendingCleanup).toBe(false);
expect(runtime.rootPath).toBeUndefined();
await expect(access(rootPath as string)).rejects.toThrow();
} finally {
Object.defineProperty(stdin, "end", {
configurable: true,
value: originalEnd,
});
failCleanup = false;
await runtime.close();
}
});
it("binds a late cleanup projection to its released root epoch after runtime reuse", async () => {
let failCleanup = true;
const runtime = new OwnedWorkerRuntime(
runtimeOptions({
launcher: async (options) => {
const spawned = await spawnOwnedProviderProcess(options);
return {
...spawned,
cleanup: async () => {
if (failCleanup)
return { cleaned: false, reason: "controlled old-epoch cleanup" };
return spawned.cleanup === undefined
? cleanupOwnedProcessGroup(spawned.ownership)
: spawned.cleanup();
},
};
},
}),
);
let oldCleanupError: OwnedWorkerRuntimeCleanupError | undefined;
try {
await runtime.start(startOptions());
const oldRoot = runtime.rootPath;
await expect(runtime.stop()).resolves.toMatchObject({
status: "incomplete",
});
try {
await OwnedWorkerRuntime.retryPending();
throw new Error("Expected pending-owner retry to fail");
} catch (cause) {
if (!(cause instanceof OwnedWorkerRuntimeCleanupError)) throw cause;
oldCleanupError = cause;
}
if (oldCleanupError === undefined)
throw new Error("Expected an owned cleanup error from the old root");
failCleanup = false;
await OwnedWorkerRuntime.retryPending();
expect(runtime.rootPath).toBeUndefined();
await expect(access(oldRoot as string)).rejects.toThrow();
await runtime.start(startOptions());
const newRoot = runtime.rootPath;
expect(newRoot).toBeDefined();
expect(newRoot).not.toBe(oldRoot);
const lateProjection = new ProviderCleanupError(
"owned-worker-test",
oldCleanupError.cleanupResources,
{ reason: oldCleanupError.message },
);
oldCleanupError.bindCleanupFailure(lateProjection);
expect(lateProjection.cleanupIncomplete).toBe(false);
expect(lateProjection.cleanupResources).toEqual([]);
expect(runtime.rootPath).toBe(newRoot);
expect(runtime.supervisor).toBeDefined();
} finally {
failCleanup = false;
await runtime.close();
}
});
it("routes shared cleanup retry through the registered higher-level owner", async () => {
let failCleanup = true;
let allowOwnerClose = false;
let delegateCalls = 0;
let runtime: OwnedWorkerRuntime;
runtime = new OwnedWorkerRuntime(
runtimeOptions({
launcher: async (options) => {
const spawned = await spawnOwnedProviderProcess(options);
return {
...spawned,
cleanup: async () => {
if (failCleanup)
return { cleaned: false, reason: "controlled delegated cleanup" };
return spawned.cleanup === undefined
? cleanupOwnedProcessGroup(spawned.ownership)
: spawned.cleanup();
},
};
},
retryCleanup: async () => {
delegateCalls += 1;
if (!allowOwnerClose)
throw new Error("higher-level owner still retains a descriptor");
await runtime.close();
},
}),
);
await runtime.start(startOptions());
const rootPath = runtime.rootPath;
try {
await expect(runtime.stop()).resolves.toMatchObject({
status: "incomplete",
});
await expect(OwnedWorkerRuntime.retryPending()).rejects.toThrow(
"higher-level owner still retains a descriptor",
);
expect(delegateCalls).toBe(1);
// A retained supervisor is not permission to bypass its dependent owner.
await expect(runtime.start(startOptions())).rejects.toThrow(
"higher-level owner still retains a descriptor",
);
expect(delegateCalls).toBe(2);
expect(runtime.rootPath).toBe(rootPath);
await access(rootPath as string);
allowOwnerClose = true;
failCleanup = false;
await OwnedWorkerRuntime.retryPending();
expect(delegateCalls).toBe(3);
expect(runtime.rootPath).toBeUndefined();
await expect(access(rootPath as string)).rejects.toThrow();
} finally {
allowOwnerClose = true;
failCleanup = false;
await runtime.close();
}
});
it("runs deferred delegated cleanup before registering a pending start acquisition", async () => {
let runtime: OwnedWorkerRuntime;
let delegatedClose: Promise<void> | undefined;
let delegateTimedOut = false;
runtime = new OwnedWorkerRuntime(
runtimeOptions({
retryCleanup: async () => {
await new Promise<void>((resolve) => setImmediate(resolve));
delegatedClose = runtime.close();
let timer: NodeJS.Timeout | undefined;
const outcome = await Promise.race([
delegatedClose.then(() => "closed" as const),
new Promise<"timeout">((resolve) => {
timer = setTimeout(() => resolve("timeout"), 250);
}),
]);
if (timer !== undefined) clearTimeout(timer);
delegateTimedOut = outcome === "timeout";
},
}),
);
try {
await runtime.start(startOptions());
const stopped = await runtime.stop();
expect(stopped.status).not.toBe("incomplete");
runtime.retainForCleanup();
await expect(runtime.start(startOptions())).rejects.toMatchObject({
_tag: "ProcessAdmissionError",
code: "runtime_closing",
});
expect(delegateTimedOut).toBe(false);
await delegatedClose;
expect(runtime.rootPath).toBeUndefined();
} finally {
await runtime.close();
}
});
it("keeps terminal close intact when close() races start() during pending cleanup retry", async () => {
let failCleanup = true;
const runtime = new OwnedWorkerRuntime(
runtimeOptions({
launcher: async (options) => {
const spawned = await spawnOwnedProviderProcess(options);
return {
...spawned,
cleanup: async () => {
if (failCleanup) return { cleaned: false, reason: "held cleanup" };
return spawned.cleanup === undefined
? cleanupOwnedProcessGroup(spawned.ownership)
: spawned.cleanup();
},
};
},
}),
);
await runtime.start(startOptions());
expect(await runtime.stop()).toMatchObject({ status: "incomplete" });
expect(runtime.hasPendingCleanup).toBe(true);
failCleanup = false;
const restarting = runtime.start(startOptions());
const closing = runtime.close();
await closing;
await expect(restarting).rejects.toMatchObject({
_tag: "ProcessAdmissionError",
code: "runtime_closing",
});
expect(runtime.hasPendingCleanup).toBe(false);
expect(runtime.rootPath).toBeUndefined();
});
it("allows concurrent start() to wait for cohort cleanup retry without failing as runtime_closing", async () => {
let failCleanup = true;
const cleanupGate = phaseGate();
const runtime = new OwnedWorkerRuntime(
runtimeOptions({
launcher: async (options) => {
const spawned = await spawnOwnedProviderProcess(options);
return {
...spawned,
cleanup: async () => {
if (failCleanup) return { cleaned: false, reason: "held cleanup" };
await cleanupGate.hold();
return spawned.cleanup === undefined
? cleanupOwnedProcessGroup(spawned.ownership)
: spawned.cleanup();
},
};
},
}),
);
try {
await runtime.start(startOptions());
expect(await runtime.stop()).toMatchObject({ status: "incomplete" });
failCleanup = false;
const cohortRetry = runtime.retryCohort();
await cleanupGate.reached(cohortRetry, "cohort cleanup hold");
const starting = runtime.start(startOptions());
cleanupGate.release();
await cohortRetry;
await expect(starting).resolves.toBeUndefined();
} finally {
cleanupGate.release();
await runtime.close();
}
});