diff --git a/server/src/services/heartbeat/recovery.ts b/server/src/services/heartbeat/recovery.ts index 4e5a0a08afd..27ac5659e84 100644 --- a/server/src/services/heartbeat/recovery.ts +++ b/server/src/services/heartbeat/recovery.ts @@ -9,7 +9,7 @@ import { recordNativeLocalProcessStop } from "../native-local-process-stop.js"; import { legacyControllerBootId, hasLiveLegacyController, - revokeExpiredLegacyController, + revokeExpiredLegacyControllerWithState, } from "../legacy-controller-lease.js"; import { remoteTerminationReceipt } from "../remote-execution-termination.js"; import { runUsedConversationAdapter } from "../conversation-continuation.js"; @@ -2314,24 +2314,27 @@ export function createHeartbeatRecovery(db: Db, dependencies: HeartbeatRecoveryD readNonEmptyString(runContext.wakeReason) === "issue_monitor_due" && monitorNextCheckAt !== undefined && (!monitorNextCheckAt || monitorNextCheckAt.getTime() <= now.getTime()); + const revokedState = await revokeExpiredLegacyControllerWithState(db, run); + if (!revokedState) continue; // 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. + // Use the state committed with the revocation, not the earlier snapshot: + // the old controller may have dispatched before its lease expired. + // The revocation matched the snapshot's boot ID before replacing it. const restartInterruptedBeforeDispatch = run.runtimeMode === "legacy" && - run.executionStage === "preparing" && + revokedState.executionStage === "preparing" && !!run.controllerBootId && run.controllerBootId !== legacyControllerBootId && - !run.processPid && - !run.processGroupId; + !revokedState.processPid && + !revokedState.processGroupId; const shouldRetry = (run.processLossRetryCount ?? 0) < 1 && ((tracksLegacyLocalChild && (!!run.processPid || !!run.processGroupId)) || restartInterruptedBeforeDispatch || monitorDispatchLostWithoutFutureWake); - if (!(await revokeExpiredLegacyController(db, run))) continue; const baseMessage = buildProcessLossMessage(run); const processLossDiagnostic = buildProcessLossDiagnostic({ run, diff --git a/server/src/services/legacy-controller-lease.test.ts b/server/src/services/legacy-controller-lease.test.ts index d2e4b2e2c40..2280f70dd0e 100644 --- a/server/src/services/legacy-controller-lease.test.ts +++ b/server/src/services/legacy-controller-lease.test.ts @@ -5,7 +5,8 @@ import { agents, companies, createDb, heartbeatRuns } from "@paperclipai/db"; import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../__tests__/helpers/embedded-postgres.js"; import { heartbeatService } from "./heartbeat.js"; import { hasLiveLegacyController, LEGACY_CONTROLLER_RENEW_MS, legacyControllerBootId, legacyControllerClaim, LegacyControllerLeaseLostError, - renewLegacyControllerLease, revokeExpiredLegacyController, watchLegacyControllerLease } from "./legacy-controller-lease.js"; + renewLegacyControllerLease, revokeExpiredLegacyController, revokeExpiredLegacyControllerWithState, + watchLegacyControllerLease } from "./legacy-controller-lease.js"; const support = await getEmbeddedPostgresTestSupport(); (support.supported ? describe : describe.skip)("durable legacy controller ownership", () => { @@ -79,6 +80,16 @@ const support = await getEmbeddedPostgresTestSupport(); expect(attempts.filter(Boolean)).toHaveLength(1); expect(await renewLegacyControllerLease(db, run)).toBe(false); }); + it("revocation reports the committed dispatch boundary instead of the caller's stale snapshot", async () => { + const stale = await seed(); + expect(await renewLegacyControllerLease(db, stale, "dispatching")).toBe(true); + await expire(stale.id); + expect(stale.executionStage).toBe("preparing"); + expect(await revokeExpiredLegacyControllerWithState(db, stale)).toEqual({ + executionStage: "dispatching", processPid: null, processGroupId: null, + }); + expect(await revokeExpiredLegacyControllerWithState(db, stale)).toBeNull(); + }); it("a crash after revocation permits a later recovery claim", async () => { const run = await seed(); await expire(run.id); diff --git a/server/src/services/legacy-controller-lease.ts b/server/src/services/legacy-controller-lease.ts index f8ec824002c..e13e2ee2308 100644 --- a/server/src/services/legacy-controller-lease.ts +++ b/server/src/services/legacy-controller-lease.ts @@ -55,10 +55,20 @@ export async function hasLiveLegacyController(db: Db, run: Run): Promise; + /** Atomically revoke an expired controller. Renewal and revocation serialize on - * the run row. Expiry permits cleanup, never dispatch of a replacement agent. */ -export async function revokeExpiredLegacyController(db: Db, run: Run): Promise { - if (run.runtimeMode === "native" || !run.controllerBootId) return true; + * the run row. Expiry permits cleanup, never dispatch of a replacement agent. + * Returns the stage and process identifiers committed with the revocation, or + * null when another writer owns the row. They cannot advance afterwards, + * because renewal requires the replaced boot ID. */ +export async function revokeExpiredLegacyControllerWithState( + db: Db, + run: Run, +): Promise { + if (run.runtimeMode === "native" || !run.controllerBootId) { + return { executionStage: run.executionStage, processPid: run.processPid, processGroupId: run.processGroupId }; + } const [revoked] = await db.update(heartbeatRuns).set({ controllerBootId: randomUUID(), controllerLeaseExpiresAt: sql`clock_timestamp() + interval '60 seconds'`, @@ -67,8 +77,16 @@ export async function revokeExpiredLegacyController(db: Db, run: Run): Promise { + return (await revokeExpiredLegacyControllerWithState(db, run)) !== null; } /** Abort the adapter if the controller cannot renew. Bound each check by the