diff --git a/doc/plugins/PLUGIN_RUNNER_EXECUTION.md b/doc/plugins/PLUGIN_RUNNER_EXECUTION.md index cf84492e020..b9d86561692 100644 --- a/doc/plugins/PLUGIN_RUNNER_EXECUTION.md +++ b/doc/plugins/PLUGIN_RUNNER_EXECUTION.md @@ -157,6 +157,16 @@ the durable journal first stops and releases the old task. A failed stop prevent A new run prepares its current assignments. Provider compatibility checks remain in the existing backends. Missing or incompatible retained state fails closed. +A driver can refuse a `submit` with `admission_rejected`. Core records the +reason on the lease and fails the run. When the run supplied `resumeFrom`, the +saved session cannot be resumed: the account changed after it started +(`account_binding_mismatch`), or its saved state is unavailable +(`session_state_unavailable`). Core then schedules one continuation in a fresh +provider session in the same workspace, and tells the agent which reason +applied. That run supplies no `resumeFrom`. If the driver refuses it too, or +refuses a run that did not supply `resumeFrom`, the run fails and automatic +retries stop. + ## Setup verification Core creates a private probe lease with an expiry. diff --git a/server/src/modules/run-dispatch/adapters/postgres.ts b/server/src/modules/run-dispatch/adapters/postgres.ts index 810d1494915..dda03cd5804 100644 --- a/server/src/modules/run-dispatch/adapters/postgres.ts +++ b/server/src/modules/run-dispatch/adapters/postgres.ts @@ -182,7 +182,7 @@ function classifyRetryReasonKind(retryReason: string | null): RetryReasonKind { if (retryReason === ISSUE_DISPOSITION_REPAIR_RETRY_REASON) return "disposition_repair"; if ((retryReason === "ai_connection_busy" || retryReason === "ai_connection_pool_wait")) return "ai_connection_wait"; if (["native_safe_replacement", "native_provider_overloaded", "native_environment_blocker", "native_agent_blocker_continuation", - "interrupted_preparation"].includes(retryReason ?? "")) return "native_safe_replacement"; + "native_resume_refused_continuation", "interrupted_preparation"].includes(retryReason ?? "")) return "native_safe_replacement"; return "other"; } diff --git a/server/src/services/execution-recovery-attempt.ts b/server/src/services/execution-recovery-attempt.ts index 98c9091806c..f7d3499b24a 100644 --- a/server/src/services/execution-recovery-attempt.ts +++ b/server/src/services/execution-recovery-attempt.ts @@ -2,6 +2,7 @@ import { RUNNER_REVISION_WAIT_RETRY_REASON } from "./runner-revision-mismatch.js import { STORAGE_UNAVAILABLE_WAIT_RETRY_REASON } from "../storage/storage-unavailable.js"; import { ENVIRONMENT_PROVIDER_WAIT_RETRY_REASON } from "./environment-provider-wait.js"; import { PROVIDER_ATTEMPT_CREDIT_GENERATION_LIMIT } from "./native-runtime/provider-attempt-outcome.js"; +import { NATIVE_RESUME_REFUSED_CONTINUATION_CODE } from "./native-runtime/native-resume-refused-continuation.js"; import { AGENT_DIRECTORY_BUSY_RETRY_REASON } from "../modules/run-dispatch/index.js"; /** @@ -32,7 +33,7 @@ export const SERVER_RESTART_RETRY_WINDOW_MS = 60 * 60_000; const UNCHARGED_RETRY_LANES: ReadonlySet = new Set([ "workspace_busy", "ai_connection_busy", "ai_connection_pool_wait", AGENT_DIRECTORY_WAIT_RETRY_REASON, RUNNER_REVISION_WAIT_RETRY_REASON, INTERRUPTED_PREPARATION_RETRY_REASON, STORAGE_UNAVAILABLE_WAIT_RETRY_REASON, SERVER_RESTART_RETRY_REASON, - ENVIRONMENT_PROVIDER_WAIT_RETRY_REASON, + ENVIRONMENT_PROVIDER_WAIT_RETRY_REASON, NATIVE_RESUME_REFUSED_CONTINUATION_CODE, ]); type RetryRun = { diff --git a/server/src/services/heartbeat.ts b/server/src/services/heartbeat.ts index 57de23a915b..03459ecaae2 100644 --- a/server/src/services/heartbeat.ts +++ b/server/src/services/heartbeat.ts @@ -3182,7 +3182,8 @@ export function heartbeatService( } const enforceContinuationOwnership = Boolean(issueId && (isFailedChatRunRetry || isResolvedInteractionContinuationWakeContext(context) || typeof context.workspaceReconstructionActionId === "string" || - ["native_safe_replacement", "native_provider_overloaded", "native_environment_blocker", "native_agent_blocker_continuation"].includes(run.scheduledRetryReason ?? ""))); + ["native_safe_replacement", "native_provider_overloaded", "native_environment_blocker", "native_agent_blocker_continuation", + "native_resume_refused_continuation"].includes(run.scheduledRetryReason ?? ""))); if (issueId && enforceContinuationOwnership) { await options.beforeResolvedInteractionContinuationDispatchCheck?.({ runId: run.id, issueId }); await options.afterResolvedInteractionContinuationDispatchCheck?.({ runId: run.id, issueId }); diff --git a/server/src/services/native-runtime/native-provider-capacity-retry.ts b/server/src/services/native-runtime/native-provider-capacity-retry.ts index 636bf4606d2..a750c752524 100644 --- a/server/src/services/native-runtime/native-provider-capacity-retry.ts +++ b/server/src/services/native-runtime/native-provider-capacity-retry.ts @@ -1,9 +1,9 @@ import { notifyIssueAttentionRetentionWork } from "../retention-work-notifications.js"; import { notifyScheduledRetryDispatch } from "../run-dispatch-notifications.js"; import { randomUUID } from "node:crypto"; -import { and, eq } from "drizzle-orm"; -import { agentWakeupRequests, heartbeatRuns, type Db } from "@paperclipai/db"; -import { accountingForScheduledRetry, executionFailureRetryCount } from "../execution-recovery-attempt.js"; +import { and, eq, inArray, sql } from "drizzle-orm"; +import { agentWakeupRequests, environmentLeases, heartbeatRuns, type Db } from "@paperclipai/db"; +import { accountingForScheduledRetry, executionRetryAttemptCount } from "../execution-recovery-attempt.js"; import { NATIVE_PROVIDER_CAPACITY_MAX_RETRIES, NATIVE_PROVIDER_OVERLOADED_CODE, NATIVE_PROVIDER_OVERLOADED_MESSAGE } from "./native-provider-failure.js"; import { NATIVE_TOOL_RECEIPT_LIMIT_CODE, NATIVE_TOOL_RECEIPT_LIMIT_CONTINUATION_DELAY_MS, NATIVE_TOOL_RECEIPT_LIMIT_HINT, NATIVE_TOOL_RECEIPT_LIMIT_MAX_CONTINUATIONS, NATIVE_TOOL_RECEIPT_LIMIT_MESSAGE, nativeRunHasStopRequest } from "./native-tool-receipt-limit.js"; @@ -13,6 +13,9 @@ import { NATIVE_AGENT_BLOCKER_CONTINUATION_CODE, NATIVE_AGENT_BLOCKER_CONTINUATI NATIVE_AGENT_BLOCKER_MAX_CONTINUATIONS, NATIVE_AGENT_BLOCKER_MESSAGE } from "./native-agent-blocker.js"; import { NativeStatusRaceError } from "./status-decision-committer.js"; import { freshSessionRetryContext } from "./fresh-session-retry-context.js"; +import { NATIVE_RESUME_REFUSAL_REASONS, NATIVE_RESUME_REFUSED_CONTINUATION_CODE, NATIVE_RESUME_REFUSED_CONTINUATION_DELAY_MS, + NATIVE_RESUME_REFUSED_MAX_CONTINUATIONS, type NativeResumeRefusalReason, nativeResumeRefusedHint, nativeResumeRefusedMessage, +} from "./native-resume-refused-continuation.js"; type NativeRetryTarget = { tx: Db; @@ -96,6 +99,39 @@ export async function materializeNativeAgentBlockerContinuation(input: NativeRet }); } +export async function materializeNativeResumeRefusedContinuation(input: NativeRetryTarget) + : Promise<{ retryId: string; reason: NativeResumeRefusalReason } | null> { + const [run] = await input.tx.select().from(heartbeatRuns).where(and( + eq(heartbeatRuns.companyId, input.companyId), eq(heartbeatRuns.id, input.runId), + eq(heartbeatRuns.agentId, input.agentId), eq(heartbeatRuns.nativeIssueId, input.issueId), + )).for("update"); + if (!run || run.runtimeMode !== "native" || nativeRunHasStopRequest(run.resultJson) + || executionRetryAttemptCount(run, NATIVE_RESUME_REFUSED_CONTINUATION_CODE) >= NATIVE_RESUME_REFUSED_MAX_CONTINUATIONS) return null; + const refusalReason = sql`${environmentLeases.metadata}#>>'{runnerTaskAdmissionRejection,reason}'`; + const [refusedResume] = await input.tx.select({ reason: refusalReason }).from(environmentLeases).where(and( + eq(environmentLeases.companyId, input.companyId), eq(environmentLeases.heartbeatRunId, run.id), + inArray(refusalReason, [...NATIVE_RESUME_REFUSAL_REASONS]), + sql`coalesce(${environmentLeases.metadata}->>'runnerTaskResumeFrom', '') <> ''`, + )).limit(1); + if (!refusedResume) return null; + const reason = refusedResume.reason as NativeResumeRefusalReason; + const retryId = await materializeNativeFreshSessionRetry(input, { + reason: NATIVE_RESUME_REFUSED_CONTINUATION_CODE, + maxRetries: NATIVE_RESUME_REFUSED_MAX_CONTINUATIONS, + delayMs: () => NATIVE_RESUME_REFUSED_CONTINUATION_DELAY_MS, + message: nativeResumeRefusedMessage(reason), + idempotencyPrefix: "native-resume-refused", + exhaustedError: "native_resume_refused_continuation_exhausted", + refuseStopped: true, + context: source => ({ + livenessContinuationSourceRunId: source.id, + livenessContinuationReason: NATIVE_RESUME_REFUSED_CONTINUATION_CODE, + livenessContinuationInstruction: nativeResumeRefusedHint(reason), + }), + }); + return { retryId, reason }; +} + async function materializeNativeFreshSessionRetry(input: NativeRetryTarget, lane: NativeRetryLane) { const [run] = await input.tx.select().from(heartbeatRuns).where(and( eq(heartbeatRuns.companyId, input.companyId), eq(heartbeatRuns.id, input.runId), @@ -108,7 +144,7 @@ async function materializeNativeFreshSessionRetry(input: NativeRetryTarget, lane eq(heartbeatRuns.companyId, input.companyId), eq(heartbeatRuns.retryOfRunId, run.id), )).limit(1); if (existing) return existing.id; - const attempt = executionFailureRetryCount(run) + 1; + const attempt = executionRetryAttemptCount(run, lane.reason) + 1; if (attempt > lane.maxRetries) throw new Error(lane.exhaustedError); const now = new Date(); const dueAt = new Date(now.getTime() + lane.delayMs(attempt)); diff --git a/server/src/services/native-runtime/native-resume-refused-continuation.integration.test.ts b/server/src/services/native-runtime/native-resume-refused-continuation.integration.test.ts new file mode 100644 index 00000000000..121341578cc --- /dev/null +++ b/server/src/services/native-runtime/native-resume-refused-continuation.integration.test.ts @@ -0,0 +1,136 @@ +import { randomUUID } from "node:crypto"; +import { and, eq } from "drizzle-orm"; +import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; +import { agents, companies, companyMemberships, completionContracts, createDb, environmentLeases, heartbeatRuns, issueRecoveryActions, + issues, nativeRunFinalizations } from "@paperclipai/db"; +import type { NativeExecutionInputV1 } from "@paperclipai/paperclip-runner"; +import { startEmbeddedPostgresTestDatabase } from "../../__tests__/helpers/embedded-postgres.js"; + +const provider = vi.hoisted(() => ({ execute: vi.fn() })); +vi.mock("../../vendor/paperclip-runner/index.js", async (importOriginal) => ({ + ...(await importOriginal()), + executeNativeSession: provider.execute, +})); + +import { executePaperclipNativeSession } from "./native-session-executor.js"; +import { buildNativeCompletionContract } from "./completion-contracts.js"; +import { prepareNativeHeartbeatRun } from "./prepare-native-run.js"; +import { heartbeatService } from "../heartbeat.js"; +import { taskInterruptionPresentation } from "../task-interruption-presentation.js"; +import { NATIVE_RESUME_REFUSED_CONTINUATION_CODE, NATIVE_RESUME_REFUSED_CONTINUATION_DELAY_MS, nativeResumeRefusedHint, + nativeResumeRefusedMessage, type NativeResumeRefusalReason as Reason } from "./native-resume-refused-continuation.js"; + +describe("native run whose environment refuses to resume its saved session", () => { + let temporary: Awaited>; + let db: ReturnType; + const companyId = randomUUID(); + const agentId = randomUUID(); + + beforeAll(async () => { + temporary = await startEmbeddedPostgresTestDatabase("native-resume-refused-"); + db = createDb(temporary.connectionString); + await db.insert(companies).values({ id: companyId, name: "Resume refused", issuePrefix: "NRR" }); + await db.insert(agents).values({ id: agentId, companyId, name: "Codex agent", status: "active", adapterType: "paperclip_runner", + adapterConfig: { provider: "codex", model: "test-model" } }); + await db.insert(companyMemberships).values({ companyId, principalType: "user", principalId: "board-user", status: "active", membershipRole: "member" }); + }); + afterAll(async () => { await temporary?.cleanup(); }); + + async function refuseAdmission(input: { reason: Reason; resumedFrom: string | null; scheduledRetryReason?: string; + scheduledRetryAttempt?: number; resultJson?: Record }) { + const issueId = randomUUID(); + await db.insert(issues).values({ id: issueId, companyId, title: "Write the brief", status: "in_progress", workMode: "standard", + assigneeAgentId: agentId, createdByUserId: "board-user", responsibleUserId: "board-user" }); + const [issue] = await db.select().from(issues).where(eq(issues.id, issueId)); + const runId = randomUUID(); + const [run] = await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, status: "running", runtimeMode: "native", + nativeIssueId: issueId, responsibleUserId: "board-user", invocationSource: "automation", triggerDetail: "system", + contextSnapshot: { issueId, wakeCommentId: "original-message" }, resultJson: input.resultJson ?? null, + scheduledRetryReason: input.scheduledRetryReason ?? null, scheduledRetryAttempt: input.scheduledRetryAttempt ?? 0 }).returning(); + await db.update(issues).set({ executionRunId: runId }).where(eq(issues.id, issueId)); + const native = await prepareNativeHeartbeatRun({ db, run, issue, environmentLeaseId: randomUUID() }); + const [contract] = await db.select().from(completionContracts).where(eq(completionContracts.issueId, issueId)); + await db.insert(nativeRunFinalizations).values({ runId, companyId, issueId, phase: "observed" }); + await db.insert(environmentLeases).values({ companyId, issueId, heartbeatRunId: runId, providerLeaseId: "attempt-task", + metadata: { driver: "plugin", runnerTaskResumeFrom: input.resumedFrom, runnerTaskDispatched: false, runnerTaskExecutionStopped: true, + runnerTaskAdmissionRejection: { taskId: "attempt-task", reason: input.reason } } }); + const execution: NativeExecutionInputV1 = { + schema: "paperclip.native-execution-input.v1", + binding: { companyId, runId, issueId, agentId, executionWorkspaceId: runId }, + provider: { kind: "codex", model: "test-model" }, + task: { identifier: issueId, title: issue.title, description: null, prompt: "Write the brief.", workMode: "standard" }, + workspace: { cwd: "/tmp", repoUrl: null, repoRef: null, branchName: null }, + session: { normalizedSessionId: native.normalizedSessionId, driverKind: "codex_app_server", protocolVersion: 1, + lifecyclePolicy: { mode: "per_turn", idleTimeoutMs: null } }, + completionContract: { id: contract.id, sha256: contract.canonicalSha256, schemaVersion: "paperclip.completion-contract.v1", + contract: buildNativeCompletionContract(issue, { revision: contract.revision }) }, + interactionResponses: [], credentialBindings: [], + }; + await db.update(heartbeatRuns).set({ runnerProfileJson: { nativeExecutionInput: execution } }).where(eq(heartbeatRuns.id, runId)); + provider.execute.mockReset().mockRejectedValue(new Error(`runner_task_admission_rejected: ${input.reason}`)); + await executePaperclipNativeSession({ db, execution, runnerInstanceId: native.runnerInstanceId, backend: { + descriptor: async () => { throw new Error("Unexpected provider call"); }, + openSession: async () => { throw new Error("Unexpected provider call"); }, + } }).catch(() => undefined); + const [coordinator] = await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, runId)); + const retries = await db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, companyId), eq(heartbeatRuns.retryOfRunId, runId))); + const holds = await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, issueId)); + const [updatedIssue] = await db.select().from(issues).where(eq(issues.id, issueId)); + return { issueId, runId, coordinator, retries, holds, issue: updatedIssue! }; + } + + function expectPermanentRefusal(refused: Awaited>) { + expect(refused.coordinator).toMatchObject({ phase: "terminal_failure", failureCode: "runner_task_admission_rejected", nextAttemptAt: null, + failureDetail: expect.objectContaining({ nextAction: expect.stringContaining("Automatic retries are stopped") }) }); + expect(refused.coordinator.failureDetail).not.toHaveProperty("successorRunId"); + expect(refused.retries).toHaveLength(0); + expect(refused.issue).toMatchObject({ status: "blocked" }); + expect(refused.holds).toEqual([expect.objectContaining({ cause: "runner_task_admission_rejected", ownerType: "board" })]); + } + + const reasons: Reason[] = ["account_binding_mismatch", "session_state_unavailable"]; + + it.each(reasons)("continues a resumed session refused with %s once in a fresh session", async reason => { + const refused = await refuseAdmission({ reason, resumedFrom: "prior-task" }); + const [retry] = refused.retries; + expect(refused.retries).toHaveLength(1); + expect(retry).toMatchObject({ status: "scheduled_retry", scheduledRetryReason: NATIVE_RESUME_REFUSED_CONTINUATION_CODE, + scheduledRetryAttempt: 1, errorCode: NATIVE_RESUME_REFUSED_CONTINUATION_CODE, error: nativeResumeRefusedMessage(reason), + contextSnapshot: { issueId: refused.issueId, forceFreshSession: true, retryOfRunId: refused.runId, + livenessContinuationSourceRunId: refused.runId, livenessContinuationReason: NATIVE_RESUME_REFUSED_CONTINUATION_CODE, + livenessContinuationInstruction: nativeResumeRefusedHint(reason) } }); + expect(retry!.contextSnapshot).not.toHaveProperty("wakeCommentId"); + expect(retry!.scheduledRetryAt!.getTime() - Date.now()).toBeLessThanOrEqual(NATIVE_RESUME_REFUSED_CONTINUATION_DELAY_MS); + expect(refused.coordinator).toMatchObject({ phase: "terminal_failure", failureCode: "runner_task_admission_rejected", + failureDetail: expect.objectContaining({ successorRunId: retry!.id, nextAction: nativeResumeRefusedMessage(reason) }) }); + const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, refused.runId)); + expect(run).toMatchObject({ status: "failed", errorCode: "runner_task_admission_rejected" }); + expect(refused.holds).toHaveLength(0); + expect(refused.issue).toMatchObject({ status: "in_progress", assigneeAgentId: agentId, executionRunId: null }); + await expect(taskInterruptionPresentation(db, refused.issue)).resolves.toMatchObject({ state: "retry_scheduled", canRetry: false }); + const scheduler = heartbeatService(db, { runtimeEnv: {} }); + expect(await scheduler.promoteDueScheduledRetries(retry!.scheduledRetryAt!)).toMatchObject({ promoted: 1, runIds: [retry!.id] }); + await db.update(heartbeatRuns).set({ status: "cancelled" }).where(eq(heartbeatRuns.id, retry!.id)); + }, 120_000); + + it("names why the saved session could not be resumed", () => { + expect(nativeResumeRefusedHint("account_binding_mismatch")).toContain("account binding changed"); + expect(nativeResumeRefusedHint("session_state_unavailable")).toContain("could not find the saved session state"); + }); + + it.each(reasons)("stops when a fresh session is refused with %s", async reason => { + expectPermanentRefusal(await refuseAdmission({ reason, resumedFrom: null })); + }, 120_000); + + it.each(reasons)("stops when the fresh continuation itself is refused with %s", async reason => { + expectPermanentRefusal(await refuseAdmission({ reason, resumedFrom: "prior-task", + scheduledRetryReason: NATIVE_RESUME_REFUSED_CONTINUATION_CODE, scheduledRetryAttempt: 1 })); + }, 120_000); + + it("does not continue a run a person stopped", async () => { + const refused = await refuseAdmission({ reason: "account_binding_mismatch", resumedFrom: "prior-task", + resultJson: { cancelledByActorType: "user" } }); + expect(refused.retries).toHaveLength(0); + expect(refused.coordinator.failureDetail).not.toHaveProperty("successorRunId"); + }, 120_000); +}); diff --git a/server/src/services/native-runtime/native-resume-refused-continuation.ts b/server/src/services/native-runtime/native-resume-refused-continuation.ts new file mode 100644 index 00000000000..74c1bbd1ee3 --- /dev/null +++ b/server/src/services/native-runtime/native-resume-refused-continuation.ts @@ -0,0 +1,22 @@ +export const NATIVE_RESUME_REFUSAL_REASONS = ["account_binding_mismatch", "session_state_unavailable"] as const; +export type NativeResumeRefusalReason = typeof NATIVE_RESUME_REFUSAL_REASONS[number]; +export const NATIVE_RESUME_REFUSED_CONTINUATION_CODE = "native_resume_refused_continuation"; +export const NATIVE_RESUME_REFUSED_MAX_CONTINUATIONS = 1; +export const NATIVE_RESUME_REFUSED_CONTINUATION_DELAY_MS = 5_000; + +const REFUSAL_CAUSES: Record = { + account_binding_mismatch: "the execution environment's account binding changed since that session started", + session_state_unavailable: "the execution environment could not find the saved session state", +}; + +export function nativeResumeRefusedMessage(reason: NativeResumeRefusalReason) { + return `The saved provider session could not be resumed, because ${REFUSAL_CAUSES[reason]}. ` + + "Paperclip continues the task once in a fresh provider session with the same workspace."; +} + +export function nativeResumeRefusedHint(reason: NativeResumeRefusalReason) { + return `The previous run could not resume its saved provider session, because ${REFUSAL_CAUSES[reason]}. ` + + "Paperclip started this fresh session once to continue. Earlier sessions may already have completed some steps: " + + "check the workspace files, this task's documents and its comments before repeating a step, and never post a comment or save a document that already exists. " + + "Then finish the remaining work and report the real outcome."; +} diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts index 6ca4d9d40e8..7c8b31b6801 100644 --- a/server/src/services/native-runtime/native-session-executor.ts +++ b/server/src/services/native-runtime/native-session-executor.ts @@ -74,6 +74,8 @@ import { environmentTaskOperationSchema, environmentTaskResultSchema } from "@pa import { preparePluginRunnerCredentials } from "./plugin-runner-credentials.js"; import { createPluginRunnerTaskOwner, verifyPluginRunnerTaskReattachment } from "./plugin-runner-task.js"; import { findNativeFailedBeforeProviderTurn, NATIVE_FAILED_BEFORE_PROVIDER_TURN_CODE, NativeFailedBeforeProviderTurnError } from "./failed-before-provider-turn.js"; +import { materializeNativeResumeRefusedContinuation } from "./native-provider-capacity-retry.js"; +import { nativeResumeRefusedMessage } from "./native-resume-refused-continuation.js"; import { findNativePredecessorRetirementUnproven, NATIVE_PREDECESSOR_RETIREMENT_UNPROVEN_CODE, NativePredecessorRetirementDirectoryBusyError, NativePredecessorRetirementUnprovenError } from "./predecessor-retirement.js"; import { inspectSandboxSessionRunner, retireSandboxRunnerPortHolders, sandboxSessionRunnerExited, type SandboxSessionRunnerInspection, @@ -13927,8 +13929,14 @@ async function executePaperclipNativeSessionAttempt( failureTask.executionRunId === input.execution.binding.runId) && (!failureTask.checkoutRunId || failureTask.checkoutRunId === input.execution.binding.runId); + const resumeRefusedSuccessor = !ownershipUnverified && stillOwnsTask && phase === "terminal_failure" + && sourceFailureCode === "runner_task_admission_rejected" + ? await materializeNativeResumeRefusedContinuation({ tx: tx as unknown as Db, + companyId: input.execution.binding.companyId, issueId: input.execution.binding.issueId, + runId: input.execution.binding.runId, agentId: input.execution.binding.agentId }) + : null; let failureBlockStatusVersion: number | undefined; - if (stillOwnsTask && recoveryProjection.issueStatus) { + if (stillOwnsTask && recoveryProjection.issueStatus && !resumeRefusedSuccessor) { const projected = await issueService(tx as unknown as Db).update( input.execution.binding.issueId, { status: recoveryProjection.issueStatus }, @@ -13948,6 +13956,14 @@ async function executePaperclipNativeSessionAttempt( .where(eq(issues.id, input.execution.binding.issueId)); } if (!stillOwnsTask) return; + if (resumeRefusedSuccessor) { + await tx.update(nativeRunFinalizations).set({ + failureDetail: sql`coalesce(${nativeRunFinalizations.failureDetail}, '{}'::jsonb) || ${JSON.stringify({ + successorRunId: resumeRefusedSuccessor.retryId, nextAction: nativeResumeRefusedMessage(resumeRefusedSuccessor.reason) })}::jsonb`, + }).where(and(eq(nativeRunFinalizations.runId, input.execution.binding.runId), + eq(nativeRunFinalizations.companyId, input.execution.binding.companyId))); + return; + } // The hold's reset deadline belongs to the provider-limit owner. if (providerLimit?.plan.automatic) await notifyDeliveryWork(tx, DELIVERY_QUEUES.providerLimitResume, JSON.stringify({ companyId: input.execution.binding.companyId }));