From 4a9ecd3aca1a47b08d5d0555ebd2eda17d99fc4d Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Thu, 26 Nov 2026 17:05:39 +0000 Subject: [PATCH] fix(recovery): continue blocked chat tasks whose run failed before provider work (#23059) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The assigned-work sweep continues open agent tasks that have nothing running and do not wait on a person > - #23051 made a setup failure before provider work continue automatically. Two review tasks on staging stayed blocked after it was deployed. > - Both tasks come from a chat channel (GitHub review bots). The sweep treats every chat-channel task as "waiting on a person's next message". It leaves these tasks out of its suspect list and gives them the `conversation` waiting reason. > - The agent never got the message, because its only run failed in setup before provider work. So the task waits on the system, not on a person. > - This pull request lets the sweep judge a blocked chat-channel task like any other task when its latest run failed in setup before provider work. > - The benefit is that these review tasks continue without a Retry, and so do the two tasks on staging. ## Linked Issues or Issue Description Refs #23051 **What happened?** After #23051 was deployed to staging, two GitHub review tasks stayed `blocked` with no new run. The sweeps ran, and other blocked tasks were continued. Each task's only run was legacy, failed with `setup_failed` during environment lease acquisition, and recorded `executionRecovery: { kind: "bootstrap", providerWorkStarted: false }` about 43 hours earlier. The tasks have `originKind: "chat_channel"`. **Expected behavior** The sweep continues a blocked task whose run failed before provider work, with bounded backoff, also when the task comes from a chat channel. **Steps to reproduce** 1. Create a chat-channel task assigned to an agent. Its only run fails with `setup_failed` before provider work. Block the task, with or without a board recovery hold. 2. Run the assigned-work sweep. 3. Before this change, `listSuspects` does not return the task. `evaluateAssignedWork` returns `waiting: conversation`, and no continuation is queued. ## What Changed - `server/src/services/recovery/assigned-work-sweep.ts`: - The suspect pre-filter still leaves chat-channel tasks out, except a blocked one whose latest run (by its assignee) failed in setup before provider work within the last 7 days (`latestRunFailedBeforeProviderWork`). - The facts loader no longer marks such a task as a conversation (`chatFailedBeforeProviderWork`, the TS twin). The latest-run read now also carries `executionRecovery`. - Agent chat conversations (`conversationAgentId`) are unchanged. Chat tasks whose agent may have started work still wait for their conversation. - Retry limits do not change. The per-task continuation allowance, the process-wide repair budget, and the company-wide automatic run brake apply as for every other sweep continuation. ## Verification - New red/green test in `server/src/__tests__/assigned-work-invariant.test.ts`: "continues a chat-channel task blocked by a legacy setup failure before provider work, with or without a hold". It uses the staging run shape: legacy, `setup_failed`, the same `resultJson` keys, the only run, about 43 hours old. Before the fix it failed (the tasks were not sweep suspects). After the fix, both the held task and the unheld task are continued. A chat task whose provider work may have started still waits (`conversation`), and an in-progress chat task is not a suspect. - In the same test, with the real heartbeat wake queue, the continuation of a held chat task is admitted as a new `issue_continuation_needed` run. - `npx vitest run src/__tests__/assigned-work-invariant.test.ts`: 35/35 pass. - `tsc --noEmit` for `server` passes. ## Risks - The sweep now acts on some chat-channel tasks. The scope is narrow: the task is blocked, its latest run is its assignee's and failed in setup before provider work, and the run ended in the last 7 days. Retries stay bounded by the existing per-task allowance and the company-wide brake. - After deploy, chat tasks blocked this way in the last 7 days are continued. The repair budget and the brake pace them. ## 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 --- .../__tests__/assigned-work-invariant.test.ts | 67 +++++++++++++++++++ .../services/recovery/assigned-work-sweep.ts | 32 +++++++-- 2 files changed, 94 insertions(+), 5 deletions(-) diff --git a/server/src/__tests__/assigned-work-invariant.test.ts b/server/src/__tests__/assigned-work-invariant.test.ts index 398afef8c42..12fec20f5c1 100644 --- a/server/src/__tests__/assigned-work-invariant.test.ts +++ b/server/src/__tests__/assigned-work-invariant.test.ts @@ -306,6 +306,73 @@ describePostgres("assigned-work invariant sweep", () => { expect(queue.calls).toHaveLength(1); }, 60_000); + it("continues a chat-channel task blocked by a legacy setup failure before provider work, with or without a hold", 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."; + // The shape two GitHub review tasks on staging were left in: the task's only + // run, legacy, failed in setup about 43 hours earlier, before provider work. + async function blockedReviewTask(input: { hold: boolean; providerWorkStarted?: boolean; endedAgoMs?: number }) { + const endedAgoMs = input.endedAgoMs ?? 43 * HOUR; + const blockedAt = new Date(Date.now() - endedAgoMs + 1_000); + const issueId = await f.issue({ status: "blocked", originKind: "chat_channel", responsibleUserId: "owner-user", blockedTransitionAt: blockedAt, updatedAt: blockedAt }); + const run = await f.run(issueId, { status: "failed", runtimeMode: "legacy", errorCode: "setup_failed", livenessState: "failed", + error: qualification, resultJson: { stopReason: "adapter_failed", failureCause: "lease_acquire_failed", timeoutFired: false, + timeoutSource: null, timeoutConfigured: false, effectiveTimeoutSec: 0, + executionRecovery: { kind: "bootstrap", providerWorkStarted: input.providerWorkStarted ?? false } }, + startedAt: new Date(Date.now() - endedAgoMs - 60_000), finishedAt: new Date(Date.now() - endedAgoMs), + createdAt: new Date(Date.now() - endedAgoMs - 60_000) }); + if (input.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 }); + } + 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; + } + const held = await blockedReviewTask({ hold: true }); + const unheld = await blockedReviewTask({ hold: false }); + const workStarted = await blockedReviewTask({ hold: false, providerWorkStarted: true }); + const waitingForMessage = await f.issue({ status: "in_progress", originKind: "chat_channel" }); + 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).toEqual(expect.arrayContaining([held, unheld])); + expect(suspects).not.toContain(workStarted); + expect(suspects).not.toContain(waitingForMessage); + + for (const issueId of [held, unheld]) { + expect(await recovery.assignedWork.checkIssue({ companyId: f.companyId, issueId })) + .toMatchObject({ outcome: "repaired", verdict: { reason: "recovery_block" } }); + expect((await db.select().from(issues).where(eq(issues.id, issueId)))[0].status).not.toBe("blocked"); + } + expect(queue.calls.map(call => call.issueId).sort()).toEqual([held, unheld].sort()); + // A chat task whose agent may have started work still waits for its conversation. + expect(await recovery.assignedWork.checkIssue({ companyId: f.companyId, issueId: workStarted })) + .toMatchObject({ outcome: "ok", verdict: { clause: "waiting", reason: "conversation" } }); + expect(queue.calls).toHaveLength(2); + + // With the real wake queue, the continuation of such a chat task is admitted as a new run. + const real = await blockedReviewTask({ hold: true }); + const heartbeat = heartbeatService(db); + try { + expect(await heartbeat.checkAssignedWorkInvariant({ companyId: f.companyId, issueId: real })) + .toMatchObject({ outcome: "repaired" }); + const runs = await db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, f.companyId), + sqlTag`${heartbeatRuns.contextSnapshot}->>'issueId' = ${real}`)); + expect(runs).toHaveLength(2); + expect(runs.find(row => row.errorCode !== "setup_failed")?.contextSnapshot) + .toMatchObject({ wakeReason: "issue_continuation_needed", issueId: real }); + } finally { + await heartbeat.drainActiveRunExecutions(); + } + }, 120_000); + it("leaves a task blocked under an active recovery hold to the hold's owner and reports it", async () => { const f = await seedCompany(); const issueId = await f.issue({ status: "blocked", blockedTransitionAt: new Date(Date.now() - 2 * HOUR) }); diff --git a/server/src/services/recovery/assigned-work-sweep.ts b/server/src/services/recovery/assigned-work-sweep.ts index 4c8a61b77d2..f96dd78a446 100644 --- a/server/src/services/recovery/assigned-work-sweep.ts +++ b/server/src/services/recovery/assigned-work-sweep.ts @@ -42,7 +42,7 @@ import { automaticRunCreationHeldUntil, readAutomaticWorkStatus, reserveAutomati import { isReattachPhaseActive, reattachPhaseRecheckAt } from "../heartbeat/run-admission.js"; import { wakeBecameFreshContinuation } from "./wake-became-fresh-continuation.js"; import { continueSweepTaskFromSavedWork } from "./sweep-saved-work-continuation.js"; -import { setupFailureBeforeProviderWorkSql } from "../continuation-cause.js"; +import { isSetupFailureBeforeProviderWork, setupFailureBeforeProviderWorkSql } from "../continuation-cause.js"; import { STRANDED_CONTINUATION_MAX_AGE_MS, STRANDED_KIND, STRANDED_PRE_PROVIDER_SETUP_MAX_AGE_MS, strandedHoldContinuesAutomatically, type StrandedHoldRun } from "./stranded-hold-continuation.js"; import { @@ -91,6 +91,13 @@ type IssueRow = Pick; +/** TS twin of `latestRunFailedBeforeProviderWork` for the loaded facts. */ +function chatFailedBeforeProviderWork(latest: RunRow | null, issue: Pick, at: Date): boolean { + if (!latest || latest.status !== "failed" || latest.agentId !== issue.assigneeAgentId || !latest.finishedAt) return false; + if (at.getTime() - new Date(latest.finishedAt).getTime() > STRANDED_PRE_PROVIDER_SETUP_MAX_AGE_MS) return false; + return isSetupFailureBeforeProviderWork({ errorCode: latest.errorCode, resultJson: latest.resultJson }); +} + type RunRow = Pick & { issueId: string }; @@ -223,7 +230,8 @@ export function assignedWorkSweep(db: Db, deps: AssignedWorkDeps) { r.finished_at as "finishedAt", r.scheduled_retry_at as "scheduledRetryAt", r.controller_boot_id as "controllerBootId", r.controller_lease_expires_at as "controllerLeaseExpiresAt", r.controller_process as "controllerProcess", - jsonb_build_object('cancelledByActorType', r.result_json->'cancelledByActorType') as "resultJson" + jsonb_build_object('cancelledByActorType', r.result_json->'cancelledByActorType', + 'executionRecovery', r.result_json->'executionRecovery') as "resultJson" from heartbeat_runs r where r.company_id = ${companyId} and (r.context_snapshot->>'issueId') = requested.id order by r.created_at desc limit 1 @@ -431,7 +439,8 @@ export function assignedWorkSweep(db: Db, deps: AssignedWorkDeps) { createdAt: issue.createdAt, unblockOwner: (issue.unblockDescriptor?.owner ?? null) as AssignedWorkFacts["issue"]["unblockOwner"], monitorNextCheckAt: issue.monitorNextCheckAt, - isConversation: Boolean(issue.conversationAgentId) || issue.originKind === "chat_channel", + isConversation: Boolean(issue.conversationAgentId) + || (issue.originKind === "chat_channel" && !(issue.status === "blocked" && chatFailedBeforeProviderWork(latest, issue, at))), awaitingFirstMessage: onboardingIds.has(issue.id), }, activeRuns: ownedRuns, @@ -498,9 +507,21 @@ export function assignedWorkSweep(db: Db, deps: AssignedWorkDeps) { * The cheap, indexed pre-filter the sweep reconstructs from: open assigned * tasks with no run that is plainly live, no pending wake and no pending * question. Everything it lets through is judged by the full predicate. - * Chat conversations and blocks older than the stale window are left out: + * Chat conversations (except a blocked chat task whose run failed before + * provider work) and blocks older than the stale window are left out: * the first wait on a person's message, the second is only reported. */ + /** A chat task whose latest run, its assignee's, failed in setup before any + * provider work: the agent never received the message, so the task waits on + * the system, not on the person's next message. */ + function latestRunFailedBeforeProviderWork(at: Date) { + return sql`coalesce((select lr.status = 'failed' and lr.agent_id = ${issues.assigneeAgentId} + and lr.finished_at > ${new Date(at.getTime() - STRANDED_PRE_PROVIDER_SETUP_MAX_AGE_MS).toISOString()}::timestamptz + and ${setupFailureBeforeProviderWorkSql("lr")} + from heartbeat_runs lr where lr.company_id = ${issues.companyId} and (lr.context_snapshot->>'issueId') = ${issues.id}::text + order by lr.created_at desc limit 1), false)`; + } + function latestRunRefusedAtDispatch(at: Date) { return sql`coalesce((select lr.status = 'cancelled' and lr.started_at is null and lr.error_code = 'execution_reconciliation_required' and lr.finished_at > ${new Date(at.getTime() - STRANDED_CONTINUATION_MAX_AGE_MS).toISOString()}::timestamptz @@ -535,7 +556,8 @@ export function assignedWorkSweep(db: Db, deps: AssignedWorkDeps) { isNull(issues.assigneeUserId), isNull(issues.hiddenAt), isNull(issues.conversationAgentId), - sql`coalesce(${issues.originKind}, '') <> 'chat_channel'`, + sql`(coalesce(${issues.originKind}, '') <> 'chat_channel' + or (${issues.status} = 'blocked' and ${latestRunFailedBeforeProviderWork(at)}))`, sql`(${issues.status} <> 'blocked' or coalesce(${issues.blockedTransitionAt}, ${issues.updatedAt}) > ${new Date(at.getTime() - STALE_BLOCK_MS).toISOString()}::timestamptz)`, sql`(${issues.monitorNextCheckAt} is null or ${issues.monitorNextCheckAt} <= ${at.toISOString()}::timestamptz)`, // A legacy run whose controller lease lapsed may have lost its owner;