diff --git a/server/src/services/native-runtime/native-run-finalizer-telemetry.test.ts b/server/src/services/native-runtime/native-run-finalizer-telemetry.test.ts index 213fae33bf7..6f627b908af 100644 --- a/server/src/services/native-runtime/native-run-finalizer-telemetry.test.ts +++ b/server/src/services/native-runtime/native-run-finalizer-telemetry.test.ts @@ -930,8 +930,9 @@ describeEmbeddedPostgres("native run finalizer / status decision committer — a expect(run?.error).toMatch(/sandbox disk is full/); expect(run?.error).not.toMatch(/after 3 attempts/); // The export hold owns the next step; no provider turn is requested. - expect(await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, fixture.issueId))) - .toEqual([expect.objectContaining({ status: "active", ownerType: "board", cause: "native_workspace_sync_out_retry_exhausted" })]); + const actions = await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, fixture.issueId)); + expect(actions).toEqual([expect.objectContaining({ status: "active", ownerType: "board", cause: "native_workspace_sync_out_retry_exhausted" })]); + expect(actions[0].nextAction).not.toMatch(/Finalization retry budget exhausted/); expect(await db.select({ id: agentWakeupRequests.id }).from(agentWakeupRequests) .where(eq(agentWakeupRequests.agentId, agentId))).toEqual(wakeupsBefore); }); @@ -949,6 +950,61 @@ describeEmbeddedPostgres("native run finalizer / status decision committer — a expect(failure).toMatchObject({ phase: "retryable_failure", failureCode: "native_workspace_sync_out_failed" }); }); + it("stops copy-back on the first unfinished Git operation failure and keeps the accepted result", async () => { + const gitOpCause = "remote_workspace_archive_git_operation_in_progress: finish or abort the Git operation before saving the workspace"; + const fixture = await seedNativeRun(); + await driveToCompleteResult(fixture); + const [accepted] = await db.select().from(nativeRunResults).where(eq(nativeRunResults.runId, fixture.runId)); + expect(accepted).toBeDefined(); + const wakeupsBefore = await db.select({ id: agentWakeupRequests.id }).from(agentWakeupRequests) + .where(eq(agentWakeupRequests.agentId, agentId)); + const failure = await recordNativeFinalizationFailure({ + db, runId: fixture.runId, error: new Error("native_workspace_sync_out_failed"), + projectRunStatus: true, failureScope: "workspace", failureCause: gitOpCause, + }); + expect(failure).toMatchObject({ + phase: "terminal_failure", + failureCode: "native_workspace_sync_out_retry_exhausted", + nextAttemptAt: null, + }); + const [coordinator] = await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, fixture.runId)); + expect(coordinator.failureDetail).toMatchObject({ + recoveryOwner: { kind: "board" }, + workspaceFinalizeAttempt: 1, + failureCause: gitOpCause, + }); + expect(coordinator.resultId).toBe(accepted.id); + expect(await db.select().from(nativeRunResults).where(eq(nativeRunResults.runId, fixture.runId))).toEqual([accepted]); + const run = await readRunError(fixture.runId); + expect(run).toMatchObject({ status: "failed", errorCode: "native_workspace_sync_out_retry_exhausted" }); + expect(run?.error).toMatch(/Git operation is still in progress/); + expect(run?.error).not.toMatch(/after 3 attempts/); + const actions = await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, fixture.issueId)); + expect(actions).toEqual([expect.objectContaining({ + status: "active", + ownerType: "board", + cause: "native_workspace_sync_out_retry_exhausted", + wakePolicy: null, + })]); + expect(actions[0].nextAction).toMatch(/Git operation/); + expect(actions[0].nextAction).not.toMatch(/Finalization retry budget exhausted/); + expect(await db.select({ id: agentWakeupRequests.id }).from(agentWakeupRequests) + .where(eq(agentWakeupRequests.agentId, agentId))).toEqual(wakeupsBefore); + }); + + it("keeps transient workspace archive change failures on their bounded retry", async () => { + const fixture = await seedNativeRun(); + await db.insert(nativeRunFinalizations).values({ + runId: fixture.runId, companyId, issueId: fixture.issueId, phase: "observed", attempt: 1, + }); + const failure = await recordNativeFinalizationFailure({ + db, runId: fixture.runId, error: new Error("native_workspace_sync_out_failed"), + projectRunStatus: true, failureScope: "workspace", + failureCause: "remote_workspace_archive_changed", + }); + expect(failure).toMatchObject({ phase: "retryable_failure", failureCode: "native_workspace_sync_out_failed" }); + }); + it("does not attach a finalization error to a provider-succeeded run when provider retries are exhausted", async () => { const fixture = await seedNativeRun(); await db.update(heartbeatRuns).set({ resultJson: { prpRunTerminalState: "succeeded", finalizationFailureCount: 2 } }) diff --git a/server/src/services/native-runtime/native-run-finalizer.ts b/server/src/services/native-runtime/native-run-finalizer.ts index dc7f0cca8cb..8ec0e7acbf2 100644 --- a/server/src/services/native-runtime/native-run-finalizer.ts +++ b/server/src/services/native-runtime/native-run-finalizer.ts @@ -1,6 +1,6 @@ import { notifyNativeEnvironmentSettlement } from "../native-environment-settlement-notifications.js"; import { isContextCompactionRun } from "../context-compaction.js"; -import { REMOTE_WORKSPACE_SANDBOX_DISK_FULL_CODE } from "../remote-workspace-transport.js"; +import { isWorkspaceGitOperationInProgress, workspaceSaveRestCause } from "./native-workspace-failure.js"; import { notifyExternalAgentSettlement } from "../../modules/external-agents/index.js"; import { notifyNativeRecoveryNotices } from "../native-recovery-notice-notifications.js"; import { resolveCommittedNativeRecoveryNotices } from "./native-recovery-notices.js"; @@ -324,11 +324,19 @@ export function readWorkspaceFailureCause(value: unknown): string | null { function terminalFinalizationFailureMessage(failureCode: string, failureScope: "provider" | "workspace" | undefined, failureCause?: string | null) { - if (failureCode === "native_workspace_sync_out_retry_exhausted" && isSandboxStorageExhausted(failureCause)) { + const saveRestCause = failureCode === "native_workspace_sync_out_retry_exhausted" + ? workspaceSaveRestCause(failureCause) + : null; + if (saveRestCause === "sandbox_disk_full") { return "Saving the workspace stopped because the sandbox disk is full. The agent's result is kept, and Paperclip " + "saves the files again from the retained sandbox without repeating the agent's work; follow the run's recovery " + `action if that cannot free enough space. Last cause: ${failureCause}`; } + if (saveRestCause === "git_operation_in_progress") { + return "Saving the workspace stopped because a Git operation is still in progress in the workspace. " + + "The agent's result is kept; finish or abort the Git operation before saving the workspace. " + + `Last cause: ${failureCause}`; + } if (failureCode === "native_workspace_sync_out_retry_exhausted") { // This code also covers local-directory and plugin workspaces, so the // message stays general and defers to the recovery action's next step. @@ -434,16 +442,6 @@ export async function endSupersededNativeFinalizationRuns(db: Db, runIds?: reado return ended; } -/** - * A full sandbox disk stops every copy-back the same way: the archive is built - * in that sandbox, and nothing frees space between finalizer attempts. It is - * recognised on the first failure and handed to saved-work recovery, which can - * reclaim the retained sandbox's inactive provider cache before saving again. - */ -function isSandboxStorageExhausted(failureCause: string | null | undefined) { - return typeof failureCause === "string" && failureCause.startsWith(`${REMOTE_WORKSPACE_SANDBOX_DISK_FULL_CODE}:`); -} - const NATIVE_FINALIZATION_RETRY_LIMIT = 3; /** * Contention while applying a saved, accepted, provider-succeeded result is @@ -595,9 +593,11 @@ async function recordRetryableFailure(input: { let finalizationFailureCount = input.failureScope === "workspace" ? null : readFinalizationFailureCount(input.run.resultJson) + 1; + const nonRetryableWorkspaceCause = + input.failureScope === "workspace" && workspaceSaveRestCause(failureCause) !== null; const budgetExhausted = input.permanent === true || - (input.failureScope === "workspace" && isSandboxStorageExhausted(failureCause)) || + nonRetryableWorkspaceCause || (workspaceFinalizeAttempt !== null ? workspaceFinalizeAttempt >= 3 : finalizationFailureCount! >= NATIVE_FINALIZATION_RETRY_LIMIT); @@ -781,7 +781,7 @@ async function recordRetryableFailure(input: { originalFailureCode: input.failureCode, }, nextAction: exhausted - ? input.permanent + ? input.permanent || nonRetryableWorkspaceCause ? input.nextAction : `Finalization retry budget exhausted. ${input.nextAction}` : input.nextAction, @@ -854,9 +854,11 @@ export async function recordNativeFinalizationFailure(input: { && (message === "native_plugin_workspace_branch_mismatch" || message === "native_plugin_workspace_owner_mismatch") ? "Repair the plugin workspace branch or owner, then resume finalization without another provider turn." : input.failureScope === "workspace" - ? input.permanent - ? "Restore the exact sandbox containing the unexported workspace changes, or resolve the task manually from durable evidence." - : "Retry workspace export and merge from the retained sandbox; do not submit another provider turn." + ? input.permanent + ? "Restore the exact sandbox containing the unexported workspace changes, or resolve the task manually from durable evidence." + : isWorkspaceGitOperationInProgress(readWorkspaceFailureCause(input.failureCause)) + ? "Finish or abort the in-progress Git operation in the workspace, then retry saving the workspace; do not submit another provider turn." + : "Retry workspace export and merge from the retained sandbox; do not submit another provider turn." : "Repair the persisted native result or contract discriminator, then resume finalization from the coordinator.", projectRunStatus: input.projectRunStatus, failureScope: input.failureScope, diff --git a/server/src/services/native-runtime/native-workspace-failure.test.ts b/server/src/services/native-runtime/native-workspace-failure.test.ts new file mode 100644 index 00000000000..64ba995f8f4 --- /dev/null +++ b/server/src/services/native-runtime/native-workspace-failure.test.ts @@ -0,0 +1,77 @@ +import { randomUUID } from "node:crypto"; +import { describe, expect, it } from "vitest"; +import { + classifyNativeWorkspaceFailure, + isWorkspaceGitOperationInProgress, + workspaceSaveRestCause, +} from "./native-workspace-failure.js"; +import { remoteWorkspaceCaptureFailureMessage } from "../remote-workspace-snapshot-archive.js"; +import { + REMOTE_WORKSPACE_SANDBOX_DISK_FULL, + remoteWorkspaceFailureCause, +} from "../remote-workspace-transport.js"; +import { + createSystemRecovery, + exhaustedSystemRecoveryAction, + failSystemRecovery, + reserveSystemRecoveryAttempt, + savedFilesUnrecoverable, + SystemRecoveryFailure, +} from "../system-recovery-state.js"; + +describe("native workspace failure classification and save-rest policy", () => { + it("recognizes the exact producer output for an in-progress Git operation through redaction", () => { + const producerMessage = remoteWorkspaceCaptureFailureMessage({ + message: "remote_workspace_archive_git_operation_in_progress: finish or abort the Git operation before saving the workspace", + }); + expect(producerMessage).not.toBeNull(); + const redactedCause = remoteWorkspaceFailureCause(new Error(producerMessage!)); + expect(redactedCause).toBe(producerMessage); + expect(isWorkspaceGitOperationInProgress(new Error(producerMessage!))).toBe(true); + expect(isWorkspaceGitOperationInProgress(redactedCause)).toBe(true); + expect(workspaceSaveRestCause(new Error(producerMessage!))).toBe("git_operation_in_progress"); + expect(workspaceSaveRestCause(redactedCause)).toBe("git_operation_in_progress"); + expect(classifyNativeWorkspaceFailure(new Error(producerMessage!))).toEqual({ + code: "workspace_sync_out_failed", + failureCode: "native_workspace_sync_out_failed", + permanent: false, + }); + }); + + it("recognizes sandbox disk full and keeps transient or unrelated errors retryable", () => { + const diskFullCause = remoteWorkspaceFailureCause(new Error(REMOTE_WORKSPACE_SANDBOX_DISK_FULL)); + expect(workspaceSaveRestCause(diskFullCause)).toBe("sandbox_disk_full"); + expect(workspaceSaveRestCause(new Error(REMOTE_WORKSPACE_SANDBOX_DISK_FULL))).toBe("sandbox_disk_full"); + + for (const transient of [ + "remote_workspace_archive_changed", + "remote_workspace_capture_failed: stage=archive code=ECONNRESET", + "Daytona syncOut directory download failed: timeout", + ]) { + expect(isWorkspaceGitOperationInProgress(transient)).toBe(false); + expect(workspaceSaveRestCause(transient)).toBeNull(); + expect(workspaceSaveRestCause(new Error(transient))).toBeNull(); + } + + expect(classifyNativeWorkspaceFailure(new Error("daytona_sandbox_not_found"))).toEqual({ + code: "workspace_sync_out_unrecoverable", + failureCode: "native_workspace_sync_out_unrecoverable", + permanent: true, + }); + }); + + it("renders plain-language recovery copy for an in-progress Git operation rest", () => { + const gitOp = failSystemRecovery( + reserveSystemRecoveryAttempt(createSystemRecovery(randomUUID()), 0)!, + new SystemRecoveryFailure("export_interrupted", "user_action_required"), + { now: 0, cause: { label: "git_operation_in_progress", code: null, status: null } }, + ); + expect(gitOp).toMatchObject({ state: "exhausted", attempts: 1, retriesUsed: 0, nextAttemptAt: null }); + expect(savedFilesUnrecoverable(gitOp)).toBe(false); + const text = exhaustedSystemRecoveryAction(gitOp); + expect(text).toMatch(/Git operation/i); + expect(text).toContain("Retry"); + expect(text).not.toContain("git_operation_in_progress"); + expect(text).not.toMatch(/administrator|\bowner\b|board member|inspect the run|environment/i); + }); +}); diff --git a/server/src/services/native-runtime/native-workspace-failure.ts b/server/src/services/native-runtime/native-workspace-failure.ts index 44144152289..9eb6376a5df 100644 --- a/server/src/services/native-runtime/native-workspace-failure.ts +++ b/server/src/services/native-runtime/native-workspace-failure.ts @@ -1,17 +1,55 @@ import { classifyWorkspaceRestoreFailure } from "@paperclipai/adapter-utils/workspace-restore-merge"; +import { REMOTE_WORKSPACE_SANDBOX_DISK_FULL_CODE } from "../remote-workspace-transport.js"; export type NativeWorkspaceFailureCode = | "workspace_sync_out_failed" | "workspace_sync_out_unrecoverable" | "workspace_sync_out_unsafe_archive"; +export type WorkspaceSaveRestCause = + | "sandbox_disk_full" + | "git_operation_in_progress"; + +export const REMOTE_WORKSPACE_GIT_OPERATION_IN_PROGRESS_CODE = + "remote_workspace_archive_git_operation_in_progress"; + +function readFailureText(value: unknown): string { + return typeof value === "string" + ? value.trim() + : value instanceof Error + ? value.message.trim() + : ""; +} + +/** + * A workspace with an unfinished Git operation (such as a conflicted merge or + * rebase) fails every copy-back attempt the same way: nothing finishes or + * aborts the Git operation between automatic attempts. + */ +export function isWorkspaceGitOperationInProgress(value: unknown): boolean { + const text = readFailureText(value); + return text === REMOTE_WORKSPACE_GIT_OPERATION_IN_PROGRESS_CODE + || text.startsWith(`${REMOTE_WORKSPACE_GIT_OPERATION_IN_PROGRESS_CODE}:`); +} + +/** + * Deterministic workspace-save refusals that repeat identically across + * automatic attempts because the sandbox state does not change between tries. + */ +export function workspaceSaveRestCause(value: unknown): WorkspaceSaveRestCause | null { + const text = readFailureText(value); + if (text.startsWith(`${REMOTE_WORKSPACE_SANDBOX_DISK_FULL_CODE}:`)) return "sandbox_disk_full"; + if (isWorkspaceGitOperationInProgress(text)) return "git_operation_in_progress"; + return null; +} + /** Keep initial and recovered copy-back failures on the same retry policy. */ export function classifyNativeWorkspaceFailure(error: unknown): { code: NativeWorkspaceFailureCode; failureCode: `native_${NativeWorkspaceFailureCode}`; permanent: boolean; } { - const message = error instanceof Error ? error.message.trim() : ""; + const message = readFailureText(error); const code: NativeWorkspaceFailureCode = message === "workspace_sync_out_unrecoverable" || message.includes("daytona_sandbox_not_found") || classifyWorkspaceRestoreFailure(error) === "restore_invalid_metadata" diff --git a/server/src/services/system-recovery-state.ts b/server/src/services/system-recovery-state.ts index 3fdbe6edeae..3e19490d845 100644 --- a/server/src/services/system-recovery-state.ts +++ b/server/src/services/system-recovery-state.ts @@ -198,6 +198,10 @@ export function exhaustedSystemRecoveryAction(state: SystemRecoveryState, eviden return "Saving the agent's files stopped because the sandbox disk is full. Paperclip deletes only inactive tool " + "caches it can prove safe, and that did not free enough space. Automatic recovery does not repeat a save that fails the same way. " + "Retry saves the files again. The agent's result is kept, and the agent will not repeat its work."; + if (state.failure?.cause?.label === "git_operation_in_progress") + return "Saving the agent's files stopped because a Git operation (such as a merge or rebase) is still in progress in the workspace. " + + "Automatic recovery does not repeat a save that fails the same way. " + + "Finish or abort the Git operation, then use Retry to save the files again. The agent's result is kept, and the agent will not repeat its work."; const lostFiles = unrecoverableSavedFilesFailure(state); if (lostFiles) return `Paperclip cannot recover the unsaved files from the previous run: ${unrecoverableSavedFilesReason(lostFiles)}. ` diff --git a/server/src/services/workspace-recovery-warm-handoff.test.ts b/server/src/services/workspace-recovery-warm-handoff.test.ts index b2c13fcfa8d..0c4246b6221 100644 --- a/server/src/services/workspace-recovery-warm-handoff.test.ts +++ b/server/src/services/workspace-recovery-warm-handoff.test.ts @@ -32,7 +32,10 @@ import { getExecutionBlocker } from "./execution-blocker.js"; import { legacyShutdownWorkspaceResourceProtected } from "./legacy-shutdown-workspace-settlement.js"; import { issueRoutes } from "../routes/issues.js"; import { errorHandler } from "../middleware/index.js"; -import { useWorkspaceRecoveryFixture, action, connectionString, db, failedWarmSource, replaceFixtureState, root, run, seed, warmHandoffSource } from "./__tests__/workspace-recovery-fixture.js"; +import { useWorkspaceRecoveryFixture, acceptedRemoteExport, action, connectionString, db, failedWarmSource, receiptOnlyRecoveryApp, recoverRunHolds, replaceFixtureState, root, run, seed, warmHandoffSource } from "./__tests__/workspace-recovery-fixture.js"; +import { finalizeNativeRun } from "./native-runtime/native-run-finalizer.js"; +import { readRemoteWorkspaceAuthority } from "./remote-workspaces.js"; +import { taskInterruptionPresentation } from "./task-interruption-presentation.js"; const targets = vi.hoisted(() => new Map()); vi.mock("./environment-execution-target.js", async importOriginal => { const actual = await importOriginal(); @@ -741,4 +744,85 @@ describe("automatic retained workspace recovery", () => { expect(rows.every(row => row.body === base.body)).toBe(true); }); + it("ends recovery at the first unfinished Git operation failure and applies the accepted result on Retry once resolved", async () => { + const gitOpError = "remote_workspace_archive_git_operation_in_progress: finish or abort the Git operation before saving the workspace"; + const f = await acceptedRemoteExport(); + const target = targets.get(f.lease.id)!, syncOut = target.runner!.syncOut!; + const gitState = { inProgress: true, saves: 0 }; + target.runner!.syncOut = async operations => { + gitState.saves++; + if (gitState.inProgress) throw new Error(gitOpError); + return syncOut(operations); + }; + const workspaceBefore = (await db.select().from(executionWorkspaces).where(eq(executionWorkspaces.id, f.workspaceId)))[0]; + await recoverRetainedWorkspace(f.input); + await recoverRetainedWorkspace(f.input); + const failed = readSystemRecovery((await action(f.actionId)).evidence); + expect(failed).toMatchObject({ + state: "exhausted", + nextAttemptAt: null, + attempts: 1, + failure: { + code: "export_interrupted", + retryClass: "user_action_required", + cause: { label: "git_operation_in_progress", code: null, status: null }, + }, + }); + const savesAtFailure = gitState.saves; + expect(savesAtFailure).toBeGreaterThan(0); + + // No further automatic retries while resting for user action. + await recoverRetainedWorkspace(f.input); + expect(gitState.saves).toBe(savesAtFailure); + + const handedOff = await action(f.actionId); + expect(handedOff).toMatchObject({ status: "active", ownerType: "board" }); + expect(handedOff.nextAction).toMatch(/Git operation/); + expect(handedOff.nextAction).toMatch(/Retry/); + + // Saved snapshot and unsaved sandbox files remain intact. + const workspaceAfter = (await db.select().from(executionWorkspaces).where(eq(executionWorkspaces.id, f.workspaceId)))[0]; + expect(readRemoteWorkspaceAuthority(workspaceAfter.metadata)?.snapshotId) + .toBe(readRemoteWorkspaceAuthority(workspaceBefore.metadata)?.snapshotId ?? null); + expect(await readFile(path.join(f.remote, "saved.txt"), "utf8")).toBe("finished work\n"); + + const issue = (await db.select().from(issues).where(eq(issues.id, f.issueId)))[0]; + expect(await taskInterruptionPresentation(db, issue)).toMatchObject({ canRetry: true, observedRunId: f.runId }); + expect(await getExecutionBlocker(db, f.companyId, f.issueId)).toMatchObject({ + runId: f.runId, + workspaceRecovery: { canRetry: true }, + }); + + const retry = async () => (await request(receiptOnlyRecoveryApp()).post(`/api/issues/${f.issueId}/retry`) + .send({ observedRunId: f.runId, idempotencyKey: randomUUID() }).expect(202)).body as { requestId: string; accepted: boolean; observedRunId: string }; + const runIds = async () => (await db.select({ id: heartbeatRuns.id }).from(heartbeatRuns) + .where(eq(heartbeatRuns.companyId, f.companyId))).map(row => row.id).sort(); + const runsBefore = await runIds(); + + // Retry while the Git operation is still open rests again immediately without starting a new run. + const stillOpen = await retry(); + await recoverRunHolds(f.input); + await heartbeatService(db).resumeTaskRetry(f.companyId, stillOpen.requestId); + expect(readSystemRecovery((await action(f.actionId)).evidence)).toMatchObject({ + state: "exhausted", + attempts: 1, + failure: { retryClass: "user_action_required", cause: { label: "git_operation_in_progress", code: null, status: null } }, + }); + expect(await runIds()).toEqual(runsBefore); + + // Once the Git operation is resolved, Retry saves the workspace and applies the accepted result without a new turn. + gitState.inProgress = false; + const resolved = await retry(); + await recoverRunHolds(f.input); + expect(readWorkspaceRecovery((await action(f.actionId)).evidence)?.status).toBe("recovered"); + await heartbeatService(db).resumeTaskRetry(f.companyId, resolved.requestId); + expect(await runIds()).toEqual(runsBefore); + const [finalizer] = await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, f.runId)); + expect(finalizer).toMatchObject({ phase: "workspace_finalizing", resultId: f.resultId }); + await finalizeNativeRun({ db, runId: f.runId, workspaceFinalizeStatus: "succeeded", projectRunStatus: true }); + expect((await db.select().from(issues).where(eq(issues.id, f.issueId)))[0]) + .toMatchObject({ status: "done", executionRunId: null, checkoutRunId: null }); + expect((await run(f.runId)).status).toBe("succeeded"); + }, 60_000); + }); diff --git a/server/src/services/workspace-recovery.ts b/server/src/services/workspace-recovery.ts index e4d9ddc8a42..3e7f285d6f6 100644 --- a/server/src/services/workspace-recovery.ts +++ b/server/src/services/workspace-recovery.ts @@ -10,7 +10,7 @@ import { beginIdleTrackedWork } from "./task-admission.js"; import { writeEnvironmentCleanup } from "./environment-cleanup-notifications.js"; import { resumePreservedResultFinalization } from "./preserved-result-finalization.js"; import { reclaimInactiveNativeProviderCache } from "./native-runtime/retained-provider-cache.js"; -import { REMOTE_WORKSPACE_SANDBOX_DISK_FULL, sandboxProviderFailureLabel } from "./remote-workspace-transport.js"; +import { sandboxProviderFailureLabel } from "./remote-workspace-transport.js"; import { and, asc, eq, gt, inArray, ne, notInArray, or, sql } from "drizzle-orm"; import { agentWakeupRequests, environmentLeases, executionWorkspaces, heartbeatRuns, issues, issueRecoveryActions, nativeRunFinalizations, workspaceOperations, type Db } from "@paperclipai/db"; import { remoteWorkspaceRunReferenceSchema, type Environment, type EnvironmentLease } from "@paperclipai/shared"; @@ -27,7 +27,7 @@ import { TRANSIENT_WORKSPACE_PREPARATION_CODES } from "./failed-preparation-retr import { hasVerifiedWorkspaceRepair, readWorkspaceRecovery, type WorkspaceRecovery } from "./workspace-recovery-receipt.js"; import { withNativeWorkspaceFinalizationOwnership } from "./native-runtime/native-workspace-finalization-ownership.js"; import { readNativeWorkspaceSyncReference, readNativeWorkspaceSyncLocalCwd, resumeNativeWorkspaceSync } from "./native-runtime/native-workspace-sync.js"; -import { classifyNativeWorkspaceFailure } from "./native-runtime/native-workspace-failure.js"; +import { classifyNativeWorkspaceFailure, workspaceSaveRestCause } from "./native-runtime/native-workspace-failure.js"; import { handOffExhaustedSystemRecovery, adoptSystemRecovery, loadSystemRecovery, updateSystemRecovery } from "./system-recovery.js"; import { SYSTEM_RECOVERY_MAX_RETRIES, createSystemRecovery, failSystemRecovery, readSystemRecovery, reserveSystemRecoveryAttempt, SystemRecoveryFailure, type SystemRecoveryState } from "./system-recovery-state.js"; @@ -48,7 +48,7 @@ const exportCauses = ["native_workspace_sync_out_unrecoverable", "native_workspa const terminal = ["failed", "interrupted", "timed_out", "cancelled", "succeeded"]; const sandboxDiskFull = /No space left on device|Disk quota exceeded/i; export const SANDBOX_DISK_FULL_RECOVERY_CAUSE = { label: "sandbox_disk_full", code: "ENOSPC", status: null } as const; -const isSandboxDiskFullSave = (error: unknown) => error instanceof Error && error.message === REMOTE_WORKSPACE_SANDBOX_DISK_FULL; +export const GIT_OPERATION_IN_PROGRESS_RECOVERY_CAUSE = { label: "git_operation_in_progress", code: null, status: null } as const; type Source = { companyId: string; issueId: string; runId: string; actionId: string }; type StopEvidenceSource = Omit & { actionId?: string }; @@ -380,7 +380,7 @@ export async function recoverRetainedWorkspace(input: Source & { db: Db; environ let saved: Awaited>; try { saved = await save(); } catch (error) { - if (!isSandboxDiskFullSave(error)) throw error; + if (workspaceSaveRestCause(error) !== "sandbox_disk_full") throw error; let reclaimed = false; try { const reclaim = await reclaimInactiveNativeProviderCache({ db, companyId: input.companyId, @@ -489,9 +489,11 @@ export async function recoverRetainedWorkspace(input: Source & { db: Db; environ return; } const classification = classifyNativeWorkspaceFailure(error); - const diskFull = !(error instanceof SystemRecoveryFailure) && !cacheReclaimUnconfirmed && isSandboxDiskFullSave(error); + const saveRestCause = error instanceof SystemRecoveryFailure ? null : workspaceSaveRestCause(error); + const diskFull = saveRestCause === "sandbox_disk_full" && !cacheReclaimUnconfirmed; + const gitOperationInProgress = saveRestCause === "git_operation_in_progress"; const failure = error instanceof SystemRecoveryFailure ? error - : diskFull ? new SystemRecoveryFailure("export_interrupted", "user_action_required") + : diskFull || gitOperationInProgress ? new SystemRecoveryFailure("export_interrupted", "user_action_required") : classifyWorkspaceRestoreFailure(error) === "restore_invalid_metadata" ? new SystemRecoveryFailure("snapshot_verification_failed", "service_required") : classification.code === "workspace_sync_out_unsafe_archive" @@ -505,7 +507,13 @@ export async function recoverRetainedWorkspace(input: Source & { db: Db; environ // A classified failure already names its subsystem. const generic = !(error instanceof SystemRecoveryFailure) && failure.retryClass === "retry_transient" && (failure.code === "provider_unavailable" || failure.code === "export_interrupted"); - const cause = diskFull ? { ...SANDBOX_DISK_FULL_RECOVERY_CAUSE } : generic ? sandboxProviderFailureLabel(error) : undefined; + const cause = diskFull + ? { ...SANDBOX_DISK_FULL_RECOVERY_CAUSE } + : gitOperationInProgress + ? { ...GIT_OPERATION_IN_PROGRESS_RECOVERY_CAUSE } + : generic + ? sandboxProviderFailureLabel(error) + : undefined; const failed = failSystemRecovery(current!, failure, { ...(typeof retryAfterAt === "number" && Number.isFinite(retryAfterAt) ? { retryAfterAt } : {}), ...(cause ? { cause } : {}), diff --git a/ui/src/components/WorkspaceExportRecovery.control.test.tsx b/ui/src/components/WorkspaceExportRecovery.control.test.tsx index 799f9958366..8f87ade392e 100644 --- a/ui/src/components/WorkspaceExportRecovery.control.test.tsx +++ b/ui/src/components/WorkspaceExportRecovery.control.test.tsx @@ -392,6 +392,26 @@ describe("governed retained-file recovery", () => { expect(api.recover).not.toHaveBeenCalled(); }); + it("hands an in-progress Git operation save rest to the task's Retry instead of its own recovery button", async () => { + const gitOp = { ...action, ownerType: "board", evidence: { ...action.evidence, systemRecovery: { + state: "exhausted", preservationOperationIds: [], failure: { code: "export_interrupted", + retryClass: "user_action_required", cause: { label: "git_operation_in_progress", code: null, status: null } } } }, + } as unknown as IssueRecoveryAction; + api.inspect.mockResolvedValue(inspection(gitOp)); + const owns = vi.fn(); + await act(async () => root.render( + + )); + await settle(); + expect(button("Recover saved files")).toBeUndefined(); + expect(button("Try file recovery again")).toBeUndefined(); + expect(owns).toHaveBeenLastCalledWith(false); + expect(owns).not.toHaveBeenCalledWith(true); + expect(container.textContent).toContain("Git operation"); + expect(container.textContent).toContain("use Retry to save them"); + expect(api.recover).not.toHaveBeenCalled(); + }); + it("only reports recovered files after the durable preservation receipt is present", async () => { const recovered = { ...action, evidence: { ...action.evidence, workspaceRecovery: { ...(action.evidence.workspaceRecovery as object), status: "recovered", diff --git a/ui/src/components/WorkspaceExportRecovery.tsx b/ui/src/components/WorkspaceExportRecovery.tsx index 89ad306f0ac..e2f2b84303a 100644 --- a/ui/src/components/WorkspaceExportRecovery.tsx +++ b/ui/src/components/WorkspaceExportRecovery.tsx @@ -125,12 +125,13 @@ function isRetainedExport(action: IssueRecoveryAction, issueId: string, companyI && typeof action.evidence.runId === "string" && action.evidence.runId.length > 0; } -/** Saved-work recovery ended because the sandbox disk was still full (#20758). */ -function isSandboxDiskFullRest(action: IssueRecoveryAction) { +/** Saved-work recovery ended on a deterministic workspace state requiring user action before Retry. */ +function userActionWorkspaceSaveRestCause(action: IssueRecoveryAction): "sandbox_disk_full" | "git_operation_in_progress" | null { const system = asObject(action.evidence.systemRecovery); const failure = asObject(system.failure); - return system.state === "exhausted" && failure.retryClass === "user_action_required" - && asObject(failure.cause).label === "sandbox_disk_full"; + if (system.state !== "exhausted" || failure.retryClass !== "user_action_required") return null; + const label = asObject(failure.cause).label; + return label === "sandbox_disk_full" || label === "git_operation_in_progress" ? label : null; } function isControllerStopRequired(action: IssueRecoveryAction, issueId: string, companyId: string) { @@ -351,26 +352,30 @@ function RetainedFilesRecovery({ action, issueId, companyId, className, onRecove const waiting = !failedReceipt && !saved && (restoring || acknowledged || serverAcknowledged); const unconfirmed = Boolean(pending && !acknowledged && !serverAcknowledged); const sourceLoading = sourceView.kind === "loading" || sourceView.kind === "reconnecting"; - // A save that rested on a full sandbox disk is resumed by the task's Retry, - // which saves the files again and then applies the saved result. Its note - // names Retry, so this panel offers no separate control for it. - const diskFullRest = isSandboxDiskFullRest(current ?? action); + // A save that rested on a deterministic workspace state (such as a full + // sandbox disk or an in-progress Git operation) is resumed by the task's + // Retry, which saves the files again and then applies the saved result. Its + // note names Retry, so this panel offers no separate control for it. + const userActionSaveRest = userActionWorkspaceSaveRestCause(current ?? action); // A verified source makes this panel the governed recovery path. Otherwise the // task's own Retry (renewed, re-verified recovery) remains the next action. - const ownsRecoveryControl = canMutate && !diskFullRest && (sourceLoading || Boolean(current && verified && !saved)); + const ownsRecoveryControl = canMutate && !userActionSaveRest && (sourceLoading || Boolean(current && verified && !saved)); // `waiting` already excludes a failed accepted request, so the reason stays // visible after a failed attempt and hides only while recovery is running. const unverified = Boolean(current && !verified && !saved && !waiting); return

{saved ? "Saved files recovered. Task recovery is still being checked." - : diskFullRest && !waiting ? "The sandbox disk was full when Paperclip saved the files. Free space, then use Retry to save them and finish the task." + : userActionSaveRest === "sandbox_disk_full" && !waiting + ? "The sandbox disk was full when Paperclip saved the files. Free space, then use Retry to save them and finish the task." + : userActionSaveRest === "git_operation_in_progress" && !waiting + ? "A Git operation was still in progress when Paperclip saved the files. Finish or abort it, then use Retry to save them and finish the task." : failedReceipt ? "File recovery has not finished. The saved source remains protected." : restoring ? "Recovering saved files. Work remains paused until recovery is verified." : waiting ? "File recovery is queued. Waiting for verified saved files." : "The saved files need recovery before work can continue."}

{canMutate ? <> - {current && verified && retryable && !waiting && !diskFullRest && (!pending || unconfirmed && checkedUnconfirmed || confirmedFailedAttempt) ? : null}