From 4697a5050836daae9b6f4276e910653a45c20694 Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Fri, 20 Nov 2026 23:33:16 -0800 Subject: [PATCH] fix: retry verified legacy adapter preparation failures (#22464) Accept the existing full preparation proof for the exact legacy adapter_failed source named by a saved Retry. Keep older recovery-hold ancestry checks and refusal gates intact. Add one-successor and missing-proof integration coverage, and synchronize the independent watchdog test fixture with reporter readiness. Qualified on 36463a770a9b1e01dd630b1f8bd48d584963005f with full green CI, Apex 5/5, no unresolved review findings and no conflicts. Focused Retry/bootstrap checks and the affected server typecheck pass after the rebase; broader local tests apply to the identical source tree. Co-Authored-By: Paperclip --- scripts/ci/stalled-file-reporter.test.mjs | 22 ++++++++- .../services/explicit-native-continuation.ts | 8 +++- .../saved-work-retry-eligibility.test.ts | 48 ++++++++++++++++++- 3 files changed, 73 insertions(+), 5 deletions(-) diff --git a/scripts/ci/stalled-file-reporter.test.mjs b/scripts/ci/stalled-file-reporter.test.mjs index ab9e58b70da..35ff44b12e2 100644 --- a/scripts/ci/stalled-file-reporter.test.mjs +++ b/scripts/ci/stalled-file-reporter.test.mjs @@ -97,7 +97,27 @@ test("passes", () => {}); let fixtureReporter = reporterPath; if (label === "a test that never settles") { fixtureReporter = path.join(directory, "after-test-start.mjs"); - writeFileSync(fixtureReporter, 'import Base from ' + JSON.stringify(pathToFileURL(reporterPath).href) + ';\nimport { existsSync } from "node:fs";\nexport default class extends Base { check() { if (!existsSync(' + JSON.stringify(startedMarker) + ')) return; super.check(); } }\n'); + writeFileSync(fixtureReporter, ` +import Base from ${JSON.stringify(pathToFileURL(reporterPath).href)}; +import { existsSync } from "node:fs"; +export default class extends Base { + ready = false; + onTestCaseReady(testCase) { + if (testCase.module.moduleId !== ${JSON.stringify(path.join(directory, "stuck.test.mjs"))}) { + super.onTestCaseReady(testCase); + return; + } + setTimeout(() => { + super.onTestCaseReady(testCase); + this.ready = true; + }, this.limitMs + 500); + } + check() { + if (!this.ready || !existsSync(${JSON.stringify(startedMarker)})) return; + super.check(); + } +} +`); } const configFile = path.join(directory, "vitest.config.mjs"); writeFileSync(configFile, `export default ${JSON.stringify({ test: { include: ["*.test.mjs"], diff --git a/server/src/services/explicit-native-continuation.ts b/server/src/services/explicit-native-continuation.ts index dd5ae58a64f..e5be7ec17a1 100644 --- a/server/src/services/explicit-native-continuation.ts +++ b/server/src/services/explicit-native-continuation.ts @@ -353,7 +353,9 @@ export async function admitExplicitNativeContinuation(input: { )).for("update"); if (!source || (source.nativeIssueId ?? source.issueId ?? source.contextSnapshot?.issueId) !== issueId || adapterExecutionControls.has(source.id) || - !(await isFailedNativePreparation(db, source, coordinator) || await isPreDispatchExecutionWaitVerified(db, source))) return refused("previous_execution_unverified", PREVIOUS_EXECUTION_UNVERIFIED); + !(await isFailedNativePreparation(db, source, coordinator) + || source.errorCode === "adapter_failed" && await isFailedNativePreparationRetryAncestor(db, source, coordinator) + || await isPreDispatchExecutionWaitVerified(db, source))) return refused("previous_execution_unverified", PREVIOUS_EXECUTION_UNVERIFIED); sourceChecks.push({ cause: "legacy_execution_requires_reconciliation", evidence: { runId: source.id } }); } if (!sourceChecks.length && !nativeQueuedSend) return null; @@ -394,7 +396,9 @@ export async function admitExplicitNativeContinuation(input: { // A user's message written after their Stop request is new direction even // when the stopped native run settled later. const stoppedAt = userStopBoundaryAt(run)!; - const failedPreparation = await isFailedNativePreparation(db, run, coordinator); + const failedPreparation = await isFailedNativePreparation(db, run, coordinator) + || taskRetry?.sourceRunId === run.id && run.errorCode === "adapter_failed" + && await isFailedNativePreparationRetryAncestor(db, run, coordinator); const unusedAdmission = run.status === "cancelled" && !run.startedAt && run.errorCode === "execution_reconciliation_required" && !run.processPid && !run.processGroupId && !run.nativeSessionId && diff --git a/server/src/services/saved-work-retry-eligibility.test.ts b/server/src/services/saved-work-retry-eligibility.test.ts index fc2602a5868..856d6711f78 100644 --- a/server/src/services/saved-work-retry-eligibility.test.ts +++ b/server/src/services/saved-work-retry-eligibility.test.ts @@ -46,7 +46,7 @@ describe("Retry of a task whose saved work recovery settled", () => { return { companyId, issueId, agentId, workspaceId }; } - async function sourceUnavailable() { + async function sourceUnavailable({ heldRun = true } = {}) { const f = await base("SU"); const { companyId, issueId, agentId, workspaceId } = f; const firstId = randomUUID(), preparedId = randomUUID(), heldId = randomUUID(), actionId = randomUUID(); @@ -126,7 +126,7 @@ describe("Retry of a task whose saved work recovery settled", () => { workspaceRestoreRecovery: { schema: "paperclip.workspace-restore-recovery.v1", leaseIds: [leaseId] }, historicalWorkspaceSource: { schema: "paperclip.historical-workspace-source.v1", runId: preparedId, leaseIds: [leaseId] }, previousWorkspaceRecovery: null } }); - await db.insert(heartbeatRuns).values({ id: heldId, companyId, agentId, issueId, status: "cancelled", runtimeMode: "legacy", + if (heldRun) await db.insert(heartbeatRuns).values({ id: heldId, companyId, agentId, issueId, status: "cancelled", runtimeMode: "legacy", errorCode: "execution_reconciliation_required", error: "Recovering saved work…", invocationSource: "automation", triggerDetail: "system", retryOfRunId: preparedId, createdAt: new Date(now - 680_000), finishedAt: new Date(now - 600_000), contextSnapshot: { issueId, taskId: issueId, source: "issue.continuation_recovery", wakeReason: "issue_continuation_needed", @@ -275,6 +275,50 @@ describe("Retry of a task whose saved work recovery settled", () => { expect(successor.contextSnapshot).toMatchObject({ taskRetryRequestId: wake.id }); }); + it("admits Retry when the latest run is the verified legacy adapter preparation itself", async () => { + const f = await sourceUnavailable({ heldRun: false }); + await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId, status: "running" }); + const receipt = await requestTaskRetry({ db, companyId: f.companyId, issueId: f.issueId, actorId, + observedRunId: f.preparedId, idempotencyKey: randomUUID(), actorSource: "local_implicit" }); + expect(receipt).toMatchObject({ accepted: true, requestId: expect.any(String) }); + const heartbeat = heartbeatService(db); + await heartbeat.resumeTaskRetry(f.companyId, receipt.requestId!); + await heartbeat.resumeTaskRetry(f.companyId, receipt.requestId!); + const [wake] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, receipt.requestId!)); + expect(wake).toMatchObject({ status: "coalesced", runId: expect.any(String) }); + const successors = await db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, f.companyId), + sql`${heartbeatRuns.contextSnapshot}->>'taskRetryRequestId' = ${receipt.requestId}`)); + expect(successors).toHaveLength(1); + expect(successors[0]).toMatchObject({ id: wake.runId, status: "queued", + contextSnapshot: { previousRunId: f.preparedId, taskRetryRequestId: receipt.requestId } }); + }); + + it.each(["provider_event", "unverified_log", "live_controller", "unsaved_files", "missing_lease", "no_allocation"] as const)( + "refuses Retry of the latest legacy adapter preparation without proof: %s", async gate => { + const f = await sourceUnavailable({ heldRun: false }); + if (gate === "provider_event") await db.insert(heartbeatRunEvents).values({ companyId: f.companyId, agentId: f.agentId, + runId: f.preparedId, seq: 5, eventType: "tool.execution.started", stream: "system" }); + if (gate === "unverified_log") logs.content.clear(); + if (gate === "live_controller") await db.update(heartbeatRuns) + .set({ controllerLeaseExpiresAt: new Date(Date.now() + 3_600_000) }).where(eq(heartbeatRuns.id, f.preparedId)); + if (gate === "unsaved_files") await db.update(executionWorkspaces) + .set({ metadata: sql`${executionWorkspaces.metadata} - 'remoteWorkspaceAbandonedEpochs'` }) + .where(eq(executionWorkspaces.id, f.workspaceId)); + if (gate === "missing_lease" || gate === "no_allocation") + await db.delete(environmentLeases).where(eq(environmentLeases.heartbeatRunId, f.preparedId)); + if (gate === "no_allocation") await db.update(heartbeatRuns).set({ + runnerProfileJson: sql`${heartbeatRuns.runnerProfileJson} - 'remoteWorkspace'`, + resultJson: sql`${heartbeatRuns.resultJson} - 'workspaceRestoreFailure' - 'workspaceRestoreRecovery'`, + }).where(eq(heartbeatRuns.id, f.preparedId)); + const receipt = await requestTaskRetry({ db, companyId: f.companyId, issueId: f.issueId, actorId, + observedRunId: f.preparedId, idempotencyKey: randomUUID(), actorSource: "local_implicit" }); + expect(receipt.requestId).toEqual(expect.any(String)); + await heartbeatService(db).resumeTaskRetry(f.companyId, receipt.requestId!); + const [wake] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, receipt.requestId!)); + expect(wake).toMatchObject({ status: "deferred_issue_execution", runId: null }); + expect(wake.payload?.executionWait).toMatchObject({ reason: "previous_execution_unverified" }); + }); + it("verifies the repair of a restored snapshot that the failed preparation never changed", async () => { const f = await restoredSnapshot(); const blocker = await getExecutionBlocker(db, f.companyId, f.issueId);