diff --git a/server/src/__tests__/released-writer-escalation.test.ts b/server/src/__tests__/released-writer-escalation.test.ts index dc5d65436f9..62d3c534c24 100644 --- a/server/src/__tests__/released-writer-escalation.test.ts +++ b/server/src/__tests__/released-writer-escalation.test.ts @@ -201,6 +201,35 @@ describePostgres("a task stranded behind its own workspace's ended writer", () = expect(wakesFor(f.task.id)).toHaveLength(1); }, 60_000); + it("a task reopened behind the refused hold gets no retry or sweep continuation and returns to this pass", async () => { + const f = await seedStrandedTask({ laterDecision: null }); + await db.delete(issueRecoveryActions).where(eq(issueRecoveryActions.id, f.actionId)); + const [latest] = await db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.issueId, f.task.id), + eq(heartbeatRuns.errorCode, "setup_failed"))).orderBy(sql`${heartbeatRuns.finishedAt} desc`).limit(1); + await db.update(heartbeatRuns).set({ contextSnapshot: { issueId: f.task.id, source: "issue.assigned_work_invariant", + wakeReason: "issue_continuation_needed", previousRunId: randomUUID() } }).where(eq(heartbeatRuns.id, latest!.id)); + await db.update(issues).set({ status: "in_progress", blockedTransitionAt: null, updatedAt: new Date(Date.now() - 3_600_000) }) + .where(eq(issues.id, f.task.id)); + const successors = async () => (await db.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(and( + eq(heartbeatRuns.issueId, f.task.id), sql`${heartbeatRuns.status} in ('queued', 'scheduled_retry', 'running')`))).length; + + expect(await recoveryService(db, { enqueueWakeup: enqueueWakeup as never }).assignedWork + .checkIssue({ companyId: f.companyId, issueId: f.task.id })).toMatchObject({ outcome: "left_to_hold_owner" }); + expect(wakesFor(f.task.id)).toEqual([]); + + await heartbeat.reconcileStrandedAssignedIssues({ companyId: f.companyId, issueId: f.task.id, skipRelatedRecovery: true }); + expect(await successors()).toBe(0); + expect(await issue(f.task.id)).toMatchObject({ status: "blocked" }); + const [escalation] = await db.select().from(issueRecoveryActions).where(and(eq(issueRecoveryActions.sourceIssueId, f.task.id), + eq(issueRecoveryActions.status, "active"))); + expect(escalation).toMatchObject({ kind: "stranded_assigned_issue", ownerType: "board" }); + + await f.releaseWriter(); + expect(await scheduledRecoveryPass(f.companyId)).toBe(true); + expect(await issue(f.task.id)).toMatchObject({ status: "todo" }); + expect(wakesFor(f.task.id)).toHaveLength(1); + }, 60_000); + it("delivers a wake that a crash left pending, and keeps backing off a refused one", async () => { const f = await seedStrandedTask({ laterDecision: null }); await f.releaseWriter(); diff --git a/server/src/services/heartbeat/retries.test.ts b/server/src/services/heartbeat/retries.test.ts index 73ea5bcf0a4..10ea547bbad 100644 --- a/server/src/services/heartbeat/retries.test.ts +++ b/server/src/services/heartbeat/retries.test.ts @@ -1,6 +1,6 @@ import { randomUUID } from "node:crypto"; import type { Db } from "@paperclipai/db"; -import { activityLog, agents, agentWakeupRequests, companies, createDb, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, heartbeatRunEvents, heartbeatRuns, issues, projects, projectWorkspaces } from "@paperclipai/db"; +import { activityLog, agents, agentWakeupRequests, companies, createDb, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, executionWorkspaces, heartbeatRunEvents, heartbeatRuns, issues, projects, projectWorkspaces } from "@paperclipai/db"; import { and, eq } from "drizzle-orm"; import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest"; import { writePaperclipSkillSyncPreference } from "@paperclipai/adapter-utils/server-utils"; @@ -12,6 +12,7 @@ import * as legacy from "../heartbeat.js"; import { createHeartbeatRunState } from "./run-state.js"; import { pendingCaseHandoffForRun } from "./case-handoff-lifecycle.js"; import * as extracted from "./retries.js"; +import { REMOTE_WORKSPACE_WRITER_PENDING_MESSAGE } from "../remote-workspace-writer-hold.js"; import type { HeartbeatRetryDependencies } from "./retries.js"; type Run = typeof heartbeatRuns.$inferSelect; @@ -343,6 +344,34 @@ describePostgres("heartbeat retry module database wiring", () => { } }); + it("does not retry a setup failure while its workspace's writer hold refuses a start, and retries once it is free", async () => { + const { run, agent, issue, companyId } = await fixture(); + const [writer] = await db.insert(heartbeatRuns).values({ companyId, agentId: agent.id, scopeKind: "issue", issueId: issue.id, + status: "failed", errorCode: "native_finalization_superseded", finishedAt: new Date(now.getTime() - 9 * 3_600_000), + contextSnapshot: { issueId: issue.id } }).returning(); + const remoteWorkspace = { schema: "paperclip.remote-workspace.v1", epoch: 3, snapshotId: randomUUID(), source: { kind: "empty" }, + writerRunId: writer!.id, dirty: true, location: null }; + const [workspace] = await db.insert(executionWorkspaces).values({ companyId, sourceIssueId: issue.id, name: "Task workspace", + mode: "isolated_workspace", strategyType: "project_primary", status: "active", providerType: "cloud_sandbox", + metadata: { remoteWorkspace } }).returning(); + try { + await db.update(issues).set({ executionWorkspaceId: workspace!.id }).where(eq(issues.id, issue.id)); + const [failed] = await db.update(heartbeatRuns).set({ errorCode: "setup_failed", error: REMOTE_WORKSPACE_WRITER_PENDING_MESSAGE }) + .where(eq(heartbeatRuns.id, run.id)).returning(); + const { retries } = boundRetries(); + expect(await retries.scheduleBoundedRetryForRun(failed!, agent, { now })) + .toMatchObject({ outcome: "not_scheduled", errorCode: "remote_workspace_writer_pending", issueId: issue.id }); + expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.retryOfRunId, run.id))).toEqual([]); + + await db.update(executionWorkspaces).set({ metadata: { remoteWorkspace: { ...remoteWorkspace, epoch: 4, writerRunId: null, dirty: false } } }) + .where(eq(executionWorkspaces.id, workspace!.id)); + expect(await retries.scheduleBoundedRetryForRun(failed!, agent, { now })).toMatchObject({ outcome: "scheduled" }); + } finally { + await db.update(issues).set({ executionWorkspaceId: null }).where(eq(issues.id, issue.id)); + await db.delete(executionWorkspaces).where(eq(executionWorkspaces.companyId, companyId)); + } + }); + // A run that could not retire its predecessor re-queues in the uncharged lane // with the answered interaction's own wake, so the retry still carries it. it("keeps an answered interaction in an uncharged interrupted-preparation retry that keeps its wake", async () => { diff --git a/server/src/services/heartbeat/retries.ts b/server/src/services/heartbeat/retries.ts index b3e18aab640..774a68e869e 100644 --- a/server/src/services/heartbeat/retries.ts +++ b/server/src/services/heartbeat/retries.ts @@ -1,5 +1,6 @@ import { hasPendingRunCleanup } from "../execution-blocker.js"; -import { runOwnerFenceHeldSql } from "../remote-workspace-writer-hold.js"; +import { failedRunWorkspaceHoldRefusesStart, REMOTE_WORKSPACE_WRITER_PENDING_CODE, REMOTE_WORKSPACE_WRITER_PENDING_MESSAGE, + runOwnerFenceHeldSql } from "../remote-workspace-writer-hold.js"; import { AGENT_DIRECTORY_BUSY_ERROR_CODE, AGENT_DIRECTORY_BUSY_MAX_DEFERRALS, AGENT_DIRECTORY_BUSY_RETRY_REASON, AGENT_DIRECTORY_BUSY_RETRY_WAKE_REASON, agentDirectoryBusyRetryDelayMs, type AgentDirectoryPreparationDeferral } from "./agent-directory-busy.js"; import { isInterruptedNativePreparation } from "../cancelled-native-startup.js"; import { isPreDispatchExecutionWaitVerified } from "../pre-dispatch-execution-wait.js"; @@ -541,6 +542,10 @@ export function createHeartbeatRetries(db: Db, dependencies: HeartbeatRetryDepen } if (await hasCaseHandoffForRun(run)) return { outcome: "not_scheduled" as const, reason: "The durable case handoff owns successor work.", issueId: readNonEmptyString(run.contextSnapshot?.issueId) }; + if (await failedRunWorkspaceHoldRefusesStart(db, run, (opts?.now ?? new Date()).getTime())) { + return { outcome: "not_scheduled" as const, reason: REMOTE_WORKSPACE_WRITER_PENDING_MESSAGE, + errorCode: REMOTE_WORKSPACE_WRITER_PENDING_CODE, issueId: readNonEmptyString(run.contextSnapshot?.issueId) }; + } if (["openai_dot", "muse"].includes(String(parseObject(agent.adapterConfig).provider)) || ["openai_dot", "muse"].includes(String(parseObject(parseObject(parseObject(run.runnerProfileJson).nativeExecutionInput).provider).kind))) { return { outcome: "not_scheduled" as const, reason: "Dot external execution must be reconciled before a new assignment; Paperclip cannot confirm its external stop.", issueId: readNonEmptyString(run.contextSnapshot?.issueId) }; diff --git a/server/src/services/recovery/assigned-work-invariant.ts b/server/src/services/recovery/assigned-work-invariant.ts index 6b391b9836a..a0329d2f569 100644 --- a/server/src/services/recovery/assigned-work-invariant.ts +++ b/server/src/services/recovery/assigned-work-invariant.ts @@ -179,6 +179,7 @@ export type AssignedWorkFacts = { /** A saved-work recovery the recovery queue still owes this task: the * task's saved files must be recovered before any run can start. */ savedWorkRecovery?: SavedWorkRecoveryFact | null; + workspaceWriterRefused?: boolean; agent: { status: string; invokable: boolean; updatedAt?: Date } | null; companyPaused: boolean; pauseHold: boolean; diff --git a/server/src/services/recovery/assigned-work-sweep.ts b/server/src/services/recovery/assigned-work-sweep.ts index ee4977f9371..e2d591a6886 100644 --- a/server/src/services/recovery/assigned-work-sweep.ts +++ b/server/src/services/recovery/assigned-work-sweep.ts @@ -102,7 +102,7 @@ function chatFailedBeforeProviderWork(latest: RunRow | null, issue: Pick & { issueId: string }; export type AssignedWorkDeps = { @@ -171,6 +171,11 @@ function createPassLog() { }; } +function leftToWorkspaceWriterHold(status: string, facts: AssignedWorkFacts, verdict: AssignedWorkVerdict): boolean { + return status !== "blocked" && facts.workspaceWriterRefused === true && verdict.kind === "violation" + && (verdict.reason === "retry_offered" || verdict.reason === "no_pending_path"); +} + export function assignedWorkSweep(db: Db, deps: AssignedWorkDeps) { const now = () => deps.now?.() ?? new Date(); const proveOwner = deps.proveOwner ?? ((stamp: LocalOwnerStamp) => proveOwnerGone(stamp, { ...currentProcessProbe(), readOnly: true })); @@ -211,7 +216,7 @@ export function assignedWorkSweep(db: Db, deps: AssignedWorkDeps) { const runIssue = sql`${heartbeatRuns.contextSnapshot}->>'issueId'`; const runColumns = { issueId: runIssue, id: heartbeatRuns.id, status: heartbeatRuns.status, agentId: heartbeatRuns.agentId, - runtimeMode: heartbeatRuns.runtimeMode, errorCode: heartbeatRuns.errorCode, finishedAt: heartbeatRuns.finishedAt, + runtimeMode: heartbeatRuns.runtimeMode, errorCode: heartbeatRuns.errorCode, error: heartbeatRuns.error, finishedAt: heartbeatRuns.finishedAt, scheduledRetryAt: heartbeatRuns.scheduledRetryAt, controllerBootId: heartbeatRuns.controllerBootId, controllerLeaseExpiresAt: heartbeatRuns.controllerLeaseExpiresAt, controllerProcess: heartbeatRuns.controllerProcess, resultJson: sql | null>`jsonb_build_object('cancelledByActorType', ${heartbeatRuns.resultJson}->'cancelledByActorType')`, @@ -231,7 +236,7 @@ export function assignedWorkSweep(db: Db, deps: AssignedWorkDeps) { from unnest(${idParam}) as requested(id) cross join lateral ( select r.id, r.status, r.agent_id as "agentId", r.runtime_mode as "runtimeMode", r.error_code as "errorCode", - r.finished_at as "finishedAt", r.scheduled_retry_at as "scheduledRetryAt", + r.error, r.finished_at as "finishedAt", r.scheduled_retry_at as "scheduledRetryAt", r.controller_boot_id as "controllerBootId", r.controller_lease_expires_at as "controllerLeaseExpiresAt", r.controller_process as "controllerProcess", jsonb_build_object('cancelledByActorType', r.result_json->'cancelledByActorType', @@ -341,10 +346,13 @@ export function assignedWorkSweep(db: Db, deps: AssignedWorkDeps) { executionRecovery: sql`${heartbeatRuns.resultJson}->'executionRecovery'` }) .from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, companyId), inArray(heartbeatRuns.id, strandedRunIds))) : []) .map(({ id, ...run }) => [id, run])); - const writerHeldIssueIds = [...actionMap.entries()].filter(([, action]) => { - const run = strandedRuns.get(String(action.evidence?.latestRunId ?? "")); - return run?.errorCode === "setup_failed" && run.error === REMOTE_WORKSPACE_WRITER_PENDING_MESSAGE; - }).map(([issueId]) => issueId); + const writerPending = (run: { errorCode: string | null; error: string | null } | null | undefined) => + run?.errorCode === "setup_failed" && run.error === REMOTE_WORKSPACE_WRITER_PENDING_MESSAGE; + const writerHeldIssueIds = [...new Set([ + ...[...actionMap.entries()].filter(([, action]) => writerPending(strandedRuns.get(String(action.evidence?.latestRunId ?? "")))) + .map(([issueId]) => issueId), + ...rowsOf(latestRuns).filter(run => writerPending(run)).map(run => run.issueId), + ])]; const writerRefusedIssueIds = new Set(); if (writerHeldIssueIds.length) { const bound = await database.select({ issueId: issues.id, metadata: executionWorkspaces.metadata }).from(issues) @@ -496,6 +504,7 @@ export function assignedWorkSweep(db: Db, deps: AssignedWorkDeps) { budgetStop: companyBudget || agent?.pauseReason === "budget" || agent?.pauseReason === "budget_exceeded", blockedBy: issue.status !== "blocked" ? null : attributeBlock(blockedEntry, issue.assigneeAgentId), savedWorkRecovery: savedWorkByIssue.get(issue.id) ?? null, + workspaceWriterRefused: writerRefusedIssueIds.has(issue.id), }); } return result; @@ -675,6 +684,7 @@ export function assignedWorkSweep(db: Db, deps: AssignedWorkDeps) { } // A stalled native run is ended by native recovery, not here: the sweep // builds no second ender. It stays a counted violation in the report. + if (leftToWorkspaceWriterHold(issue.status, facts, verdict)) return { verdict, outcome: "left_to_hold_owner", retryAt: null }; if (verdict.reason === "native_run_stalled") return { verdict, outcome: "left_to_native_recovery", retryAt: null }; if (verdict.reason === "run_owner_gone") { // Hand the run to heartbeat's lost-process settle path; its own failure @@ -885,7 +895,8 @@ export function assignedWorkSweep(db: Db, deps: AssignedWorkDeps) { const verdict = evaluateAssignedWork(fresh, at); let stalledFence: Claimed["stalledFence"] = null; if (verdict.kind !== "violation" || verdict.stale || verdict.reason === "run_owner_gone" || verdict.reason === "native_run_stalled" - || (current.status === "blocked" && fresh.activeRecoveryAction && !fresh.activeRecoveryAction.continuedBySweep)) return { kind: "changed" as const }; + || (current.status === "blocked" && fresh.activeRecoveryAction && !fresh.activeRecoveryAction.continuedBySweep) + || leftToWorkspaceWriterHold(current.status, fresh, verdict)) return { kind: "changed" as const }; if (verdict.reason === "queued_run_stalled") { const stall = fresh.activeRuns.find(run => run.id === verdict.runId)?.queuedStall; const fence = fences.find(row => row.id === verdict.runId); diff --git a/server/src/services/recovery/service.ts b/server/src/services/recovery/service.ts index 886bd22baf5..21fcd5ff2be 100644 --- a/server/src/services/recovery/service.ts +++ b/server/src/services/recovery/service.ts @@ -1,5 +1,6 @@ import { wakeWaitersOfStalledIssues, type BlockerStallWakeup } from "./blocker-stall-wakeups.js"; import { wakeReadyPoolDependentsForBlocker } from "../headless-task-queue.js"; +import { failedRunWorkspaceHoldRefusesStart } from "../remote-workspace-writer-hold.js"; import { ANTIGRAVITY_SWARM_UNAVAILABLE } from "../antigravity-swarm-refusal.js"; import { DEPENDENCY_WAKE_REPEATED_FAILURE_STREAK, readDependencyWakeCircuit } from "./dependency-wake-circuit-breaker.js"; import { INTERACTION_DELIVERY_DENIED, isInteractionDeliveryDeniedRun } from "../agent-interaction-delivery.js"; @@ -6116,7 +6117,8 @@ export function recoveryService( // escalates it as before. preparationRetry = latestRun!.agentId === agentId && await failedRunOwnsPreparationRetry(issue.companyId, latestRun!.id); - const sweepOwnsFailure = !preparationRetry && assignedWorkSweepOwnsFailedRun(issue, latestRun, agentId); + const sweepOwnsFailure = !preparationRetry && assignedWorkSweepOwnsFailedRun(issue, latestRun, agentId) + && !(await failedRunWorkspaceHoldRefusesStart(db, { ...latestRun!, companyId: issue.companyId })); if (classification.kind === "non_retryable" && sweepOwnsFailure) { result.skipped += 1; continue; diff --git a/server/src/services/remote-workspace-writer-hold.ts b/server/src/services/remote-workspace-writer-hold.ts index 66aeb0ff5dc..b51f254bd50 100644 --- a/server/src/services/remote-workspace-writer-hold.ts +++ b/server/src/services/remote-workspace-writer-hold.ts @@ -1,7 +1,7 @@ import { and, eq, inArray, or, sql } from "drizzle-orm"; import { environmentLeases, executionWorkspaces, heartbeatRuns, issueRecoveryActions, issues, nativeRunFinalizations, workspaceOperations, type Db } from "@paperclipai/db"; -import { remoteWorkspaceRunReferenceSchema, type RemoteWorkspaceAuthority } from "@paperclipai/shared"; +import { readRemoteWorkspaceAuthority, remoteWorkspaceRunReferenceSchema, type RemoteWorkspaceAuthority } from "@paperclipai/shared"; import { adapterExecutionControls } from "./adapter-execution-control.js"; import { hasRecoveredCleanupStopReceipt, hasRemoteTerminationReceipt, resolveRemoteTerminationLease } from "./remote-execution-termination.js"; import { canonicalExecutionUuid } from "./execution-identity.js"; @@ -86,6 +86,7 @@ export function runOwnerFenceHeldSql() { /** The setup error a run gets when reservation refuses a remote workspace hold. */ export const REMOTE_WORKSPACE_WRITER_PENDING_MESSAGE = "The workspace still has an unfinished writer or save operation."; +export const REMOTE_WORKSPACE_WRITER_PENDING_CODE = "remote_workspace_writer_pending"; type RemoteWorkspaceWriterHold = Awaited>; @@ -167,6 +168,23 @@ export async function readRemoteWorkspaceWriterHold(tx: Db, input: { return { kind: "unattributed" }; } +export async function failedRunWorkspaceHoldRefusesStart(tx: Db, run: { + id: string; companyId: string; errorCode: string | null; error: string | null; + issueId?: string | null; contextSnapshot?: unknown; +}, now = Date.now()): Promise { + if (run.errorCode !== "setup_failed" || run.error !== REMOTE_WORKSPACE_WRITER_PENDING_MESSAGE) return false; + const snapshot = object(run.contextSnapshot); + const issueId = uuid(run.issueId) ?? uuid(snapshot.issueId) ?? uuid(snapshot.taskId); + if (!issueId) return false; + const [row] = await tx.select({ metadata: executionWorkspaces.metadata }).from(issues) + .innerJoin(executionWorkspaces, and(eq(executionWorkspaces.companyId, issues.companyId), + eq(executionWorkspaces.id, issues.executionWorkspaceId))) + .where(and(eq(issues.companyId, run.companyId), eq(issues.id, issueId))); + const authority = row ? readRemoteWorkspaceAuthority(row.metadata as Record | null) : null; + if (!authority) return false; + return remoteWorkspaceHoldRefusesStart(await readRemoteWorkspaceWriterHold(tx, { companyId: run.companyId, authority, runId: run.id }), now); +} + /** * Abandons a dirty remote workspace epoch whose ended writer was already * superseded by a recorded successor run, once that successor has also ended