Skip to content

Commit 1a789b3

Browse files
committed
fix(nodes): keep starting containers out of the exited state
`inspectNodeWorkerContainer` read `{{.State.Running}}`, which is false both before a container starts and after it exits, so the supervisor treated a container still in `created` as a finished workload. A `status()` poll landing in the window between spawning `docker start --attach` and the container entering `running` therefore killed and removed a healthy worker and finalized its launch as `failed` with exit code 137. Classify the engine's `{{.State.Status}}` instead: statuses that still own a workload stay `live`, only finished ones report `dead`. This also tightens removal verification, which previously accepted a surviving `created` container as successfully removed. Verified against Docker 29.4.0: a container reports `created|false` for roughly the first 100ms after its start client is spawned. The fake engine now models engine status like a real one, and a regression test holds a container in `created` until the supervisor inspects it, then asserts the launch stays running and completes.
1 parent 49c5bb2 commit 1a789b3

2 files changed

Lines changed: 69 additions & 15 deletions

File tree

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

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,18 @@ const CONTAINER_NODE_EXECUTABLE = "node";
3434
const CONTAINER_PATH = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin";
3535
const CONTAINER_ID_PATTERN = /^[a-f0-9]{64}$/u;
3636
const ENCODED_LAUNCH_PATTERN = /^[A-Za-z0-9_-]+$/u;
37+
// `.State.Running` is false both before a container starts and after it exits.
38+
// A created or initialized container still owns an admitted workload, so its
39+
// launch must never be finalized or fenced as if the worker had already ended.
40+
const OWNED_CONTAINER_STATUSES = new Set([
41+
"created",
42+
"initialized",
43+
"running",
44+
"paused",
45+
"restarting",
46+
"stopping",
47+
]);
48+
const ENDED_CONTAINER_STATUSES = new Set(["exited", "stopped", "dead", "removing"]);
3749

