Skip to content

Commit bf83a4d

Browse files
authored
fix(node-host): recover worker hosting after transient initialization failures (#128798)
* 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 * fix(node-host): preserve permanent container mismatch failures Keep durable engine and daemon-context mismatches on the actionable disabled path while retrying only transient supervisor reconciliation failures.\n\nRefs #128794 * fix(node-host): withdraw hosting on late context mismatch Stop retrying when a later reconciliation attempt proves a permanent container context mismatch, close the supervisor, and withdraw worker hosting from runner inventory.\n\nRefs #128794
1 parent 5238648 commit bf83a4d

8 files changed

Lines changed: 433 additions & 212 deletions
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
export function resolveNodeHostGatewayPlatformIdentity(platform: NodeJS.Platform): {
2+
platform: string;
3+
deviceFamily?: string;
4+
} {
5+
switch (platform) {
6+
case "darwin":
7+
return { platform: "macos", deviceFamily: "Mac" };
8+
case "win32":
9+
return { platform: "windows", deviceFamily: "Windows" };
10+
case "linux":
11+
return { platform: "linux", deviceFamily: "Linux" };
12+
default:
13+
return { platform: "unknown" };
14+
}
15+
}

‎src/node-host/node-worker-container-lifecycle.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@ import { inspectNodeWorkerProcessIdentity } from "./node-worker-process-identity
1212

1313
type NodeWorkerContainerOwner = { gatewayNamespace: string; launchId: string };
1414

15+
export class NodeWorkerContainerContextMismatchError extends Error {}
16+
1517
/** Owns exact container authority and startup cleanup independently of client PIDs. */
1618
export class NodeWorkerContainerLifecycle {
1719
constructor(
@@ -27,7 +29,7 @@ export class NodeWorkerContainerLifecycle {
2729
(receipt.container.engine !== this.engine.id ||
2830
receipt.container.engineTarget !== this.engine.target)
2931
) {
30-
throw new Error(
32+
throw new NodeWorkerContainerContextMismatchError(
3133
`node worker launch ${receipt.launchId} belongs to a different ${receipt.container.engine} engine or daemon; restore its original engine context before enabling worker hosting`,
3234
);
3335
}
@@ -82,7 +84,7 @@ export class NodeWorkerContainerLifecycle {
8284

8385
private requireMatchingEngine(container: NodeWorkerContainerIdentity): NodeWorkerContainerEngine {
8486
if (container.engine !== this.engine.id || container.engineTarget !== this.engine.target) {
85-
throw new Error(
87+
throw new NodeWorkerContainerContextMismatchError(
8688
`node worker container belongs to a different ${container.engine} engine or daemon context`,
8789
);
8890
}

‎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/runner.ts‎

Lines changed: 8 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ import {
3030
resolveNodeHostCloudflareAccess,
3131
type NodeHostCloudflareAccessConfig,
3232
} from "./gateway-cloudflare-access.js";
33+
import { resolveNodeHostGatewayPlatformIdentity } from "./gateway-platform-identity.js";
3334
import {
3435
coerceNodeInvokeCancelPayload,
3536
coerceNodeInvokeInputPayload,
@@ -58,22 +59,6 @@ type NodeHostRunOptions = {
5859
installedAppsSharing?: boolean;
5960
};
6061

61-
function resolveNodeHostGatewayPlatformIdentity(platform: NodeJS.Platform): {
62-
platform: string;
63-
deviceFamily?: string;
64-
} {
65-
switch (platform) {
66-
case "darwin":
67-
return { platform: "macos", deviceFamily: "Mac" };
68-
case "win32":
69-
return { platform: "windows", deviceFamily: "Windows" };
70-
case "linux":
71-
return { platform: "linux", deviceFamily: "Linux" };
72-
default:
73-
return { platform: "unknown" };
74-
}
75-
}
76-
7762
function writeStderrLine(message: string): void {
7863
process.stderr.write(`${message}\n`);
7964
}
@@ -286,6 +271,7 @@ export async function runNodeHost(opts: NodeHostRunOptions): Promise<void> {
286271
forceWorkerRuns: opts.forceWorkerRuns,
287272
installedAppsSharingEnabled: config.installedAppsSharing,
288273
});
274+
let workerHostingEnabled = preparedRuntime.workerHostingEnabled;
289275
if (preparedRuntime.workerHostingDisabledReason) {
290276
writeStderrLine(
291277
`node host worker hosting disabled: ${preparedRuntime.workerHostingDisabledReason}`,
@@ -517,7 +503,7 @@ export async function runNodeHost(opts: NodeHostRunOptions): Promise<void> {
517503
{
518504
protocolFeatures: [NODE_WORKER_SUPERVISOR_PROTOCOL_FEATURE],
519505
workerHost:
520-
preparedRuntime.workerHostingEnabled && workerCapacity
506+
workerHostingEnabled && workerCapacity
521507
? {
522508
enabled: true,
523509
capacity: workerCapacity,
@@ -675,6 +661,11 @@ export async function runNodeHost(opts: NodeHostRunOptions): Promise<void> {
675661
workerCapacity = capacity;
676662
publishRunnerInventory();
677663
},
664+
onWorkerHostingDisabled: (reason) => {
665+
workerHostingEnabled = false;
666+
writeStderrLine(`node host worker hosting disabled: ${reason}`);
667+
publishRunnerInventory();
668+
},
678669
onManifestChanged: (manifest) => {
679670
// Manifest changes force a reconnect. Retire the current publication queue
680671
// now so it cannot drain against the closing connection.

‎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();

0 commit comments

Comments
 (0)