fix(heartbeat): retry setup when project storage is still being prepared (#23362)

## 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.
> - A provider can answer a polled preparation with the closed reason
`storage_pending`. This means that the project's storage is still being
prepared. The provider gives this answer before any workspace effect.
> - Setup recorded this answer as a generic `setup_failed`. It scheduled
no retry. The task waited for a person to press Retry, and Sentry
received an error for each attempt.
> - This pull request gives the answer its own transient setup code,
`workspace_storage_pending`. Setup then retries the same workspace
within the bounded bootstrap budget.
> - The benefit is that a task continues by itself when the project's
storage becomes ready, and Sentry gets a report only when no retry owns
recovery.

## Linked Issues or Issue Description

Refs #19249 (the same retry for a stopped plugin worker)
Refs #21510 (the same deferred Sentry report for a saved-sandbox resume
outage)

**What happened?**
On staging, runs failed in the preparing stage with "Project storage is
still being prepared; retry the same workspace shortly". Each run waited
about 3.5 minutes in the polled preparation. Then the provider answered
`storage_pending`. The run got `setup_failed` with
`workspaceProviderFailure: { kind: "provider", reason:
"storage_pending", retryable: true }` and `executionRecovery: { kind:
"bootstrap", providerWorkStarted: false }`. No retry was scheduled. A
person pressed Retry several times, and each attempt sent a new Sentry
error.

**Expected behavior**
No workspace effect or provider work started, and the provider marks the
reason retryable. The run must retry within the bounded bootstrap
budget, as it does for `plugin_worker_unavailable`. Sentry must get a
report only when no retry is scheduled.

**Steps to reproduce**
1. Use a project whose workspace storage is still being provisioned.
2. Wake an agent whose legacy run prepares a workspace through that
provider.
3. The provider answers `storage_pending` at the end of its wait. The
run fails with `setup_failed`. No retry is scheduled.

**Paperclip version or commit**
master at 7ce7d99f8a.

## What Changed

- `workspace-provider-failure.ts`: add `WORKSPACE_STORAGE_PENDING_CODE`
(`workspace_storage_pending`) and `findWorkspaceStoragePendingFailure`.
The finder matches only a provider answer with the closed reason
`storage_pending`.
- `run-completion.ts`: map that answer to `workspace_storage_pending`.
Do this only before provider dispatch and only for a legacy run with no
native session or runner instance. These are the same guards as for the
sibling transient codes.
- `failed-preparation-retry.ts`: add the code to the transient
preparation codes, so setup schedules the bounded bootstrap retry. An
accepted interaction keeps its own continuation retry, as for the
sibling codes.
- Retry, legacy recovery, recovery service and telemetry: treat the code
like the other bootstrap-only transient codes. The stranded-task notice
has a title and a next action for it.
- `run-failure-report.ts`: wait for the retry decision before the Sentry
report (`workspaceStoragePendingRetry`), with the same handshake as
`sandboxResumeRetry`. A scheduled retry is not reported. An unscheduled
or exhausted retry is reported.
- Other retryable provider reasons (`remote_incomplete`,
`context_changed`, `deadline_exceeded`) do not change. These reasons can
follow a started effect, so they keep `setup_failed`.

## Verification

- Red: the new `run-completion` test failed on the unchanged code. A
fresh `storage_pending` answer got `setup_failed`, the same code that
staging recorded.
- Green: the same test passes. A fresh answer gets
`workspace_storage_pending`, `providerWorkStarted: false` and a bounded
retry. A started or native run keeps `setup_failed` and gets no retry.
Provider text does not reach the run.
- New test: `remote_incomplete`, `context_changed` and
`deadline_exceeded` answers keep `setup_failed` and get no retry.
- New report tests: a pending or scheduled decision sends no Sentry
report. An unscheduled decision, an unknown decision, `all` mode, and
another error code are reported once, without provider text.
- `heartbeat-retry-scheduling`: the new code is bounded across a restart
and honors resume, pause, Stop and a blocking dependency.
- `vitest run src/services/heartbeat/run-completion.test.ts
src/services/__tests__/run-failure-report-sandbox-resume.test.ts`: 190
passed.
- `vitest run src/__tests__/heartbeat-retry-scheduling.test.ts -t
"bootstrap retries across restart"`: 20 passed.
- `vitest run src/__tests__/workspace-provider-failure.test.ts
src/__tests__/agent-task-run-telemetry.test.ts`: 61 passed.
- Review fix: the escalated `workspace_storage_pending` notice no longer
says that Paperclip retried automatically, because recovery can show it
when no retry was scheduled. A new notice test failed on the old wording
and passes now (`workspace-provider-failure.test.ts`: 7 passed).
- `PAPERCLIP_TYPECHECK_LOW_MEMORY=1 pnpm --filter @paperclipai/server
typecheck`: all seven layers pass. (A single-program `tsc -p server` run
was stopped by the memory limit of the local machine; the layered check
is the documented low-memory path.)

