From c654932b02b8ffcc702b55d6a9888ccc0394c7e6 Mon Sep 17 00:00:00 2001 From: Devin Foley <139239+devinfoley@users.noreply.github.com> Date: Thu, 15 Oct 2026 00:16:32 +0000 Subject: [PATCH] fix(heartbeat): retry legacy runs a restart stopped before dispatch A hard server restart can kill the process after it claims a legacy run but before the adapter dispatch renewal. The next boot reaps the run after its controller lease expires. The run has no pid and no bootstrap evidence, so it settles failed/process_lost, schedules no retry, and legacy recovery holds it for operator reconciliation. The dispatch renewal persists executionStage "dispatching" in the same update that admits the adapter. An expired lease from another boot that is still "preparing" therefore proves that provider work never started. Record bootstrap evidence for that case and use the bounded process-loss retry. Keep the retried restart interruption out of unexpected-mode Sentry run-failure reports. Fixes PAPERCLIP-BACKEND-3A Co-Authored-By: Claude Opus 5.5 --- .../heartbeat-process-recovery.test.ts | 66 +++++++++++++++++++ .../__tests__/run-failure-report.test.ts | 46 +++++++++++++ server/src/services/heartbeat/recovery.ts | 20 +++++- server/src/services/run-failure-report.ts | 20 +++++- 4 files changed, 150 insertions(+), 2 deletions(-) diff --git a/server/src/__tests__/heartbeat-process-recovery.test.ts b/server/src/__tests__/heartbeat-process-recovery.test.ts index ea30fdea2c4..46c9e3de558 100644 --- a/server/src/__tests__/heartbeat-process-recovery.test.ts +++ b/server/src/__tests__/heartbeat-process-recovery.test.ts @@ -3250,6 +3250,72 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => { expect(retries).toHaveLength(0); }); + // A hard restart can kill the server after it claimed a legacy run but before + // the adapter dispatch renewal, leaving an expired lease from another boot. + async function seedRestartOrphanedLegacySetup(executionStage: "preparing" | "dispatching") { + const fixture = await seedRunFixture({ + adapterType: "paperclip_runner", + agentStatus: "idle", + runtimeMode: "legacy", + }); + await db.update(heartbeatRuns).set({ + controllerBootId: randomUUID(), + controllerLeaseExpiresAt: sql`clock_timestamp() - interval '1 second'`, + executionStage, + }).where(eq(heartbeatRuns.id, fixture.runId)); + return fixture; + } + + it("retries a legacy run that a restart stopped before adapter dispatch", async () => { + const { companyId, runId, issueId } = await seedRestartOrphanedLegacySetup("preparing"); + + const heartbeat = heartbeatService(db); + const result = await heartbeat.reapOrphanedRuns(); + + expect(result).toEqual({ reaped: 1, runIds: [runId] }); + const [reaped] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)); + expect(reaped).toMatchObject({ + status: "failed", + errorCode: "process_lost", + error: "Process lost -- server may have restarted; retrying once", + }); + expect(reaped?.resultJson).toMatchObject({ + executionRecovery: { kind: "bootstrap", providerWorkStarted: false }, + processLossDiagnostic: { localCheck: "no_identifiers", retryEligible: true, runPredatesObserver: true }, + }); + const retries = await db.select().from(heartbeatRuns).where(and( + eq(heartbeatRuns.companyId, companyId), + eq(heartbeatRuns.retryOfRunId, runId), + )); + expect(retries).toEqual([expect.objectContaining({ status: "scheduled_retry" })]); + expect(await db.select().from(issueRecoveryActions) + .where(eq(issueRecoveryActions.sourceIssueId, issueId))).toEqual([]); + expect(mockAdapterExecute).not.toHaveBeenCalled(); + }); + + it("keeps an orphaned legacy run that reached adapter dispatch held for reconciliation", async () => { + const { companyId, runId, issueId } = await seedRestartOrphanedLegacySetup("dispatching"); + + const heartbeat = heartbeatService(db); + await heartbeat.reapOrphanedRuns(); + + const [reaped] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)); + expect(reaped).toMatchObject({ + status: "failed", + errorCode: "process_lost", + error: "Process lost -- server may have restarted", + }); + expect(reaped?.resultJson).not.toHaveProperty("executionRecovery"); + expect(await db.select().from(heartbeatRuns).where(and( + eq(heartbeatRuns.companyId, companyId), + eq(heartbeatRuns.retryOfRunId, runId), + ))).toEqual([]); + expect(await db.select().from(issueRecoveryActions) + .where(eq(issueRecoveryActions.sourceIssueId, issueId))).toEqual([ + expect.objectContaining({ cause: "legacy_execution_requires_reconciliation" }), + ]); + }); + async function withTempPaperclipHome( fn: (home: string) => Promise, ): Promise { diff --git a/server/src/services/__tests__/run-failure-report.test.ts b/server/src/services/__tests__/run-failure-report.test.ts index 0914b1a2e3d..038f2b6fd32 100644 --- a/server/src/services/__tests__/run-failure-report.test.ts +++ b/server/src/services/__tests__/run-failure-report.test.ts @@ -393,6 +393,52 @@ describeEmbeddedPostgres("reportRunFailure", () => { expect(mockCaptureRunFailure).toHaveBeenCalledOnce(); }); + function restartInterruptedSetupRun(overrides: Partial = {}) { + return buildRun({ + error: "Process lost -- server may have restarted; retrying once", + runtimeMode: "legacy", executionStage: "preparing", processPid: null, processGroupId: null, + resultJson: { + executionRecovery: { kind: "bootstrap", providerWorkStarted: false }, + processLossDiagnostic: { + pidRecorded: false, groupRecorded: false, localCheck: "no_identifiers", + retryEligible: true, runPredatesObserver: true, + }, + }, + ...overrides, + }); + } + + it("keeps a retried restart interruption of legacy setup local", async () => { + await seedCompanyAndAgent({ adapterType: "paperclip_runner" }); + await reportRunFailure(db, restartInterruptedSetupRun()); + expect(mockCaptureRunFailure).not.toHaveBeenCalled(); + }); + + it("reports a retried restart interruption of legacy setup in all mode", async () => { + vi.stubEnv("PAPERCLIP_SENTRY_RUN_FAILURES", "all"); + await seedCompanyAndAgent({ adapterType: "paperclip_runner" }); + await reportRunFailure(db, restartInterruptedSetupRun()); + expect(mockCaptureRunFailure).toHaveBeenCalledOnce(); + }); + + it.each([ + { executionStage: "dispatching" }, { runtimeMode: "native" }, { processPid: 4242 }, + { errorCode: "adapter_failed" }, + { resultJson: { processLossDiagnostic: { localCheck: "no_identifiers", retryEligible: true, runPredatesObserver: true } } }, + { resultJson: { + executionRecovery: { kind: "bootstrap", providerWorkStarted: false }, + processLossDiagnostic: { localCheck: "no_identifiers", retryEligible: false, runPredatesObserver: true }, + } }, + { resultJson: { + executionRecovery: { kind: "bootstrap", providerWorkStarted: false }, + processLossDiagnostic: { localCheck: "no_identifiers", retryEligible: true, runPredatesObserver: false }, + } }, + ])("reports process loss without restart-before-dispatch evidence: %j", async (overrides) => { + await seedCompanyAndAgent({ adapterType: "paperclip_runner" }); + await reportRunFailure(db, restartInterruptedSetupRun(overrides)); + expect(mockCaptureRunFailure).toHaveBeenCalledOnce(); + }); + async function expiredGrokOffer(input: { wakes: Array<{ status: "rejected" | "accepted" | "acknowledged" | "unknown"; httpStatus: number | null }>; acceptedAt?: Date | null; diff --git a/server/src/services/heartbeat/recovery.ts b/server/src/services/heartbeat/recovery.ts index 4a6db618b5a..4e5a0a08afd 100644 --- a/server/src/services/heartbeat/recovery.ts +++ b/server/src/services/heartbeat/recovery.ts @@ -2314,10 +2314,22 @@ export function createHeartbeatRecovery(db: Db, dependencies: HeartbeatRecoveryD readNonEmptyString(runContext.wakeReason) === "issue_monitor_due" && monitorNextCheckAt !== undefined && (!monitorNextCheckAt || monitorNextCheckAt.getTime() <= now.getTime()); + // A legacy controller persists "dispatching" in the same lease renewal + // that admits the adapter. An expired lease from another boot that is + // still "preparing" proves a restart stopped setup before provider work. + // Read the boot ID before revocation replaces it. + const restartInterruptedBeforeDispatch = + run.runtimeMode === "legacy" && + run.executionStage === "preparing" && + !!run.controllerBootId && + run.controllerBootId !== legacyControllerBootId && + !run.processPid && + !run.processGroupId; const shouldRetry = (run.processLossRetryCount ?? 0) < 1 && ((tracksLegacyLocalChild && (!!run.processPid || !!run.processGroupId)) || + restartInterruptedBeforeDispatch || monitorDispatchLostWithoutFutureWake); if (!(await revokeExpiredLegacyController(db, run))) continue; const baseMessage = buildProcessLossMessage(run); @@ -2344,7 +2356,13 @@ export function createHeartbeatRecovery(db: Db, dependencies: HeartbeatRecoveryD "failed", { conversationContinuationEligible, - resultJson: { ...parseObject(run.resultJson), processLossDiagnostic }, + resultJson: { + ...parseObject(run.resultJson), + processLossDiagnostic, + ...(restartInterruptedBeforeDispatch + ? { executionRecovery: { kind: "bootstrap", providerWorkStarted: false } } + : {}), + }, errorCode: "process_lost", errorMessage: shouldRetry ? `${baseMessage}; retrying once` diff --git a/server/src/services/run-failure-report.ts b/server/src/services/run-failure-report.ts index abf0152adf3..0fe6b277688 100644 --- a/server/src/services/run-failure-report.ts +++ b/server/src/services/run-failure-report.ts @@ -166,6 +166,23 @@ function isHermesConnectionFailure(run: HeartbeatRun, options: RunFailureReportO (connection.reason === "remote_unavailable" && code === "hermes_gateway_upstream_error"); } +/** + * The orphan reaper proved a server restart stopped legacy setup before + * dispatch and made the run eligible for its bounded retry. Only that reaper + * branch pairs process loss with bootstrap evidence. + */ +function isRestartInterruptedSetup(run: HeartbeatRun): boolean { + if ( + run.status !== "failed" || run.errorCode !== "process_lost" || run.runtimeMode !== "legacy" || + run.executionStage !== "preparing" || run.processPid != null || run.processGroupId != null + ) return false; + const recovery = asRecord(run.resultJson?.executionRecovery); + const processLoss = asRecord(run.resultJson?.processLossDiagnostic); + return recovery?.kind === "bootstrap" && recovery.providerWorkStarted === false && + processLoss?.retryEligible === true && processLoss.runPredatesObserver === true && + processLoss.localCheck === "no_identifiers"; +} + /** * The adapter proved the user's provider account is out of quota, and recovery * waits for its reset. Both fields come from the adapter's own classifier. @@ -218,7 +235,8 @@ export function reportRunFailure(db: Db, run: HeartbeatRun, options: RunFailureR isAiConnectionSelectionBlocker(run, options) || isLocalPathWorkspaceConfigurationBlocker(run, options) || isGitConnectionFailure(run, options) || - isProviderQuotaFailure(run, options) + isProviderQuotaFailure(run, options) || + isRestartInterruptedSetup(run) )) return Promise.resolve(); const runStatus = run.status; const report = captureTerminalRunFailure(db, run, runStatus, options, mode);