From f5457565de87b3f76b88eab6fbca94f428966d03 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Fri, 4 Dec 2026 14:08:47 -0600 Subject: [PATCH] fix(heartbeat): retry setup on retryable remote_incomplete workspace failures (#23764) ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Before a run starts its provider, Paperclip prepares the task workspace through a workspace provider plugin using a deterministic `operationId` > - A workspace provider can fail preparation with the closed retryable reason `remote_incomplete` when a remote storage or runtime request does not finish > - Setup recorded `remote_incomplete` as a generic `setup_failed` with no bounded retry, and release recovery immediately marked the task `blocked` without retrying the same workspace or showing the workspace failure reason in the escalation notice body > - This pull request gives a fresh pre-dispatch `remote_incomplete` answer its own transient setup code, `workspace_storage_incomplete`, routes it through the bounded bootstrap retry budget (deferring Sentry reporting until the retry decision), and forwards saved `workspaceProviderFailure` details into immediate execution-path escalation notices > - The benefit is that a task retries the same workspace automatically across transient remote storage/runtime failures instead of immediately blocking for a person ## Linked Issues or Issue Description Refs #23362, #19249 **What happened?** When a workspace provider returned the closed retryable reason `remote_incomplete` (`"Workspace storage operation is incomplete; retry the same workspace"`) during workspace bootstrap (`executionRecovery: { kind: "bootstrap", providerWorkStarted: false }`), `failRunSetup` recorded `errorCode: "setup_failed"` and scheduled no retry. Immediately after, `releaseIssueExecution` treated `setup_failed` as non-retryable continuation failure and marked the task `blocked` with a generic notice that omitted the workspace failure reason. **Expected behavior** When a legacy run fails before provider dispatch with a retryable `remote_incomplete` workspace provider answer, setup must classify it as `workspace_storage_incomplete` and schedule a bounded bootstrap retry of the same workspace (matching `workspace_storage_pending` and `plugin_worker_unavailable`). Sentry must report only when no retry is scheduled or retries are exhausted, and immediate execution-path escalation notices must include the bounded `workspaceProviderFailure` message when present. **Steps to reproduce** 1. Start a legacy run whose workspace preparation calls a workspace provider plugin. 2. Have the provider reject preparation with `PluginWorkspaceOperationError("remote_incomplete")`. 3. Before this fix, `failRunSetup` writes `errorCode: "setup_failed"`, schedules no bounded retry, and `releaseIssueExecution` immediately blocks the task. **Paperclip version or commit** Reproduced on `master` (`01ecbadbf1`). **Deployment mode** Self-hosted server and managed plugin workspace environments (`authenticated` and `local_trusted`). ## What Changed - `server/src/services/workspace-provider-failure.ts`: add `WORKSPACE_STORAGE_INCOMPLETE_CODE` (`workspace_storage_incomplete`) and `findWorkspaceStorageIncompleteFailure` matching `kind === "provider" && reason === "remote_incomplete"`. - `server/src/services/heartbeat/run-completion.ts`: map a fresh pre-dispatch legacy `remote_incomplete` failure (with no native session or runner instance) to `workspace_storage_incomplete`, route it through `scheduleBoundedRetryForRun` (keeping accepted interaction retries owned by the interaction lane), and defer Sentry reporting via `workspaceStorageIncompleteRetry`. - `server/src/services/failed-preparation-retry.ts`, `server/src/services/heartbeat/retries.ts`, `server/src/services/legacy-execution-recovery.ts`, `server/src/services/recovery/service.ts`, `server/src/services/agent-task-run-telemetry.ts`: handle `workspace_storage_incomplete` alongside `workspace_storage_pending`. - `server/src/services/recovery/stranded-notice.ts` & `server/src/services/heartbeat.ts`: add a stranded escalation notice for `workspace_storage_incomplete` and pass `workspaceProviderFailure: readWorkspaceProviderFailure(input.runRow.resultJson)` into `buildImmediateExecutionPathRecoveryNoticeSeed`. - `server/src/services/run-failure-diagnostics.ts` & `server/src/services/run-failure-report.ts`: add `workspaceStorageIncompleteRetry` deferred Sentry reporting handshake. - Add red-then-green regression tests in `run-completion.test.ts`, `workspace-provider-failure.test.ts`, `run-failure-report-sandbox-resume.test.ts`, and `heartbeat-retry-scheduling.test.ts`. ## Verification - Red before the fix: - `pnpm --dir server exec vitest run src/services/heartbeat/run-completion.test.ts -t "incomplete workspace storage"` failed on the `fresh` scenario with `errorCode: "setup_failed"` instead of `"workspace_storage_incomplete"`. - Green after the fix: - Focused `run-completion.test.ts`, `run-failure-report-sandbox-resume.test.ts`, `workspace-provider-failure.test.ts`, `agent-task-run-telemetry.test.ts`, `heartbeat-retry-scheduling.test.ts` (`bootstrap retries across restart`), and `pnpm --dir server typecheck` all pass. ## Risks - Low risk. No database schema, API route, or plugin wire protocol changes. - Retry applies only before provider dispatch on a legacy run with no native session or runner instance, bounded by the existing bootstrap retry budget (2 retries). Started and native runs keep `setup_failed` with no automatic retry. - Every workspace preparation call carries a deterministic `operationId` derived from workspace ID, generation, and operation payload, and `remote_incomplete` is explicitly marked `retryable: true` for the same workspace. ## Model Used - Google DeepMind Gemini 4 Neon (Medium reasoning budget), via Antigravity with tool use (code search, file edits, local test execution, and GitHub CLI). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip --- .../heartbeat-retry-scheduling.test.ts | 2 +- .../workspace-provider-failure.test.ts | 21 +++++++ .../run-failure-report-sandbox-resume.test.ts | 61 +++++++++++++++++-- .../src/services/agent-task-run-telemetry.ts | 1 + .../src/services/failed-preparation-retry.ts | 18 ++++-- server/src/services/heartbeat.ts | 9 ++- server/src/services/heartbeat/retries.ts | 9 +-- .../services/heartbeat/run-completion.test.ts | 20 +++++- .../src/services/heartbeat/run-completion.ts | 32 +++++----- .../src/services/legacy-execution-recovery.ts | 4 +- server/src/services/recovery/service.ts | 3 +- .../src/services/recovery/stranded-notice.ts | 1 + .../src/services/run-failure-diagnostics.ts | 7 ++- server/src/services/run-failure-report.ts | 20 +++--- .../services/workspace-provider-failure.ts | 26 +++++++- 15 files changed, 178 insertions(+), 56 deletions(-) diff --git a/server/src/__tests__/heartbeat-retry-scheduling.test.ts b/server/src/__tests__/heartbeat-retry-scheduling.test.ts index 1a3c9af7863..eff39b048e8 100644 --- a/server/src/__tests__/heartbeat-retry-scheduling.test.ts +++ b/server/src/__tests__/heartbeat-retry-scheduling.test.ts @@ -520,7 +520,7 @@ describeEmbeddedPostgres("heartbeat bounded retry scheduling", () => { return { companyId, agentId, issueId, runId, now }; } - it.each(["remote_workspace_prepare_timeout", "reusable_sandbox_resume_failed", "remote_workspace_restore_failed", "reviewed_chat_execution_binding_not_ready", "workspace_storage_pending"].flatMap(errorCode => + it.each(["remote_workspace_prepare_timeout", "reusable_sandbox_resume_failed", "remote_workspace_restore_failed", "reviewed_chat_execution_binding_not_ready", "workspace_storage_pending", "workspace_storage_incomplete"].flatMap(errorCode => (["resume", "paused", "Stop", "dependency"] as const).map(action => [errorCode, action] as const)))("bounds %s bootstrap retries across restart and honors %s", async (errorCode, action) => { const { companyId, agentId, issueId, runId, now } = await seedMaxTurnFixture(); await db.update(agents).set({ adapterType: "paperclip_runner", adapterConfig: { provider: "codex", model: "gpt-6.1-sol" } }) diff --git a/server/src/__tests__/workspace-provider-failure.test.ts b/server/src/__tests__/workspace-provider-failure.test.ts index 3ab7759ab20..a314de8eaa1 100644 --- a/server/src/__tests__/workspace-provider-failure.test.ts +++ b/server/src/__tests__/workspace-provider-failure.test.ts @@ -175,4 +175,25 @@ describe("workspace provider call failures", () => { expect(notice.body).toContain("no agent work started"); expect(notice.body).not.toMatch(/retried automatically|tries again automatically/); }); + + it("names incomplete workspace storage without claiming a retry that recovery did not schedule", () => { + const saved = readWorkspaceProviderFailure({ + workspaceProviderFailure: { kind: "provider", reason: "remote_incomplete", retryable: true }, + }); + const notice = buildStrandedRecoveryEscalationNotice({ + seed: buildNoRunningExecutionNoticeSeed({ status: "in_progress", workspaceProviderFailure: saved }), + recoveryActionId: id(14), + recoveryOwner: null, + sourceRun: { + id: id(15), + status: "failed", + errorCode: "workspace_storage_incomplete", + errorSummary: workspaceProviderFailureMessage(saved), + }, + }); + expect(JSON.stringify(notice.presentation)).toContain("Workspace storage operation did not finish"); + expect(JSON.stringify(notice.metadata)).toContain("Workspace storage operation is incomplete"); + expect(notice.body).toContain("no agent work started"); + expect(notice.body).not.toMatch(/retried automatically|tries again automatically/); + }); }); diff --git a/server/src/services/__tests__/run-failure-report-sandbox-resume.test.ts b/server/src/services/__tests__/run-failure-report-sandbox-resume.test.ts index 483d5d221d8..7109d66c990 100644 --- a/server/src/services/__tests__/run-failure-report-sandbox-resume.test.ts +++ b/server/src/services/__tests__/run-failure-report-sandbox-resume.test.ts @@ -15,7 +15,7 @@ vi.mock("../../sentry.js", () => ({ import { environmentResumeErrorData, JsonRpcCallError, PLUGIN_RPC_ERROR_CODES, PluginWorkspaceOperationError, workspaceOperationErrorData } from "@paperclipai/plugin-sdk"; import { reportRunFailure } from "../run-failure-report.js"; import { REUSABLE_SANDBOX_RESUME_FAILED_CODE, ReusableSandboxResumeError } from "../reusable-sandbox-resume-error.js"; -import { WORKSPACE_STORAGE_PENDING_CODE, workspaceProviderCallFailure } from "../workspace-provider-failure.js"; +import { WORKSPACE_STORAGE_INCOMPLETE_CODE, WORKSPACE_STORAGE_PENDING_CODE, workspaceProviderCallFailure } from "../workspace-provider-failure.js"; const testDatabaseUrl = process.env.PAPERCLIP_TEST_DATABASE_URL; const embeddedPostgresSupport = testDatabaseUrl ? { supported: true } : await getEmbeddedPostgresTestSupport(); @@ -158,11 +158,11 @@ describeEmbeddedPostgres("reportRunFailure setup retry decisions", () => { it("keeps pending project storage local until its retry decision, and after a scheduled retry", async () => { const run = storagePendingRun(); const error = storagePending(); - await reportRunFailure(db, run, { phase: "setup", error, workspaceStoragePendingRetry: "pending" }); - await reportRunFailure(db, run, { phase: "setup", error, workspaceStoragePendingRetry: "scheduled" }); + await reportRunFailure(db, run, { phase: "setup", error, workspaceStorageRetry: "pending" }); + await reportRunFailure(db, run, { phase: "setup", error, workspaceStorageRetry: "scheduled" }); // The setup path reports once more with its decision, so a pending write stays local in every mode. vi.stubEnv("PAPERCLIP_SENTRY_RUN_FAILURES", "all"); - await reportRunFailure(db, run, { phase: "setup", error, workspaceStoragePendingRetry: "pending" }); + await reportRunFailure(db, run, { phase: "setup", error, workspaceStorageRetry: "pending" }); expect(mockCaptureRunFailure).not.toHaveBeenCalled(); }); @@ -171,11 +171,60 @@ describeEmbeddedPostgres("reportRunFailure setup retry decisions", () => { ["the decision is unknown", {}, undefined, "unexpected"], ["every run failure is reported", {}, "scheduled", "all"], ["the run failed for another reason", { errorCode: "setup_failed" }, "scheduled", "unexpected"], - ] as const)("reports pending project storage when %s", async (_label, overrides, workspaceStoragePendingRetry, mode) => { + ] as const)("reports pending project storage when %s", async (_label, overrides, workspaceStorageRetry, mode) => { vi.stubEnv("PAPERCLIP_SENTRY_RUN_FAILURES", mode); const run = storagePendingRun(overrides); await reportRunFailure(db, run, { phase: "setup", error: storagePending(), - ...(workspaceStoragePendingRetry ? { workspaceStoragePendingRetry } : {}) }); + ...(workspaceStorageRetry ? { workspaceStorageRetry } : {}) }); + expect(mockCaptureRunFailure).toHaveBeenCalledOnce(); + expect(mockCaptureRunFailure.mock.calls[0]![0]).toMatchObject({ errorCode: run.errorCode, runStatus: "failed" }); + expect(JSON.stringify(mockCaptureRunFailure.mock.calls[0]![0])).not.toContain("private provider text"); + }); + + const storageIncomplete = () => workspaceProviderCallFailure(new JsonRpcCallError({ + code: PLUGIN_RPC_ERROR_CODES.WORKER_ERROR, + message: "private provider text", + data: workspaceOperationErrorData(new PluginWorkspaceOperationError("remote_incomplete")), + })); + + function storageIncompleteRun(overrides: Partial = {}): typeof heartbeatRuns.$inferSelect { + return { + id: randomUUID(), + companyId, + agentId, + status: "failed", + error: "Workspace storage operation is incomplete; retry the same workspace", + errorCode: WORKSPACE_STORAGE_INCOMPLETE_CODE, + runtimeMode: "legacy", + executionStage: "preparing", + nativeIssueId: null, + contextSnapshot: null, + resultJson: { executionRecovery: { kind: "bootstrap", providerWorkStarted: false }, + workspaceProviderFailure: { kind: "provider", reason: "remote_incomplete", retryable: true } }, + ...overrides, + } as unknown as typeof heartbeatRuns.$inferSelect; + } + + it("keeps incomplete workspace storage local until its retry decision, and after a scheduled retry", async () => { + const run = storageIncompleteRun(); + const error = storageIncomplete(); + await reportRunFailure(db, run, { phase: "setup", error, workspaceStorageRetry: "pending" }); + await reportRunFailure(db, run, { phase: "setup", error, workspaceStorageRetry: "scheduled" }); + vi.stubEnv("PAPERCLIP_SENTRY_RUN_FAILURES", "all"); + await reportRunFailure(db, run, { phase: "setup", error, workspaceStorageRetry: "pending" }); + expect(mockCaptureRunFailure).not.toHaveBeenCalled(); + }); + + it.each([ + ["no retry was scheduled", {}, "not_scheduled", "unexpected"], + ["the decision is unknown", {}, undefined, "unexpected"], + ["every run failure is reported", {}, "scheduled", "all"], + ["the run failed for another reason", { errorCode: "setup_failed" }, "scheduled", "unexpected"], + ] as const)("reports incomplete workspace storage when %s", async (_label, overrides, workspaceStorageRetry, mode) => { + vi.stubEnv("PAPERCLIP_SENTRY_RUN_FAILURES", mode); + const run = storageIncompleteRun(overrides); + await reportRunFailure(db, run, { phase: "setup", error: storageIncomplete(), + ...(workspaceStorageRetry ? { workspaceStorageRetry } : {}) }); expect(mockCaptureRunFailure).toHaveBeenCalledOnce(); expect(mockCaptureRunFailure.mock.calls[0]![0]).toMatchObject({ errorCode: run.errorCode, runStatus: "failed" }); expect(JSON.stringify(mockCaptureRunFailure.mock.calls[0]![0])).not.toContain("private provider text"); diff --git a/server/src/services/agent-task-run-telemetry.ts b/server/src/services/agent-task-run-telemetry.ts index 0ad40a74a0f..d8870664e39 100644 --- a/server/src/services/agent-task-run-telemetry.ts +++ b/server/src/services/agent-task-run-telemetry.ts @@ -43,6 +43,7 @@ const PLATFORM_FAILURE_CODES = new Set([ "lease_released_before_terminal", "plugin_worker_unavailable", "workspace_storage_pending", + "workspace_storage_incomplete", "native_workspace_sync_out_retry_exhausted", "queued_run_claim_rejected", ]); diff --git a/server/src/services/failed-preparation-retry.ts b/server/src/services/failed-preparation-retry.ts index 1e0d5b6418b..bdb59400d58 100644 --- a/server/src/services/failed-preparation-retry.ts +++ b/server/src/services/failed-preparation-retry.ts @@ -10,7 +10,7 @@ import { REUSABLE_SANDBOX_RESUME_FAILED_CODE } from "./reusable-sandbox-resume-e import { REVIEWED_CHAT_BINDING_NOT_READY } from "./reviewed-chat-binding-diagnostics.js"; import { RUNNER_REVISION_MISMATCH_CODE } from "./runner-revision-mismatch.js"; import { WORKSPACE_GIT_SCAN_ERROR_CODES } from "./workspace-git-operation-scheduler.js"; -import { WORKSPACE_STORAGE_PENDING_CODE } from "./workspace-provider-failure.js"; +import { WORKSPACE_STORAGE_INCOMPLETE_CODE, WORKSPACE_STORAGE_PENDING_CODE } from "./workspace-provider-failure.js"; type HeartbeatRun = typeof heartbeatRuns.$inferSelect; @@ -20,9 +20,19 @@ export const TRANSIENT_WORKSPACE_PREPARATION_CODES: readonly string[] = [ REMOTE_WORKSPACE_RESTORE_FAILED_CODE, PLUGIN_WORKER_UNAVAILABLE_CODE, RUNNER_REVISION_MISMATCH_CODE, ENVIRONMENT_PROVIDER_UNAVAILABLE_CODE, REPOSITORY_CATALOG_UNAVAILABLE_CODE, REVIEWED_CHAT_BINDING_NOT_READY, - STORAGE_UNAVAILABLE_CODE, WORKSPACE_STORAGE_PENDING_CODE, + STORAGE_UNAVAILABLE_CODE, WORKSPACE_STORAGE_PENDING_CODE, WORKSPACE_STORAGE_INCOMPLETE_CODE, ]; +/** Transient setup codes whose accepted-interaction wakes stay on the interaction continuation retry lane. */ +export const INTERACTION_OWNED_TRANSIENT_SETUP_CODES: readonly string[] = [ + PLUGIN_WORKER_UNAVAILABLE_CODE, WORKSPACE_STORAGE_PENDING_CODE, WORKSPACE_STORAGE_INCOMPLETE_CODE, + ENVIRONMENT_PROVIDER_UNAVAILABLE_CODE, REPOSITORY_CATALOG_UNAVAILABLE_CODE, REVIEWED_CHAT_BINDING_NOT_READY, +]; + +export function isInteractionOwnedTransientSetupCode(code: string | null | undefined): boolean { + return typeof code === "string" && INTERACTION_OWNED_TRANSIENT_SETUP_CODES.includes(code); +} + export function isTransientWorkspacePreparationCode(code: string | null | undefined): boolean { return typeof code === "string" && TRANSIENT_WORKSPACE_PREPARATION_CODES.includes(code); } @@ -45,8 +55,6 @@ export function failedPreparationOwnsBoundedRetry(run: Pick { + const remoteIncomplete = () => workspaceProviderCallFailure(new JsonRpcCallError({ code: PLUGIN_RPC_ERROR_CODES.WORKER_ERROR, + message: "private provider text", data: workspaceOperationErrorData(new PluginWorkspaceOperationError("remote_incomplete")) })); + + it.each(["fresh", "started", "retained"] as const)("routes a %s incomplete workspace storage answer through bounded bootstrap recovery", async scenario => { + const f = await fixture({ runtimeMode: scenario === "retained" ? "native" : "legacy" }); + f.deps.scheduleBoundedRetryForRun.mockResolvedValueOnce({ outcome: "not_scheduled", reason: "Fixture scheduler boundary", issueId: null }); + await f.completion.failRunSetup(f.setup(remoteIncomplete(), scenario === "started")); + const failed = await read(f.run.id); + expect(failed).toMatchObject({ status: "failed", errorCode: scenario === "fresh" ? "workspace_storage_incomplete" : "setup_failed", + error: "Workspace storage operation is incomplete; retry the same workspace" }); + expect(failed.error).not.toContain("private"); + if (scenario === "fresh") { + expect(failed.resultJson).toMatchObject({ executionRecovery: { kind: "bootstrap", providerWorkStarted: false }, + workspaceProviderFailure: { kind: "provider", reason: "remote_incomplete", retryable: true } }); + expect(f.deps.scheduleBoundedRetryForRun).toHaveBeenCalledWith(expect.objectContaining({ id: f.run.id }), f.agent); + } else expect(f.deps.scheduleBoundedRetryForRun).not.toHaveBeenCalled(); + }); + + it.each(["context_changed", "deadline_exceeded"] as const)("keeps a retryable %s provider answer a generic setup failure", async reason => { const f = await fixture(); await f.completion.failRunSetup(f.setup(workspaceProviderCallFailure(new JsonRpcCallError({ code: PLUGIN_RPC_ERROR_CODES.WORKER_ERROR, message: "private provider text", data: workspaceOperationErrorData(new PluginWorkspaceOperationError(reason)) })))); diff --git a/server/src/services/heartbeat/run-completion.ts b/server/src/services/heartbeat/run-completion.ts index 119d483f837..2739bede80d 100644 --- a/server/src/services/heartbeat/run-completion.ts +++ b/server/src/services/heartbeat/run-completion.ts @@ -33,13 +33,14 @@ import { pendingCaseHandoffForRun } from "./case-handoff-lifecycle.js"; import { NON_RETRYABLE_PREFLIGHT_FAILURE_CODES, isHeartbeatRunTerminalStatus } from "./run-lifecycle.js"; import { ChatControlRecoveryUnresolvedError } from "./queue.js"; import { readTransientRecoveryContractFromRun, readHeartbeatRunErrorFamily, isTransientWorkspacePreparationCode } from "./retries.js"; +import { isInteractionOwnedTransientSetupCode } from "../failed-preparation-retry.js"; import { RemoteWorkspacePreparationTimeoutError, REMOTE_WORKSPACE_RESTORE_FAILED_CODE, findRemoteWorkspaceRestoreError, isRemoteWorkspaceSandboxDiskFullError } from "../remote-workspace-transport.js"; import { escalateRemoteWorkspaceRestoreFailure } from "../remote-workspace-restore-recovery.js"; import { findReusableSandboxResumeError } from "../reusable-sandbox-resume-error.js"; import { findPluginWorkerUnavailableError, PLUGIN_WORKER_UNAVAILABLE_CODE } from "../plugin-worker-unavailable-error.js"; import { ENVIRONMENT_PROVIDER_UNAVAILABLE_CODE, findEnvironmentProviderUnavailableError } from "../environment-provider-unavailable-error.js"; import { REPOSITORY_CATALOG_UNAVAILABLE_CODE, findRepositoryCatalogUnavailableError } from "../repository-catalog-unavailable-error.js"; -import { findWorkspaceProviderFailure, findWorkspaceStoragePendingFailure, WORKSPACE_STORAGE_PENDING_CODE } from "../workspace-provider-failure.js"; +import { findRetryableWorkspaceStorageSetupCode, findWorkspaceProviderFailure, WORKSPACE_STORAGE_RETRY_CODES } from "../workspace-provider-failure.js"; import { isRunnerRevisionMismatch, RUNNER_REVISION_MISMATCH_CODE, RUNNER_REVISION_MISMATCH_RETRY } from "../runner-revision-mismatch.js"; import { readPluginTaskError } from "../environment-task-runtime.js"; import { isStorageUnavailableError, STORAGE_CREDENTIALS_REJECTED_MESSAGE, STORAGE_UNAVAILABLE_CODE, STORAGE_UNAVAILABLE_EXHAUSTED_MESSAGE, STORAGE_UNAVAILABLE_MESSAGE, STORAGE_UNAVAILABLE_RETRY, storageUnavailableHeldMessage, storageUnavailableMessage } from "../../storage/storage-unavailable.js"; @@ -1734,11 +1735,11 @@ export function createHeartbeatRunCompletion(db: Db, dependencies: HeartbeatRunC // bootstrap budget; the worker is restarted or replaced meanwhile. const pluginWorkerUnavailableFailure = !providerDispatchStarted && run.runtimeMode === "legacy" && run.nativeSessionId === null && run.runnerInstanceId === null ? findPluginWorkerUnavailableError(outerErr) : null; - // The workspace provider answered that project storage is still being - // prepared. It gives that answer before any workspace effect, so the same - // workspace is retried within the bootstrap budget. - const workspaceStoragePending = !providerDispatchStarted && run.runtimeMode === "legacy" - && run.nativeSessionId === null && run.runnerInstanceId === null && findWorkspaceStoragePendingFailure(outerErr) !== null; + // Retryable pre-dispatch workspace storage failures (`storage_pending` and + // `remote_incomplete`) retry the same workspace within the bootstrap budget. + const workspaceStorageRetryCode = !providerDispatchStarted && run.runtimeMode === "legacy" + && run.nativeSessionId === null && run.runnerInstanceId === null + ? findRetryableWorkspaceStorageSetupCode(outerErr) : null; // The environment provider refused lease acquisition with a transient // status (HTTP 5xx/429/timeout) before dispatch. Each retry is a new, // separately owned creation attempt; an unconfirmed provisional allocation @@ -1767,7 +1768,7 @@ export function createHeartbeatRunCompletion(db: Db, dependencies: HeartbeatRunC reusableSandboxResumeFailure?.code ?? remoteWorkspaceRestoreFailure?.code ?? pluginWorkerUnavailableFailure?.code ?? - (workspaceStoragePending ? WORKSPACE_STORAGE_PENDING_CODE : null) ?? + workspaceStorageRetryCode ?? environmentProviderUnavailable?.code ?? repositoryCatalogUnavailable?.code ?? reviewedChatBindingNotReady?.code ?? @@ -1788,8 +1789,8 @@ export function createHeartbeatRunCompletion(db: Db, dependencies: HeartbeatRunC // a provider outage is reported only after that retry decision. const sandboxResumeOutage = setupFailureErrorCode === reusableSandboxResumeFailure?.code && reusableSandboxResumeFailure.providerOutage; - // Pending project storage is reported only when no bounded retry owns it. - const storagePendingRetry = setupFailureErrorCode === WORKSPACE_STORAGE_PENDING_CODE; + // Retryable pre-dispatch workspace storage failures are reported only when no bounded retry owns them. + const workspaceStorageRetry = WORKSPACE_STORAGE_RETRY_CODES.has(setupFailureErrorCode); // Bounded kind and reason only: a workspace provider's own text never crosses into Core. const workspaceProviderFailure = findWorkspaceProviderFailure(outerErr)?.summary() ?? null; // A wrapped query error hides its driver cause (for example @@ -1882,7 +1883,7 @@ export function createHeartbeatRunCompletion(db: Db, dependencies: HeartbeatRunC // The Sentry report waits for the bounded retry decision below. ...(reviewedChatBindingNotReady ? { reviewedChatRetry: "pending" as const } : {}), ...(sandboxResumeOutage ? { sandboxResumeRetry: "pending" as const } : {}), - ...(storagePendingRetry ? { workspaceStoragePendingRetry: "pending" as const } : {}), + ...(workspaceStorageRetry ? { workspaceStorageRetry: "pending" as const } : {}), }, { setupFailure: true }).catch(() => ({ run: null, updated: false as const })); let setupRetryScheduled = false; if (!setupFailureWrite.updated) { @@ -1968,11 +1969,7 @@ export function createHeartbeatRunCompletion(db: Db, dependencies: HeartbeatRunC } else if (livenessRun.errorCode !== PROJECT_ACCESS_DENIED) { // An accepted interaction keeps its own continuation retry, which // carries the interaction and escalates on exhaustion. - const interactionOwnsRetry = (livenessRun.errorCode === PLUGIN_WORKER_UNAVAILABLE_CODE - || livenessRun.errorCode === WORKSPACE_STORAGE_PENDING_CODE - || livenessRun.errorCode === ENVIRONMENT_PROVIDER_UNAVAILABLE_CODE - || livenessRun.errorCode === REPOSITORY_CATALOG_UNAVAILABLE_CODE - || livenessRun.errorCode === REVIEWED_CHAT_BINDING_NOT_READY) + const interactionOwnsRetry = isInteractionOwnedTransientSetupCode(livenessRun.errorCode) && isResolvedInteractionContinuationWakeContext(livenessRun.contextSnapshot); const retry = await (isTransientWorkspacePreparationCode(livenessRun.errorCode) && !interactionOwnsRetry ? livenessRun.errorCode === RUNNER_REVISION_MISMATCH_CODE @@ -2021,13 +2018,14 @@ export function createHeartbeatRunCompletion(db: Db, dependencies: HeartbeatRunC ); } // This path owned the failed-status write, which deferred the report. - const deferredReportRun = (reviewedChatBindingNotReady || sandboxResumeOutage || storagePendingRetry) && setupFailureWrite.updated + const deferredReportRun = (reviewedChatBindingNotReady || sandboxResumeOutage || workspaceStorageRetry) && setupFailureWrite.updated ? failedRun ?? setupFailureWrite.run : null; if (deferredReportRun) { const retryDecision = setupRetryScheduled ? "scheduled" as const : "not_scheduled" as const; void reportRunFailure(db, deferredReportRun, { error: outerErr, phase: "setup", secretValues: readFailureReportSecrets(), ...(reviewedChatBindingNotReady ? { reviewedChatRetry: retryDecision } - : storagePendingRetry ? { workspaceStoragePendingRetry: retryDecision } : { sandboxResumeRetry: retryDecision }) }); + : workspaceStorageRetry ? { workspaceStorageRetry: retryDecision } + : { sandboxResumeRetry: retryDecision }) }); } // Ensure the agent is not left stuck in "running" if the setup-failure // path owned the terminal transition. If another path already finalized diff --git a/server/src/services/legacy-execution-recovery.ts b/server/src/services/legacy-execution-recovery.ts index 0f8f4924c29..7d3980ab94d 100644 --- a/server/src/services/legacy-execution-recovery.ts +++ b/server/src/services/legacy-execution-recovery.ts @@ -10,7 +10,7 @@ import { isPreDispatchExecutionWaitVerified } from "./pre-dispatch-execution-wai import { REMOTE_WORKSPACE_PREPARATION_TIMEOUT_CODE, REMOTE_WORKSPACE_RESTORE_FAILED_CODE } from "./remote-workspace-transport.js"; import { REUSABLE_SANDBOX_RESUME_FAILED_CODE } from "./reusable-sandbox-resume-error.js"; import { PLUGIN_WORKER_UNAVAILABLE_CODE } from "./plugin-worker-unavailable-error.js"; -import { WORKSPACE_STORAGE_PENDING_CODE } from "./workspace-provider-failure.js"; +import { WORKSPACE_STORAGE_INCOMPLETE_CODE, WORKSPACE_STORAGE_PENDING_CODE } from "./workspace-provider-failure.js"; import { ENVIRONMENT_PROVIDER_UNAVAILABLE_CODE } from "./environment-provider-unavailable-error.js"; import { REPOSITORY_CATALOG_UNAVAILABLE_CODE } from "./repository-catalog-unavailable-error.js"; import { RUNNER_REVISION_MISMATCH_CODE } from "./runner-revision-mismatch.js"; @@ -90,7 +90,7 @@ export function legacyExecutionNeedsReconciliation( if ((run.errorCode === "workspace_git_scan_timeout" || run.errorCode === "workspace_git_scan_saturated" || run.errorCode === REMOTE_WORKSPACE_PREPARATION_TIMEOUT_CODE || run.errorCode === REUSABLE_SANDBOX_RESUME_FAILED_CODE || run.errorCode === REMOTE_WORKSPACE_RESTORE_FAILED_CODE || run.errorCode === PLUGIN_WORKER_UNAVAILABLE_CODE - || run.errorCode === WORKSPACE_STORAGE_PENDING_CODE + || run.errorCode === WORKSPACE_STORAGE_PENDING_CODE || run.errorCode === WORKSPACE_STORAGE_INCOMPLETE_CODE || run.errorCode === RUNNER_REVISION_MISMATCH_CODE || run.errorCode === ENVIRONMENT_PROVIDER_UNAVAILABLE_CODE || run.errorCode === REPOSITORY_CATALOG_UNAVAILABLE_CODE) && evidence?.kind === "bootstrap" && evidence.providerWorkStarted === false) return false; diff --git a/server/src/services/recovery/service.ts b/server/src/services/recovery/service.ts index dbd949354c7..7359fa46f75 100644 --- a/server/src/services/recovery/service.ts +++ b/server/src/services/recovery/service.ts @@ -201,7 +201,7 @@ import { } from "./origins.js"; import { withRecoveryContext } from "./status-only-context.js"; import { getExecutionBlocker } from "../execution-blocker.js"; -import { readWorkspaceProviderFailure, WORKSPACE_STORAGE_PENDING_CODE } from "../workspace-provider-failure.js"; +import { readWorkspaceProviderFailure, WORKSPACE_STORAGE_INCOMPLETE_CODE, WORKSPACE_STORAGE_PENDING_CODE } from "../workspace-provider-failure.js"; import { currentRunFailureText } from "../native-runtime/native-exact-resume-failure.js"; import { isAutomaticRecoverySuppressedByPauseHold } from "./pause-hold-guard.js"; import { rehomeStrandedLegacyWorkspaceTasks } from "./legacy-workspace-rehome.js"; @@ -660,6 +660,7 @@ const NON_RETRYABLE_CONTINUATION_ERROR_CODES = new Set([ REMOTE_WORKSPACE_RESTORE_FAILED_CODE, PLUGIN_WORKER_UNAVAILABLE_CODE, WORKSPACE_STORAGE_PENDING_CODE, + WORKSPACE_STORAGE_INCOMPLETE_CODE, ENVIRONMENT_PROVIDER_UNAVAILABLE_CODE, RUNNER_REVISION_MISMATCH_CODE, "low_trust_isolation_unavailable", diff --git a/server/src/services/recovery/stranded-notice.ts b/server/src/services/recovery/stranded-notice.ts index b2f5d8e558d..9de2029ccd7 100644 --- a/server/src/services/recovery/stranded-notice.ts +++ b/server/src/services/recovery/stranded-notice.ts @@ -83,6 +83,7 @@ const WORKSPACE_SCAN_NOTICES: Record([ + WORKSPACE_STORAGE_PENDING_CODE, + WORKSPACE_STORAGE_INCOMPLETE_CODE, +]); + +const RETRYABLE_PROVIDER_REASON_TO_SETUP_CODE: Partial> = { + storage_pending: WORKSPACE_STORAGE_PENDING_CODE, + remote_incomplete: WORKSPACE_STORAGE_INCOMPLETE_CODE, +}; + +/** Classify a retryable pre-dispatch workspace provider reason to its transient setup code. */ +export function findRetryableWorkspaceStorageSetupCode(error: unknown): string | null { const failure = findWorkspaceProviderFailure(error); - return failure?.kind === "provider" && failure.reason === "storage_pending" ? failure : null; + if (failure?.kind !== "provider" || !failure.reason) return null; + return RETRYABLE_PROVIDER_REASON_TO_SETUP_CODE[failure.reason] ?? null; } export type WorkspaceProviderFailureSummary = {