Files
PaperClipAI/server/src/services/pre-dispatch-execution-evidence.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

119 lines
7.9 KiB
TypeScript

import { and, eq, inArray, isNotNull, isNull, or, sql } from "drizzle-orm";
import { environmentLeases, heartbeatRunEvents, heartbeatRuns, issueRecoveryActions, nativeRunFinalizations } from "@paperclipai/db";
import { PROCESS_IDENTITY_RECORDED, PROCESS_START_REQUESTED } from "./native-local-process-stop.js";
import { LEGACY_WORKSPACE_RECOVERY_SCHEMA } from "./workspace-restore-recovery-state.js";
import { readRunCancellation } from "./run-cancellation.js";
import { EXECUTION_RECONCILIATION_CAUSES } from "@paperclipai/shared";
export function isPreDispatchResourceWait(run: Pick<typeof heartbeatRuns.$inferSelect,
"runtimeMode" | "status" | "errorCode" | "resultJson">): boolean {
const evidence = run.resultJson?.executionRecovery as Record<string, unknown> | undefined;
return run.runtimeMode === "legacy" && run.status === "cancelled" && evidence?.providerWorkStarted === false &&
(run.errorCode === "workspace_busy" && evidence.kind === "workspace_wait" ||
run.errorCode === "agent_directory_busy" && evidence.kind === "agent_directory_wait" ||
["ai_connection_busy", "ai_connection_pool_exhausted", "provider_limit_wait"].includes(run.errorCode ?? "") &&
evidence.kind === "ai_connection_wait");
}
export function isAgentDirectoryPreparationWait(run: Pick<typeof heartbeatRuns.$inferSelect,
"runtimeMode" | "status" | "errorCode" | "resultJson">): boolean {
const evidence = run.resultJson?.executionRecovery as Record<string, unknown> | undefined;
const cancellation = run.resultJson?.cancellation as Record<string, unknown> | undefined;
return run.runtimeMode === "legacy" && run.status === "cancelled" && run.errorCode === "agent_directory_busy"
&& evidence?.kind === "agent_directory_wait" && evidence.providerWorkStarted === false
&& cancellation?.source === "control_plane" && cancellation.expected === true;
}
export function agentDirectoryPreparationWaitPredicate() {
return sql`(${heartbeatRuns.runtimeMode} = 'legacy' and ${heartbeatRuns.status} = 'cancelled'
and ${heartbeatRuns.errorCode} = 'agent_directory_busy'
and ${heartbeatRuns.resultJson}#>>'{executionRecovery,kind}' = 'agent_directory_wait'
and ${heartbeatRuns.resultJson}#>'{executionRecovery,providerWorkStarted}' = 'false'::jsonb
and ${heartbeatRuns.resultJson}#>>'{cancellation,source}' = 'control_plane'
and ${heartbeatRuns.resultJson}#>'{cancellation,expected}' = 'true'::jsonb)`;
}
/** The control plane cancels a run that is still waiting, for example a
* scheduled retry superseded by a task change. This row check only selects a
* candidate cheaply; `unclaimedControlPlaneCancellationPredicate` (with the
* chain rule) plus `noRetainedExecutionPredicate` is the proof. */
export function isUnclaimedControlPlaneCancellationCandidate(run: Pick<typeof heartbeatRuns.$inferSelect,
"runtimeMode" | "status" | "errorCode" | "resultJson">): boolean {
const cancellation = readRunCancellation(run.resultJson);
return run.runtimeMode === "legacy" && run.status === "cancelled" && run.errorCode === "cancelled" &&
cancellation?.source === "control_plane" && cancellation.expected && cancellation.initiator.type === "system";
}
/** A retry continues its chain, so its own missing execution evidence is not
* enough. Terminalization records a reconciliation hold on any predecessor
* whose outcome is unknown, and the scheduler refuses to retry such a run.
* The chain is settled when the predecessor exists and carries no such hold
* that is still effective or was superseded. A row with retry metadata whose
* predecessor was deleted fails closed. Workspace-wait retries keep their own
* proof (`isCancelledNativeStartup`). */
export function settledRetryPredecessorPredicate() {
return sql`(case when ${heartbeatRuns.retryOfRunId} is null
then ${heartbeatRuns.scheduledRetryAttempt} = 0 and ${heartbeatRuns.scheduledRetryReason} is null
else coalesce(${heartbeatRuns.scheduledRetryReason}, '') <> 'workspace_busy'
and exists (select 1 from heartbeat_runs predecessor
where predecessor.company_id = ${heartbeatRuns.companyId} and predecessor.id = ${heartbeatRuns.retryOfRunId}
and predecessor.agent_id = ${heartbeatRuns.agentId} and predecessor.finished_at is not null)
and not exists (select 1 from ${issueRecoveryActions}
where ${issueRecoveryActions.companyId} = ${heartbeatRuns.companyId}
and coalesce(${issueRecoveryActions.evidence}->>'runId', ${issueRecoveryActions.evidence}->>'sourceRunId')
= ${heartbeatRuns.retryOfRunId}::text
and (${effectiveReconciliationHoldPredicate()}
-- A newer hold superseded this one; the predecessor's obligation was not settled.
or (${inArray(issueRecoveryActions.cause, [...EXECUTION_RECONCILIATION_CAUSES])}
and ${issueRecoveryActions.status} = 'cancelled' and ${issueRecoveryActions.outcome} = 'cancelled')))
end)`;
}
/** A reconciliation hold that still blocks execution: open, or resolved with
* automatic replay blocked. Shared by the task blocker and the retry-chain proof. */
export function effectiveReconciliationHoldPredicate() {
return and(
inArray(issueRecoveryActions.cause, [...EXECUTION_RECONCILIATION_CAUSES]),
or(inArray(issueRecoveryActions.status, ["active", "escalated"]),
sql`${issueRecoveryActions.evidence}->'automaticRecovery'->>'replay' = 'blocked'`),
)!;
}
/** SQL proof for `isUnclaimedControlPlaneCancellationCandidate`. Callers add
* `noRetainedExecutionPredicate` for the run's own execution evidence. */
export function unclaimedControlPlaneCancellationPredicate() {
return sql`(${heartbeatRuns.errorCode} = 'cancelled'
and ${heartbeatRuns.resultJson}#>>'{cancellation,source}' = 'control_plane'
and ${heartbeatRuns.resultJson}#>'{cancellation,expected}' = 'true'::jsonb
and ${heartbeatRuns.resultJson}#>>'{cancellation,initiator,type}' = 'system'
and ${settledRetryPredecessorPredicate()})`;
}
export function executionStartedEventPredicate() {
return or(isNotNull(heartbeatRunEvents.sourceEventId), inArray(heartbeatRunEvents.eventType,
["adapter.invoke", PROCESS_START_REQUESTED, PROCESS_IDENTITY_RECORDED, "harness.ready", "session.started",
"session.resumed", "session.updated", "turn.started", "provider.event", "provider.rpc_result", "tool.execution.started"]));
}
/** Both dispatch cancellation policies require this same retained-evidence
* proof. Each caller still owns its terminal status and admission receipt. */
export function noRetainedExecutionPredicate() {
return and(
isNull(heartbeatRuns.startedAt), isNull(heartbeatRuns.runtimeModeResolvedAt),
isNull(heartbeatRuns.processPid), isNull(heartbeatRuns.processGroupId), isNull(heartbeatRuns.processStartedAt),
isNull(heartbeatRuns.nativeIssueId), isNull(heartbeatRuns.nativeSessionId), isNull(heartbeatRuns.sessionIdAfter),
isNull(heartbeatRuns.controllerBootId), isNull(heartbeatRuns.controllerLeaseExpiresAt), isNull(heartbeatRuns.executionStage),
sql`coalesce(${heartbeatRuns.resultJson}->>'workspaceRestoreFailure', '') <> 'restore_unsafe_archive'`,
sql`coalesce(${heartbeatRuns.resultJson}->'workspaceRestoreRecovery'->>'schema', '') <> ${LEGACY_WORKSPACE_RECOVERY_SCHEMA}`,
sql`not (coalesce(${heartbeatRuns.runnerProfileJson}, '{}'::jsonb) ?| array[
'nativeExecutionInput', 'nativeWorkspaceSync', 'remoteWorkspace', 'nativeWorkspaceFinalizationOwner', 'sessionCheckpoint'])`,
sql`not exists (select 1 from ${nativeRunFinalizations}
where ${nativeRunFinalizations.companyId} = ${heartbeatRuns.companyId} and ${nativeRunFinalizations.runId} = ${heartbeatRuns.id})`,
sql`not exists (select 1 from ${environmentLeases}
where ${environmentLeases.companyId} = ${heartbeatRuns.companyId} and ${environmentLeases.heartbeatRunId} = ${heartbeatRuns.id})`,
sql`not exists (select 1 from ${heartbeatRunEvents}
where ${and(eq(heartbeatRunEvents.companyId, heartbeatRuns.companyId),
eq(heartbeatRunEvents.runId, heartbeatRuns.id), executionStartedEventPredicate())})`,
);
}