mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-04 04:29:01 +01:00
fix(native): retire a failed run's lapsed claim after a newer run takes over
A native run can fail while its controller on another server still holds the finalization claim (phase observed). When the task then moves on to a newer run, nothing could settle that claim: - the expired-owner pass cannot verify a controller in another process space, so it holds the task for the board, naming the old run; - restart recovery returns issue_execution_lock_changed before it reaches the bounded wait that ends unverifiable runs, and writes nothing. So the check repeated every minute, the hold never cleared, and the task's automatic continuation and the user's Retry were refused indefinitely. Restart recovery now retires that claim once the same bounded wait has passed since the lease lapsed, when a newer run of the task exists. The old run keeps its failure, the task's lock and the newer run are untouched, and the hold that names the old run is resolved. No new turn starts here. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
3f882fc589
commit
c8f9f23680
3 files changed
+221
-3
No files matched your search
@@ -53,7 +53,7 @@ import { issueRecoveryActionService } from "../issue-recovery-actions.js";
|
||||
import { isNewTerminalRunFailure, reportRunFailure } from "../run-failure-report.js";
|
||||
import { nativeControllerAuthorityDigest, isNativeRunnerOwnershipHeld, readNativeRemoteExecutionOwnership } from "./native-runner-ownership.js";
|
||||
import { nativeRestartContinuationInFlight, nativeRestartInterruptedTurnId, type PersistedNativeSession } from "../../vendor/paperclip-runner/index.js";
|
||||
import { retireSupersededNativeRetry } from "./native-superseded-retry.js";
|
||||
import { retireSupersededFailedNativeOwner, retireSupersededNativeRetry } from "./native-superseded-retry.js";
|
||||
import { legacyWorkspaceRecoveryNotMigrated } from "../legacy-workspace-recovery-migration.js";
|
||||
import { NATIVE_INTERRUPTION_NO_PROGRESS_DEADLINE_MS } from "../fresh-continuation-fallback.js";
|
||||
import { requestNativeStartupCleanup, readNativeStartupContext, promoteNativeStartupCleanup } from "./native-startup-cleanup.js";
|
||||
@@ -1370,6 +1370,20 @@ export async function claimNativeRestartRecoveries(input: {
|
||||
const handedOff = row.issueExecutionRunId === null && nativeRunHandedOffTask(row.run.resultJson, issue);
|
||||
if (row.issueExecutionRunId !== row.run.id && !(stopCleanup && row.issueExecutionRunId === null) && !releasedRemoteRetry
|
||||
&& !admission.exhausted && !handedOff) {
|
||||
// A failed run whose claim outlived it, after a newer run took over the
|
||||
// task: the bounded wait below is never reached from here, so retire
|
||||
// the claim (and the hold naming it) once that same bound has passed.
|
||||
const reason = "native_superseded_owner_retired";
|
||||
if (!stopCleanup && !input.liveRunExecutions?.has(row.run.id) && await retireSupersededFailedNativeOwner(tx as unknown as Db, {
|
||||
run: row.run, coordinator: row.coordinator, issueExecutionRunId: row.issueExecutionRunId, now,
|
||||
boundedWaitMs: NATIVE_NAMESPACE_UNVERIFIED_WAIT_MS,
|
||||
recoveryHistory: appendBoundedRecoveryHistory(historyEntry({
|
||||
now, restartKind: input.restartKind, controller, generation: row.coordinator.controllerGeneration,
|
||||
disposition: "blocked", reason, requestId: input.recoveryRequestId ?? null,
|
||||
providerAttempt: row.coordinator.attempt, processPid: row.run.processPid, processStartedAt: row.run.processStartedAt,
|
||||
hasCheckpoint: false, hasProviderEvidence: false, stderrTail: row.run.stderrExcerpt,
|
||||
})),
|
||||
})) return { kind: "blocked", runId: row.run.id, reason } as const;
|
||||
return {
|
||||
kind: "blocked",
|
||||
runId: row.run.id,
|
||||
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { heartbeatRuns, issueRecoveryActions, issues, nativeRunFinalizations } from "@paperclipai/db";
|
||||
import { beforeAll, expect, it } from "vitest";
|
||||
import { describeEmbeddedPostgres, nativeRestartFixture } from "../../__tests__/helpers/native-restart.js";
|
||||
import { currentProcessSpaceHash } from "../controller-process-identity.js";
|
||||
import { releaseAbandonedNativeOwners, resetAbandonedNativeOwnerReleaseForTests } from "./native-failed-run-owner-release.js";
|
||||
import { claimNativeRestartRecoveries, NATIVE_NAMESPACE_UNVERIFIED_WAIT_MS } from "./native-restart-recovery.js";
|
||||
|
||||
// A run failed while its controller (on another server) still held the
|
||||
// finalization claim. The task moved on to a newer run. Nothing here can prove
|
||||
// that old controller stopped, so the expired-owner pass holds the task for
|
||||
// the board, and restart recovery used to stop at "the task's lock moved" on
|
||||
// every pass: the claim never settled and the hold never cleared, so automatic
|
||||
// continuation and the user's Retry were refused indefinitely.
|
||||
describeEmbeddedPostgres("a failed run's unverifiable owner after the task moved on", () => {
|
||||
const environment = nativeRestartFixture();
|
||||
const { seedRun } = environment;
|
||||
let companyId: string;
|
||||
let agentId: string;
|
||||
let successor: typeof environment.current.successor;
|
||||
beforeAll(() => { ({ companyId, agentId, successor } = environment.current); });
|
||||
|
||||
async function seedSupersededFailedOwner(label: string, options: { lapsedMs: number; newerRun: boolean }) {
|
||||
const fixture = await seedRun(`${label}-${randomUUID()}`);
|
||||
const foreignSpace = `foreign:${currentProcessSpaceHash()}`;
|
||||
const failedAt = new Date(Date.now() - options.lapsedMs - 60_000);
|
||||
await fixture.db.update(heartbeatRuns).set({ status: "failed", createdAt: new Date(failedAt.getTime() - 180_000), startedAt: new Date(failedAt.getTime() - 120_000),
|
||||
finishedAt: failedAt, errorCode: "native_session_interrupted",
|
||||
error: "native_session_interrupted: native_finalization_missing: session returned no semantic result" })
|
||||
.where(eq(heartbeatRuns.id, fixture.runId));
|
||||
await fixture.db.update(nativeRunFinalizations).set({ controllerBootId: randomUUID(), controllerPid: 2_000_000_051,
|
||||
controllerProcessStartedAt: new Date(failedAt.getTime() - 600_000), controllerHostHash: foreignSpace,
|
||||
leaseOwner: `default:resume:${randomUUID()}`, leaseExpiresAt: new Date(Date.now() - options.lapsedMs),
|
||||
attempt: 1, controllerGeneration: 1 }).where(eq(nativeRunFinalizations.runId, fixture.runId));
|
||||
// The failure released the task's lock; nothing holds it now.
|
||||
await fixture.db.update(issues).set({ executionRunId: null }).where(eq(issues.id, fixture.issueId));
|
||||
let newerRunId: string | null = null;
|
||||
if (options.newerRun) {
|
||||
// A later run of the same task started after the failure and also ended.
|
||||
newerRunId = randomUUID();
|
||||
await fixture.db.insert(heartbeatRuns).values({ id: newerRunId, companyId, agentId, status: "failed",
|
||||
runtimeMode: "native", nativeIssueId: fixture.issueId, invocationSource: "automation", triggerDetail: "system",
|
||||
contextSnapshot: { issueId: fixture.issueId }, createdAt: new Date(failedAt.getTime() + 1_000),
|
||||
startedAt: new Date(failedAt.getTime() + 2_000), finishedAt: new Date(failedAt.getTime() + 30_000),
|
||||
errorCode: "native_session_interrupted" });
|
||||
}
|
||||
// The expired-owner pass cannot verify a controller in another process
|
||||
// space, so it holds the task for the board, naming the old run.
|
||||
resetAbandonedNativeOwnerReleaseForTests();
|
||||
await releaseAbandonedNativeOwners(fixture.db);
|
||||
const held = await activeHolds(fixture);
|
||||
expect(held).toEqual([expect.objectContaining({ ownerType: "board", cause: "native_restart_recovery_blocked",
|
||||
evidence: expect.objectContaining({ runId: fixture.runId }) })]);
|
||||
return { ...fixture, newerRunId };
|
||||
}
|
||||
|
||||
async function activeHolds(fixture: { db: Awaited<ReturnType<typeof seedRun>>["db"]; issueId: string }) {
|
||||
return fixture.db.select().from(issueRecoveryActions).where(and(
|
||||
eq(issueRecoveryActions.sourceIssueId, fixture.issueId), eq(issueRecoveryActions.status, "active")));
|
||||
}
|
||||
|
||||
it("retires the old owner after the bounded wait and releases the hold that blocked the task", async () => {
|
||||
const fixture = await seedSupersededFailedOwner("SUPERSEDED-OWNER",
|
||||
{ lapsedMs: NATIVE_NAMESPACE_UNVERIFIED_WAIT_MS + 60_000, newerRun: true });
|
||||
|
||||
const dispositions = await claimNativeRestartRecoveries({ db: fixture.db, controller: successor,
|
||||
restartKind: "hard", runIds: [fixture.runId] });
|
||||
|
||||
expect(dispositions).toEqual([expect.objectContaining({ kind: "blocked", runId: fixture.runId,
|
||||
reason: "native_superseded_owner_retired" })]);
|
||||
const [coordinator] = await fixture.db.select().from(nativeRunFinalizations)
|
||||
.where(eq(nativeRunFinalizations.runId, fixture.runId));
|
||||
expect(coordinator).toMatchObject({ phase: "terminal_failure", leaseOwner: null, leaseExpiresAt: null,
|
||||
failureDetail: expect.objectContaining({ successorRunId: fixture.newerRunId, executorStopEvidence: "unverified" }) });
|
||||
// The old run keeps its own failure; the task's lock is not touched.
|
||||
const [run] = await fixture.db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, fixture.runId));
|
||||
expect(run).toMatchObject({ status: "failed", errorCode: "native_session_interrupted", nativePhase: "terminal_failure" });
|
||||
const [task] = await fixture.db.select().from(issues).where(eq(issues.id, fixture.issueId));
|
||||
expect(task!.executionRunId).toBeNull();
|
||||
// The hold that refused Retry and automatic continuation is released, and
|
||||
// the expired-owner pass does not raise it again.
|
||||
expect(await activeHolds(fixture)).toEqual([]);
|
||||
resetAbandonedNativeOwnerReleaseForTests();
|
||||
await releaseAbandonedNativeOwners(fixture.db);
|
||||
expect(await activeHolds(fixture)).toEqual([]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ label: "within the bounded wait", lapsedMs: 30_000, newerRun: true },
|
||||
{ label: "with no newer run of the task", lapsedMs: NATIVE_NAMESPACE_UNVERIFIED_WAIT_MS + 60_000, newerRun: false },
|
||||
])("keeps the old owner and its hold $label", async ({ lapsedMs, newerRun }) => {
|
||||
const fixture = await seedSupersededFailedOwner("SUPERSEDED-KEEP", { lapsedMs, newerRun });
|
||||
|
||||
const dispositions = await claimNativeRestartRecoveries({ db: fixture.db, controller: successor,
|
||||
restartKind: "hard", runIds: [fixture.runId] });
|
||||
|
||||
expect(dispositions).toEqual([expect.objectContaining({ runId: fixture.runId, reason: "issue_execution_lock_changed" })]);
|
||||
const [coordinator] = await fixture.db.select().from(nativeRunFinalizations)
|
||||
.where(eq(nativeRunFinalizations.runId, fixture.runId));
|
||||
expect(coordinator).toMatchObject({ phase: "observed", leaseOwner: expect.any(String) });
|
||||
expect(await activeHolds(fixture)).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,13 @@
|
||||
import { and, desc, eq, gt, isNotNull, sql } from "drizzle-orm";
|
||||
import { environmentLeases, heartbeatRuns, nativeRunFinalizations, type Db } from "@paperclipai/db";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { and, desc, eq, gt, inArray, isNotNull, or, sql, type SQL } from "drizzle-orm";
|
||||
import { environmentLeases, heartbeatRuns, issueRecoveryActions, nativeRunFinalizations, nativeRunResults, type Db } from "@paperclipai/db";
|
||||
import { DELIVERY_QUEUES, notifyDeliveryWork } from "../delivery-work-notifications.js";
|
||||
import { notifyExecutionRunWork } from "../execution-control-notifications.js";
|
||||
import { issueRecoveryActionService } from "../issue-recovery-actions.js";
|
||||
import { notifyNativeFinalizationWork } from "../native-finalization-notifications.js";
|
||||
import { notifyNativeStatusReassessment } from "../native-status-reassessment-notifications.js";
|
||||
import { LEGACY_WORKSPACE_RECOVERY_KEY } from "../workspace-restore-recovery-state.js";
|
||||
import { activeNativeExecutionRunIds } from "./native-active-runs.js";
|
||||
import { hasRequiredWorkspaceRecovery, nativeRunHasNoWorkspaceAccess } from "../workspace-restore-recovery-state.js";
|
||||
import { preserveNativeFailedWorkspace } from "./native-failed-workspace-recovery.js";
|
||||
import { readNativeWorkspaceSyncReference } from "./native-workspace-sync.js";
|
||||
@@ -54,3 +61,96 @@ export async function retireSupersededNativeRetry(db: Db, input: {
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* A run failed while its controller still held the finalization claim
|
||||
* (`observed`), and the task has since moved on: its lock left this run and a
|
||||
* newer run of the task exists. When nothing here can verify that controller
|
||||
* stopped (it ran in another process space), the expired-owner pass holds the
|
||||
* task for the board and restart recovery stops at "the task's lock moved",
|
||||
* so the claim never settles and the hold never clears: automatic continuation
|
||||
* and the user's Retry are refused indefinitely.
|
||||
*
|
||||
* After the same bounded wait that ends any run whose lapsed controller cannot
|
||||
* be verified (measured from the lease lapse), the claim is retired. The run
|
||||
* keeps its own failure; the task's lock and the newer run are untouched; the
|
||||
* hold naming this run is released. No turn starts here: the task continues
|
||||
* through its normal paths (newer run's recovery, Retry, assigned work).
|
||||
*/
|
||||
export async function retireSupersededFailedNativeOwner(db: Db, input: {
|
||||
run: typeof heartbeatRuns.$inferSelect;
|
||||
coordinator: typeof nativeRunFinalizations.$inferSelect;
|
||||
issueExecutionRunId: string | null;
|
||||
now: Date;
|
||||
boundedWaitMs: number;
|
||||
recoveryHistory: SQL;
|
||||
}): Promise<{ successorRunId: string } | null> {
|
||||
const { run, coordinator, now } = input;
|
||||
const leaseOwner = coordinator.leaseOwner;
|
||||
if (run.runtimeMode !== "native" || run.status !== "failed" || !run.finishedAt
|
||||
|| coordinator.phase !== "observed" || coordinator.resultId || !leaseOwner
|
||||
|| leaseOwner.startsWith("native-finalizer:") || leaseOwner.startsWith("native-cleanup:")
|
||||
|| coordinator.companyId !== run.companyId || coordinator.runId !== run.id
|
||||
|| input.issueExecutionRunId === run.id
|
||||
|| !coordinator.leaseExpiresAt || now.getTime() - coordinator.leaseExpiresAt.getTime() < input.boundedWaitMs
|
||||
|| (run.controllerLeaseExpiresAt && run.controllerLeaseExpiresAt > now)
|
||||
|| activeNativeExecutionRunIds.has(run.id)
|
||||
|| run.resultJson?.[LEGACY_WORKSPACE_RECOVERY_KEY] != null) return null;
|
||||
// Same exclusions as the expired-owner pass: an unsettled environment lease
|
||||
// or a pending Stop belongs to its own settlement path.
|
||||
const [heldElsewhere] = await db.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(and(
|
||||
eq(heartbeatRuns.id, run.id), or(
|
||||
sql`exists (select 1 from ${environmentLeases} lease
|
||||
where lease.company_id = ${heartbeatRuns.companyId} and lease.heartbeat_run_id = ${heartbeatRuns.id}
|
||||
and ((lease.released_at is null and not (lease.status = 'retained' and lease.cleanup_status = 'success'))
|
||||
or lease.status = 'pending_cleanup' or lease.cleanup_status = 'failed'))`,
|
||||
sql`coalesce(${heartbeatRuns.resultJson}, '{}'::jsonb) #>> '{nativeCancellation,dispatchState}' = 'pending'`,
|
||||
))).limit(1);
|
||||
if (heldElsewhere) return null;
|
||||
const [accepted] = await db.select({ id: nativeRunResults.id }).from(nativeRunResults).where(and(
|
||||
eq(nativeRunResults.companyId, run.companyId), eq(nativeRunResults.runId, run.id),
|
||||
eq(nativeRunResults.schemaStatus, "accepted"))).limit(1);
|
||||
if (accepted) return null;
|
||||
const source = sql`(select source.created_at from ${heartbeatRuns} source
|
||||
where source.id = ${run.id} and source.company_id = ${run.companyId})`;
|
||||
const [newer] = await db.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(and(
|
||||
eq(heartbeatRuns.companyId, run.companyId), sql`${heartbeatRuns.id} <> ${run.id}`,
|
||||
or(eq(heartbeatRuns.nativeIssueId, coordinator.issueId), eq(heartbeatRuns.issueId, coordinator.issueId),
|
||||
sql`${heartbeatRuns.contextSnapshot}->>'issueId' = ${coordinator.issueId}`),
|
||||
or(sql`${heartbeatRuns.createdAt} > ${source}`,
|
||||
and(sql`${heartbeatRuns.createdAt} = ${source}`, sql`${heartbeatRuns.id} > ${run.id}`)),
|
||||
)).orderBy(desc(heartbeatRuns.createdAt)).limit(1);
|
||||
if (!newer) return null;
|
||||
|
||||
const scope = { companyId: run.companyId, agentId: run.agentId, runId: run.id, issueId: coordinator.issueId };
|
||||
await notifyExecutionRunWork(db, scope);
|
||||
await notifyNativeFinalizationWork(db, scope);
|
||||
// A result-less `observed` owner holds pending cost accounting; settlement releases it.
|
||||
await notifyDeliveryWork(db, DELIVERY_QUEUES.accounting, run.companyId);
|
||||
const [updated] = await db.update(nativeRunFinalizations).set({ phase: "terminal_failure", leaseOwner: null,
|
||||
leaseExpiresAt: null, controlDeadlineAt: null, nextAttemptAt: null, recoveryState: "blocked",
|
||||
failureCode: coordinator.failureCode ?? run.errorCode ?? "native_restart_recovery_blocked",
|
||||
failureDetail: { ...coordinator.failureDetail, reason: "superseded_failed_owner_retired",
|
||||
successorRunId: newer.id, executorStopEvidence: "unverified",
|
||||
releasedOwner: { leaseOwner, attempt: coordinator.attempt, controllerGeneration: coordinator.controllerGeneration } },
|
||||
recoveryHistory: input.recoveryHistory, updatedAt: now,
|
||||
}).where(and(eq(nativeRunFinalizations.runId, run.id), eq(nativeRunFinalizations.phase, "observed"),
|
||||
eq(nativeRunFinalizations.leaseOwner, leaseOwner), eq(nativeRunFinalizations.attempt, coordinator.attempt)))
|
||||
.returning({ runId: nativeRunFinalizations.runId });
|
||||
if (!updated) return null;
|
||||
const [retired] = await db.update(heartbeatRuns).set({ nativePhase: "terminal_failure", nativePhaseUpdatedAt: now,
|
||||
executionStatusDeliveryId: randomUUID(), updatedAt: now }).where(eq(heartbeatRuns.id, run.id)).returning();
|
||||
if (retired) await preserveNativeFailedWorkspace(db, retired);
|
||||
await notifyNativeStatusReassessment(db, scope);
|
||||
const holds = await db.select({ id: issueRecoveryActions.id }).from(issueRecoveryActions).where(and(
|
||||
eq(issueRecoveryActions.companyId, run.companyId), eq(issueRecoveryActions.sourceIssueId, coordinator.issueId),
|
||||
inArray(issueRecoveryActions.status, ["active", "escalated"]),
|
||||
eq(issueRecoveryActions.cause, "native_restart_recovery_blocked"),
|
||||
sql`${issueRecoveryActions.evidence}->>'runId' = ${run.id}`));
|
||||
for (const hold of holds) {
|
||||
await issueRecoveryActionService(db).resolveActiveForIssue({ companyId: run.companyId,
|
||||
sourceIssueId: coordinator.issueId, actionId: hold.id, status: "resolved", outcome: "cancelled",
|
||||
resolutionNote: "This run had already ended and a newer run took over the task. Its old claim was released." }, db);
|
||||
}
|
||||
return { successorRunId: newer.id };
|
||||
}
|
||||
Reference in new issue
Block a user