Skip to content

A self-improving RLM agent for coding workflows and long-running autonomous tasks.

Rust

fix(coding-agent): finalize timed-out worker stops instead of stranding registrations (#851)

Sebastian Müllere9ef57774090
diff --git a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts b/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts
index c7bb17d1c7..eae3124b16 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts
@@ -43,7 +43,7 @@ import {
import { canonicalSessionPath, getProcessStartId, SessionAlreadyActiveError } from "../../core/session-lease.js";
import { readSessionInfo, type SessionInfo } from "../../core/session-manager.js";
import { SettingsManager } from "../../core/settings-manager.js";
-import { signalProcessGroupOrProcess } from "../../utils/child-process.js";
+import { isProcessAlive, processIdExists, signalProcessGroupOrProcess } from "../../utils/child-process.js";
import type { AgentConnectionHeartbeat } from "../agent-connection/types.js";
import { attachJsonlLineReader, serializeJsonLine } from "../rpc/jsonl.js";
import type { PrivateFrame } from "../session-worker/private-framing.js";
@@ -136,6 +136,13 @@ const UPDATE_RESTART_WORKER_REQUEST_TIMEOUT_MS = 90_000;
const UPDATE_RESTART_PREPARE_DEADLINE_MS = 100_000;
const WORKER_RETRY_DELAYS_MS = [250, 1000, 5000] as const;
const DEFERRED_RECOVERY_RECHECK_MS = 5000;
+const STOP_FINALIZATION_RECHECK_MS = 250;
+const STOP_FINALIZATION_SIGKILL_GRACE_MS = 5000;
+const STOP_FINALIZATION_RETRY_MS = 5000;
+// Polling loops probe existence cheaply via kill(0); the ps-backed zombie and
+// identity checks are throttled so a wedged worker cannot saturate the
+// supervisor event loop with synchronous subprocess spawns.
+const LIVENESS_IDENTITY_RECHECK_MS = 500;
const OWNED_WORKER_DISCONNECT_GRACE_MS = 30_000;
const IDLE_EVICTION_MAX_SWEEP_INTERVAL_MS = 5 * 60_000;
const IDLE_EVICTION_MIN_SWEEP_INTERVAL_MS = 60_000;
@@ -261,6 +268,7 @@ interface ResidentWorker {
intentionalStop: boolean;
stopRevision: number;
launchEnv?: Record<string, string>;
+ stopFinalization?: Promise<void>;
ownerCleanupTimer?: ReturnType<typeof setTimeout>;
promotedOwnerClientId?: string;
updateRestartPrepareClient?: DaemonWorkerClient;
@@ -329,6 +337,8 @@ class SupervisorRecoveryCancelledError extends Error {
class SnapshotLoadInvalidatedError extends Error {}
+class WorkerStopTimeoutError extends Error {}
+
function isSupervisorGenerationStale(error: unknown): boolean {
return (
typeof error === "object" &&
@@ -511,15 +521,6 @@ function looksLikeSessionPath(selector: string): boolean {
return isAbsolute(selector) || selector.endsWith(".jsonl") || selector.includes("/") || selector.includes("\\");
}
-function isProcessAlive(pid: number): boolean {
- try {
- process.kill(pid, 0);
- return true;
- } catch (error) {
- return (error as NodeJS.ErrnoException).code === "EPERM";
- }
-}
-
function isFinalizedTranscriptEvent(eventType: string | undefined): boolean {
return (
eventType === "message_end" ||
@@ -2383,9 +2384,6 @@ export class DaemonSupervisor {
await this.assertRecoveryAllowed();
if (worker.descriptor.stopRequestedAt) {
try {
- // A tombstoned worker must not run long enough to elect another
- // supervisor while its intentional stop is being adopted.
- signalProcessGroupOrProcess(worker.descriptor.pid, "SIGKILL");
await this.stopWorker(worker, true, true, worker.descriptor.archiveOnStop === true);
this.log(`Completed intentional stop for worker ${worker.descriptor.workerId} during supervisor adoption`);
} catch (error) {
@@ -4541,6 +4539,30 @@ export class DaemonSupervisor {
renameSync(tempPath, path);
}
+ /**
+ * Verdict on whether a pid is still the process we launched. Callers must
+ * be conservative in both directions: signal a pid only on "current"
+ * (never SIGKILL a recycled pid), and clean up a registration only on
+ * "gone"/"replaced" (never orphan a live worker because a transient
+ * identity lookup failed).
+ */
+ private processIdentity(
+ pid: number,
+ processStartId: string | undefined,
+ ): "current" | "replaced" | "gone" | "unknown" {
+ if (!isProcessAlive(pid)) {
+ return "gone";
+ }
+ if (processStartId === undefined) {
+ return "unknown";
+ }
+ const observed = getProcessStartId(pid);
+ if (observed === undefined) {
+ return "unknown";
+ }
+ return observed === processStartId ? "current" : "replaced";
+ }
+
private async stopWorker(
worker: ResidentWorker,
removeDescriptor: boolean,
@@ -4576,6 +4598,24 @@ export class DaemonSupervisor {
if (!recoveryCleanup) {
worker.stopRevision++;
}
+ // A retry can rescind this stop and relaunch the worker while we await
+ // below. Bind every liveness check and signal to the process this stop
+ // entered with, and abort cleanup once the stop no longer applies: the
+ // pid changed (relaunched) or a removeDescriptor stop lost its tombstone
+ // (rescinded, even before the successor pid lands).
+ const entryPid = worker.descriptor.pid;
+ const entryStartId = worker.descriptor.processStartId;
+ const assertStopStillApplies = () => {
+ if (directChild) {
+ return;
+ }
+ if (
+ worker.descriptor.pid !== entryPid ||
+ (removeDescriptor && worker.descriptor.stopRequestedAt === undefined)
+ ) {
+ throw new Error(`Session worker ${worker.descriptor.workerId} was relaunched during stop`);
+ }
+ };
try {
if (removeDescriptor) {
this.persistWorkerStopTombstone(worker, archiveSession);
@@ -4624,22 +4664,42 @@ export class DaemonSupervisor {
worker.client = undefined;
} else if (directChild) {
directChild.child.kill("SIGTERM");
- } else if (isProcessAlive(worker.descriptor.pid)) {
- signalProcessGroupOrProcess(worker.descriptor.pid, "SIGTERM");
- }
- const isWorkerProcessAlive = () =>
- directChild
- ? directChild.child.exitCode === null && directChild.child.signalCode === null
- : isProcessAlive(worker.descriptor.pid);
+ } else if (this.processIdentity(entryPid, entryStartId) === "current") {
+ signalProcessGroupOrProcess(entryPid, "SIGTERM");
+ }
+ // Identity-aware in both directions: a replaced pid counts as gone (never
+ // signal a recycled pid) while an unknown identity counts as alive (never
+ // clean up a possibly-live worker on a transient lookup failure). kill(0)
+ // runs on every poll; the expensive identity check is throttled.
+ let identityVerdict: "current" | "replaced" | "gone" | "unknown" = "current";
+ let identityCheckedAt = 0;
+ const isWorkerProcessAlive = () => {
+ if (directChild) {
+ return directChild.child.exitCode === null && directChild.child.signalCode === null;
+ }
+ if (!processIdExists(entryPid)) {
+ return false;
+ }
+ const now = Date.now();
+ if (now - identityCheckedAt >= LIVENESS_IDENTITY_RECHECK_MS) {
+ identityCheckedAt = now;
+ identityVerdict = this.processIdentity(entryPid, entryStartId);
+ }
+ return identityVerdict !== "replaced" && identityVerdict !== "gone";
+ };
const gracefulDeadline = Date.now() + (force ? 500 : 2000);
while (isWorkerProcessAlive() && Date.now() < gracefulDeadline) {
await delay(25);
}
+ let sigkillSent = false;
if (force && isWorkerProcessAlive()) {
if (directChild) {
- directChild.child.kill("SIGKILL");
- } else {
- signalProcessGroupOrProcess(worker.descriptor.pid, "SIGKILL");
+ sigkillSent = directChild.child.kill("SIGKILL");
+ } else if (this.processIdentity(entryPid, entryStartId) === "current") {
+ // Fresh, unthrottled check: the cached verdict may be up to 500ms
+ // old, long enough for the pid to be recycled.
+ signalProcessGroupOrProcess(entryPid, "SIGKILL");
+ sigkillSent = true;
}
const forceDeadline = Date.now() + 1000;
while (isWorkerProcessAlive() && Date.now() < forceDeadline) {
@@ -4648,16 +4708,23 @@ export class DaemonSupervisor {
}
if (isWorkerProcessAlive()) {
worker.intentionalStop = worker.descriptor.stopRequestedAt !== undefined;
- throw new Error(`Session worker ${worker.descriptor.workerId} did not stop${force ? " after SIGKILL" : ""}`);
+ if (removeDescriptor) {
+ this.scheduleWorkerStopFinalization(worker);
+ }
+ throw new WorkerStopTimeoutError(
+ `Session worker ${worker.descriptor.workerId} did not stop${sigkillSent ? " after SIGKILL" : ""}`,
+ );
}
if (directChild) {
await directChild.closed;
}
+ assertStopStillApplies();
if (removeDescriptor && worker.descriptor.archiveOnStop) {
if (force) {
this.reclaimStoppedWorkerCronLock(worker);
}
await this.finalizeArchivedWorkerStop(worker);
+ assertStopStillApplies();
}
this.workers.delete(worker.descriptor.workerId);
if (removeDescriptor) {
@@ -4669,6 +4736,105 @@ export class DaemonSupervisor {
}
}
+ /**
+ * A stop that timed out leaves a tombstoned registration behind. Keep
+ * escalating in the background until the process is gone, then finish the
+ * interrupted cleanup instead of leaving a dead worker registered forever.
+ */
+ private scheduleWorkerStopFinalization(worker: ResidentWorker): void {
+ if (worker.stopFinalization) {
+ return;
+ }
+ worker.stopFinalization = this.finalizeTimedOutWorkerStop(worker).finally(() => {
+ worker.stopFinalization = undefined;
+ });
+ }
+
+ private async finalizeTimedOutWorkerStop(worker: ResidentWorker): Promise<void> {
+ // Bind to the exact process generation being stopped: a retry can rescind
+ // the stop and relaunch with a new pid, and the OS can recycle the old
+ // pid. The finalizer must never follow either successor.
+ const pid = worker.descriptor.pid;
+ const processStartId = worker.descriptor.processStartId;
+ const stopRevision = worker.stopRevision;
+ const isStopGenerationCurrent = () =>
+ this.workers.get(worker.descriptor.workerId) === worker &&
+ worker.stopRevision === stopRevision &&
+ worker.descriptor.stopRequestedAt !== undefined &&
+ worker.descriptor.pid === pid;
+ // A replaced pid counts as gone (never SIGKILL a recycled pid); an
+ // unobservable identity counts as alive (never clean up a possibly-live
+ // worker). kill(0) probes every poll; ps-backed checks are throttled.
+ let stoppedVerdict = true;
+ let stoppedCanSignal = processStartId !== undefined;
+ let stoppedCheckedAt = 0;
+ const isStoppedProcessAlive = () => {
+ if (!processIdExists(pid)) {
+ return false;
+ }
+ const now = Date.now();
+ if (now - stoppedCheckedAt < LIVENESS_IDENTITY_RECHECK_MS) {
+ return stoppedVerdict;
+ }
+ stoppedCheckedAt = now;
+ if (!isProcessAlive(pid)) {
+ stoppedVerdict = false;
+ } else if (processStartId === undefined) {
+ stoppedVerdict = true;
+ // Without an identity captured while the original worker was known
+ // alive, this pid may now belong to an unrelated process. Keep
+ // waiting for it to disappear, but never escalate by pid alone.
+ stoppedCanSignal = false;
+ } else {
+ const observed = getProcessStartId(pid);
+ stoppedVerdict = observed !== processStartId ? observed === undefined : true;
+ stoppedCanSignal = observed === processStartId;
+ }
+ return stoppedVerdict;
+ };
+ const sigkillDeadline = Date.now() + STOP_FINALIZATION_SIGKILL_GRACE_MS;
+ let killed = false;
+ while (!this.shuttingDown) {
+ if (!isStopGenerationCurrent()) {
+ return;
+ }
+ if (!isStoppedProcessAlive()) {
+ break;
+ }
+ if (!killed && stoppedCanSignal && Date.now() >= sigkillDeadline) {
+ // Fresh, unthrottled identity check right before signalling: the
+ // cached verdict may be up to 500ms old, long enough for the pid
+ // to be recycled by an unrelated process. A transiently
+ // unobservable identity skips this attempt but keeps escalation
+ // armed so a wedged worker is still killed on a later pass.
+ const observedNow = processStartId === undefined ? undefined : getProcessStartId(pid);
+ if (processStartId === undefined || observedNow === processStartId) {
+ signalProcessGroupOrProcess(pid, "SIGKILL");
+ killed = true;
+ }
+ }
+ await unrefDelay(STOP_FINALIZATION_RECHECK_MS);
+ }
+ // Retry transient cleanup failures (for example catalog archival) so a
+ // dead worker's registration is never stranded permanently. Each attempt
+ // bumps the worker's stopRevision, so rescission is detected through the
+ // registration and tombstone instead of the waiting-phase snapshot.
+ const isCleanupStillWanted = () =>
+ this.workers.get(worker.descriptor.workerId) === worker &&
+ worker.descriptor.stopRequestedAt !== undefined &&
+ worker.descriptor.pid === pid;
+ while (!this.shuttingDown && isCleanupStillWanted()) {
+ try {
+ await this.stopWorker(worker, true, true, worker.descriptor.archiveOnStop === true);
+ this.log(`Finalized timed-out stop for worker ${worker.descriptor.workerId}`);
+ return;
+ } catch (error) {
+ this.reportCleanupFailure(`timed-out worker stop ${worker.descriptor.workerId}`, error);
+ await unrefDelay(STOP_FINALIZATION_RETRY_MS);
+ }
+ }
+ }
+
private async finalizeArchivedWorkerStop(worker: ResidentWorker): Promise<void> {
const context = this.workerSessionArtifactContext(worker);
if (!context) {
@@ -4880,7 +5046,18 @@ export class DaemonSupervisor {
}
if (stopWorkers) {
await Promise.all(
- [...this.workers.values()].map((worker) => this.stopWorker(worker, true, forceWorkers, true)),
+ [...this.workers.values()].map(async (worker) => {
+ try {
+ await this.stopWorker(worker, true, forceWorkers, true);
+ } catch (error) {
+ if (!(error instanceof WorkerStopTimeoutError)) {
+ throw error;
+ }
+ this.log(
+ `Worker ${worker.descriptor.workerId} remains tombstoned for recovery after shutdown: ${error.message}`,
+ );
+ }
+ }),
);
if (!this.hasPersistedWorkerDescriptors()) {
rmSync(this.supervisorConfigPath, { force: true });
diff --git a/packages/coding-agent/src/utils/child-process.ts b/packages/coding-agent/src/utils/child-process.ts
index dd2d021343..3f587327f8 100644
--- a/packages/coding-agent/src/utils/child-process.ts
+++ b/packages/coding-agent/src/utils/child-process.ts
@@ -1,4 +1,5 @@
-import type { ChildProcess } from "node:child_process";
+import { type ChildProcess, execFileSync } from "node:child_process";
+import { readFileSync } from "node:fs";
import { constants } from "node:os";
import { basename } from "node:path";
@@ -12,6 +13,44 @@ export function shouldUseWindowsShell(command: string): boolean {
return commandName.endsWith(".cmd") || commandName.endsWith(".bat") || WINDOWS_SHELL_COMMANDS.has(commandName);
}
+/** Cheap kill(0) existence probe; counts zombies as existing. */
+export function processIdExists(pid: number): boolean {
+ try {
+ process.kill(pid, 0);
+ return true;
+ } catch (error) {
+ return (error as NodeJS.ErrnoException).code === "EPERM";
+ }
+}
+
+/** A zombie has already exited; it only lingers until its parent reaps it. */
+export function isZombieProcess(pid: number): boolean {
+ if (process.platform === "win32") {
+ return false;
+ }
+ try {
+ const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
+ const state = stat
+ .slice(stat.lastIndexOf(")") + 2)
+ .trimStart()
+ .charAt(0);
+ return state === "Z";
+ } catch {
+ // Fall through to the portable process listing used on macOS and BSD.
+ }
+ try {
+ const state = execFileSync("ps", ["-p", String(pid), "-o", "stat="], { encoding: "utf8" }).trim();
+ return state.startsWith("Z");
+ } catch {
+ return false;
+ }
+}
+
+/** True only for a process that is actually running: zombies do not count. */
+export function isProcessAlive(pid: number): boolean {
+ return processIdExists(pid) && !isZombieProcess(pid);
+}
+
export function signalProcessGroupOrProcess(pid: number, signal: NodeJS.Signals): void {
try {
process.kill(-pid, signal);
diff --git a/packages/coding-agent/test/child-process.test.ts b/packages/coding-agent/test/child-process.test.ts
index 8000c2f9ce..6a807f32fc 100644
--- a/packages/coding-agent/test/child-process.test.ts
+++ b/packages/coding-agent/test/child-process.test.ts
@@ -1,7 +1,7 @@
-import type { ChildProcess } from "node:child_process";
+import { type ChildProcess, spawn } from "node:child_process";
import { EventEmitter } from "node:events";
import { describe, expect, it } from "vitest";
-import { waitForChildProcess } from "../src/utils/child-process.js";
+import { isProcessAlive, isZombieProcess, waitForChildProcess } from "../src/utils/child-process.js";
describe("waitForChildProcess", () => {
it("reports signaled already-exited children as failures", async () => {
@@ -15,3 +15,49 @@ describe("waitForChildProcess", () => {
await expect(waitForChildProcess(child as unknown as ChildProcess)).resolves.toBe(143);
});
});
+
+describe("process liveness", () => {
+ it("treats the current process as alive and not a zombie", () => {
+ expect(isProcessAlive(process.pid)).toBe(true);
+ expect(isZombieProcess(process.pid)).toBe(false);
+ });
+
+ it("treats an exited process as dead", async () => {
+ const child = spawn(process.execPath, ["--eval", "process.exit(0)"], { stdio: "ignore" });
+ await new Promise<void>((resolveExit) => child.once("exit", () => resolveExit()));
+ // Node reaps its own children on exit, so the pid is fully gone.
+ await new Promise((resolveDelay) => setTimeout(resolveDelay, 50));
+ expect(isProcessAlive(child.pid!)).toBe(false);
+ });
+
+ it.skipIf(process.platform === "win32")("treats a zombie process as dead", async () => {
+ // A parent that forks and never reaps leaves the child as a zombie.
+ const parent = spawn(
+ "perl",
+ ["-e", '$| = 1; my $pid = fork(); if ($pid) { print "$pid\\n"; sleep 30 } else { exit 0 }'],
+ { stdio: ["ignore", "pipe", "ignore"] },
+ );
+ try {
+ const zombiePid = await new Promise<number>((resolvePid, rejectPid) => {
+ let output = "";
+ const timer = setTimeout(() => rejectPid(new Error("Timed out waiting for the zombie pid")), 5000);
+ parent.stdout.on("data", (chunk: Buffer) => {
+ output += chunk.toString();
+ const parsed = Number.parseInt(output.trim(), 10);
+ if (Number.isInteger(parsed) && parsed > 0) {
+ clearTimeout(timer);
+ resolvePid(parsed);
+ }
+ });
+ });
+ const deadline = Date.now() + 5000;
+ while (!isZombieProcess(zombiePid) && Date.now() < deadline) {
+ await new Promise((resolveDelay) => setTimeout(resolveDelay, 25));
+ }
+ expect(isZombieProcess(zombiePid)).toBe(true);
+ expect(isProcessAlive(zombiePid)).toBe(false);
+ } finally {
+ parent.kill("SIGKILL");
+ }
+ });
+});
diff --git a/packages/coding-agent/test/daemon-supervisor-monitor.test.ts b/packages/coding-agent/test/daemon-supervisor-monitor.test.ts
index 112d75487a..7748ef2acf 100644
--- a/packages/coding-agent/test/daemon-supervisor-monitor.test.ts
+++ b/packages/coding-agent/test/daemon-supervisor-monitor.test.ts
@@ -6,6 +6,7 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import type { AgentMessage } from "@earendil-works/pi-agent-core";
import { afterEach, describe, expect, it, vi } from "vitest";
+import { getProcessStartId } from "../src/core/session-lease.js";
import type { DaemonSocketClient } from "../src/modes/daemon/active-session-state.js";
import { CommandRecoveryJournal } from "../src/modes/daemon/command-recovery-journal.js";
import { DaemonCatalogClient } from "../src/modes/daemon/daemon-catalog-process.js";
@@ -27,6 +28,7 @@ import {
import { MutationDrainLatch } from "../src/modes/daemon/mutation-drain-latch.js";
import { WorkerRecoveryJournal } from "../src/modes/daemon/worker-recovery-journal.js";
import type { PrivateFrame } from "../src/modes/session-worker/private-framing.js";
+import * as childProcessModule from "../src/utils/child-process.js";
import { createDeferred } from "./suite/scheduling.js";
const workerLaunchTestState = vi.hoisted(() => ({
@@ -188,6 +190,7 @@ function createExistingLaunchWorker(root: string, descriptorDir: string) {
version: 1 as const,
workerId,
pid: 999_999,
+ processStartId: undefined as string | undefined,
socketPath: join(root, `${workerId}.sock`),
recoveryJournalPath: join(descriptorDir, `${workerId}.recovery.jsonl`),
orphanProcessJournalPath: join(descriptorDir, `${workerId}.orphans.jsonl`),
@@ -898,6 +901,11 @@ describe("daemon worker supervisor monitoring", () => {
);
await rollbackStarted;
supervisor.shuttingDown = true;
+ workerLaunchTestState.forceMissingProcessStartId = false;
+ existing.descriptor.processStartId = getProcessStartId(existing.descriptor.pid);
+ if (existing.descriptor.processStartId === undefined) {
+ throw new Error("Could not identify launched worker before shutdown");
+ }
await supervisor.stopWorker(existing, true, true);
releaseRollback();
@@ -955,6 +963,73 @@ describe("daemon worker supervisor monitoring", () => {
}
});
+ it("completes shutdown without awaiting an unsignalable worker finalizer", async () => {
+ vi.useFakeTimers();
+ const root = mkdtempSync(join(tmpdir(), "prime-supervisor-shutdown-finalization-test-"));
+ supervisorRegistryDirs.add(root);
+ const worker = {
+ descriptor: {
+ workerId: "worker-shutdown-finalization",
+ pid: 111_123,
+ rootActiveSessionId: "active-1",
+ stopRequestedAt: new Date().toISOString(),
+ archiveOnStop: true,
+ },
+ client: undefined,
+ summaries: new Map(),
+ snapshotCache: new Map(),
+ transcriptCaches: new Map(),
+ snapshotGenerations: new Map(),
+ snapshotLoads: new Map(),
+ intentionalStop: true,
+ stopRevision: 1,
+ stopFinalization: new Promise<void>(() => {}),
+ };
+ const workers = new Map([[worker.descriptor.workerId, worker]]);
+ const exit = vi.spyOn(process, "exit").mockImplementation(((code?: string | number | null) => {
+ throw new Error(`exit ${code}`);
+ }) as typeof process.exit);
+ const killSpy = vi.spyOn(childProcessModule, "signalProcessGroupOrProcess").mockImplementation(() => {});
+ const existsSpy = vi.spyOn(childProcessModule, "processIdExists").mockReturnValue(true);
+ const aliveSpy = vi.spyOn(childProcessModule, "isProcessAlive").mockReturnValue(true);
+ const catalogStop = vi.fn(async () => undefined);
+ const log = vi.fn();
+ const supervisor = Object.assign(Object.create(DaemonSupervisor.prototype), {
+ shuttingDown: false,
+ signalCleanupHandlers: [],
+ workers,
+ clients: new Set(),
+ persistWorkerStopTombstone: vi.fn(),
+ hasPersistedWorkerDescriptors: vi.fn(() => true),
+ catalog: { stop: catalogStop },
+ cleanupSocket: vi.fn(),
+ snapshotCacheRoot: join(root, "cache"),
+ log,
+ }) as {
+ shutdown(exitCode: number, stopWorkers: boolean, relaunch?: boolean, forceWorkers?: boolean): Promise<never>;
+ };
+
+ try {
+ const shutdown = supervisor.shutdown(0, true, false, true).then(
+ () => undefined,
+ (error: unknown) => error,
+ );
+ await vi.advanceTimersByTimeAsync(2000);
+ await expect(shutdown).resolves.toEqual(new Error("exit 0"));
+
+ expect(workers.has(worker.descriptor.workerId)).toBe(true);
+ expect(killSpy).not.toHaveBeenCalled();
+ expect(catalogStop).toHaveBeenCalledOnce();
+ expect(log).toHaveBeenCalledWith(expect.stringContaining("remains tombstoned for recovery"));
+ expect(exit).toHaveBeenCalledWith(0);
+ } finally {
+ exit.mockRestore();
+ killSpy.mockRestore();
+ existsSpy.mockRestore();
+ aliveSpy.mockRestore();
+ }
+ });
+
it("does not poll a healthy supervisor after the startup check", async () => {
vi.useFakeTimers();
let resolveProbe: () => void = () => undefined;
@@ -1699,6 +1774,709 @@ describe("daemon worker supervisor monitoring", () => {
]);
});
+ it("adopts a tombstoned worker through identity-aware stop handling", async () => {
+ const worker = {
+ descriptor: {
+ workerId: "worker-adopted-stop",
+ pid: 111_123,
+ processStartId: "proc:original",
+ stopRequestedAt: new Date().toISOString(),
+ archiveOnStop: true,
+ },
+ };
+ const stopWorker = vi.fn(async () => {});
+ const supervisor = Object.assign(Object.create(DaemonSupervisor.prototype), {
+ assertRecoveryAllowed: vi.fn(async () => undefined),
+ stopWorker,
+ log: vi.fn(),
+ }) as {
+ adoptOrRecoverWorker(target: object): Promise<void>;
+ };
+ const killSpy = vi.spyOn(childProcessModule, "signalProcessGroupOrProcess").mockImplementation(() => {});
+ try {
+ await supervisor.adoptOrRecoverWorker(worker);
+
+ expect(killSpy).not.toHaveBeenCalled();
+ expect(stopWorker).toHaveBeenCalledWith(worker, true, true, true);
+ } finally {
+ killSpy.mockRestore();
+ }
+ });
+
+ it("finalizes a timed-out stop once the worker process dies", async () => {
+ vi.useFakeTimers();
+ const worker = {
+ descriptor: {
+ workerId: "worker-timed-out-stop",
+ pid: process.pid,
+ rootActiveSessionId: "active-1",
+ stopRequestedAt: new Date().toISOString(),
+ },
+ intentionalStop: true,
+ stopRevision: 0,
+ stopFinalization: undefined as Promise<void> | undefined,
+ };
+ let alive = true;
+ const stopWorker = vi.fn(async () => {});
+ const supervisor = Object.assign(Object.create(DaemonSupervisor.prototype), {
+ workers: new Map([[worker.descriptor.workerId, worker]]),
+ shuttingDown: false,
+ stopWorker,
+ persistWorker: vi.fn(),
+ log: vi.fn(),
+ reportCleanupFailure: vi.fn(),
+ }) as {
+ scheduleWorkerStopFinalization(target: object): void;
+ };
+ const childProcessModule = await import("../src/utils/child-process.js");
+ const aliveSpy = vi.spyOn(childProcessModule, "isProcessAlive").mockImplementation(() => alive);
+ try {
+ supervisor.scheduleWorkerStopFinalization(worker);
+ const finalization = worker.stopFinalization;
+ expect(finalization).toBeDefined();
+
+ await vi.advanceTimersByTimeAsync(500);
+ expect(stopWorker).not.toHaveBeenCalled();
+
+ alive = false;
+ await vi.advanceTimersByTimeAsync(500);
+ await finalization;
+
+ expect(stopWorker).toHaveBeenCalledWith(worker, true, true, false);
+ expect(worker.stopFinalization).toBeUndefined();
+ } finally {
+ aliveSpy.mockRestore();
+ }
+ });
+
+ it("escalates a stuck stop to SIGKILL before finalizing", async () => {
+ vi.useFakeTimers();
+ const processStartId = getProcessStartId(process.pid);
+ if (processStartId === undefined) {
+ throw new Error("Could not identify test process");
+ }
+ const worker = {
+ descriptor: {
+ workerId: "worker-stuck-stop",
+ pid: process.pid,
+ processStartId,
+ rootActiveSessionId: "active-1",
+ stopRequestedAt: new Date().toISOString(),
+ archiveOnStop: true,
+ },
+ intentionalStop: true,
+ stopRevision: 0,
+ stopFinalization: undefined as Promise<void> | undefined,
+ };
+ let alive = true;
+ const stopWorker = vi.fn(async () => {});
+ const supervisor = Object.assign(Object.create(DaemonSupervisor.prototype), {
+ workers: new Map([[worker.descriptor.workerId, worker]]),
+ shuttingDown: false,
+ stopWorker,
+ persistWorker: vi.fn(),
+ log: vi.fn(),
+ reportCleanupFailure: vi.fn(),
+ }) as {
+ scheduleWorkerStopFinalization(target: object): void;
+ };
+ const childProcessModule = await import("../src/utils/child-process.js");
+ const aliveSpy = vi.spyOn(childProcessModule, "isProcessAlive").mockImplementation(() => alive);
+ const killSpy = vi.spyOn(childProcessModule, "signalProcessGroupOrProcess").mockImplementation((_pid, signal) => {
+ if (signal === "SIGKILL") {
+ alive = false;
+ }
+ });
+ try {
+ supervisor.scheduleWorkerStopFinalization(worker);
+ const finalization = worker.stopFinalization;
+
+ await vi.advanceTimersByTimeAsync(10_000);
+ await finalization;
+
+ expect(killSpy).toHaveBeenCalledWith(worker.descriptor.pid, "SIGKILL");
+ expect(stopWorker).toHaveBeenCalledWith(worker, true, true, true);
+ } finally {
+ aliveSpy.mockRestore();
+ killSpy.mockRestore();
+ }
+ });
+
+ it("never follows a relaunched worker pid after a retry rescinds the stop", async () => {
+ vi.useFakeTimers();
+ const worker = {
+ descriptor: {
+ workerId: "worker-relaunched",
+ pid: 111_111,
+ rootActiveSessionId: "active-1",
+ stopRequestedAt: new Date().toISOString() as string | undefined,
+ },
+ intentionalStop: true,
+ stopRevision: 3,
+ stopFinalization: undefined as Promise<void> | undefined,
+ };
+ const stopWorker = vi.fn(async () => {});
+ const supervisor = Object.assign(Object.create(DaemonSupervisor.prototype), {
+ workers: new Map([[worker.descriptor.workerId, worker]]),
+ shuttingDown: false,
+ stopWorker,
+ persistWorker: vi.fn(),
+ log: vi.fn(),
+ reportCleanupFailure: vi.fn(),
+ }) as {
+ scheduleWorkerStopFinalization(target: object): void;
+ };
+ const existsSpy = vi.spyOn(childProcessModule, "processIdExists").mockReturnValue(true);
+ const aliveSpy = vi.spyOn(childProcessModule, "isProcessAlive").mockReturnValue(true);
+ const killSpy = vi.spyOn(childProcessModule, "signalProcessGroupOrProcess").mockImplementation(() => {});
+ try {
+ supervisor.scheduleWorkerStopFinalization(worker);
+ const finalization = worker.stopFinalization;
+
+ // An explicit retry rescinds the stop and relaunches with a new pid
+ // while the old process is still wedged.
+ await vi.advanceTimersByTimeAsync(1000);
+ worker.descriptor.stopRequestedAt = undefined;
+ worker.intentionalStop = false;
+ worker.stopRevision = 4;
+ worker.descriptor.pid = 222_222;
+
+ await vi.advanceTimersByTimeAsync(20_000);
+ await finalization;
+
+ // The healthy relaunched worker must never be signalled or stopped.
+ expect(killSpy).not.toHaveBeenCalledWith(222_222, "SIGKILL");
+ expect(killSpy).not.toHaveBeenCalled();
+ expect(stopWorker).not.toHaveBeenCalled();
+ } finally {
+ existsSpy.mockRestore();
+ aliveSpy.mockRestore();
+ killSpy.mockRestore();
+ }
+ });
+
+ it("treats a recycled pid as gone instead of killing its new owner", async () => {
+ vi.useFakeTimers();
+ const worker = {
+ descriptor: {
+ workerId: "worker-recycled-pid",
+ pid: 111_112,
+ processStartId: "proc:original",
+ rootActiveSessionId: "active-1",
+ stopRequestedAt: new Date().toISOString(),
+ },
+ intentionalStop: true,
+ stopRevision: 0,
+ stopFinalization: undefined as Promise<void> | undefined,
+ };
+ const stopWorker = vi.fn(async () => {});
+ const supervisor = Object.assign(Object.create(DaemonSupervisor.prototype), {
+ workers: new Map([[worker.descriptor.workerId, worker]]),
+ shuttingDown: false,
+ stopWorker,
+ persistWorker: vi.fn(),
+ log: vi.fn(),
+ reportCleanupFailure: vi.fn(),
+ }) as {
+ scheduleWorkerStopFinalization(target: object): void;
+ };
+ const childProcessModule = await import("../src/utils/child-process.js");
+ const sessionLeaseModule = await import("../src/core/session-lease.js");
+ // The pid is alive, but it now belongs to an unrelated process.
+ const existsSpy = vi.spyOn(childProcessModule, "processIdExists").mockReturnValue(true);
+ const aliveSpy = vi.spyOn(childProcessModule, "isProcessAlive").mockReturnValue(true);
+ const killSpy = vi.spyOn(childProcessModule, "signalProcessGroupOrProcess").mockImplementation(() => {});
+ const startIdSpy = vi.spyOn(sessionLeaseModule, "getProcessStartId").mockReturnValue("proc:recycled");
+ try {
+ supervisor.scheduleWorkerStopFinalization(worker);
+ const finalization = worker.stopFinalization;
+
+ await vi.advanceTimersByTimeAsync(20_000);
+ await finalization;
+
+ // The original worker is gone, so the stop is finalized without ever
+ // signalling the unrelated pid owner.
+ expect(killSpy).not.toHaveBeenCalled();
+ expect(stopWorker).toHaveBeenCalledWith(worker, true, true, false);
+ } finally {
+ existsSpy.mockRestore();
+ aliveSpy.mockRestore();
+ killSpy.mockRestore();
+ startIdSpy.mockRestore();
+ }
+ });
+
+ it("aborts stale stop cleanup when the worker was relaunched during an await", async () => {
+ const worker = {
+ descriptor: {
+ workerId: "worker-relaunched-during-stop",
+ pid: 111_115,
+ rootActiveSessionId: "active-1",
+ stopRequestedAt: new Date().toISOString() as string | undefined,
+ archiveOnStop: true,
+ },
+ client: undefined,
+ summaries: new Map(),
+ snapshotCache: new Map(),
+ transcriptCaches: new Map(),
+ snapshotGenerations: new Map(),
+ snapshotLoads: new Map(),
+ intentionalStop: true,
+ stopRevision: 0,
+ };
+ const workers = new Map([[worker.descriptor.workerId, worker]]);
+ const supervisor = Object.assign(Object.create(DaemonSupervisor.prototype), {
+ workers,
+ shuttingDown: false,
+ persistWorker: vi.fn(),
+ persistWorkerStopTombstone: vi.fn(),
+ reclaimStoppedWorkerCronLock: vi.fn(),
+ // Archival yields, and a retry relaunches the worker meanwhile.
+ finalizeArchivedWorkerStop: vi.fn(async () => {
+ worker.descriptor.pid = 222_222;
+ worker.descriptor.stopRequestedAt = undefined;
+ }),
+ deleteWorkerDescriptor: vi.fn(),
+ syncAgentPeers: vi.fn(async () => {}),
+ broadcastHeartbeatsChanged: vi.fn(),
+ log: vi.fn(),
+ reportCleanupFailure: vi.fn(),
+ }) as unknown as {
+ stopWorker(
+ target: object,
+ removeDescriptor: boolean,
+ force?: boolean,
+ archiveSession?: boolean,
+ ): Promise<void>;
+ deleteWorkerDescriptor: ReturnType<typeof vi.fn>;
+ };
+ const childProcessModule = await import("../src/utils/child-process.js");
+ const existsSpy = vi.spyOn(childProcessModule, "processIdExists").mockReturnValue(false);
+ const aliveSpy = vi.spyOn(childProcessModule, "isProcessAlive").mockReturnValue(false);
+ try {
+ await expect(supervisor.stopWorker(worker, true, true, true)).rejects.toThrow("was relaunched during stop");
+
+ // The relaunched worker's registration and descriptor must survive.
+ expect(workers.has(worker.descriptor.workerId)).toBe(true);
+ expect(supervisor.deleteWorkerDescriptor).not.toHaveBeenCalled();
+ } finally {
+ existsSpy.mockRestore();
+ aliveSpy.mockRestore();
+ }
+ });
+
+ it("aborts stale stop cleanup when the stop is rescinded before the relaunch lands", async () => {
+ const worker = {
+ descriptor: {
+ workerId: "worker-rescinded-during-stop",
+ pid: 111_120,
+ rootActiveSessionId: "active-1",
+ stopRequestedAt: new Date().toISOString() as string | undefined,
+ archiveOnStop: true,
+ },
+ client: undefined,
+ summaries: new Map(),
+ snapshotCache: new Map(),
+ transcriptCaches: new Map(),
+ snapshotGenerations: new Map(),
+ snapshotLoads: new Map(),
+ intentionalStop: true,
+ stopRevision: 0,
+ };
+ const workers = new Map([[worker.descriptor.workerId, worker]]);
+ const supervisor = Object.assign(Object.create(DaemonSupervisor.prototype), {
+ workers,
+ shuttingDown: false,
+ persistWorker: vi.fn(),
+ persistWorkerStopTombstone: vi.fn(),
+ reclaimStoppedWorkerCronLock: vi.fn(),
+ // A retry rescinds the tombstone while archival yields, before
+ // recoverWorker has assigned the successor pid.
+ finalizeArchivedWorkerStop: vi.fn(async () => {
+ worker.descriptor.stopRequestedAt = undefined;
+ }),
+ deleteWorkerDescriptor: vi.fn(),
+ syncAgentPeers: vi.fn(async () => {}),
+ broadcastHeartbeatsChanged: vi.fn(),
+ log: vi.fn(),
+ reportCleanupFailure: vi.fn(),
+ }) as unknown as {
+ stopWorker(
+ target: object,
+ removeDescriptor: boolean,
+ force?: boolean,
+ archiveSession?: boolean,
+ ): Promise<void>;
+ deleteWorkerDescriptor: ReturnType<typeof vi.fn>;
+ };
+ const childProcessModule = await import("../src/utils/child-process.js");
+ const existsSpy = vi.spyOn(childProcessModule, "processIdExists").mockReturnValue(false);
+ const aliveSpy = vi.spyOn(childProcessModule, "isProcessAlive").mockReturnValue(false);
+ try {
+ await expect(supervisor.stopWorker(worker, true, true, true)).rejects.toThrow("was relaunched during stop");
+
+ // The revived registration and descriptor must survive for recovery.
+ expect(workers.has(worker.descriptor.workerId)).toBe(true);
+ expect(supervisor.deleteWorkerDescriptor).not.toHaveBeenCalled();
+ } finally {
+ existsSpy.mockRestore();
+ aliveSpy.mockRestore();
+ }
+ });
+
+ it("never signals an identity-less worker pid during a forced stop", async () => {
+ vi.useFakeTimers();
+ const worker = {
+ descriptor: {
+ workerId: "worker-force-missing-identity",
+ pid: 111_122,
+ rootActiveSessionId: "active-1",
+ stopRequestedAt: new Date().toISOString(),
+ },
+ client: undefined,
+ summaries: new Map(),
+ snapshotCache: new Map(),
+ transcriptCaches: new Map(),
+ snapshotGenerations: new Map(),
+ snapshotLoads: new Map(),
+ intentionalStop: true,
+ stopRevision: 0,
+ };
+ const supervisor = Object.assign(Object.create(DaemonSupervisor.prototype), {
+ workers: new Map([[worker.descriptor.workerId, worker]]),
+ shuttingDown: false,
+ persistWorker: vi.fn(),
+ persistWorkerStopTombstone: vi.fn(),
+ scheduleWorkerStopFinalization: vi.fn(),
+ syncAgentPeers: vi.fn(async () => {}),
+ broadcastHeartbeatsChanged: vi.fn(),
+ }) as unknown as {
+ stopWorker(target: object, removeDescriptor: boolean, force?: boolean): Promise<void>;
+ scheduleWorkerStopFinalization: ReturnType<typeof vi.fn>;
+ };
+ const existsSpy = vi.spyOn(childProcessModule, "processIdExists").mockReturnValue(true);
+ const aliveSpy = vi.spyOn(childProcessModule, "isProcessAlive").mockReturnValue(true);
+ const killSpy = vi.spyOn(childProcessModule, "signalProcessGroupOrProcess").mockImplementation(() => {});
+ try {
+ const stopping = supervisor.stopWorker(worker, true, true).then(
+ () => undefined,
+ (error: unknown) => error,
+ );
+ await vi.advanceTimersByTimeAsync(2000);
+
+ const error = await stopping;
+ expect(error).toBeInstanceOf(Error);
+ expect((error as Error).message).toBe("Session worker worker-force-missing-identity did not stop");
+ expect(killSpy).not.toHaveBeenCalled();
+ expect(supervisor.scheduleWorkerStopFinalization).toHaveBeenCalledWith(worker);
+ } finally {
+ existsSpy.mockRestore();
+ aliveSpy.mockRestore();
+ killSpy.mockRestore();
+ }
+ });
+
+ it("re-verifies identity at SIGKILL time even within the throttle window", async () => {
+ vi.useFakeTimers();
+ const worker = {
+ descriptor: {
+ workerId: "worker-kill-window-recycle",
+ pid: 111_118,
+ processStartId: "proc:original",
+ rootActiveSessionId: "active-1",
+ stopRequestedAt: new Date().toISOString(),
+ },
+ intentionalStop: true,
+ stopRevision: 0,
+ stopFinalization: undefined as Promise<void> | undefined,
+ };
+ const workers = new Map([[worker.descriptor.workerId, worker]]);
+ const stopWorker = vi.fn(async () => {
+ workers.delete(worker.descriptor.workerId);
+ });
+ const supervisor = Object.assign(Object.create(DaemonSupervisor.prototype), {
+ workers,
+ shuttingDown: false,
+ stopWorker,
+ persistWorker: vi.fn(),
+ log: vi.fn(),
+ reportCleanupFailure: vi.fn(),
+ }) as {
+ scheduleWorkerStopFinalization(target: object): void;
+ };
+ const childProcessModule = await import("../src/utils/child-process.js");
+ const sessionLeaseModule = await import("../src/core/session-lease.js");
+ const existsSpy = vi.spyOn(childProcessModule, "processIdExists").mockReturnValue(true);
+ const aliveSpy = vi.spyOn(childProcessModule, "isProcessAlive").mockReturnValue(true);
+ const killSpy = vi.spyOn(childProcessModule, "signalProcessGroupOrProcess").mockImplementation(() => {});
+ // The worker is current on the throttled polls, but the pid is recycled
+ // by the time the SIGKILL deadline arrives.
+ const startIdSpy = vi.spyOn(sessionLeaseModule, "getProcessStartId").mockReturnValue("proc:original");
+ try {
+ supervisor.scheduleWorkerStopFinalization(worker);
+ await vi.advanceTimersByTimeAsync(4900);
+ startIdSpy.mockReturnValue("proc:recycled");
+ await vi.advanceTimersByTimeAsync(2000);
+
+ // The fresh check at signal time sees the recycled pid and holds fire.
+ expect(killSpy).not.toHaveBeenCalled();
+ } finally {
+ existsSpy.mockRestore();
+ aliveSpy.mockRestore();
+ killSpy.mockRestore();
+ startIdSpy.mockRestore();
+ }
+ });
+
+ it("retries SIGKILL after a transient identity outage at the deadline", async () => {
+ vi.useFakeTimers();
+ const worker = {
+ descriptor: {
+ workerId: "worker-kill-retry",
+ pid: 111_119,
+ processStartId: "proc:original",
+ rootActiveSessionId: "active-1",
+ stopRequestedAt: new Date().toISOString(),
+ },
+ intentionalStop: true,
+ stopRevision: 0,
+ stopFinalization: undefined as Promise<void> | undefined,
+ };
+ const workers = new Map([[worker.descriptor.workerId, worker]]);
+ const stopWorker = vi.fn(async () => {
+ workers.delete(worker.descriptor.workerId);
+ });
+ const supervisor = Object.assign(Object.create(DaemonSupervisor.prototype), {
+ workers,
+ shuttingDown: false,
+ stopWorker,
+ persistWorker: vi.fn(),
+ log: vi.fn(),
+ reportCleanupFailure: vi.fn(),
+ }) as {
+ scheduleWorkerStopFinalization(target: object): void;
+ };
+ const childProcessModule = await import("../src/utils/child-process.js");
+ const sessionLeaseModule = await import("../src/core/session-lease.js");
+ const existsSpy = vi.spyOn(childProcessModule, "processIdExists").mockReturnValue(true);
+ let alive = true;
+ const aliveSpy = vi.spyOn(childProcessModule, "isProcessAlive").mockImplementation(() => alive);
+ const killSpy = vi.spyOn(childProcessModule, "signalProcessGroupOrProcess").mockImplementation((_pid, signal) => {
+ if (signal === "SIGKILL") {
+ alive = false;
+ }
+ });
+ // Identity observation is down when the SIGKILL deadline passes...
+ const startIdSpy = vi.spyOn(sessionLeaseModule, "getProcessStartId").mockReturnValue(undefined);
+ try {
+ supervisor.scheduleWorkerStopFinalization(worker);
+ const finalization = worker.stopFinalization;
+
+ await vi.advanceTimersByTimeAsync(8000);
+ expect(killSpy).not.toHaveBeenCalled();
+
+ // ...but once identity is observable again, escalation still fires.
+ startIdSpy.mockReturnValue("proc:original");
+ await vi.advanceTimersByTimeAsync(5000);
+ await finalization;
+ expect(killSpy).toHaveBeenCalledWith(worker.descriptor.pid, "SIGKILL");
+ expect(stopWorker).toHaveBeenCalled();
+ } finally {
+ existsSpy.mockRestore();
+ aliveSpy.mockRestore();
+ killSpy.mockRestore();
+ startIdSpy.mockRestore();
+ }
+ });
+
+ it("keeps waiting when process identity is transiently unobservable", async () => {
+ vi.useFakeTimers();
+ const worker = {
+ descriptor: {
+ workerId: "worker-unknown-identity-stop",
+ pid: 111_114,
+ processStartId: "proc:original",
+ rootActiveSessionId: "active-1",
+ stopRequestedAt: new Date().toISOString(),
+ },
+ intentionalStop: true,
+ stopRevision: 0,
+ stopFinalization: undefined as Promise<void> | undefined,
+ };
+ const stopWorker = vi.fn(async () => {});
+ const supervisor = Object.assign(Object.create(DaemonSupervisor.prototype), {
+ workers: new Map([[worker.descriptor.workerId, worker]]),
+ shuttingDown: false,
+ stopWorker,
+ persistWorker: vi.fn(),
+ log: vi.fn(),
+ reportCleanupFailure: vi.fn(),
+ }) as {
+ scheduleWorkerStopFinalization(target: object): void;
+ };
+ const childProcessModule = await import("../src/utils/child-process.js");
+ const sessionLeaseModule = await import("../src/core/session-lease.js");
+ const existsSpy = vi.spyOn(childProcessModule, "processIdExists").mockReturnValue(true);
+ const aliveSpy = vi.spyOn(childProcessModule, "isProcessAlive").mockReturnValue(true);
+ const killSpy = vi.spyOn(childProcessModule, "signalProcessGroupOrProcess").mockImplementation(() => {});
+ // Identity observation fails transiently (e.g. ps unavailable).
+ const startIdSpy = vi.spyOn(sessionLeaseModule, "getProcessStartId").mockReturnValue(undefined);
+ try {
+ supervisor.scheduleWorkerStopFinalization(worker);
+
+ await vi.advanceTimersByTimeAsync(20_000);
+
+ // The possibly-live worker is neither signalled nor cleaned up.
+ expect(killSpy).not.toHaveBeenCalled();
+ expect(stopWorker).not.toHaveBeenCalled();
+ expect(worker.stopFinalization).toBeDefined();
+ } finally {
+ existsSpy.mockRestore();
+ aliveSpy.mockRestore();
+ killSpy.mockRestore();
+ startIdSpy.mockRestore();
+ }
+ });
+
+ it("never SIGKILLs an identity-less worker pid", async () => {
+ vi.useFakeTimers();
+ const worker = {
+ descriptor: {
+ workerId: "worker-missing-identity",
+ pid: 111_121,
+ rootActiveSessionId: "active-1",
+ stopRequestedAt: new Date().toISOString(),
+ },
+ intentionalStop: true,
+ stopRevision: 0,
+ stopFinalization: undefined as Promise<void> | undefined,
+ };
+ const stopWorker = vi.fn(async () => {});
+ const supervisor = Object.assign(Object.create(DaemonSupervisor.prototype), {
+ workers: new Map([[worker.descriptor.workerId, worker]]),
+ shuttingDown: false,
+ stopWorker,
+ persistWorker: vi.fn(),
+ log: vi.fn(),
+ reportCleanupFailure: vi.fn(),
+ }) as {
+ scheduleWorkerStopFinalization(target: object): void;
+ };
+ const childProcessModule = await import("../src/utils/child-process.js");
+ const sessionLeaseModule = await import("../src/core/session-lease.js");
+ const existsSpy = vi.spyOn(childProcessModule, "processIdExists").mockReturnValue(true);
+ const aliveSpy = vi.spyOn(childProcessModule, "isProcessAlive").mockReturnValue(true);
+ const killSpy = vi.spyOn(childProcessModule, "signalProcessGroupOrProcess").mockImplementation(() => {});
+ const startIdSpy = vi.spyOn(sessionLeaseModule, "getProcessStartId").mockReturnValue("proc:unrelated");
+ try {
+ supervisor.scheduleWorkerStopFinalization(worker);
+
+ await vi.advanceTimersByTimeAsync(20_000);
+
+ expect(killSpy).not.toHaveBeenCalled();
+ expect(stopWorker).not.toHaveBeenCalled();
+ expect(worker.stopFinalization).toBeDefined();
+ } finally {
+ existsSpy.mockRestore();
+ aliveSpy.mockRestore();
+ killSpy.mockRestore();
+ startIdSpy.mockRestore();
+ }
+ });
+
+ it("retries finalization after a transient cleanup failure", async () => {
+ vi.useFakeTimers();
+ const worker = {
+ descriptor: {
+ workerId: "worker-transient-cleanup",
+ pid: process.pid,
+ rootActiveSessionId: "active-1",
+ stopRequestedAt: new Date().toISOString(),
+ },
+ intentionalStop: true,
+ stopRevision: 0,
+ stopFinalization: undefined as Promise<void> | undefined,
+ };
+ const workers = new Map([[worker.descriptor.workerId, worker]]);
+ const stopWorker = vi
+ .fn(async () => {
+ workers.delete(worker.descriptor.workerId);
+ })
+ .mockImplementationOnce(async () => {
+ throw new Error("archive temporarily unavailable");
+ });
+ const supervisor = Object.assign(Object.create(DaemonSupervisor.prototype), {
+ workers,
+ shuttingDown: false,
+ stopWorker,
+ persistWorker: vi.fn(),
+ log: vi.fn(),
+ reportCleanupFailure: vi.fn(),
+ }) as {
+ scheduleWorkerStopFinalization(target: object): void;
+ };
+ const childProcessModule = await import("../src/utils/child-process.js");
+ const aliveSpy = vi.spyOn(childProcessModule, "isProcessAlive").mockReturnValue(false);
+ try {
+ supervisor.scheduleWorkerStopFinalization(worker);
+ const finalization = worker.stopFinalization;
+
+ await vi.advanceTimersByTimeAsync(20_000);
+ await finalization;
+
+ // The first attempt failed transiently; the registration is still
+ // cleaned up by a retry instead of being stranded forever.
+ expect(stopWorker).toHaveBeenCalledTimes(2);
+ expect(workers.size).toBe(0);
+ } finally {
+ aliveSpy.mockRestore();
+ }
+ });
+
+ it("leaves a rescinded stop to the retry flow instead of finalizing it", async () => {
+ vi.useFakeTimers();
+ const worker = {
+ descriptor: {
+ workerId: "worker-rescinded-stop",
+ pid: process.pid,
+ rootActiveSessionId: "active-1",
+ stopRequestedAt: new Date().toISOString() as string | undefined,
+ },
+ intentionalStop: true,
+ stopRevision: 0,
+ stopFinalization: undefined as Promise<void> | undefined,
+ };
+ let alive = true;
+ const stopWorker = vi.fn(async () => {});
+ const supervisor = Object.assign(Object.create(DaemonSupervisor.prototype), {
+ workers: new Map([[worker.descriptor.workerId, worker]]),
+ shuttingDown: false,
+ stopWorker,
+ persistWorker: vi.fn(),
+ log: vi.fn(),
+ reportCleanupFailure: vi.fn(),
+ }) as {
+ scheduleWorkerStopFinalization(target: object): void;
+ };
+ const childProcessModule = await import("../src/utils/child-process.js");
+ const aliveSpy = vi.spyOn(childProcessModule, "isProcessAlive").mockImplementation(() => alive);
+ try {
+ supervisor.scheduleWorkerStopFinalization(worker);
+ const finalization = worker.stopFinalization;
+
+ // An explicit retry revives the worker while its process is exiting.
+ worker.descriptor.stopRequestedAt = undefined;
+ worker.intentionalStop = false;
+ alive = false;
+ await vi.advanceTimersByTimeAsync(500);
+ await finalization;
+
+ expect(stopWorker).not.toHaveBeenCalled();
+ } finally {
+ aliveSpy.mockRestore();
+ }
+ });
+
it("ignores malformed persisted worker descriptors", () => {
const descriptorDir = mkdtempSync(join(tmpdir(), "prime-supervisor-descriptor-test-"));
try {
diff --git a/packages/coding-agent/test/daemon-supervisor-process.test.ts b/packages/coding-agent/test/daemon-supervisor-process.test.ts
index e013e9d134..3f2d7d8fde 100644
--- a/packages/coding-agent/test/daemon-supervisor-process.test.ts
+++ b/packages/coding-agent/test/daemon-supervisor-process.test.ts
@@ -827,6 +827,71 @@ describe("daemon supervisor resident workers", () => {
await waitForSocketGone(socketPath);
}, 30_000);
+ it(
+ "finalizes a timed-out worker stop by force-stopping the process and removing its registration",
+ { tags: ["process-stress"], timeout: 45_000 },
+ async () => {
+ const root = tempDir();
+ const agentDir = join(root, "agent");
+ const projectDir = join(root, "project");
+ const sessionDir = join(agentDir, "sessions");
+ const socketPath = join(
+ tmpdir(),
+ `prime-supervisor-stop-finalize-${process.pid}-${randomUUID().slice(0, 8)}.sock`,
+ );
+ mkdirSync(projectDir, { recursive: true });
+ const sessionManager = SessionManager.create(projectDir, sessionDir);
+ sessionManager.appendMessage({ role: "user", content: "finalize me", timestamp: 1 });
+ const sessionFile = sessionManager.getSessionFile();
+ if (!sessionFile) {
+ throw new Error("Fixture session did not persist");
+ }
+
+ const supervisor = spawnSupervisor(agentDir, socketPath, projectDir);
+ const client = await connectEventually(socketPath, supervisor);
+ const created = await client.request({
+ type: "create",
+ sessionPath: sessionFile,
+ lifecycle: "client_owned",
+ config: { cwd: projectDir, agentDir, sessionDir, noTools: true, noExtensions: true },
+ });
+ if (!created.success) {
+ throw new Error(created.error);
+ }
+ const summary = requireSummary(created.data);
+ if (!summary.workerPid) {
+ throw new Error("Resident worker did not expose its pid");
+ }
+ workerPids.add(summary.workerPid);
+ const activeSessionId = summary.activeSessionId ?? summary.id;
+
+ // A suspended worker cannot exit within the stop deadline, so the stop
+ // times out and used to leave a tombstoned registration behind forever.
+ process.kill(summary.workerPid, "SIGSTOP");
+ const stopResult = await client.request({ type: "complete_owned_session", activeSessionId }, 30_000);
+ expect(stopResult).toMatchObject({
+ success: false,
+ error: expect.stringContaining("did not stop"),
+ });
+ const tombstone = readWorkerDescriptor(agentDir);
+ expect(tombstone.stopRequestedAt).toEqual(expect.any(String));
+
+ // The supervisor finishes the interrupted stop on its own: it escalates
+ // to SIGKILL, waits for the process to die, and removes the registration.
+ await waitForProcessGone(summary.workerPid);
+ workerPids.delete(summary.workerPid);
+ await waitForCondition(
+ () => countWorkerDescriptors(agentDir) === 0,
+ "Timed-out worker stop was not finalized",
+ 20_000,
+ );
+
+ await client.request({ type: "shutdown" });
+ client.close();
+ await waitForSocketGone(socketPath);
+ },
+ );
+
it(
"does not resurrect an intentionally stopped root when the supervisor dies during kill",
{ tags: ["process-stress"], timeout: 30_000 },