mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-30 17:14:54 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The heartbeat service holds a task for reconciliation when a legacy run stops and Paperclip cannot tell which of its actions took effect > - A task moved to backlog while its automatic retry still waited for its scheduled time. The control plane cancelled that retry before anyone claimed it > - The cancelled retry had no start time, stage, process, lease or execution events. It still got an "unknown outcome" hold, because its chain had already spent two failure retries > - After that, every wake was refused with `execution_reconciliation_required`, and Retry could not clear the hold. The rule is that a Retry button that is shown must work > - This pull request treats an unclaimed control-plane cancellation like the other never-started dispatch cancellations > - The benefit is that the task continues on its next wake or Retry, and tasks that are already stuck recover without manual work ## Linked Issues or Issue Description Refs #20752 (related: it hardens the `queued` cancel marker; it does not cover a cancelled `scheduled_retry`) **What happened?** A task had a pending scheduled retry (status `scheduled_retry`, never started). The task moved to backlog, and the control plane cancelled the retry (`errorCode: "cancelled"`, cancellation `source: control_plane`, `expected: true`, initiator `system`). The chain had `executionRetryAccounting.failureRetries = 2`. Terminalization recorded a `legacy_execution_requires_reconciliation` hold with automatic replay blocked. When the task moved back to todo, each new run was cancelled before it started with `execution_reconciliation_required`. The task showed `canRetry: false`, and a Retry press did not start a run or clear the hold. **Steps to reproduce** 1. Give a legacy-runtime agent a task with a pending `scheduled_retry` run whose chain has spent two failure retries. 2. Move the task to backlog. The control plane cancels the pending retry with `expectedStatus: "scheduled_retry"`. 3. Move the task to todo, then press Retry. **Expected behavior** The cancelled retry never ran, so there is nothing to reconcile. The next wake or Retry starts a fresh run. **Actual behavior** The task stays held. Every wake is refused, and Retry does not start a run. ## What Changed - Root cause 1: cancelling a never-started run stamps "no provider work" evidence only when its status was `queued`, not `scheduled_retry`. - Root cause 2: `legacyExecutionNeedsReconciliation` returns "hold" when the chain has two or more failure retries, before it reads any no-provider-work evidence. - `neverStartedDispatchCancellationPredicate` (and its synchronous pre-check in `isPreDispatchReviewWaitVerified`) now also accepts an expected system `control_plane` cancellation with `errorCode = "cancelled"`. It requires the same retained-execution proof as the dispatch-gate cancellations. A retry also needs a settled predecessor (`settledRetryPredecessorPredicate`). Terminalization records a reconciliation hold on a predecessor whose outcome is unknown, and the scheduler does not retry such a run. So the predecessor must exist and carry no effective or superseded reconciliation hold. A row with retry metadata whose predecessor was deleted fails closed. Workspace-wait chains keep their dedicated proof. The candidate check reads the cancellation with `readRunCancellation`; the SQL predicate in `pre-dispatch-execution-evidence.ts` is the single proof. - The same predicate is used at terminalization (no new hold) and in `executionBlockerPredicate` (a hold that an earlier release recorded no longer blocks). Tasks that are already stuck therefore recover on their next wake or Retry. The audit row is kept. - `doc/heartbeat-internals.md` documents the rule. ## Verification - New `server/src/__tests__/never-started-retry-cancellation-hold.test.ts`: - backlog cancel of a pending retry (real `cancelRun` with `expectedStatus: "scheduled_retry"`) → no hold → todo → Retry queues a fresh run, and the dispatch gate sees no blocker; - a hold recorded by an earlier release plus a refused todo run → Retry queues a fresh run, and the blocker clears; - the hold stays when the cancelled retry shows a start time, a process, a stage, an execution event, or an unexpected cancellation, or when its predecessor is held or was deleted. The main case runs with three real chains: a transient failure before provider work, an `ai_connection_busy` wait, and an environment wait after a succeeded run. - Red/green: without the fix, the first two cases fail (the blocker shows `canRetry: false` and "Automatic recovery stopped…"). With the fix, all 11 cases pass (4 fail without it). - Related suites pass: `explicit-native-continuation`, `task-retry`, `legacy-execution-recovery`, `heartbeat-undispatched-execution-wait`, `issue-scheduled-retry-routes`, `execution-blocker-read`, `legacy-continuation-authority` (728 tests across 8 suites). - `pnpm typecheck` in `server/` passes. - Note: 7 tests in `chat-channels.integration.test.ts` ("reconciled chat retry delivery ownership") fail locally when the full file runs, on unmodified `master` too. A continuation from an earlier test in the shared database leaks into their global delivery sweep. They pass when run alone. This change does not cause them. ## Risks - Low risk. The exemption needs all of these: a legacy run; `cancelled` status with `errorCode = "cancelled"`; an expected system `control_plane` cancellation; no retained execution evidence (start, stage, controller, process, session, lease, finalization or execution events); and, for a retry, a predecessor that still exists and has no reconciliation hold. Operator Stops, failed predecessors and runs with any execution evidence keep today's behavior. - No migration. Historical holds are kept as audit rows. They only stop blocking. - Not covered here: a retry cancelled while its predecessor failed with unknown outcomes keeps its hold. That case needs a separate decision about where Retry should anchor. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude Code with tool use (shell, file edits, test runs) and extended reasoning. ## 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>
184 lines
13 KiB
TypeScript
184 lines
13 KiB
TypeScript
import { randomUUID } from "node:crypto";
|
|
import { and, eq, inArray } from "drizzle-orm";
|
|
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
|
import {
|
|
agentWakeupRequests, agents, companies, createDb, heartbeatRunEvents, heartbeatRuns, issueRecoveryActions, issues,
|
|
} from "@paperclipai/db";
|
|
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
|
|
import { getExecutionBlocker } from "../services/execution-blocker.js";
|
|
import { heartbeatService } from "../services/heartbeat.js";
|
|
import { requestTaskRetry } from "../services/task-retry.js";
|
|
|
|
// A task moved to backlog while its automatic retry was still waiting for its
|
|
// scheduled time. The control plane cancels that retry before it ever starts,
|
|
// so no action of it can have taken effect. Moving the task back to todo and
|
|
// pressing Retry must continue the task, not leave it held for reconciliation.
|
|
const support = await getEmbeddedPostgresTestSupport();
|
|
(support.supported ? describe : describe.skip)("a pending retry cancelled before it started", () => {
|
|
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
|
|
let db: ReturnType<typeof createDb>;
|
|
beforeAll(async () => {
|
|
database = await startEmbeddedPostgresTestDatabase("never-started-retry-cancellation-");
|
|
db = createDb(database.connectionString);
|
|
}, 90_000);
|
|
afterAll(async () => { await db?.$client.end({ timeout: 1 }); await database?.cleanup(); });
|
|
|
|
// The scheduler retries only a run that needs no reconciliation: a transient
|
|
// failure before provider work, a resource wait it cancelled itself, or (as
|
|
// in the reported incident) an environment wait after a run that succeeded.
|
|
async function seed(predecessor: "failed_before_provider_work" | "succeeded" | "ai_connection_wait" = "failed_before_provider_work") {
|
|
const companyId = randomUUID(), agentId = randomUUID(), issueId = randomUUID();
|
|
const sourceRunId = randomUUID(), retryRunId = randomUUID(), wakeupRequestId = randomUUID();
|
|
const now = Date.now();
|
|
const retryReason = { failed_before_provider_work: "transient_failure", succeeded: "native_environment_blocker",
|
|
ai_connection_wait: "ai_connection_busy" }[predecessor];
|
|
await db.insert(companies).values({ id: companyId, name: "Backlog retry", defaultResponsibleUserId: "board",
|
|
issuePrefix: "B" + companyId.replaceAll("-", "").slice(0, 8) });
|
|
await db.insert(agents).values({ id: agentId, companyId, name: "Worker", role: "engineer",
|
|
adapterType: "paperclip_runner", status: "idle", runtimeConfig: { heartbeat: { maxConcurrentRuns: 1 } } });
|
|
await db.insert(issues).values({ id: issueId, companyId, title: "Answer the customer", status: "in_progress",
|
|
assigneeAgentId: agentId });
|
|
await db.insert(heartbeatRuns).values({ id: sourceRunId, companyId, agentId, issueId, runtimeMode: "legacy",
|
|
startedAt: new Date(now - 120_000), finishedAt: new Date(now - 90_000),
|
|
createdAt: new Date(now - 120_000), contextSnapshot: { issueId },
|
|
...(predecessor === "succeeded" ? { status: "succeeded" }
|
|
: predecessor === "ai_connection_wait" ? { status: "cancelled", errorCode: "ai_connection_busy",
|
|
resultJson: { executionRecovery: { kind: "ai_connection_wait", providerWorkStarted: false } } }
|
|
: { status: "failed", errorCode: "adapter_failed",
|
|
resultJson: { executionRecovery: { kind: "bootstrap", providerWorkStarted: false } } }) });
|
|
// The scheduler's placeholder: it only waits for its time and has never
|
|
// been claimed, so it has no process, lease, stage or execution events.
|
|
// Its chain has already spent two automatic retries.
|
|
await db.insert(agentWakeupRequests).values({ id: wakeupRequestId, companyId, agentId, source: "automation",
|
|
triggerDetail: "system", reason: "bounded_transient_heartbeat_retry", status: "queued",
|
|
payload: { issueId, retryOfRunId: sourceRunId } });
|
|
await db.insert(heartbeatRuns).values({ id: retryRunId, companyId, agentId, issueId, runtimeMode: "legacy",
|
|
invocationSource: "automation", triggerDetail: "system", status: "scheduled_retry", wakeupRequestId,
|
|
retryOfRunId: sourceRunId, scheduledRetryAt: new Date(now + 60_000), scheduledRetryAttempt: 2,
|
|
scheduledRetryReason: retryReason, createdAt: new Date(now - 60_000),
|
|
contextSnapshot: { issueId, retryOfRunId: sourceRunId, retryReason, scheduledRetryAttempt: 2,
|
|
executionRetryAccounting: { version: 1, failureRetries: 2, maxTurnContinuations: 0 } } });
|
|
await db.update(agentWakeupRequests).set({ runId: retryRunId }).where(eq(agentWakeupRequests.id, wakeupRequestId));
|
|
await db.update(issues).set({ executionRunId: retryRunId, executionLockedAt: new Date(now - 60_000) })
|
|
.where(eq(issues.id, issueId));
|
|
return { companyId, agentId, issueId, sourceRunId, retryRunId };
|
|
}
|
|
|
|
/** The task moved to backlog: the control plane cancels its pending retry
|
|
* with the same call the issue route makes for a superseded scheduled retry. */
|
|
async function moveToBacklog(f: Awaited<ReturnType<typeof seed>>) {
|
|
await db.update(issues).set({ status: "backlog" }).where(eq(issues.id, f.issueId));
|
|
const cancelled = await heartbeatService(db).cancelRun(f.retryRunId, undefined, { expectedStatus: "scheduled_retry" });
|
|
expect(cancelled).toMatchObject({ status: "cancelled", startedAt: null });
|
|
}
|
|
|
|
const holds = (issueId: string) => db.select().from(issueRecoveryActions).where(and(
|
|
eq(issueRecoveryActions.sourceIssueId, issueId), eq(issueRecoveryActions.cause, "legacy_execution_requires_reconciliation")));
|
|
|
|
it.each(["failed_before_provider_work", "succeeded", "ai_connection_wait"] as const)(
|
|
"does not hold the task for reconciliation, so todo and Retry continue it (predecessor %s)", async predecessor => {
|
|
const f = await seed(predecessor);
|
|
await moveToBacklog(f);
|
|
// Red before the fix: an unverified-outcome hold named the cancelled retry.
|
|
expect(await getExecutionBlocker(db, f.companyId, f.issueId)).toBeNull();
|
|
expect((await holds(f.issueId)).filter(hold => hold.status !== "resolved" ||
|
|
(hold.evidence.automaticRecovery as Record<string, unknown> | undefined)?.replay === "blocked")).toEqual([]);
|
|
|
|
// Back to todo, then Retry. Keep the agent busy so the new run stays
|
|
// queued instead of launching a provider in this test.
|
|
await db.update(issues).set({ status: "todo", executionRunId: null, executionLockedAt: null })
|
|
.where(eq(issues.id, f.issueId));
|
|
const [busy] = await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId,
|
|
status: "running" }).returning();
|
|
const receipt = await requestTaskRetry({ db, companyId: f.companyId, issueId: f.issueId, actorId: "board",
|
|
actorSource: "local_implicit", observedRunId: f.retryRunId, idempotencyKey: randomUUID() });
|
|
expect(receipt).toMatchObject({ accepted: true, observedRunId: f.retryRunId });
|
|
await heartbeatService(db).resumeTaskRetry(f.companyId, receipt.requestId!);
|
|
const queued = await db.select().from(heartbeatRuns).where(and(
|
|
eq(heartbeatRuns.companyId, f.companyId), eq(heartbeatRuns.status, "queued")));
|
|
expect(queued).toHaveLength(1);
|
|
expect((await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, receipt.requestId!)))[0])
|
|
.toMatchObject({ status: "coalesced", runId: queued[0].id });
|
|
// The dispatch gate reads this same blocker when the agent becomes free.
|
|
await db.update(heartbeatRuns).set({ status: "succeeded", finishedAt: new Date() }).where(eq(heartbeatRuns.id, busy.id));
|
|
expect(await getExecutionBlocker(db, f.companyId, f.issueId)).toBeNull();
|
|
});
|
|
|
|
it("releases a hold an earlier release recorded, so Retry starts a fresh run", async () => {
|
|
const f = await seed();
|
|
await moveToBacklog(f);
|
|
// The state tasks were left in before the fix: an automatic no-replay
|
|
// hold on the cancelled retry, and the todo wake refused behind it.
|
|
const [hold] = await db.insert(issueRecoveryActions).values({ companyId: f.companyId, sourceIssueId: f.issueId,
|
|
kind: "active_run_watchdog", cause: "legacy_execution_requires_reconciliation",
|
|
fingerprint: `legacy-execution:${f.retryRunId}`, status: "resolved", outcome: "blocked", ownerType: "board",
|
|
nextAction: "Automatic recovery stopped.",
|
|
evidence: { runId: f.retryRunId, originalFailureCode: "cancelled", adapterRecovery: "unsupported_or_unknown", attempt: 3,
|
|
automaticRecovery: { policy: "preserve_without_replay_v1", runId: f.retryRunId, replay: "blocked", actionOutcome: "unknown" } },
|
|
}).returning();
|
|
await db.update(issues).set({ status: "todo", executionRunId: null, executionLockedAt: null })
|
|
.where(eq(issues.id, f.issueId));
|
|
const [refused] = await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId,
|
|
issueId: f.issueId, runtimeMode: "legacy", status: "cancelled", errorCode: "execution_reconciliation_required",
|
|
finishedAt: new Date(), contextSnapshot: { issueId: f.issueId },
|
|
resultJson: { stopReason: "execution_reconciliation_required", timeoutSource: "stale_queued_run_gate",
|
|
timeoutFired: false, timeoutConfigured: false, effectiveTimeoutSec: 0,
|
|
executionWait: { issueId: f.issueId, recoveryActionId: hold.id } } }).returning();
|
|
|
|
expect(await getExecutionBlocker(db, f.companyId, f.issueId)).toBeNull();
|
|
const [busy] = await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId,
|
|
status: "running" }).returning();
|
|
const receipt = await requestTaskRetry({ db, companyId: f.companyId, issueId: f.issueId, actorId: "board",
|
|
actorSource: "local_implicit", observedRunId: refused.id, idempotencyKey: randomUUID() });
|
|
expect(receipt).toMatchObject({ accepted: true, observedRunId: refused.id });
|
|
await heartbeatService(db).resumeTaskRetry(f.companyId, receipt.requestId!);
|
|
const queued = await db.select().from(heartbeatRuns).where(and(
|
|
eq(heartbeatRuns.companyId, f.companyId), eq(heartbeatRuns.status, "queued")));
|
|
expect(queued).toHaveLength(1);
|
|
await db.update(heartbeatRuns).set({ status: "succeeded", finishedAt: new Date() }).where(eq(heartbeatRuns.id, busy.id));
|
|
expect(await getExecutionBlocker(db, f.companyId, f.issueId)).toBeNull();
|
|
// The audit row is kept; it no longer blocks execution.
|
|
expect((await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, hold.id)))[0])
|
|
.toMatchObject({ status: "resolved", outcome: "blocked" });
|
|
});
|
|
|
|
it.each(["started", "process", "stage", "execution_event", "unexpected_cancellation", "predecessor_superseded", "predecessor_blocked", "predecessor_deleted"] as const)(
|
|
"keeps the hold when the cancelled retry shows it may have run: %s", async evidence => {
|
|
const f = await seed();
|
|
await moveToBacklog(f);
|
|
// The retry continues its chain: a predecessor with its own unknown
|
|
// outcome, or one that is gone, keeps the hold on the retry too.
|
|
if (evidence === "predecessor_superseded" || evidence === "predecessor_blocked") await db.insert(issueRecoveryActions).values({
|
|
companyId: f.companyId, sourceIssueId: f.issueId, kind: "active_run_watchdog",
|
|
cause: "legacy_execution_requires_reconciliation", fingerprint: `legacy-execution:${f.sourceRunId}`, ownerType: "board",
|
|
...(evidence === "predecessor_superseded"
|
|
? { status: "cancelled", outcome: "cancelled", nextAction: "Superseded by a newer hold.", evidence: { runId: f.sourceRunId } }
|
|
: { status: "resolved", outcome: "blocked", nextAction: "Automatic recovery stopped.",
|
|
evidence: { runId: f.sourceRunId, automaticRecovery: { replay: "blocked", actionOutcome: "unknown" } } }) });
|
|
else if (evidence === "predecessor_deleted") await db.update(heartbeatRuns).set({ retryOfRunId: null })
|
|
.where(eq(heartbeatRuns.id, f.retryRunId));
|
|
else if (evidence === "execution_event") await db.insert(heartbeatRunEvents).values({ companyId: f.companyId,
|
|
agentId: f.agentId, runId: f.retryRunId, seq: 1000, eventType: "tool.execution.started" });
|
|
else {
|
|
const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.retryRunId));
|
|
await db.update(heartbeatRuns).set({
|
|
...(evidence === "started" ? { startedAt: new Date() } : {}),
|
|
...(evidence === "process" ? { processPid: 999_999 } : {}),
|
|
...(evidence === "stage" ? { executionStage: "preparing" } : {}),
|
|
...(evidence === "unexpected_cancellation" ? { resultJson: { ...run.resultJson,
|
|
cancellation: { ...(run.resultJson?.cancellation as Record<string, unknown>), expected: false } } } : {}),
|
|
}).where(eq(heartbeatRuns.id, f.retryRunId));
|
|
}
|
|
const [hold] = await db.insert(issueRecoveryActions).values({ companyId: f.companyId, sourceIssueId: f.issueId,
|
|
kind: "active_run_watchdog", cause: "legacy_execution_requires_reconciliation",
|
|
fingerprint: `legacy-execution:${f.retryRunId}`, status: "resolved", outcome: "blocked", ownerType: "board",
|
|
nextAction: "Automatic recovery stopped.",
|
|
evidence: { runId: f.retryRunId, automaticRecovery: { replay: "blocked", actionOutcome: "unknown" } } }).returning();
|
|
// The task stays held (by the retry's hold, or by the predecessor's own one).
|
|
expect(await getExecutionBlocker(db, f.companyId, f.issueId))
|
|
.toMatchObject({ cause: "legacy_execution_requires_reconciliation" });
|
|
expect(await holds(f.issueId)).toContainEqual(expect.objectContaining({ id: hold.id }));
|
|
await db.delete(issueRecoveryActions).where(inArray(issueRecoveryActions.id, [hold.id]));
|
|
});
|
|
});
|