mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-29 15:52:36 +01:00
fix(recovery): continue blocked chat tasks whose run failed before provider work (#23059)
## 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 <noreply@anthropic.com>
This commit is contained in:
1 parent
4ea6fa61d5
commit
4a9ecd3aca
2 files changed
+94
-5
No files matched your search
@@ -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<typeof issues.$inferSelect, "id" | "companyId" | "status" |
|
||||
| "blockedTransitionAt" | "updatedAt" | "unblockDescriptor" | "monitorNextCheckAt" | "conversationAgentId" | "originKind"
|
||||
| "projectId" | "statusVersion" | "executionState" | "identifier" | "createdAt" | "blockedOwnerNotifiedAt">;
|
||||
|
||||
/** TS twin of `latestRunFailedBeforeProviderWork` for the loaded facts. */
|
||||
function chatFailedBeforeProviderWork(latest: RunRow | null, issue: Pick<IssueRow, "assigneeAgentId">, 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<typeof heartbeatRuns.$inferSelect, "id" | "status" | "agentId" | "runtimeMode" | "errorCode" | "finishedAt"
|
||||
| "scheduledRetryAt" | "controllerBootId" | "controllerLeaseExpiresAt" | "controllerProcess" | "resultJson"> & { 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;
|
||||
|
||||
Reference in new issue
Block a user