Skip to content

Commit 904347d

Browse files
committed
fix(node-host): retry worker supervisor initialization
Clear failed initialization ownership for retry, retain valid container supervisors after transient reconciliation errors, and retry from the runtime until capacity becomes authoritative or shutdown cancels the lifecycle.\n\nRefs #128794
1 parent 59a9221 commit 904347d

5 files changed

Lines changed: 323 additions & 187 deletions

File tree

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

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -194,6 +194,42 @@ async function waitForIdentityDeath(identity: NodeWorkerProcessIdentity) {
194194
}
195195

196196
describe("node worker supervisor recovery", () => {
197+
it("coalesces failed initialization and retries reconciliation on the next attempt", async () => {
198+
const { bundleRoot, env } = fixture("node-worker-initialization-retry-");
199+
const capacitySnapshots: Array<{ total: number; available: number }> = [];
200+
const supervisor = createNodeWorkerSupervisor({
201+
bundleRoot,
202+
env,
203+
capacity: 2,
204+
onCapacityChanged: (capacity) => capacitySnapshots.push(capacity),
205+
});
206+
const reconciliation = vi
207+
.spyOn(NodeWorkerLaunchStore.prototype, "listNonterminal")
208+
.mockImplementationOnce(() => {
209+
throw new Error("temporary launch journal failure");
210+
});
211+
212+
try {
213+
const first = supervisor.initialize();
214+
const concurrent = supervisor.initialize();
215+
216+
expect(concurrent).toBe(first);
217+
await expect(first).rejects.toThrow("temporary launch journal failure");
218+
await expect(supervisor.initialize()).resolves.toBeUndefined();
219+
expect(reconciliation).toHaveBeenCalledTimes(2);
220+
expect(capacitySnapshots).toEqual([
221+
{ total: 2, available: 0 },
222+
{ total: 2, available: 0 },
223+
{ total: 2, available: 2 },
224+
]);
225+
await expect(supervisor.initialize()).resolves.toBeUndefined();
226+
expect(reconciliation).toHaveBeenCalledTimes(2);
227+
} finally {
228+
reconciliation.mockRestore();
229+
await supervisor.close().catch(() => undefined);
230+
}
231+
});
232+
197233
it("atomically adopts pending work only after the previous supervisor is stale", async () => {
198234
const { bundleRoot, env, workspaceDir } = fixture("node-worker-stale-pending-");
199235
const supervisor = createNodeWorkerSupervisor({ bundleRoot, env });

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

Lines changed: 17 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -103,23 +103,24 @@ class NodeWorkerSupervisor {
103103
this.capacity = new NodeWorkerCapacity(this.store, options);
104104
}
105105

106-
private requireSupervisorIdentity(): NodeWorkerProcessIdentity {
107-
return (this.supervisorIdentity ??= requireNodeWorkerProcessIdentity(process.pid));
108-
}
109-
110106
initialize(): Promise<void> {
111-
return (this.initializationPromise ??= this.containerEngine
112-
? this.initializeContainerHosting()
113-
: this.capacity.initialize(async (receipt) => {
114-
await this.recoverRunning(receipt, false);
115-
}));
116-
}
117-
118-
private async initializeContainerHosting(): Promise<void> {
119-
await this.containerLifecycle?.initialize();
120-
await this.capacity.initialize(async (receipt) => {
121-
await this.recoverRunning(receipt, false);
107+
if (this.initializationPromise) {
108+
return this.initializationPromise;
109+
}
110+
const initialization = (async () => {
111+
if (this.containerLifecycle) {
112+
await this.containerLifecycle.initialize();
113+
}
114+
await this.capacity.initialize(async (receipt) => {
115+
await this.recoverRunning(receipt, false);
116+
});
117+
})().catch((error: unknown) => {
118+
if (this.initializationPromise === initialization) {
119+
this.initializationPromise = undefined;
120+
}
121+
throw error;
122122
});
123+
return (this.initializationPromise = initialization);
123124
}
124125

125126
private requireContainerLifecycle(): NodeWorkerContainerLifecycle {
@@ -164,7 +165,7 @@ class NodeWorkerSupervisor {
164165
return receipt;
165166
}
166167
}
167-
const supervisor = this.requireSupervisorIdentity();
168+
const supervisor = (this.supervisorIdentity ??= requireNodeWorkerProcessIdentity(process.pid));
168169
const claimInput = {
169170
launchId: input.launchId,
170171
planHash,

‎src/node-host/runtime.test.ts‎

Lines changed: 0 additions & 153 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@ import { NODE_DEVICE_APPS_COMMAND } from "../infra/node-commands.js";
33
import type { OpenClawPluginNodeHostCommandIo } from "../plugins/types.js";
44
import { NODE_DESKTOP_STREAM_COMMAND } from "../shared/node-desktop-stream.js";
55
import type { NodeHostClient } from "./client.js";
6-
import { createNodeWorkerSupervisor } from "./node-worker-supervisor.js";
76
import { listRegisteredNodeHostCapsAndCommands } from "./plugin-node-host.js";
87
import { prepareNodeHostRuntime } from "./runtime.js";
98

@@ -13,11 +12,6 @@ const mocks = vi.hoisted(() => {
1312
closeMcp,
1413
closeWorkerSupervisor: vi.fn(async () => undefined),
1514
initializeWorkerSupervisor: vi.fn(async () => undefined),
16-
resolveContainerEngine: vi.fn(async (_options?: { env?: NodeJS.ProcessEnv }) => ({
17-
id: "docker" as const,
18-
command: "docker",
19-
target: "e".repeat(64),
20-
})),
2115
handleInvoke: vi.fn(async () => undefined),
2216
progressStartHeartbeats: vi.fn(),
2317
progressWrite: vi.fn(async (_chunk: string) => undefined),
@@ -50,10 +44,6 @@ vi.mock("./node-invoke-progress.js", () => ({
5044
})),
5145
}));
5246

53-
vi.mock("./node-worker-container-engine.js", () => ({
54-
resolveNodeWorkerContainerEngine: mocks.resolveContainerEngine,
55-
}));
56-
5747
vi.mock("./node-worker-supervisor.js", () => ({
5848
createNodeWorkerSupervisor: vi.fn(() => ({
5949
initialize: mocks.initializeWorkerSupervisor,
@@ -139,149 +129,6 @@ function holdInvoke(onCommand?: (io: OpenClawPluginNodeHostCommandIo) => void) {
139129
};
140130
}
141131

142-
describe("node-host worker manifest", () => {
143-
it("allows environment-managed processes to force worker hosting without durable config", async () => {
144-
const prepared = await prepareNodeHostRuntime({
145-
config: { nodeHost: { skills: { enabled: false }, workerRuns: { enabled: false } } },
146-
env: { PATH: "/usr/bin" },
147-
enableWorkerRuns: true,
148-
forceWorkerRuns: true,
149-
});
150-
151-
expect(prepared.workerHostingEnabled).toBe(true);
152-
});
153-
154-
it("keeps local consent separate from connection metadata", async () => {
155-
const prepared = await prepareNodeHostRuntime({
156-
config: { nodeHost: { skills: { enabled: false }, workerRuns: { enabled: true } } },
157-
env: { PATH: "/usr/bin" },
158-
enableWorkerRuns: true,
159-
});
160-
161-
expect(prepared.workerHostingEnabled).toBe(true);
162-
expect(prepared.manifest).not.toHaveProperty("workerRuns");
163-
expect(mocks.resolveContainerEngine).not.toHaveBeenCalled();
164-
});
165-
166-
it("disables container-isolated hosting and records why when no engine is usable", async () => {
167-
const reason =
168-
"Container-isolated node workers require Docker or Podman; install and start an engine.";
169-
mocks.resolveContainerEngine.mockRejectedValueOnce(new Error(reason));
170-
171-
const prepared = await prepareNodeHostRuntime({
172-
config: {
173-
nodeHost: {
174-
skills: { enabled: false },
175-
workerRuns: { enabled: true, isolation: "container" },
176-
},
177-
},
178-
env: { PATH: "/usr/bin" },
179-
enableWorkerRuns: true,
180-
});
181-
182-
expect(prepared.workerHostingEnabled).toBe(false);
183-
expect(prepared.workerHostingDisabledReason).toBe(reason);
184-
const runtime = prepared.start({
185-
client: { request: vi.fn(async () => ({})) } as unknown as NodeHostClient,
186-
});
187-
expect(createNodeWorkerSupervisor).not.toHaveBeenCalled();
188-
await runtime.close();
189-
});
190-
191-
it("disables container-isolated hosting on Windows before probing or advertising an engine", async () => {
192-
const prepared = await prepareNodeHostRuntime({
193-
config: {
194-
nodeHost: {
195-
skills: { enabled: false },
196-
workerRuns: { enabled: true, isolation: "container" },
197-
},
198-
},
199-
env: { PATH: "/usr/bin" },
200-
enableWorkerRuns: true,
201-
platform: "win32",
202-
});
203-
204-
expect(prepared.workerHostingEnabled).toBe(false);
205-
expect(prepared.workerHostingDisabledReason).toMatch(/windows.*(?:linux|macos)/iu);
206-
expect(mocks.resolveContainerEngine).not.toHaveBeenCalled();
207-
expect(createNodeWorkerSupervisor).not.toHaveBeenCalled();
208-
const runtime = prepared.start({
209-
client: { request: vi.fn(async () => ({})) } as unknown as NodeHostClient,
210-
});
211-
expect(createNodeWorkerSupervisor).not.toHaveBeenCalled();
212-
await runtime.close();
213-
});
214-
215-
it("resolves the container engine once and passes its exact identity to the supervisor", async () => {
216-
mocks.initializeWorkerSupervisor.mockImplementationOnce(async () => {
217-
const options = vi.mocked(createNodeWorkerSupervisor).mock.calls[0]?.[0];
218-
options?.onCapacityChanged?.({ total: 3, available: 0 });
219-
options?.onCapacityChanged?.({ total: 3, available: 3 });
220-
});
221-
const prepared = await prepareNodeHostRuntime({
222-
config: {
223-
nodeHost: {
224-
skills: { enabled: false },
225-
workerRuns: {
226-
enabled: true,
227-
isolation: "container",
228-
containerImage: "registry.example/openclaw-worker:22",
229-
},
230-
},
231-
},
232-
env: { PATH: "/usr/bin" },
233-
enableWorkerRuns: true,
234-
});
235-
236-
expect(prepared.workerHostingEnabled).toBe(true);
237-
expect(mocks.resolveContainerEngine).toHaveBeenCalledOnce();
238-
expect(mocks.initializeWorkerSupervisor).toHaveBeenCalledOnce();
239-
const onRunnerCapacityChanged = vi.fn();
240-
const runtime = prepared.start({
241-
client: { request: vi.fn(async () => ({})) } as unknown as NodeHostClient,
242-
onRunnerCapacityChanged,
243-
});
244-
expect(createNodeWorkerSupervisor).toHaveBeenCalledWith(
245-
expect.objectContaining({
246-
containerEngine: { id: "docker", command: "docker", target: "e".repeat(64) },
247-
containerImage: "registry.example/openclaw-worker:22",
248-
}),
249-
);
250-
expect(mocks.resolveContainerEngine).toHaveBeenCalledOnce();
251-
expect(mocks.initializeWorkerSupervisor).toHaveBeenCalledOnce();
252-
expect(onRunnerCapacityChanged).toHaveBeenCalledExactlyOnceWith({ total: 3, available: 3 });
253-
await runtime.close();
254-
});
255-
256-
it("fails closed when container launch reconciliation cannot establish safe ownership", async () => {
257-
mocks.initializeWorkerSupervisor.mockRejectedValueOnce(new Error("orphan sweep failed"));
258-
259-
const prepared = await prepareNodeHostRuntime({
260-
config: {
261-
nodeHost: {
262-
skills: { enabled: false },
263-
workerRuns: { enabled: true, isolation: "container" },
264-
},
265-
},
266-
env: { PATH: "/usr/bin" },
267-
enableWorkerRuns: true,
268-
});
269-
270-
expect(prepared.workerHostingEnabled).toBe(false);
271-
expect(prepared.workerHostingDisabledReason).toContain("orphan sweep failed");
272-
expect(mocks.closeWorkerSupervisor).toHaveBeenCalledOnce();
273-
const onRunnerCapacityChanged = vi.fn();
274-
const runtime = prepared.start({
275-
client: { request: vi.fn(async () => ({})) } as unknown as NodeHostClient,
276-
onRunnerCapacityChanged,
277-
});
278-
expect(createNodeWorkerSupervisor).toHaveBeenCalledOnce();
279-
expect(onRunnerCapacityChanged).not.toHaveBeenCalled();
280-
await runtime.close();
281-
expect(mocks.closeWorkerSupervisor).toHaveBeenCalledOnce();
282-
});
283-
});
284-
285132
describe("node-host invocation cancellation", () => {
286133
it("cancels ordinary node invocations", async () => {
287134
const held = holdInvoke();

‎src/node-host/runtime.ts‎

Lines changed: 32 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@ import {
4444
import { scanNodeHostedSkills } from "./skills.js";
4545

4646
const DEFAULT_NODE_PATH = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin";
47+
const WORKER_INITIALIZATION_RETRY_MS = 5_000;
4748

4849
type NodeHostManifest = {
4950
caps: string[];
@@ -296,18 +297,17 @@ export async function prepareNodeHostRuntime(params?: {
296297
let preparedContainerWorkspace: NodeWorkerWorkspaceRuntime | undefined;
297298
let preparedContainerSupervisor: ReturnType<typeof createNodeWorkerSupervisor> | undefined;
298299
let preparedContainerCapacity: NodeWorkerCapacitySnapshot | undefined;
300+
let preparedContainerInitialized = false;
299301
let publishContainerCapacity: ((capacity: NodeWorkerCapacitySnapshot) => void) | undefined;
300302
let workerHostingDisabledReason: string | undefined;
301303
if (workerRunsEnabled && config.nodeHost?.workerRuns?.isolation === "container") {
302-
let engineResolved = false;
303304
try {
304305
if (platform === "win32") {
305306
throw new Error(
306307
'Container-isolated node workers are unsupported on Windows because native paths cannot be mounted at their container paths; run the node host on Linux or macOS, or set isolation to "none".',
307308
);
308309
}
309310
const containerEngine = await resolveNodeWorkerContainerEngine({ env });
310-
engineResolved = true;
311311
preparedContainerWorkspace = new NodeWorkerWorkspaceRuntime({ env });
312312
preparedContainerSupervisor = createNodeWorkerSupervisor({
313313
env,
@@ -322,25 +322,19 @@ export async function prepareNodeHostRuntime(params?: {
322322
publishContainerCapacity?.(capacity);
323323
},
324324
});
325-
// Container ownership and orphan cleanup must succeed before any worker capacity is advertised.
326-
await preparedContainerSupervisor.initialize();
327-
} catch (error) {
328-
let failure = error;
329325
try {
330-
await preparedContainerSupervisor?.close();
331-
} catch (closeError) {
332-
if (closeError !== error) {
333-
failure = new Error(`${String(error)}; supervisor cleanup failed: ${String(closeError)}`);
334-
}
326+
// Container ownership and orphan cleanup must precede positive capacity publication.
327+
await preparedContainerSupervisor.initialize();
328+
preparedContainerInitialized = true;
329+
} catch (error) {
330+
logDebug(`node-host: worker capacity reconciliation failed: ${String(error)}`);
335331
}
332+
} catch (error) {
336333
workerRunsEnabled = false;
337334
preparedContainerWorkspace = undefined;
338335
preparedContainerSupervisor = undefined;
339336
preparedContainerCapacity = undefined;
340-
const detail = failure instanceof Error ? failure.message : String(failure);
341-
workerHostingDisabledReason = engineResolved
342-
? `container worker reconciliation failed: ${detail}; inspect the container engine and worker launch journal before retrying`
343-
: detail;
337+
workerHostingDisabledReason = error instanceof Error ? error.message : String(error);
344338
}
345339
}
346340
const skills = config.nodeHost?.skills?.enabled === false ? null : scanNodeHostedSkills();
@@ -379,6 +373,9 @@ export async function prepareNodeHostRuntime(params?: {
379373
initialInventory,
380374
start({ client, onInventoryChanged, onManifestChanged, onRunnerCapacityChanged }) {
381375
const mcpAbort = new AbortController();
376+
let closing = false;
377+
let closePromise: Promise<void> | undefined;
378+
let initializationRetry: ReturnType<typeof setTimeout> | undefined;
382379
const workerWorkspace =
383380
preparedContainerWorkspace ??
384381
(workerRunsEnabled ? new NodeWorkerWorkspaceRuntime({ env }) : undefined);
@@ -400,10 +397,25 @@ export async function prepareNodeHostRuntime(params?: {
400397
if (preparedContainerCapacity) {
401398
onRunnerCapacityChanged?.(preparedContainerCapacity);
402399
}
403-
} else if (workerSupervisor) {
400+
}
401+
const initializeWorkerSupervisor = () => {
402+
if (!workerSupervisor || closing) {
403+
return;
404+
}
404405
void workerSupervisor.initialize().catch((error: unknown) => {
405406
logDebug(`node-host: worker capacity reconciliation failed: ${String(error)}`);
407+
if (closing) {
408+
return;
409+
}
410+
initializationRetry = setTimeout(() => {
411+
initializationRetry = undefined;
412+
initializeWorkerSupervisor();
413+
}, WORKER_INITIALIZATION_RETRY_MS);
414+
initializationRetry.unref?.();
406415
});
416+
};
417+
if (workerSupervisor && !preparedContainerInitialized) {
418+
initializeWorkerSupervisor();
407419
}
408420
const skillBins = new SkillBinsCache(client, pathEnv);
409421
const activeInvokes = new Map<string, ActiveNodeInvoke>();
@@ -428,8 +440,6 @@ export async function prepareNodeHostRuntime(params?: {
428440
}
429441
| undefined;
430442
let manager: NodeHostMcpManager | undefined;
431-
let closing = false;
432-
let closePromise: Promise<void> | undefined;
433443
const publishInventory = () =>
434444
onInventoryChanged?.(
435445
createInventory(skills, currentPluginNodeHost.nodePluginTools, manager?.descriptors),
@@ -615,6 +625,10 @@ export async function prepareNodeHostRuntime(params?: {
615625
return closePromise;
616626
}
617627
closing = true;
628+
if (initializationRetry) {
629+
clearTimeout(initializationRetry);
630+
initializationRetry = undefined;
631+
}
618632
this.cancelAll();
619633
const preludeErrors: unknown[] = [];
620634
try {

0 commit comments

Comments
 (0)