mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-01 09:39:53 +01:00
fix(recovery): stop re-waking a blocked task whose dependency runs keep failing (#22818)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - A blocked task waits on other tasks. When all its blockers are done, Paperclip wakes the assignee. A periodic backstop does this when the normal event is missed. > - The backstop deduplicates wakes with a key that includes the blocked cycle (`blockedTransitionAt`). > - A woken run that fails can leave the task blocked again. That starts a new cycle, so the next sweep sees a new key and wakes the task again. > - When the failure is deterministic, this never stops. One hosted task ran more than 11,000 failed runs in five days, about one every 20 seconds. > - This pull request adds a circuit breaker to the backstop: after each failed attempt, the next dependency wake waits longer (1m, 5m, 25m, ... up to 24h). > - The benefit is that a setup failure can no longer become thousands of automatic runs. ## Linked Issues or Issue Description **What happened?** A blocked task had all blockers done. The issue graph liveness backstop woke its agent with `issue_blockers_resolved`. Each run failed in setup (`durable_prp_canonical_json_too_large`). The task returned to `blocked` with a new `blockedTransitionAt`. The backstop then emitted another wake with a new idempotency key. The activity log of the task had 11,215 `issue.blockers_resolved_wake_emitted` rows, each with a different key, and 11,621 failed runs. **Expected behavior** A wake that did not help is not repeated without limit. Paperclip waits longer after each failure, and then probes again. A newer blocker result, an edit of the blocker set, or a run that does not fail starts a fresh attempt. **Steps to reproduce** 1. Create a blocked task with one done blocker and an agent assignee. 2. Record three `issue_blockers_resolved` wakes for the task, each with a failed run and a different blocked-cycle key. 3. Run `reconcileResolvedDependencyWakes()`. 4. Before this change, the backstop emits a fourth wake. Refs #22705, #22707 (the underlying setup size failure and its retry classification). Those changes stop scheduled retries for that one error. The backstop loop is a separate path and accepts any failure class, so it needs its own breaker. ## What Changed - New `server/src/services/recovery/dependency-wake-circuit-breaker.ts`. It reads this agent's terminal runs on the task (any wake reason), newest first. It reads runs through `heartbeat_runs.issue_id` (indexed). It counts consecutive `failed` or `timed_out` runs that finished after the latest blocker change: blocker completion, succeeded workspace finalize, an added blocker relation, or an `issue.blockers_updated` edit. Each run counts once. A run that did not fail ends the streak. `interrupted` runs (restart, deploy) are neutral. - The wait before the next dependency wake is 1 minute after one failure, then multiplied by 5 per failure, capped at 24 hours. After the wait, one wake probes again, so a fix that ships later is picked up. - `reconcileResolvedDependencyWakeBackstop` calls the breaker before it enqueues a wake. A skipped wake reports its retry time through `onDeferredDeadline`. New counter: `failedWakeBackoffSkipped`. When a task has three or more consecutive failures, the sweep logs one warning with the task ids. - Tests: backstop regressions (production shape, backoff elapsed, reset by a later successful run, reset by a newer blocker result, reset by a blocker-set edit) and unit tests for the policy (duplicate receipts, interrupted runs, capped probe). ## Verification - `cd server && npx vitest run src/__tests__/heartbeat-issue-liveness-escalation.test.ts src/services/recovery/dependency-wake-circuit-breaker.test.ts src/services/workspace-recovery-dependency-finalize.test.ts src/__tests__/issue-blocker-stall-wakeups.test.ts`: all pass. - Red/green: with the backstop hook reverted, the production-shape test fails (`expected 1 to be 0`: the backstop wakes the task again). With the hook, it passes. - Existing backstop tests (self-blocked, same-cycle dedup, blocker completion) still pass. ## Risks - A task whose dependency runs keep failing is woken less often, at most once a day after about six failures. The failed run still shows its own error and action. Before this change the same task ran without limit. - The breaker adds one run read per candidate that passes all earlier checks (four small aggregate reads more only when a recent run failed). It does not run for tasks that are not ready or already have a wake. - No schema change. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude Code with tool use (shell, browser, file edits). ## 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: Paperclip <noreply@paperclip.ing> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
4 files changed
+428
No files matched your search
@@ -1314,6 +1314,174 @@ describeEmbeddedPostgres("heartbeat resolved dependency wake reconciliation", ()
|
||||
expect(result.existingWakeSkipped).toBe(1);
|
||||
});
|
||||
|
||||
async function seedFailedDependencyWakes(input: {
|
||||
companyId: string;
|
||||
agentId: string;
|
||||
blockedIssueId: string;
|
||||
blockerIssueId: string;
|
||||
count: number;
|
||||
lastFinishedAt: Date;
|
||||
contextOnly?: boolean;
|
||||
}) {
|
||||
// Production shape: the blocker finished long ago, then each woken run failed
|
||||
// and left the task blocked in a new cycle, so every wake carries a different
|
||||
// cycle-aware idempotency key.
|
||||
const blockerChangedAt = new Date(input.lastFinishedAt.getTime() - 60 * 60_000);
|
||||
await db.update(issues).set({ status: "done", completedAt: blockerChangedAt })
|
||||
.where(eq(issues.id, input.blockerIssueId));
|
||||
await db.update(issueRelations).set({ createdAt: blockerChangedAt })
|
||||
.where(eq(issueRelations.relatedIssueId, input.blockedIssueId));
|
||||
for (let index = input.count - 1; index >= 0; index -= 1) {
|
||||
const finishedAt = new Date(input.lastFinishedAt.getTime() - index * 20_000);
|
||||
const requestedAt = new Date(finishedAt.getTime() - 15_000);
|
||||
const [run] = await db.insert(heartbeatRuns).values({
|
||||
companyId: input.companyId,
|
||||
agentId: input.agentId,
|
||||
// Promoted wakes bind the task only in the context snapshot.
|
||||
issueId: input.contextOnly ? null : input.blockedIssueId,
|
||||
status: "failed",
|
||||
errorCode: "native_session_interrupted",
|
||||
startedAt: requestedAt,
|
||||
finishedAt,
|
||||
contextSnapshot: { issueId: input.blockedIssueId, wakeReason: "issue_blockers_resolved" },
|
||||
}).returning();
|
||||
await db.insert(agentWakeupRequests).values({
|
||||
companyId: input.companyId,
|
||||
agentId: input.agentId,
|
||||
source: "automation",
|
||||
triggerDetail: "system",
|
||||
reason: "issue_blockers_resolved",
|
||||
payload: {
|
||||
issueId: input.blockedIssueId,
|
||||
resolvedBlockerIssueId: input.blockerIssueId,
|
||||
blockerIssueIds: [input.blockerIssueId],
|
||||
},
|
||||
status: "completed",
|
||||
runId: run.id,
|
||||
requestedAt,
|
||||
finishedAt,
|
||||
idempotencyKey: buildIssueBlockersResolvedWakeStateKey({
|
||||
dependentIssueId: input.blockedIssueId,
|
||||
blockerIssueIds: [input.blockerIssueId],
|
||||
blockedTransitionAt: new Date(requestedAt.getTime() - 1_000),
|
||||
}),
|
||||
});
|
||||
}
|
||||
await db.update(issues).set({ blockedTransitionAt: new Date(input.lastFinishedAt.getTime() + 1_000) })
|
||||
.where(eq(issues.id, input.blockedIssueId));
|
||||
}
|
||||
|
||||
async function countDependencyWakes(companyId: string) {
|
||||
const rows = await db.select({ id: agentWakeupRequests.id }).from(agentWakeupRequests)
|
||||
.where(and(eq(agentWakeupRequests.companyId, companyId), eq(agentWakeupRequests.reason, "issue_blockers_resolved")));
|
||||
return rows.length;
|
||||
}
|
||||
|
||||
it("backs off re-waking a blocked task whose resolved-dependency runs keep failing", async () => {
|
||||
const fixture = await seedResolvedDependencyBackstopFixture({ workspaceState: "none" });
|
||||
await seedFailedDependencyWakes({ ...fixture, count: 3, lastFinishedAt: new Date(Date.now() - 30_000) });
|
||||
const deadlines: number[] = [];
|
||||
|
||||
const result = await heartbeatService(db).reconcileResolvedDependencyWakes({
|
||||
issueId: fixture.blockedIssueId, onDeferredDeadline: (at: number) => deadlines.push(at),
|
||||
});
|
||||
|
||||
expect(result.healed).toBe(0);
|
||||
expect(result.failedWakeBackoffSkipped).toBe(1);
|
||||
expect(result.repeatedFailureIssueIds).toEqual([fixture.blockedIssueId]);
|
||||
expect(deadlines).toHaveLength(1);
|
||||
expect(deadlines[0]).toBeGreaterThan(Date.now() + 20 * 60_000);
|
||||
expect(await countDependencyWakes(fixture.companyId)).toBe(3);
|
||||
});
|
||||
|
||||
it("counts failed runs bound to the task only through their context", async () => {
|
||||
const fixture = await seedResolvedDependencyBackstopFixture({ workspaceState: "none" });
|
||||
await seedFailedDependencyWakes({ ...fixture, count: 2, lastFinishedAt: new Date(Date.now() - 30_000), contextOnly: true });
|
||||
|
||||
const result = await heartbeatService(db).reconcileResolvedDependencyWakes({ issueId: fixture.blockedIssueId });
|
||||
|
||||
expect(result.healed).toBe(0);
|
||||
expect(result.failedWakeBackoffSkipped).toBe(1);
|
||||
});
|
||||
|
||||
it("wakes again once the failure backoff has passed", async () => {
|
||||
const fixture = await seedResolvedDependencyBackstopFixture({ workspaceState: "none" });
|
||||
await seedFailedDependencyWakes({ ...fixture, count: 1, lastFinishedAt: new Date(Date.now() - 10 * 60_000) });
|
||||
|
||||
const result = await heartbeatService(db).reconcileResolvedDependencyWakes({ issueId: fixture.blockedIssueId });
|
||||
|
||||
expect(result.healed).toBe(1);
|
||||
});
|
||||
|
||||
it("resets the failure backoff after a later successful run on the task", async () => {
|
||||
const fixture = await seedResolvedDependencyBackstopFixture({ workspaceState: "none" });
|
||||
await seedFailedDependencyWakes({ ...fixture, count: 3, lastFinishedAt: new Date(Date.now() - 60_000) });
|
||||
await db.insert(heartbeatRuns).values({
|
||||
companyId: fixture.companyId, agentId: fixture.agentId, issueId: fixture.blockedIssueId, status: "succeeded",
|
||||
startedAt: new Date(Date.now() - 30_000), finishedAt: new Date(Date.now() - 20_000),
|
||||
contextSnapshot: { issueId: fixture.blockedIssueId, wakeReason: "issue_assigned" },
|
||||
});
|
||||
|
||||
const result = await heartbeatService(db).reconcileResolvedDependencyWakes({ issueId: fixture.blockedIssueId });
|
||||
|
||||
expect(result.healed).toBe(1);
|
||||
});
|
||||
|
||||
it("resets the failure backoff when the blocker set is edited", async () => {
|
||||
const fixture = await seedResolvedDependencyBackstopFixture({ workspaceState: "none" });
|
||||
await seedFailedDependencyWakes({ ...fixture, count: 3, lastFinishedAt: new Date(Date.now() - 60_000) });
|
||||
await db.insert(activityLog).values({
|
||||
companyId: fixture.companyId, actorType: "user", actorId: "board-user", action: "issue.blockers_updated",
|
||||
entityType: "issue", entityId: fixture.blockedIssueId,
|
||||
details: { blockedByIssueIds: [fixture.blockerIssueId], removedBlockedByIssueIds: [randomUUID()] },
|
||||
createdAt: new Date(Date.now() - 10_000),
|
||||
});
|
||||
|
||||
const result = await heartbeatService(db).reconcileResolvedDependencyWakes({ issueId: fixture.blockedIssueId });
|
||||
|
||||
expect(result.healed).toBe(1);
|
||||
});
|
||||
|
||||
it("resets the failure backoff when a blocker finalizes newer work", async () => {
|
||||
const fixture = await seedResolvedDependencyBackstopFixture({ workspaceState: "finalized" });
|
||||
await seedFailedDependencyWakes({ ...fixture, count: 3, lastFinishedAt: new Date(Date.now() - 60_000) });
|
||||
await db.update(workspaceOperations).set({ finishedAt: new Date(Date.now() - 2 * 60 * 60_000) })
|
||||
.where(eq(workspaceOperations.issueId, fixture.blockerIssueId));
|
||||
await db.insert(workspaceOperations).values({
|
||||
companyId: fixture.companyId, executionWorkspaceId: fixture.executionWorkspaceId, issueId: fixture.blockerIssueId,
|
||||
phase: "workspace_finalize", status: "succeeded", startedAt: new Date(Date.now() - 20_000),
|
||||
finishedAt: new Date(Date.now() - 10_000),
|
||||
});
|
||||
|
||||
const result = await heartbeatService(db).reconcileResolvedDependencyWakes({ issueId: fixture.blockedIssueId });
|
||||
|
||||
expect(result.healed).toBe(1);
|
||||
});
|
||||
|
||||
it("resets the failure backoff when workspace recovery saves newer blocker work", async () => {
|
||||
const fixture = await seedResolvedDependencyBackstopFixture({ workspaceState: "none" });
|
||||
await seedFailedDependencyWakes({ ...fixture, count: 3, lastFinishedAt: new Date(Date.now() - 60_000) });
|
||||
await db.insert(workspaceOperations).values({
|
||||
companyId: fixture.companyId, executionWorkspaceId: null, issueId: fixture.blockerIssueId,
|
||||
phase: "workspace_finalize", status: "succeeded", metadata: { owningService: "workspace_recovery" },
|
||||
startedAt: new Date(Date.now() - 20_000), finishedAt: new Date(Date.now() - 10_000),
|
||||
});
|
||||
|
||||
const result = await heartbeatService(db).reconcileResolvedDependencyWakes({ issueId: fixture.blockedIssueId });
|
||||
|
||||
expect(result.healed).toBe(1);
|
||||
});
|
||||
|
||||
it("resets the failure backoff when a blocker produces a newer result", async () => {
|
||||
const fixture = await seedResolvedDependencyBackstopFixture({ workspaceState: "none" });
|
||||
await seedFailedDependencyWakes({ ...fixture, count: 3, lastFinishedAt: new Date(Date.now() - 60_000) });
|
||||
await db.update(issues).set({ completedAt: new Date(Date.now() - 10_000) }).where(eq(issues.id, fixture.blockerIssueId));
|
||||
|
||||
const result = await heartbeatService(db).reconcileResolvedDependencyWakes({ issueId: fixture.blockedIssueId });
|
||||
|
||||
expect(result.healed).toBe(1);
|
||||
});
|
||||
|
||||
it("does not re-wake an assignee agent that opened the current blocked cycle itself", async () => {
|
||||
const { companyId, agentId, blockedIssueId } =
|
||||
await seedResolvedDependencyBackstopFixture({ workspaceState: "none" });
|
||||
|
||||
Reference in new issue
Block a user