fix(recovery): continue tasks blocked by a setup failure before provider work (#23051)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Task recovery continues interrupted work so that nobody has to press
Retry
> - A run can fail during setup before any provider work starts. For
example, the environment lease is refused because the sandbox snapshot
qualification is stale.
> - Such a run records the generic `setup_failed` code with
`executionRecovery: { kind: "bootstrap", providerWorkStarted: false }`.
Only the named transient setup codes counted as "continues
automatically", so the board escalation kept the task blocked behind a
manual Retry.
> - On staging, two review tasks stayed blocked this way for days, with
no later run.
> - This pull request makes every setup failure that ended before
provider work continue automatically, under the existing per-task
allowance and the company-wide automatic run brake.
> - The benefit is that a task that never started does not need a
person. Tasks already blocked this way continue after deploy.

## Linked Issues or Issue Description

**What happened?**
Two review tasks on staging failed in their first run with
`setup_failed` ("Failed to acquire lease for environment ...
sandbox_snapshot_qualification_required"). No provider work started.
Each task stayed `blocked` with a system-owned failed interruption and
`canRetry: true`. No automatic continuation followed.

**Expected behavior**
A system-owned setup failure before provider work continues
automatically with bounded backoff. The needed-retry rate is 0%.

**Steps to reproduce**
1. A task's first run fails in setup before dispatch with the generic
`setup_failed` code (for example, a refused environment lease).
2. Generic continuation recovery escalates the task to a board-owned
stranded hold and blocks it.
3. The assigned-work sweep leaves the task to the hold owner
(`left_to_hold_owner`), because `continuesAutomatically` accepted only
the named transient setup codes.

## What Changed

- `continuation-cause.ts`: add `isSetupFailureBeforeProviderWork` and
its SQL twin `setupFailureBeforeProviderWorkSql`. Each matches any
`SETUP_FAILURE_CODES` value, including `setup_failed`, when the run
recorded bootstrap with `providerWorkStarted: false`.
`continuesAutomatically` and `continuesAutomaticallySql` use them for
first-run failures.
- `stranded-hold-continuation.ts`: a stranded hold from such a failure
stays eligible for 7 days (`STRANDED_PRE_PROVIDER_SETUP_MAX_AGE_MS`, the
same as the sweep's `STALE_BLOCK_MS`). Other causes keep the 24-hour
window. Tasks blocked before this release are continued after deploy
without a Retry.
- `assigned-work-sweep.ts`: the suspect pre-filter uses the same longer
window for this failure class.
- Repetition stays bounded by existing mechanisms: the per-task
`continuationAllowance` (2, 4, 8, then 15-minute spacing, at most 6 an
hour), the process-wide repair budget, and the company-wide automatic
run brake. The brake already counts `providerWorkStarted=false` failures
as `failed_before_starting`.

## Verification

- New red/green test in
`server/src/__tests__/assigned-work-invariant.test.ts`: "continues a
task blocked by an environment setup failure before any provider work,
including one blocked days ago". It failed before the fix (the task was
not a sweep suspect). It passes after the fix. A task blocked 40 hours
ago is continued once, and the hold resolves as restored. Work that may
have started, or a run without the bootstrap record, stays with the hold
owner. A block older than 7 days is not touched.
- The existing "temporary setup failure" case now uses an 8-day-old
block for its "old" control, because pre-provider setup failures are now
eligible for 7 days.
- `npx vitest run src/__tests__/assigned-work-invariant.test.ts`: 34/34
pass.
- Related suites: fresh-continuation-fallback, run-completion,
task-retry, task-interruption-presentation, retries, dot-runner,
issue-recovery-actions, recovery-observability,
released-writer-escalation, github retry/recovery integration, and
others. 920 tests pass. Locally, `run-completion.test.ts` reports only
an `afterAll` embedded-Postgres teardown timeout. All of its 263 tests
pass.
- `tsc --noEmit` for `server` passes.

## Risks

- A generic `setup_failed` that is really deterministic is now retried
automatically. The per-task allowance (at most 6 an hour, with backoff)
and the company-wide brake bound this. These are the same bounds that
recovery runs failing with `setup_failed` already use. Person-owned
causes have their own codes and are not affected.
- After deploy, blocked tasks from the last 7 days that match this class
are continued. The process-wide repair budget and the brake pace them.
- The stranded notice text for `setup_failed` still mentions Retry. The
sweep continues the task within the settling grace, and its activity
says that no Retry is needed.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude
Code with tool use (shell, file edits, test execution).

## 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: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
DottaandClaude Opus 5.5 authored and GitHub committed 2026-11-26 13:57:19 +00:00
1 parent 880b0c3a7c
commit 4bf6a50e9d
4 files changed
+95 -12

No files matched your search

@@ -232,7 +232,8 @@ describePostgres("assigned-work invariant sweep", () => {
return { issueId, hold };
}
const recent = await escalated({ endedAgoMs: 2 * HOUR, cause: "transport_timeout" });
const old = await escalated({ endedAgoMs: 30 * HOUR, cause: "transport_timeout" });
// No provider work started, so it stays eligible for the sweep's week, not the 24-hour window.
const old = await escalated({ endedAgoMs: 8 * 24 * HOUR, cause: "transport_timeout" });
const lasting = await escalated({ endedAgoMs: 2 * HOUR, cause: "provider_access_denied" });
const queue = wakeQueue();
const recovery = recoveryService(db, { enqueueWakeup: queue.enqueueWakeup });
@@ -247,7 +248,57 @@ describePostgres("assigned-work invariant sweep", () => {
expect((await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, recent.hold.id)))[0])
.toMatchObject({ status: "resolved", outcome: "restored", ownerType: "system", resolutionNote: "stranded_transient_continued" });
for (const left of [old, lasting]) {
for (const [left, outcome] of [[old, "stale_reported"], [lasting, "left_to_hold_owner"]] as const) {
expect(await recovery.assignedWork.checkIssue({ companyId: f.companyId, issueId: left.issueId }))
.toMatchObject({ outcome });
expect((await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, left.hold.id)))[0].status).toBe("active");
}
expect(queue.calls).toHaveLength(1);
}, 60_000);
it("continues a task blocked by an environment setup failure before any provider work, including one blocked days ago", async () => {
const f = await seedCompany();
const qualification = 'Failed to acquire lease for environment "Paperclip Sandbox" (sandbox): sandbox_snapshot_qualification_required: '
+ "The snapshot qualification is missing or stale.";
async function escalated(input: { endedAgoMs: number; executionRecovery: Record<string, unknown> | null }) {
const blockedAt = new Date(Date.now() - input.endedAgoMs + 1_000);
const issueId = await f.issue({ status: "blocked", blockedTransitionAt: blockedAt, updatedAt: blockedAt });
const run = await f.run(issueId, { status: "failed", errorCode: "setup_failed", livenessState: "failed", error: qualification,
resultJson: { failureCause: "lease_acquire_failed", ...(input.executionRecovery ? { executionRecovery: input.executionRecovery } : {}) },
startedAt: new Date(Date.now() - input.endedAgoMs - 60_000), finishedAt: new Date(Date.now() - input.endedAgoMs),
createdAt: new Date(Date.now() - input.endedAgoMs - 60_000) });
const [hold] = await db.insert(issueRecoveryActions).values({ companyId: f.companyId, sourceIssueId: issueId,
kind: "stranded_assigned_issue", status: "active", ownerType: "board", cause: "stranded_assigned_issue",
fingerprint: `source_scoped_recovery:${f.companyId}:${issueId}:stranded_assigned_issue`,
evidence: { previousStatus: "todo", latestRunId: run.id, latestRunErrorCode: "setup_failed",
routingPolicy: "board_escalation_no_takeover_v1" },
nextAction: "Board operator: inspect the evidence, repair the runtime if appropriate.", attemptCount: 1 }).returning();
await db.insert(activityLog).values({ companyId: f.companyId, actorType: "system", actorId: "system", action: "issue.updated",
entityType: "issue", entityId: issueId, details: { status: "blocked", previousStatus: "todo",
source: "recovery.reconcile_stranded_assigned_issue" }, createdAt: blockedAt });
return { issueId, hold };
}
const beforeWork = { kind: "bootstrap", providerWorkStarted: false };
// Blocked about two days before the deploy that carries this repair.
const blockedDaysAgo = await escalated({ endedAgoMs: 40 * HOUR, executionRecovery: beforeWork });
const workStarted = await escalated({ endedAgoMs: 2 * HOUR, executionRecovery: { kind: "bootstrap", providerWorkStarted: true } });
const unproven = await escalated({ endedAgoMs: 2 * HOUR, executionRecovery: null });
const tooOld = await escalated({ endedAgoMs: 8 * 24 * HOUR, executionRecovery: beforeWork });
const queue = wakeQueue();
const recovery = recoveryService(db, { enqueueWakeup: queue.enqueueWakeup });
const suspects = (await recovery.assignedWork.listSuspects({ companyId: f.companyId }, null, 100)).map(row => row.id);
expect(suspects).toContain(blockedDaysAgo.issueId);
expect(suspects).not.toContain(tooOld.issueId);
expect(await recovery.assignedWork.checkIssue({ companyId: f.companyId, issueId: blockedDaysAgo.issueId }))
.toMatchObject({ outcome: "repaired", verdict: { reason: "recovery_block" } });
expect(queue.calls).toEqual([{ agentId: f.agentId, issueId: blockedDaysAgo.issueId, source: "issue.assigned_work_invariant" }]);
expect((await db.select().from(issues).where(eq(issues.id, blockedDaysAgo.issueId)))[0].status).toBe("todo");
expect((await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, blockedDaysAgo.hold.id)))[0])
.toMatchObject({ status: "resolved", outcome: "restored", ownerType: "system" });
// Work that may have started, or a run that never recorded it had not, keeps its owner's decision.
for (const left of [workStarted, unproven]) {
expect(await recovery.assignedWork.checkIssue({ companyId: f.companyId, issueId: left.issueId }))
.toMatchObject({ outcome: "left_to_hold_owner" });
expect((await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, left.hold.id)))[0].status).toBe("active");