Files
PaperClipAI/server/src/services/pre-dispatch-review-wait.ts
T
DottaandClaude Opus 5.5 50cee0cb8f fix(recovery): do not hold a task for a retry cancelled before it started (#22262)
## 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>
2026-11-23 07:49:59 -06:00

102 lines
6.3 KiB
TypeScript

import { and, eq, inArray, isNotNull, or } from "drizzle-orm";
import { environmentLeases, heartbeatRunEvents, heartbeatRuns, nativeRunFinalizations, type Db } from "@paperclipai/db";
import { hasRemoteTerminationReceipt } from "./remote-execution-termination.js";
import { hasRequiredWorkspaceRecovery } from "./workspace-restore-recovery-state.js";
import { executionStartedEventPredicate, isUnclaimedControlPlaneCancellationCandidate, noRetainedExecutionPredicate,
unclaimedControlPlaneCancellationPredicate } from "./pre-dispatch-execution-evidence.js";
import type { QueuedRunStalenessErrorCode } from "../modules/run-dispatch/index.js";
type Run = typeof heartbeatRuns.$inferSelect;
type DispatchFields = "startedAt" | "runtimeModeResolvedAt" | "processPid" | "processGroupId" |
"processStartedAt" | "nativeIssueId" | "nativeSessionId" | "sessionIdAfter" |
"controllerBootId" | "controllerLeaseExpiresAt" | "executionStage" | "contextSnapshot";
const staleDispatchReconciliationExemptions = {
issue_not_found: true,
issue_not_in_progress: true,
issue_assignee_changed: true,
issue_waiting_for_response: true,
issue_continuation_waiting_on_review: true,
issue_dependencies_blocked: true,
issue_blocked: true,
issue_execution_lock_changed: true,
issue_terminal_status: true,
issue_review_participant_changed: true,
issue_in_backlog: true,
// This code requires its own executionWait receipt in pre-dispatch-execution-wait.ts.
execution_reconciliation_required: false,
} satisfies Record<QueuedRunStalenessErrorCode, boolean>;
const staleDispatchErrorCodes = Object.entries(staleDispatchReconciliationExemptions)
.filter(([, exempt]) => exempt).map(([errorCode]) => errorCode);
/** A dispatch cancellation is not an interrupted provider attempt. Historical
* rows need no new receipt, but every retained execution reference must agree. */
export function neverStartedDispatchCancellationPredicate() {
return and(
eq(heartbeatRuns.runtimeMode, "legacy"), eq(heartbeatRuns.status, "cancelled"),
or(inArray(heartbeatRuns.errorCode, staleDispatchErrorCodes), unclaimedControlPlaneCancellationPredicate()),
isNotNull(heartbeatRuns.finishedAt),
noRetainedExecutionPredicate(),
);
}
/** The queued-run gate owns this receipt before execution authority is claimed.
* A deliberate review or connection response wait has no provider actions to reconcile. The error code
* alone is not proof; missing or conflicting dispatch evidence retains the hold. */
export function isPreDispatchReviewWait(
run: Pick<Run, "runtimeMode" | "status" | "errorCode" | "resultJson"> & Partial<Pick<Run, DispatchFields>>,
): boolean {
const finalResponseWait = run.errorCode === "issue_waiting_for_response" &&
(run.resultJson?.preDispatchResponseWait as { version?: number; providerWorkStarted?: boolean } | undefined)?.version === 1 &&
(run.resultJson?.preDispatchResponseWait as { providerWorkStarted?: boolean } | undefined)?.providerWorkStarted === false;
return run.runtimeMode === "legacy" && run.status === "cancelled" &&
(run.errorCode === "issue_continuation_waiting_on_review" ||
(run.errorCode === "issue_waiting_for_response" &&
run.contextSnapshot?.connectionIntentResolution === "existing_connection" &&
run.contextSnapshot?.source === "connection_intent.resolved" &&
run.contextSnapshot?.interactionKind === "connection_intent" &&
run.contextSnapshot?.interactionStatus === "expired" &&
run.contextSnapshot?.mutation === "interaction" &&
typeof run.contextSnapshot?.interactionId === "string")) &&
run.resultJson?.stopReason === run.errorCode &&
run.resultJson?.timeoutSource === "stale_queued_run_gate" &&
run.resultJson?.workspaceRestoreFailure !== "restore_unsafe_archive" &&
(finalResponseWait || (run.startedAt === null && run.runtimeModeResolvedAt === null)) &&
run.processPid === null && run.processGroupId === null && run.processStartedAt === null &&
run.nativeIssueId === null && run.nativeSessionId === null && run.sessionIdAfter === null &&
(finalResponseWait || (run.controllerBootId === null && run.controllerLeaseExpiresAt === null && run.executionStage === null));
}
/** The row receipt is a candidate, not permission to discard conflicting
* retained execution or cleanup evidence. Historical false holds must be
* checked against the same evidence that gates explicit user admission. */
export async function isPreDispatchReviewWaitVerified(db: Db, run: Run): Promise<boolean> {
if (run.runtimeMode === "legacy" && run.status === "cancelled" && run.finishedAt !== null &&
(staleDispatchErrorCodes.some(errorCode => errorCode === run.errorCode) || isUnclaimedControlPlaneCancellationCandidate(run)) &&
[run.startedAt, run.runtimeModeResolvedAt, run.processPid, run.processGroupId, run.processStartedAt,
run.nativeIssueId, run.nativeSessionId, run.sessionIdAfter, run.controllerBootId,
run.controllerLeaseExpiresAt, run.executionStage].every(value => value === null) &&
run.resultJson?.workspaceRestoreFailure !== "restore_unsafe_archive" && !hasRequiredWorkspaceRecovery(run.resultJson)) {
const [unstarted] = await db.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(and(
eq(heartbeatRuns.companyId, run.companyId), eq(heartbeatRuns.id, run.id), neverStartedDispatchCancellationPredicate(),
)).limit(1);
if (unstarted) return true;
}
if (!isPreDispatchReviewWait(run)) return false;
const [coordinator] = await db.select({ id: nativeRunFinalizations.runId }).from(nativeRunFinalizations).where(and(
eq(nativeRunFinalizations.companyId, run.companyId), eq(nativeRunFinalizations.runId, run.id),
)).limit(1);
if (coordinator) return false;
const leases = await db.select().from(environmentLeases).where(and(
eq(environmentLeases.companyId, run.companyId), eq(environmentLeases.heartbeatRunId, run.id),
));
if (leases.some(lease => lease.provider === "local"
? !lease.releasedAt || lease.status === "pending_cleanup" || lease.cleanupStatus === "failed"
: !hasRemoteTerminationReceipt(lease))) return false;
const [execution] = await db.select({ id: heartbeatRunEvents.id }).from(heartbeatRunEvents).where(and(
eq(heartbeatRunEvents.companyId, run.companyId), eq(heartbeatRunEvents.runId, run.id),
executionStartedEventPredicate(),
)).limit(1);
return !execution;
}