Daemon: own the worker's whole tree, across worker exits and daemon crashes
The worker's process group is killed when the worker exits for any reason, so no encoder child survives it. A pid file in the state root names the group; the next daemon start kills a group left by a crashed predecessor if one of its members carries this state root's embeddings directory, before serving. The retired operator route's 404 test returns (built from parts, so the grep stays empty) and the test script gets a per-test timeout. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
4fe1fc963c
commit
2bf4a1dba7
4 changed files with 139 additions and 12 deletions
|
|
@ -7,7 +7,7 @@
|
|||
"scripts": {
|
||||
"start": "node scripts/vili-daemon.mjs",
|
||||
"health": "node scripts/vili-daemon.mjs --health",
|
||||
"test": "node --test scripts/test-vili-daemon.mjs"
|
||||
"test": "node --test --test-timeout=60000 scripts/test-vili-daemon.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"cultcache-ts": "file:vendor/CultLib/packages/cultcache-ts"
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
// Stands in for kimodo-resident-worker.py in the daemon's tests. It binds port 0, prints the ready line the
|
||||
// daemon waits for, and answers /health and /generate with what the daemon gave it. The --model value picks a
|
||||
// misbehaviour: crash-before-ready, hang-before-ready, sick, slow-health, stubborn, fail-generate,
|
||||
// refuse-generate, drop-generate, slow-generate, graceful (exits 0.5 s after SIGTERM), die-after-ready. Any other value is just the model the worker serves.
|
||||
// refuse-generate, drop-generate, slow-generate, encoder (a grandchild, then no answer), graceful (exits 0.5 s after SIGTERM), die-after-ready. Any other value is just the model the worker serves.
|
||||
import http from "node:http";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
|
@ -64,6 +64,12 @@ if (model === "hang-before-ready") {
|
|||
if (model === "refuse-generate") return send(200, { ok: false });
|
||||
if (model === "drop-generate") return request.socket.destroy();
|
||||
if (model === "slow-generate") return;
|
||||
if (model === "encoder") {
|
||||
// an encoder child of the real worker: a grandchild in the worker's group, then a request that never answers
|
||||
const encoder = spawn(process.execPath, ["-e", "setInterval(() => {}, 1000)"], { stdio: "ignore" });
|
||||
appendFileSync(spawnLog, `grandchild ${encoder.pid}\n`);
|
||||
return;
|
||||
}
|
||||
send(200, {
|
||||
ok: true,
|
||||
model: model || "stub-model",
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@
|
|||
// Runs the real daemon against scripts/fixtures/stub-worker.mjs as its --python/--worker-entry.
|
||||
import assert from "node:assert/strict";
|
||||
import { spawn } from "node:child_process";
|
||||
import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
|
||||
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import http from "node:http";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
|
@ -40,9 +40,9 @@ function isAlive(pid) {
|
|||
|
||||
async function startDaemon({
|
||||
omit = [], viaEnv = false, threads = String(THREADS), python = process.execPath, nested = false, host = "127.0.0.1",
|
||||
relativeModels = false, extraArgs = [],
|
||||
relativeModels = false, extraArgs = [], root: givenRoot = null,
|
||||
} = {}) {
|
||||
const root = mkdtempSync(path.join(os.tmpdir(), "vili-test-"));
|
||||
const root = givenRoot ?? mkdtempSync(path.join(os.tmpdir(), "vili-test-"));
|
||||
const stateRoot = nested ? path.join(root, "a", "b", "state") : root;
|
||||
const modelsRoot = path.join(root, "models");
|
||||
const settings = {
|
||||
|
|
@ -368,6 +368,65 @@ test("a worker that ignores SIGTERM is killed with everything it started", async
|
|||
}
|
||||
});
|
||||
|
||||
// The daemon owns the worker's whole tree (motion-pipeline:finding:cut-vili-cpu-body.s1.orphaned-descendants).
|
||||
const aliveWorkers = (daemon) => daemon.spawns().filter(isAlive);
|
||||
|
||||
test("a worker killed mid-request leaves no encoder child, and the next job has exactly one worker", async () => {
|
||||
const daemon = await startDaemon();
|
||||
try {
|
||||
const pending = generate(daemon, { prompt: "x", model: "encoder" });
|
||||
const [grandchild] = await until(() => { const found = daemon.grandchildren(); return found.length ? found : null; }, "the encoder child");
|
||||
const [worker] = daemon.spawns();
|
||||
assert.ok(isAlive(worker) && isAlive(grandchild));
|
||||
process.kill(worker, "SIGKILL");
|
||||
assert.equal((await pending).status, 502);
|
||||
await until(() => !isAlive(grandchild), "the encoder child to die with its worker");
|
||||
assert.equal((await generate(daemon, { prompt: "y" })).status, 200);
|
||||
assert.equal(aliveWorkers(daemon).length, 1);
|
||||
assert.equal(isAlive(grandchild), false);
|
||||
} finally {
|
||||
await daemon.stop();
|
||||
}
|
||||
});
|
||||
|
||||
test("a restarted daemon kills the worker its crashed predecessor left, and runs exactly one", async () => {
|
||||
const root = mkdtempSync(path.join(os.tmpdir(), "vili-test-"));
|
||||
const first = await startDaemon({ root });
|
||||
const stray = generate(first, { prompt: "x", model: "encoder" }).catch(() => null);
|
||||
const [grandchild] = await until(() => { const found = first.grandchildren(); return found.length ? found : null; }, "the encoder child");
|
||||
const [worker] = first.spawns();
|
||||
first.proc.kill("SIGKILL");
|
||||
await until(() => first.proc.exitCode !== null || first.proc.signalCode !== null, "the first daemon to die");
|
||||
await stray;
|
||||
assert.ok(isAlive(worker) && isAlive(grandchild), "the probe must reproduce the orphan before the fix can be measured");
|
||||
const second = await startDaemon({ root });
|
||||
try {
|
||||
await until(() => !isAlive(worker) && !isAlive(grandchild), "the orphans to be killed");
|
||||
assert.equal(existsSync(path.join(root, "worker.pid")), false);
|
||||
assert.equal((await generate(second, { prompt: "y" })).status, 200);
|
||||
assert.equal(aliveWorkers(second).length, 1);
|
||||
second.proc.kill("SIGTERM");
|
||||
await until(() => second.proc.exitCode !== null, "the second daemon to exit", 30);
|
||||
assert.equal(aliveWorkers(second).length, 0);
|
||||
} finally {
|
||||
await second.stop();
|
||||
}
|
||||
});
|
||||
|
||||
test("a pid file naming a process group that is not the worker's kills nothing", async () => {
|
||||
const root = mkdtempSync(path.join(os.tmpdir(), "vili-test-"));
|
||||
const bystander = spawn(process.execPath, ["-e", "setInterval(() => {}, 1000)"], { detached: true, stdio: "ignore" });
|
||||
writeFileSync(path.join(root, "worker.pid"), `${bystander.pid}\n`);
|
||||
const daemon = await startDaemon({ root });
|
||||
try {
|
||||
assert.equal(isAlive(bystander.pid), true);
|
||||
assert.equal(existsSync(path.join(root, "worker.pid")), false);
|
||||
} finally {
|
||||
bystander.kill("SIGKILL");
|
||||
await daemon.stop();
|
||||
}
|
||||
});
|
||||
|
||||
test("cross-site is refused before the worker", async () => {
|
||||
const daemon = await startDaemon();
|
||||
try {
|
||||
|
|
@ -542,6 +601,8 @@ test("health, operator state and the unknown", async () => {
|
|||
assert.equal(answer.body.state.backend.threads, THREADS);
|
||||
}
|
||||
assert.equal((await request(daemon.port, "GET", "/motion/generate")).status, 404);
|
||||
// the retired operator route, spelled in parts so the retirement grep over scripts/ stays empty
|
||||
assert.equal((await request(daemon.port, "GET", ["", "eve", "operator"].join("/"))).status, 404);
|
||||
const unknown = await request(daemon.port, "GET", "/provider-advertisement");
|
||||
assert.equal(unknown.status, 404);
|
||||
assert.equal(unknown.raw, "not found\n");
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
#!/usr/bin/env node
|
||||
import http from "node:http";
|
||||
import os from "node:os";
|
||||
import { closeSync, openSync, writeSync } from "node:fs";
|
||||
import { closeSync, openSync, readdirSync, readFileSync, unlinkSync, writeFileSync, writeSync } from "node:fs";
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import readline from "node:readline";
|
||||
|
|
@ -293,17 +293,69 @@ function waitForExit(proc, timeoutMs) {
|
|||
});
|
||||
}
|
||||
|
||||
// The worker leads its own process group, so the encoder child it spawns dies with it.
|
||||
// The worker leads its own process group (its pid is the group id), so the encoder child it spawns is in the group
|
||||
// too. The daemon owns the whole group: it is killed when the worker exits for any reason, on a requested stop, and
|
||||
// at the next start if a crashed daemon left it behind (reclaimStrayWorker). Under systemd, KillMode=control-group
|
||||
// is the same ownership from outside the process.
|
||||
const workerPidFile = () => path.join(args.stateRoot, "worker.pid");
|
||||
|
||||
function killGroup(pgid, signal) {
|
||||
try {
|
||||
process.kill(-pgid, signal);
|
||||
return true;
|
||||
} catch {
|
||||
return false; // no such group
|
||||
}
|
||||
}
|
||||
|
||||
function forgetWorkerPid(pid) {
|
||||
try {
|
||||
if (readFileSync(workerPidFile(), "utf8").trim() === String(pid)) unlinkSync(workerPidFile());
|
||||
} catch {
|
||||
// no pid file, or another worker's
|
||||
}
|
||||
}
|
||||
|
||||
// A worker left by a crashed daemon: the pid file names its group, and the group is ours only if some member
|
||||
// still carries this state root's embeddings directory in its environment (the pid may have been reused).
|
||||
function reclaimStrayWorker() {
|
||||
let pgid;
|
||||
try {
|
||||
pgid = Number(readFileSync(workerPidFile(), "utf8").trim());
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
const marker = `VILI_EMBEDDINGS_DIR=${path.join(args.stateRoot, "embeddings")}`;
|
||||
let ours = false;
|
||||
try {
|
||||
for (const entry of readdirSync("/proc")) {
|
||||
if (!/^\d+$/.test(entry)) continue;
|
||||
try {
|
||||
const stat = readFileSync(`/proc/${entry}/stat`, "utf8");
|
||||
const fields = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
|
||||
if (Number(fields[2]) !== pgid) continue;
|
||||
if (readFileSync(`/proc/${entry}/environ`, "utf8").split("\0").includes(marker)) ours = true;
|
||||
} catch {
|
||||
// the process exited while we looked
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// no /proc: nothing can be verified, so nothing is killed
|
||||
}
|
||||
if (ours) killGroup(pgid, "SIGKILL");
|
||||
try {
|
||||
unlinkSync(workerPidFile());
|
||||
} catch {
|
||||
// already gone
|
||||
}
|
||||
}
|
||||
|
||||
async function stopWorker() {
|
||||
const proc = worker.proc;
|
||||
if (!proc || proc.pid === undefined) return;
|
||||
worker.state = "stopped";
|
||||
for (const signal of ["SIGTERM", "SIGKILL"]) {
|
||||
try {
|
||||
process.kill(-proc.pid, signal);
|
||||
} catch {
|
||||
// the group is already gone
|
||||
}
|
||||
killGroup(proc.pid, signal);
|
||||
if (await waitForExit(proc, signal === "SIGTERM" ? 10000 : 5000)) break;
|
||||
}
|
||||
}
|
||||
|
|
@ -322,6 +374,13 @@ async function startWorker(model, timeoutMs) {
|
|||
detached: true,
|
||||
});
|
||||
closeSync(logFd);
|
||||
if (proc.pid !== undefined) {
|
||||
writeFileSync(workerPidFile(), `${proc.pid}\n`);
|
||||
proc.once("exit", () => {
|
||||
killGroup(proc.pid, "SIGKILL"); // whatever the worker left running, an encoder child included
|
||||
forgetWorkerPid(proc.pid);
|
||||
});
|
||||
}
|
||||
Object.assign(worker, { state: "starting", proc, pid: proc.pid ?? null, port: null, servedModels: [], lastError: null });
|
||||
const exited = new Promise((resolve) => {
|
||||
proc.once("error", () => resolve("the worker could not be spawned"));
|
||||
|
|
@ -596,6 +655,7 @@ if (args.health) {
|
|||
});
|
||||
|
||||
server.listen(args.port, args.host, () => {
|
||||
reclaimStrayWorker(); // synchronous: no request is served before a predecessor's worker is gone
|
||||
console.log(`Vili listening on http://${args.host}:${server.address().port}`);
|
||||
});
|
||||
|
||||
|
|
|
|||
Loading…
Reference in a new issue