fix: make task recovery durable and preserve current requests (#13075)

Make task recovery durable and preserve the latest user request across native and legacy continuations. Keep routine recovery quiet and prevent replay when action outcomes are uncertain.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip authored and GitHub committed 2026-09-09 09:14:25 -05:00
1 parent 6681104692
commit 35fdc0c66b
98 files changed
+224889 -1364

No files matched your search

@@ -1,6 +1,6 @@
import { randomUUID } from "node:crypto";
import { eq, sql } from "drizzle-orm";
import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
import {
agents,
companies,
@@ -11,6 +11,7 @@ import {
heartbeatRuns,
issueDocuments,
issueRelations,
issueRecoveryActions,
issueTreeHolds,
issues,
} from "@paperclipai/db";
@@ -186,6 +187,88 @@ describeEmbeddedPostgres("run-dispatch postgres adapter", () => {
});
}
it.each(["executionRunId", "checkoutRunId"] as const)("suppresses delayed native replacement after another run acquires %s", async (lock) => {
const { companyId, agentId } = await seedCompanyAndAgent();
const issueId = randomUUID();
await seedIssue({ companyId, issueId, assigneeAgentId: agentId, status: "in_progress" });
const contextSnapshot = { issueId, wakeReason: "native_safe_replacement", retryReason: "native_safe_replacement", forceFreshSession: true };
const replacementId = await seedRun({ companyId, agentId, status: "scheduled_retry", contextSnapshot });
const competingId = await seedRun({ companyId, agentId, status: "running", contextSnapshot: { issueId } });
await db.update(issues).set({ [lock]: competingId }).where(eq(issues.id, issueId));
const adapter = createPostgresRunDispatchAdapter(db);
expect(await adapter.evaluateScheduledRetryGate({ companyId, runId: replacementId, retryReasonOverride: "native_safe_replacement", now: new Date() }))
.toMatchObject({ allowed: false, errorCode: "issue_execution_lock_changed" });
await db.update(heartbeatRuns).set({ status: "queued" }).where(eq(heartbeatRuns.id, replacementId));
expect(await adapter.cancelStaleQueuedRun({ companyId, runId: replacementId, expectedStatus: "queued", now: new Date() }))
.toMatchObject({ outcome: "cancelled", errorCode: "issue_execution_lock_changed" });
// A competing owner can also appear after queue validation. The final
// dispatch gate must prevent any provider call, even from a running row.
await db.update(heartbeatRuns).set({ status: "running" }).where(eq(heartbeatRuns.id, replacementId));
let dispatched = false;
const outcome = await adapter.dispatchResolvedInteractionIfCurrent({ companyId, runId: replacementId,
expectedStatus: "running", now: new Date(), dispatch: async () => { dispatched = true; } });
expect(outcome).toMatchObject({ dispatched: false, cancellation: { outcome: "cancelled" } });
expect(dispatched).toBe(false);
expect((await db.select().from(issues).where(eq(issues.id, issueId)))[0]![lock]).toBe(competingId);
expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, competingId)))[0]?.status).toBe("running");
});
it("commits the handoff without awaiting a recovered provider that fails before spawning", async () => {
const { companyId, agentId } = await seedCompanyAndAgent();
const issueId = randomUUID();
await seedIssue({ companyId, issueId, assigneeAgentId: agentId, status: "in_progress" });
const runId = await seedRun({ companyId, agentId, status: "running", contextSnapshot: { issueId } });
await db.update(issues).set({ executionRunId: runId }).where(eq(issues.id, issueId));
const adapter = createPostgresRunDispatchAdapter(db);
const gate = await adapter.dispatchResolvedInteractionIfCurrent({
companyId, runId, expectedStatus: "running", now: new Date(),
dispatch: async () => {
// The incident's third attempt failed here before onSpawn. A held
// admission lock makes this finalization fail with lock_timeout.
await db.transaction(async tx => {
await tx.execute(sql`select set_config('lock_timeout', '1000', true)`);
await tx.update(issues).set({ executionRunId: null }).where(eq(issues.id, issueId));
await tx.update(heartbeatRuns).set({ status: "failed", finishedAt: new Date() }).where(eq(heartbeatRuns.id, runId));
});
return "provider_checkpoint_failed_terminal";
},
});
expect(gate.dispatched).toBe(true);
if (gate.dispatched) expect(await gate.resultPromise).toBe("provider_checkpoint_failed_terminal");
expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)))[0]?.status).toBe("failed");
});
it("initiates dispatch before admission locks can be released to a competing owner", async () => {
const { companyId, agentId } = await seedCompanyAndAgent();
const issueId = randomUUID();
await seedIssue({ companyId, issueId, assigneeAgentId: agentId, status: "in_progress" });
const runId = await seedRun({ companyId, agentId, status: "running", contextSnapshot: { issueId } });
const competingId = await seedRun({ companyId, agentId, status: "running", contextSnapshot: { issueId } });
await db.update(issues).set({ executionRunId: runId }).where(eq(issues.id, issueId));
const transaction = db.transaction.bind(db);
const ordering: string[] = [];
// Inject a competing claim immediately after commit, before control returns
// to the adapter. A callback outside the transaction would run too late.
const transactionSpy = vi.spyOn(db, "transaction").mockImplementation(async (callback, config) => {
const value = await transaction(callback, config);
await db.update(issues).set({ executionRunId: competingId }).where(eq(issues.id, issueId));
ordering.push("competing-owner");
return value;
});
try {
const gate = await createPostgresRunDispatchAdapter(db).dispatchResolvedInteractionIfCurrent({
companyId, runId, expectedStatus: "running", now: new Date(),
dispatch: async () => { ordering.push("handoff"); return "started"; },
});
expect(gate.dispatched).toBe(true);
if (gate.dispatched) expect(await gate.resultPromise).toBe("started");
expect(ordering).toEqual(["handoff", "competing-owner"]);
} finally {
transactionSpy.mockRestore();
}
});
async function waitForBlockedForUpdate(tableName: string) {
for (let attempt = 0; attempt < 80; attempt += 1) {
const [waiting] = await db.execute<{ waiting: boolean }>(sql`
@@ -612,4 +695,14 @@ describeEmbeddedPostgres("run-dispatch postgres adapter", () => {
15_000,
);
});
it.each(["active", "resolved"])("blocks a generic retry after %s no-replay disposition", async status => {
const { companyId, agentId } = await seedCompanyAndAgent();
const issueId = randomUUID(), runId = randomUUID();
await db.insert(issues).values({ id: issueId, companyId, title: "Uncertain email", status: "in_progress", assigneeAgentId: agentId });
await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, status: "queued", contextSnapshot: { issueId, wakeReason: "retry_failed_run" } });
await db.insert(issueRecoveryActions).values({ companyId, sourceIssueId: issueId, kind: "active_run_watchdog", ownerType: "board", cause: "uncertain_external_action", status, evidence: status === "resolved" ? { automaticRecovery: { replay: "blocked" } } : {}, fingerprint: runId, nextAction: "Verify whether email-1 was sent before continuing." });
const adapter = createPostgresRunDispatchAdapter(db);
await expect(adapter.cancelStaleQueuedRun({ companyId, runId, expectedStatus: "queued", now: new Date() })).resolves.toMatchObject({ outcome: "cancelled", errorCode: "execution_reconciliation_required" });
});
});
@@ -1,4 +1,5 @@
import { and, asc, eq, gte, inArray, lte } from "drizzle-orm";
import { EXECUTION_RECONCILIATION_CAUSES } from "@paperclipai/shared";
import { and, asc, eq, gte, inArray, lte, or, sql } from "drizzle-orm";
import type { Db } from "@paperclipai/db";
import {
agentWakeupRequests,
@@ -106,6 +107,7 @@ function readNonEmptyString(value: unknown): string | null {
function classifyRetryReasonKind(retryReason: string | null): RetryReasonKind {
if (retryReason === MAX_TURN_CONTINUATION_RETRY_REASON) return "max_turn_continuation";
if (retryReason === ISSUE_DISPOSITION_REPAIR_RETRY_REASON) return "disposition_repair";
if (retryReason === "native_safe_replacement") return "native_safe_replacement";
return "other";
}
@@ -199,8 +201,8 @@ export function createPostgresRunDispatchAdapter(
and(eq(heartbeatRuns.id, input.runId), eq(heartbeatRuns.companyId, input.companyId)),
)
// Keep the run status stable through the semantic decision and any
// resulting mutation. Adapter-owned work starts only after this
// transaction releases the lock at the handoff boundary.
// resulting mutation and synchronous dispatch handoff. Never await
// adapter-owned work while this transaction holds the row locks.
.for("update")
.then((rows) => rows[0] ?? null);
if (!run) return { kind: "missing" as const };
@@ -313,6 +315,7 @@ export function createPostgresRunDispatchAdapter(
assigneeAgentId: issues.assigneeAgentId,
assigneeUserId: issues.assigneeUserId,
executionRunId: issues.executionRunId,
checkoutRunId: issues.checkoutRunId,
executionPolicy: issues.executionPolicy,
executionState: issues.executionState,
monitorNextCheckAt: issues.monitorNextCheckAt,
@@ -333,6 +336,7 @@ export function createPostgresRunDispatchAdapter(
facts.issueStatus = issue.status;
facts.issueAssigneeAgentId = issue.assigneeAgentId;
facts.issueExecutionRunId = issue.executionRunId;
facts.issueCheckoutRunId = issue.checkoutRunId;
facts.reviewParticipant = buildReviewParticipantFacts({
isInReview: issue.status === "in_review",
executionState: parseIssueExecutionState(issue.executionState),
@@ -455,6 +459,7 @@ export function createPostgresRunDispatchAdapter(
status: issues.status,
assigneeAgentId: issues.assigneeAgentId,
executionRunId: issues.executionRunId,
checkoutRunId: issues.checkoutRunId,
executionState: issues.executionState,
})
.from(issues)
@@ -526,6 +531,7 @@ export function createPostgresRunDispatchAdapter(
issueStatus: issue?.status ?? null,
issueAssigneeAgentId: issue?.assigneeAgentId ?? null,
issueExecutionRunId: issue?.executionRunId ?? null,
issueCheckoutRunId: issue?.checkoutRunId ?? null,
isResolvedInteractionContinuation,
isConnectionContinuation: (isResolvedInteractionContinuation && context.interactionKind === "connection_intent")
|| context.source === "connection_tools.refreshed",
@@ -718,7 +724,8 @@ export function createPostgresRunDispatchAdapter(
const isLegacyMissingIssueException =
!gate.allowed &&
gate.errorCode === "issue_not_found" &&
factsResult.facts.retryReasonKind !== "max_turn_continuation";
factsResult.facts.retryReasonKind !== "max_turn_continuation" &&
factsResult.facts.retryReasonKind !== "native_safe_replacement";
if (!gate.allowed && !isLegacyMissingIssueException) {
const cancelled = await cancelSuppressedRetryInTx(tx as unknown as Db, {
@@ -863,6 +870,17 @@ export function createPostgresRunDispatchAdapter(
const contextSnapshot = parseObject(run.contextSnapshot);
const issueId = readNonEmptyString(contextSnapshot.issueId);
if (!issueId) return { issueId: null, decision: { stale: false as const } };
const [recovery] = await tx.select({ id: issueRecoveryActions.id, nextAction: issueRecoveryActions.nextAction })
.from(issueRecoveryActions).where(and(
eq(issueRecoveryActions.companyId, run.companyId), eq(issueRecoveryActions.sourceIssueId, issueId),
or(inArray(issueRecoveryActions.status, ["active", "escalated"]),
sql`${issueRecoveryActions.evidence}->'automaticRecovery'->>'replay' = 'blocked'`),
inArray(issueRecoveryActions.cause, [...EXECUTION_RECONCILIATION_CAUSES]),
)).limit(1);
if (recovery) return { issueId, decision: { stale: true as const,
errorCode: "execution_reconciliation_required" as const, reason: recovery.nextAction,
details: { issueId, recoveryActionId: recovery.id },
} };
const facts = await loadStalenessFacts(
{
runId: run.id,
@@ -926,7 +944,7 @@ export function createPostgresRunDispatchAdapter(
stale: true as const,
errorCode: "issue_execution_lock_changed" as const,
reason:
"Cancelled because resolved-interaction continuation no longer owns the issue execution lock before adapter dispatch",
"Cancelled because continuation no longer owns the issue execution lock before adapter dispatch",
details: {
issueId,
expectedExecutionRunId: run.id,
@@ -948,19 +966,13 @@ export function createPostgresRunDispatchAdapter(
return { dispatched: false as const, cancellation };
}
let dispatchStarted = false;
let resolveDispatchStarted!: () => void;
const dispatchStartedPromise = new Promise<void>((resolve) => {
resolveDispatchStarted = resolve;
});
const markDispatchStarted = () => {
if (dispatchStarted) return;
dispatchStarted = true;
resolveDispatchStarted();
};
const resultPromise = input.dispatch(markDispatchStarted);
void resultPromise.then(markDispatchStarted, markDispatchStarted);
await dispatchStartedPromise;
// Hand off while ownership is still locked, but do not await the provider
// promise. Bootstrap and failure finalization can update these same rows;
// the transaction must commit independently of either callback completing.
const resultPromise = input.dispatch(() => {});
// A synchronous rejection can precede the commit response. Observe it
// immediately while preserving the original promise for the caller.
void resultPromise.catch(() => {});
return { dispatched: true as const, resultPromise };
};
@@ -974,6 +986,7 @@ export function createPostgresRunDispatchAdapter(
},
dispatchLockedRun,
);
}
return {
@@ -68,6 +68,19 @@ function baseStalenessFacts(): QueuedRunFacts {
}
describe("decideScheduledRetryGate", () => {
it("allows the current reviewer and rejects a replaced participant", () => {
const facts: ScheduledRetryFacts = {
...baseGateFacts(), issueStatus: "in_review", issueAssigneeAgentId: "implementor",
reviewParticipant: { isInReview: true, hasParticipant: true, participantIsAgent: true,
participantAgentId: "agent-1", currentStageType: "review", currentParticipant: { type: "agent", agentId: "agent-1" } },
};
expect(decideScheduledRetryGate(facts, NOW)).toEqual({ allowed: true });
expect(decideScheduledRetryGate({ ...facts, reviewParticipant: { ...facts.reviewParticipant, participantAgentId: "new-reviewer" } }, NOW))
.toMatchObject({ allowed: false, errorCode: "issue_reassigned" });
expect(decideScheduledRetryGate({ ...facts, reviewParticipant: NO_PARTICIPANT }, NOW))
.toMatchObject({ allowed: false, errorCode: "issue_reassigned" });
});
it("allows a run with no issueId before any issue check runs", () => {
const facts = { ...baseGateFacts(), issueId: null, issueFound: false };
expect(decideScheduledRetryGate(facts, NOW)).toEqual({ allowed: true });
@@ -431,3 +444,20 @@ describe("decideQueuedRunStaleness", () => {
expect(decideQueuedRunStaleness(facts, NOW)).toEqual({ stale: false });
});
});
describe("native replacement execution authority", () => {
it.each([
{ issueExecutionRunId: "newer-run", issueCheckoutRunId: null },
{ issueExecutionRunId: null, issueCheckoutRunId: "newer-run" },
])("rejects another owner's lock at both retry gates: %j", (locks) => {
expect(decideScheduledRetryGate({ ...baseGateFacts(), retryReasonKind: "native_safe_replacement", ...locks }, NOW))
.toMatchObject({ allowed: false, errorCode: "issue_execution_lock_changed" });
expect(decideQueuedRunStaleness({ ...baseStalenessFacts(), retryReasonKind: "native_safe_replacement", ...locks }, NOW))
.toMatchObject({ stale: true, errorCode: "issue_execution_lock_changed" });
});
it.each([null, "run-1"])("allows vacant or already-owned replacement locks: %s", (owner) => {
const locks = { issueExecutionRunId: owner, issueCheckoutRunId: owner };
expect(decideScheduledRetryGate({ ...baseGateFacts(), retryReasonKind: "native_safe_replacement", ...locks }, NOW)).toEqual({ allowed: true });
expect(decideQueuedRunStaleness({ ...baseStalenessFacts(), retryReasonKind: "native_safe_replacement", ...locks }, NOW)).toEqual({ stale: false });
});
});
@@ -9,6 +9,7 @@
export type RetryReasonKind =
| "max_turn_continuation"
| "disposition_repair"
| "native_safe_replacement"
| "other";
export type BudgetBlockFacts = {
@@ -90,6 +91,7 @@ export type ScheduledRetryFacts = {
issueStatus: string | null;
issueAssigneeAgentId: string | null;
issueExecutionRunId: string | null;
issueCheckoutRunId?: string | null;
isNonAssigneeWorkspaceBusyRetry: boolean;
reviewParticipant: ReviewParticipantFacts;
@@ -101,6 +103,7 @@ export type ScheduledRetryFacts = {
};
export type QueuedRunStalenessErrorCode =
| "execution_reconciliation_required"
| "issue_not_found"
| "issue_assignee_changed"
| "issue_terminal_status"
@@ -128,6 +131,7 @@ export type QueuedRunFacts = {
issueStatus: string | null;
issueAssigneeAgentId: string | null;
issueExecutionRunId: string | null;
issueCheckoutRunId?: string | null;
isResolvedInteractionContinuation: boolean;
/** A connection resolution or tool refresh can resume an agent waiting in review. */
@@ -202,6 +206,7 @@ type ExecutionLockFacts = {
requiresExecutionLock: boolean;
runId: string;
issueExecutionRunId: string | null;
issueCheckoutRunId?: string | null;
};
type ExecutionLockOutcome = "ok" | "lock_changed";
@@ -325,6 +330,11 @@ export function decideScheduledRetryGate(
runAgentId: facts.runAgentId,
issueAssigneeAgentId: facts.issueAssigneeAgentId,
isNonAssigneeWorkspaceBusyRetry: facts.isNonAssigneeWorkspaceBusyRetry,
isCurrentReviewParticipant:
facts.reviewParticipant.isInReview &&
facts.reviewParticipant.hasParticipant &&
facts.reviewParticipant.participantIsAgent &&
facts.reviewParticipant.participantAgentId === facts.runAgentId,
});
if (ownership === "reassigned") {
return {
@@ -340,6 +350,13 @@ export function decideScheduledRetryGate(
};
}
if (facts.retryReasonKind === "native_safe_replacement" &&
[facts.issueExecutionRunId, facts.issueCheckoutRunId].some(id => id != null && id !== facts.runId)) {
return { allowed: false, issueId: facts.issueId, errorCode: "issue_execution_lock_changed",
reason: "Scheduled replacement suppressed because another run owns task execution or checkout",
details: { issueId: facts.issueId, currentExecutionRunId: facts.issueExecutionRunId, currentCheckoutRunId: facts.issueCheckoutRunId ?? null } };
}
const requiresInProgress = facts.retryReasonKind === "max_turn_continuation";
const statusOutcome = decideIssueStatus({
status: facts.issueStatus,
@@ -539,6 +556,13 @@ export function decideQueuedRunStaleness(
};
}
if (facts.retryReasonKind === "native_safe_replacement" &&
[facts.issueExecutionRunId, facts.issueCheckoutRunId].some(id => id != null && id !== facts.runId)) {
return { stale: true, errorCode: "issue_execution_lock_changed",
reason: "Cancelled because another run owns task execution or checkout before replacement dispatch",
details: { issueId: facts.issueId, currentExecutionRunId: facts.issueExecutionRunId, currentCheckoutRunId: facts.issueCheckoutRunId ?? null } };
}
const requiresInProgress = facts.retryReasonKind === "max_turn_continuation";
const statusOutcome = decideIssueStatus({
status: facts.issueStatus,