mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-25 16:14:26 +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" });
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
DEPENDENCY_WAKE_MAX_BACKOFF_MS,
|
||||
decideDependencyWakeCircuit,
|
||||
dependencyWakeBackoffMs,
|
||||
type DependencyWakeRunSample,
|
||||
} from "./dependency-wake-circuit-breaker.js";
|
||||
|
||||
const now = Date.parse("2099-01-01T12:00:00.000Z");
|
||||
let nextId = 0;
|
||||
|
||||
function run(status: string, minutesAgo: number, id = `run-${nextId++}`): DependencyWakeRunSample {
|
||||
return { id, status, finishedAt: new Date(now - minutesAgo * 60_000) };
|
||||
}
|
||||
|
||||
function decide(runs: DependencyWakeRunSample[], latestBlockerChangeAt: Date | null = null) {
|
||||
return decideDependencyWakeCircuit({ runs, latestBlockerChangeAt, now });
|
||||
}
|
||||
|
||||
describe("dependencyWakeBackoffMs", () => {
|
||||
it("grows by five per failure and is capped", () => {
|
||||
expect([1, 2, 3, 4].map(dependencyWakeBackoffMs)).toEqual([60_000, 300_000, 1_500_000, 7_500_000]);
|
||||
expect(dependencyWakeBackoffMs(50)).toBe(DEPENDENCY_WAKE_MAX_BACKOFF_MS);
|
||||
});
|
||||
});
|
||||
|
||||
describe("decideDependencyWakeCircuit", () => {
|
||||
it("stays closed with no failed runs", () => {
|
||||
expect(decide([])).toEqual({ state: "closed", consecutiveFailures: 0 });
|
||||
expect(decide([run("succeeded", 0)])).toEqual({ state: "closed", consecutiveFailures: 0 });
|
||||
});
|
||||
|
||||
it("backs off after a recent failure and closes once the backoff has passed", () => {
|
||||
expect(decide([run("failed", 0)])).toEqual({ state: "backoff", consecutiveFailures: 1, retryAt: now + 60_000 });
|
||||
expect(decide([run("failed", 2)]).state).toBe("closed");
|
||||
expect(decide([run("failed", 2), run("timed_out", 3)])).toMatchObject({ state: "backoff", consecutiveFailures: 2 });
|
||||
});
|
||||
|
||||
it("probes again after the capped backoff, however long the streak", () => {
|
||||
const streak = Array.from({ length: 12 }, (_, index) => run("failed", 24 * 60 + 1 + index));
|
||||
expect(decide(streak)).toEqual({ state: "closed", consecutiveFailures: 12 });
|
||||
});
|
||||
|
||||
it("counts a failed run once even when several wake receipts point to it", () => {
|
||||
expect(decide([run("failed", 3, "same"), run("failed", 3, "same"), run("failed", 3, "same")]))
|
||||
.toEqual({ state: "closed", consecutiveFailures: 1 });
|
||||
});
|
||||
|
||||
it("treats interrupted runs as neutral", () => {
|
||||
expect(decide([run("interrupted", 0), run("failed", 1), run("failed", 2)]))
|
||||
.toMatchObject({ state: "backoff", consecutiveFailures: 2 });
|
||||
});
|
||||
|
||||
it("resets on a run that did not fail, whatever woke it", () => {
|
||||
expect(decide([run("failed", 0), run("succeeded", 1), run("failed", 2), run("failed", 3)]))
|
||||
.toMatchObject({ state: "backoff", consecutiveFailures: 1 });
|
||||
expect(decide([run("cancelled", 0), run("failed", 1)])).toEqual({ state: "closed", consecutiveFailures: 0 });
|
||||
});
|
||||
|
||||
it("orders runs by finish time", () => {
|
||||
expect(decide([run("failed", 2), run("succeeded", 3), run("failed", 0)]))
|
||||
.toMatchObject({ state: "backoff", consecutiveFailures: 2 });
|
||||
});
|
||||
|
||||
it("ignores failures from before the latest blocker change", () => {
|
||||
const runs = [run("failed", 0), run("failed", 2), run("failed", 3)];
|
||||
expect(decide(runs, new Date(now - 90_000))).toMatchObject({ state: "backoff", consecutiveFailures: 1 });
|
||||
expect(decide(runs, new Date(now))).toEqual({ state: "closed", consecutiveFailures: 0 });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,160 @@
|
||||
import { and, desc, eq, inArray, isNull, max, or, sql } from "drizzle-orm";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import { activityLog, heartbeatRuns, issueRelations, issues, workspaceOperations } from "@paperclipai/db";
|
||||
import { boundRunIssueIdSql } from "../run-task-binding.js";
|
||||
|
||||
/**
|
||||
* Circuit breaker for the resolved-dependency wake backstop.
|
||||
*
|
||||
* The backstop wakes the assignee of a blocked task whose blockers are all done.
|
||||
* Its idempotency key includes the task's blocked cycle, so a woken run that
|
||||
* fails and leaves the task blocked again starts a new cycle and a new key. When
|
||||
* that failure is deterministic, every sweep woke the task again: one production
|
||||
* task ran 11,000+ failed runs this way. The failed run has its own recovery
|
||||
* (retry scheduling, permanent failure classification); the blockers have not
|
||||
* changed, so the backstop must not keep re-delivering the same news.
|
||||
*
|
||||
* Policy: count the consecutive failed runs of this agent on this task, newest
|
||||
* first, that finished after the latest blocker change (a blocker result, or an
|
||||
* edit of the blocker set). Each failure multiplies
|
||||
* the wait before the next dependency wake by 5 (1m, 5m, 25m, ...), capped at
|
||||
* DEPENDENCY_WAKE_MAX_BACKOFF_MS. The breaker never closes for good: after the
|
||||
* wait, one wake probes again, so a fix that ships later is picked up. A run
|
||||
* that did not fail (any wake reason) or a newer blocker change resets it.
|
||||
* Interrupted runs (server restart, deploy) are neutral.
|
||||
*/
|
||||
export const DEPENDENCY_WAKE_BASE_BACKOFF_MS = 60_000;
|
||||
export const DEPENDENCY_WAKE_BACKOFF_FACTOR = 5;
|
||||
export const DEPENDENCY_WAKE_MAX_BACKOFF_MS = 24 * 60 * 60_000;
|
||||
/** Streak at which the backstop reports the task as repeatedly failing. */
|
||||
export const DEPENDENCY_WAKE_REPEATED_FAILURE_STREAK = 3;
|
||||
const RUN_SAMPLE_LIMIT = 12;
|
||||
|
||||
const FAILED_RUN_STATUSES = new Set(["failed", "timed_out"]);
|
||||
const NEUTRAL_RUN_STATUSES = new Set(["interrupted"]);
|
||||
|
||||
export type DependencyWakeRunSample = {
|
||||
id: string;
|
||||
status: string;
|
||||
finishedAt: Date | null;
|
||||
};
|
||||
|
||||
export type DependencyWakeCircuitDecision =
|
||||
| { state: "closed"; consecutiveFailures: number }
|
||||
| { state: "backoff"; consecutiveFailures: number; retryAt: number };
|
||||
|
||||
export function dependencyWakeBackoffMs(consecutiveFailures: number): number {
|
||||
if (consecutiveFailures <= 0) return 0;
|
||||
const exponent = Math.min(consecutiveFailures - 1, 16);
|
||||
return Math.min(DEPENDENCY_WAKE_BASE_BACKOFF_MS * DEPENDENCY_WAKE_BACKOFF_FACTOR ** exponent,
|
||||
DEPENDENCY_WAKE_MAX_BACKOFF_MS);
|
||||
}
|
||||
|
||||
/** `runs` are this agent's recent runs on the task, in any order. */
|
||||
export function decideDependencyWakeCircuit(input: {
|
||||
runs: DependencyWakeRunSample[];
|
||||
latestBlockerChangeAt: Date | null;
|
||||
now: number;
|
||||
}): DependencyWakeCircuitDecision {
|
||||
const seen = new Set<string>();
|
||||
let consecutiveFailures = 0;
|
||||
let latestFailureAt: number | null = null;
|
||||
const runs = [...input.runs].sort((a, b) => (b.finishedAt?.getTime() ?? 0) - (a.finishedAt?.getTime() ?? 0));
|
||||
for (const run of runs) {
|
||||
if (seen.has(run.id)) continue;
|
||||
seen.add(run.id);
|
||||
if (!run.finishedAt) continue;
|
||||
// Only attempts made against the current blockers and their results count.
|
||||
if (input.latestBlockerChangeAt && run.finishedAt.getTime() <= input.latestBlockerChangeAt.getTime()) break;
|
||||
if (NEUTRAL_RUN_STATUSES.has(run.status)) continue;
|
||||
if (!FAILED_RUN_STATUSES.has(run.status)) break;
|
||||
consecutiveFailures += 1;
|
||||
latestFailureAt ??= run.finishedAt.getTime();
|
||||
}
|
||||
if (consecutiveFailures === 0 || latestFailureAt === null) return { state: "closed", consecutiveFailures };
|
||||
const retryAt = latestFailureAt + dependencyWakeBackoffMs(consecutiveFailures);
|
||||
if (retryAt > input.now) return { state: "backoff", consecutiveFailures, retryAt };
|
||||
return { state: "closed", consecutiveFailures };
|
||||
}
|
||||
|
||||
export async function readDependencyWakeCircuit(
|
||||
db: Db,
|
||||
input: { companyId: string; issueId: string; agentId: string; blockerIssueIds: string[]; now?: number },
|
||||
): Promise<DependencyWakeCircuitDecision> {
|
||||
// Match the canonical run-task binding. The OR over the three indexed binding
|
||||
// paths (issue_id, native_issue_id, context issueId) lets the planner use
|
||||
// their company-scoped indexes; the coalesced binding keeps the match exact.
|
||||
// Unfinished runs are skipped.
|
||||
const runs = await db
|
||||
.select({ id: heartbeatRuns.id, status: heartbeatRuns.status, finishedAt: heartbeatRuns.finishedAt })
|
||||
.from(heartbeatRuns)
|
||||
.where(and(
|
||||
eq(heartbeatRuns.companyId, input.companyId),
|
||||
or(
|
||||
eq(heartbeatRuns.issueId, input.issueId),
|
||||
eq(heartbeatRuns.nativeIssueId, input.issueId),
|
||||
sql`${heartbeatRuns.contextSnapshot} ->> 'issueId' = ${input.issueId}`,
|
||||
),
|
||||
sql`${boundRunIssueIdSql()} = ${input.issueId}`,
|
||||
eq(heartbeatRuns.agentId, input.agentId),
|
||||
))
|
||||
.orderBy(desc(heartbeatRuns.createdAt), desc(heartbeatRuns.id))
|
||||
.limit(RUN_SAMPLE_LIMIT);
|
||||
if (!runs.some((run) => FAILED_RUN_STATUSES.has(run.status))) return { state: "closed", consecutiveFailures: 0 };
|
||||
|
||||
const changeTimes: unknown[] = [];
|
||||
if (input.blockerIssueIds.length > 0) {
|
||||
const [completed] = await db.select({ at: max(issues.completedAt) }).from(issues).where(and(
|
||||
eq(issues.companyId, input.companyId),
|
||||
inArray(issues.id, input.blockerIssueIds),
|
||||
));
|
||||
// Join through each blocker's execution workspace so the read uses
|
||||
// workspace_operations_company_workspace_issue_started_idx.
|
||||
const [finalized] = await db.select({ at: max(workspaceOperations.finishedAt) })
|
||||
.from(issues)
|
||||
.innerJoin(workspaceOperations, and(
|
||||
eq(workspaceOperations.companyId, issues.companyId),
|
||||
eq(workspaceOperations.executionWorkspaceId, issues.executionWorkspaceId),
|
||||
eq(workspaceOperations.issueId, issues.id),
|
||||
))
|
||||
.where(and(
|
||||
eq(issues.companyId, input.companyId),
|
||||
inArray(issues.id, input.blockerIssueIds),
|
||||
eq(workspaceOperations.phase, "workspace_finalize"),
|
||||
eq(workspaceOperations.status, "succeeded"),
|
||||
));
|
||||
// Workspace recovery saves blocker work without an execution workspace. The
|
||||
// null workspace still matches the leading columns of the same index.
|
||||
const [recovered] = await db.select({ at: max(workspaceOperations.finishedAt) }).from(workspaceOperations).where(and(
|
||||
eq(workspaceOperations.companyId, input.companyId),
|
||||
isNull(workspaceOperations.executionWorkspaceId),
|
||||
inArray(workspaceOperations.issueId, input.blockerIssueIds),
|
||||
eq(workspaceOperations.phase, "workspace_finalize"),
|
||||
eq(workspaceOperations.status, "succeeded"),
|
||||
sql`${workspaceOperations.metadata}->>'owningService' = 'workspace_recovery'`,
|
||||
));
|
||||
changeTimes.push(completed?.at, finalized?.at, recovered?.at);
|
||||
}
|
||||
// A changed blocker set is a new attempt: an added blocker leaves a relation
|
||||
// row, and every add or removal through the API records issue.blockers_updated.
|
||||
const [related] = await db.select({ at: max(issueRelations.createdAt) }).from(issueRelations).where(and(
|
||||
eq(issueRelations.companyId, input.companyId),
|
||||
eq(issueRelations.relatedIssueId, input.issueId),
|
||||
eq(issueRelations.type, "blocks"),
|
||||
));
|
||||
const [edited] = await db.select({ at: max(activityLog.createdAt) }).from(activityLog).where(and(
|
||||
eq(activityLog.companyId, input.companyId),
|
||||
eq(activityLog.entityType, "issue"),
|
||||
eq(activityLog.entityId, input.issueId),
|
||||
eq(activityLog.action, "issue.blockers_updated"),
|
||||
));
|
||||
changeTimes.push(related?.at, edited?.at);
|
||||
let latestBlockerChangeAt: Date | null = null;
|
||||
for (const value of changeTimes) {
|
||||
if (value == null) continue;
|
||||
const at = value instanceof Date ? value : new Date(value as string);
|
||||
if (Number.isNaN(at.getTime())) continue;
|
||||
if (!latestBlockerChangeAt || at > latestBlockerChangeAt) latestBlockerChangeAt = at;
|
||||
}
|
||||
return decideDependencyWakeCircuit({ runs, latestBlockerChangeAt, now: input.now ?? Date.now() });
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { wakeWaitersOfStalledIssues, type BlockerStallWakeup } from "./blocker-stall-wakeups.js";
|
||||
import { DEPENDENCY_WAKE_REPEATED_FAILURE_STREAK, readDependencyWakeCircuit } from "./dependency-wake-circuit-breaker.js";
|
||||
import { INTERACTION_DELIVERY_DENIED, isInteractionDeliveryDeniedRun } from "../agent-interaction-delivery.js";
|
||||
import { notifyScheduledRetryDispatch } from "../run-dispatch-notifications.js";
|
||||
import { OWNER_UNPROVABLE_CAUSE } from "./owner-gone-attestation.js";
|
||||
@@ -6166,6 +6167,7 @@ export function recoveryService(
|
||||
healed: 0,
|
||||
existingWakeSkipped: 0,
|
||||
selfBlockedSkipped: 0,
|
||||
failedWakeBackoffSkipped: 0,
|
||||
livePathSkipped: 0,
|
||||
interactionSkipped: 0,
|
||||
pauseHoldSkipped: 0,
|
||||
@@ -6174,6 +6176,7 @@ export function recoveryService(
|
||||
deferredOrFailed: 0,
|
||||
enqueueFailed: 0,
|
||||
issueIds: [] as string[],
|
||||
repeatedFailureIssueIds: [] as string[],
|
||||
};
|
||||
|
||||
const source = opts?.source ?? "issue_graph_liveness.backstop";
|
||||
@@ -6367,6 +6370,24 @@ export function recoveryService(
|
||||
continue;
|
||||
}
|
||||
|
||||
// A woken run that fails can leave the task blocked again, which starts a
|
||||
// new blocked cycle and a new idempotency key. Without this breaker a
|
||||
// deterministic failure re-woke the task on every sweep, forever.
|
||||
const circuit = await readDependencyWakeCircuit(db, {
|
||||
companyId,
|
||||
issueId: candidate.id,
|
||||
agentId,
|
||||
blockerIssueIds: readiness.blockerIssueIds,
|
||||
});
|
||||
if (circuit.state === "backoff") {
|
||||
result.failedWakeBackoffSkipped += 1;
|
||||
if (circuit.consecutiveFailures >= DEPENDENCY_WAKE_REPEATED_FAILURE_STREAK) {
|
||||
result.repeatedFailureIssueIds.push(candidate.id);
|
||||
}
|
||||
opts?.onDeferredDeadline?.(circuit.retryAt);
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
const wake = await deps.enqueueWakeup(agentId, {
|
||||
source: "automation",
|
||||
@@ -6440,6 +6461,15 @@ export function recoveryService(
|
||||
"issue graph liveness backstop healed resolved blocked dependency wakes",
|
||||
);
|
||||
}
|
||||
if (result.repeatedFailureIssueIds.length > 0) {
|
||||
logger.warn(
|
||||
{
|
||||
issueIds: result.repeatedFailureIssueIds,
|
||||
source,
|
||||
},
|
||||
"issue graph liveness backstop is backing off blocked tasks whose resolved-dependency runs keep failing",
|
||||
);
|
||||
}
|
||||
|
||||
// A stalled child or blocker: tell whoever waits on it, once per stall
|
||||
// (blocker-stall-wakeups.ts). This sweep visits each blocked issue, which
|
||||
|
||||
Reference in new issue
Block a user