Skip to content

Commit 6b1eaca

Browse files
authored
fix(process): settle disconnected workers after pipe closure (#132447)
* fix(process): settle disconnected workers after pipe closure * test: extract child adapter fixtures and preserve readonly state * test: extract media migration snapshot fixture * test: evict worker credentials before output without sleeps
1 parent 0120dac commit 6b1eaca

5 files changed

Lines changed: 393 additions & 176 deletions

File tree

‎src/node-host/node-worker-supervisor.test-support.ts‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -157,7 +157,6 @@ if (mode === "admission-rearm") {
157157
} else if (mode === "quiet-fail") {
158158
exitWorker(7);
159159
} else if (mode === "secret-fail") {
160-
await new Promise((resolve) => setTimeout(resolve, 500));
161160
const credential = descriptor.admission.credential;
162161
const escaped = JSON.stringify(credential).slice(1, -1);
163162
process.stderr.write(
@@ -176,7 +175,6 @@ if (mode === "admission-rearm") {
176175
process.stderr.write("x".repeat(5000) + representation + "y".repeat(suffixBytes));
177176
exitWorker(7);
178177
} else if (mode === "secret-success") {
179-
await new Promise((resolve) => setTimeout(resolve, 500));
180178
const credential = descriptor.admission.credential;
181179
finish(descriptor, {
182180
...completedResult,

‎src/node-host/node-worker-supervisor.test.ts‎

Lines changed: 72 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,9 @@ import { afterEach, describe, expect, it, vi } from "vitest";
66
import { useAutoCleanupTempDirTracker } from "../../test/helpers/temp-dir.js";
77
import { NODE_WORKER_CAPACITY_EXHAUSTED_ERROR_CODE } from "../infra/node-commands.js";
88
import { NODE_WORKER_CAPACITY_MAX } from "../infra/node-runner-inventory.js";
9-
import { registerSecretValueForRedaction } from "../logging/secret-redaction-registry.js";
9+
import * as secretRegistry from "../logging/secret-redaction-registry.js";
1010
import { resetSecretRedactionRegistryForTest } from "../logging/secret-redaction-registry.test-support.js";
11+
import * as processTree from "../process/kill-tree.js";
1112
import {
1213
closeOpenClawStateDatabaseForTest,
1314
openOpenClawStateDatabase,
@@ -55,6 +56,19 @@ function launchInput(workspaceDir: string, launchId: string, prompt = "success")
5556
return input;
5657
}
5758

59+
function evictWorkerCredentialsOnRegistration() {
60+
const { registerSecretValueForRedaction } = secretRegistry;
61+
// Both launch paths register before sending a turn. Evict every registration so a
62+
// later launch cannot restore the global secret and hide a missing worker scrubber.
63+
return vi.spyOn(secretRegistry, "registerSecretValueForRedaction").mockImplementation((value) => {
64+
registerSecretValueForRedaction(value);
65+
for (let index = 0; index < 600; index += 1) {
66+
registerSecretValueForRedaction(`eviction-secret-${index}`);
67+
}
68+
expect(secretRegistry.isSecretValueRegisteredForRedaction(value)).toBe(false);
69+
});
70+
}
71+
5872
describe("node worker supervisor", () => {
5973
it.each([
6074
{ availableParallelism: 0, expected: 1 },
@@ -531,12 +545,12 @@ describe("node worker supervisor", () => {
531545
const failureInput = launchInput(workspaceDir, "failure-launch", "secret-fail");
532546
const overflowInput = launchInput(workspaceDir, "overflow-launch", "overflow");
533547

548+
const registrations = evictWorkerCredentialsOnRegistration();
534549
await supervisor.launch(successInput, TEST_WORKER_ENDPOINT);
535550
await supervisor.launch(failureInput, TEST_WORKER_ENDPOINT);
536551
await supervisor.launch(overflowInput, TEST_WORKER_ENDPOINT);
537-
for (let index = 0; index < 600; index += 1) {
538-
registerSecretValueForRedaction(`eviction-secret-${index}`);
539-
}
552+
expect(registrations).toHaveBeenCalledTimes(3);
553+
expect(registrations).toHaveBeenCalledWith(TEST_WORKER_CREDENTIAL);
540554
const success = await waitForTerminal(supervisor, successInput.launchId);
541555
const failure = await waitForTerminal(supervisor, failureInput.launchId);
542556
const overflow = await waitForTerminal(supervisor, overflowInput.launchId);
@@ -595,19 +609,19 @@ describe("node worker supervisor", () => {
595609
try {
596610
const original = await supervisor.launch(first, TEST_WORKER_ENDPOINT);
597611
await waitForTerminal(supervisor, first.launchId);
612+
const registrations = evictWorkerCredentialsOnRegistration();
598613
expect(await supervisor.launch(second, TEST_WORKER_ENDPOINT)).toMatchObject({
599614
worker: original.worker,
600615
});
601-
for (let index = 0; index < 600; index += 1) {
602-
registerSecretValueForRedaction(`rotated-eviction-secret-${index}`);
603-
}
616+
expect(registrations).toHaveBeenCalledWith(second.descriptor.admission.credential);
604617
const completed = await waitForTerminal(supervisor, second.launchId);
605618
expect(JSON.parse(completed.resultJson ?? "null")).toEqual({
606619
status: "completed",
607620
transcriptLeafId: "raw [REDACTED] encoded [REDACTED]",
608621
transcriptNextSeq: 2,
609622
});
610623

624+
registrations.mockRestore();
611625
await supervisor.launch(last, TEST_WORKER_ENDPOINT);
612626
const failed = await waitForTerminal(supervisor, last.launchId);
613627
expect(failed).toMatchObject({
@@ -623,10 +637,21 @@ describe("node worker supervisor", () => {
623637
});
624638

625639
it("does not open or signal a child after markRunning observes its terminal receipt", async () => {
626-
const { supervisor, workspaceDir } = fixture();
640+
const capacities: Array<{ total: number; available: number }> = [];
641+
const { supervisor, workspaceDir, env } = fixture({
642+
capacity: 1,
643+
onCapacityChanged: (capacity) => capacities.push(capacity),
644+
});
627645
const input = launchInput(workspaceDir, "fast-terminal-launch", "fast-terminal");
646+
const captureSpawn = vi.spyOn(childProcess.ChildProcess.prototype, "emit");
647+
const signalTree = vi.spyOn(processTree, "signalProcessTree");
648+
let child: ChildProcess | undefined;
628649
vi.spyOn(NodeWorkerLaunchStore.prototype, "markRunning").mockImplementation(
629650
function (this: NodeWorkerLaunchStore, params) {
651+
child = captureSpawn.mock.contexts.find(
652+
(context): context is ChildProcess =>
653+
context instanceof childProcess.ChildProcess && context.pid === params.worker.pid,
654+
);
630655
return this.finish({
631656
launchId: params.launchId,
632657
planHash: params.planHash,
@@ -638,15 +663,25 @@ describe("node worker supervisor", () => {
638663
},
639664
);
640665

641-
expect(await supervisor.launch(input, TEST_WORKER_ENDPOINT)).toMatchObject({
642-
state: "completed",
643-
});
644-
const marker = path.join(workspaceDir, "fast-terminal-marker");
645-
await new Promise((resolve) => {
646-
setTimeout(resolve, 150);
647-
});
648-
expect(fs.existsSync(marker)).toBe(false);
649-
await supervisor.close();
666+
try {
667+
expect(await supervisor.launch(input, TEST_WORKER_ENDPOINT)).toMatchObject({
668+
state: "completed",
669+
});
670+
// Capacity returns only after the real child exit and adapter settlement.
671+
await vi.waitFor(() => expect(capacities.at(-1)).toEqual({ total: 1, available: 1 }), {
672+
timeout: 5_000,
673+
});
674+
expect(child?.exitCode).toBe(0);
675+
expect(child?.signalCode).toBeNull();
676+
expect(child?.stdout?.closed).toBe(true);
677+
expect(child?.stderr?.closed).toBe(true);
678+
expect(fs.existsSync(path.join(workspaceDir, "fast-terminal-marker"))).toBe(false);
679+
expect(new NodeWorkerLaunchStore({ env }).get(input.launchId)?.state).toBe("completed");
680+
await supervisor.close();
681+
expect(signalTree).not.toHaveBeenCalled();
682+
} finally {
683+
await supervisor.close();
684+
}
650685
});
651686

652687
it("records a gated child that exits before journal readiness as terminal", async () => {
@@ -682,6 +717,7 @@ describe("node worker supervisor", () => {
682717
const input = launchInput(workspaceDir, "blocked-cancel", "wait");
683718
const sibling = launchInput(workspaceDir, "unrelated-worker", "wait");
684719
const captureSpawn = vi.spyOn(childProcess.ChildProcess.prototype, "emit");
720+
const signalTree = vi.spyOn(processTree, "signalProcessTree");
685721
let heldWrite: { data: unknown; callback?: (error?: Error | null) => void } | undefined;
686722
let restoreWrite: (() => void) | undefined;
687723
let cancellation: ReturnType<NodeWorkerSupervisor["cancel"]> | undefined;
@@ -704,17 +740,29 @@ describe("node worker supervisor", () => {
704740
return false;
705741
});
706742
restoreWrite = () => write.mockRestore();
743+
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
707744
cancellation = supervisor.cancel(testNodeWorkerLaunchIdentity(input)).then((receipt) => {
708745
cancelled = receipt;
709746
return receipt;
710747
});
711-
await vi.waitFor(() => {
712-
expect(heldWrite?.data).toBe(
713-
`${JSON.stringify({ type: "cancel", turnId: input.launchId })}\n`,
714-
);
715-
expect(heldWrite?.callback).toEqual(expect.any(Function));
716-
});
748+
await vi.advanceTimersByTimeAsync(0);
749+
expect(heldWrite?.data).toBe(
750+
`${JSON.stringify({ type: "cancel", turnId: input.launchId })}\n`,
751+
);
752+
expect(heldWrite?.callback).toEqual(expect.any(Function));
753+
754+
await vi.advanceTimersByTimeAsync(4_999);
755+
expect(signalTree).not.toHaveBeenCalled();
756+
expect(cancelled).toBeUndefined();
757+
expect(new NodeWorkerLaunchStore({ env }).get(input.launchId)?.state).toBe("running");
758+
expect(inspectNodeWorkerProcessIdentity(running.worker!)).toBe("live");
759+
expect(inspectNodeWorkerProcessIdentity(unrelated.worker!)).toBe("live");
760+
expect(capacities.at(-1)).toEqual({ total: 2, available: 0 });
717761

762+
// Fire only the blocked-write deadline. Restore real timers before its
763+
// rejection continuation schedules process termination and escalation.
764+
vi.advanceTimersByTime(1);
765+
vi.useRealTimers();
718766
await vi.waitFor(
719767
() => {
720768
expect(cancelled).toMatchObject({ state: "cancelled", worker: running.worker });
@@ -733,6 +781,7 @@ describe("node worker supervisor", () => {
733781
),
734782
).resolves.toMatchObject({ state: "running" });
735783
} finally {
784+
vi.useRealTimers();
736785
captureSpawn.mockRestore();
737786
restoreWrite?.();
738787
// Release the injected write even on the pre-fix failure, so cleanup cannot inherit its hang.
Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
import type { ChildProcess } from "node:child_process";
2+
import { EventEmitter } from "node:events";
3+
import { mkdir, writeFile } from "node:fs/promises";
4+
import path from "node:path";
5+
import { PassThrough } from "node:stream";
6+
import { vi, type Mock } from "vitest";
7+
8+
export function createStubChild(pid = 1234) {
9+
const child = new EventEmitter() as ChildProcess;
10+
child.stdin = new PassThrough() as ChildProcess["stdin"];
11+
child.stdout = new PassThrough() as ChildProcess["stdout"];
12+
child.stderr = new PassThrough() as ChildProcess["stderr"];
13+
Object.defineProperty(child, "stdio", {
14+
value: [child.stdin, child.stdout, child.stderr],
15+
configurable: true,
16+
});
17+
Object.defineProperty(child, "pid", { value: pid, configurable: true });
18+
Object.defineProperty(child, "killed", { value: false, configurable: true, writable: true });
19+
Object.defineProperty(child, "exitCode", { value: null, configurable: true, writable: true });
20+
Object.defineProperty(child, "signalCode", { value: null, configurable: true, writable: true });
21+
Object.defineProperty(child, "channel", { value: {}, configurable: true });
22+
Object.defineProperty(child, "connected", { value: true, configurable: true, writable: true });
23+
const killMock = vi.fn(() => true);
24+
const sendMock = vi.fn((_message: unknown, ...args: unknown[]) => {
25+
const callback = args.findLast((value) => typeof value === "function") as
26+
| ((error: Error | null) => void)
27+
| undefined;
28+
callback?.(null);
29+
return true;
30+
});
31+
const disconnectMock = vi.fn(() => {
32+
Object.defineProperty(child, "connected", { value: false, configurable: true, writable: true });
33+
child.emit("disconnect");
34+
});
35+
child.kill = killMock as ChildProcess["kill"];
36+
child.send = sendMock as ChildProcess["send"];
37+
child.disconnect = disconnectMock as ChildProcess["disconnect"];
38+
const emitClose = (code: number | null, signal: NodeJS.Signals | null = null) => {
39+
child.emit("close", code, signal);
40+
};
41+
const emitExit = (code: number | null, signal: NodeJS.Signals | null = null) => {
42+
Object.defineProperty(child, "exitCode", { value: code, configurable: true, writable: true });
43+
Object.defineProperty(child, "signalCode", {
44+
value: signal,
45+
configurable: true,
46+
writable: true,
47+
});
48+
child.emit("exit", code, signal);
49+
};
50+
return { child, disconnectMock, killMock, sendMock, emitClose, emitExit };
51+
}
52+
53+
type SpawnWithFallbackParams = {
54+
argv?: string[];
55+
options?: {
56+
detached?: boolean;
57+
env?: NodeJS.ProcessEnv | Record<string, string>;
58+
stdio?: string[];
59+
windowsHide?: boolean;
60+
windowsVerbatimArguments?: boolean;
61+
};
62+
fallbacks?: Array<{ options?: { detached?: boolean } }>;
63+
};
64+
65+
export function firstSpawnWithFallbackParams(mock: Mock): SpawnWithFallbackParams {
66+
const [call] = mock.mock.calls;
67+
if (!call) {
68+
throw new Error("expected spawnWithFallback call");
69+
}
70+
const [params] = call;
71+
if (typeof params !== "object" || params === null || Array.isArray(params)) {
72+
throw new Error("expected spawnWithFallback params to be an object");
73+
}
74+
return params;
75+
}
76+
77+
export function firstMockArg(
78+
mock: { mock: { calls: readonly unknown[][] } },
79+
label: string,
80+
): unknown {
81+
const [call] = mock.mock.calls;
82+
if (!call) {
83+
throw new Error(`expected ${label} call`);
84+
}
85+
return call[0];
86+
}
87+
88+
export async function createWindowsNpmShim(params: {
89+
binDir: string;
90+
command: string;
91+
packagePath: string[];
92+
}) {
93+
const { binDir } = params;
94+
const entrypoint = path.join(binDir, "node_modules", ...params.packagePath);
95+
await mkdir(path.dirname(entrypoint), { recursive: true });
96+
await writeFile(entrypoint, "", "utf8");
97+
const relativeEntrypoint = path.relative(binDir, entrypoint).replaceAll(path.sep, "\\");
98+
const shimHead =
99+
"@ECHO off\r\nGOTO start\r\n:find_dp0\r\nSET dp0=%~dp0\r\nEXIT /b\r\n:start\r\nSETLOCAL\r\nCALL :find_dp0\r\n";
100+
const shimCommand = entrypoint.endsWith(".exe")
101+
? `"%dp0%\\${relativeEntrypoint}" %*\r\n`
102+
: `IF EXIST "%dp0%\\node.exe" (\r\n SET "_prog=%dp0%\\node.exe"\r\n) ELSE (\r\n SET "_prog=node"\r\n)\r\nendLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\\${relativeEntrypoint}" %*\r\n`;
103+
await writeFile(path.join(binDir, `${params.command}.cmd`), `${shimHead}${shimCommand}`, "utf8");
104+
return { binDir, entrypoint };
105+
}

0 commit comments

Comments
 (0)