Skip to content

Commit d1651de

Browse files
committed
test(node-host): serialize fake container state transitions
1 parent 6934b8f commit d1651de

2 files changed

Lines changed: 145 additions & 48 deletions

File tree

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

Lines changed: 62 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -53,20 +53,27 @@ const { spawn } = require("node:child_process");
5353
const { createHash } = require("node:crypto");
5454
const { DatabaseSync } = require("node:sqlite");
5555
const fs = require("node:fs");
56+
const { withFileLockSync } = require(fileLockModule);
5657
const path = require("node:path");
5758
const args = process.argv.slice(2);
5859
const command = args[0];
5960
const statePath = (id) => path.join(engineRoot, id + ".container.json");
6061
const load = (id) => JSON.parse(fs.readFileSync(statePath(id), "utf8"));
61-
// Sibling shim invocations (rm/inspect/wait) read this state while another
62-
// writes it. A truncating write exposes a zero-length window, so a reader
63-
// parses partial JSON and the shim exits 1; rename is atomic, so readers
64-
// always see either the previous or the next complete state.
65-
const save = (container) => {
66-
const target = statePath(container.id);
67-
const pending = target + "." + process.pid + ".pending";
68-
fs.writeFileSync(pending, JSON.stringify(container));
69-
fs.renameSync(pending, target);
62+
// Separate CLI processes share one fake daemon. Serialize state transitions so
63+
// a delayed start or exit callback cannot recreate a removed container.
64+
const withContainerLock = (id, operation) => withFileLockSync(statePath(id), {
65+
payload: () => ({ pid: process.pid, createdAt: new Date().toISOString() }),
66+
timeoutMs: 5_000,
67+
}, operation);
68+
const save = (container) => fs.writeFileSync(statePath(container.id), JSON.stringify(container));
69+
const killWorker = (container) => {
70+
if (container.pid) {
71+
try {
72+
process.kill(process.platform === "win32" ? container.pid : -container.pid, "SIGKILL");
73+
} catch (error) {
74+
if (error.code !== "ESRCH") throw error;
75+
}
76+
}
7077
};
7178
const launchIdFor = (container) =>
7279
Buffer.from(container.labels["openclaw.node-worker.launch"], "base64url").toString("utf8");
@@ -155,12 +162,13 @@ if (command === "version") {
155162
const entry = args[entrypoint + 3];
156163
const workerArgs = args.slice(entrypoint + 4);
157164
const container = { id, labels, env, mounts, image, entry, workerArgs, status: "created", pid: null };
158-
save(container);
165+
withContainerLock(id, () => save(container));
159166
record({ argv: args, container, journal: journalState(launchIdFor(container)) });
160167
releaseAfterMarker("hold-create", () => process.stdout.write(id + "\n"));
161168
} else if (command === "start") {
162169
void (async () => {
163-
const container = readContainer(args.at(-1));
170+
const id = args.at(-1);
171+
let container = withContainerLock(id, () => readContainer(id));
164172
const journal = await waitForRunningJournal(container);
165173
record({ argv: args, journal });
166174
const persisted = journal?.container_json && JSON.parse(journal.container_json);
@@ -175,14 +183,18 @@ if (command === "version") {
175183
// A real engine leaves the container "created" until its start request lands,
176184
// so the marker lets a test hold the launch inside that startup window.
177185
await new Promise((resolve) => releaseAfterMarker("hold-start", resolve));
178-
const child = spawn(process.execPath, [container.entry, ...container.workerArgs], {
179-
detached: process.platform !== "win32",
180-
env: container.env,
181-
stdio: ["pipe", "inherit", "inherit"],
186+
const child = withContainerLock(id, () => {
187+
container = readContainer(id);
188+
const child = spawn(process.execPath, [container.entry, ...container.workerArgs], {
189+
detached: process.platform !== "win32",
190+
env: container.env,
191+
stdio: ["pipe", "inherit", "inherit"],
192+
});
193+
container.status = "running";
194+
container.pid = child.pid;
195+
save(container);
196+
return child;
182197
});
183-
container.status = "running";
184-
container.pid = child.pid;
185-
save(container);
186198
process.stdin.pipe(child.stdin);
187199
child.stdin.on("error", (error) => {
188200
if (error.code !== "EPIPE") throw error;
@@ -192,12 +204,14 @@ if (command === "version") {
192204
process.exitCode = 1;
193205
});
194206
child.once("exit", (code, signal) => {
195-
if (fs.existsSync(statePath(container.id))) {
196-
const current = load(container.id);
197-
current.status = "exited";
198-
current.pid = null;
199-
save(current);
200-
}
207+
withContainerLock(container.id, () => {
208+
if (fs.existsSync(statePath(container.id))) {
209+
const current = load(container.id);
210+
current.status = "exited";
211+
current.pid = null;
212+
save(current);
213+
}
214+
});
201215
process.exit(code ?? (signal ? 137 : 0));
202216
});
203217
})().catch((error) => {
@@ -207,7 +221,7 @@ if (command === "version") {
207221
} else if (command === "inspect") {
208222
const id = args.at(-1);
209223
record({ argv: args });
210-
const container = readContainer(id);
224+
const container = withContainerLock(id, () => readContainer(id));
211225
const format = args[args.indexOf("--format") + 1];
212226
const columns = [container.status];
213227
// Releasing the startup hold here proves the supervisor observed the container
@@ -223,41 +237,42 @@ if (command === "version") {
223237
}
224238
process.stdout.write(columns.join("\t") + "\n");
225239
} else if (command === "kill") {
226-
const container = readContainer(args.at(-1));
227-
record({ argv: args, journal: journalState(launchIdFor(container)) });
228-
if (container.status !== "running") {
229-
process.stderr.write("container is not running\n");
230-
process.exit(1);
231-
}
232-
container.status = "exited";
233-
save(container);
234-
if (container.pid) {
235-
try {
236-
process.kill(process.platform === "win32" ? container.pid : -container.pid, "SIGKILL");
237-
} catch (error) {
238-
if (error.code !== "ESRCH") throw error;
240+
const id = args.at(-1);
241+
withContainerLock(id, () => {
242+
const container = readContainer(id);
243+
record({ argv: args, journal: journalState(launchIdFor(container)) });
244+
if (container.status !== "running") {
245+
process.stderr.write("container is not running\n");
246+
process.exit(1);
239247
}
240-
}
241-
process.stdout.write(container.id + "\n");
248+
container.status = "exited";
249+
save(container);
250+
killWorker(container);
251+
process.stdout.write(container.id + "\n");
252+
});
242253
} else if (command === "rm") {
243-
const container = readContainer(args.at(-1));
254+
const id = args.at(-1);
255+
const container = withContainerLock(id, () => readContainer(id));
244256
record({ argv: args, journal: journalState(launchIdFor(container)) });
245257
if (fs.existsSync(path.join(engineRoot, "fail-removal"))) {
246258
process.stderr.write("injected container removal failure\n");
247259
process.exit(1);
248260
}
249-
releaseAfterMarker("hold-removal", () => {
250-
fs.unlinkSync(statePath(container.id));
251-
process.stdout.write(container.id + "\n");
252-
});
261+
releaseAfterMarker("hold-removal", () => withContainerLock(id, () => {
262+
const current = readContainer(id);
263+
killWorker(current);
264+
fs.unlinkSync(statePath(id));
265+
process.stdout.write(id + "\n");
266+
}));
253267
} else if (command === "ps") {
254268
record({ argv: args });
255269
const ownerFilter = args.find((arg) => arg.startsWith("label=openclaw.node-worker.host="));
256270
const owner = ownerFilter?.slice("label=openclaw.node-worker.host=".length);
257271
for (const file of fs.readdirSync(engineRoot).sort()) {
258272
if (!file.endsWith(".container.json")) continue;
259-
const container = JSON.parse(fs.readFileSync(path.join(engineRoot, file), "utf8"));
260-
if (container.labels["openclaw.node-worker.host"] !== owner) continue;
273+
const id = file.slice(0, -".container.json".length);
274+
const container = withContainerLock(id, () => fs.existsSync(statePath(id)) ? load(id) : undefined);
275+
if (!container || container.labels["openclaw.node-worker.host"] !== owner) continue;
261276
process.stdout.write([
262277
container.id,
263278
container.labels["openclaw.node-worker.gateway"],

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

Lines changed: 83 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,18 @@
11
import { createHash } from "node:crypto";
22
import fs from "node:fs";
3+
import { createRequire } from "node:module";
34
import path from "node:path";
45
import { afterEach, describe, expect, it, vi } from "vitest";
56
import { useAutoCleanupTempDirTracker } from "../../test/helpers/temp-dir.js";
67
import * as processExec from "../process/exec.js";
8+
import { createChildAdapter } from "../process/supervisor/adapters/child.js";
79
import { closeOpenClawStateDatabaseForTest } from "../state/openclaw-state-db.js";
10+
import { completeWorkerLaunchDescriptor } from "../worker/launch-descriptor.js";
811
import type { WorkerConnectionEndpoint } from "../worker/worker-connection-endpoint.js";
12+
import { buildWorkerProcessTurn } from "../worker/worker-process-protocol.js";
913
import { NodeWorkerContainerLifecycle } from "./node-worker-container-lifecycle.js";
1014
import { NodeWorkerLaunchStore } from "./node-worker-launch-store.js";
15+
import { sendNodeWorkerInput } from "./node-worker-launch-transport.js";
1116
import {
1217
inspectNodeWorkerProcessIdentity,
1318
requireNodeWorkerProcessIdentity,
@@ -35,6 +40,7 @@ const hostLabel = "openclaw.node-worker.host";
3540
const gatewayLabel = "openclaw.node-worker.gateway";
3641
const launchLabel = "openclaw.node-worker.launch";
3742
const DAEMON_TIMER_SCALE = 5;
43+
const fileLockModule = createRequire(import.meta.url).resolve("@openclaw/fs-safe/file-lock");
3844

3945
type FakeContainer = {
4046
id: string;
@@ -81,7 +87,7 @@ function containerFixture(
8187
fs.writeFileSync(path.join(engineRoot, "daemon-id"), daemonId);
8288
fs.writeFileSync(
8389
command,
84-
`#!${process.execPath}\nconst engineRoot = ${JSON.stringify(engineRoot)};\nconst stateRoot = ${JSON.stringify(stateDir)};\nconst commandLog = ${JSON.stringify(commandLog)};\nconst expectedEngineTarget = ${JSON.stringify(engineTarget)};\n${fakeEngineSource}`,
90+
`#!${process.execPath}\nconst engineRoot = ${JSON.stringify(engineRoot)};\nconst stateRoot = ${JSON.stringify(stateDir)};\nconst commandLog = ${JSON.stringify(commandLog)};\nconst expectedEngineTarget = ${JSON.stringify(engineTarget)};\nconst fileLockModule = ${JSON.stringify(fileLockModule)};\n${fakeEngineSource}`,
8591
{ mode: 0o755 },
8692
);
8793
const containerEngine = {
@@ -523,6 +529,82 @@ describe("node worker supervisor container isolation", () => {
523529
},
524530
);
525531

532+
it.each(["before startup", "while running"] as const)(
533+
"force removal fences the fake container %s",
534+
async (phase) => {
535+
const fixture = containerFixture();
536+
const launchId = "container-force-removal";
537+
const container = fixture.seed({ id: "9".repeat(64), launchId, status: "created" });
538+
const { input } = claimFixtureLaunch(fixture, launchId, container.id);
539+
const startMarker = path.join(fixture.engineRoot, "hold-start");
540+
if (phase === "before startup") {
541+
fs.writeFileSync(startMarker, "hold");
542+
}
543+
const adapter = await createChildAdapter({
544+
argv: [fixture.containerEngine.command, "start", "--attach", "--interactive", container.id],
545+
env: fixture.containerEngine.env,
546+
exactEnv: true,
547+
stdinMode: "pipe-open",
548+
});
549+
let exited = false;
550+
const completed = adapter.wait().finally(() => {
551+
exited = true;
552+
});
553+
try {
554+
await sendNodeWorkerInput(
555+
adapter,
556+
buildWorkerProcessTurn(completeWorkerLaunchDescriptor(input.descriptor, endpoint)),
557+
);
558+
await vi.waitFor(
559+
() => expect(fixture.events().some((event) => event.argv[0] === "start")).toBe(true),
560+
{ timeout: 5_000 },
561+
);
562+
let worker: ReturnType<typeof requireNodeWorkerProcessIdentity> | undefined;
563+
if (phase === "while running") {
564+
await waitForWorkerStarted(fixture.workspaceDir);
565+
const started = JSON.parse(
566+
fs.readFileSync(path.join(fixture.workspaceDir, `${launchId}.fixture.json`), "utf8"),
567+
) as { pid: number };
568+
worker = requireNodeWorkerProcessIdentity(started.pid);
569+
}
570+
await processExec.runExec(
571+
fixture.containerEngine.command,
572+
["rm", "--force", container.id],
573+
{
574+
baseEnv: fixture.containerEngine.env,
575+
timeoutMs: 15_000,
576+
logOutput: false,
577+
},
578+
);
579+
expect(fixture.exists(container.id)).toBe(false);
580+
if (phase === "before startup") {
581+
fs.unlinkSync(startMarker);
582+
adapter.stdin?.end();
583+
await completed;
584+
expect(fixture.exists(container.id)).toBe(false);
585+
expect(fs.existsSync(path.join(fixture.workspaceDir, "worker-started"))).toBe(false);
586+
} else {
587+
await vi.waitFor(() => expect(inspectNodeWorkerProcessIdentity(worker!)).toBe("dead"), {
588+
timeout: 5_000,
589+
});
590+
await completed;
591+
expect(fixture.exists(container.id)).toBe(false);
592+
}
593+
} finally {
594+
if (fs.existsSync(startMarker)) {
595+
fs.unlinkSync(startMarker);
596+
}
597+
adapter.stdin?.end();
598+
if (!exited) {
599+
adapter.kill("SIGKILL");
600+
}
601+
await completed;
602+
adapter.dispose();
603+
await fixture.supervisor.close();
604+
}
605+
},
606+
);
607+
526608
it("keeps a pending cancelled container slot occupied until the fake engine confirms removal", async () => {
527609
const capacitySnapshots: Array<{ total: number; available: number }> = [];
528610
const fixture = containerFixture({

0 commit comments

Comments
 (0)