diff --git a/server/src/__tests__/agent-run-authentication.test.ts b/server/src/__tests__/agent-run-authentication.test.ts index fe2da4eb363..40c6e79985d 100644 --- a/server/src/__tests__/agent-run-authentication.test.ts +++ b/server/src/__tests__/agent-run-authentication.test.ts @@ -78,12 +78,16 @@ const support = await getEmbeddedPostgresTestSupport(); contextSnapshot: { prompt: payload, conversationMode: true } }).where(eq(heartbeatRuns.id, runId)); const [row] = await loadAgentRunAuthentication(db, input); expect(contract(row)).toEqual(contract(await baseline())); - expect(row.resultJson).toEqual({ executionCancellation: { state: null } }); + expect(row.resultJson).toEqual({ executionCancellation: { state: null }, freshContinuationSupersededAt: null }); expect(row.contextSnapshot).toEqual({ conversationMode: true }); expect(Buffer.byteLength(JSON.stringify(row))).toBeLessThan(512); await db.update(heartbeatRuns).set({ resultJson: { executionCancellation: { state: "requested" } } }) .where(eq(heartbeatRuns.id, runId)); expect(agentRunWritesRevoked((await loadAgentRunAuthentication(db, input))[0])).toBe(true); + // A run that a fresh continuation replaced loses its writes too. + await db.update(heartbeatRuns).set({ status: "failed", resultJson: { freshContinuationSupersededAt: new Date().toISOString() } }) + .where(eq(heartbeatRuns.id, runId)); + expect(agentRunWritesRevoked((await loadAgentRunAuthentication(db, input))[0])).toBe(true); }); it("does not return another company, agent, or run", async () => { diff --git a/server/src/__tests__/assigned-work-invariant.test.ts b/server/src/__tests__/assigned-work-invariant.test.ts index 1f1d296eaed..5dca17b02fe 100644 --- a/server/src/__tests__/assigned-work-invariant.test.ts +++ b/server/src/__tests__/assigned-work-invariant.test.ts @@ -320,11 +320,11 @@ describePostgres("assigned-work invariant sweep", () => { expect(enqueueWakeup).toHaveBeenCalledTimes(3); }, 60_000); - it("with the real wake queue, a hold that defers the continuation leaves a violation that is retried no faster than the cap", async () => { - // Current master without a fresh-continuation fallback: the task's last - // run left a legacy reconciliation hold, so admission defers the ordinary - // continuation wake. Nothing pending is left behind, so it stays a - // violation, is retried with spacing, and never loops faster than the cap. + it("with the real wake queue, a hold reached by the sweep's wake becomes one pending fresh continuation", async () => { + // The task's last run left a legacy reconciliation hold. The sweep's + // ordinary continuation wake reaches the fresh-continuation fallback, + // which settles the hold and records one pending continuation (owned by + // the execution-continuation worker). The next sweep adds no attempt. const f = await seedCompany(); const issueId = await f.issue(); const run = await f.run(issueId, { status: "failed", errorCode: "process_lost", livenessState: "failed" }); @@ -344,9 +344,12 @@ describePostgres("assigned-work invariant sweep", () => { const [entry] = await db.select().from(activityLog).where(and(eq(activityLog.entityId, issueId), eq(activityLog.action, ASSIGNED_WORK_CONTINUED_ACTION))); expect(entry.details).toMatchObject({ outcome: "not_started" }); - // A second sweep right away is spaced, not another attempt. + const [record] = await db.select().from(issueRecoveryActions).where(and(eq(issueRecoveryActions.sourceIssueId, issueId), + sqlTag`${issueRecoveryActions.evidence}->'freshContinuation' is not null`)); + expect(record!.evidence).toMatchObject({ continuationDelivery: "pending" }); + // A second sweep right away adds no attempt. expect(await heartbeat.checkAssignedWorkInvariant({ companyId: f.companyId, issueId })) - .toMatchObject({ outcome: "deferred_rate_limit", verdict: { kind: "violation" } }); + .not.toMatchObject({ outcome: "repaired" }); expect(await db.select().from(activityLog).where(and(eq(activityLog.entityId, issueId), eq(activityLog.action, ASSIGNED_WORK_CONTINUED_ACTION)))).toHaveLength(1); } finally { diff --git a/server/src/__tests__/heartbeat-native-restart-suspension.test.ts b/server/src/__tests__/heartbeat-native-restart-suspension.test.ts index 0790a358428..ce5753dea9e 100644 --- a/server/src/__tests__/heartbeat-native-restart-suspension.test.ts +++ b/server/src/__tests__/heartbeat-native-restart-suspension.test.ts @@ -934,7 +934,10 @@ describeEmbeddedPostgres("heartbeat native recovery interrupted by graceful shut try { const dispositions = await claimNativeRestartRecoveries({ db: f.db, restartKind: "hard", runIds: [f.runId], onClaim }); expect(probe.observed).toEqual([]); - expect(dispositions).toEqual([{ kind: "awaiting_evidence", runId: f.runId, reason: "controller_process_space_unverified" }]); + // Only a lapsed lease starts the bounded wait that ends the run. + expect(dispositions).toEqual([{ kind: "awaiting_evidence", runId: f.runId, reason: "controller_process_space_unverified", + // Every wait is rechecked; only a lapsed lease starts the bounded end. + retryAt: expect.any(Date) }]); expect(onClaim).not.toHaveBeenCalled(); const [after] = await f.db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, f.runId)); expect(after).toMatchObject({ leaseOwner: before.leaseOwner, leaseExpiresAt: before.leaseExpiresAt, @@ -959,7 +962,7 @@ describeEmbeddedPostgres("heartbeat native recovery interrupted by graceful shut const probe = observeOwnerPid(), onClaim = vi.fn(); try { expect(await claimNativeRestartRecoveries({ db: f.db, restartKind: "hard", runIds: [f.runId], onClaim })) - .toEqual([{ kind: "awaiting_evidence", runId: f.runId, reason: "controller_process_space_unverified" }]); + .toEqual([{ kind: "awaiting_evidence", runId: f.runId, reason: "controller_process_space_unverified", retryAt: expect.any(Date) }]); expect(probe.observed).toEqual([]); expect(onClaim).not.toHaveBeenCalled(); const [after] = await f.db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, f.runId)); @@ -1018,7 +1021,7 @@ describeEmbeddedPostgres("heartbeat native recovery interrupted by graceful shut controllerProcessStartedAt: current.processStartedAt }).where(eq(nativeRunFinalizations.runId, f.runId)); const onClaim = vi.fn(); const dispositions = await claimNativeRestartRecoveries({ db: f.db, restartKind: "hard", runIds: [f.runId], onClaim }); - expect(dispositions).toEqual([{ kind: "awaiting_evidence", runId: f.runId, reason: "controller_still_alive" }]); + expect(dispositions).toEqual([{ kind: "awaiting_evidence", runId: f.runId, reason: "controller_still_alive", retryAt: expect.any(Date) }]); expect(onClaim).not.toHaveBeenCalled(); }, 60_000); @@ -1146,7 +1149,7 @@ describeEmbeddedPostgres("heartbeat native recovery interrupted by graceful shut const probe = observeOwnerPid(); try { expect(await claimNativeRestartRecoveries({ db: f.db, restartKind: "hard", runIds: [f.runId] })) - .toEqual([{ kind: "awaiting_evidence", runId: f.runId, reason: "native_finalization_or_cleanup_owner" }]); + .toEqual([{ kind: "awaiting_evidence", runId: f.runId, reason: "native_finalization_or_cleanup_owner", retryAt: expect.any(Date) }]); expect(probe.observed).toEqual([]); expect(await f.db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, f.issueId))).toEqual([]); } finally { probe.restore(); } @@ -1161,7 +1164,7 @@ describeEmbeddedPostgres("heartbeat native recovery interrupted by graceful shut const probe = observeOwnerPid(); try { expect(await claimNativeRestartRecoveries({ db: f.db, restartKind: "hard", runIds: [f.runId] })) - .toEqual([{ kind: "awaiting_evidence", runId: f.runId, reason: "remote_controller_process_space_unverified" }]); + .toEqual([{ kind: "awaiting_evidence", runId: f.runId, reason: "remote_controller_process_space_unverified", retryAt: expect.any(Date) }]); expect(probe.observed).toEqual([]); const [action] = await f.db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, f.issueId)); expect(action.evidence.controllerAuthority).toBeUndefined(); @@ -1545,7 +1548,7 @@ describeEmbeddedPostgres("heartbeat native recovery interrupted by graceful shut const probe = observeOwnerPid(); try { expect(await claimNativeRestartRecoveries({ db: f.db, restartKind: "hard", runIds: [f.runId] })) - .toEqual([{ kind: "awaiting_evidence", runId: f.runId, reason: "remote_controller_process_space_unverified" }]); + .toEqual([{ kind: "awaiting_evidence", runId: f.runId, reason: "remote_controller_process_space_unverified", retryAt: expect.any(Date) }]); expect(probe.observed).toEqual([]); const [action] = await f.db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, f.issueId)); expect(action.evidence.controllerAuthority).toBeUndefined(); @@ -1561,7 +1564,7 @@ describeEmbeddedPostgres("heartbeat native recovery interrupted by graceful shut const unreadable = vi.spyOn(controllerProcess, "currentProcessSpaceHash").mockReturnValue("unknown"); try { expect(await claimNativeRestartRecoveries({ db: f.db, restartKind: "hard", runIds: [f.runId] })) - .toEqual([{ kind: "awaiting_evidence", runId: f.runId, reason: "controller_process_space_unverified" }]); + .toEqual([{ kind: "awaiting_evidence", runId: f.runId, reason: "controller_process_space_unverified", retryAt: expect.any(Date) }]); } finally { unreadable.mockRestore(); } const [attention] = await f.db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, f.issueId)); const probe = observeOwnerPid(); diff --git a/server/src/__tests__/issue-monitor-scheduler.test.ts b/server/src/__tests__/issue-monitor-scheduler.test.ts index 3915b80fcad..75b3973a6eb 100644 --- a/server/src/__tests__/issue-monitor-scheduler.test.ts +++ b/server/src/__tests__/issue-monitor-scheduler.test.ts @@ -28,6 +28,7 @@ import { startEmbeddedPostgresTestDatabase, } from "./helpers/embedded-postgres.js"; import { heartbeatService } from "../services/heartbeat.ts"; +import { deliverReconciledExecutions } from "../services/execution-recovery-resolution.ts"; import { normalizeIssueExecutionPolicy, parseIssueExecutionState } from "../services/issue-execution-policy.ts"; import { PaperclipRunnerToolAuthority } from "../services/native-runtime/paperclip-runner-tool-authority.js"; @@ -329,8 +330,11 @@ describeEmbeddedPostgres("issue monitor scheduler", () => { expect((await db.select().from(agentWakeupRequests)).filter(wake => wake.reason === "issue_monitor_due")).toHaveLength(1); }); - it("explains held monitor dispatch without replaying uncertain execution", async () => { - const { companyId, issueId, agentId, nextCheckAt } = await seedFixture(); + // Before the fresh-continuation fallback this hold deferred the monitor for + // a person. The due monitor is an ordinary continuation: it now settles the + // hold and starts one fresh run, without replaying the interrupted execution. + it("continues a held task in a fresh run when its monitor is due, without replaying uncertain execution", async () => { + const { companyId, issueId, agentId } = await seedFixture(); const sourceRunId = randomUUID(); await db.insert(heartbeatRuns).values({ id: sourceRunId, companyId, agentId, runtimeMode: "legacy", status: "interrupted", errorCode: "process_lost", @@ -341,26 +345,19 @@ describeEmbeddedPostgres("issue monitor scheduler", () => { evidence: { runId: sourceRunId }, nextAction: "Inspect the interrupted execution before continuing." }).returning(); const heartbeat = heartbeatService(db); const tickAt = new Date("2026-04-11T12:31:00.000Z"); - expect((await heartbeat.tickTimers(tickAt)).enqueued).toBe(0); - expect((await heartbeat.tickTimers(new Date(tickAt.getTime() + 30_000))).enqueued).toBe(0); - const [waiting] = await db.select().from(issues).where(eq(issues.id, issueId)); - expect(waiting.monitorNextCheckAt).toEqual(nextCheckAt); - expect(waiting.monitorWakeRequestedAt).toBeNull(); - expect(waiting.monitorAttemptCount).toBe(0); - expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.agentId, agentId))).toHaveLength(1); - const diagnostics = (await db.select().from(activityLog).where(eq(activityLog.entityId, issueId))) - .filter(row => row.action === "issue.monitor_deferred"); - expect(diagnostics).toHaveLength(1); - expect(diagnostics[0]?.details).toMatchObject({ nextCheckAt: nextCheckAt.toISOString(), - reason: "execution_reconciliation_required", blockerCause: "legacy_execution_requires_reconciliation", attemptCount: 0 }); - expect((await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, hold!.id)))[0]?.status).toBe("active"); - await db.update(issueRecoveryActions).set({ status: "resolved", resolvedAt: new Date(), - evidence: { runId: sourceRunId, executionReconciliation: { action: "continue" } } }).where(eq(issueRecoveryActions.id, hold!.id)); - expect((await heartbeat.tickTimers(new Date(tickAt.getTime() + 60_000))).enqueued).toBe(1); - expect((await heartbeat.tickTimers(new Date(tickAt.getTime() + 90_000))).enqueued).toBe(0); - const [triggered] = await db.select().from(issues).where(eq(issues.id, issueId)); - expect(triggered.monitorAttemptCount).toBe(1); - expect(triggered.monitorNextCheckAt).toBeNull(); + // The due monitor reaches the fallback, which records one pending fresh + // continuation and coalesces the monitor wake into it. + await heartbeat.tickTimers(tickAt); + const [settled] = await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, hold!.id)); + expect(settled).toMatchObject({ status: "resolved", outcome: "restored" }); + expect(settled!.evidence).toMatchObject({ continuationDelivery: "pending", + freshContinuation: { sourceRunId, trigger: "continuation_wake" } }); + // The continuation worker starts it once, as a fresh session. + await deliverReconciledExecutions(db, heartbeat.wakeup); + await deliverReconciledExecutions(db, heartbeat.wakeup); + const successors = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.retryOfRunId, sourceRunId)); + expect(successors).toHaveLength(1); + expect(successors[0]!.contextSnapshot).toMatchObject({ forceFreshSession: true, previousRunId: sourceRunId }); }); it("recovers a rejected native monitor call and delivers the corrected schedule once", async () => { diff --git a/server/src/agent-run-cancellation.ts b/server/src/agent-run-cancellation.ts index b49e7155848..6d65bae980f 100644 --- a/server/src/agent-run-cancellation.ts +++ b/server/src/agent-run-cancellation.ts @@ -2,16 +2,25 @@ import { and, eq, inArray } from "drizzle-orm"; import { caseHandoffs, heartbeatRuns, type Db } from "@paperclipai/db"; import { forbidden } from "./errors.js"; -/** Stop revokes write authority before waiting for the executor to settle. */ +/** Stop revokes write authority before waiting for the executor to settle. + * A run that a fresh continuation replaced loses it too: its agent may still + * be alive in an unreachable sandbox, and only the new run acts on the task. */ export function agentRunWritesRevoked(run: { status: string; resultJson?: Record | null; } | null | undefined): boolean { const cancellation = run?.resultJson?.executionCancellation; - return run?.status === "cancelled" || Boolean(cancellation && typeof cancellation === "object" + return run?.status === "cancelled" || agentRunSupersededByFreshContinuation(run) || Boolean(cancellation && typeof cancellation === "object" && "state" in cancellation && cancellation.state === "requested"); } +/** Recorded by the fresh-continuation fallback on the run it replaced. */ +export const FRESH_CONTINUATION_SUPERSEDED_KEY = "freshContinuationSupersededAt"; + +export function agentRunSupersededByFreshContinuation(run: { resultJson?: Record | null } | null | undefined) { + return typeof run?.resultJson?.[FRESH_CONTINUATION_SUPERSEDED_KEY] === "string"; +} + /** The caller must supply its write transaction, so Stop and commit serialize. */ export async function assertAgentRunWriteAllowed(tx: Db, companyId: string, actor: { agentId?: string | null; @@ -27,6 +36,9 @@ export async function assertAgentRunWriteAllowed(tx: Db, companyId: string, acto .for("share"); const stoppedForThisMutation = run?.status === "cancelled" && actor.stopId && run.resultJson?.issueMutationStopId === actor.stopId; + if (agentRunSupersededByFreshContinuation(run)) { + throw forbidden("A newer run continues this task. End the turn.", { code: "agent_run_superseded" }); + } if (agentRunWritesRevoked(run) && !stoppedForThisMutation) { throw forbidden("This run was cancelled", { code: "agent_run_cancelled" }); } diff --git a/server/src/middleware/agent-run-authentication.ts b/server/src/middleware/agent-run-authentication.ts index d130e9e706b..58634b3702b 100644 --- a/server/src/middleware/agent-run-authentication.ts +++ b/server/src/middleware/agent-run-authentication.ts @@ -13,7 +13,8 @@ export function loadAgentRunAuthentication(db: Db, input: { resultJson: sql>`jsonb_build_object( 'executionCancellation', jsonb_build_object( 'state', ${heartbeatRuns.resultJson}->'executionCancellation'->'state' - ) + ), + 'freshContinuationSupersededAt', ${heartbeatRuns.resultJson}->'freshContinuationSupersededAt' )`, contextSnapshot: sql>`jsonb_build_object( 'conversationMode', ${heartbeatRuns.contextSnapshot}->'conversationMode' diff --git a/server/src/middleware/auth.ts b/server/src/middleware/auth.ts index 60ca593d153..c55103703b2 100644 --- a/server/src/middleware/auth.ts +++ b/server/src/middleware/auth.ts @@ -23,7 +23,7 @@ import { rekeyCompanyIssueIdentifiers, } from "../services/issue-prefix.js"; import { verifyLocalAgentJwt } from "../agent-auth-jwt.js"; -import { agentRunWritesRevoked } from "../agent-run-cancellation.js"; +import { agentRunSupersededByFreshContinuation, agentRunWritesRevoked } from "../agent-run-cancellation.js"; import { loadAgentRunAuthentication } from "./agent-run-authentication.js"; import { isUuidLike, normalizeAgentApiKeyScope, type DeploymentMode } from "@paperclipai/shared"; import type { BetterAuthSessionResult } from "../auth/better-auth.js"; @@ -405,6 +405,10 @@ export function actorMiddleware(db: Db, opts: ActorMiddlewareOptions): RequestHa if (agentRunWritesRevoked(identityRun) && !["GET", "HEAD", "OPTIONS"].includes(req.method)) { const conversation = identityRun?.contextSnapshot?.conversationMode === true; + if (agentRunSupersededByFreshContinuation(identityRun)) { + _res.status(403).json({ error: "A newer run continues this task. End the turn.", code: "agent_run_superseded" }); + return; + } _res.status(403).json({ error: conversation ? "This conversation turn was cancelled" : "This run was cancelled", code: conversation ? "conversation_turn_cancelled" : "agent_run_cancelled" }); return; diff --git a/server/src/modules/wake-queue/adapters/postgres.ts b/server/src/modules/wake-queue/adapters/postgres.ts index 59dce5b560f..95341f6bf18 100644 --- a/server/src/modules/wake-queue/adapters/postgres.ts +++ b/server/src/modules/wake-queue/adapters/postgres.ts @@ -927,8 +927,9 @@ async function recordNativeTerminalRecoveryIfNeeded(tx: Db, run: ReleaseRun, iss cause: "native_continuation_requires_reconciliation", fingerprint: `native-continuation:${run.id}`, evidence: { runId: run.id, originalFailureCode: run.errorCode, ...(nativeFailureBlock ? { nativeFailureBlock } : {}) }, - nextAction: - "Inspect the original failure and reconcile the previous execution before continuing. Automatic recovery cannot start another incident.", + // The fresh-continuation fallback settles this hold unless its cause is + // the person's; the text never asks anyone to repair the run. + nextAction: "The run stopped before it finished. Paperclip continues the task from its last saved work.", maxAttempts: 3, wakePolicy: null, supersedeOnIdentityChange: true, diff --git a/server/src/services/execution-control-work.ts b/server/src/services/execution-control-work.ts index b0c7ca75ce7..69981ba1647 100644 --- a/server/src/services/execution-control-work.ts +++ b/server/src/services/execution-control-work.ts @@ -5,6 +5,7 @@ import type { createDeliveryWorkCoordinator } from "./delivery-work-coordinator. import { type DeliveryQueue } from "./delivery-work-notifications.js"; import { EXECUTION_RECONCILIATION_INTERVAL_MS } from "./execution-control-deadline.js"; import { obsoleteExecutionConversationHold, unresolvedExecutionDispositions } from "./execution-recovery-resolution.js"; +import { heldExecutionsAwaitingFreshContinuation, nextFreshContinuationCheckAt } from "./fresh-continuation-fallback.js"; import { hasPendingNativeReplacements } from "./native-runtime/native-safe-replacement.js"; import { nextAbandonedNativeOwnerReleaseAt } from "./native-runtime/native-failed-run-owner-release.js"; import { hasPendingPauseResume } from "./issue-tree-resume.js"; @@ -103,11 +104,14 @@ export function executionControlSchedule(db: Db) { return rows.length ? retry() : null; }, async disposition() { - const [conversation, execution] = await Promise.all([ + const now = new Date(); + const [conversation, execution, held, nextCheck] = await Promise.all([ db.select({ id: issueRecoveryActions.id }).from(issueRecoveryActions).where(obsoleteExecutionConversationHold()).limit(1), unresolvedExecutionDispositions(db, 1), + heldExecutionsAwaitingFreshContinuation(db, now, 1), + nextFreshContinuationCheckAt(db), ]); - return conversation.length || execution.length ? retry() : null; + return conversation.length || execution.length || held.length ? retry() : deadline([nextCheck ? new Date(nextCheck) : null]); }, async localLogin() { const rows = await db.select({ at: adapterAuthSessions.expiresAt }).from(adapterAuthSessions).where(and( diff --git a/server/src/services/execution-projection.ts b/server/src/services/execution-projection.ts index 8eb8ad22eac..06a351c7162 100644 --- a/server/src/services/execution-projection.ts +++ b/server/src/services/execution-projection.ts @@ -360,10 +360,16 @@ export function projectExecution( ) { if (recoveryAction.evidence.continuationDelivery === "invalidated") { projection.cause = "continuation_ownership_changed"; - projection.nextAction = - "The task was closed or reassigned before delivery. Inspect the current task owner and status."; + projection.nextAction = "The task changed before this continuation started, so it was not started."; return set("failed", "Continuation cancelled"); } + // A hold the fresh-continuation fallback settled together with another: + // the task continues through that record. + if (recoveryAction.evidence.continuationDelivery === "coalesced") { + projection.cause = null; + projection.nextAction = "Paperclip continues the task in a fresh run from its saved work."; + return set("queued", "Continuing automatically"); + } const reconciliation = recoveryAction.evidence.executionReconciliation; if (recoveryAction.cause === "native_restart_recovery_blocked" && recoveryAction.evidence.reason === "controller_process_space_unverified" @@ -390,10 +396,13 @@ export function projectExecution( projection.cause = null; projection.nextAction = deliveredRunId ? null - : "The previous execution is reconciled. Its continuation is queued for delivery."; + : recoveryAction.evidence.freshContinuationSettlement + ? "Paperclip continues the task in a fresh run from its saved work." + : "The previous execution is reconciled. Its continuation is queued for delivery."; return set( deliveredRunId ? "completed" : "queued", - deliveredRunId ? "Continued in another run" : "Continuation queued", + deliveredRunId ? "Continued in another run" + : recoveryAction.evidence.freshContinuationSettlement ? "Continuing automatically" : "Continuation queued", ); } if ( diff --git a/server/src/services/execution-recovery-resolution.ts b/server/src/services/execution-recovery-resolution.ts index e59f05c18f5..5002ee9c15f 100644 --- a/server/src/services/execution-recovery-resolution.ts +++ b/server/src/services/execution-recovery-resolution.ts @@ -36,6 +36,8 @@ import { hasRequiredWorkspaceRecovery } from "./workspace-restore-recovery-state import { hasRemoteTerminationReceipt } from "./remote-execution-termination.js"; import { readSystemRecovery } from "./system-recovery-state.js"; import { provenGoneLegacyControllerBootId } from "./legacy-controller-lease.js"; +import { continueFreshInTransaction, continueHeldExecutions, freshContinuationCheckDue, recordFreshContinuationCheck, + settleCoalescedFreshContinuationHolds } from "./fresh-continuation-fallback.js"; import { alias } from "drizzle-orm/pg-core"; /** An operator records observed outcomes; this is not permission to blindly retry. */ @@ -397,8 +399,28 @@ export async function deliverReconciledExecutions( evidence: sql`${issueRecoveryActions.evidence} || '{"continuationDelivery":"invalidated"}'::jsonb`, }) .where(pendingDecision); + await settleCoalescedFreshContinuationHolds(db, { companyId: action.companyId, primaryId: action.id, delivery: "invalidated" }); continue; } + // A fresh continuation is the task's next run only while nothing else + // started one: a person's Retry or saved input that ran since it was + // recorded already continues the task, so it is never a second run. + const fresh = action.evidence.freshContinuation as { recordedAt?: unknown } | undefined; + if (fresh && typeof fresh.recordedAt === "string") { + const [newer] = await db.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(and( + eq(heartbeatRuns.companyId, action.companyId), sql`${heartbeatRuns.id}::text <> ${decision.runId}`, + or(eq(heartbeatRuns.nativeIssueId, task.id), eq(heartbeatRuns.issueId, task.id), + sql`${heartbeatRuns.contextSnapshot}->>'issueId' = ${task.id}::text`), + sql`${heartbeatRuns.createdAt} >= ${fresh.recordedAt}::timestamptz`)).limit(1); + if (newer) { + await db.update(issueRecoveryActions).set({ evidence: sql`${issueRecoveryActions.evidence} || ${JSON.stringify( + { continuationDelivery: "delivered", continuationRunId: newer.id, continuationSupersededByRun: true })}::jsonb` }) + .where(pendingDecision); + await settleCoalescedFreshContinuationHolds(db, { companyId: action.companyId, primaryId: action.id, + delivery: "delivered", continuationRunId: newer.id }); + continue; + } + } const run = await wake(action.returnOwnerAgentId, { source: "automation", triggerDetail: "system", @@ -416,6 +438,8 @@ export async function deliverReconciledExecutions( forceFreshSession: true, wakeReason: "issue_recovery_action_restored", source: "execution.reconciled", + ...((action.evidence.freshContinuation as { isolation?: unknown } | undefined)?.isolation === "fresh_isolated_workspace" + ? { freshContinuationIsolation: action.id } : {}), }, }); if (run) @@ -443,6 +467,8 @@ export async function deliverReconciledExecutions( )}::jsonb`, }) .where(pendingDecision); + await settleCoalescedFreshContinuationHolds(tx as unknown as Db, { companyId: action.companyId, primaryId: action.id, + delivery: "delivered", continuationRunId: run.id }); }); } catch { logger.warn( @@ -499,6 +525,8 @@ export function unresolvedExecutionDispositions(db: Db, limit: number) { sql`not (${issueRecoveryActions.evidence} ? 'systemRecovery')`, inArray(issueRecoveryActions.status, ["active", "escalated"]), eq(issueRecoveryActions.kind, "active_run_watchdog"), + // A fresh continuation that backed off is checked again when due. + freshContinuationCheckDue(new Date()), or(inArray(issueRecoveryActions.cause, [...EXECUTION_RECONCILIATION_CAUSES]), and( eq(heartbeatRuns.runtimeMode, "native"), eq(heartbeatRuns.nativePhase, "terminal_failure"), eq(nativeRunFinalizations.phase, "terminal_failure"), isNull(nativeRunFinalizations.nextAttemptAt), @@ -700,6 +728,20 @@ export async function settleUnrecoverableExecutions( !["done", "cancelled"].includes(task.status) && (!task.executionRunId || task.executionRunId === run.id) && (!task.checkoutRunId || task.checkoutRunId === run.id); + // Exact recovery is ruled out. Unless the cause is the person's, the + // task continues in a fresh run from its last saved work instead of + // waiting for a person. + // A preparation that never started provider work keeps its own replay + // lane, which takes over the settled hold; the held sweep follows it. + if (current && !isInterruptedNativePreparationCandidate(run)) { + const fresh = await continueFreshInTransaction(tx as unknown as Db, { companyId: task.companyId, runId: run.id, + trigger: "recovery_refused", now }); + if (["continued", "already_continued", "successor_exists"].includes(fresh.kind)) return; + if (fresh.kind === "backoff" || fresh.kind === "exact_recovery_pending") { + await recordFreshContinuationCheck(tx as unknown as Db, { companyId: task.companyId, actionId: action.id }, fresh, now); + return; + } + } const note = executionRecoverySettlementNote({ current, cause: action.cause, workspaceRestoreFailed: hasWorkspaceRestoreFailure(run.resultJson), trigger: action.evidence.trigger }); await notifyUnsafeWorkspaceExportRecovery(tx, { companyId: task.companyId, issueId: task.id }); @@ -803,4 +845,7 @@ export async function settleUnrecoverableExecutions( ); } } + // Tasks already held by settled records (including those older releases + // saved) continue from their saved work on this worker too. + await continueHeldExecutions(db, now); } diff --git a/server/src/services/fresh-continuation-fallback.test.ts b/server/src/services/fresh-continuation-fallback.test.ts new file mode 100644 index 00000000000..21a67499d96 --- /dev/null +++ b/server/src/services/fresh-continuation-fallback.test.ts @@ -0,0 +1,838 @@ +import { randomUUID } from "node:crypto"; +import { and, eq, sql } from "drizzle-orm"; +import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest"; +import { + activityLog, agentWakeupRequests, agents, approvals, authUsers, companies, createDb, environmentLeases, environments, executionWorkspaces, heartbeatRuns, issueApprovals, issueRecoveryActions, issueThreadInteractions, + issues, nativeRunFinalizations, toolInvocations, +} from "@paperclipai/db"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../__tests__/helpers/embedded-postgres.js"; +import { deliverReconciledExecutions, settleUnrecoverableExecutions } from "./execution-recovery-resolution.js"; +import { getExecutionBlocker } from "./execution-blocker.js"; +import { + FRESH_CONTINUATIONS_PER_HOUR, FRESH_CONTINUATION_SCHEMA, PERSON_OWNED_FAILURE_CODES, continueHeldExecutions, ensureFreshContinuation, + freshContinuationNote, heldExecutionsAwaitingFreshContinuation, nextFreshContinuationCheckAt, recordFreshContinuationCheck, FRESH_CONTINUATION_PENDING_BOUND_MS, FRESH_CONTINUATION_PROGRESS_BOUND_MS, FRESH_CONTINUATION_SAVED_WORK_BOUND_MS, +} from "./fresh-continuation-fallback.js"; +import { heartbeatService } from "./heartbeat.js"; +import { buildExecutionContinuation } from "./execution-continuation.js"; +import { currentProcessSpaceHash } from "./controller-process-identity.js"; +import { executionControlSchedule } from "./execution-control-work.js"; +import { readFreshWorkspaceReadiness } from "./fresh-workspace-continuation.js"; +import { taskInterruptionPresentation } from "./task-interruption-presentation.js"; +import { agentRunWritesRevoked, assertAgentRunWriteAllowed } from "../agent-run-cancellation.js"; +import { loadAgentRunAuthentication } from "../middleware/agent-run-authentication.js"; +import { SERVER_RESTART_RETRY_MAX_ATTEMPTS, SERVER_RESTART_RETRY_WINDOW_MS } from "./execution-recovery-attempt.js"; +import { FRESH_CONTINUATION_WINDOW_MS } from "./fresh-continuation-fallback.js"; + +const support = await getEmbeddedPostgresTestSupport(); +const suite = support.supported ? describe : describe.skip; + +// Copy shown to people never asks them to inspect or repair a sandbox, workspace or run. +const adminText = /sandbox|inspect|repair|administrator|reconcile/i; + +type Seed = { + runtime: "native" | "legacy"; status?: "failed" | "interrupted" | "timed_out" | "cancelled"; + errorCode: string; error?: string; + /** How today's code leaves the run: an active hold (before disposition) or a settled-but-blocked hold (older releases). */ + hold?: "active" | "settled_blocked" | "none"; + coordinatorState?: string; +}; + +suite("fresh-continuation fallback", () => { + let db!: ReturnType; + let temporary: Awaited> | null = null; + let companyId = "", agentId = "", userId = ""; + + beforeAll(async () => { + temporary = await startEmbeddedPostgresTestDatabase("paperclip-fresh-continuation-"); + db = createDb(temporary.connectionString); + companyId = randomUUID(); agentId = randomUUID(); userId = randomUUID(); + await db.insert(authUsers).values({ id: userId, name: "Board", email: `${userId}@example.test`, + emailVerified: true, createdAt: new Date(), updatedAt: new Date() }); + await db.insert(companies).values({ id: companyId, name: "Paperclip", issuePrefix: "FCF", + requireBoardApprovalForNewAgents: false, defaultResponsibleUserId: userId }); + await db.insert(agents).values({ id: agentId, companyId, name: "Coder", role: "engineer", status: "idle", + adapterType: "paperclip_runner", adapterConfig: {}, runtimeConfig: { heartbeat: { maxConcurrentRuns: 1 } }, permissions: {} }); + }, 60_000); + + afterEach(async () => { + await db.execute(sql`truncate table issue_recovery_actions, native_run_finalizations, tool_invocations, + issue_approvals, approvals, issue_thread_interactions, activity_log, agent_wakeup_requests, environment_leases, execution_workspaces, heartbeat_runs, issues cascade`); + }); + + afterAll(async () => { await db?.$client.end(); await temporary?.cleanup(); }); + + /** A run that ended without finishing, in the shape today's release leaves it. */ + async function unfinishedRun(seed: Seed) { + const issueId = randomUUID(), runId = randomUUID(); + const finishedAt = new Date(Date.now() - 60_000); + await db.insert(issues).values({ id: issueId, companyId, title: "Ship the release notes", status: "blocked", + assigneeAgentId: agentId, statusVersion: 4, blockedTransitionAt: finishedAt }); + await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, invocationSource: "assignment", issueId, + nativeIssueId: seed.runtime === "native" ? issueId : null, runtimeMode: seed.runtime, + status: seed.status ?? "failed", errorCode: seed.errorCode, error: seed.error ?? seed.errorCode, + startedAt: new Date(finishedAt.getTime() - 10 * 60_000), finishedAt, createdAt: new Date(finishedAt.getTime() - 11 * 60_000), + responsibleUserId: userId, contextSnapshot: { issueId, wakeReason: "issue_assigned" }, + ...(seed.runtime === "native" ? { nativePhase: "terminal_failure" } + : { runnerProfileJson: { adapterDispatch: { adapterType: "paperclip_runner" } } }) }); + if (seed.runtime === "native") { + await db.insert(nativeRunFinalizations).values({ runId, companyId, issueId, phase: "terminal_failure", + recoveryState: seed.coordinatorState ?? "blocked", failureCode: "native_continuation_requires_reconciliation", leaseOwner: null }); + } + let actionId: string | null = null; + if ((seed.hold ?? "active") !== "none") { + const native = seed.runtime === "native"; + const settled = seed.hold === "settled_blocked"; + const [action] = await db.insert(issueRecoveryActions).values({ companyId, sourceIssueId: issueId, kind: "active_run_watchdog", + status: settled ? "resolved" : "active", outcome: settled ? "blocked" : null, resolvedAt: settled ? finishedAt : null, + ownerType: "board", returnOwnerAgentId: agentId, + cause: native ? "native_continuation_requires_reconciliation" : "legacy_execution_requires_reconciliation", + fingerprint: native ? `native-continuation:${runId}` : `legacy-execution:${runId}`, + nextAction: "Inspect the original failure and reconcile the previous execution before continuing. Automatic recovery cannot start another incident.", + maxAttempts: 3, createdAt: finishedAt, + evidence: { runId, originalFailureCode: seed.errorCode, nativeFailureBlock: { runId, statusVersion: 4 }, + ...(settled ? { automaticRecovery: { policy: "preserve_without_replay_v1", runId, replay: "blocked", + actionOutcome: "unknown", recordedAt: finishedAt.toISOString() } } : {}) } }).returning(); + actionId = action!.id; + } + return { issueId, runId, actionId }; + } + + const issue = async (id: string) => (await db.select().from(issues).where(eq(issues.id, id)))[0]!; + const successors = async (runId: string) => db.select().from(heartbeatRuns).where(eq(heartbeatRuns.retryOfRunId, runId)); + /** Keeps the agent's only slot busy, so a delivered continuation stays observable as queued. */ + async function occupySlot() { + const [other] = await db.insert(issues).values({ companyId, title: "Other work", status: "in_progress", assigneeAgentId: agentId }).returning(); + await db.insert(heartbeatRuns).values({ companyId, agentId, issueId: other!.id, status: "running", contextSnapshot: { issueId: other!.id } }); + } + async function deliver() { + const heartbeat = heartbeatService(db); + await deliverReconciledExecutions(db, heartbeat.wakeup); + await deliverReconciledExecutions(db, heartbeat.wakeup); + } + + async function expectOneFreshSuccessor(f: { issueId: string; runId: string }) { + expect(await getExecutionBlocker(db, companyId, f.issueId)).toBeNull(); + expect(await issue(f.issueId)).toMatchObject({ status: "todo" }); + await occupySlot(); + await deliver(); + const next = await successors(f.runId); + expect(next).toHaveLength(1); + expect(next[0]!.contextSnapshot).toMatchObject({ issueId: f.issueId, previousRunId: f.runId, forceFreshSession: true, + wakeReason: "issue_recovery_action_restored" }); + const [record] = await db.select().from(issueRecoveryActions).where(and(eq(issueRecoveryActions.sourceIssueId, f.issueId), + sql`${issueRecoveryActions.evidence}->'freshContinuation' is not null`)); + expect(record!.evidence).toMatchObject({ continuationDelivery: "delivered", continuationRunId: next[0]!.id, + freshContinuation: { schema: FRESH_CONTINUATION_SCHEMA, sourceRunId: f.runId }, + executionReconciliation: { runId: f.runId, providerStopped: true, actionOutcome: "mixed" } }); + expect(record!.nextAction).not.toMatch(adminText); + expect(record!.ownerType).toBe("system"); + return next[0]!; + } + + // The five most frequent endings on staging (2026-11-12): each left the task + // Blocked for a person with no successor run. + it.each([ + { errorCode: "native_continuation_requires_reconciliation", error: "runner_remote_process_identity_unavailable", runtime: "native" as const }, + { errorCode: "controller_lease_lost", error: "Legacy controller lease lost", runtime: "legacy" as const }, + { errorCode: "process_lost", error: "Process lost -- server may have restarted; retrying once", runtime: "legacy" as const }, + { errorCode: "server_shutdown_interrupted", error: "Interrupted by graceful server shutdown (SIGTERM)", runtime: "legacy" as const, + status: "interrupted" as const }, + { errorCode: "native_session_interrupted", error: "runner_ingress_auth_failed: Runner ingress did not complete PRP authentication", + runtime: "native" as const }, + ])("continues a task whose run ended with $errorCode in exactly one fresh run from saved work", async seed => { + const f = await unfinishedRun(seed); + await settleUnrecoverableExecutions(db); + const hold = (await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, f.actionId!)))[0]!; + expect(hold).toMatchObject({ status: "resolved", outcome: "restored" }); + expect(hold.evidence.automaticRecovery).toBeUndefined(); + await expectOneFreshSuccessor(f); + }, 60_000); + + // The only native swap failure left on a later staging swap: the Runner + // resumed a harness that was not suspended or was gone. + // Exact resume is fixed elsewhere; whatever still fails must fall back. + it.each([ + { errorCode: "native_session_interrupted", + error: "runner_ingress_unavailable: runnerd process failed: runner_harness_state_mismatch: resumed_not_suspended" }, + { errorCode: "native_session_interrupted", + error: "runner_ingress_unavailable: runnerd process failed: runner_harness_state_mismatch: resumed_unavailable" }, + { errorCode: "runner_harness_state_mismatch", error: "runner_harness_state_mismatch: resumed_unavailable" }, + ])("continues a task whose resumed Runner harness was in the wrong state ($error)", async seed => { + const f = await unfinishedRun({ runtime: "native", ...seed }); + await settleUnrecoverableExecutions(db); + await expectOneFreshSuccessor(f); + }, 60_000); + + // Staging: the person had already pressed Retry, and the automatic successor + // could not carry that authorization forward. That is the system's failure, + // not the person's: the task continues under its responsible user. + it("continues a task whose automatic retry lost the person's continuation authorization", async () => { + expect(PERSON_OWNED_FAILURE_CODES).not.toContain("continuation_user_authorization_missing"); + const f = await unfinishedRun({ runtime: "legacy", errorCode: "continuation_user_authorization_missing", + error: "The automatic retry could not revalidate the original user continuation" }); + await settleUnrecoverableExecutions(db); + const next = await expectOneFreshSuccessor(f); + expect(next.responsibleUserId).toBe(userId); + }, 60_000); + + it("falls back for a failure code nobody has classified yet", async () => { + const f = await unfinishedRun({ runtime: "native", errorCode: "runner_new_failure_added_next_week" }); + await settleUnrecoverableExecutions(db); + await expectOneFreshSuccessor(f); + }, 60_000); + + it("creates one successor when two servers call it at once", async () => { + const f = await unfinishedRun({ runtime: "native", errorCode: "native_continuation_requires_reconciliation", + error: "runner_remote_process_identity_unavailable" }); + const results = await Promise.all([ + ensureFreshContinuation(db, { companyId, runId: f.runId, trigger: "recovery_refused" }), + ensureFreshContinuation(db, { companyId, runId: f.runId, trigger: "recovery_refused" }), + settleUnrecoverableExecutions(db).then(() => null), + ]); + expect(results.filter(result => result?.kind === "continued")).toHaveLength(1); + expect(results.filter(result => result && result.kind !== "continued").map(result => result!.kind)) + .toEqual([expect.stringMatching(/already_continued|successor_exists/)]); + await expectOneFreshSuccessor(f); + // A later call, from either server or a sweep, adds nothing. + expect(await ensureFreshContinuation(db, { companyId, runId: f.runId, trigger: "held_recovery" })) + .toMatchObject({ kind: expect.stringMatching(/already_continued|successor_exists/) }); + await deliver(); + expect(await successors(f.runId)).toHaveLength(1); + }, 60_000); + + // Upgrade safety: rows saved by the previous release (a settled-but-blocked + // no-replay hold, its coordinator still awaiting a runner reattach) and a + // task already Blocked continue on the first pass after deploy, without Retry. + it("continues tasks that older releases left blocked by these codes", async () => { + const f = await unfinishedRun({ runtime: "native", errorCode: "native_continuation_requires_reconciliation", + error: "runner_remote_process_identity_unavailable", hold: "settled_blocked", coordinatorState: "awaiting_runner_reattach" }); + expect(await getExecutionBlocker(db, companyId, f.issueId)).toMatchObject({ recoveryActionId: f.actionId }); + await settleUnrecoverableExecutions(db); + await expectOneFreshSuccessor(f); + }, 60_000); + + const sweepWake = (issueId: string) => heartbeatService(db).wakeup(agentId, { source: "automation", triggerDetail: "system", + reason: "issue_continuation_needed", payload: { issueId }, requestedByActorType: "system", + requestedByActorId: "idle-task-sweep", contextSnapshot: { issueId, taskId: issueId, wakeReason: "issue_continuation_needed" } }); + const pendingRecord = async (issueId: string) => (await db.select().from(issueRecoveryActions).where(and( + eq(issueRecoveryActions.sourceIssueId, issueId), sql`${issueRecoveryActions.evidence}->'freshContinuation' is not null`)))[0]; + + // An ordinary system wake (the idle-task sweep's) reaches the fallback. The + // continuation is recorded pending and counts as delivered only once a run + // for it exists. + it("records a pending continuation for an ordinary continuation wake and delivers it once", async () => { + const f = await unfinishedRun({ runtime: "native", errorCode: "native_continuation_requires_reconciliation", + error: "runner_remote_process_identity_unavailable", hold: "settled_blocked" }); + await occupySlot(); + expect(await sweepWake(f.issueId)).toBeNull(); + expect(await getExecutionBlocker(db, companyId, f.issueId)).toBeNull(); + expect((await pendingRecord(f.issueId))!.evidence).toMatchObject({ continuationDelivery: "pending", + freshContinuation: { sourceRunId: f.runId, trigger: "continuation_wake", delivery: "recorded" } }); + // A second sweep wake adds nothing. + expect(await sweepWake(f.issueId)).toBeNull(); + await deliver(); + expect(await successors(f.runId)).toHaveLength(1); + expect((await pendingRecord(f.issueId))!.evidence.continuationDelivery).toBe("delivered"); + }, 60_000); + + // A gate after the hook must never consume the recovery: it stays pending + // and is delivered once the gate clears. + it("keeps the continuation pending while the agent's daily run limit declines it, then delivers it", async () => { + const f = await unfinishedRun({ runtime: "native", errorCode: "native_session_interrupted", hold: "settled_blocked" }); + await db.update(agents).set({ runtimeConfig: { heartbeat: { maxConcurrentRuns: 1, maxDailyRuns: 1 } } }).where(eq(agents.id, agentId)); + try { + // The source run already used today's single run. + expect(await sweepWake(f.issueId)).toBeNull(); + await deliver(); + expect(await successors(f.runId)).toHaveLength(0); + expect((await pendingRecord(f.issueId))!.evidence.continuationDelivery).toBe("pending"); + // The limit clears: the next pass delivers it. + await db.update(agents).set({ runtimeConfig: { heartbeat: { maxConcurrentRuns: 1 } } }).where(eq(agents.id, agentId)); + await occupySlot(); + await deliver(); + expect(await successors(f.runId)).toHaveLength(1); + } finally { + await db.update(agents).set({ runtimeConfig: { heartbeat: { maxConcurrentRuns: 1 } } }).where(eq(agents.id, agentId)); + } + }, 60_000); + + it("leaves a paused agent's task waiting with that reason, not idle and not consumed", async () => { + const f = await unfinishedRun({ runtime: "native", errorCode: "native_session_interrupted", hold: "settled_blocked" }); + await db.update(agents).set({ status: "paused" }).where(eq(agents.id, agentId)); + try { + expect(await ensureFreshContinuation(db, { companyId, runId: f.runId, trigger: "continuation_wake" })) + .toEqual({ kind: "person_owned", reason: "agent_not_available" }); + expect(await pendingRecord(f.issueId)).toBeUndefined(); + expect(await getExecutionBlocker(db, companyId, f.issueId)).toMatchObject({ recoveryActionId: f.actionId }); + } finally { + await db.update(agents).set({ status: "idle" }).where(eq(agents.id, agentId)); + } + }, 60_000); + + // The chaos repro: the agent's only slot is held. The delivered continuation + // waits queued (never lost) and starts as soon as the slot frees. + it("leaves the delivered continuation queued while the agent's slot is full and starts it when the slot frees", async () => { + const f = await unfinishedRun({ runtime: "native", errorCode: "process_lost" }); + expect(await ensureFreshContinuation(db, { companyId, runId: f.runId, trigger: "recovery_refused" })).toMatchObject({ kind: "continued" }); + const [other] = await db.insert(issues).values({ companyId, title: "Holds the slot", status: "in_progress", assigneeAgentId: agentId }).returning(); + const [holder] = await db.insert(heartbeatRuns).values({ companyId, agentId, issueId: other!.id, status: "running", + contextSnapshot: { issueId: other!.id } }).returning(); + await deliver(); + const [next] = await successors(f.runId); + expect(next).toMatchObject({ status: "queued" }); + expect((await pendingRecord(f.issueId))!.evidence).toMatchObject({ continuationDelivery: "delivered", continuationRunId: next!.id }); + // The slot frees: the queued continuation is dispatched. + await db.update(heartbeatRuns).set({ status: "succeeded", finishedAt: new Date() }).where(eq(heartbeatRuns.id, holder!.id)); + await heartbeatService(db).resumeQueuedRuns(); + await vi.waitFor(async () => { + const [current] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, next!.id)); + expect(current!.status).not.toBe("queued"); + }, { timeout: 20_000, interval: 100 }); + }, 60_000); + + // The Retry banner never shows while Paperclip is continuing the task itself. + it("presents a task whose continuation is recorded or scheduled as continuing, with no Retry", async () => { + const f = await unfinishedRun({ runtime: "native", errorCode: "native_restart_recovery_blocked" }); + const presentation = async () => { + const task = await issue(f.issueId); + return taskInterruptionPresentation(db, { id: task.id, companyId, status: task.status, + assigneeAgentId: task.assigneeAgentId, projectId: task.projectId }); + }; + // A scheduled check (exact recovery still has its chance): a timed wait, no Retry. + await recordFreshContinuationCheck(db, { companyId, actionId: f.actionId! }, + { kind: "exact_recovery_pending", reason: "native_finalizer_active", retryAt: new Date(Date.now() + 60_000) }); + expect(await presentation()).toMatchObject({ state: "retry_scheduled", canRetry: false }); + // Recorded, not yet started: continuing, no Retry. + await db.update(issueRecoveryActions).set({ evidence: sql`${issueRecoveryActions.evidence} - 'freshContinuationCheck'` }) + .where(eq(issueRecoveryActions.id, f.actionId!)); + expect(await ensureFreshContinuation(db, { companyId, runId: f.runId, trigger: "recovery_refused" })).toMatchObject({ kind: "continued" }); + expect(await presentation()).toMatchObject({ state: "working", canRetry: false }); + }, 60_000); + + it("never starts a second run when a person's Retry already continued the task", async () => { + const f = await unfinishedRun({ runtime: "native", errorCode: "process_lost" }); + expect(await ensureFreshContinuation(db, { companyId, runId: f.runId, trigger: "recovery_refused" })).toMatchObject({ kind: "continued" }); + // A person's Retry started a run before the continuation was delivered. + const [retry] = await db.insert(heartbeatRuns).values({ companyId, agentId, issueId: f.issueId, nativeIssueId: f.issueId, + status: "queued", contextSnapshot: { issueId: f.issueId, wakeReason: "task_retry" } }).returning(); + await deliver(); + expect(await successors(f.runId)).toHaveLength(0); + expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.issueId, f.issueId))).toHaveLength(2); + expect((await pendingRecord(f.issueId))!.evidence).toMatchObject({ continuationDelivery: "delivered", continuationRunId: retry!.id }); + }, 60_000); + + /** The continuation's own wake, exactly as the delivery worker sends it, without its pre-check. */ + async function deliveryWake(f: { issueId: string; runId: string }) { + const record = (await pendingRecord(f.issueId))!; + return heartbeatService(db).wakeup(agentId, { source: "automation", triggerDetail: "system", + reason: "issue_recovery_action_restored", idempotencyKey: `execution-reconciliation:${record.id}`, + payload: { issueId: f.issueId, recoveryActionId: record.id }, requestedByActorType: "system", requestedByActorId: "execution-recovery", + contextSnapshot: { issueId: f.issueId, taskId: f.issueId, recoveryActionId: record.id, previousRunId: f.runId, + retryOfRunId: f.runId, forceFreshSession: true, wakeReason: "issue_recovery_action_restored", source: "execution.reconciled" } }); + } + + it("lets a run that started and finished in the delivery window consume the continuation under the task lock", async () => { + const f = await unfinishedRun({ runtime: "native", errorCode: "process_lost" }); + expect(await ensureFreshContinuation(db, { companyId, runId: f.runId, trigger: "recovery_refused" })).toMatchObject({ kind: "continued" }); + // Between the worker's pre-check and admission, saved input ran and finished. + const [intervening] = await db.insert(heartbeatRuns).values({ companyId, agentId, issueId: f.issueId, nativeIssueId: f.issueId, + status: "succeeded", finishedAt: new Date(), contextSnapshot: { issueId: f.issueId, wakeReason: "issue_commented" } }).returning(); + await occupySlot(); + expect(await deliveryWake(f)).toBeNull(); + expect(await successors(f.runId)).toHaveLength(0); + expect((await pendingRecord(f.issueId))!.evidence).toMatchObject({ continuationDelivery: "delivered", continuationRunId: intervening!.id }); + }, 60_000); + + it("starts no run for a task that moved to review in the delivery window", async () => { + const f = await unfinishedRun({ runtime: "native", errorCode: "process_lost" }); + expect(await ensureFreshContinuation(db, { companyId, runId: f.runId, trigger: "recovery_refused" })).toMatchObject({ kind: "continued" }); + await db.update(issues).set({ status: "in_review" }).where(eq(issues.id, f.issueId)); + await occupySlot(); + expect(await deliveryWake(f)).toBeNull(); + expect(await successors(f.runId)).toHaveLength(0); + expect((await pendingRecord(f.issueId))!.evidence.continuationDelivery).toBe("invalidated"); + }, 60_000); + + it("settles coalesced holds with their primary, so a task back in todo is not shown as working and the sweep sees it", async () => { + const f = await unfinishedRun({ runtime: "native", errorCode: "native_session_interrupted" }); + // A second no-replay hold of the same run, settled together with the first. + const [sibling] = await db.insert(issueRecoveryActions).values({ companyId, sourceIssueId: f.issueId, kind: "active_run_watchdog", + status: "resolved", outcome: "blocked", ownerType: "board", cause: "native_restart_recovery_blocked", + fingerprint: `native-restart:${f.runId}`, nextAction: "held", resolvedAt: new Date(), + evidence: { runId: f.runId, automaticRecovery: { policy: "preserve_without_replay_v1", runId: f.runId, replay: "blocked" } } }).returning(); + expect(await ensureFreshContinuation(db, { companyId, runId: f.runId, trigger: "recovery_refused" })).toMatchObject({ kind: "continued" }); + expect((await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, sibling!.id)))[0]!.evidence.continuationDelivery) + .toBe("coalesced"); + // The task moves to review before delivery: the primary is cancelled, and so is its sibling. + await db.update(issues).set({ status: "in_review" }).where(eq(issues.id, f.issueId)); + await occupySlot(); + expect(await deliveryWake(f)).toBeNull(); + expect((await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, sibling!.id)))[0]!.evidence.continuationDelivery) + .toBe("invalidated"); + // Back to todo with nothing pending: a failed attempt with Retry, not "working". + await db.update(issues).set({ status: "todo" }).where(eq(issues.id, f.issueId)); + const task = await issue(f.issueId); + expect(await taskInterruptionPresentation(db, { id: task.id, companyId, status: task.status, + assigneeAgentId: task.assigneeAgentId, projectId: task.projectId })).toMatchObject({ state: "failed", canRetry: true }); + // The assigned-work sweep sees it as left with nothing pending: inside its + // settle window after the recent change it schedules the recheck, never "ok". + const check = await heartbeatService(db).checkAssignedWorkInvariant({ companyId, issueId: f.issueId }); + expect(["violation", "settling"]).toContain(check?.verdict.kind); + }, 60_000); + + // The agent is told to check, redo what is missing, and ask only through the + // normal approval step; never that someone must restore the previous attempt. + it("guides the agent to check and redo, never to wait for an operator to recover the previous attempt", async () => { + for (const unverified of [[], ["github.merge_pull_request"]]) { + const note = freshContinuationNote({ runId: randomUUID(), unverified, workspace: "restored_last_save" }); + if (unverified.length) expect(note).toContain("first check whether it took effect"); + expect(note).toContain("do it again and continue the task"); + // It does not contradict "do not repeat completed actions": it scopes itself to unknown outcomes. + expect(note).toContain("Completed actions with recorded results are still not repeated"); + expect(note).toContain("request it through the normal approval step"); + expect(note).not.toMatch(/operator|recover its result|execution state|authorize rerunning/i); + } + // The same holds for the continuation context the agent actually receives. + const f = await unfinishedRun({ runtime: "native", errorCode: "native_session_interrupted" }); + expect(await ensureFreshContinuation(db, { companyId, runId: f.runId, trigger: "recovery_refused" })).toMatchObject({ kind: "continued" }); + const continuation = await buildExecutionContinuation({ db, companyId, issueId: f.issueId, agentId, + context: { previousRunId: f.runId }, summary: null, exposeLowTrustRaw: false }); + const text = JSON.stringify(continuation); + expect(text).toContain("was cut off before it finished"); + expect(text).not.toMatch(/operator must|recover its result|recover .*execution state|authorize rerunning/i); + }, 60_000); + + // A task whose run completes normally gets no fallback activity at all, even + // with an older hold on the task (a run queued across a swap that then ran). + it("leaves a task that completes normally alone, even with an older run's hold", async () => { + const f = await unfinishedRun({ runtime: "native", errorCode: "native_continuation_requires_reconciliation", hold: "settled_blocked" }); + const [later] = await db.insert(heartbeatRuns).values({ companyId, agentId, issueId: f.issueId, nativeIssueId: f.issueId, + status: "succeeded", startedAt: new Date(), finishedAt: new Date(), contextSnapshot: { issueId: f.issueId } }).returning(); + expect(await ensureFreshContinuation(db, { companyId, runId: f.runId, trigger: "held_recovery" })).toEqual({ kind: "successor_exists" }); + expect(await ensureFreshContinuation(db, { companyId, runId: later!.id, trigger: "held_recovery" })) + .toEqual({ kind: "not_applicable", reason: "run_not_unfinished" }); + await db.update(issues).set({ status: "done" }).where(eq(issues.id, f.issueId)); + await settleUnrecoverableExecutions(db); + await occupySlot(); + expect(await sweepWake(f.issueId)).toBeNull(); + await deliver(); + expect(await pendingRecord(f.issueId)).toBeUndefined(); + expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.issueId, f.issueId))).toHaveLength(2); + }, 60_000); + + it("starts no run for a task that finished while its continuation was pending", async () => { + const f = await unfinishedRun({ runtime: "native", errorCode: "process_lost" }); + expect(await ensureFreshContinuation(db, { companyId, runId: f.runId, trigger: "recovery_refused" })).toMatchObject({ kind: "continued" }); + await db.update(issues).set({ status: "done" }).where(eq(issues.id, f.issueId)); + await deliver(); + expect(await successors(f.runId)).toHaveLength(0); + expect((await pendingRecord(f.issueId))!.evidence.continuationDelivery).toBe("invalidated"); + }, 60_000); + + // Crash between writes: the decision committed, the process died before any + // run was created. Nothing is lost: the next delivery pass starts it. + it("delivers a committed continuation after a crash before its run was created", async () => { + const f = await unfinishedRun({ runtime: "native", errorCode: "process_lost" }); + expect(await ensureFreshContinuation(db, { companyId, runId: f.runId, trigger: "recovery_refused" })).toMatchObject({ kind: "continued" }); + expect(await successors(f.runId)).toHaveLength(0); + // A new process: a fresh service instance and worker pass. + await occupySlot(); + await deliver(); + expect(await successors(f.runId)).toHaveLength(1); + }, 60_000); + + // The cut-off run's agent may still be alive in its old, unreachable sandbox. + // Once the continuation is recorded it can neither write to the task through + // the API nor publish its workspace, and the next run restores the last save + // into a new root on a new allocation. + it("fences the cut-off run: its API writes are refused and its workspace epoch is abandoned", async () => { + const f = await unfinishedRun({ runtime: "native", errorCode: "native_continuation_requires_reconciliation", + error: "runner_remote_process_identity_unavailable" }); + const workspaceId = randomUUID(), snapshotId = null, leaseId = randomUUID(), environmentId = randomUUID(); + const location = { environmentId, leaseId, providerLeaseId: "sandbox-1", remoteCwd: "/home/daytona/.paperclip-workspaces/a" }; + await db.insert(executionWorkspaces).values({ id: workspaceId, companyId, sourceIssueId: f.issueId, mode: "isolated", + strategyType: "remote", name: "Task workspace", providerType: "remote", providerRef: location.remoteCwd, + metadata: { remoteWorkspace: { schema: "paperclip.remote-workspace.v1", epoch: 3, snapshotId, + source: { kind: "empty" }, location, writerRunId: f.runId, dirty: true } } }); + await db.update(heartbeatRuns).set({ runnerProfileJson: { remoteWorkspace: { schema: "paperclip.remote-workspace-run.v1", + workspaceId, leaseId, providerLeaseId: location.providerLeaseId, remoteCwd: location.remoteCwd, epoch: 3, + state: "prepared", snapshotId } } }).where(eq(heartbeatRuns.id, f.runId)); + // Today a failed run's token still writes. + const [before] = await loadAgentRunAuthentication(db, { runId: f.runId, companyId, agentId }); + expect(agentRunWritesRevoked(before)).toBe(false); + + expect(await ensureFreshContinuation(db, { companyId, runId: f.runId, trigger: "recovery_refused" })).toMatchObject({ kind: "continued" }); + + // The auth middleware's own row read refuses every write of the old token. + const [after] = await loadAgentRunAuthentication(db, { runId: f.runId, companyId, agentId }); + expect(agentRunWritesRevoked(after)).toBe(true); + await expect(db.transaction(tx => assertAgentRunWriteAllowed(tx as unknown as typeof db, companyId, { agentId, runId: f.runId }))) + .rejects.toMatchObject({ status: 403, details: { code: "agent_run_superseded" } }); + // The workspace writer is fenced out and the next preparation starts from the last save in a new root. + const [workspace] = await db.select().from(executionWorkspaces).where(eq(executionWorkspaces.id, workspaceId)); + expect(workspace!.metadata!.remoteWorkspace).toMatchObject({ epoch: 4, writerRunId: null, dirty: false, location: null }); + expect(workspace!.providerRef).toBeNull(); + expect(workspace!.metadata!.remoteWorkspaceAbandonedEpochs).toEqual([expect.objectContaining({ epoch: 3, runId: f.runId, location })]); + // The continuation's own token is unaffected. + await occupySlot(); + await deliver(); + const [next] = await successors(f.runId); + await expect(db.transaction(tx => assertAgentRunWriteAllowed(tx as unknown as typeof db, companyId, { agentId, runId: next!.id }))) + .resolves.toBeTruthy(); + }, 60_000); + + // The staging shape: the new server cannot re-reach the old Runner, so the old + // run's sandbox lease is still active (or its cleanup is pending) with no stop + // receipt. The continuation must still start, not wait behind that cleanup. + it.each(["active", "pending_cleanup"] as const)("starts the continuation while the unreachable old lease is %s", async leaseStatus => { + const f = await unfinishedRun({ runtime: "native", errorCode: "native_continuation_requires_reconciliation", + error: "runner_remote_process_identity_unavailable" }); + const [environment] = await db.insert(environments).values({ name: `sandbox-${f.runId}`, driver: "sandbox" }).returning(); + await db.insert(environmentLeases).values({ companyId, issueId: f.issueId, heartbeatRunId: f.runId, + environmentId: environment!.id, provider: "daytona", providerLeaseId: `sandbox-${f.runId}`, status: leaseStatus, + leasePolicy: "retain_on_failure", metadata: { remoteCwd: "/home/daytona/work", driver: "sandbox" } }); + await settleUnrecoverableExecutions(db); + await deliver(); + const [next] = await successors(f.runId); + expect(next).toBeTruthy(); + // Admission claims it: it leaves the queue instead of being declined for the old run's cleanup. + await vi.waitFor(async () => { + const [current] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, next!.id)); + expect(current!.status).not.toBe("queued"); + }, { timeout: 20_000, interval: 100 }); + // The abandoned allocation stays fenced: the old run still cannot write. + const [old] = await loadAgentRunAuthentication(db, { runId: f.runId, companyId, agentId }); + expect(agentRunWritesRevoked(old)).toBe(true); + }, 60_000); + + // A legacy run whose local process may still be alive: the continuation must + // never write the same directory. It gets a new isolated workspace and the + // decision records the stop as unproven. + it("gives the continuation a new isolated workspace while the old local writer may be alive", async () => { + const f = await unfinishedRun({ runtime: "legacy", errorCode: "controller_lease_lost", error: "Legacy controller lease lost" }); + // Its controller ran on another host (the replaced server), so no probe from here can prove it gone. + await db.update(heartbeatRuns).set({ processPid: 4242, processHostHash: "replaced-server", processStartedAt: new Date(Date.now() - 600_000) }) + .where(eq(heartbeatRuns.id, f.runId)); + expect(await ensureFreshContinuation(db, { companyId, runId: f.runId, trigger: "recovery_refused" })) + .toMatchObject({ kind: "continued", isolation: "fresh_isolated_workspace" }); + const [hold] = await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, f.actionId!)); + expect(hold!.evidence).toMatchObject({ freshContinuation: { isolation: "fresh_isolated_workspace", stopProof: "unproven_isolated" }, + executionReconciliation: { providerStopProof: "isolated" } }); + await occupySlot(); + await deliver(); + const [next] = await successors(f.runId); + expect(next!.contextSnapshot).toMatchObject({ freshContinuationIsolation: f.actionId }); + // Workspace selection gives it a new isolated workspace, never the old directory. + expect(await readFreshWorkspaceReadiness(db, next!)).toEqual({ mode: "fresh_isolated_workspace", retryIntentId: f.actionId, + sourceRunId: f.runId, retainedSourceIds: [] }); + }, 60_000); + + // The recorded process identity (host, PID space, start time) of this process. + const liveIdentity = () => ({ processPid: process.pid, processHostHash: currentProcessSpaceHash(), + processStartedAt: new Date(Date.now() - process.uptime() * 1_000) }); + + /** Moves the recorded start of the pending wait into the past. */ + async function waitedFor(actionId: string, ms: number) { + await db.update(issueRecoveryActions).set({ evidence: sql`jsonb_set(${issueRecoveryActions.evidence}, + '{freshContinuationCheck,firstPendingAt}', to_jsonb(${Date.now() - ms}::bigint))` }).where(eq(issueRecoveryActions.id, actionId)); + } + + it("lets a previous process still running on this host settle first, for about ten minutes at most", async () => { + const f = await unfinishedRun({ runtime: "legacy", errorCode: "process_lost" }); + await db.update(heartbeatRuns).set(liveIdentity()).where(eq(heartbeatRuns.id, f.runId)); + const first = await ensureFreshContinuation(db, { companyId, runId: f.runId, trigger: "recovery_refused" }); + expect(first).toMatchObject({ kind: "exact_recovery_pending", reason: "previous_process_running" }); + // Rechecks back off from one minute. + expect((first as { retryAt: Date }).retryAt.getTime()).toBeLessThanOrEqual(Date.now() + 61_000); + await recordFreshContinuationCheck(db, { companyId, actionId: f.actionId! }, first); + const [hold] = await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, f.actionId!)); + expect(hold!.evidence.freshContinuationCheck).toMatchObject({ checks: 1, firstPendingAt: expect.any(Number) }); + // Past the bound it stops waiting and continues in a new isolated workspace. + await waitedFor(f.actionId!, FRESH_CONTINUATION_PENDING_BOUND_MS + 1_000); + expect(await ensureFreshContinuation(db, { companyId, runId: f.runId, trigger: "recovery_refused" })) + .toMatchObject({ kind: "continued", isolation: "fresh_isolated_workspace" }); + }, 60_000); + + it("keeps waiting up to fifteen minutes while the exact-recovery owner shows progress", async () => { + const f = await unfinishedRun({ runtime: "legacy", errorCode: "controller_lease_lost" }); + await db.update(heartbeatRuns).set({ controllerLeaseExpiresAt: new Date(Date.now() + 365 * 86_400_000) }) + .where(eq(heartbeatRuns.id, f.runId)); + const waiting = await ensureFreshContinuation(db, { companyId, runId: f.runId, trigger: "recovery_refused" }); + await recordFreshContinuationCheck(db, { companyId, actionId: f.actionId! }, waiting); + await waitedFor(f.actionId!, FRESH_CONTINUATION_PENDING_BOUND_MS + 1_000); + // The owner renewed its lease since the last check: progress. + await db.update(heartbeatRuns).set({ lastOutputAt: new Date(Date.now() + 1_000) }).where(eq(heartbeatRuns.id, f.runId)); + expect(await ensureFreshContinuation(db, { companyId, runId: f.runId, trigger: "recovery_refused" })) + .toMatchObject({ kind: "exact_recovery_pending", reason: "controller_lease_live" }); + await waitedFor(f.actionId!, FRESH_CONTINUATION_PROGRESS_BOUND_MS + 1_000); + expect(await ensureFreshContinuation(db, { companyId, runId: f.runId, trigger: "recovery_refused" })) + .toMatchObject({ kind: "continued", isolation: "fresh_isolated_workspace" }); + }, 60_000); + + it("does not mistake a recycled PID for the old writer", async () => { + const f = await unfinishedRun({ runtime: "legacy", errorCode: "process_lost" }); + // The PID is alive now, but it belongs to a process that started after the old one was recorded. + await db.update(heartbeatRuns).set({ ...liveIdentity(), processStartedAt: new Date("2020-01-01T00:00:00Z") }) + .where(eq(heartbeatRuns.id, f.runId)); + expect(await ensureFreshContinuation(db, { companyId, runId: f.runId, trigger: "recovery_refused" })) + .toMatchObject({ kind: "continued" }); + }, 60_000); + + /** A saved-work (workspace) recovery generation on the run's hold, as workspace recovery records it. */ + async function savedWorkRecovery(f: { runId: string; actionId: string | null }, state: "awaiting_evidence" | "running") { + const [hold] = await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, f.actionId!)); + await db.update(issueRecoveryActions).set({ evidence: { ...hold!.evidence, + systemRecovery: { schema: "paperclip.system-recovery.v1", policyVersion: 1, phase: "reconcile_effects", state, + sourceRunId: f.runId, attempts: 1, retriesUsed: 0, revision: 2, failure: null, intentId: null, deadlineAt: null, + nextAttemptAt: null, firstFailureAt: null, freshAttemptRunId: null, providerCooldownAt: null, + attemptId: randomUUID(), generationId: randomUUID(), preservationOperationIds: [] } } }) + .where(eq(issueRecoveryActions.id, f.actionId!)); + } + + it("bounds a saved-work recovery that is waiting with no progress, on a scheduled deadline", async () => { + const f = await unfinishedRun({ runtime: "legacy", errorCode: "server_shutdown_interrupted", status: "interrupted" }); + await savedWorkRecovery(f, "awaiting_evidence"); + // The held-run scan selects it: exact recovery keeps its first chance. + expect(await continueHeldExecutions(db)).toMatchObject({ continued: 0 }); + const [hold] = await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, f.actionId!)); + expect(hold!.evidence.freshContinuationCheck).toMatchObject({ kind: "exact_recovery_pending", reason: "saved_work_recovery_running" }); + // With no other event, the worker is scheduled for the next check. + expect(await nextFreshContinuationCheckAt(db)).toBe((hold!.evidence.freshContinuationCheck as { nextCheckAt: number }).nextCheckAt); + // No progress by the bound: the task continues fresh in a new root, and the + // preempted recovery is no longer scheduled (its hold carries the decision), + // so a late result cannot reach the new workspace. + await waitedFor(f.actionId!, FRESH_CONTINUATION_PENDING_BOUND_MS + 1_000); + await db.update(issueRecoveryActions).set({ evidence: sql`jsonb_set(${issueRecoveryActions.evidence}, + '{freshContinuationCheck,nextCheckAt}', to_jsonb(${Date.now() - 1_000}::bigint))` }).where(eq(issueRecoveryActions.id, f.actionId!)); + expect(await continueHeldExecutions(db)).toMatchObject({ continued: 1 }); + const [settled] = await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, f.actionId!)); + expect(settled!.evidence).toMatchObject({ executionReconciliation: { runId: f.runId }, + freshContinuation: { isolation: "fresh_isolated_workspace" } }); + }, 60_000); + + it("lets a running saved-work recovery that keeps advancing use its own budget", async () => { + const f = await unfinishedRun({ runtime: "legacy", errorCode: "server_shutdown_interrupted", status: "interrupted" }); + await savedWorkRecovery(f, "running"); + const first = await ensureFreshContinuation(db, { companyId, runId: f.runId, trigger: "held_recovery" }); + await recordFreshContinuationCheck(db, { companyId, actionId: f.actionId! }, first); + await waitedFor(f.actionId!, FRESH_CONTINUATION_PROGRESS_BOUND_MS + 1_000); + // The recovery advanced (a new attempt) since the last check: it keeps going past 15 minutes. + await db.update(issueRecoveryActions).set({ updatedAt: new Date(Date.now() + 1_000), + evidence: sql`jsonb_set(${issueRecoveryActions.evidence}, '{systemRecovery,attempts}', '2'::jsonb)` }) + .where(eq(issueRecoveryActions.id, f.actionId!)); + expect(await ensureFreshContinuation(db, { companyId, runId: f.runId, trigger: "held_recovery" })) + .toMatchObject({ kind: "exact_recovery_pending", reason: "saved_work_recovery_running" }); + // Its 30-minute budget is the cap. + await waitedFor(f.actionId!, FRESH_CONTINUATION_SAVED_WORK_BOUND_MS + 1_000); + expect(await ensureFreshContinuation(db, { companyId, runId: f.runId, trigger: "held_recovery" })) + .toMatchObject({ kind: "continued", isolation: "fresh_isolated_workspace" }); + }, 60_000); + + it("bounds every exact-recovery wait, here a controller lease that never lapses", async () => { + const f = await unfinishedRun({ runtime: "legacy", errorCode: "controller_lease_lost" }); + await db.update(heartbeatRuns).set({ controllerLeaseExpiresAt: new Date(Date.now() + 365 * 86_400_000) }) + .where(eq(heartbeatRuns.id, f.runId)); + const waiting = await ensureFreshContinuation(db, { companyId, runId: f.runId, trigger: "recovery_refused" }); + expect(waiting).toMatchObject({ kind: "exact_recovery_pending", reason: "controller_lease_live" }); + await recordFreshContinuationCheck(db, { companyId, actionId: f.actionId! }, waiting); + await waitedFor(f.actionId!, FRESH_CONTINUATION_PENDING_BOUND_MS + 1_000); + expect(await ensureFreshContinuation(db, { companyId, runId: f.runId, trigger: "recovery_refused" })) + .toMatchObject({ kind: "continued", isolation: "fresh_isolated_workspace" }); + }, 60_000); + + it("keeps the task workspace when the old local writer is proven gone", async () => { + const f = await unfinishedRun({ runtime: "legacy", errorCode: "process_lost" }); + expect(await ensureFreshContinuation(db, { companyId, runId: f.runId, trigger: "recovery_refused" })) + .toMatchObject({ kind: "continued", isolation: "writer_ended" }); + }, 60_000); + + it("settles only the reconciliation holds it owns and leaves restore holds and history alone", async () => { + const f = await unfinishedRun({ runtime: "native", errorCode: "native_session_interrupted" }); + const [history] = await db.insert(issueRecoveryActions).values({ companyId, sourceIssueId: f.issueId, kind: "active_run_watchdog", + status: "cancelled", outcome: "cancelled", ownerType: "board", cause: "native_restart_recovery_blocked", + fingerprint: `history:${f.runId}`, nextAction: "Old note", resolutionNote: "kept", resolvedAt: new Date(), + evidence: { runId: f.runId } }).returning(); + expect(await ensureFreshContinuation(db, { companyId, runId: f.runId, trigger: "recovery_refused" })).toMatchObject({ kind: "continued" }); + const [untouched] = await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, history!.id)); + expect(untouched).toMatchObject({ status: "cancelled", nextAction: "Old note", resolutionNote: "kept", ownerType: "board" }); + expect(untouched!.evidence).toEqual({ runId: f.runId }); + + // A restore hold that workspace recovery has not finished keeps the task with it. + const g = await unfinishedRun({ runtime: "native", errorCode: "native_session_interrupted" }); + const [restore] = await db.insert(issueRecoveryActions).values({ companyId, sourceIssueId: g.issueId, kind: "active_run_watchdog", + status: "resolved", outcome: "blocked", ownerType: "system", cause: "native_continuation_requires_reconciliation", + fingerprint: `native-workspace:${g.runId}`, nextAction: "Recovering saved work", resolvedAt: new Date(), + evidence: { runId: g.runId, workspaceRestoreFailure: "restore_unsafe_archive", + automaticRecovery: { policy: "preserve_without_replay_v1", runId: g.runId, replay: "blocked" } } }).returning(); + expect(await ensureFreshContinuation(db, { companyId, runId: g.runId, trigger: "recovery_refused" })) + .toMatchObject({ kind: "exact_recovery_pending", reason: "workspace_recovery_owns_restore" }); + const [kept] = await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, restore!.id)); + expect(kept!.evidence).toMatchObject({ workspaceRestoreFailure: "restore_unsafe_archive", automaticRecovery: { replay: "blocked" } }); + expect(kept!.evidence.executionReconciliation).toBeUndefined(); + }, 60_000); + + it("schedules no recheck for a held task nothing would act on", async () => { + const f = await unfinishedRun({ runtime: "native", errorCode: "native_session_interrupted", hold: "settled_blocked" }); + await db.update(issueRecoveryActions).set({ evidence: sql`${issueRecoveryActions.evidence} || ${JSON.stringify({ + freshContinuationCheck: { kind: "person_owned", reason: "approval_pending", checkedAt: Date.now() - 7_200_000, + nextCheckAt: Date.now() - 3_600_000 } })}::jsonb` }).where(eq(issueRecoveryActions.id, f.actionId!)); + expect(await nextFreshContinuationCheckAt(db)).not.toBeNull(); + // The task was cancelled after that check: the schedule goes quiet. + await db.update(issues).set({ status: "cancelled" }).where(eq(issues.id, f.issueId)); + expect(await nextFreshContinuationCheckAt(db)).toBeNull(); + expect(await heldExecutionsAwaitingFreshContinuation(db, new Date(), 10)).toEqual([]); + expect(await executionControlSchedule(db).disposition()).toBeNull(); + }, 60_000); + + it("tells the agent the previous attempt was cut off and which actions are unverified", async () => { + const f = await unfinishedRun({ runtime: "native", errorCode: "native_session_interrupted" }); + await db.insert(toolInvocations).values({ companyId, agentId, issueId: f.issueId, runId: f.runId, toolName: "github.create_pull_request", + riskLevel: "write", status: "executing", startedAt: new Date() } as typeof toolInvocations.$inferInsert); + expect(await ensureFreshContinuation(db, { companyId, runId: f.runId, trigger: "recovery_refused" })).toMatchObject({ kind: "continued" }); + const [hold] = await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, f.actionId!)); + const decision = hold!.evidence.executionReconciliation as Record; + expect(decision.outcomeEvidence).toContain(`run ${f.runId}) was cut off`); + expect(decision.outcomeEvidence).toContain("github.create_pull_request"); + expect(decision.outcomeEvidence).not.toMatch(adminText); + }, 60_000); + + it.each([ + { title: "a pending approval", setup: "approval" as const, errorCode: "native_continuation_requires_reconciliation" }, + { title: "a credential the person has not shared", setup: "none" as const, errorCode: "configuration_incomplete" }, + { title: "a budget stop", setup: "none" as const, errorCode: "budget_blocked" }, + ])("leaves a task waiting on $title for the person", async ({ setup, errorCode }) => { + expect(PERSON_OWNED_FAILURE_CODES).toContain("configuration_incomplete"); + const f = await unfinishedRun({ runtime: "native", errorCode }); + if (setup === "approval") { + const [approval] = await db.insert(approvals).values({ companyId, type: "approve_ceo_strategy", status: "pending", + payload: {} } as typeof approvals.$inferInsert).returning(); + await db.insert(issueApprovals).values({ companyId, issueId: f.issueId, approvalId: approval!.id } as typeof issueApprovals.$inferInsert); + } + expect(await ensureFreshContinuation(db, { companyId, runId: f.runId, trigger: "recovery_refused" })) + .toMatchObject({ kind: "person_owned" }); + await settleUnrecoverableExecutions(db); + expect(await issue(f.issueId)).toMatchObject({ status: "blocked" }); + await deliver(); + expect(await successors(f.runId)).toHaveLength(0); + }, 60_000); + + it("bounds continuations with the server-restart lane's hourly cap", () => { + expect(FRESH_CONTINUATIONS_PER_HOUR).toBe(SERVER_RESTART_RETRY_MAX_ATTEMPTS); + expect(FRESH_CONTINUATION_WINDOW_MS).toBe(SERVER_RESTART_RETRY_WINDOW_MS); + }); + + // Governance gates are never retired or bypassed by the fallback. + it.each(["question_pending", "user_owned_hold", "operator_continuation_recorded", "owner_gone_attestation"] as const)( + "leaves a task behind a real governance gate (%s) for the person", async gate => { + const f = await unfinishedRun({ runtime: "native", errorCode: "native_continuation_requires_reconciliation" }); + if (gate === "question_pending") await db.insert(issueThreadInteractions).values({ companyId, issueId: f.issueId, + kind: "ask_user_questions", status: "pending", payload: { questions: [] } } as unknown as typeof issueThreadInteractions.$inferInsert); + if (gate === "user_owned_hold") await db.update(issueRecoveryActions).set({ ownerType: "user", ownerUserId: userId }) + .where(eq(issueRecoveryActions.id, f.actionId!)); + if (gate === "operator_continuation_recorded" || gate === "owner_gone_attestation") { + const [hold] = await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, f.actionId!)); + await db.update(issueRecoveryActions).set({ evidence: { ...hold!.evidence, + ...(gate === "owner_gone_attestation" ? { ownerGoneAttestation: { actorId: userId } } : { explicitUserContinuation: { actorId: userId } }) } }) + .where(eq(issueRecoveryActions.id, f.actionId!)); + } + const before = (await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, f.actionId!)))[0]!; + expect(await ensureFreshContinuation(db, { companyId, runId: f.runId, trigger: "recovery_refused" })) + .toMatchObject({ kind: "person_owned" }); + const after = (await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, f.actionId!)))[0]!; + expect(after.evidence).toEqual(before.evidence); + expect(after.status).toBe(before.status); + await deliver(); + expect(await successors(f.runId)).toHaveLength(0); + }, 60_000); + + // Interruption with an unknown outcome is not a governance gate: the task + // continues, but as a fresh run, never a replay, and with an audit trail. + it("continues an interrupted governed action as a fresh run, never a replay, and keeps the audit trail", async () => { + const f = await unfinishedRun({ runtime: "native", errorCode: "native_continuation_requires_reconciliation", + error: "runner_remote_process_identity_unavailable", hold: "settled_blocked" }); + const [inFlight] = await db.insert(toolInvocations).values({ companyId, agentId, issueId: f.issueId, runId: f.runId, + toolName: "github.merge_pull_request", riskLevel: "write", status: "executing", startedAt: new Date() } as typeof toolInvocations.$inferInsert) + .returning(); + const original = (await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, f.actionId!)))[0]!.evidence.automaticRecovery; + await settleUnrecoverableExecutions(db); + const next = await expectOneFreshSuccessor(f); + // A fresh session: the interrupted turn is not re-sent. + expect(next.contextSnapshot).toMatchObject({ forceFreshSession: true }); + expect(next.sessionIdBefore).toBeNull(); + // The cut-off tool call is not re-executed: it stays as recorded and no new invocation exists. + const invocations = await db.select().from(toolInvocations).where(eq(toolInvocations.issueId, f.issueId)); + expect(invocations).toEqual([expect.objectContaining({ id: inFlight!.id, runId: f.runId, status: "executing" })]); + // The earlier no-replay decision stays as history beside the attributed fallback decision. + const [hold] = await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, f.actionId!)); + expect(hold!.evidence.automaticRecoveryHistory).toEqual(original); + expect(hold!.evidence.freshContinuationSettlement).toMatchObject({ actorType: "system", actorId: "fresh-continuation", + decision: "continue_in_fresh_run", replay: "none", reason: "exact_resumption_unavailable", + unverifiedActions: ["github.merge_pull_request"], recordedAt: expect.any(String) }); + expect((hold!.evidence.executionReconciliation as Record).outcomeEvidence).toContain("github.merge_pull_request"); + expect(await db.select().from(activityLog).where(and(eq(activityLog.entityId, f.issueId), + eq(activityLog.action, "issue.continued_from_saved_work")))).toHaveLength(1); + }, 60_000); + + // The isolation decision is a property of the task's next run, whatever path starts it. + it("moves the task off the old writer's workspace for every next run, saved input included", async () => { + const f = await unfinishedRun({ runtime: "legacy", errorCode: "controller_lease_lost", error: "Legacy controller lease lost" }); + const [workspace] = await db.insert(executionWorkspaces).values({ companyId, sourceIssueId: f.issueId, mode: "isolated", + strategyType: "git_worktree", name: "Task workspace", cwd: "/tmp/old-writer" }).returning(); + await db.update(issues).set({ executionWorkspaceId: workspace!.id, workspaceBindingRevision: 2 }).where(eq(issues.id, f.issueId)); + await db.update(heartbeatRuns).set({ processPid: 4242, processHostHash: "replaced-server", processStartedAt: new Date(Date.now() - 600_000), + contextSnapshot: { issueId: f.issueId, executionWorkspaceId: workspace!.id } }).where(eq(heartbeatRuns.id, f.runId)); + // A person's saved message is waiting: it continues the task itself. + await db.insert(agentWakeupRequests).values({ companyId, agentId, source: "on_demand", status: "deferred_issue_execution", + requestedByActorType: "user", requestedByActorId: userId, payload: { issueId: f.issueId } }); + expect(await ensureFreshContinuation(db, { companyId, runId: f.runId, trigger: "recovery_refused" })) + .toMatchObject({ kind: "continued", isolation: "fresh_isolated_workspace", delivery: "saved_input" }); + // No delivery path can reach the old directory: the task is no longer bound to it. + expect(await issue(f.issueId)).toMatchObject({ executionWorkspaceId: null, workspaceBindingRevision: 3 }); + const [kept] = await db.select().from(executionWorkspaces).where(eq(executionWorkspaces.id, workspace!.id)); + expect(kept!.cwd).toBe("/tmp/old-writer"); + }, 60_000); + + it("records its own isolated continuation when saved input could not avoid a shared directory", async () => { + const f = await unfinishedRun({ runtime: "legacy", errorCode: "controller_lease_lost" }); + await db.update(heartbeatRuns).set({ processPid: 4242, processHostHash: "replaced-server", processStartedAt: new Date(Date.now() - 600_000) }) + .where(eq(heartbeatRuns.id, f.runId)); + await db.insert(agentWakeupRequests).values({ companyId, agentId, source: "on_demand", status: "deferred_issue_execution", + requestedByActorType: "user", requestedByActorId: userId, payload: { issueId: f.issueId } }); + expect(await ensureFreshContinuation(db, { companyId, runId: f.runId, trigger: "recovery_refused" })) + .toMatchObject({ kind: "continued", isolation: "fresh_isolated_workspace", delivery: "recorded" }); + }, 60_000); + + it("backs off instead of blocking once a task used its hourly continuations", async () => { + const f = await unfinishedRun({ runtime: "native", errorCode: "process_lost" }); + for (let index = 0; index < FRESH_CONTINUATIONS_PER_HOUR; index++) { + await db.insert(issueRecoveryActions).values({ companyId, sourceIssueId: f.issueId, kind: "active_run_watchdog", status: "resolved", + outcome: "restored", ownerType: "system", cause: "fresh_continuation", fingerprint: `fresh-continuation:${randomUUID()}`, + nextAction: "continued", evidence: { runId: randomUUID(), continuationDelivery: "delivered", + freshContinuation: { schema: FRESH_CONTINUATION_SCHEMA, sourceRunId: randomUUID(), + recordedAt: new Date(Date.now() - (index + 1) * 60_000).toISOString() } } }); + } + await settleUnrecoverableExecutions(db); + const [hold] = await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, f.actionId!)); + // Not blocked for a person: the hold stays with the system and is checked again when the window frees a slot. + expect(hold).toMatchObject({ status: "active" }); + expect(hold!.evidence.freshContinuationCheck).toMatchObject({ kind: "backoff", nextCheckAt: expect.any(Number) }); + expect(await continueHeldExecutions(db)).toMatchObject({ continued: 0 }); + // With no other event, the disposition worker is scheduled for exactly the + // moment the window has room again. + const retryAt = (hold!.evidence.freshContinuationCheck as { nextCheckAt: number }).nextCheckAt; + expect(retryAt).toBeGreaterThan(Date.now()); + expect(await nextFreshContinuationCheckAt(db)).toBe(retryAt); + expect(await executionControlSchedule(db).disposition()).toBe(retryAt); + // The hour passes (the window's records age out and the check falls due); + // the scheduled pass alone continues the task. + await db.execute(sql`update issue_recovery_actions set evidence = jsonb_set(evidence, '{freshContinuation,recordedAt}', + to_jsonb((now() - interval '2 hours')::text)) where evidence ? 'freshContinuation'`); + await db.update(issueRecoveryActions).set({ evidence: sql`jsonb_set(${issueRecoveryActions.evidence}, + '{freshContinuationCheck,nextCheckAt}', to_jsonb(${Date.now() - 1_000}::bigint))` }).where(eq(issueRecoveryActions.id, f.actionId!)); + expect(await executionControlSchedule(db).disposition()).toBeLessThanOrEqual(Date.now() + 60_000); + await settleUnrecoverableExecutions(db); + expect(await ensureFreshContinuation(db, { companyId, runId: f.runId, trigger: "held_recovery" })) + .toMatchObject({ kind: "already_continued" }); + expect(await db.select({ id: agentWakeupRequests.id }).from(agentWakeupRequests)).toHaveLength(0); + }, 60_000); +}); diff --git a/server/src/services/fresh-continuation-fallback.ts b/server/src/services/fresh-continuation-fallback.ts new file mode 100644 index 00000000000..092084af912 --- /dev/null +++ b/server/src/services/fresh-continuation-fallback.ts @@ -0,0 +1,741 @@ +import { and, asc, desc, eq, gt, inArray, isNull, or, sql } from "drizzle-orm"; +import { + agentWakeupRequests, agents, approvals, companies, executionWorkspaces, heartbeatRuns, issueApprovals, issueRecoveryActions, + issueThreadInteractions, issues, nativeRunFinalizations, toolInvocations, type Db, +} from "@paperclipai/db"; +import { + EXECUTION_RECONCILIATION_CAUSES, readRemoteWorkspaceAuthority, remoteWorkspaceRunReferenceSchema, type ExecutionReconciliation, +} from "@paperclipai/shared"; +import { logger } from "../middleware/logger.js"; +import { logActivity } from "./activity-log.js"; +import { FRESH_CONTINUATION_SUPERSEDED_KEY } from "../agent-run-cancellation.js"; +import { isAcknowledgedNativeReassignmentStop, isAcknowledgedNativeStop } from "./acknowledged-native-stop.js"; +import { adapterExecutionControls } from "./adapter-execution-control.js"; +import { isInterruptedNativePreparationCandidate } from "./cancelled-native-startup.js"; +import { notifyDeferredWakesForIssue } from "./deferred-execution-notifications.js"; +import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notifications.js"; +import { issueService } from "./issues.js"; +import { holdOwnsBlockedStatus } from "./recovery-hold-blocked-status.js"; +import { proveRunProcessGone } from "./run-process-owner.js"; +import { hasPendingRunCleanup } from "./execution-blocker.js"; +import { abandonUnverifiedRemoteWorkspaceEpoch } from "./remote-workspace-epoch-abandonment.js"; +import { notifyRoutineExecutionStatus } from "./routine-execution-status-notifications.js"; +import { notifyStatusCardIssueChange } from "./status-card-notifications.js"; +import { readRunCancellation } from "./run-cancellation.js"; +import { readSystemRecovery } from "./system-recovery-state.js"; + +/** + * Fresh-continuation fallback: exact resumption of an unfinished run is an + * optimization, never a requirement. + * + * When a run ended without finishing its work and nothing exact follows it + * (no resumed session, no replacement, no scheduled retry, no saved input), + * `ensureFreshContinuation` starts the task again in a fresh session from its + * last verified saved workspace and its conversation. It needs no person and + * no proof that the old executor stopped: + * + * - The old run keeps its own fencing. Its remote workspace epoch is abandoned + * when it still owns it, so its writer can never publish again and the next + * run restores the last committed save into a new root on a new allocation. + * The unverified files stay in the abandoned root (recorded on the + * workspace), unapplied. + * - The opening context of the continuation names the cut-off run and every + * action whose outcome is unknown, so the agent checks before repeating a + * side effect. + * + * Eligibility is by classification, not by an allowlist: every failure is + * eligible except the causes a person must resolve (`PERSON_OWNED_FAILURE_CODES` + * and the task-level waits in `personOwnedTaskWait`). A failure code added + * later falls back without a change here. + * + * Idempotent per source run: the task row lock serializes callers on every + * server, and the recorded `freshContinuation.sourceRunId` (or any newer run of + * the task) makes later calls a no-op. Bounded per task, not per failure: at + * most `FRESH_CONTINUATIONS_PER_HOUR` continuations in a rolling hour, then it + * backs off and is checked again; it never charges the task's failure budget. + */ + +export const FRESH_CONTINUATION_SCHEMA = "paperclip.fresh-continuation.v1" as const; +export const FRESH_CONTINUATION_ACTOR = "fresh-continuation" as const; +/** Cause of the record written when the run left no hold of its own. Not an execution blocker. */ +export const FRESH_CONTINUATION_CAUSE = "fresh_continuation" as const; +/** Evidence key for the last check that did not continue (and when to check again). */ +export const FRESH_CONTINUATION_CHECK_KEY = "freshContinuationCheck" as const; +/** The restart lane's bound, reused: continuations per task per rolling hour. */ +// Literal values (an import would be undefined under the heartbeat module's +// import cycle); a test pins them to SERVER_RESTART_RETRY_MAX_ATTEMPTS/_WINDOW_MS. +export const FRESH_CONTINUATIONS_PER_HOUR = 6; +export const FRESH_CONTINUATION_WINDOW_MS = 60 * 60_000; +const PERSON_RECHECK_MS = 60 * 60_000; +/** Consecutive pending checks (about 12 minutes) before the fallback stops waiting. */ +/** Worst case from the first pending check to the fresh continuation. */ +export const FRESH_CONTINUATION_PENDING_BOUND_MS = 10 * 60_000; +/** Longer cap while the exact-recovery owner shows progress (a new event or a renewed lease). */ +export const FRESH_CONTINUATION_PROGRESS_BOUND_MS = 15 * 60_000; +/** Saved-work recovery that is running and advancing keeps its own budget. */ +export const FRESH_CONTINUATION_SAVED_WORK_BOUND_MS = 30 * 60_000; +const EXACT_RECOVERY_RECHECK_MS = 60_000; + +/** + * Run failure codes that only a person can resolve (the test for each: did a + * person fail to do something, or did the system fail to carry it forward? Only + * the first belongs here; e.g. a lost carry-over of a Retry's authorization, + * `continuation_user_authorization_missing`, is the system's): they stopped the work, a + * credential or access they must share, a configuration choice they must make, + * a budget stop, or a provider usage limit that is waiting as designed. Every + * other code, including codes that do not exist yet, gets the fallback. + */ +export const PERSON_OWNED_FAILURE_CODES = [ + // A person stopped or paused the work. + "cancelled", "operator_cancelled", "operator_interrupted", "issue_cancelled", "issue_paused", "agent_paused", + // A credential, secret or access the person must share. + "configuration_incomplete", "slack_configuration_incomplete", "signing_secret_unconfigured", + "user_secret_missing", "user_secret_definition_missing", "user_secret_definition_inactive", + "github_access_denied", "github_repo_not_accessible", "github_auth_required", "project_access_denied", + "permission_denied", "responsible_user_unauthorized", "oauth_access_projection_disabled", + "acpx_auth_required", "codex_auth_required", "claude_auth_required", "provider_auth_failed", "hermes_gateway_auth_failed", + // A configuration choice the person must change. + "native_provider_model_rejected", "provider_tool_definition_invalid", "turn_limit_exhausted", + // Budget stops. + "budget_blocked", "budget_hard_stop", "budget_exceeded", + // Provider usage limits that wait (and resume) as designed. + "provider_quota", "provider_limit_wait", "native_provider_usage_limit", + // An approval the person must give. + "approval_required", "formal_approval_unavailable", +] as const; + +export function isPersonOwnedFailureCode(code: string | null | undefined): boolean { + return typeof code === "string" && (PERSON_OWNED_FAILURE_CODES as readonly string[]).includes(code); +} + +const UNFINISHED_STATUSES = ["failed", "timed_out", "interrupted", "cancelled"]; +const LIVE_RUN_STATUSES = ["queued", "running", "scheduled_retry"]; +const EXACT_RECOVERY_STATES = ["scheduled", "running", "awaiting_evidence"]; + +/** + * How the continuation is kept apart from the old executor: + * - `remote_epoch`: the old run's remote workspace epoch is fenced (abandoned, or + * already taken from it), so it can never publish; the next preparation + * restores the last committed save into a new root. + * - `writer_ended`: the old local writer is proven gone (no process, no + * unsettled allocation), so the task workspace is safe to reuse. + * - `fresh_isolated_workspace`: the old local writer is not proven gone, so the + * continuation gets a new isolated workspace and never writes the old + * directory. Nothing waits for that proof. + */ +export type FreshContinuationIsolation = "remote_epoch" | "writer_ended" | "fresh_isolated_workspace"; + +export type FreshContinuationTrigger = "recovery_refused" | "held_recovery" | "continuation_wake"; + +export type FreshContinuationResult = + | { kind: "continued"; recoveryActionId: string; delivery: "recorded" | "caller_owns" | "saved_input"; isolation: FreshContinuationIsolation } + | { kind: "already_continued"; recoveryActionId: string } + | { kind: "successor_exists" } + | { kind: "dependency_wait" } + | { kind: "person_owned"; reason: string } + | { kind: "backoff"; retryAt: Date } + | { kind: "exact_recovery_pending"; reason: string; retryAt: Date; progressAt?: number; savedWorkSignature?: string } + | { kind: "not_applicable"; reason: string }; + +type Input = { + companyId: string; + runId: string; + trigger: FreshContinuationTrigger; + now?: Date; + /** + * `record`: record one durable continuation that the execution-continuation + * worker delivers. `caller_owns`: the caller is admitting a wake for this + * task in the same transaction, and that wake is the continuation. + */ + delivery?: "record" | "caller_owns"; +}; + +const object = (value: unknown): Record => + value && typeof value === "object" && !Array.isArray(value) ? value as Record : {}; + +function holdRunId(evidence: Record): string | null { + const value = evidence.runId ?? evidence.sourceRunId; + return typeof value === "string" ? value : null; +} + +/** Task-level waits that belong to a person. Read under the task lock. */ +async function personOwnedTaskWait(tx: Db, input: { companyId: string; issue: typeof issues.$inferSelect; + run: typeof heartbeatRuns.$inferSelect }): Promise { + const { companyId, issue, run } = input; + const [approval] = await tx.select({ id: approvals.id }).from(issueApprovals).innerJoin(approvals, and( + eq(approvals.id, issueApprovals.approvalId), eq(approvals.companyId, companyId), + )).where(and(eq(issueApprovals.companyId, companyId), eq(issueApprovals.issueId, issue.id), + inArray(approvals.status, ["pending", "revision_requested"]))).limit(1); + if (approval) return "approval_pending"; + const [question] = await tx.select({ id: issueThreadInteractions.id }).from(issueThreadInteractions).where(and( + eq(issueThreadInteractions.companyId, companyId), eq(issueThreadInteractions.issueId, issue.id), + eq(issueThreadInteractions.status, "pending"))).limit(1); + if (question) return "question_pending"; + const [agent] = await tx.select({ status: agents.status, lifecycleState: agents.lifecycleState }).from(agents) + .where(and(eq(agents.companyId, companyId), eq(agents.id, run.agentId))); + if (!agent || ["paused", "terminated", "pending_approval"].includes(agent.status) || agent.lifecycleState !== "ready") + return "agent_not_available"; + const [company] = await tx.select({ status: companies.status }).from(companies).where(eq(companies.id, companyId)); + if (company && company.status !== "active") return "company_paused"; + return null; +} + +/** Actions of the source run that ended with an unknown outcome. */ +async function unverifiedActions(tx: Db, run: typeof heartbeatRuns.$inferSelect): Promise { + const names = new Set(); + for (const receipt of Object.values(object(object(run.resultJson).apiToolReceipts)).map(object)) { + if (receipt.state !== "completed" || object(receipt.result).outcome === "unknown") + names.add(typeof receipt.toolName === "string" ? receipt.toolName : "a Paperclip API call"); + } + const rows = await tx.select({ toolName: toolInvocations.toolName }).from(toolInvocations).where(and( + eq(toolInvocations.companyId, run.companyId), eq(toolInvocations.runId, run.id), + sql`${toolInvocations.riskLevel} is distinct from 'read'`, + inArray(toolInvocations.status, ["executing", "failed", "timed_out"]))).limit(20); + for (const row of rows) names.add(row.toolName); + return [...names].slice(0, 20); +} + +/** The opening context of the continuation. It names no person who must act. */ +export function freshContinuationNote(input: { runId: string; unverified: string[]; workspace: "restored_last_save" | "kept" }) { + const actions = input.unverified.length + ? `These actions of that run have unverified outcomes: ${input.unverified.join(", ")}. For each one, first check whether it took effect.` + : "No action of that run is recorded with an unknown outcome; check the task's recent history before repeating any side effect."; + const files = input.workspace === "restored_last_save" + ? "Its unsaved file changes could not be verified, so this run starts from the last saved version of the workspace; those changes were not applied." + : "This run starts from the task's saved workspace."; + // How to proceed. Nobody has to restore the previous attempt: the agent + // checks, redoes what is missing, and asks only through the normal approval. + const guidance = "Completed actions with recorded results are still not repeated; this applies only to the actions above, whose outcome is unknown. " + + "If an action did not take effect, or repeating it is safe, do it again and continue the task. " + + "If repeating it would be a governed or irreversible action, request it through the normal approval step. " + + "Nothing about the previous attempt needs to be restored before you continue."; + return `The previous attempt (run ${input.runId}) was cut off before it finished. ${files} ${actions} ${guidance}`; +} + +const USER_TEXT = "The previous run was cut off. Paperclip continues the task in a fresh run from its last saved work."; + +/** Abandons the source run's remote workspace epoch when it still owns it. */ +async function fenceSourceWorkspace(tx: Db, run: typeof heartbeatRuns.$inferSelect) { + const parsed = remoteWorkspaceRunReferenceSchema.safeParse(object(run.runnerProfileJson).remoteWorkspace); + if (!parsed.success || parsed.data.state !== "prepared") return null; + const reference = parsed.data; + const [workspace] = await tx.select({ metadata: executionWorkspaces.metadata }).from(executionWorkspaces).where(and( + eq(executionWorkspaces.companyId, run.companyId), eq(executionWorkspaces.id, reference.workspaceId))); + let authority; + try { authority = readRemoteWorkspaceAuthority(workspace?.metadata); } catch { return null; } + if (!authority?.location || authority.writerRunId !== run.id || authority.epoch !== reference.epoch) return null; + try { + const abandoned = await tx.transaction(savepoint => abandonUnverifiedRemoteWorkspaceEpoch(savepoint, { + companyId: run.companyId, workspaceId: reference.workspaceId, runId: run.id, epoch: authority.epoch, + snapshotId: authority.snapshotId, location: authority.location! })); + return { workspaceId: reference.workspaceId, abandonedEpoch: authority.epoch, epoch: abandoned.authority.epoch, + snapshotId: authority.snapshotId, + quarantine: { state: "retained_unapplied" as const, remoteCwd: authority.location.remoteCwd, + providerLeaseId: authority.location.providerLeaseId } }; + } catch (error) { + if (error instanceof Error && error.message === "remote_workspace_authority_changed") return null; + throw error; + } +} + +/** + * The one distinction this module turns on: a real human gate versus system + * uncertainty. + * + * A human gate is a decision a person actually made or still owes: a pending + * approval or question (`personOwnedTaskWait`), a hold a user owns, or an + * operator decision recorded on the hold (an owner-gone attestation, an + * explicit continuation, a reconciliation). The fallback never retires or + * bypasses one. + * + * Everything else is system uncertainty, however it is labelled: a + * no-replay record (`automaticRecovery.replay: blocked`, "outcome unknown after + * an interruption"), a hold whose owner type is `board` because nobody else was + * assigned, or a controller whose process space cannot be verified. Owner type + * alone never proves that a person must act. For these the fallback starts a + * fresh run, never a replay: the interrupted turn is not re-sent, no tool call + * or write is re-executed, and any governed action goes through its approval + * gate again. + */ +export function isHumanGate(hold: Pick): boolean { + return Boolean(hold.ownerUserId || hold.evidence.ownerGoneAttestation || hold.evidence.explicitUserContinuation + || hold.evidence.executionReconciliation); +} + +const isRestoreHold = (hold: typeof issueRecoveryActions.$inferSelect) => + hold.evidence.workspaceRestoreFailure !== undefined || hold.evidence.workspaceRestoreRecovery !== undefined; +const blocksExecution = (hold: typeof issueRecoveryActions.$inferSelect) => + ["active", "escalated"].includes(hold.status) || object(hold.evidence.automaticRecovery).replay === "blocked"; + +/** A reconciliation hold that blocks the task and that this decision settles. */ +function isOwnedReconciliationHold(hold: typeof issueRecoveryActions.$inferSelect) { + if (!(EXECUTION_RECONCILIATION_CAUSES as readonly string[]).includes(hold.cause) || !blocksExecution(hold)) return false; + if (isHumanGate(hold)) return false; + // A restore hold is owned only once its saved-work recovery completed. + return !isRestoreHold(hold) || readSystemRecovery(hold.evidence)?.state === "complete"; +} + +/** + * The old local writer's state. `alive`: its process is running on this host, + * so it is still executing and is settled by its own owner (stop, reaper) + * first. `ended`: no process this host can see and no allocation or workspace + * finalization left unsettled. `unproven`: anything else (another host, an + * unsettled allocation); the continuation is isolated from it, never waits. + */ +async function localWriterState(tx: Db, run: typeof heartbeatRuns.$inferSelect): Promise<"alive" | "ended" | "unproven"> { + // The shared owner proof compares the recorded process identity (host, PID + // space, start time), so a recycled PID is never mistaken for the old writer. + const proof = await proveRunProcessGone(run, "fresh_continuation"); + if (proof?.verdict === "alive") return "alive"; + if (proof?.verdict === "unprovable" || await hasPendingRunCleanup(tx, run.companyId, run.id)) return "unproven"; + return "ended"; +} + +/** The workspace selection a delivered continuation carries (read only when its context names it). */ +export async function readFreshContinuationReadiness(db: Db, run: Pick, issueId: string) { + const recordId = object(run.contextSnapshot).freshContinuationIsolation; + if (typeof recordId !== "string" || !/^[0-9a-f-]{36}$/i.test(recordId)) return null; + const [record] = await db.select({ evidence: issueRecoveryActions.evidence }).from(issueRecoveryActions).where(and( + eq(issueRecoveryActions.companyId, run.companyId), eq(issueRecoveryActions.sourceIssueId, issueId), + sql`${issueRecoveryActions.id}::text = ${recordId}`, + sql`${issueRecoveryActions.evidence}#>>'{freshContinuation,isolation}' = 'fresh_isolated_workspace'`)).limit(1); + const sourceRunId = object(record?.evidence.freshContinuation).sourceRunId; + if (typeof sourceRunId !== "string") return null; + return { mode: "fresh_isolated_workspace" as const, retryIntentId: recordId, sourceRunId, retainedSourceIds: [] as string[] }; +} + +export async function ensureFreshContinuation(db: Db, input: Input): Promise { + return db.transaction(tx => continueFreshInTransaction(tx as unknown as Db, input)); +} + +/** + * The fallback inside the caller's transaction. Locks in the shared order + * (task, coordinator, run, recovery actions, workspace); rows the caller + * already locked are locked again harmlessly. + */ +export async function continueFreshInTransaction(tx: Db, input: Input): Promise { + const now = input.now && Number.isFinite(input.now.getTime()) ? input.now : new Date(); + const { companyId } = input; + const [peek] = await tx.select({ issueId: heartbeatRuns.issueId, nativeIssueId: heartbeatRuns.nativeIssueId, + contextSnapshot: heartbeatRuns.contextSnapshot }).from(heartbeatRuns) + .where(and(eq(heartbeatRuns.companyId, companyId), eq(heartbeatRuns.id, input.runId))); + if (!peek) return { kind: "not_applicable", reason: "run_missing" }; + const contextIssueId = object(peek.contextSnapshot).issueId; + const issueId = peek.nativeIssueId ?? peek.issueId ?? (typeof contextIssueId === "string" ? contextIssueId : null); + if (!issueId) return { kind: "not_applicable", reason: "run_has_no_task" }; + const [issue] = await tx.select().from(issues).where(and(eq(issues.companyId, companyId), eq(issues.id, issueId))).for("update"); + const [coordinator] = await tx.select().from(nativeRunFinalizations).where(and( + eq(nativeRunFinalizations.companyId, companyId), eq(nativeRunFinalizations.runId, input.runId))).for("update"); + const [run] = await tx.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, companyId), + eq(heartbeatRuns.id, input.runId))).for("update"); + if (!issue || !run) return { kind: "not_applicable", reason: "run_missing" }; + if (!UNFINISHED_STATUSES.includes(run.status) || !run.finishedAt) return { kind: "not_applicable", reason: "run_not_unfinished" }; + if (!issue.assigneeAgentId || issue.assigneeAgentId !== run.agentId || issue.assigneeUserId + || ["done", "cancelled"].includes(issue.status)) return { kind: "not_applicable", reason: "task_changed" }; + + const holds = await tx.select().from(issueRecoveryActions).where(and(eq(issueRecoveryActions.companyId, companyId), + eq(issueRecoveryActions.sourceIssueId, issue.id), + or(sql`${issueRecoveryActions.evidence}->>'runId' = ${run.id}`, sql`${issueRecoveryActions.evidence}->>'sourceRunId' = ${run.id}`))) + .orderBy(asc(issueRecoveryActions.createdAt), asc(issueRecoveryActions.id)).for("update"); + const prior = holds.find(hold => object(hold.evidence.freshContinuation).sourceRunId === run.id); + if (prior) return { kind: "already_continued", recoveryActionId: prior.id }; + // The holds this decision owns: reconciliation holds that still block the + // task. Workspace restore/repair holds stay with workspace recovery, and + // resolved history is never rewritten. + const ownedHolds = holds.filter(isOwnedReconciliationHold); + + // Every wait is bounded in time: about 10 minutes from the first pending + // check, or 15 while the exact-recovery owner shows progress (a new run + // event, output or lease renewal since the last check). Then the fallback + // stops waiting and continues in isolation (writes revoked, new root). + const pendingMarker = holds.map(hold => object(hold.evidence[FRESH_CONTINUATION_CHECK_KEY])) + .filter(check => check.kind === "exact_recovery_pending" && typeof check.firstPendingAt === "number") + .sort((a, b) => Number(a.firstPendingAt) - Number(b.firstPendingAt))[0]; + // Saved-work recovery shows progress when its generation advances (revision + // or attempt) or its hold is updated; the run and coordinator when they + // emit output, renew a lease or update. + const savedWork = holds.map(hold => readSystemRecovery(hold.evidence)).filter(recovery => recovery !== null); + const progressAt = Math.max(run.updatedAt?.getTime() ?? 0, run.lastOutputAt?.getTime() ?? 0, + coordinator?.updatedAt?.getTime() ?? 0, coordinator?.leaseExpiresAt?.getTime() ?? 0, + ...holds.filter(hold => readSystemRecovery(hold.evidence)).map(hold => hold.updatedAt.getTime())); + const savedWorkSignature = savedWork.map(recovery => `${recovery!.generationId}:${recovery!.revision}:${recovery!.attempts}:${recovery!.state}`) + .sort().join("|"); + const waitedMs = pendingMarker ? now.getTime() - Number(pendingMarker.firstPendingAt) : 0; + const progressing = Boolean(pendingMarker && ((typeof pendingMarker.progressAt === "number" && progressAt > pendingMarker.progressAt) + || (typeof pendingMarker.savedWorkSignature === "string" && savedWorkSignature !== pendingMarker.savedWorkSignature))); + // Saved-work recovery that is running and advancing keeps its own 30-minute + // budget: it may still rescue unsaved files. Anything idle gets the normal bound. + const savedWorkAdvancing = progressing && savedWork.some(recovery => recovery!.state === "running"); + const waitBounded = savedWorkAdvancing ? waitedMs >= FRESH_CONTINUATION_SAVED_WORK_BOUND_MS + : waitedMs >= FRESH_CONTINUATION_PROGRESS_BOUND_MS || (waitedMs >= FRESH_CONTINUATION_PENDING_BOUND_MS && !progressing); + // Rechecks back off 1, 2, 3, 4 minutes, so the bound is reached on time. + const step = Math.min(4, (typeof pendingMarker?.checks === "number" ? pendingMarker.checks : 0) + 1) * EXACT_RECOVERY_RECHECK_MS; + const pending = (reason: string, retryAt: Date): FreshContinuationResult | null => waitBounded ? null + : { kind: "exact_recovery_pending", reason, progressAt, savedWorkSignature, + retryAt: new Date(Math.min(retryAt.getTime(), now.getTime() + step)) }; + + // (a) Something already follows this run: a newer run of the task, a linked + // replacement, or an operator's continuation. + const [newer] = await tx.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(and( + eq(heartbeatRuns.companyId, companyId), sql`${heartbeatRuns.id} <> ${run.id}`, + or(eq(heartbeatRuns.nativeIssueId, issue.id), eq(heartbeatRuns.issueId, issue.id), + sql`${heartbeatRuns.contextSnapshot}->>'issueId' = ${issue.id}`), + or(inArray(heartbeatRuns.status, LIVE_RUN_STATUSES), + sql`(${heartbeatRuns.createdAt}, ${heartbeatRuns.id}) > (${run.createdAt.toISOString()}::timestamptz, ${run.id}::uuid)`))).limit(1); + if (newer || typeof object(coordinator?.failureDetail).successorRunId === "string" + || holds.some(hold => hold.evidence.executionReconciliation && ["pending", "delivered", "delegated"] + .includes(String(hold.evidence.continuationDelivery)))) return { kind: "successor_exists" }; + + // Exact recovery that is still under way keeps its chance, for a bounded + // number of checks; each owner below also bounds itself. + const recheck = new Date(now.getTime() + EXACT_RECOVERY_RECHECK_MS); + const waits: Array = []; + if (adapterExecutionControls.has(run.id)) waits.push(pending("execution_settling", recheck)); + if (coordinator?.leaseOwner || (coordinator?.resultId && coordinator.phase !== "committed") + || (coordinator?.nextAttemptAt && coordinator.nextAttemptAt > now)) + waits.push(pending("native_finalizer_active", + coordinator?.nextAttemptAt && coordinator.nextAttemptAt > now ? coordinator.nextAttemptAt : recheck)); + if (run.controllerLeaseExpiresAt && run.controllerLeaseExpiresAt > now) + waits.push(pending("controller_lease_live", run.controllerLeaseExpiresAt)); + // A preparation that never started provider work has its own bounded retry + // lane (the ownership pass). It gets the first chance; the fallback follows. + if (isInterruptedNativePreparationCandidate(run) && !holds.some(hold => hold.evidence[FRESH_CONTINUATION_CHECK_KEY])) + waits.push(pending("interrupted_preparation_lane", recheck)); + for (const hold of holds) { + const recovery = readSystemRecovery(hold.evidence); + if (recovery && EXACT_RECOVERY_STATES.includes(recovery.state)) + waits.push(pending("saved_work_recovery_running", + new Date(Math.max(recheck.getTime(), recovery.nextAttemptAt ?? 0)))); + if (!isOwnedReconciliationHold(hold) && isRestoreHold(hold) && blocksExecution(hold) && recovery?.state !== "complete") + waits.push(pending("workspace_recovery_owns_restore", recheck)); + const retainedCheck = object(hold.evidence.retainedSourceFallbackCheck); + if (recovery?.state === "exhausted" && typeof retainedCheck.nextCheckAt === "number" && retainedCheck.nextCheckAt > now.getTime()) + waits.push(pending("retained_source_fallback_pending", new Date(retainedCheck.nextCheckAt))); + } + const firstWait = waits.find(wait => wait !== null); + if (firstWait) return firstWait; + // Past the bound, a hold that workspace recovery still owns is settled too: + // the continuation never uses that workspace (isolation below). + const owned = waitBounded ? holds.filter(hold => isOwnedReconciliationHold(hold) + || (isRestoreHold(hold) && blocksExecution(hold) && !isHumanGate(hold))) : ownedHolds; + + // (b) Causes that are the person's. + if (isPersonOwnedFailureCode(run.errorCode)) return { kind: "person_owned", reason: run.errorCode! }; + // A Stop a person (or an agent acting on the task) asked for is never undone. + const cancellation = readRunCancellation(run.resultJson); + if ((cancellation && ["user", "agent"].includes(cancellation.initiator.type)) + || object(run.resultJson).operatorInterrupted === true + || (run.status === "cancelled" && (isAcknowledgedNativeStop(run) || isAcknowledgedNativeReassignmentStop(run) + // A cancellation that recorded neither its cause nor a system initiator may + // be a person's Stop saved by an older release; it is never undone. + || (!cancellation && !run.errorCode)))) + return { kind: "person_owned", reason: "stopped_on_request" }; + // A task in review waits for its reviewer. + if (issue.status === "in_review") return { kind: "person_owned", reason: "in_review" }; + // A recorded operator reconciliation that already delivered a continuation + // was handled above (successor_exists); any other human gate stays. + if (holds.some(hold => blocksExecution(hold) && isHumanGate(hold) && !hold.evidence.executionReconciliation) + || holds.some(hold => hold.ownerUserId || hold.evidence.ownerGoneAttestation || hold.evidence.explicitUserContinuation)) + return { kind: "person_owned", reason: "operator_decision_recorded" }; + const taskWait = await personOwnedTaskWait(tx, { companyId, issue, run }); + if (taskWait) return { kind: "person_owned", reason: taskWait }; + let ownsBlock = false; + if (issue.status === "blocked") { + const receipts = holds.filter(hold => hold.evidence.nativeFailureBlock !== undefined || hold.evidence.legacyCancellationBlock !== undefined + || hold.evidence.nativeBootstrapFailureBlock !== undefined); + ownsBlock = (receipts.length ? receipts : holds).some(hold => holdOwnsBlockedStatus(hold, issue, run)) + || receipts.some(hold => [hold.evidence.legacyCancellationBlock, hold.evidence.nativeBootstrapFailureBlock] + .some(block => object(block).runId === run.id && object(block).statusVersion === Number(issue.statusVersion))) + // A run that left no hold: its terminal failure set the block and nothing changed it since. + || (!holds.length && issue.lastStatusDecisionId === null && issue.blockedTransitionAt !== null + && issue.blockedTransitionAt.getTime() >= run.finishedAt.getTime() - 1_000); + if (!ownsBlock) return { kind: "person_owned", reason: "blocked_by_another_decision" }; + const readiness = await issueService(tx).listDependencyReadiness(companyId, [issue.id], tx); + if (readiness.get(issue.id)?.isDependencyReady === false) return { kind: "dependency_wait" }; + } + + // (c) Bounded per task: the restart lane's hourly cap, then back off. + const windowStart = new Date(now.getTime() - FRESH_CONTINUATION_WINDOW_MS).toISOString(); + const recent = await tx.select({ recordedAt: sql`${issueRecoveryActions.evidence}#>>'{freshContinuation,recordedAt}'` }) + .from(issueRecoveryActions).where(and(eq(issueRecoveryActions.companyId, companyId), + eq(issueRecoveryActions.sourceIssueId, issue.id), + sql`${issueRecoveryActions.evidence}#>>'{freshContinuation,schema}' = ${FRESH_CONTINUATION_SCHEMA}`, + sql`${issueRecoveryActions.evidence}#>>'{freshContinuation,recordedAt}' > ${windowStart}`)) + .orderBy(asc(sql`${issueRecoveryActions.evidence}#>>'{freshContinuation,recordedAt}'`)); + if (recent.length >= FRESH_CONTINUATIONS_PER_HOUR) { + const oldest = new Date(recent[0]!.recordedAt).getTime(); + return { kind: "backoff", retryAt: new Date(oldest + FRESH_CONTINUATION_WINDOW_MS) }; + } + + // Saved user input (a message or a Retry the person pressed) continues the + // task through normal admission once nothing blocks it; a second, automatic + // continuation would run after it. + const [savedInput] = await tx.select({ id: agentWakeupRequests.id }).from(agentWakeupRequests).where(and( + eq(agentWakeupRequests.companyId, companyId), eq(agentWakeupRequests.status, "deferred_issue_execution"), + eq(agentWakeupRequests.requestedByActorType, "user"), sql`${agentWakeupRequests.payload}->>'issueId' = ${issue.id}`)).limit(1); + let delivery: "recorded" | "caller_owns" | "saved_input" = input.delivery === "caller_owns" ? "caller_owns" + : savedInput ? "saved_input" : "recorded"; + + // (d) Continue: fence the old workspace epoch, settle every hold of the run, + // release the Blocked status this failure owns, and record one continuation. + const remoteSource = remoteWorkspaceRunReferenceSchema.safeParse(object(run.runnerProfileJson).remoteWorkspace).success; + const writer = remoteSource ? null : await localWriterState(tx, run); + // A local process still running on this host is executing: its own owner + // (the reaper or a Stop) settles it first, then the fallback continues. + const aliveWait = writer === "alive" ? pending("previous_process_running", new Date(now.getTime() + step)) : null; + if (aliveWait) return aliveWait; + const fenced = await fenceSourceWorkspace(tx, run); + // Never claim a stop that was not proven: record what isolates the successor. + const isolation: FreshContinuationIsolation = fenced || remoteSource ? "remote_epoch" + : writer === "ended" && !waitBounded ? "writer_ended" : "fresh_isolated_workspace"; + // With no task workspace binding to move, only a run that carries the + // isolation in its context can avoid the shared directory: the recorded + // continuation runs first, and saved input follows it. + if (isolation === "fresh_isolated_workspace" && !issue.executionWorkspaceId && delivery === "saved_input") delivery = "recorded"; + const unverified = await unverifiedActions(tx, run); + const note = freshContinuationNote({ runId: run.id, unverified, + workspace: isolation === "writer_ended" ? "kept" : "restored_last_save" }); + const decision: ExecutionReconciliation & { providerStopProof: "writer_ended" | "isolated" } = { runId: run.id, providerStopped: true, + // Only a proven end is a stop. `isolated` means exactly: the old run's agent + // token is refused for writes, and the continuation runs in a new workspace + // root (a fenced remote epoch or a new local workspace). Nothing more. + providerStopProof: isolation === "writer_ended" ? "writer_ended" : "isolated", + actionOutcome: "mixed", outcomeEvidence: note, + workspaceRepairEvidence: fenced + ? `Paperclip abandoned unverified workspace epoch ${fenced.abandonedEpoch} of run ${run.id}; the continuation restores ` + + `${fenced.snapshotId ? `committed snapshot ${fenced.snapshotId}` : "the workspace source"} into a new root.` + : isolation === "fresh_isolated_workspace" + ? `The previous writer of run ${run.id} is not proven stopped, so the continuation starts in a new isolated workspace; no unverified files are applied.` + : `The continuation of run ${run.id} starts from the task's last saved workspace; no unverified files are applied.` }; + const freshContinuation = { schema: FRESH_CONTINUATION_SCHEMA, sourceRunId: run.id, trigger: input.trigger, + failureCode: run.errorCode ?? null, delivery, recordedAt: now.toISOString(), isolation, + stopProof: isolation === "writer_ended" ? "writer_ended" : fenced ? "unproven_epoch_abandoned" : "unproven_isolated", + unverifiedActions: unverified, ...(fenced ? { workspace: fenced } : {}) }; + const reconciliation = { ...decision, actorId: FRESH_CONTINUATION_ACTOR, recordedAt: now.toISOString() }; + // Who, what, why and when. A fresh run is not a replay: the interrupted turn + // is not re-sent, no tool call or write is re-executed, and any governed + // action the new run wants goes through its approval gate again. + const settlement = { schema: FRESH_CONTINUATION_SCHEMA, actorType: "system", actorId: FRESH_CONTINUATION_ACTOR, + decision: "continue_in_fresh_run", replay: "none", sourceRunId: run.id, failureCode: run.errorCode ?? null, + reason: "exact_resumption_unavailable", isolation, unverifiedActions: unverified, recordedAt: now.toISOString() }; + const ownerHold = owned.find(hold => issue.status === "blocked" && holdOwnsBlockedStatus(hold, issue, run)) ?? owned.at(-1); + + await notifyDeliveryWork(tx, DELIVERY_QUEUES.executionContinuation); + await notifyDeliveryWork(tx, DELIVERY_QUEUES.executionReplacement); + await notifyDeliveryWork(tx, DELIVERY_QUEUES.issueMonitors); + await notifyDeliveryWork(tx, DELIVERY_QUEUES.agentTimers); + await notifyStatusCardIssueChange(tx, companyId); + await notifyRoutineExecutionStatus(tx, issue.id, companyId); + if (delivery === "saved_input") await notifyDeferredWakesForIssue(tx, { companyId, issueId: issue.id }); + + let primaryId: string; + const continuationDelivery = delivery === "recorded" ? "pending" : "not_requested"; + if (ownerHold) { + primaryId = ownerHold.id; + for (const hold of owned) { + const primary = hold.id === ownerHold.id; + // The earlier no-replay decision stays on the hold as history, and the + // fallback is recorded beside it as its own attributed system decision. + const { automaticRecovery, [FRESH_CONTINUATION_CHECK_KEY]: _check, ...evidence } = hold.evidence; + await tx.update(issueRecoveryActions).set({ status: "resolved", outcome: "restored", resolvedAt: hold.resolvedAt ?? now, + updatedAt: now, ownerType: "system", ownerAgentId: null, ownerUserId: null, wakePolicy: null, monitorPolicy: null, + returnOwnerAgentId: primary ? run.agentId : hold.returnOwnerAgentId, nextAction: USER_TEXT, + resolutionNote: "continued_fresh_from_last_saved", + evidence: { ...evidence, executionReconciliation: reconciliation, freshContinuationSettlement: settlement, + ...(automaticRecovery !== undefined ? { automaticRecoveryHistory: automaticRecovery } : {}), + ...(primary ? { freshContinuation, continuationDelivery } + : { continuationDelivery: "coalesced", coalescedIntoRecoveryActionId: ownerHold.id }) }, + }).where(and(eq(issueRecoveryActions.companyId, companyId), eq(issueRecoveryActions.id, hold.id))); + } + } else { + const [created] = await tx.insert(issueRecoveryActions).values({ companyId, sourceIssueId: issue.id, + kind: "active_run_watchdog", status: "resolved", outcome: "restored", ownerType: "system", + returnOwnerAgentId: run.agentId, cause: FRESH_CONTINUATION_CAUSE, fingerprint: `fresh-continuation:${run.id}`, + nextAction: USER_TEXT, resolutionNote: "continued_fresh_from_last_saved", resolvedAt: now, attemptCount: 1, + evidence: { runId: run.id, originalFailureCode: run.errorCode ?? null, executionReconciliation: reconciliation, + freshContinuationSettlement: settlement, freshContinuation, continuationDelivery } }).returning({ id: issueRecoveryActions.id }); + primaryId = created!.id; + } + // The replaced run loses its write authority: its agent may still be alive + // in an unreachable sandbox, and only the continuation may act on the task. + await tx.update(heartbeatRuns).set({ resultJson: sql`coalesce(${heartbeatRuns.resultJson}, '{}'::jsonb) + || ${JSON.stringify({ [FRESH_CONTINUATION_SUPERSEDED_KEY]: now.toISOString() })}::jsonb` }).where(and( + eq(heartbeatRuns.companyId, companyId), eq(heartbeatRuns.id, run.id))); + // The source is never replayed or replaced exactly after this decision. + if (coordinator) { + await tx.update(nativeRunFinalizations).set({ failureDetail: sql`coalesce(${nativeRunFinalizations.failureDetail}, '{}'::jsonb) + || ${JSON.stringify({ replacementDenied: "fresh_continuation" })}::jsonb` }).where(and( + eq(nativeRunFinalizations.companyId, companyId), eq(nativeRunFinalizations.runId, run.id))); + } + // The isolation is a property of the task's next run, whatever path starts + // it (a system continuation, saved input, a person's Retry, a sweep wake): + // the task no longer points at the directory the old writer may still use, + // so every next run prepares a new workspace. The old one is left in place. + if (isolation === "fresh_isolated_workspace" && issue.executionWorkspaceId) { + await tx.update(issues).set({ executionWorkspaceId: null, workspaceBindingRevision: sql`${issues.workspaceBindingRevision} + 1`, + updatedAt: now }).where(and(eq(issues.companyId, companyId), eq(issues.id, issue.id))); + } + if (issue.status === "blocked") { + await tx.update(issues).set({ status: "todo", unblockDescriptor: null, blockedTransitionAt: null, + blockedOwnerNotifiedAt: null, updatedAt: now }).where(and(eq(issues.companyId, companyId), eq(issues.id, issue.id))); + await logActivity(tx, { companyId, actorType: "system", actorId: FRESH_CONTINUATION_ACTOR, action: "issue.updated", + entityType: "issue", entityId: issue.id, agentId: run.agentId, runId: run.id, + details: { status: "todo", previousStatus: "blocked", reason: "fresh_continuation", recoveryActionId: primaryId, + _previous: { status: "blocked" } } }); + } + await logActivity(tx, { companyId, actorType: "system", actorId: FRESH_CONTINUATION_ACTOR, + action: "issue.continued_from_saved_work", entityType: "issue", entityId: issue.id, agentId: run.agentId, runId: run.id, + details: { recoveryActionId: primaryId, sourceRunId: run.id, failureCode: run.errorCode ?? null, trigger: input.trigger, + delivery, workspaceEpochAbandoned: Boolean(fenced), unverifiedActionCount: unverified.length } }); + logger.info({ runId: run.id, issueId: issue.id, failureCode: run.errorCode, trigger: input.trigger, delivery }, + "Unfinished run continues in a fresh run from saved work"); + return { kind: "continued", recoveryActionId: primaryId, delivery, isolation }; +} + +/** Records why a hold was not continued yet, and when to look again. */ +export async function recordFreshContinuationCheck(db: Db, input: { companyId: string; actionId: string }, + result: FreshContinuationResult, now = new Date()) { + if (result.kind === "continued" || result.kind === "already_continued") return; + const nextCheckAt = result.kind === "backoff" || result.kind === "exact_recovery_pending" ? result.retryAt.getTime() + : result.kind === "person_owned" || result.kind === "dependency_wait" ? now.getTime() + PERSON_RECHECK_MS : null; + const [row] = await db.select({ evidence: issueRecoveryActions.evidence }).from(issueRecoveryActions).where(and( + eq(issueRecoveryActions.companyId, input.companyId), eq(issueRecoveryActions.id, input.actionId))); + const prior = object(row?.evidence[FRESH_CONTINUATION_CHECK_KEY]); + const same = prior.kind === result.kind; + const checks = same && typeof prior.checks === "number" ? prior.checks + 1 : 1; + const firstPendingAt = result.kind === "exact_recovery_pending" + ? (same && typeof prior.firstPendingAt === "number" ? prior.firstPendingAt : now.getTime()) : null; + const marker = { kind: result.kind, reason: "reason" in result ? result.reason : null, checks, checkedAt: now.getTime(), nextCheckAt, + ...(firstPendingAt !== null ? { firstPendingAt, + progressAt: result.kind === "exact_recovery_pending" ? result.progressAt ?? null : null, + savedWorkSignature: result.kind === "exact_recovery_pending" ? result.savedWorkSignature ?? null : null } : {}) }; + await db.update(issueRecoveryActions).set({ evidence: sql`${issueRecoveryActions.evidence} + || jsonb_build_object(${FRESH_CONTINUATION_CHECK_KEY}::text, ${JSON.stringify(marker)}::jsonb)` }).where(and( + eq(issueRecoveryActions.companyId, input.companyId), eq(issueRecoveryActions.id, input.actionId))); +} + +/** Not yet checked, or due for another check. */ +export function freshContinuationCheckDue(now: Date) { + return sql`(${issueRecoveryActions.evidence}->${FRESH_CONTINUATION_CHECK_KEY} is null + or coalesce((${issueRecoveryActions.evidence}#>>'{freshContinuationCheck,nextCheckAt}')::bigint, 9223372036854775807) <= ${now.getTime()})`; +} + +/** + * Holds that today keep a task waiting with no automatic continuation, including + * every shape older releases saved: settled-but-blocked no-replay holds, and + * saved-work recoveries that finished or gave up. Exact recovery still under + * way is excluded (it is checked again by its owner and here afterwards). + */ +export function heldExecutionsAwaitingFreshContinuation(db: Db, now: Date, limit: number) { + return db.select({ id: issueRecoveryActions.id, companyId: issueRecoveryActions.companyId, + runId: sql`coalesce(${issueRecoveryActions.evidence}->>'runId', ${issueRecoveryActions.evidence}->>'sourceRunId')` }) + .from(issueRecoveryActions).innerJoin(issues, and(eq(issues.id, issueRecoveryActions.sourceIssueId), + eq(issues.companyId, issueRecoveryActions.companyId))) + .where(and(heldExecutionWhere(), freshContinuationCheckDue(now))) + .orderBy(asc(issueRecoveryActions.updatedAt), asc(issueRecoveryActions.id)) + .limit(limit); +} + +/** Held reconciliation records of a task's latest unfinished run (joined to its task). */ +function heldExecutionWhere(options: { includeActive?: boolean } = {}) { + return and( + inArray(issueRecoveryActions.cause, [...EXECUTION_RECONCILIATION_CAUSES]), + sql`${issueRecoveryActions.evidence}->'executionReconciliation' is null`, + sql`${issueRecoveryActions.evidence}->'freshContinuation' is null`, + sql`coalesce(${issueRecoveryActions.evidence}->>'runId', ${issueRecoveryActions.evidence}->>'sourceRunId') is not null`, + or( + sql`${issueRecoveryActions.evidence}->'automaticRecovery'->>'replay' = 'blocked'`, + and(inArray(issueRecoveryActions.status, ["active", "escalated"]), + sql`${issueRecoveryActions.evidence}#>>'{systemRecovery,state}' in ('complete', 'exhausted')`), + options.includeActive ? and(inArray(issueRecoveryActions.status, ["active", "escalated"]), + eq(issueRecoveryActions.kind, "active_run_watchdog")) : undefined, + // Saved-work recovery still under way: checked so its bound is reached + // (exact recovery keeps its first chance inside the fallback). + sql`${issueRecoveryActions.evidence}#>>'{systemRecovery,state}' in ('scheduled', 'running', 'awaiting_evidence')`, + ), + isNull(issueRecoveryActions.ownerUserId), + sql`${issues.status} not in ('done', 'cancelled')`, + sql`${issues.assigneeAgentId} is not null`, + // Only the task's latest run, unfinished and still its assignee's: other + // holds are history, and are never touched here. + sql`exists (select 1 from ${heartbeatRuns} source where source.company_id = ${issueRecoveryActions.companyId} + and source.id::text = coalesce(${issueRecoveryActions.evidence}->>'runId', ${issueRecoveryActions.evidence}->>'sourceRunId') + and source.status in ('failed', 'timed_out', 'interrupted', 'cancelled') and source.finished_at is not null + and source.agent_id = ${issues.assigneeAgentId} + and not exists (select 1 from ${heartbeatRuns} newer where newer.company_id = source.company_id and newer.id <> source.id + and (newer.native_issue_id = ${issues.id} or newer.issue_id = ${issues.id} or newer.context_snapshot->>'issueId' = ${issues.id}::text) + and (newer.status in ('queued', 'running', 'scheduled_retry') or (newer.created_at, newer.id) > (source.created_at, source.id))))`, + )!; +} + +/** The earliest time a deferred check becomes due again, if any. */ +export async function nextFreshContinuationCheckAt(db: Db): Promise { + // The same records the held-run query and the disposition pass would select; + // a deadline on a record nothing would act on never schedules a scan. + // That includes active holds that backed off: the disposition pass rechecks + // them when due, and nothing else would wake it then. + const [held] = await db.select({ at: sql`min((${issueRecoveryActions.evidence}#>>'{freshContinuationCheck,nextCheckAt}')::bigint)` }) + .from(issueRecoveryActions).innerJoin(issues, and(eq(issues.id, issueRecoveryActions.sourceIssueId), + eq(issues.companyId, issueRecoveryActions.companyId))) + .where(and(heldExecutionWhere({ includeActive: true }), + sql`${issueRecoveryActions.evidence}#>>'{freshContinuationCheck,nextCheckAt}' is not null`)); + return held?.at ? Number(held.at) : null; +} + +/** + * Continues tasks held by recovery records, including records saved by older + * releases, so tasks already waiting continue after deploy without a Retry. + * Runs on the execution-disposition worker. Bounded per pass. + */ +export async function continueHeldExecutions(db: Db, now = new Date(), limit = 25) { + const candidates = await heldExecutionsAwaitingFreshContinuation(db, now, limit); + let continued = 0; + const seen = new Set(); + for (const candidate of candidates) { + if (!candidate.runId || seen.has(candidate.runId)) continue; + seen.add(candidate.runId); + try { + const result = await ensureFreshContinuation(db, { companyId: candidate.companyId, runId: candidate.runId, + trigger: "held_recovery", now }); + if (result.kind === "continued") continued += 1; + else await recordFreshContinuationCheck(db, { companyId: candidate.companyId, actionId: candidate.id }, result, now); + } catch (error) { + logger.warn({ err: error, recoveryActionId: candidate.id }, "Fresh continuation of a held task deferred"); + await recordFreshContinuationCheck(db, { companyId: candidate.companyId, actionId: candidate.id }, + { kind: "exact_recovery_pending", reason: "fallback_failed", retryAt: new Date(now.getTime() + EXACT_RECOVERY_RECHECK_MS) }, now) + .catch(() => undefined); + } + } + return { checked: seen.size, continued }; +} + +/** Holds settled together with a primary record follow its final delivery + * state, so no coalesced hold outlives the record it points at. */ +export async function settleCoalescedFreshContinuationHolds(db: Db, input: { companyId: string; primaryId: string; + delivery: "delivered" | "invalidated"; continuationRunId?: string | null }) { + await db.update(issueRecoveryActions).set({ evidence: sql`${issueRecoveryActions.evidence} || ${JSON.stringify({ + continuationDelivery: input.delivery, ...(input.continuationRunId ? { continuationRunId: input.continuationRunId } : {}) })}::jsonb` }) + .where(and(eq(issueRecoveryActions.companyId, input.companyId), + sql`${issueRecoveryActions.evidence}->>'coalescedIntoRecoveryActionId' = ${input.primaryId}`, + sql`${issueRecoveryActions.evidence}->>'continuationDelivery' = 'coalesced'`)); +} + +/** A fresh continuation of this task is recorded and its run does not exist yet. */ +export async function hasPendingFreshContinuation(db: Db, companyId: string, issueId: string) { + const [row] = await db.select({ id: issueRecoveryActions.id }).from(issueRecoveryActions).where(and( + eq(issueRecoveryActions.companyId, companyId), eq(issueRecoveryActions.sourceIssueId, issueId), + eq(issueRecoveryActions.status, "resolved"), + sql`${issueRecoveryActions.evidence}->>'continuationDelivery' = 'pending'`, + sql`${issueRecoveryActions.evidence}#>>'{freshContinuation,schema}' = ${FRESH_CONTINUATION_SCHEMA}`)).limit(1); + return Boolean(row); +} + +/** Newest-first list of fresh continuations of one task (diagnostics and tests). */ +export async function listFreshContinuations(db: Db, input: { companyId: string; issueId: string }) { + return db.select().from(issueRecoveryActions).where(and(eq(issueRecoveryActions.companyId, input.companyId), + eq(issueRecoveryActions.sourceIssueId, input.issueId), + sql`${issueRecoveryActions.evidence}#>>'{freshContinuation,schema}' = ${FRESH_CONTINUATION_SCHEMA}`, + gt(sql`${issueRecoveryActions.evidence}#>>'{freshContinuation,recordedAt}'`, ""))) + .orderBy(desc(issueRecoveryActions.updatedAt)); +} diff --git a/server/src/services/fresh-workspace-continuation.ts b/server/src/services/fresh-workspace-continuation.ts index c05d2b3c233..710147a2bfd 100644 --- a/server/src/services/fresh-workspace-continuation.ts +++ b/server/src/services/fresh-workspace-continuation.ts @@ -20,6 +20,7 @@ import { taskRetryRunAncestry } from "./recovery-run-ancestry.js"; import { parseNativeExecutionInput } from "../vendor/paperclip-runner/index.js"; import { nativeExecutionUsesTaskWorkspace } from "./heartbeat/external-provider.js"; import { preparePluginWorkspace, type WorkspaceWorkers } from "./plugin-workspaces.js"; +import { readFreshContinuationReadiness } from "./fresh-continuation-fallback.js"; export type ContinuationReadiness = | { mode: "resume_preserved_workspace"; preservationReceiptId: string } @@ -360,6 +361,11 @@ export async function readFreshWorkspaceReadiness(db: Db, run: Pick>'{explicitUserContinuation,runId}' = ${run.id}`, diff --git a/server/src/services/heartbeat/queue.ts b/server/src/services/heartbeat/queue.ts index d51f66b3bd4..4adbbeb259e 100644 --- a/server/src/services/heartbeat/queue.ts +++ b/server/src/services/heartbeat/queue.ts @@ -3,6 +3,7 @@ import { connectionIntentService } from "../connection-intents.js"; import { verifyBlockerStallWake } from "../recovery/blocker-stall-wakeups.js"; import { CONTEXT_COMPACTION_WAKE_REASON, ContextCompactionError, isContextCompactionRun, readContextCompactionRequest } from "../context-compaction.js"; import { isProcessRunAdmissionClosed } from "./run-admission.js"; +import { continueFreshInTransaction, hasPendingFreshContinuation, settleCoalescedFreshContinuationHolds } from "../fresh-continuation-fallback.js"; import { refreshRunStartYieldIfStale } from "../run-start-handover.js"; import { deliveredQueuedCommentIds } from "../queued-comment-delivery.js"; import { hasAutomaticInteractionDeliveryHold, INTERACTION_DELIVERY_DENIED, recheckQueuedRunInteractions, withInteractionDeliveryOrigin } from "../agent-interaction-delivery.js"; @@ -1256,6 +1257,7 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende if (!previousRunId || previousRunId === run.id) continue; const [previous] = await tx.select({ status: heartbeatRuns.status, agentId: heartbeatRuns.agentId, issueId: heartbeatRuns.issueId, nativeIssueId: heartbeatRuns.nativeIssueId, + supersededByFreshContinuation: sql`${heartbeatRuns.resultJson} ? 'freshContinuationSupersededAt'`, contextIssueId: sql`coalesce(${heartbeatRuns.contextSnapshot}->>'issueId', ${heartbeatRuns.contextSnapshot}->>'taskId')`, }) .from(heartbeatRuns).where(and( @@ -1270,7 +1272,10 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende liveRunExecutions.has(previousRunId)) { return declined("predecessor_still_executing", previousRunId); } - if (await hasPendingRunCleanup(tx, run.companyId, previousRunId)) { + // A fresh continuation replaced the predecessor: its writes are revoked + // and it shares no workspace with this run (a fenced remote epoch or a + // new isolated workspace), so its cleanup continues without holding it. + if (!previous?.supersededByFreshContinuation && await hasPendingRunCleanup(tx, run.companyId, previousRunId)) { return declined("predecessor_cleanup_pending", previousRunId); } } @@ -3632,6 +3637,27 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende } if (action.evidence.continuationDelivery !== "pending") return { kind: "skipped" as const }; + // Under the task lock: a fresh continuation is the task's next run + // only while nothing else continued it. A run started since it was + // recorded (active or already finished, from a person's Retry or + // saved input) consumes it, and a task that moved to review gets none. + const freshRecordedAt = readNonEmptyString(parseObject(action.evidence.freshContinuation).recordedAt); + if (freshRecordedAt) { + const [intervening] = await tx.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(and( + eq(heartbeatRuns.companyId, issue.companyId), sql`${heartbeatRuns.id}::text <> ${sourceRunId}`, + or(eq(heartbeatRuns.nativeIssueId, issue.id), eq(heartbeatRuns.issueId, issue.id), + sql`${heartbeatRuns.contextSnapshot}->>'issueId' = ${issue.id}::text`), + sql`${heartbeatRuns.createdAt} >= ${freshRecordedAt}::timestamptz`)).limit(1); + if (intervening || issue.status === "in_review") { + await tx.update(issueRecoveryActions).set({ evidence: sql`${issueRecoveryActions.evidence} || ${JSON.stringify( + intervening ? { continuationDelivery: "delivered", continuationRunId: intervening.id, continuationSupersededByRun: true } + : { continuationDelivery: "invalidated", continuationInvalidatedReason: "in_review" })}::jsonb` }) + .where(and(eq(issueRecoveryActions.companyId, issue.companyId), eq(issueRecoveryActions.id, action.id))); + await settleCoalescedFreshContinuationHolds(tx as unknown as Db, { companyId: issue.companyId, primaryId: action.id, + delivery: intervening ? "delivered" : "invalidated", continuationRunId: intervening?.id ?? null }); + return { kind: "skipped" as const }; + } + } const [reconciledRun] = await tx.select().from(heartbeatRuns).where(and( eq(heartbeatRuns.companyId, issue.companyId), eq(heartbeatRuns.id, sourceRunId), )); @@ -3727,6 +3753,18 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende const continuationHold = () => executionBlocker ?? { recoveryActionId: null, cause: "native_continuation_requires_reconciliation" as const, nextAction: continuationWait.message, }; + // Only system continuation wakes (sweeps, monitors, timers) reach + // the fresh-continuation fallback. A person's Retry, message or + // queued send keeps its own exact admission; the disposition worker + // settles the hold through the same fallback, and the saved input + // then continues the task. + const systemWake = opts.requestedByActorType !== "user" && !taskRetryActorId && !wakeCommentId + && !durableRequest && !opts.queuedCommentInterruptId && !opts.queuedCommentRequestId && !opts.failedRunId + && !executionReconciliationWake; + // A recorded fresh continuation that has no run yet is this task's + // next run: another system wake is coalesced into it, never a second run. + if (systemWake && !executionBlocker && await hasPendingFreshContinuation(tx as unknown as Db, issue.companyId, issue.id)) + return { kind: "skipped" as const }; if ((executionBlocker || opts.queuedCommentInterruptId) && !ownsReconstructionContinuation && !(await admitExplicitNativeContinuation({ db: tx as unknown as Db, companyId: issue.companyId, issueId: issue.id, agentId, actorType: taskRetryActorId ? "user" : opts.requestedByActorType, actorId: taskRetryActorId ?? opts.requestedByActorId, @@ -3739,7 +3777,23 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende interactionPayload: payload, dryRun: true, onBlocked: (reason, message) => { continuationBlocked = true; continuationWait = { reason, message }; }, - })) && (executionBlocker || (continuationBlocked && !verifiedConversationReset))) return deferBlockedExecution(continuationHold()); + })) && (executionBlocker || (continuationBlocked && !verifiedConversationReset))) { + // A hold left by an unfinished run never refuses an ordinary + // continuation: unless its cause is the person's, the fallback + // settles it in this transaction and this wake becomes the fresh + // continuation from the task's saved work. + // Agent Chat conversations keep their own owner-bound continuation. + const freshSourceRunId = systemWake && executionBlocker?.recoveryActionId && executionBlocker.runId + && !issue.conversationAgentId ? executionBlocker.runId : null; + // The continuation is recorded as pending and owned by the + // execution-continuation worker until a run for it exists: a later + // gate (daily limit, slots, pause, budget), a skip or a crash can + // never consume it. This system wake is coalesced into it. + const fresh = freshSourceRunId ? await continueFreshInTransaction(tx as unknown as Db, { + companyId: issue.companyId, runId: freshSourceRunId, trigger: "continuation_wake", delivery: "record" }) : null; + if (fresh?.kind !== "continued" && fresh?.kind !== "already_continued") return deferBlockedExecution(continuationHold()); + return { kind: "skipped" as const }; + } if ( diff --git a/server/src/services/native-runtime/native-controller-host-recovery.ts b/server/src/services/native-runtime/native-controller-host-recovery.ts index eb0a1602ef3..00c8391492e 100644 --- a/server/src/services/native-runtime/native-controller-host-recovery.ts +++ b/server/src/services/native-runtime/native-controller-host-recovery.ts @@ -28,9 +28,10 @@ export async function requestNativeControllerStopConfirmation(tx: Db, coordinato evidence: { runId: coordinator.runId, controller: { bootId: coordinator.controllerBootId, pid: coordinator.controllerPid, hostHash: coordinator.controllerHostHash, processStartedAt: coordinator.controllerProcessStartedAt?.toISOString() ?? null } }, - nextAction: "Paperclip cannot verify that this run's previous server stopped from the current host. " - + "Confirm that the previous server process has stopped (for example, its " - + "container was replaced), then recovery checks the saved run. Controller confirmation does not confirm that its provider or tools stopped.", + // Optional faster path: without a confirmation, the run ends after a + // bounded wait and the task continues in a fresh, isolated run. + nextAction: "The server running this task restarted. Paperclip continues the task in a fresh run shortly. " + + "Confirming that the previous server stopped is optional and only makes that faster.", }).onConflictDoNothing(); } diff --git a/server/src/services/native-runtime/native-remote-retry-admission.test.ts b/server/src/services/native-runtime/native-remote-retry-admission.test.ts index c717dcd5ece..f34349e5ab1 100644 --- a/server/src/services/native-runtime/native-remote-retry-admission.test.ts +++ b/server/src/services/native-runtime/native-remote-retry-admission.test.ts @@ -651,7 +651,7 @@ describeEmbeddedPostgres("remote native retry execution admission", () => { expect(await f.db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, f.issueId))) .toMatchObject([{ ownerType: "board", wakePolicy: null, evidence: { automaticAdmissionExhausted: true, executorStopEvidence: "unverified", providerPid: 1386, checkpointPreserved: true }, - nextAction: expect.stringContaining("original executor stop and state remain unverified") }]); + nextAction: "This run stopped before it finished. Your saved work is kept." }]); expect(await claimNativeRestartRecoveries({ db: f.db, controller: environment.current.successor, restartKind: "hard", runIds: [f.runId], now: new Date(now.getTime() + 3_600_000) })).toEqual([]); }); diff --git a/server/src/services/native-runtime/native-restart-recovery.ts b/server/src/services/native-runtime/native-restart-recovery.ts index 450e63c531a..6ddd401fcd9 100644 --- a/server/src/services/native-runtime/native-restart-recovery.ts +++ b/server/src/services/native-runtime/native-restart-recovery.ts @@ -989,6 +989,61 @@ export function appendBoundedRecoveryHistory(entry: Record) { )`; } +/** How long a lapsed controller whose process space cannot be verified is + * waited for before its run ends and the task continues in a fresh run. */ +export const NATIVE_NAMESPACE_UNVERIFIED_WAIT_MS = 2 * 60_000; + +/** When the current, unbroken run of namespace waits for this reason began. */ +function namespaceWaitStartedAt(history: unknown, reason: string): number | null { + const entries = Array.isArray(history) ? history as Array> : []; + let since: number | null = null; + for (let index = entries.length - 1; index >= 0; index--) { + const entry = entries[index]!; + if (entry.disposition !== "awaiting_evidence" || entry.reason !== reason) break; + const at = typeof entry.at === "string" ? Date.parse(entry.at) : NaN; + if (Number.isFinite(at)) since = at; + } + return since; +} + +/** Ends a run whose lapsed controller cannot be verified, like a blocked + * restart recovery, and records a system-owned hold for the fallback. */ +async function endNamespaceUnverifiedRun(tx: Db, row: { + run: typeof heartbeatRuns.$inferSelect; coordinator: typeof nativeRunFinalizations.$inferSelect; + issueAssigneeAgentId: string | null; issueStatus: string; +}, now: Date, reason: string, event: ReturnType, recoveryRequestId: string | null) { + await notifyExecutionRunWork(tx, { companyId: row.run.companyId }); + await tx.update(nativeRunFinalizations).set({ phase: "terminal_failure", leaseOwner: null, leaseExpiresAt: null, + nextAttemptAt: null, failureCode: "native_restart_recovery_blocked", + failureDetail: { ...row.coordinator.failureDetail, reason, executorStopEvidence: "unverified" }, + recoveryState: "blocked", recoveryRequestId, recoveryHistory: appendBoundedRecoveryHistory(event), updatedAt: now, + }).where(and(eq(nativeRunFinalizations.runId, row.run.id), eq(nativeRunFinalizations.attempt, row.coordinator.attempt), + eq(nativeRunFinalizations.phase, row.coordinator.phase))); + await notifyExternalAgentSettlement(tx, { companyId: row.run.companyId, runId: row.run.id }); + await notifyNativeEnvironmentSettlement(tx, { companyId: row.run.companyId, runId: row.run.id }); + await notifyInstructionCollection(tx, { companyId: row.run.companyId, runId: row.run.id }); + await notifyCancelledWorkspacePreservation(tx, { companyId: row.run.companyId, runId: row.run.id }); + await notifyUnsafeWorkspaceExportRunChange(tx, row.run); + const [updatedRun] = await tx.update(heartbeatRuns).set({ status: "failed", nativePhase: "terminal_failure", + nativePhaseUpdatedAt: now, executionStatusDeliveryId: randomUUID(), finishedAt: now, + errorCode: "native_restart_recovery_blocked", error: reason, updatedAt: now, + }).where(eq(heartbeatRuns.id, row.run.id)).returning(); + await notifyNativeStatusReassessment(tx, { companyId: row.run.companyId, issueId: row.coordinator.issueId }); + await tx.update(issues).set({ executionRunId: null, updatedAt: now }).where(and(eq(issues.id, row.coordinator.issueId), + eq(issues.companyId, row.run.companyId), eq(issues.executionRunId, row.run.id))); + await tx.update(issues).set({ checkoutRunId: null, updatedAt: now }).where(and(eq(issues.id, row.coordinator.issueId), + eq(issues.companyId, row.run.companyId), eq(issues.checkoutRunId, row.run.id))); + if (row.issueAssigneeAgentId === row.run.agentId && !["done", "cancelled"].includes(row.issueStatus)) { + await issueRecoveryActionService(tx).upsertSourceScoped({ companyId: row.run.companyId, sourceIssueId: row.coordinator.issueId, + kind: "active_run_watchdog", ownerType: "system", returnOwnerAgentId: row.run.agentId, + cause: "native_restart_recovery_blocked", fingerprint: `native-restart:${row.run.id}`, + evidence: { runId: row.run.id, reason, executorStopEvidence: "unverified", providerAttempt: row.coordinator.attempt }, + nextAction: "The server running this task restarted. Paperclip continues the task in a fresh run from its saved work.", + maxAttempts: 3, wakePolicy: null, supersedeOnIdentityChange: true }); + } + if (updatedRun) await preserveNativeFailedWorkspace(tx, updatedRun); +} + /** Shared by restart inspection and failed-owner cleanup under their existing * issue/coordinator/run locks. Publishing attention never grants a new turn. */ export async function surfaceNativeControllerNamespaceAttention(db: Db, input: { @@ -1020,9 +1075,13 @@ export async function surfaceNativeControllerNamespaceAttention(db: Db, input: { evidence: { runId: input.run.id, reason, executorStopEvidence: "unverified", ...(!input.remoteProcess ? { controllerAuthority: { schema: "paperclip.native-controller-authority.v1", digest, leaseExpiresAt: input.coordinator.leaseExpiresAt!.toISOString() } } : {}) }, + // No person is required: once the previous controller has stopped + // renewing its lease for a bounded wait, the run ends and the task + // continues in a fresh, isolated run. Recording the stops is optional + // and only makes that faster. nextAction: input.remoteProcess - ? "Use the task's ordinary Stop action and its environment provider's stop/cleanup recovery. Wait for that exact controller/provider acknowledgement. Local PID checks and local containment confirmation cannot authorize remote recovery." - : "Stop the original controller and provider on their original host. After the saved lease expires, a board operator must record both stops and review action outcomes. Recording containment does not retry the task.", + ? "The server running this task restarted. Paperclip continues the task in a fresh run from its saved work shortly. Using the task's ordinary Stop action is optional and only makes that faster." + : "The server running this task restarted. Paperclip continues the task in a fresh run from its saved work shortly.", createOnly: !existing, supersedeOnIdentityChange: true, attemptCount: 0, maxAttempts: null, timeoutAt: null, lastAttemptAt: null, wakePolicy: null, monitorPolicy: null, @@ -1366,6 +1425,29 @@ export async function claimNativeRestartRecoveries(input: { if (!takeover.allowed && ["controller_host_unrecorded", "controller_host_unprovable"].includes(takeover.reason)) { await requestNativeControllerStopConfirmation(tx as unknown as Db, row.coordinator); } + // The previous controller's lease lapsed (a live one is still renewing it + // and is waited for above) but its process space cannot be verified from + // here. That is system uncertainty, not a person's decision: after a + // bounded wait the run ends, stops holding the task and the agent's + // slots, and the fresh-continuation fallback continues the task with the + // old run's writes revoked and a new workspace root. + // The same holds when the previous controller's host was never recorded + // or cannot be proven from here: confirming its stop is optional. + const unverifiableLapsedController = !takeover.allowed && !nonExecutionOwner + && (row.coordinator.leaseExpiresAt === null || row.coordinator.leaseExpiresAt <= now) + && (namespaceAttentionNeeded || ["controller_host_unrecorded", "controller_host_unprovable"].includes(takeover.reason)); + if (unverifiableLapsedController) { + const waitingSince = namespaceWaitStartedAt(row.coordinator.recoveryHistory, takeover.reason); + if (waitingSince !== null && now.getTime() - waitingSince >= NATIVE_NAMESPACE_UNVERIFIED_WAIT_MS) { + await endNamespaceUnverifiedRun(tx as unknown as Db, row, now, takeover.reason, historyEntry({ + now, restartKind: input.restartKind, controller, generation: row.coordinator.controllerGeneration, + disposition: "blocked", reason: takeover.reason, requestId: input.recoveryRequestId ?? null, + providerAttempt: row.coordinator.attempt, processPid: row.run.processPid, processStartedAt: row.run.processStartedAt, + hasCheckpoint: false, hasProviderEvidence: false, stderrTail: row.run.stderrExcerpt, + }), input.recoveryRequestId ?? null); + return { kind: "blocked", runId: row.run.id, reason: takeover.reason } as const; + } + } if (!takeover.allowed) { if (namespaceAttentionNeeded) { await surfaceNativeControllerNamespaceAttention(tx as unknown as Db, { @@ -1418,7 +1500,9 @@ export async function claimNativeRestartRecoveries(input: { : ownControllerProcess && row.coordinator.leaseExpiresAt && row.coordinator.leaseExpiresAt > now && !input.handedOffForShutdown?.(row.run.id) ? { retryAt: row.coordinator.leaseExpiresAt } : ["controller_lease_held", "controller_lease_grace"].includes(takeover.reason) - ? { retryAt: new Date(now.getTime() + CONTROLLER_LEASE_RENEW_MS) } : {}), + ? { retryAt: new Date(now.getTime() + CONTROLLER_LEASE_RENEW_MS) } + // The bounded wait for an unverifiable controller is checked again when it ends. + : unverifiableLapsedController ? { retryAt: new Date(now.getTime() + NATIVE_NAMESPACE_UNVERIFIED_WAIT_MS) } : {}), } as const; } @@ -1728,9 +1812,11 @@ export async function claimNativeRestartRecoveries(input: { const reason = hold?.reason ?? (ownershipChanged ? "task_ownership_or_status_changed" : exhaustedRemoteRetry ? "execution_recovery_budget_exhausted" : classification.reason); - const nextAction = hold - ? "Automatic admission checks exhausted. The original executor stop and state remain unverified. The provider PID, checkpoint and task bindings are preserved; reconcile that execution before starting fresh work." - : "Inspect the preserved checkpoint and reconcile the previous execution before starting a fresh session."; + // No person is asked to inspect or reconcile: unless the cause is the + // person's, the fresh-continuation fallback continues the task. + // Shown to people: plain words only. A person's Stop or pause keeps the + // task as they asked; otherwise the fallback continues it. + const nextAction = "This run stopped before it finished. Your saved work is kept."; if (!claimKind) { const generation = row.coordinator.controllerGeneration; @@ -2048,11 +2134,74 @@ export async function claimNativeRestartRecoveries(input: { if (terminalRunToReport) void reportRunFailure(input.db, terminalRunToReport); if (claimScope && "leaseOwner" in disposition) input.onClaim?.(disposition, claimScope); - dispositions.push(disposition); + dispositions.push(disposition.kind === "awaiting_evidence" + ? await boundAwaitingEvidence(input.db, candidate, disposition, now, input.restartKind) + : disposition); } return dispositions; } +/** Waits this process resolves by itself (its own executor, a locked row). */ +const SELF_RESOLVING_WAITS = ["current_controller_preparing", "recovery_rows_busy"]; +/** Hard cap on any restart-recovery wait whose owner is not renewing a lease. */ +export const NATIVE_RESTART_EVIDENCE_HARD_CAP_MS = 10 * 60_000; + +/** + * Every restart-recovery wait has an owner and a bound. Each awaiting-evidence + * disposition is checked again (`retryAt`, at most two minutes out). Once the + * previous controller's lease has lapsed for `NATIVE_NAMESPACE_UNVERIFIED_WAIT_MS`, + * or the wait has lasted `NATIVE_RESTART_EVIDENCE_HARD_CAP_MS`, and no live + * controller is renewing a lease, the run ends: it stops holding the task and + * the agent's slots, and the fresh-continuation fallback continues the task, + * isolated. A controller that is still renewing its lease is never ended early. + */ +async function boundAwaitingEvidence(db: Db, candidate: { runId: string; companyId: string; issueId: string }, + disposition: { kind: "awaiting_evidence"; runId: string; reason: string; retryAt?: Date; transitionUnchanged?: boolean }, now: Date, + restartKind: NativeRestartKind): Promise { + // A wait without its own recheck gets one; an owner's own schedule is kept. + const recheck = disposition.retryAt ?? new Date(now.getTime() + NATIVE_NAMESPACE_UNVERIFIED_WAIT_MS); + const waiting = { ...disposition, retryAt: recheck }; + if (SELF_RESOLVING_WAITS.includes(disposition.reason)) return disposition; + try { + return await db.transaction(async tx => { + const [issue] = await tx.select({ id: issues.id }).from(issues).where(and(eq(issues.id, candidate.issueId), + eq(issues.companyId, candidate.companyId))).for("update", { skipLocked: true }); + if (!issue) return waiting; + const [row] = await tx.select({ run: heartbeatRuns, coordinator: nativeRunFinalizations, + issueAssigneeAgentId: issues.assigneeAgentId, issueStatus: issues.status }) + .from(heartbeatRuns).innerJoin(nativeRunFinalizations, eq(nativeRunFinalizations.runId, heartbeatRuns.id)) + .innerJoin(issues, eq(issues.id, nativeRunFinalizations.issueId)) + .where(and(eq(heartbeatRuns.id, candidate.runId), eq(heartbeatRuns.companyId, candidate.companyId))) + .for("update", { of: [heartbeatRuns, nativeRunFinalizations], skipLocked: true }); + if (!row || !["running", "queued"].includes(row.run.status) || row.coordinator.phase === "committed" + || row.coordinator.resultId) return waiting; + const leaseExpiresAt = row.coordinator.leaseExpiresAt?.getTime() ?? 0; + // A controller that still renews its lease is alive: never ended early. + if (leaseExpiresAt > now.getTime()) return waiting; + const detail = (row.coordinator.failureDetail ?? {}) as Record; + const since = typeof detail.restartEvidenceWaitSince === "string" ? Date.parse(detail.restartEvidenceWaitSince) : NaN; + if (!Number.isFinite(since)) { + await tx.update(nativeRunFinalizations).set({ failureDetail: sql`coalesce(${nativeRunFinalizations.failureDetail}, '{}'::jsonb) + || ${JSON.stringify({ restartEvidenceWaitSince: now.toISOString() })}::jsonb` }) + .where(eq(nativeRunFinalizations.runId, row.run.id)); + return waiting; + } + const lapsedFor = now.getTime() - Math.max(since, leaseExpiresAt); + if (lapsedFor < NATIVE_NAMESPACE_UNVERIFIED_WAIT_MS && now.getTime() - since < NATIVE_RESTART_EVIDENCE_HARD_CAP_MS) return waiting; + const reason = `restart_evidence_timeout:${disposition.reason}`.slice(0, 120); + const controller = await currentNativeControllerIdentity(); + await endNamespaceUnverifiedRun(tx as unknown as Db, row, now, reason, historyEntry({ now, restartKind, controller, + generation: row.coordinator.controllerGeneration, disposition: "blocked", reason, requestId: null, + providerAttempt: row.coordinator.attempt, processPid: row.run.processPid, processStartedAt: row.run.processStartedAt, + hasCheckpoint: false, hasProviderEvidence: false, stderrTail: row.run.stderrExcerpt }), null); + return { kind: "blocked" as const, runId: row.run.id, reason }; + }); + } catch (error) { + logger.warn({ err: error, runId: candidate.runId }, "bounded restart-recovery wait check deferred"); + return waiting; + } +} + export async function nativeRestartRecoverySummary(db: Db) { const rows = await db .select({ diff --git a/server/src/services/native-runtime/native-runner-restart-recovery.integration.test.ts b/server/src/services/native-runtime/native-runner-restart-recovery.integration.test.ts index cf50f4d54b1..04152a91dac 100644 --- a/server/src/services/native-runtime/native-runner-restart-recovery.integration.test.ts +++ b/server/src/services/native-runtime/native-runner-restart-recovery.integration.test.ts @@ -97,7 +97,8 @@ vi.mock("../../sentry.js", async () => { captureRunFailure: mockCaptureRunFailure, }; }); -import { claimNativeRestartRecoveries, currentNativeControllerIdentity, NATIVE_NO_PROGRESS_RESTART_LIMIT, NATIVE_PROGRESS_CREDIT_GENERATION_LIMIT, NATIVE_RESTART_RECOVERY_FAILED, nextNativeProviderAttempt, type NativeControllerIdentity } from "./native-restart-recovery.js"; +import { ensureFreshContinuation } from "../fresh-continuation-fallback.js"; +import { claimNativeRestartRecoveries, currentNativeControllerIdentity, NATIVE_NAMESPACE_UNVERIFIED_WAIT_MS, NATIVE_NO_PROGRESS_RESTART_LIMIT, NATIVE_PROGRESS_CREDIT_GENERATION_LIMIT, NATIVE_RESTART_RECOVERY_FAILED, nextNativeProviderAttempt, type NativeControllerIdentity } from "./native-restart-recovery.js"; import { taskInterruptionPresentation } from "../task-interruption-presentation.js"; import { requestTaskRetry } from "../task-retry.js"; @@ -2345,6 +2346,95 @@ process.on("SIGTERM", () => child.kill("SIGTERM")); ]); }); + // The two-server swap: the new server sees a mid-tool run whose lapsed + // controller lived in another process space it cannot verify. After the + // bounded wait the run ends (freeing the task and the agent's slot), and the + // fresh-continuation fallback continues the task once, isolated. + it("ends a mid-tool run whose lapsed controller cannot be verified after the bounded wait, then continues the task fresh", async () => { + const fixture = await seedRun(`NAMESPACE-END-${randomUUID()}`); + const oldBoot = randomUUID(), foreignSpace = `foreign:${currentProcessSpaceHash()}`, startedAt = new Date(Date.now() - 600_000); + await fixture.db.update(heartbeatRuns).set({ processPid: 2_000_000_011, processStartedAt: startedAt, processHostHash: foreignSpace }) + .where(eq(heartbeatRuns.id, fixture.runId)); + await fixture.db.update(nativeRunFinalizations).set({ controllerBootId: oldBoot, controllerPid: 2_000_000_012, + controllerProcessStartedAt: startedAt, controllerHostHash: foreignSpace, + leaseOwner: `foreign-in-flight:${randomUUID()}`, leaseExpiresAt: new Date(0), attempt: 1, controllerGeneration: 1, + // The new server has already waited past the bound for this exact reason. + recoveryHistory: [{ at: new Date(Date.now() - NATIVE_NAMESPACE_UNVERIFIED_WAIT_MS - 1_000).toISOString(), + disposition: "awaiting_evidence", reason: "controller_process_space_unverified" }], + }).where(eq(nativeRunFinalizations.runId, fixture.runId)); + const dispositions = await claimNativeRestartRecoveries({ db: fixture.db, controller: successor, + restartKind: "hard", runIds: [fixture.runId] }); + expect(dispositions).toEqual([expect.objectContaining({ kind: "blocked", runId: fixture.runId, + reason: "controller_process_space_unverified" })]); + const [run] = await fixture.db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, fixture.runId)); + expect(run).toMatchObject({ status: "failed", errorCode: "native_restart_recovery_blocked" }); + const [task] = await fixture.db.select().from(issues).where(eq(issues.id, fixture.issueId)); + expect(task!.executionRunId).toBeNull(); + const holds = await fixture.db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, fixture.issueId)); + const hold = holds.find(row => row.status === "active"); + expect(hold).toMatchObject({ ownerType: "system", cause: "native_restart_recovery_blocked" }); + expect(hold!.nextAction).not.toMatch(/operator|board|inspect|repair/i); + expect(await ensureFreshContinuation(fixture.db, { companyId, runId: fixture.runId, trigger: "recovery_refused" })) + .toMatchObject({ kind: "continued" }); + }); + + // Graceful-drain hand-off: the outgoing server handed the run off, the new + // server classified it awaiting evidence, and the evidence never arrived. + // Every awaiting-evidence wait is bounded: once the old lease has lapsed for + // the bound, the run ends (its slot and task lock are freed) and the task + // continues once, fresh and isolated. + it("ends a handed-off run whose restart evidence never arrives within the bound, then continues the task fresh", async () => { + const fixture = await seedRun(`EVIDENCE-TIMEOUT-${randomUUID()}`); + const foreignSpace = `foreign:${currentProcessSpaceHash()}`, startedAt = new Date(Date.now() - 600_000); + await fixture.db.update(nativeRunFinalizations).set({ controllerBootId: randomUUID(), controllerPid: 2_000_000_031, + controllerProcessStartedAt: startedAt, controllerHostHash: foreignSpace, + leaseOwner: `drained:${randomUUID()}`, leaseExpiresAt: new Date(Date.now() - NATIVE_NAMESPACE_UNVERIFIED_WAIT_MS - 5_000), + attempt: 1, controllerGeneration: 1, recoveryHistory: [], + failureDetail: { restartEvidenceWaitSince: new Date(Date.now() - NATIVE_NAMESPACE_UNVERIFIED_WAIT_MS - 1_000).toISOString() }, + }).where(eq(nativeRunFinalizations.runId, fixture.runId)); + const dispositions = await claimNativeRestartRecoveries({ db: fixture.db, controller: successor, + restartKind: "hard", runIds: [fixture.runId] }); + expect(dispositions).toEqual([expect.objectContaining({ kind: "blocked", runId: fixture.runId })]); + const [run] = await fixture.db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, fixture.runId)); + expect(run).toMatchObject({ status: "failed", errorCode: "native_restart_recovery_blocked" }); + const [task] = await fixture.db.select().from(issues).where(eq(issues.id, fixture.issueId)); + expect(task!.executionRunId).toBeNull(); + expect(await ensureFreshContinuation(fixture.db, { companyId, runId: fixture.runId, trigger: "recovery_refused" })) + .toMatchObject({ kind: "continued" }); + }); + + it("schedules a recheck for every awaiting-evidence wait and does not end it before the bound", async () => { + const fixture = await seedRun(`EVIDENCE-EARLY-${randomUUID()}`); + const foreignSpace = `foreign:${currentProcessSpaceHash()}`, startedAt = new Date(Date.now() - 600_000); + await fixture.db.update(nativeRunFinalizations).set({ controllerBootId: randomUUID(), controllerPid: 2_000_000_041, + controllerProcessStartedAt: startedAt, controllerHostHash: foreignSpace, + leaseOwner: `drained:${randomUUID()}`, leaseExpiresAt: new Date(Date.now() - 1_000), attempt: 1, controllerGeneration: 1, + recoveryHistory: [], failureDetail: {}, + }).where(eq(nativeRunFinalizations.runId, fixture.runId)); + const dispositions = await claimNativeRestartRecoveries({ db: fixture.db, controller: successor, + restartKind: "hard", runIds: [fixture.runId] }); + expect(dispositions).toEqual([expect.objectContaining({ kind: "awaiting_evidence", runId: fixture.runId, retryAt: expect.any(Date) })]); + const [run] = await fixture.db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, fixture.runId)); + expect(run!.status).not.toBe("failed"); + }); + + it("leaves a run alone while its foreign controller still renews its lease during a server overlap", async () => { + const fixture = await seedRun(`NAMESPACE-OVERLAP-${randomUUID()}`); + const foreignSpace = `foreign:${currentProcessSpaceHash()}`, startedAt = new Date(Date.now() - 600_000); + await fixture.db.update(nativeRunFinalizations).set({ controllerBootId: randomUUID(), controllerPid: 2_000_000_021, + controllerProcessStartedAt: startedAt, controllerHostHash: foreignSpace, + leaseOwner: `foreign-live:${randomUUID()}`, leaseExpiresAt: new Date(Date.now() + 60_000), attempt: 1, controllerGeneration: 1, + recoveryHistory: [{ at: new Date(Date.now() - 10 * 60_000).toISOString(), + disposition: "awaiting_evidence", reason: "controller_process_space_unverified" }], + }).where(eq(nativeRunFinalizations.runId, fixture.runId)); + const dispositions = await claimNativeRestartRecoveries({ db: fixture.db, controller: successor, + restartKind: "hard", runIds: [fixture.runId] }); + // A live lease is waited for; the bounded end never applies to it. + expect(dispositions).toEqual([expect.objectContaining({ kind: "awaiting_evidence", runId: fixture.runId })]); + const [run] = await fixture.db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, fixture.runId)); + expect(run!.status).not.toBe("failed"); + }); + it.each(["stopped", "fenced"] as const)("keeps foreign local Runner and provider ownership after its controller is %s", async state => { const fixture = await seedRun(`FOREIGN-LOCAL-${state}-${randomUUID()}`); const oldBoot = randomUUID(), foreignSpace = `foreign:${currentProcessSpaceHash()}`; @@ -2388,8 +2478,9 @@ process.on("SIGTERM", () => child.kill("SIGTERM")); const [run] = await fixture.db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, fixture.runId)); const stopped = await hasNativeLocalProcessStop(fixture.db, companyId, fixture.runId); expect(probes).toEqual([]); + // The namespace wait is bounded: it is checked again when the wait ends. expect(dispositions).toEqual([{ kind: "awaiting_evidence", runId: fixture.runId, - reason: "controller_process_space_unverified" }]); + reason: "controller_process_space_unverified", retryAt: expect.any(Date) }]); expect(claimed).not.toHaveBeenCalled(); expect(stamped).not.toHaveBeenCalled(); expect(stopped).toBe(false); diff --git a/server/src/services/task-interruption-presentation.ts b/server/src/services/task-interruption-presentation.ts index 1e8c2f59f15..abf793cada9 100644 --- a/server/src/services/task-interruption-presentation.ts +++ b/server/src/services/task-interruption-presentation.ts @@ -89,6 +89,9 @@ type ProjectionState = { * remote environment, or a scheduled close in this process. Without one, * nothing settles the gate by itself, so Retry is the way forward. */ cleanupSettling?: boolean; + /** The fresh-continuation fallback is continuing this run's task (recorded, + * not yet started) or will check it again at `nextCheckAt`. */ + freshContinuation?: { state: "continuing" } | { state: "scheduled"; nextCheckAt: number }; }; // A task read reports the change that made a task fail, not every later read of @@ -263,6 +266,10 @@ function projectTaskInterruptionState(issue: ProjectionIssue, input: ProjectionS && !(retryWait?.sourceRunId === run.id && retryWait.preparationStatus) && system?.state !== "exhausted") return { ...base, intentId: interruptWait.id, state: "working" }; if (["running", "queued"].includes(run.status)) return { ...base, state: "working" }; + // Paperclip is continuing the task by itself: no failed attempt and no Retry. + if (input.freshContinuation?.state === "continuing") return { ...base, state: "working", canRetry: false }; + if (input.freshContinuation?.state === "scheduled" && input.freshContinuation.nextCheckAt > now) + return { ...base, state: "retry_scheduled", nextRetryAt: new Date(input.freshContinuation.nextCheckAt).toISOString(), canRetry: false }; const deniedProject = deniedProjectId(issue, run); let projectAccess: TaskInterruptionPresentation["projectAccess"]; if (deniedProject !== undefined) { @@ -560,6 +567,25 @@ export async function taskInterruptionPresentations(db: Db, companyId: string, i inArray(sql`${issueRecoveryActions.evidence}->>'runId'`, runIds), sql`${issueRecoveryActions.evidence} ? 'systemRecovery'`, )).orderBy(issueRecoveryActions.sourceIssueId, desc(issueRecoveryActions.createdAt)) : []; + // The fresh-continuation fallback's records for these runs. + const freshRows = runIds.length ? await db.select({ issueId: issueRecoveryActions.sourceIssueId, + runId: sql`${issueRecoveryActions.evidence}->>'runId'`, + delivery: sql`${issueRecoveryActions.evidence}->>'continuationDelivery'`, + recorded: sql`${issueRecoveryActions.evidence} ? 'freshContinuation'`, + checkKind: sql`${issueRecoveryActions.evidence}#>>'{freshContinuationCheck,kind}'`, + nextCheckAt: sql`${issueRecoveryActions.evidence}#>>'{freshContinuationCheck,nextCheckAt}'` }) + .from(issueRecoveryActions).where(and(eq(issueRecoveryActions.companyId, companyId), inArray(issueRecoveryActions.sourceIssueId, ids), + inArray(sql`${issueRecoveryActions.evidence}->>'runId'`, runIds), + sql`(${issueRecoveryActions.evidence} ? 'freshContinuationSettlement' or ${issueRecoveryActions.evidence} ? 'freshContinuationCheck')`)) : []; + const freshContinuationFor = (issueId: string, runId: string | undefined): ProjectionState["freshContinuation"] => { + const rows = freshRows.filter(row => row.issueId === issueId && row.runId === runId); + // Only the primary record (it carries `freshContinuation`) says whether a + // continuation is still on its way; holds coalesced into it never do. + if (rows.some(row => row.recorded && ["pending", "not_requested"].includes(row.delivery ?? ""))) return { state: "continuing" }; + const scheduled = rows.filter(row => ["exact_recovery_pending", "backoff"].includes(row.checkKind ?? "") && row.nextCheckAt) + .map(row => Number(row.nextCheckAt)).sort((a, b) => a - b)[0]; + return scheduled ? { state: "scheduled", nextCheckAt: scheduled } : undefined; + }; const ownerStops = runIds.length ? await db.select({ issueId: issueRecoveryActions.sourceIssueId, runId: sql`${issueRecoveryActions.evidence}->>'runId'` }).from(issueRecoveryActions).where(and( eq(issueRecoveryActions.companyId, companyId), inArray(issueRecoveryActions.sourceIssueId, ids), @@ -659,6 +685,7 @@ export async function taskInterruptionPresentations(db: Db, companyId: string, i const facts = { run: runMap.get(issue.id), action: actionMap.get(issue.id), wait: waitMap.get(issue.id), retryWait: retryWaitMap.get(issue.id) }; const presentation = projectTaskInterruption(issue, { ...facts, + freshContinuation: freshContinuationFor(issue.id, facts.run?.id), interruptWait: interruptWaitFor(issue.id), projectAccessAllowed: denied?.length === 0, projectAccessProjectId: denied?.includes(issue.projectId ?? "") ? issue.projectId : null,