diff --git a/server/src/__tests__/task-interruption-automatic-path.test.ts b/server/src/__tests__/task-interruption-automatic-path.test.ts new file mode 100644 index 00000000000..17443fd2171 --- /dev/null +++ b/server/src/__tests__/task-interruption-automatic-path.test.ts @@ -0,0 +1,108 @@ +import { randomUUID } from "node:crypto"; +import { eq } from "drizzle-orm"; +import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; +import { agents, agentWakeupRequests, applyPendingMigrations, companies, createDb, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, + heartbeatRuns, issueRecoveryActions, issues, nativeRunFinalizations } from "@paperclipai/db"; +import { taskInterruptionPresentation } from "../services/task-interruption-presentation.js"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; +import { resolveExternalTestDatabaseUrl } from "./helpers/external-test-database.js"; + +const externalDatabaseUrl = resolveExternalTestDatabaseUrl("PAPERCLIP_TASK_INTERRUPTION_TEST_DATABASE_URL"); +const support = externalDatabaseUrl ? { supported: true } : await getEmbeddedPostgresTestSupport(); +vi.mock("../sentry.js", () => ({ captureTaskInterruptionFailure: vi.fn() })); + +describe.skipIf(!support.supported)("Retry is offered only when no automatic path exists", () => { + let database: Awaited>; + let db: ReturnType; + beforeAll(async () => { + if (externalDatabaseUrl) await applyPendingMigrations(externalDatabaseUrl); + database = externalDatabaseUrl ? { connectionString: externalDatabaseUrl, cleanup: async () => {} } + : await startEmbeddedPostgresTestDatabase("interruption-automatic-"); + db = createDb(database.connectionString); + }, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS); + afterAll(async () => { await db?.$client.end(); await database?.cleanup(); }); + + async function seedTask(status = "in_progress") { + const companyId = randomUUID(), agentId = randomUUID(); + await db.insert(companies).values({ id: companyId, name: "Swap company", issuePrefix: `S${companyId.slice(0, 7)}` }); + await db.insert(agents).values({ id: agentId, companyId, name: "Swap agent", adapterType: "paperclip_runner" }); + const [issue] = await db.insert(issues).values({ companyId, title: "Work across a release swap", + status, assigneeAgentId: agentId }).returning(); + return { companyId, agentId, issue: issue! }; + } + + async function seedSwapEndedRun(finishedAt: Date) { + const task = await seedTask(); + const runId = randomUUID(); + await db.insert(heartbeatRuns).values({ id: runId, companyId: task.companyId, agentId: task.agentId, + nativeIssueId: task.issue.id, scopeKind: "issue", status: "failed", runtimeMode: "native", + nativePhase: "terminal_failure", errorCode: "native_restart_recovery_blocked", + error: "controller_process_space_unverified", startedAt: new Date(finishedAt.getTime() - 60_000), finishedAt }); + await db.insert(nativeRunFinalizations).values({ companyId: task.companyId, issueId: task.issue.id, runId, + phase: "terminal_failure", attempt: 1, failureCode: "native_restart_recovery_blocked", recoveryState: "blocked" }); + const [hold] = await db.insert(issueRecoveryActions).values({ companyId: task.companyId, sourceIssueId: task.issue.id, + kind: "active_run_watchdog", status: "active", ownerType: "system", returnOwnerAgentId: task.agentId, + cause: "native_restart_recovery_blocked", fingerprint: `native-restart:${runId}`, + evidence: { runId, reason: "controller_process_space_unverified", executorStopEvidence: "unverified", providerAttempt: 1 }, + nextAction: "The server running this task restarted. Paperclip continues the task in a fresh run from its saved work.", + maxAttempts: 3, createdAt: finishedAt, updatedAt: finishedAt }).returning(); + return { ...task, runId, hold: hold! }; + } + + it("shows a run ended by a release swap as working while its system hold awaits the automatic continuation", async () => { + const { issue, runId } = await seedSwapEndedRun(new Date(Date.now() - 5_000)); + expect(await taskInterruptionPresentation(db, issue)).toMatchObject({ responsibility: "system", state: "working", + canRetry: false, observedRunId: runId }); + }); + + it("still offers Retry when the system hold was not taken up by the continuation worker in time", async () => { + const { issue } = await seedSwapEndedRun(new Date(Date.now() - 10 * 60_000)); + expect(await taskInterruptionPresentation(db, issue)).toMatchObject({ state: "failed", canRetry: true }); + }); + + it("still offers Retry once the continuation worker decided it cannot continue the task", async () => { + const { issue, hold } = await seedSwapEndedRun(new Date(Date.now() - 5_000)); + await db.update(issueRecoveryActions).set({ evidence: { ...hold.evidence, + freshContinuationCheck: { kind: "not_applicable", reason: "task_changed", checks: 1, checkedAt: Date.now(), nextCheckAt: null } } }) + .where(eq(issueRecoveryActions.id, hold.id)); + expect(await taskInterruptionPresentation(db, issue)).toMatchObject({ state: "failed", canRetry: true }); + }); + + it("still offers Retry when a person owns the hold", async () => { + const { issue, hold, companyId } = await seedSwapEndedRun(new Date(Date.now() - 5_000)); + await db.update(issueRecoveryActions).set({ evidence: { ...hold.evidence, ownerGoneAttestation: { companyId } } }) + .where(eq(issueRecoveryActions.id, hold.id)); + expect(await taskInterruptionPresentation(db, issue)).toMatchObject({ state: "failed", canRetry: true }); + }); + + it("still offers Retry when recovery gave up and handed the hold to the board", async () => { + const { issue, hold } = await seedSwapEndedRun(new Date(Date.now() - 5_000)); + await db.update(issueRecoveryActions).set({ ownerType: "board" }).where(eq(issueRecoveryActions.id, hold.id)); + expect(await taskInterruptionPresentation(db, issue)).toMatchObject({ state: "failed", canRetry: true }); + }); + + it("shows a healthy task as working while the message queued during its succeeded run is delivered", async () => { + const { companyId, agentId, issue } = await seedTask(); + const runId = randomUUID(), finishedAt = new Date(Date.now() - 3_000); + await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, nativeIssueId: issue.id, scopeKind: "issue", + status: "succeeded", runtimeMode: "native", startedAt: new Date(Date.now() - 5 * 60_000), finishedAt }); + await db.insert(agentWakeupRequests).values({ companyId, agentId, source: "on_demand", reason: "issue_commented", + status: "deferred_issue_execution", requestedByActorType: "user", requestedAt: new Date(Date.now() - 2 * 60_000), + payload: { issueId: issue.id } }); + expect(await taskInterruptionPresentation(db, issue)).toMatchObject({ state: "working", canRetry: false }); + expect(await taskInterruptionPresentation(db, { ...issue, status: "in_review" })).toMatchObject({ state: "working", canRetry: false }); + expect(await taskInterruptionPresentation(db, { ...issue, status: "blocked" })).toMatchObject({ state: "failed", canRetry: true }); + await db.update(heartbeatRuns).set({ finishedAt: new Date(Date.now() - 10 * 60_000) }).where(eq(heartbeatRuns.id, runId)); + expect(await taskInterruptionPresentation(db, issue)).toMatchObject({ canRetry: true }); + }); + + it("does not offer Retry on a parent whose run succeeded and that waits for its subtasks", async () => { + const { companyId, agentId, issue } = await seedTask(); + await db.insert(issues).values({ companyId, title: "Subtask", status: "in_progress", assigneeAgentId: agentId, parentId: issue.id }); + await db.insert(heartbeatRuns).values({ companyId, agentId, nativeIssueId: issue.id, scopeKind: "issue", + status: "succeeded", runtimeMode: "native", finishedAt: new Date(Date.now() - 3_000) }); + await db.insert(agentWakeupRequests).values({ companyId, agentId, source: "automation", reason: "issue_children_completed", + status: "queued", requestedByActorType: "system", payload: { issueId: issue.id } }); + expect(await taskInterruptionPresentation(db, issue)).toMatchObject({ canRetry: false }); + }); +}); diff --git a/server/src/services/task-interruption-presentation.test.ts b/server/src/services/task-interruption-presentation.test.ts index a48bd6bc763..2d7378f5658 100644 --- a/server/src/services/task-interruption-presentation.test.ts +++ b/server/src/services/task-interruption-presentation.test.ts @@ -544,3 +544,25 @@ describe("native cleanup quarantine presentation", () => { paused: false, approval: false })).toMatchObject({ state: "failed", canRetry: true }); }); }); + +describe("automatic scheduled retry", () => { + const now = Date.parse("2026-11-12T23:00:00Z"); + const scheduled = { ...run, status: "scheduled_retry", runtimeMode: "legacy", errorCode: null, resultJson: null, + scheduledRetryReason: "transient_failure", scheduledRetryAt: new Date(now + 60_000) }; + + it("shows a pending transient-failure retry as scheduled without a competing Retry", () => { + expect(projectTaskInterruption(issue, { run: scheduled, agent, paused: false, approval: false }, now)) + .toMatchObject({ state: "retry_scheduled", canRetry: false, nextRetryAt: new Date(now + 60_000).toISOString() }); + }); + + it("offers Retry once the scheduled retry is past due with nothing else pending", () => { + expect(projectTaskInterruption(issue, { run: { ...scheduled, scheduledRetryAt: new Date(now - 10 * 60_000) }, agent, + paused: false, approval: false }, now)).toMatchObject({ state: "failed", canRetry: true }); + }); + + it("offers Retry once the scheduled retries are exhausted", () => { + expect(projectTaskInterruption(issue, { run: { ...scheduled, status: "failed", errorCode: "transient_failure_retry_exhausted", + scheduledRetryAt: new Date(now - 60_000) }, agent, paused: false, approval: false }, now)) + .toMatchObject({ state: "failed", canRetry: true }); + }); +}); diff --git a/server/src/services/task-interruption-presentation.ts b/server/src/services/task-interruption-presentation.ts index abf793cada9..19e933cd2eb 100644 --- a/server/src/services/task-interruption-presentation.ts +++ b/server/src/services/task-interruption-presentation.ts @@ -7,7 +7,7 @@ import { nativeSessionCleanupBlock } from "../vendor/paperclip-runner/index.js"; import { agents, agentWakeupRequests, approvals, chatActions, companies, environmentLeases, heartbeatRuns, issueApprovals, issueRecoveryActions, issues, issueTreeHoldMembers, issueTreeHolds, nativeRunFinalizations, projects, type Db } from "@paperclipai/db"; import { unionAll } from "drizzle-orm/pg-core"; -import { HEARTBEAT_RUN_STATUSES, readProviderFailure, type TaskInterruptionPresentation } from "@paperclipai/shared"; +import { EXECUTION_RECONCILIATION_CAUSES, HEARTBEAT_RUN_STATUSES, readProviderFailure, type TaskInterruptionPresentation } from "@paperclipai/shared"; import { captureTaskInterruptionFailure } from "../sentry.js"; import { isAiAuthenticationBlocked } from "./ai-auth-failure.js"; import { readSystemRecovery } from "./system-recovery-state.js"; @@ -39,6 +39,8 @@ const NATIVE_RESUME_DISPATCH_GRACE_MS = 2 * 60_000; // A queued-message Interrupt waits for the stopped run's cleanup before its // successor starts. Past this, a hand-off that never started offers Retry. const QUEUED_INTERRUPT_HANDOFF_GRACE_MS = 5 * 60_000; +const QUEUED_INPUT_DISPATCH_GRACE_MS = 2 * 60_000; +const AUTOMATIC_DISPOSITION_GRACE_MS = 2 * 60_000; type ProjectionIssue = Pick; type ProjectionRun = Pick now) return { ...base, state: "retry_scheduled", nextRetryAt: new Date(input.freshContinuation.nextCheckAt).toISOString(), canRetry: false }; + if (input.automaticDispositionAt !== undefined && ["failed", "timed_out", "interrupted", "cancelled"].includes(run.status) + && now - Math.max(input.automaticDispositionAt, run.finishedAt?.getTime() ?? 0) < AUTOMATIC_DISPOSITION_GRACE_MS) + return { ...base, state: "working", canRetry: false }; const deniedProject = deniedProjectId(issue, run); let projectAccess: TaskInterruptionPresentation["projectAccess"]; if (deniedProject !== undefined) { @@ -316,7 +322,7 @@ function projectTaskInterruptionState(issue: ProjectionIssue, input: ProjectionS : "Paperclip couldn’t confirm shutdown. Your work is saved; continuation is paused." } }; } if (retryAt && retryAt > now) return { ...base, state: "retry_scheduled", - nextRetryAt: new Date(retryAt).toISOString(), canRetry: !preparationPending && !nativeResumeAt, + nextRetryAt: new Date(retryAt).toISOString(), canRetry: !preparationPending && !nativeResumeAt && run.status !== "scheduled_retry", ...(system?.nextAttemptAt && recoveryStep ? { recoveryStep } : {}) }; if (nativeResumeAt && !system && now - nativeResumeAt < NATIVE_RESUME_DISPATCH_GRACE_MS) return { ...base, state: "working" }; @@ -337,7 +343,9 @@ function projectTaskInterruptionState(issue: ProjectionIssue, input: ProjectionS && (reason !== "cleanup_quarantined" || !input.cleanupSettling), retryWait: { reason, message: retryWaitMessages[reason] ?? "Retry is waiting for execution checks. Your message is saved." } }; } - if (wait && wait.requestedAt.getTime() > now - 10_000 && system?.state !== "exhausted") + const queuedDuringRun = Boolean(wait && run.status === "succeeded" && ["todo", "in_progress", "in_review"].includes(issue.status) && run.finishedAt && wait.requestedAt.getTime() <= run.finishedAt.getTime() + && now - run.finishedAt.getTime() < QUEUED_INPUT_DISPATCH_GRACE_MS); + if (wait && (wait.requestedAt.getTime() > now - 10_000 || queuedDuringRun) && system?.state !== "exhausted") return { ...base, state: "working" }; if (run.errorCode === NATIVE_SESSION_CLEANUP_QUARANTINED) { // The provider turn completed and its work is saved; only shutdown of the @@ -586,6 +594,23 @@ export async function taskInterruptionPresentations(db: Db, companyId: string, i .map(row => Number(row.nextCheckAt)).sort((a, b) => a - b)[0]; return scheduled ? { state: "scheduled", nextCheckAt: scheduled } : undefined; }; + const dispositionRows = runIds.length ? await db.select({ issueId: issueRecoveryActions.sourceIssueId, + runId: sql`${issueRecoveryActions.evidence}->>'runId'`, updatedAt: issueRecoveryActions.updatedAt }) + .from(issueRecoveryActions).where(and(eq(issueRecoveryActions.companyId, companyId), + inArray(issueRecoveryActions.sourceIssueId, ids), inArray(sql`${issueRecoveryActions.evidence}->>'runId'`, runIds), + inArray(issueRecoveryActions.status, ["active", "escalated"]), eq(issueRecoveryActions.ownerType, "system"), + inArray(issueRecoveryActions.cause, [...EXECUTION_RECONCILIATION_CAUSES]), isNull(issueRecoveryActions.ownerUserId), + sql`not (${issueRecoveryActions.evidence} ?| array['systemRecovery', 'executionReconciliation', 'freshContinuation', + 'freshContinuationCheck', 'ownerGoneAttestation', 'explicitUserContinuation'])`)) : []; + const automaticDispositionAt = new Map(); + if (dispositionRows.length) { + const { isPersonOwnedFailureCode } = await import("./fresh-continuation-fallback.js"); + for (const row of dispositionRows) { + const run = runs.find(candidate => candidate.issueId === row.issueId && candidate.id === row.runId); + if (!run || isPersonOwnedFailureCode(run.errorCode)) continue; + automaticDispositionAt.set(row.issueId, Math.max(automaticDispositionAt.get(row.issueId) ?? 0, row.updatedAt.getTime())); + } + } 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), @@ -686,6 +711,7 @@ export async function taskInterruptionPresentations(db: Db, companyId: string, i retryWait: retryWaitMap.get(issue.id) }; const presentation = projectTaskInterruption(issue, { ...facts, freshContinuation: freshContinuationFor(issue.id, facts.run?.id), + automaticDispositionAt: automaticDispositionAt.get(issue.id), interruptWait: interruptWaitFor(issue.id), projectAccessAllowed: denied?.length === 0, projectAccessProjectId: denied?.includes(issue.projectId ?? "") ? issue.projectId : null,