Skip to content

Commit 712fa8d

Browse files
committed
improve(worker): diagnose admission-deadline failures and widen daemon revalidation budget
WorkerAdmissionDeadlineExceededError now carries the terminal diagnosis — the last connection failure kind and detail, attempt count, and the redacted endpoint — instead of a bare deadline sentence, and that text flows through IPC, container stderr, the node launch journal, and the gateway turn error. Credential material (raw, URL-encoded, JSON-escaped) is scrubbed before truncation. A LAN partition was misdiagnosed as a gateway admission wedge for a day because the old text was identical for never-connected and never-answered (#129979). Container daemon revalidation gets a 30s budget: a slammed-but-healthy OrbStack daemon exceeded the old 5s under a 50-container burst; fail-closed semantics unchanged.
1 parent 6f37877 commit 712fa8d

12 files changed

Lines changed: 337 additions & 78 deletions

‎docs/cli/worker.md‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,17 @@ no longer current. Missing, duplicate, or unknown tool names also invalidate the
3434
envelope. Operators should start workers through the cloud worker
3535
orchestrator rather than invoke this entry point directly.
3636

37+
If admission exhausts its 120-second retry budget, the terminal error includes
38+
the attempt count, Gateway host and port (or local socket path), and last failure.
39+
`connect failed` means the WebSocket did not open; check reachability and TLS.
40+
`no hello within deadline` means it opened but the Gateway did not complete worker
41+
admission. A retryable admission rejection retains its reason. These bounded,
42+
credential-redacted details appear in the node launch journal and turn error.
43+
44+
Container launches revalidate the pinned daemon identity before creating each
45+
container. This check allows 30 seconds for a busy daemon; a timeout still fails
46+
the launch and names the command. A changed daemon identity remains a hard failure.
47+
3748
## Runtime boundary
3849

3950
The process runs the normal embedded agent loop with a restricted backend:

‎src/gateway/worker-environments/node-worker-tunnel.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -249,7 +249,7 @@ describe("node worker tunnel manager", () => {
249249
it("projects a terminal gateway connection failure into the launch result", async () => {
250250
const record = environment();
251251
const errorText =
252-
"worker could not reach gateway gateway.example: certificate rejected; check TLS pin/publicUrl configuration";
252+
"worker admission deadline exceeded after 3 attempts to gateway.example:18789: connect failed: Opening handshake has timed out";
253253
const manager = createNodeWorkerTunnelManager({
254254
gatewayDeviceId: "gateway-device-1",
255255
getEnvironment: () => record,

‎src/gateway/worker-environments/worker-turn-launcher-failure-recovery.test.ts‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -556,14 +556,16 @@ describe("worker turn launcher failure recovery", () => {
556556
expect(teardownStates).toEqual([]);
557557
});
558558

559-
it("keeps redacted process failure details on a valid UTF-16 boundary", async () => {
559+
it("preserves the admission diagnosis with bounded redacted process failure details", async () => {
560560
seedActivePlacement();
561561
const secret = "$SUPERSECRET123";
562-
const redactedPrefix = "DISCORD_BOT_TOKEN=*** ";
562+
const diagnosis =
563+
"worker admission deadline exceeded after 3 attempts to gateway.example:18789: connect failed: Opening handshake has timed out; ";
564+
const redactedPrefix = `${diagnosis}DISCORD_BOT_TOKEN=*** `;
563565
const padding = "a".repeat(399 - redactedPrefix.length);
564566
const retained = `${redactedPrefix}${padding}`;
565567
const emoji = String.fromCodePoint(0x1f600);
566-
const stderr = `DISCORD_BOT_TOKEN=${secret} ${padding}${emoji}tail`;
568+
const stderr = `${diagnosis}DISCORD_BOT_TOKEN=${secret} ${padding}${emoji}tail`;
567569
const stopTunnel = vi.fn(async () => {});
568570
const destroy = vi.fn(async () => attachedEnvironment());
569571
const environments: WorkerTurnEnvironmentService = {

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

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,9 @@ type NodeWorkerContainerExpectedOwner = {
2626
};
2727

2828
const DEFAULT_NODE_WORKER_CONTAINER_IMAGE = "node:22-slim";
29+
// Burst launches can delay a healthy daemon's identity response; keep revalidation
30+
// fail-closed without treating temporary daemon contention as an unavailable engine.
31+
const CONTAINER_REVALIDATION_TIMEOUT_MS = 30_000;
2932

3033
const HOST_LABEL = "openclaw.node-worker.host";
3134
const GATEWAY_LABEL = "openclaw.node-worker.gateway";
@@ -95,6 +98,7 @@ async function resolveContainerEngineTarget(
9598
options: { pinned?: boolean } = {},
9699
): Promise<Pick<NodeWorkerContainerEngine, "target" | "env">> {
97100
const env = engine.env ?? process.env;
101+
const timeoutMs = options.pinned ? CONTAINER_REVALIDATION_TIMEOUT_MS : 5_000;
98102
if (engine.id === "docker") {
99103
const endpoint =
100104
env.DOCKER_HOST?.trim() ||
@@ -114,7 +118,7 @@ async function resolveContainerEngineTarget(
114118
const daemonId = await runContainerCommand(
115119
{ ...engine, env: frozenEnv },
116120
["info", "--format", "{{.ID}}"],
117-
5_000,
121+
timeoutMs,
118122
);
119123
if (!daemonId || daemonId === "<no value>") {
120124
throw new Error("Docker daemon did not report a stable identity");
@@ -128,7 +132,7 @@ async function resolveContainerEngineTarget(
128132
const info = await runContainerCommand(
129133
engine,
130134
["info", "--format", "{{.Host.Hostname}}\t{{.Store.GraphRoot}}\t{{.Host.RemoteSocket.Path}}"],
131-
5_000,
135+
timeoutMs,
132136
);
133137
const [hostname, graphRoot, remoteSocket = "", extra] = info.split("\t");
134138
if (extra !== undefined || !hostname || !graphRoot || hostname === "<no value>") {

‎src/node-host/node-worker-launch-transport.ts‎

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@ import { isGatewayLoopbackHost } from "../../packages/gateway-client/src/websock
22
import { createChildAdapter } from "../process/supervisor/adapters/child.js";
33
import type { WorkerLaunchDescriptor } from "../worker/launch-descriptor.js";
44
import { parseNodeWorkerConnectionFailureMessage } from "../worker/node-supervisor-protocol.js";
5-
import { formatWorkerConnectionFailure } from "../worker/worker-connection-contract.js";
65
import {
76
buildNodeWorkerContainerStartArgv,
87
createNodeWorkerContainer,
@@ -68,13 +67,10 @@ export async function prepareNodeWorkerLaunchTransport(
6867
return;
6968
}
7069
options.connectionFailure.errorText = diagnostic.cause
71-
? formatWorkerConnectionFailure(
72-
options.descriptor.connectionEndpoint,
73-
sanitizeNodeWorkerDiagnostic(
74-
diagnostic.cause,
75-
"node worker gateway connection failed",
76-
options.scrubber.scrub,
77-
),
70+
? sanitizeNodeWorkerDiagnostic(
71+
diagnostic.cause,
72+
"node worker gateway connection failed",
73+
options.scrubber.scrub,
7874
)
7975
: undefined;
8076
},

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

Lines changed: 78 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,9 @@ if (process.connected || process.argv.includes("--internal-worker-ipc")) {
3333
process.stderr.write("container worker unexpectedly received Node IPC");
3434
process.exit(24);
3535
}
36-
if (descriptor.assignment.prompt === "wait") {
36+
if (descriptor.assignment.prompt === "admission-failure") {
37+
throw new Error("worker admission deadline exceeded after 9 attempts to gateway.example:443: connect failed: Opening handshake has timed out " + descriptor.admission.credential);
38+
} else if (descriptor.assignment.prompt === "wait") {
3739
fs.writeFileSync(descriptor.assignment.workspaceDir + "/worker-started", "started");
3840
setInterval(() => {}, 1000);
3941
} else {
@@ -131,7 +133,9 @@ if (command === "version") {
131133
} else if (command === "info") {
132134
const daemonId = fs.readFileSync(path.join(engineRoot, "daemon-id"), "utf8");
133135
record({ argv: args, daemonId });
134-
process.stdout.write(daemonId + "\n");
136+
const delayFile = path.join(engineRoot, "info-delay-ms");
137+
const delayMs = fs.existsSync(delayFile) ? Number(fs.readFileSync(delayFile, "utf8")) : 0;
138+
setTimeout(() => process.stdout.write(daemonId + "\n"), delayMs);
135139
} else if (command === "create") {
136140
const id = createHash("sha256").update(JSON.stringify(args)).digest("hex");
137141
const labels = {};
@@ -497,6 +501,28 @@ describe("node worker supervisor container isolation", () => {
497501
}
498502
});
499503

504+
it("persists the container worker's admission diagnosis from stderr without credentials", async () => {
505+
const fixture = containerFixture();
506+
const input = testWorkerLaunchInput(
507+
fixture.workspaceDir,
508+
"container-admission-failure",
509+
"admission-failure",
510+
);
511+
try {
512+
await fixture.supervisor.launch(input, endpoint);
513+
const failed = await waitForTerminal(fixture.supervisor, input.launchId);
514+
expect(failed).toMatchObject({ state: "failed" });
515+
expect(failed?.errorText).toContain(
516+
"worker admission deadline exceeded after 9 attempts to gateway.example:443: connect failed: Opening handshake has timed out",
517+
);
518+
expect(failed?.errorText).not.toContain(input.descriptor.admission.credential);
519+
expect(Buffer.byteLength(failed?.errorText ?? "", "utf8")).toBeLessThanOrEqual(4_096);
520+
expect((await fixture.supervisor.status(input.launchId))?.errorText).toBe(failed?.errorText);
521+
} finally {
522+
await fixture.supervisor.close();
523+
}
524+
});
525+
500526
it("keeps a launch running while its container is still starting", async () => {
501527
const fixture = containerFixture();
502528
const input = testWorkerLaunchInput(fixture.workspaceDir, "container-startup-poll");
@@ -567,6 +593,56 @@ describe("node worker supervisor container isolation", () => {
567593
}
568594
});
569595

596+
it(
597+
"launches after a busy daemon takes six seconds to revalidate",
598+
{ timeout: 15_000 },
599+
async () => {
600+
const fixture = containerFixture();
601+
const input = testWorkerLaunchInput(fixture.workspaceDir, "container-busy-daemon");
602+
fs.writeFileSync(path.join(fixture.engineRoot, "info-delay-ms"), "6000");
603+
604+
try {
605+
expect(await fixture.supervisor.launch(input, endpoint)).toMatchObject({
606+
state: "running",
607+
});
608+
expect(await waitForTerminal(fixture.supervisor, input.launchId)).toMatchObject({
609+
state: "completed",
610+
});
611+
} finally {
612+
await fixture.supervisor.close();
613+
}
614+
},
615+
);
616+
617+
it(
618+
"records the revalidation command when the daemon exceeds its deadline",
619+
{ timeout: 45_000 },
620+
async () => {
621+
const fixture = containerFixture();
622+
const input = testWorkerLaunchInput(fixture.workspaceDir, "container-unresponsive-daemon");
623+
fs.writeFileSync(path.join(fixture.engineRoot, "info-delay-ms"), "35000");
624+
625+
try {
626+
const failed = await fixture.supervisor.launch(input, endpoint);
627+
628+
expect(failed.state).toBe("failed");
629+
expect(failed.errorText).toMatch(/Command timed out after \d+ milliseconds:/u);
630+
expect(failed.errorText).toContain("docker info --format '{{.ID}}'");
631+
expect(await fixture.supervisor.status(input.launchId)).toMatchObject({
632+
state: "failed",
633+
errorText: failed.errorText,
634+
});
635+
expect(
636+
fixture
637+
.events()
638+
.filter((event) => event.argv[0] === "create" || event.argv[0] === "start"),
639+
).toEqual([]);
640+
} finally {
641+
await fixture.supervisor.close();
642+
}
643+
},
644+
);
645+
570646
it("keeps a pending cancelled container slot occupied until the fake engine confirms removal", async () => {
571647
const capacitySnapshots: Array<{ total: number; available: number }> = [];
572648
const fixture = containerFixture({

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

Lines changed: 16 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -84,19 +84,22 @@ const writeResultAndExit = (value) => {
8484
exitWorker(0);
8585
};
8686
const mode = descriptor.assignment.prompt;
87-
if (mode === "connection-failure") {
88-
process.send(
89-
{
90-
type: "openclaw-worker-connection-failure-v1",
91-
cause: "certificate rejected " + descriptor.admission.credential,
92-
},
93-
() =>
94-
fs.writeFileSync(
95-
path.join(descriptor.assignment.workspaceDir, "connection-failure-reported"),
96-
"reported",
97-
),
98-
);
99-
setInterval(() => {}, 1000);
87+
if (mode === "connection-failure" || mode === "connection-deadline") {
88+
const target = new URL(descriptor.connectionEndpoint.url).host;
89+
const report = (cause) => new Promise((resolve) => process.send(
90+
{ type: "openclaw-worker-connection-failure-v1", cause }, resolve,
91+
));
92+
await report("worker could not reach gateway " + target + ": certificate rejected " +
93+
descriptor.admission.credential + "; check TLS pin/publicUrl configuration");
94+
if (mode === "connection-deadline") {
95+
await report("worker admission deadline exceeded after 3 attempts to " + target +
96+
": connect failed: Opening handshake has timed out " + descriptor.admission.credential);
97+
process.stderr.write("worker admission deadline exceeded\n");
98+
exitWorker(7);
99+
} else {
100+
fs.writeFileSync(path.join(descriptor.assignment.workspaceDir, "connection-failure-reported"), "reported");
101+
setInterval(() => {}, 1000);
102+
}
100103
} else if (mode === "wait") {
101104
setInterval(() => {}, 1000);
102105
} else if (mode === "tree") {

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

Lines changed: 31 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -632,31 +632,39 @@ describe("node worker supervisor", () => {
632632
await supervisor.close();
633633
});
634634

635-
it("records the child's last gateway connection failure when cancelling admission", async () => {
636-
const { supervisor, workspaceDir } = fixture();
637-
const input = launchInput(workspaceDir, "connection-failure-launch", "connection-failure");
638-
expect(
635+
it.each([
636+
[
637+
"connection-failure",
638+
"cancelled",
639+
"worker could not reach gateway gateway.example:18789: certificate rejected ",
640+
],
641+
[
642+
"connection-deadline",
643+
"failed",
644+
"worker admission deadline exceeded after 3 attempts to gateway.example:18789: connect failed: Opening handshake has timed out ",
645+
],
646+
] as const)(
647+
"records the child's %s diagnosis in the terminal journal",
648+
async (prompt, state, errorText) => {
649+
const { supervisor, workspaceDir } = fixture();
650+
const input = launchInput(workspaceDir, "connection-failure-launch", prompt);
639651
await supervisor.launch(input, {
640652
kind: "websocket",
641-
url: "wss://gateway.example/__openclaw__/worker",
642-
}),
643-
).toMatchObject({
644-
state: "running",
645-
});
646-
await vi.waitFor(() =>
647-
expect(fs.existsSync(path.join(workspaceDir, "connection-failure-reported"))).toBe(true),
648-
);
649-
650-
const cancelled = await supervisor.cancel(testNodeWorkerLaunchIdentity(input));
651-
expect(cancelled).toMatchObject({
652-
state: "cancelled",
653-
errorText: expect.stringMatching(
654-
/^worker could not reach gateway gateway\.example: certificate rejected .+; check TLS pin\/publicUrl configuration$/u,
655-
),
656-
});
657-
expect(cancelled?.errorText).not.toContain(TEST_WORKER_CREDENTIAL);
658-
await supervisor.close();
659-
});
653+
url: "wss://gateway.example:18789/__openclaw__/worker",
654+
});
655+
if (state === "cancelled") {
656+
await vi.waitFor(() =>
657+
expect(fs.existsSync(path.join(workspaceDir, "connection-failure-reported"))).toBe(true),
658+
);
659+
await supervisor.cancel(testNodeWorkerLaunchIdentity(input));
660+
}
661+
const terminal = await waitForTerminal(supervisor, input.launchId);
662+
expect(terminal).toMatchObject({ state, errorText: expect.stringContaining(errorText) });
663+
expect(Buffer.byteLength(terminal.errorText ?? "", "utf8")).toBeLessThanOrEqual(4 * 1024);
664+
expect(terminal.errorText).not.toContain(TEST_WORKER_CREDENTIAL);
665+
await supervisor.close();
666+
},
667+
);
660668

661669
it.each([
662670
["cancel", "cancelled"],

0 commit comments

Comments
 (0)