Files
PaperClipAI/server/src/services/cancelled-native-startup.ts
T
DottaandPaperclip 2518ac85ab fix(recovery): continue verified failed native preparation (#18908)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Task Retry keeps a durable request while the system stops old work
and saves its files.
> - Native preparation can fail after it allocates a workspace, but
before it starts a provider.
> - Completed preservation can resolve the action while the original
Retry still waits.
> - The old classifier rejected every allocated failed preparation. The
source check also returned before its canonical Retry fallback.
> - This pull request accepts only complete server proof and moves the
existing exact-source fallback before that return.
> - The same Retry can then start one normal continuation. Current
access and unknown execution still hold work.
> - Saving files and admitting that continuation must use the same
parent-row lock order; the composed head includes the supporting
preservation fix.

## Linked Issues or Issue Description

**What happened?**

Task Retry accepted a failed native preparation and saved its request.
The workspace had complete preservation and stop receipts. The request
still waited for execution recovery and created no continuation.

**Expected behavior**

The same deliberate Retry must continue after the system verifies all
saved files and source leases. It must preserve current task, actor,
repository, Stop and execution checks.

**Steps to reproduce**

1. Record a native-adapter claim that fails during unresolved legacy
preparation, before provider execution.
2. Finish real workspace preservation and exact lease cleanup.
3. Submit normal HTTP task Retry and reconcile its canonical request.
4. On the base commit, no run is linked to that request. With this
change, one continuation is linked to it.

**Paperclip version or commit**

Reproduced on master `d7283e875772ca8c684dc86e471e6b48d543b7b1`.

**Deployment mode**

Source checkout with real local PostgreSQL and filesystem archives.
Object storage, sandbox transport and the native provider backend are
controlled in the final execution test. This is not a live model or
hosted object-storage claim.

**Prerequisite: #18918** at `4c1d7769e6cfa9536a67c4e3b536cef155f19966`.
This head includes that parent through normal history-preserving merges
while retaining `master` as its target. The parent owns remote workspace
save, prepare and provision lock order, legacy import reservation and
publication, their concurrency regressions, and the database lock-order
documentation. Merge the parent before this PR; no deployment is
implied.

Related: Refs #18892 for interrupted preparation. Refs #18882 for the
separate connected-chat setup path. Refs #18898 for already-admitted
cleanup waits. This change does not depend on #18882 or #18898.

## What Changed

- Accept allocated failed preparation only with the server error and
durable settlement records, no
execution/session/checkpoint/output/result/coordinator evidence, all
exact remote source leases stopped, and verified saved workspace proof.
- Recognize only the host's closed accounting scope and typed
pre-provider unsupported-harness warning. Unknown accounting, provider
metrics and arbitrary diagnostics remain holds.
- Check the canonical failed-preparation source before an empty
resolved-action list can return. Reuse the normal locked continuation
checks.
- Add HTTP, preservation-worker and native execution coverage, including
source failures produced by real heartbeat workspace preparation. Keep
one canonical request and one provider turn. Preserve the original
failure and real archive files.
- Restore storage, environment and experimental settings even if native
test setup or owned async cleanup fails.
- Cover changed Stop, source, actor, controller, provider evidence,
snapshot generation, writer and lease receipts. Keep current
unavailable-catalog denial before provider startup.
- Share one bounded host-settlement receipt reader between failed-native
preparation and existing-directory readiness. Keep each caller's
accounting, profile and additional warning restrictions.
- Include parent #18918's company/task/run-before-workspace ordering for
save, prepare and provision. Keep legacy import publication out of
reverse native-owner waits with exact NOWAIT refusal. Retain foreign
keys, ownership checks, uploaded work and transaction-aware
notifications.
- Document the failed-preparation continuation and parent lock-order
contracts.

## Verification

- Causal base comparison: the normal HTTP/preservation regression fails
on the canonical request's missing successor. Both existing
interrupted-preparation controls pass; the same cases pass with the
classifier/fallback repair.
- Actual heartbeat-produced catalog failures reproduce RED before the
host-accounting fix, both with and without the real typed
unsupported-harness warning. No source failure records are patched in
those cases.
- The native execution case keeps `paperclip_runner`, native runtime
selection and the requested Codex model. A controlled native session
reads real restored `saved.txt`, writes `continued.txt`, emits an
accepted result and finishes through the real finalizer once. Only the
external native backend is controlled.
- Current unavailable-catalog admission and suspended authenticated
membership remain denials before provider work. Extra
provider/session/accounting material, Stop, newer source,
writer/generation and lease-receipt mismatches remain held.
- Both settlement consumers pass 53 focused real
PostgreSQL/filesystem/native-boundary cases on Node24.22.2.
Existing-directory warning presentation/provenance and
durable-measurement restrictions are preserved.
- Parent #18918 proves real PostgreSQL lock cycles through actual save,
prepare, provision, reservation and import publication owners. Its
native status peer test proves a busy refusal without a deadlock.
Immutable task binding, writer/epoch fences, same-journal retry and
unexpected-error rollback controls retain uploaded objects and original
files. The original spontaneous peer identity is not claimed.
- Historical head `6204f565` passed all 54 CI checks, but its local
affected run passed only 572/573 with a real PostgreSQL preservation
deadlock and its Paperclip review was 3/5. Those results remain
historical evidence; this composed head includes the explicit parent
repair.
- Production-composed head `93a02d4cf74f4d8d2cc6c1b62884bc58280500bf`,
Node24.22.2 / pnpm9.15.4: full `pnpm build` and recursive `pnpm -r
typecheck` passed. The six affected recovery, continuation, Retry,
migration and concurrency files passed 724 tests. Opt-in remote
workspace integration passed 65/65 and ownership lifecycle passed 16/16,
with no skips.
- Final head `65dcd6c6a601448b5a436b7a7f2c84b8cfde761b` adds only the
parent's unsupported-host test guard. Its 18 concurrency cases and
generated server test-layer typecheck passed on the exact head.
Production bytes match the qualified head above.
- Exact-head CI passed on `65dcd6c6`: 54 success, 3 skipped, 1 neutral;
no failed or pending jobs. Greptile reviewed this exact commit at 5/5
with no actionable issue and zero open threads.
- The current-head Paperclip assessment is registered and queued with no
run at the latest observation. It has not delivered a current-head
score. The earlier 3/5 assessment and its resolved findings remain
history. No extra review request or hosted task replay was used to force
delivery.

## Risks

- The new allocated-source proof is conservative. Extra or missing
execution material keeps work held and needs inspection.
- This changes admission after completed preservation. It does not
certify unknown provider effects or restore repository access.
- Administrative import can now return a named busy hold while an
execution row is owned. It retains the archive and journal for a later
administrative retry.
- There is no schema migration or new API. Stop, task ownership, current
actor access, budget and approval checks retain their normal owners.

## Model Used

OpenAI Codex, GPT-6 family. The exact runtime model ID and context
window are not exposed in this agent session. The agent used reasoning,
tool calls, code edits, real local PostgreSQL and filesystem tests. A
separate Codex agent reviewed the admission and execution boundaries.

## 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
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-04 07:17:49 -06:00

190 lines
14 KiB
TypeScript

import { isPreDispatchReviewWait } from "./pre-dispatch-review-wait.js";
import { and, eq, inArray, isNotNull, or } from "drizzle-orm";
import { environmentLeases, heartbeatRunEvents, heartbeatRuns, nativeRunFinalizations, nativeRunResults, type Db } from "@paperclipai/db";
import { isUuidLike } from "@paperclipai/shared";
import { claimedAdapterType } from "./conversation-continuation.js";
import { PROCESS_IDENTITY_RECORDED, PROCESS_START_REQUESTED } from "./native-local-process-stop.js";
import { hasRemoteTerminationReceipt } from "./remote-execution-termination.js";
import { canContinueCancelledRun, readRunCancellation } from "./run-cancellation.js";
import { legacyControllerBootId } from "./legacy-controller-lease.js";
import { hasRequiredWorkspaceRecovery } from "./workspace-restore-recovery-state.js";
import { hasVerifiedWorkspaceRepair } from "./workspace-recovery-receipt.js";
import { readFailedPreparationSettlement } from "./failed-preparation-settlement.js";
type Run = Pick<typeof heartbeatRuns.$inferSelect,
"id" | "companyId" | "status" | "startedAt" | "finishedAt" | "runtimeMode" |
"runtimeModeResolvedAt" | "errorCode" | "error" | "resultJson" | "runnerProfileJson" |
"contextSnapshot" | "processPid" | "processGroupId" | "processStartedAt" |
"sessionIdAfter" | "issueId" | "nativeIssueId" | "nativeSessionId" | "executionStage" |
"controllerBootId" | "controllerLeaseExpiresAt">;
type Coordinator = typeof nativeRunFinalizations.$inferSelect;
export async function isFailedNativePreparation(db: Db, run: Run, coordinator: Coordinator | undefined) {
if (run.status === "interrupted") return !coordinator && isInterruptedNativePreparation(db, run);
const recovery = run.resultJson?.executionRecovery as Record<string, unknown> | undefined;
if (run.status !== "failed" || !run.finishedAt || run.runtimeMode !== "legacy" || run.runtimeModeResolvedAt
|| run.errorCode !== "setup_failed" || run.executionStage !== "preparing"
|| claimedAdapterType(run) !== "paperclip_runner" || coordinator
|| recovery?.kind !== "bootstrap" || recovery.providerWorkStarted !== false
|| run.processPid || run.processGroupId || run.processStartedAt || run.sessionIdAfter
|| run.nativeIssueId || run.nativeSessionId || run.runnerProfileJson?.nativeExecutionInput != null
|| run.runnerProfileJson?.nativeWorkspaceSync != null
|| run.controllerLeaseExpiresAt && run.controllerLeaseExpiresAt > new Date()) return false;
const leases = await db.select().from(environmentLeases).where(and(
eq(environmentLeases.companyId, run.companyId), eq(environmentLeases.heartbeatRunId, run.id),
));
const [result] = await db.select({ id: nativeRunResults.id }).from(nativeRunResults).where(and(
eq(nativeRunResults.companyId, run.companyId), eq(nativeRunResults.runId, run.id),
)).limit(1);
if (result || await nativeStartupHasExecutionEvidence(db, run)) return false;
if (!leases.length && run.runnerProfileJson?.remoteWorkspace == null) return true;
const issueId = run.nativeIssueId ?? run.issueId ?? run.contextSnapshot?.issueId;
return typeof issueId === "string" && leases.length > 0 && leases.every(lease => lease.issueId === issueId
&& lease.metadata?.pendingCleanupInFlight !== true && hasRemoteTerminationReceipt(lease))
&& await hasSettledFailedPreparationEvidence(db, run)
&& await hasVerifiedWorkspaceRepair(db, run);
}
async function hasSettledFailedPreparationEvidence(db: Db, run: Run): Promise<boolean> {
const [source] = await db.select({ agentId: heartbeatRuns.agentId,
runtimeModeResolverVersion: heartbeatRuns.runtimeModeResolverVersion, runtimeModeReason: heartbeatRuns.runtimeModeReason,
runnerInstanceId: heartbeatRuns.runnerInstanceId, nativePhase: heartbeatRuns.nativePhase,
driverKind: heartbeatRuns.driverKind, driverVersion: heartbeatRuns.driverVersion,
completionContractId: heartbeatRuns.completionContractId, completionContractSha256: heartbeatRuns.completionContractSha256,
sessionIdBefore: heartbeatRuns.sessionIdBefore, externalRunId: heartbeatRuns.externalRunId,
logStore: heartbeatRuns.logStore, logRef: heartbeatRuns.logRef, logBytes: heartbeatRuns.logBytes,
logSha256: heartbeatRuns.logSha256, logCompressed: heartbeatRuns.logCompressed,
stdoutExcerpt: heartbeatRuns.stdoutExcerpt, stderrExcerpt: heartbeatRuns.stderrExcerpt,
lastOutputAt: heartbeatRuns.lastOutputAt, lastOutputSeq: heartbeatRuns.lastOutputSeq,
lastOutputStream: heartbeatRuns.lastOutputStream, lastOutputBytes: heartbeatRuns.lastOutputBytes,
usageJson: heartbeatRuns.usageJson, exitCode: heartbeatRuns.exitCode, signal: heartbeatRuns.signal,
}).from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, run.companyId), eq(heartbeatRuns.id, run.id)));
if (!source || source.logCompressed || source.lastOutputSeq !== 0 || Object.entries(source).some(([key, value]) =>
!["agentId", "logCompressed", "lastOutputSeq", "usageJson"].includes(key) && value !== null)
|| !hasOnlyPreparationAccountingContext(source.usageJson, run.issueId ?? run.contextSnapshot?.issueId)
|| Object.keys(run.runnerProfileJson ?? {}).some(key => !["adapterDispatch", "remoteWorkspace",
"chatControlRecoveryAdmission"].includes(key))
|| run.resultJson?.stopReason !== "adapter_failed"
|| Object.keys(run.resultJson).some(key => !["stopReason", "timeoutFired", "timeoutSource", "executionRecovery",
"timeoutConfigured", "effectiveTimeoutSec", "systemRecoveryAdoption", "workspaceRestoreFailure",
"workspaceRestoreRecovery"].includes(key))) return false;
return Boolean(await readFailedPreparationSettlement(db, { ...run, agentId: source.agentId }));
}
function hasOnlyPreparationAccountingContext(usage: unknown, issueId: unknown): boolean {
if (usage === null) return true;
if (!usage || typeof usage !== "object" || Array.isArray(usage)
|| Object.keys(usage).length !== 1 || !Object.hasOwn(usage, "ledgerScope")) return false;
const scope = (usage as Record<string, unknown>).ledgerScope as Record<string, unknown> | null;
return Boolean(scope && typeof scope === "object" && !Array.isArray(scope) && Object.keys(scope).length === 3
&& scope.issueId === issueId && (scope.projectId === null || typeof scope.projectId === "string" && isUuidLike(scope.projectId))
&& (scope.billingCode === null || typeof scope.billingCode === "string"));
}
/** Candidate state only. Admission must also verify ownership, execution records,
* stopped leases, and any saved-file obligation below. */
export function isInterruptedNativePreparationCandidate(run: Run): boolean {
const cancellation = readRunCancellation(run.resultJson);
// Older shutdown records predate structured cancellation. Current records
// identify unexpected system interruption without relying on an error label.
const systemInterruption = cancellation
? cancellation.initiator.type === "system" && cancellation.source !== "operator" &&
(cancellation.source === "shutdown" || cancellation.expected === false)
: run.errorCode === "server_shutdown_interrupted";
const recovery = run.resultJson?.executionRecovery as Record<string, unknown> | undefined;
return Boolean(systemInterruption && run.status === "interrupted" && run.finishedAt
&& run.runtimeMode === "legacy" && !run.runtimeModeResolvedAt && run.executionStage === "preparing"
&& claimedAdapterType(run) === "paperclip_runner" && !run.processPid && !run.processGroupId
&& !run.processStartedAt && !run.sessionIdAfter && !run.nativeIssueId && !run.nativeSessionId
&& run.runnerProfileJson?.nativeExecutionInput == null && recovery?.providerWorkStarted !== true);
}
export async function isInterruptedNativePreparation(db: Db, run: Run): Promise<boolean> {
const recovery = run.resultJson?.executionRecovery as Record<string, unknown> | undefined;
const settled = recovery?.kind === "bootstrap" && recovery.providerWorkStarted === false;
if (!isInterruptedNativePreparationCandidate(run)
|| run.controllerLeaseExpiresAt && run.controllerLeaseExpiresAt > new Date()
|| !settled && (!run.controllerBootId || run.controllerBootId === legacyControllerBootId)) 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);
const [result] = await db.select({ id: nativeRunResults.id }).from(nativeRunResults).where(and(
eq(nativeRunResults.companyId, run.companyId), eq(nativeRunResults.runId, run.id),
)).limit(1);
if (coordinator || result || await nativeStartupHasExecutionEvidence(db, run)) 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.releasedAt || lease.status === "pending_cleanup" || lease.cleanupStatus === "failed"
|| lease.metadata?.pendingCleanupInFlight === true
|| lease.provider !== "local" && !hasRemoteTerminationReceipt(lease))) return false;
if (hasRequiredWorkspaceRecovery(run.resultJson) || run.runnerProfileJson?.remoteWorkspace != null
|| run.runnerProfileJson?.nativeWorkspaceSync != null) return hasVerifiedWorkspaceRepair(db, run);
return run.resultJson?.workspaceRestoreFailure == null;
}
/** Candidate for explicit user Retry only, never automatic replay after Stop. */
export async function canRetryStoppedRun(db: Db, run: Run): Promise<boolean> {
if (run.errorCode === "native_session_cleanup_quarantined") return false;
if (["failed", "timed_out"].includes(run.status) || canContinueCancelledRun(run)) return true;
if (run.status !== "cancelled" || !run.finishedAt || run.processPid || run.processGroupId ||
run.processStartedAt || run.sessionIdAfter) return false;
const [coordinator] = await db.select().from(nativeRunFinalizations).where(and(
eq(nativeRunFinalizations.companyId, run.companyId), eq(nativeRunFinalizations.runId, run.id),
));
return isCancelledNativeStartup(db, run, coordinator);
}
/** Caller holds the coordinator and run locks when using this proof to admit
* work. Attempt zero is a durable never-claimed receipt: every native executor
* commits its first claim before it can start or attach a provider. */
export async function isCancelledNativeStartup(db: Db, run: Run, coordinator: Coordinator | undefined) {
if (run.status !== "cancelled" || !run.finishedAt || run.processPid || run.processGroupId ||
run.processStartedAt || run.sessionIdAfter) return false;
const cancellation = run.resultJson?.startupCancellation as Record<string, unknown> | undefined;
// Older builds could omit the cancellation fence or its unwind marker. Their immutable
// native-adapter claim and unresolved preparation stage still prove that
// provider dispatch did not begin. Require an expired owner from another
// server boot; neither a missing PID nor mutable agent settings is proof.
const historicalBeforeSelection = run.runtimeMode === "legacy" && !run.runtimeModeResolvedAt &&
run.executionStage === "preparing" && !run.nativeIssueId && !run.nativeSessionId && !coordinator &&
claimedAdapterType(run) === "paperclip_runner" && run.errorCode === "operator_interrupted" &&
(run.resultJson === null || cancellation?.beforeNativeSelection === true) &&
Boolean(run.controllerBootId && run.controllerBootId !== legacyControllerBootId &&
run.controllerLeaseExpiresAt && run.controllerLeaseExpiresAt <= new Date());
const beforeReviewDispatch = isPreDispatchReviewWait(run) && !coordinator;
const beforeSelection = beforeReviewDispatch || historicalBeforeSelection || run.runtimeMode === "legacy" && !run.runtimeModeResolvedAt &&
!run.nativeSessionId && !coordinator && claimedAdapterType(run) === "paperclip_runner" &&
cancellation?.beforeNativeSelection === true;
const neverClaimed = run.runtimeMode === "native" && coordinator &&
["observed", "terminal_failure"].includes(coordinator.phase) && coordinator.attempt === 0 &&
coordinator.controllerGeneration === 0 && !coordinator.controllerBootId &&
!coordinator.controllerPid && !coordinator.leaseOwner && !coordinator.leaseExpiresAt &&
!coordinator.resultId && !coordinator.failureDetail?.successorRunId;
if (!beforeSelection && !neverClaimed) return false;
const settled = beforeReviewDispatch || typeof run.resultJson?.startupPreparationSettledAt === "string";
// The old preparer can still be unwinding even though the run is terminal.
if (!settled && run.controllerLeaseExpiresAt && run.controllerLeaseExpiresAt > new Date()) return false;
const leases = await db.select().from(environmentLeases).where(and(
eq(environmentLeases.companyId, run.companyId), eq(environmentLeases.heartbeatRunId, run.id),
));
if ((!settled && leases.length === 0 && !historicalBeforeSelection) || leases.some(lease =>
lease.provider === "local"
? !lease.releasedAt || lease.status === "pending_cleanup" || lease.cleanupStatus === "failed"
: !hasRemoteTerminationReceipt(lease))) return false;
// Reject contradictory retained evidence, including a crash after a launch
// request but before the PID callback. Provider events never certify a stop.
return !await nativeStartupHasExecutionEvidence(db, run);
}
async function nativeStartupHasExecutionEvidence(db: Db, run: Run) {
const [execution] = await db.select({ id: heartbeatRunEvents.id }).from(heartbeatRunEvents).where(and(
eq(heartbeatRunEvents.companyId, run.companyId), eq(heartbeatRunEvents.runId, run.id),
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"])),
)).limit(1);
return Boolean(execution);
}