## Risks

- Low risk. The retry uses the existing bounded bootstrap budget (two
retries). When the budget is exhausted, the existing board recovery
action takes over and Sentry gets the report.
- The retry applies only before provider dispatch on a legacy run. A
native run or a started run keeps the old behavior.
- A wrapper that drops the error `cause` keeps the old `setup_failed`
behavior. It does not cause a wrong retry.
- Project storage that never becomes ready still needs a fix in the
provider. This change only stops a short wait from needing a person.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, with tool use and code
execution in Claude Code.

## 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
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: devinfoley <139239+devinfoley@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
authored and GitHub committed 2026-12-01 10:20:56 +00:00
1 parent b3fd921cfb
commit 6678554a5a
14 files changed
+153 -10

No files matched your search

@@ -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"].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"].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" } })
@@ -164,4 +164,15 @@ describe("workspace provider call failures", () => {
expect(escalated.body).toContain("Saved workspace storage no longer matches this workspace");
expect(escalated.body).toContain("after 2 tries");
});
it("names pending project storage without claiming a retry that recovery did not schedule", () => {
const notice = buildStrandedRecoveryEscalationNotice({
recoveryActionId: id(12),
recoveryOwner: null,
sourceRun: { id: id(13), status: "failed", errorCode: "workspace_storage_pending" },
});
expect(JSON.stringify(notice.presentation)).toContain("Project storage was still being prepared");
expect(notice.body).toContain("no agent work started");
expect(notice.body).not.toMatch(/retried automatically|tries again automatically/);
});
});
@@ -12,15 +12,16 @@ vi.mock("../../sentry.js", () => ({
captureRunFailure: mockCaptureRunFailure,
}));
import { environmentResumeErrorData, JsonRpcCallError } from "@paperclipai/plugin-sdk";
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";
const testDatabaseUrl = process.env.PAPERCLIP_TEST_DATABASE_URL;
const embeddedPostgresSupport = testDatabaseUrl ? { supported: true } : await getEmbeddedPostgresTestSupport();
const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip;
describeEmbeddedPostgres("reportRunFailure sandbox resume provider outages", () => {
describeEmbeddedPostgres("reportRunFailure setup retry decisions", () => {
let db!: ReturnType<typeof createDb>;
let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;
let companyId!: string;
@@ -128,4 +129,55 @@ describeEmbeddedPostgres("reportRunFailure sandbox resume provider outages", ()
expect(mockCaptureRunFailure).toHaveBeenCalledOnce();
expect(mockCaptureRunFailure.mock.calls[0]![0]).toMatchObject({ errorCode: run.errorCode, runStatus: "failed" });
});
// The workspace provider answered `storage_pending` before any workspace
// effect. Only the closed reason crosses JSON-RPC; provider text never does.
const storagePending = () => workspaceProviderCallFailure(new JsonRpcCallError({ code: PLUGIN_RPC_ERROR_CODES.WORKER_ERROR,
message: "private provider text", data: workspaceOperationErrorData(new PluginWorkspaceOperationError("storage_pending")) }));
function storagePendingRun(
overrides: Partial<typeof heartbeatRuns.$inferSelect> = {},
): typeof heartbeatRuns.$inferSelect {
return {
id: randomUUID(),
companyId,
agentId,
status: "failed",
error: "Project storage is still being prepared; retry the same workspace shortly",
errorCode: WORKSPACE_STORAGE_PENDING_CODE,
runtimeMode: "legacy",
executionStage: "preparing",
nativeIssueId: null,
contextSnapshot: null,
resultJson: { executionRecovery: { kind: "bootstrap", providerWorkStarted: false },
workspaceProviderFailure: { kind: "provider", reason: "storage_pending", retryable: true } },
...overrides,
} as unknown as typeof heartbeatRuns.$inferSelect;
}
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" });
// 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" });
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 pending project storage when %s", async (_label, overrides, workspaceStoragePendingRetry, mode) => {
vi.stubEnv("PAPERCLIP_SENTRY_RUN_FAILURES", mode);
const run = storagePendingRun(overrides);
await reportRunFailure(db, run, { phase: "setup", error: storagePending(),
...(workspaceStoragePendingRetry ? { workspaceStoragePendingRetry } : {}) });
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");
});
});
@@ -42,6 +42,7 @@ const PLATFORM_FAILURE_CODES = new Set<string>([
"native_execution_ownership_unverified",
"lease_released_before_terminal",
"plugin_worker_unavailable",
"workspace_storage_pending",
"native_workspace_sync_out_retry_exhausted",
"queued_run_claim_rejected",
]);
@@ -10,6 +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";
type HeartbeatRun = typeof heartbeatRuns.$inferSelect;
@@ -19,7 +20,7 @@ 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,
STORAGE_UNAVAILABLE_CODE, WORKSPACE_STORAGE_PENDING_CODE,
];
export function isTransientWorkspacePreparationCode(code: string | null | undefined): boolean {
@@ -44,7 +45,8 @@ export function failedPreparationOwnsBoundedRetry(run: Pick<HeartbeatRun,
if (run.errorCode === REMOTE_WORKSPACE_RESTORE_FAILED_CODE)
return parseObject(run.resultJson?.remoteWorkspaceRestore).retryable === true;
// An accepted interaction keeps its own continuation retry.
return !((run.errorCode === PLUGIN_WORKER_UNAVAILABLE_CODE || run.errorCode === ENVIRONMENT_PROVIDER_UNAVAILABLE_CODE
return !((run.errorCode === PLUGIN_WORKER_UNAVAILABLE_CODE || run.errorCode === WORKSPACE_STORAGE_PENDING_CODE
|| run.errorCode === ENVIRONMENT_PROVIDER_UNAVAILABLE_CODE
|| run.errorCode === REPOSITORY_CATALOG_UNAVAILABLE_CODE || run.errorCode === REVIEWED_CHAT_BINDING_NOT_READY)
&& isResolvedInteractionContinuationWakeContext(run.contextSnapshot));
}
+2
View File
@@ -35,6 +35,7 @@ import {
import { isReplacedPreparation, isServerReplacementInterruption } from "../server-replacement-interruption.js";
import { failedPreparationOwnsBoundedRetry, isTransientWorkspacePreparationCode } from "../failed-preparation-retry.js";
import { PLUGIN_WORKER_UNAVAILABLE_CODE } from "../plugin-worker-unavailable-error.js";
import { 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 { REVIEWED_CHAT_BINDING_NOT_READY } from "../reviewed-chat-binding-diagnostics.js";
@@ -406,6 +407,7 @@ function isRetryableInteractionContinuationInfrastructureFailure(
run.errorCode === "process_lost" ||
run.errorCode === CONTROLLER_LEASE_LOST_FAILURE_CODE ||
run.errorCode === PLUGIN_WORKER_UNAVAILABLE_CODE ||
run.errorCode === WORKSPACE_STORAGE_PENDING_CODE ||
run.errorCode === ENVIRONMENT_PROVIDER_UNAVAILABLE_CODE ||
run.errorCode === REPOSITORY_CATALOG_UNAVAILABLE_CODE ||
run.errorCode === REVIEWED_CHAT_BINDING_NOT_READY ||
@@ -1836,6 +1836,35 @@ describe.skipIf(!support.supported && !process.env.PAPERCLIP_TEST_DATABASE_URL)(
expect(f.deps.scheduleBoundedRetryForRun).toHaveBeenCalledWith(expect.objectContaining({ id: f.run.id }), f.agent);
});
// The workspace provider kept its polled preparation pending until its own
// deadline, then answered `storage_pending` before any workspace effect, as
// staging recorded while a project's storage was still provisioning.
const storagePending = () => workspaceProviderCallFailure(new JsonRpcCallError({ code: PLUGIN_RPC_ERROR_CODES.WORKER_ERROR,
message: "private provider text", data: workspaceOperationErrorData(new PluginWorkspaceOperationError("storage_pending")) }));
it.each(["fresh", "started", "retained"] as const)("routes a %s pending project 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(storagePending(), scenario === "started"));
const failed = await read(f.run.id);
expect(failed).toMatchObject({ status: "failed", errorCode: scenario === "fresh" ? "workspace_storage_pending" : "setup_failed",
error: "Project storage is still being prepared; retry the same workspace shortly" });
expect(failed.error).not.toContain("private");
if (scenario === "fresh") {
expect(failed.resultJson).toMatchObject({ executionRecovery: { kind: "bootstrap", providerWorkStarted: false },
workspaceProviderFailure: { kind: "provider", reason: "storage_pending", retryable: true } });
expect(f.deps.scheduleBoundedRetryForRun).toHaveBeenCalledWith(expect.objectContaining({ id: f.run.id }), f.agent);
} else expect(f.deps.scheduleBoundedRetryForRun).not.toHaveBeenCalled();
});
it.each(["remote_incomplete", "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)) }))));
expect(await read(f.run.id)).toMatchObject({ status: "failed", errorCode: "setup_failed" });
expect(f.deps.scheduleBoundedRetryForRun).not.toHaveBeenCalled();
});
it("keeps a found project authentication conflict a configuration gap that blocks for the board", async () => {
const f = await fixture();
const conflict = unprocessable("This agent's managed AI connection conflicts with project authentication settings in .claude/settings.json.",
@@ -31,7 +31,7 @@ import { findReusableSandboxResumeError } from "../reusable-sandbox-resume-error
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 } from "../workspace-provider-failure.js";
import { findWorkspaceProviderFailure, findWorkspaceStoragePendingFailure, WORKSPACE_STORAGE_PENDING_CODE } 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";
@@ -1720,6 +1720,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;
// 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
@@ -1747,6 +1752,7 @@ export function createHeartbeatRunCompletion(db: Db, dependencies: HeartbeatRunC
reusableSandboxResumeFailure?.code ??
remoteWorkspaceRestoreFailure?.code ??
pluginWorkerUnavailableFailure?.code ??
(workspaceStoragePending ? WORKSPACE_STORAGE_PENDING_CODE : null) ??
environmentProviderUnavailable?.code ??
repositoryCatalogUnavailable?.code ??
reviewedChatBindingNotReady?.code ??
@@ -1767,6 +1773,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;
// 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
@@ -1859,6 +1867,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 } : {}),
}, { setupFailure: true }).catch(() => ({ run: null, updated: false as const }));
let setupRetryScheduled = false;
if (!setupFailureWrite.updated) {
@@ -1945,6 +1954,7 @@ export function createHeartbeatRunCompletion(db: Db, dependencies: HeartbeatRunC
// 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)
@@ -1996,12 +2006,13 @@ export function createHeartbeatRunCompletion(db: Db, dependencies: HeartbeatRunC
);
}
// This path owned the failed-status write, which deferred the report.
const deferredReportRun = (reviewedChatBindingNotReady || sandboxResumeOutage) && setupFailureWrite.updated
const deferredReportRun = (reviewedChatBindingNotReady || sandboxResumeOutage || storagePendingRetry) && 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 } : { sandboxResumeRetry: retryDecision }) });
...(reviewedChatBindingNotReady ? { reviewedChatRetry: retryDecision }
: storagePendingRetry ? { workspaceStoragePendingRetry: 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
@@ -10,6 +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 { 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";
@@ -89,6 +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 === RUNNER_REVISION_MISMATCH_CODE || run.errorCode === ENVIRONMENT_PROVIDER_UNAVAILABLE_CODE
|| run.errorCode === REPOSITORY_CATALOG_UNAVAILABLE_CODE) &&
evidence?.kind === "bootstrap" && evidence.providerWorkStarted === false) return false;
+2 -1
View File
@@ -197,7 +197,7 @@ import {
} from "./origins.js";
import { withRecoveryContext } from "./status-only-context.js";
import { getExecutionBlocker } from "../execution-blocker.js";
import { readWorkspaceProviderFailure } from "../workspace-provider-failure.js";
import { readWorkspaceProviderFailure, 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";
@@ -655,6 +655,7 @@ const NON_RETRYABLE_CONTINUATION_ERROR_CODES = new Set<string>([
REUSABLE_SANDBOX_RESUME_FAILED_CODE,
REMOTE_WORKSPACE_RESTORE_FAILED_CODE,
PLUGIN_WORKER_UNAVAILABLE_CODE,
WORKSPACE_STORAGE_PENDING_CODE,
ENVIRONMENT_PROVIDER_UNAVAILABLE_CODE,
RUNNER_REVISION_MISMATCH_CODE,
"low_trust_isolation_unavailable",
@@ -81,6 +81,7 @@ const WORKSPACE_SCAN_NOTICES: Record<string, { title: string; nextAction: string
remote_workspace_prepare_timeout: { title: "Workspace setup timed out", nextAction: TEMPORARY_SETUP_NEXT_ACTION },
remote_workspace_restore_failed: { title: "Saved workspace could not be restored", nextAction: REMOTE_WORKSPACE_RESTORE_NEXT_ACTION },
plugin_worker_unavailable: { title: "Environment plugin was not running", nextAction: "The plugin that starts this agent's sandbox was not running, so no agent work started. Press Retry once it is running again." },
workspace_storage_pending: { title: "Project storage was still being prepared", nextAction: "The project's workspace storage was not ready yet, so no agent work started. Press Retry once the project's storage is ready." },
environment_provider_unavailable: { title: "Environment provider was temporarily unavailable", nextAction: "Paperclip kept retrying automatically for 30 minutes, but the provider was still unavailable. No agent work started. Retry the task once the provider is available." },
reusable_sandbox_resume_failed: { title: "Saved sandbox could not be resumed", nextAction: "The sandbox service did not start the saved sandbox in time. "
+ "The saved sandbox and its files were kept, and no agent work started. Paperclip tries again automatically." },
@@ -51,6 +51,11 @@ export interface RunFailureReportOptions {
* answered with an HTTP 5xx, with the same `pending` handshake.
*/
sandboxResumeRetry?: "pending" | "scheduled" | "not_scheduled";
/**
* The bounded retry decision for a workspace provider that reported project
* storage still pending before any workspace effect, with the same handshake.
*/
workspaceStoragePendingRetry?: "pending" | "scheduled" | "not_scheduled";
}
export interface RunFailureException {
+14 -1
View File
@@ -24,6 +24,7 @@ import { NATIVE_TOOL_RECEIPT_LIMIT_CODE } from "./native-runtime/native-tool-rec
import { PROJECT_ACCESS_DENIED } from "./project-access-denial.js";
import { REVIEWED_CHAT_BINDING_NOT_READY } from "./reviewed-chat-binding-diagnostics.js";
import { REUSABLE_SANDBOX_RESUME_FAILED_CODE } from "./reusable-sandbox-resume-error.js";
import { WORKSPACE_STORAGE_PENDING_CODE } from "./workspace-provider-failure.js";
import { readProviderFailure } from "@paperclipai/shared";
type HeartbeatRun = typeof heartbeatRuns.$inferSelect;
@@ -359,6 +360,16 @@ function isScheduledSandboxResumeRetry(run: HeartbeatRun, options: RunFailureRep
options.sandboxResumeRetry === "scheduled";
}
/**
* The workspace provider reported project storage still pending before any
* workspace effect, and the setup path scheduled the bounded retry of the same
* workspace. The retry owns recovery; an exhausted or unscheduled retry stays reportable.
*/
function isScheduledWorkspaceStoragePendingRetry(run: HeartbeatRun, options: RunFailureReportOptions): boolean {
return run.status === "failed" && run.errorCode === WORKSPACE_STORAGE_PENDING_CODE &&
options.workspaceStoragePendingRetry === "scheduled";
}
const providerAuthErrorCodes = new Set(["claude_auth_required", "acpx_auth_required"]);
/**
@@ -413,7 +424,8 @@ export function reportRunFailure(db: Db, run: HeartbeatRun, options: RunFailureR
// The terminal write that ends the retry reports instead (`isNewTerminalRunFailure`).
if (isPendingNativeRetry(run)) return Promise.resolve();
// The setup path reports this run again once it has decided the retry.
if (options.reviewedChatRetry === "pending" || options.sandboxResumeRetry === "pending") return Promise.resolve();
if (options.reviewedChatRetry === "pending" || options.sandboxResumeRetry === "pending"
|| options.workspaceStoragePendingRetry === "pending") return Promise.resolve();
if (mode === "unexpected" && (
isMissingSecretConfigurationBlocker(run, options) ||
isAiConnectionSelectionBlocker(run, options) ||
@@ -429,6 +441,7 @@ export function reportRunFailure(db: Db, run: HeartbeatRun, options: RunFailureR
isAcpProviderAccessFailure(run, options) ||
isScheduledReviewedChatRetry(run, options) ||
isScheduledSandboxResumeRetry(run, options) ||
isScheduledWorkspaceStoragePendingRetry(run, options) ||
isRestartInterruptedSetup(run)
)) return Promise.resolve();
const runStatus = run.status;
@@ -107,6 +107,19 @@ export function findWorkspaceProviderFailure(error: unknown): WorkspaceProviderF
return null;
}
/**
* Setup failure code for a workspace provider that reported its project storage
* still pending. The provider answers this reason before it starts any workspace
* effect, so setup retries the same workspace within the bounded bootstrap budget.
*/
export const WORKSPACE_STORAGE_PENDING_CODE = "workspace_storage_pending";
/** Find a provider's pending-storage answer through setup's error wrappers. */
export function findWorkspaceStoragePendingFailure(error: unknown): WorkspaceProviderFailureError | null {
const failure = findWorkspaceProviderFailure(error);
return failure?.kind === "provider" && failure.reason === "storage_pending" ? failure : null;
}
export type WorkspaceProviderFailureSummary = {
kind: WorkspaceProviderFailureKind;
reason: PluginWorkspaceOperationFailureReason | null;