A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
fix(coding-agent): self-heal stale worker registrations on resume (#852)
Sebastian Müller14d6e74919a5
diff --git a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts b/packages/coding-agent/src/modes/daemon/daemon-supervisor.tsindex eae3124b16..92997edf4e 100644--- a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts+++ b/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts@@ -139,6 +139,7 @@ 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;+const STALE_RECLAIM_WAIT_MS = 10_000;// 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.@@ -2005,7 +2006,7 @@ export class DaemonSupervisor {const ownerClientId = command.lifecycle === "client_owned" ? clientId : undefined;if (command.sessionPath) {const activeMatches = this.matchWorkers(command.sessionPath);- if (activeMatches.length === 1) {+ if (activeMatches.length === 1 && !(await this.reclaimStaleWorkerRegistration(activeMatches[0]!.worker))) {return this.reuseWorkerForCreate(activeMatches[0]!.worker, ownerClientId, command.sessionPath);}if (activeMatches.length > 1) {@@ -2017,7 +2018,7 @@ export class DaemonSupervisor {: await this.catalog.resolve(command.sessionPath, config.cwd ?? process.cwd(), config.sessionDir);createCommand = { ...createCommand, sessionPath };const existing = this.findWorkerBySessionFile(sessionPath);- if (existing) {+ if (existing && !(await this.reclaimStaleWorkerRegistration(existing.worker))) {return this.reuseWorkerForCreate(existing.worker, ownerClientId, sessionPath);}// A passive child from a stopped worker reopens as top-level here (pre-existing behavior);@@ -2068,6 +2069,46 @@ export class DaemonSupervisor {throw new SessionAlreadyActiveError(sessionPath, worker.descriptor.rootActiveSessionId);}+ /**+ * A stopping worker whose process already died can strand its registration+ * (for example when the stop timed out and its finalization was interrupted+ * by a supervisor restart). Such a registration would block reopening the+ * saved transcript forever, so complete the interrupted stop and let the+ * caller launch a fresh worker for the saved session.+ */+ private async reclaimStaleWorkerRegistration(worker: ResidentWorker): Promise<boolean> {+ if (worker.client !== undefined || worker.recovery !== undefined) {+ return false;+ }+ if (worker.descriptor.stopRequestedAt === undefined) {+ return false;+ }+ // Fail fast before waiting on anything: only a confirmed-dead process is+ // reclaimable. A live, unknown, or still-stopping worker is left alone+ // and the caller reports the session as already active.+ const identity = this.processIdentity(worker.descriptor.pid, worker.descriptor.processStartId);+ if (identity !== "gone" && identity !== "replaced") {+ return false;+ }+ // Single cleanup path: the background stop finalizer is identity-aware,+ // retrying, and single-flighted, so concurrent resumes share one stop.+ // The wait is bounded so a resume request always returns promptly.+ this.scheduleWorkerStopFinalization(worker);+ const finalization = worker.stopFinalization;+ if (finalization) {+ await Promise.race([finalization.catch(() => undefined), unrefDelay(STALE_RECLAIM_WAIT_MS)]);+ }+ if (this.workers.get(worker.descriptor.workerId) === worker) {+ // The process is confirmed dead, so the registration must never be+ // reused; slow cleanup fails the resume honestly instead.+ throw new Error(+ `Stopped session worker ${worker.descriptor.workerId} is still being cleaned up; retry shortly`,+ );+ }+ this.log(`Reclaimed stale registration for stopped worker ${worker.descriptor.workerId}`);+ return true;+ }+private async promoteOwnedWorker(client: DaemonSocketClient, worker: ResidentWorker): Promise<void> {const clientId = this.protocolClientId(client);if (worker.descriptor.ownerClientId === undefined && worker.promotedOwnerClientId === clientId) {@@ -2384,6 +2425,26 @@ export class DaemonSupervisor {await this.assertRecoveryAllowed();if (worker.descriptor.stopRequestedAt) {try {+ // A descriptor persisted before identity tracking has no+ // processStartId, so stopWorker could neither signal the live+ // process nor let the finalizer escalate. Authenticating on the+ // worker's socket proves the pid still belongs to our worker, so+ // the start id observed while it was alive can be persisted (and+ // the connected client gives stopWorker its graceful IPC path).+ if (worker.descriptor.processStartId === undefined && isProcessAlive(worker.descriptor.pid)) {+ const observedProcessStartId = getProcessStartId(worker.descriptor.pid);+ try {+ await this.connectWorker(worker, 2000);+ if (observedProcessStartId) {+ worker.descriptor.processStartId = observedProcessStartId;+ this.persistWorker(worker);+ }+ } catch {+ // Unverifiable identity stays untrusted; the stop below+ // still runs its graceful path and the finalizer keeps+ // waiting rather than signalling a possibly-recycled pid.+ }+ }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) {diff --git a/packages/coding-agent/test/daemon-supervisor-monitor.test.ts b/packages/coding-agent/test/daemon-supervisor-monitor.test.tsindex 7748ef2acf..03bb76264b 100644--- a/packages/coding-agent/test/daemon-supervisor-monitor.test.ts+++ b/packages/coding-agent/test/daemon-supervisor-monitor.test.ts@@ -1803,6 +1803,72 @@ describe("daemon worker supervisor monitoring", () => {}});+ it("captures the live process identity before an adoption stop when the descriptor has none", async () => {+ const worker = {+ descriptor: {+ workerId: "worker-adopted-legacy",+ pid: process.pid,+ stopRequestedAt: new Date().toISOString(),+ archiveOnStop: false,+ } as { processStartId?: string },+ };+ const stopOrder: string[] = [];+ const supervisor = Object.assign(Object.create(DaemonSupervisor.prototype), {+ assertRecoveryAllowed: vi.fn(async () => undefined),+ connectWorker: vi.fn(async () => {+ stopOrder.push("connect");+ }),+ persistWorker: vi.fn(() => {+ stopOrder.push("persist");+ }),+ stopWorker: vi.fn(async () => {+ stopOrder.push("stop");+ }),+ log: vi.fn(),+ }) as {+ adoptOrRecoverWorker(target: object): Promise<void>;+ };++ await supervisor.adoptOrRecoverWorker(worker);++ // Identity is captured and persisted before the stop runs, so stopWorker+ // and its finalizer can signal the live process instead of waiting forever.+ expect(worker.descriptor.processStartId).toBe(getProcessStartId(process.pid));+ expect(stopOrder).toEqual(["connect", "persist", "stop"]);+ });++ it("keeps an unverifiable identity untrusted when the adoption connect fails", async () => {+ const worker = {+ descriptor: {+ workerId: "worker-adopted-unverified",+ pid: process.pid,+ stopRequestedAt: new Date().toISOString(),+ archiveOnStop: false,+ } as { processStartId?: string },+ };+ const persistWorker = vi.fn();+ const stopWorker = vi.fn(async () => {});+ const supervisor = Object.assign(Object.create(DaemonSupervisor.prototype), {+ assertRecoveryAllowed: vi.fn(async () => undefined),+ connectWorker: vi.fn(async () => {+ throw new Error("connect refused");+ }),+ persistWorker,+ stopWorker,+ log: vi.fn(),+ }) as {+ adoptOrRecoverWorker(target: object): Promise<void>;+ };++ await supervisor.adoptOrRecoverWorker(worker);++ // The pid could belong to anything; never adopt an identity the socket+ // handshake did not confirm.+ expect(worker.descriptor.processStartId).toBeUndefined();+ expect(persistWorker).not.toHaveBeenCalled();+ expect(stopWorker).toHaveBeenCalledWith(worker, true, true, false);+ });+it("finalizes a timed-out stop once the worker process dies", async () => {vi.useFakeTimers();const worker = {@@ -2477,6 +2543,268 @@ describe("daemon worker supervisor monitoring", () => {}});+ it("reclaims a stale tombstoned registration whose process is gone", async () => {+ const worker = {+ descriptor: {+ workerId: "worker-stale-registration",+ pid: process.pid,+ rootActiveSessionId: "active-1",+ stopRequestedAt: new Date().toISOString(),+ },+ client: undefined,+ recovery: undefined,+ intentionalStop: true,+ stopRevision: 0,+ };+ 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,+ stopWorker,+ log: vi.fn(),+ reportCleanupFailure: vi.fn(),+ }) as {+ reclaimStaleWorkerRegistration(target: object): Promise<boolean>;+ };+ const childProcessModule = await import("../src/utils/child-process.js");+ const aliveSpy = vi.spyOn(childProcessModule, "isProcessAlive").mockReturnValue(false);+ try {+ await expect(supervisor.reclaimStaleWorkerRegistration(worker)).resolves.toBe(true);+ expect(stopWorker).toHaveBeenCalledWith(worker, true, true, false);+ } finally {+ aliveSpy.mockRestore();+ }+ });++ it("reclaims a stale registration whose pid was recycled by another process", async () => {+ const worker = {+ descriptor: {+ workerId: "worker-recycled-registration",+ pid: 111_113,+ processStartId: "proc:original",+ rootActiveSessionId: "active-1",+ stopRequestedAt: new Date().toISOString(),+ },+ client: undefined,+ recovery: undefined,+ intentionalStop: true,+ stopRevision: 0,+ };+ 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,+ stopWorker,+ log: vi.fn(),+ reportCleanupFailure: vi.fn(),+ }) as {+ reclaimStaleWorkerRegistration(target: object): Promise<boolean>;+ };+ const childProcessModule = await import("../src/utils/child-process.js");+ const sessionLeaseModule = await import("../src/core/session-lease.js");+ // The pid is alive, but it belongs to an unrelated process now.+ const aliveSpy = vi.spyOn(childProcessModule, "isProcessAlive").mockReturnValue(true);+ const startIdSpy = vi.spyOn(sessionLeaseModule, "getProcessStartId").mockReturnValue("proc:recycled");+ try {+ await expect(supervisor.reclaimStaleWorkerRegistration(worker)).resolves.toBe(true);+ expect(stopWorker).toHaveBeenCalledWith(worker, true, true, false);+ } finally {+ aliveSpy.mockRestore();+ startIdSpy.mockRestore();+ }+ });++ it("waits for an in-flight stop finalization instead of stopping twice", async () => {+ const worker = {+ descriptor: {+ workerId: "worker-finalizing",+ pid: process.pid,+ rootActiveSessionId: "active-1",+ stopRequestedAt: new Date().toISOString(),+ },+ client: undefined,+ recovery: undefined,+ intentionalStop: true,+ stopRevision: 0,+ stopFinalization: undefined as Promise<void> | undefined,+ };+ const workers = new Map([[worker.descriptor.workerId, worker]]);+ let releaseFinalization!: () => void;+ worker.stopFinalization = new Promise<void>((resolveFinalization) => {+ releaseFinalization = () => {+ workers.delete(worker.descriptor.workerId);+ resolveFinalization();+ };+ });+ const stopWorker = vi.fn(async () => {});+ const supervisor = Object.assign(Object.create(DaemonSupervisor.prototype), {+ workers,+ stopWorker,+ log: vi.fn(),+ reportCleanupFailure: vi.fn(),+ }) as {+ reclaimStaleWorkerRegistration(target: object): Promise<boolean>;+ };++ const childProcessModule = await import("../src/utils/child-process.js");+ const aliveSpy = vi.spyOn(childProcessModule, "isProcessAlive").mockReturnValue(false);+ try {+ const reclaim = supervisor.reclaimStaleWorkerRegistration(worker);+ releaseFinalization();++ // The reclaim defers to the finalizer's cleanup instead of duplicating it.+ await expect(reclaim).resolves.toBe(true);+ expect(stopWorker).not.toHaveBeenCalled();+ } finally {+ aliveSpy.mockRestore();+ }+ });++ it("fails resume honestly when confirmed-dead cleanup outlasts the bounded wait", async () => {+ vi.useFakeTimers();+ const worker = {+ descriptor: {+ workerId: "worker-slow-cleanup",+ pid: 111_117,+ rootActiveSessionId: "active-1",+ stopRequestedAt: new Date().toISOString(),+ },+ client: undefined,+ recovery: undefined,+ intentionalStop: true,+ stopRevision: 0,+ stopFinalization: undefined as Promise<void> | undefined,+ };+ const supervisor = Object.assign(Object.create(DaemonSupervisor.prototype), {+ workers: new Map([[worker.descriptor.workerId, worker]]),+ shuttingDown: false,+ // Cleanup hangs past the bounded reclaim wait.+ stopWorker: vi.fn(() => new Promise<void>(() => {})),+ persistWorker: vi.fn(),+ log: vi.fn(),+ reportCleanupFailure: vi.fn(),+ }) as {+ reclaimStaleWorkerRegistration(target: object): Promise<boolean>;+ };+ const childProcessModule = await import("../src/utils/child-process.js");+ const aliveSpy = vi.spyOn(childProcessModule, "isProcessAlive").mockReturnValue(false);+ try {+ const reclaim = supervisor.reclaimStaleWorkerRegistration(worker);+ const outcome = reclaim.then(+ () => "reused",+ () => "failed",+ );+ await vi.advanceTimersByTimeAsync(60_000);++ // The dead registration is never handed back to the resume path.+ await expect(outcome).resolves.toBe("failed");+ } finally {+ aliveSpy.mockRestore();+ }+ });++ it("shares one stop between concurrent resume reclaims", async () => {+ const worker = {+ descriptor: {+ workerId: "worker-concurrent-reclaim",+ pid: 111_116,+ rootActiveSessionId: "active-1",+ stopRequestedAt: new Date().toISOString(),+ },+ client: undefined,+ recovery: undefined,+ 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 {+ reclaimStaleWorkerRegistration(target: object): Promise<boolean>;+ };+ const childProcessModule = await import("../src/utils/child-process.js");+ const aliveSpy = vi.spyOn(childProcessModule, "isProcessAlive").mockReturnValue(false);+ try {+ const results = await Promise.all([+ supervisor.reclaimStaleWorkerRegistration(worker),+ supervisor.reclaimStaleWorkerRegistration(worker),+ ]);++ expect(results).toEqual([true, true]);+ // Both concurrent resumes share the single-flighted finalizer stop.+ expect(stopWorker).toHaveBeenCalledTimes(1);+ } finally {+ aliveSpy.mockRestore();+ }+ });++ it("does not reclaim a stopping worker whose process is still alive", async () => {+ const worker = {+ descriptor: {+ workerId: "worker-still-alive",+ pid: process.pid,+ rootActiveSessionId: "active-1",+ stopRequestedAt: new Date().toISOString(),+ },+ client: undefined,+ recovery: undefined,+ intentionalStop: true,+ stopRevision: 0,+ };+ const stopWorker = vi.fn(async () => {});+ const supervisor = Object.assign(Object.create(DaemonSupervisor.prototype), {+ workers: new Map([[worker.descriptor.workerId, worker]]),+ stopWorker,+ log: vi.fn(),+ reportCleanupFailure: vi.fn(),+ }) as {+ reclaimStaleWorkerRegistration(target: object): Promise<boolean>;+ };+ const childProcessModule = await import("../src/utils/child-process.js");+ const aliveSpy = vi.spyOn(childProcessModule, "isProcessAlive").mockReturnValue(true);+ try {+ await expect(supervisor.reclaimStaleWorkerRegistration(worker)).resolves.toBe(false);+ expect(stopWorker).not.toHaveBeenCalled();+ } finally {+ aliveSpy.mockRestore();+ }+ });++ it("does not reclaim a healthy connected worker", async () => {+ const worker = {+ descriptor: { workerId: "worker-healthy", pid: process.pid, rootActiveSessionId: "active-1" },+ client: {},+ recovery: undefined,+ intentionalStop: false,+ stopRevision: 0,+ };+ const stopWorker = vi.fn(async () => {});+ const supervisor = Object.assign(Object.create(DaemonSupervisor.prototype), {+ workers: new Map([[worker.descriptor.workerId, worker]]),+ stopWorker,+ log: vi.fn(),+ reportCleanupFailure: vi.fn(),+ }) as {+ reclaimStaleWorkerRegistration(target: object): Promise<boolean>;+ };++ await expect(supervisor.reclaimStaleWorkerRegistration(worker)).resolves.toBe(false);+ expect(stopWorker).not.toHaveBeenCalled();+ });+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.tsindex 3f2d7d8fde..43df0e2cbf 100644--- a/packages/coding-agent/test/daemon-supervisor-process.test.ts+++ b/packages/coding-agent/test/daemon-supervisor-process.test.ts@@ -892,6 +892,91 @@ describe("daemon supervisor resident workers", () => {},);+ it(+ "resumes a saved session immediately after a worker stop fails and the process dies",+ { 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-resume-heal-${process.pid}-${randomUUID().slice(0, 8)}.sock`,+ );+ mkdirSync(projectDir, { recursive: true });+ const sessionManager = SessionManager.create(projectDir, sessionDir);+ sessionManager.appendMessage({ role: "user", content: "resume 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 forces the stop past its deadline, leaving a+ // tombstoned registration for a process that dies moments later.+ 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"),+ });+ process.kill(summary.workerPid, "SIGKILL");+ await waitForProcessGone(summary.workerPid);+ workerPids.delete(summary.workerPid);++ // Resuming the saved transcript must not be blocked by the stale+ // registration. Whichever cleanup wins the race — the background stop+ // finalizer or the resume-time reclaim (each covered deterministically+ // by unit tests) — the user-visible guarantee is the same: the resume+ // below must succeed with a fresh worker.+ const resumed = await client.request({+ type: "create",+ sessionPath: sessionFile,+ config: { cwd: projectDir, agentDir, sessionDir, noTools: true, noExtensions: true },+ });+ expect(resumed.success).toBe(true);+ const resumedSummary = requireSummary(resumed.success ? resumed.data : undefined);+ expect(resumedSummary.sessionId).toBe(summary.sessionId);+ expect(resumedSummary.workerPid).not.toBe(summary.workerPid);+ expect(resumedSummary.workerState).toBe("ready");+ if (resumedSummary.workerPid) {+ workerPids.add(resumedSummary.workerPid);+ }++ const attached = await client.request({+ type: "attach",+ activeSessionId: resumedSummary.activeSessionId ?? resumedSummary.id,+ });+ expect(attached.success).toBe(true);++ await client.request({ type: "shutdown" });+ client.close();+ await waitForSocketGone(socketPath);+ if (resumedSummary.workerPid) {+ await waitForProcessGone(resumedSummary.workerPid);+ workerPids.delete(resumedSummary.workerPid);+ }+ },+ );+it("does not resurrect an intentionally stopped root when the supervisor dies during kill",{ tags: ["process-stress"], timeout: 30_000 },