3850
function hostNamespace(bundleRoot: string): string {
3951
return createHash("sha256").update(path.resolve(bundleRoot)).digest("hex").slice(0, 32);
@@ -343,8 +355,8 @@ export async function inspectNodeWorkerContainer(
343355
): Promise<"live" | "dead" | "reused" | "unknown"> {
344356
try {
345357
const format = expected
346-
? `{{.State.Running}}\t{{index .Config.Labels "${HOST_LABEL}"}}\t{{index .Config.Labels "${GATEWAY_LABEL}"}}\t{{index .Config.Labels "${LAUNCH_LABEL}"}}`
347-
: "{{.State.Running}}";
358+
? `{{.State.Status}}\t{{index .Config.Labels "${HOST_LABEL}"}}\t{{index .Config.Labels "${GATEWAY_LABEL}"}}\t{{index .Config.Labels "${LAUNCH_LABEL}"}}`
359+
: "{{.State.Status}}";
348360
const state = await runContainerCommand(engine, [
349361
"inspect",
350362
"--type",
@@ -353,7 +365,7 @@ export async function inspectNodeWorkerContainer(
353365
format,
354366
containerId,
355367
]);
356-
const [running, owner, gateway, launch, extra] = state.split("\t");
368+
const [status = "", owner, gateway, launch, extra] = state.split("\t");
357369
if (expected) {
358370
if (
359371
extra !== undefined ||
@@ -366,7 +378,11 @@ export async function inspectNodeWorkerContainer(
366378
} else if (owner !== undefined) {
367379
return "unknown";
368380
}
369-
return running === "true" ? "live" : running === "false" ? "dead" : "unknown";
381+
return OWNED_CONTAINER_STATUSES.has(status)
382+
? "live"
383+
: ENDED_CONTAINER_STATUSES.has(status)
384+
? "dead"
385+
: "unknown";
370386
} catch (error) {
371387
return missingContainer(error) ? "dead" : "unknown";
372388
}

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

Lines changed: 49 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -147,7 +147,7 @@ if (command === "version") {
147147
}
148148
const entry = args.at(-1);
149149
const image = args.at(-2);
150-
const container = { id, labels, env, mounts, image, entry, running: false, pid: null };
150+
const container = { id, labels, env, mounts, image, entry, status: "created", pid: null };
151151
save(container);
152152
record({ argv: args, container, journal: journalState(launchIdFor(container)) });
153153
releaseAfterMarker("hold-create", () => process.stdout.write(id + "\n"));
@@ -167,12 +167,15 @@ if (command === "version") {
167167
process.stderr.write("container worker executed before its exact identity was journaled\n");
168168
process.exit(67);
169169
}
170+
// A real engine leaves the container "created" until its start request lands,
171+
// so the marker lets a test hold the launch inside that startup window.
172+
await new Promise((resolve) => releaseAfterMarker("hold-start", resolve));
170173
const child = spawn(process.execPath, [container.entry], {
171174
detached: process.platform !== "win32",
172175
env: container.env,
173176
stdio: ["pipe", "inherit", "inherit"],
174177
});
175-
container.running = true;
178+
container.status = "running";
176179
container.pid = child.pid;
177180
save(container);
178181
child.stdin.end(descriptor);
@@ -183,7 +186,7 @@ if (command === "version") {
183186
child.once("exit", (code, signal) => {
184187
if (fs.existsSync(statePath(container.id))) {
185188
const current = load(container.id);
186-
current.running = false;
189+
current.status = "exited";
187190
current.pid = null;
188191
save(current);
189192
}
@@ -198,7 +201,11 @@ if (command === "version") {
198201
record({ argv: args });
199202
const container = readContainer(id);
200203
const format = args[args.indexOf("--format") + 1];
201-
const columns = [String(container.running)];
204+
const columns = [container.status];
205+
// Releasing the startup hold here proves the supervisor observed the container
206+
// while it was still created: the launch only proceeds after that observation.
207+
const startHold = path.join(engineRoot, "hold-start");
208+
if (fs.existsSync(startHold)) fs.unlinkSync(startHold);
202209
if (format.includes("openclaw.node-worker.host")) {
203210
columns.push(
204211
container.labels["openclaw.node-worker.host"] ?? "",
@@ -210,11 +217,11 @@ if (command === "version") {
210217
} else if (command === "kill") {
211218
const container = readContainer(args.at(-1));
212219
record({ argv: args, journal: journalState(launchIdFor(container)) });
213-
if (!container.running) {
220+
if (container.status !== "running") {
214221
process.stderr.write("container is not running\n");
215222
process.exit(1);
216223
}
217-
container.running = false;
224+
container.status = "exited";
218225
save(container);
219226
if (container.pid) {
220227
try {
@@ -263,7 +270,7 @@ type FakeContainer = {
263270
mounts: string[];
264271
image: string;
265272
entry: string;
266-
running: boolean;
273+
status: "created" | "running" | "exited";
267274
pid: number | null;
268275
};
269276

@@ -339,7 +346,12 @@ function containerFixture(
339346
.split("\n")
340347
.map((line) => JSON.parse(line) as EngineEvent);
341348
},
342-
seed(params: { id: string; launchId: string; owner?: string; running?: boolean }) {
349+
seed(params: {
350+
id: string;
351+
launchId: string;
352+
owner?: string;
353+
status?: FakeContainer["status"];
354+
}) {
343355
const container: FakeContainer = {
344356
id: params.id,
345357
labels: {
@@ -351,7 +363,7 @@ function containerFixture(
351363
mounts: [],
352364
image: "node:22-slim",
353365
entry: bundleEntry,
354-
running: params.running ?? true,
366+
status: params.status ?? "running",
355367
pid: null,
356368
};
357369
fs.writeFileSync(
@@ -435,7 +447,7 @@ describe("node worker supervisor container isolation", () => {
435447
},
436448
});
437449
const completed = await waitForTerminal(fixture.supervisor, input.launchId);
438-
expect(completed?.state).toBe("completed");
450+
expect(completed).toMatchObject({ state: "completed" });
439451
expect(JSON.parse(completed?.resultJson ?? "null")).toEqual({
440452
status: "completed",
441453
argv: [],
@@ -484,6 +496,32 @@ describe("node worker supervisor container isolation", () => {
484496
}
485497
});
486498

499+
it("keeps a launch running while its container is still starting", async () => {
500+
const fixture = containerFixture();
501+
const input = testWorkerLaunchInput(fixture.workspaceDir, "container-startup-poll");
502+
const startMarker = path.join(fixture.engineRoot, "hold-start");
503+
fs.writeFileSync(startMarker, "hold");
504+
505+
try {
506+
const running = await fixture.supervisor.launch(input, endpoint);
507+
508+
// The fake engine keeps the container created until this poll inspects it,
509+
// so the supervisor must not read startup as an exited worker.
510+
expect(await fixture.supervisor.status(input.launchId)).toMatchObject({
511+
state: "running",
512+
container: running.container,
513+
});
514+
expect(await waitForTerminal(fixture.supervisor, input.launchId)).toMatchObject({
515+
state: "completed",
516+
});
517+
} finally {
518+
if (fs.existsSync(startMarker)) {
519+
fs.unlinkSync(startMarker);
520+
}
521+
await fixture.supervisor.close();
522+
}
523+
});
524+
487525
it("uses the documented Node 22 image when no override is configured", async () => {
488526
const fixture = containerFixture();
489527
const input = testWorkerLaunchInput(fixture.workspaceDir, "container-default-image");
@@ -667,7 +705,7 @@ describe("node worker supervisor container isolation", () => {
667705
it("interrupts a stale running journal after verifying its dead container identity", async () => {
668706
const fixture = containerFixture();
669707
const launchId = "container-dead-recovery";
670-
const container = fixture.seed({ id: "c".repeat(64), launchId, running: false });
708+
const container = fixture.seed({ id: "c".repeat(64), launchId, status: "exited" });
671709
claimFixtureLaunch(fixture, launchId, container.id);
672710

673711
try {

0 commit comments

Comments
 (0)