mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-30 09:05:15 +01:00
fix(presentation): offer Retry only when no automatic continuation or scheduled retry is pending (#21264, includes #21200)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - When a run fails with a transient error, Paperclip schedules the next attempt by itself and shows "retrying automatically" with a countdown. > - The task presentation also offered the Retry button next to that countdown. > - The system owns the next attempt while the run is `scheduled_retry`, so the button is misleading: it suggests that a person must act. > - This pull request stops offering Retry while a scheduled retry is pending. Retry returns when the scheduled retry is past due with nothing pending, or when the retries are exhausted. > - The benefit is one clear message: Paperclip retries by itself, and Retry appears only when it is the way forward. ## Linked Issues or Issue Description **What happened?** A legacy run in status `scheduled_retry` (for example reason `transient_failure`, which is not a shared-resource wait and has no system recovery) projected `state: "retry_scheduled"` with `canRetry: true`. The UI then showed the Retry button beside "retrying automatically". The cause is in `projectTaskInterruptionState` in `server/src/services/task-interruption-presentation.ts`: the `retryAt > now` branch set `canRetry: !preparationPending && !nativeResumeAt`, which ignores that the run itself is the scheduled attempt. **Expected behavior** While a run is `scheduled_retry` and its retry time is in the future, the task shows the countdown and offers no Retry. When the scheduled retry is past due with nothing pending, or the retries are exhausted, Retry is offered. **Steps to reproduce** 1. Let a task's run fail with a transient failure that schedules an automatic retry. 2. Open the task before the retry time. 3. The task shows "retrying automatically" and the Retry button. **What a Retry click does today in this state** `requestTaskRetry` (`server/src/services/task-retry.ts`) treats a latest run in `scheduled_retry` as busy. It accepts the click (202), records the request as `coalesced` onto the scheduled run and returns `scheduledRetryRunId`. It does not start a second attempt next to the scheduled one. The button is therefore misleading but not unsafe, and this pull request changes only what the task shows. ## What Changed - `server/src/services/task-interruption-presentation.ts`: in the `retry_scheduled` branch, `canRetry` is now also false when `run.status === "scheduled_retry"`. - `server/src/services/task-interruption-presentation.test.ts`: three tests for a scheduled transient-failure retry. - This branch is based on current `master` and includes #21200, which has not merged yet and changes the same file. The diff of this pull request against #21200 is one line and the tests. ## Verification - `cd server && npx vitest run src/services/task-interruption-presentation.test.ts -t "automatic scheduled retry"` - "shows a pending transient-failure retry as scheduled without a competing Retry": red on `master` (`canRetry: true`), green with this change. - "offers Retry once the scheduled retry is past due with nothing else pending": green before and after. - "offers Retry once the scheduled retries are exhausted": green before and after. - Locally: `task-interruption-presentation.test.ts`, `task-interruption-query.test.ts` and `task-interruption-automatic-path.test.ts` pass (107 tests). Server typecheck: 0 errors. The wider suites that read the presentation run in CI; they were not repeated locally because the machine was under memory pressure. ## Risks - Low risk. The change affects presentation only. The Retry route still accepts a click and coalesces it onto the scheduled run, as before. - If a scheduled retry never dispatches, the task offers Retry again once the retry time passes, as before this change. - No schema, API or UI change. ## Model Used - Claude Opus 5.5 (Anthropic), model ID `claude-opus-5-5`, used in Claude Code with tool use (shell, file edits, test execution). Extended reasoning was available. ## 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
6cb0dd0c6b
commit
d169dd5a90
3 files changed
+159
-3
No files matched your search
@@ -0,0 +1,108 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import { agents, agentWakeupRequests, applyPendingMigrations, companies, createDb, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS,
|
||||
heartbeatRuns, issueRecoveryActions, issues, nativeRunFinalizations } from "@paperclipai/db";
|
||||
import { taskInterruptionPresentation } from "../services/task-interruption-presentation.js";
|
||||
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
|
||||
import { resolveExternalTestDatabaseUrl } from "./helpers/external-test-database.js";
|
||||
|
||||
const externalDatabaseUrl = resolveExternalTestDatabaseUrl("PAPERCLIP_TASK_INTERRUPTION_TEST_DATABASE_URL");
|
||||
const support = externalDatabaseUrl ? { supported: true } : await getEmbeddedPostgresTestSupport();
|
||||
vi.mock("../sentry.js", () => ({ captureTaskInterruptionFailure: vi.fn() }));
|
||||
|
||||
describe.skipIf(!support.supported)("Retry is offered only when no automatic path exists", () => {
|
||||
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
|
||||
let db: ReturnType<typeof createDb>;
|
||||
beforeAll(async () => {
|
||||
if (externalDatabaseUrl) await applyPendingMigrations(externalDatabaseUrl);
|
||||
database = externalDatabaseUrl ? { connectionString: externalDatabaseUrl, cleanup: async () => {} }
|
||||
: await startEmbeddedPostgresTestDatabase("interruption-automatic-");
|
||||
db = createDb(database.connectionString);
|
||||
}, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS);
|
||||
afterAll(async () => { await db?.$client.end(); await database?.cleanup(); });
|
||||
|
||||
async function seedTask(status = "in_progress") {
|
||||
const companyId = randomUUID(), agentId = randomUUID();
|
||||
await db.insert(companies).values({ id: companyId, name: "Swap company", issuePrefix: `S${companyId.slice(0, 7)}` });
|
||||
await db.insert(agents).values({ id: agentId, companyId, name: "Swap agent", adapterType: "paperclip_runner" });
|
||||
const [issue] = await db.insert(issues).values({ companyId, title: "Work across a release swap",
|
||||
status, assigneeAgentId: agentId }).returning();
|
||||
return { companyId, agentId, issue: issue! };
|
||||
}
|
||||
|
||||
async function seedSwapEndedRun(finishedAt: Date) {
|
||||
const task = await seedTask();
|
||||
const runId = randomUUID();
|
||||
await db.insert(heartbeatRuns).values({ id: runId, companyId: task.companyId, agentId: task.agentId,
|
||||
nativeIssueId: task.issue.id, scopeKind: "issue", status: "failed", runtimeMode: "native",
|
||||
nativePhase: "terminal_failure", errorCode: "native_restart_recovery_blocked",
|
||||
error: "controller_process_space_unverified", startedAt: new Date(finishedAt.getTime() - 60_000), finishedAt });
|
||||
await db.insert(nativeRunFinalizations).values({ companyId: task.companyId, issueId: task.issue.id, runId,
|
||||
phase: "terminal_failure", attempt: 1, failureCode: "native_restart_recovery_blocked", recoveryState: "blocked" });
|
||||
const [hold] = await db.insert(issueRecoveryActions).values({ companyId: task.companyId, sourceIssueId: task.issue.id,
|
||||
kind: "active_run_watchdog", status: "active", ownerType: "system", returnOwnerAgentId: task.agentId,
|
||||
cause: "native_restart_recovery_blocked", fingerprint: `native-restart:${runId}`,
|
||||
evidence: { runId, reason: "controller_process_space_unverified", executorStopEvidence: "unverified", providerAttempt: 1 },
|
||||
nextAction: "The server running this task restarted. Paperclip continues the task in a fresh run from its saved work.",
|
||||
maxAttempts: 3, createdAt: finishedAt, updatedAt: finishedAt }).returning();
|
||||
return { ...task, runId, hold: hold! };
|
||||
}
|
||||
|
||||
it("shows a run ended by a release swap as working while its system hold awaits the automatic continuation", async () => {
|
||||
const { issue, runId } = await seedSwapEndedRun(new Date(Date.now() - 5_000));
|
||||
expect(await taskInterruptionPresentation(db, issue)).toMatchObject({ responsibility: "system", state: "working",
|
||||
canRetry: false, observedRunId: runId });
|
||||
});
|
||||
|
||||
it("still offers Retry when the system hold was not taken up by the continuation worker in time", async () => {
|
||||
const { issue } = await seedSwapEndedRun(new Date(Date.now() - 10 * 60_000));
|
||||
expect(await taskInterruptionPresentation(db, issue)).toMatchObject({ state: "failed", canRetry: true });
|
||||
});
|
||||
|
||||
it("still offers Retry once the continuation worker decided it cannot continue the task", async () => {
|
||||
const { issue, hold } = await seedSwapEndedRun(new Date(Date.now() - 5_000));
|
||||
await db.update(issueRecoveryActions).set({ evidence: { ...hold.evidence,
|
||||
freshContinuationCheck: { kind: "not_applicable", reason: "task_changed", checks: 1, checkedAt: Date.now(), nextCheckAt: null } } })
|
||||
.where(eq(issueRecoveryActions.id, hold.id));
|
||||
expect(await taskInterruptionPresentation(db, issue)).toMatchObject({ state: "failed", canRetry: true });
|
||||
});
|
||||
|
||||
it("still offers Retry when a person owns the hold", async () => {
|
||||
const { issue, hold, companyId } = await seedSwapEndedRun(new Date(Date.now() - 5_000));
|
||||
await db.update(issueRecoveryActions).set({ evidence: { ...hold.evidence, ownerGoneAttestation: { companyId } } })
|
||||
.where(eq(issueRecoveryActions.id, hold.id));
|
||||
expect(await taskInterruptionPresentation(db, issue)).toMatchObject({ state: "failed", canRetry: true });
|
||||
});
|
||||
|
||||
it("still offers Retry when recovery gave up and handed the hold to the board", async () => {
|
||||
const { issue, hold } = await seedSwapEndedRun(new Date(Date.now() - 5_000));
|
||||
await db.update(issueRecoveryActions).set({ ownerType: "board" }).where(eq(issueRecoveryActions.id, hold.id));
|
||||
expect(await taskInterruptionPresentation(db, issue)).toMatchObject({ state: "failed", canRetry: true });
|
||||
});
|
||||
|
||||
it("shows a healthy task as working while the message queued during its succeeded run is delivered", async () => {
|
||||
const { companyId, agentId, issue } = await seedTask();
|
||||
const runId = randomUUID(), finishedAt = new Date(Date.now() - 3_000);
|
||||
await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, nativeIssueId: issue.id, scopeKind: "issue",
|
||||
status: "succeeded", runtimeMode: "native", startedAt: new Date(Date.now() - 5 * 60_000), finishedAt });
|
||||
await db.insert(agentWakeupRequests).values({ companyId, agentId, source: "on_demand", reason: "issue_commented",
|
||||
status: "deferred_issue_execution", requestedByActorType: "user", requestedAt: new Date(Date.now() - 2 * 60_000),
|
||||
payload: { issueId: issue.id } });
|
||||
expect(await taskInterruptionPresentation(db, issue)).toMatchObject({ state: "working", canRetry: false });
|
||||
expect(await taskInterruptionPresentation(db, { ...issue, status: "in_review" })).toMatchObject({ state: "working", canRetry: false });
|
||||
expect(await taskInterruptionPresentation(db, { ...issue, status: "blocked" })).toMatchObject({ state: "failed", canRetry: true });
|
||||
await db.update(heartbeatRuns).set({ finishedAt: new Date(Date.now() - 10 * 60_000) }).where(eq(heartbeatRuns.id, runId));
|
||||
expect(await taskInterruptionPresentation(db, issue)).toMatchObject({ canRetry: true });
|
||||
});
|
||||
|
||||
it("does not offer Retry on a parent whose run succeeded and that waits for its subtasks", async () => {
|
||||
const { companyId, agentId, issue } = await seedTask();
|
||||
await db.insert(issues).values({ companyId, title: "Subtask", status: "in_progress", assigneeAgentId: agentId, parentId: issue.id });
|
||||
await db.insert(heartbeatRuns).values({ companyId, agentId, nativeIssueId: issue.id, scopeKind: "issue",
|
||||
status: "succeeded", runtimeMode: "native", finishedAt: new Date(Date.now() - 3_000) });
|
||||
await db.insert(agentWakeupRequests).values({ companyId, agentId, source: "automation", reason: "issue_children_completed",
|
||||
status: "queued", requestedByActorType: "system", payload: { issueId: issue.id } });
|
||||
expect(await taskInterruptionPresentation(db, issue)).toMatchObject({ canRetry: false });
|
||||
});
|
||||
});
|
||||
@@ -544,3 +544,25 @@ describe("native cleanup quarantine presentation", () => {
|
||||
paused: false, approval: false })).toMatchObject({ state: "failed", canRetry: true });
|
||||
});
|
||||
});
|
||||
|
||||
describe("automatic scheduled retry", () => {
|
||||
const now = Date.parse("2026-11-12T23:00:00Z");
|
||||
const scheduled = { ...run, status: "scheduled_retry", runtimeMode: "legacy", errorCode: null, resultJson: null,
|
||||
scheduledRetryReason: "transient_failure", scheduledRetryAt: new Date(now + 60_000) };
|
||||
|
||||
it("shows a pending transient-failure retry as scheduled without a competing Retry", () => {
|
||||
expect(projectTaskInterruption(issue, { run: scheduled, agent, paused: false, approval: false }, now))
|
||||
.toMatchObject({ state: "retry_scheduled", canRetry: false, nextRetryAt: new Date(now + 60_000).toISOString() });
|
||||
});
|
||||
|
||||
it("offers Retry once the scheduled retry is past due with nothing else pending", () => {
|
||||
expect(projectTaskInterruption(issue, { run: { ...scheduled, scheduledRetryAt: new Date(now - 10 * 60_000) }, agent,
|
||||
paused: false, approval: false }, now)).toMatchObject({ state: "failed", canRetry: true });
|
||||
});
|
||||
|
||||
it("offers Retry once the scheduled retries are exhausted", () => {
|
||||
expect(projectTaskInterruption(issue, { run: { ...scheduled, status: "failed", errorCode: "transient_failure_retry_exhausted",
|
||||
scheduledRetryAt: new Date(now - 60_000) }, agent, paused: false, approval: false }, now))
|
||||
.toMatchObject({ state: "failed", canRetry: true });
|
||||
});
|
||||
});
|
||||
@@ -7,7 +7,7 @@ import { nativeSessionCleanupBlock } from "../vendor/paperclip-runner/index.js";
|
||||
import { agents, agentWakeupRequests, approvals, chatActions, companies, environmentLeases, heartbeatRuns, issueApprovals, issueRecoveryActions,
|
||||
issues, issueTreeHoldMembers, issueTreeHolds, nativeRunFinalizations, projects, type Db } from "@paperclipai/db";
|
||||
import { unionAll } from "drizzle-orm/pg-core";
|
||||
import { HEARTBEAT_RUN_STATUSES, readProviderFailure, type TaskInterruptionPresentation } from "@paperclipai/shared";
|
||||
import { EXECUTION_RECONCILIATION_CAUSES, HEARTBEAT_RUN_STATUSES, readProviderFailure, type TaskInterruptionPresentation } from "@paperclipai/shared";
|
||||
import { captureTaskInterruptionFailure } from "../sentry.js";
|
||||
import { isAiAuthenticationBlocked } from "./ai-auth-failure.js";
|
||||
import { readSystemRecovery } from "./system-recovery-state.js";
|
||||
@@ -39,6 +39,8 @@ const NATIVE_RESUME_DISPATCH_GRACE_MS = 2 * 60_000;
|
||||
// A queued-message Interrupt waits for the stopped run's cleanup before its
|
||||
// successor starts. Past this, a hand-off that never started offers Retry.
|
||||
const QUEUED_INTERRUPT_HANDOFF_GRACE_MS = 5 * 60_000;
|
||||
const QUEUED_INPUT_DISPATCH_GRACE_MS = 2 * 60_000;
|
||||
const AUTOMATIC_DISPOSITION_GRACE_MS = 2 * 60_000;
|
||||
|
||||
type ProjectionIssue = Pick<typeof issues.$inferSelect, "id" | "companyId" | "status" | "assigneeAgentId" | "projectId">;
|
||||
type ProjectionRun = Pick<typeof heartbeatRuns.$inferSelect,
|
||||
@@ -92,6 +94,7 @@ type ProjectionState = {
|
||||
/** The fresh-continuation fallback is continuing this run's task (recorded,
|
||||
* not yet started) or will check it again at `nextCheckAt`. */
|
||||
freshContinuation?: { state: "continuing" } | { state: "scheduled"; nextCheckAt: number };
|
||||
automaticDispositionAt?: number;
|
||||
};
|
||||
|
||||
// A task read reports the change that made a task fail, not every later read of
|
||||
@@ -270,6 +273,9 @@ function projectTaskInterruptionState(issue: ProjectionIssue, input: ProjectionS
|
||||
if (input.freshContinuation?.state === "continuing") return { ...base, state: "working", canRetry: false };
|
||||
if (input.freshContinuation?.state === "scheduled" && input.freshContinuation.nextCheckAt > now)
|
||||
return { ...base, state: "retry_scheduled", nextRetryAt: new Date(input.freshContinuation.nextCheckAt).toISOString(), canRetry: false };
|
||||
if (input.automaticDispositionAt !== undefined && ["failed", "timed_out", "interrupted", "cancelled"].includes(run.status)
|
||||
&& now - Math.max(input.automaticDispositionAt, run.finishedAt?.getTime() ?? 0) < AUTOMATIC_DISPOSITION_GRACE_MS)
|
||||
return { ...base, state: "working", canRetry: false };
|
||||
const deniedProject = deniedProjectId(issue, run);
|
||||
let projectAccess: TaskInterruptionPresentation["projectAccess"];
|
||||
if (deniedProject !== undefined) {
|
||||
@@ -316,7 +322,7 @@ function projectTaskInterruptionState(issue: ProjectionIssue, input: ProjectionS
|
||||
: "Paperclip couldn’t confirm shutdown. Your work is saved; continuation is paused." } };
|
||||
}
|
||||
if (retryAt && retryAt > now) return { ...base, state: "retry_scheduled",
|
||||
nextRetryAt: new Date(retryAt).toISOString(), canRetry: !preparationPending && !nativeResumeAt,
|
||||
nextRetryAt: new Date(retryAt).toISOString(), canRetry: !preparationPending && !nativeResumeAt && run.status !== "scheduled_retry",
|
||||
...(system?.nextAttemptAt && recoveryStep ? { recoveryStep } : {}) };
|
||||
if (nativeResumeAt && !system && now - nativeResumeAt < NATIVE_RESUME_DISPATCH_GRACE_MS)
|
||||
return { ...base, state: "working" };
|
||||
@@ -337,7 +343,9 @@ function projectTaskInterruptionState(issue: ProjectionIssue, input: ProjectionS
|
||||
&& (reason !== "cleanup_quarantined" || !input.cleanupSettling), retryWait: { reason,
|
||||
message: retryWaitMessages[reason] ?? "Retry is waiting for execution checks. Your message is saved." } };
|
||||
}
|
||||
if (wait && wait.requestedAt.getTime() > now - 10_000 && system?.state !== "exhausted")
|
||||
const queuedDuringRun = Boolean(wait && run.status === "succeeded" && ["todo", "in_progress", "in_review"].includes(issue.status) && run.finishedAt && wait.requestedAt.getTime() <= run.finishedAt.getTime()
|
||||
&& now - run.finishedAt.getTime() < QUEUED_INPUT_DISPATCH_GRACE_MS);
|
||||
if (wait && (wait.requestedAt.getTime() > now - 10_000 || queuedDuringRun) && system?.state !== "exhausted")
|
||||
return { ...base, state: "working" };
|
||||
if (run.errorCode === NATIVE_SESSION_CLEANUP_QUARANTINED) {
|
||||
// The provider turn completed and its work is saved; only shutdown of the
|
||||
@@ -586,6 +594,23 @@ export async function taskInterruptionPresentations(db: Db, companyId: string, i
|
||||
.map(row => Number(row.nextCheckAt)).sort((a, b) => a - b)[0];
|
||||
return scheduled ? { state: "scheduled", nextCheckAt: scheduled } : undefined;
|
||||
};
|
||||
const dispositionRows = runIds.length ? await db.select({ issueId: issueRecoveryActions.sourceIssueId,
|
||||
runId: sql<string>`${issueRecoveryActions.evidence}->>'runId'`, updatedAt: issueRecoveryActions.updatedAt })
|
||||
.from(issueRecoveryActions).where(and(eq(issueRecoveryActions.companyId, companyId),
|
||||
inArray(issueRecoveryActions.sourceIssueId, ids), inArray(sql`${issueRecoveryActions.evidence}->>'runId'`, runIds),
|
||||
inArray(issueRecoveryActions.status, ["active", "escalated"]), eq(issueRecoveryActions.ownerType, "system"),
|
||||
inArray(issueRecoveryActions.cause, [...EXECUTION_RECONCILIATION_CAUSES]), isNull(issueRecoveryActions.ownerUserId),
|
||||
sql`not (${issueRecoveryActions.evidence} ?| array['systemRecovery', 'executionReconciliation', 'freshContinuation',
|
||||
'freshContinuationCheck', 'ownerGoneAttestation', 'explicitUserContinuation'])`)) : [];
|
||||
const automaticDispositionAt = new Map<string, number>();
|
||||
if (dispositionRows.length) {
|
||||
const { isPersonOwnedFailureCode } = await import("./fresh-continuation-fallback.js");
|
||||
for (const row of dispositionRows) {
|
||||
const run = runs.find(candidate => candidate.issueId === row.issueId && candidate.id === row.runId);
|
||||
if (!run || isPersonOwnedFailureCode(run.errorCode)) continue;
|
||||
automaticDispositionAt.set(row.issueId, Math.max(automaticDispositionAt.get(row.issueId) ?? 0, row.updatedAt.getTime()));
|
||||
}
|
||||
}
|
||||
const ownerStops = runIds.length ? await db.select({ issueId: issueRecoveryActions.sourceIssueId,
|
||||
runId: sql<string>`${issueRecoveryActions.evidence}->>'runId'` }).from(issueRecoveryActions).where(and(
|
||||
eq(issueRecoveryActions.companyId, companyId), inArray(issueRecoveryActions.sourceIssueId, ids),
|
||||
@@ -686,6 +711,7 @@ export async function taskInterruptionPresentations(db: Db, companyId: string, i
|
||||
retryWait: retryWaitMap.get(issue.id) };
|
||||
const presentation = projectTaskInterruption(issue, { ...facts,
|
||||
freshContinuation: freshContinuationFor(issue.id, facts.run?.id),
|
||||
automaticDispositionAt: automaticDispositionAt.get(issue.id),
|
||||
interruptWait: interruptWaitFor(issue.id),
|
||||
projectAccessAllowed: denied?.length === 0,
|
||||
projectAccessProjectId: denied?.includes(issue.projectId ?? "") ? issue.projectId : null,
|
||||
|
||||
Reference in new issue
Block a user