diff --git a/server/src/services/heartbeat/queue.ts b/server/src/services/heartbeat/queue.ts index bfa9c1be7aa..acff3577cc3 100644 --- a/server/src/services/heartbeat/queue.ts +++ b/server/src/services/heartbeat/queue.ts @@ -3872,6 +3872,20 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende eq(heartbeatRuns.companyId, issue.companyId), eq(heartbeatRuns.nativeIssueId, issue.id), eq(heartbeatRuns.runtimeMode, "native"), inArray(heartbeatRuns.status, ["queued", "running", "scheduled_retry"]), )).limit(1).then(rows => rows[0] ?? null); + // Under the issue lock, so overlapping sweeps cannot both continue + // the same run. A skipped, failed or cancelled wake is no successor. + const successorRunId = issueStateGuard?.withoutSuccessorOfRunId; + if (successorRunId && ( + await tx.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(and( + eq(heartbeatRuns.companyId, issue.companyId), eq(heartbeatRuns.retryOfRunId, successorRunId), + )).limit(1).then(rows => rows.length > 0) || + await tx.select({ id: agentWakeupRequests.id }).from(agentWakeupRequests).where(and( + eq(agentWakeupRequests.companyId, issue.companyId), + sql`${agentWakeupRequests.payload}->>'issueId' = ${issue.id}`, + sql`${agentWakeupRequests.payload}->>'retryOfRunId' = ${successorRunId}`, + notInArray(agentWakeupRequests.status, ["skipped", "failed", "cancelled"]), + )).limit(1).then(rows => rows.length > 0) + )) return { kind: "skipped" as const }; if ( issueStateGuard && (!issueStateGuard.statuses.includes(issue.status) || diff --git a/server/src/services/heartbeat/run-preparation.ts b/server/src/services/heartbeat/run-preparation.ts index 4d2d8f50e65..5a6ba478ce1 100644 --- a/server/src/services/heartbeat/run-preparation.ts +++ b/server/src/services/heartbeat/run-preparation.ts @@ -840,6 +840,8 @@ export interface WakeupOptions { statusVersion?: number; monitorNextCheckAt?: string; monitorWakeRequestedAt?: string; + /** Skip when a wake or run that continues this run already exists. */ + withoutSuccessorOfRunId?: string; /** Internal diagnostic only; the callback cannot grant admission. */ onExecutionDeferred?: (blockerCause: string, recoveryActionId?: string | null) => void; }; diff --git a/server/src/services/native-runtime/chat-attachment-reuse.ts b/server/src/services/native-runtime/chat-attachment-reuse.ts index 648891c375c..0723d53f9cd 100644 --- a/server/src/services/native-runtime/chat-attachment-reuse.ts +++ b/server/src/services/native-runtime/chat-attachment-reuse.ts @@ -40,6 +40,7 @@ import { boundExternalChatProvider } from "./external-chat-provider.js"; import { resolveExternalChatQuestionResponse } from "./external-chat-question-response.js"; import { githubRunReplyState } from "../chat-run-publications.js"; import { readPreservedNativeResultFinalization } from "./preserved-native-result-finalization.js"; +import { settledRunOwnsResponseWait } from "./external-chat-wait-authorization.js"; // This boundary reads identity and wake authority, never launch renderings, // saved provider profiles, or run output. Keep the nested wake proof narrow too. @@ -829,6 +830,7 @@ export async function resolveExternalChatResponseWaitAuthorizationInTransaction( .select({ assigneeAgentId: issues.assigneeAgentId, executionRunId: issues.executionRunId, + checkoutRunId: issues.checkoutRunId, }) .from(issues) .where( @@ -900,12 +902,14 @@ export async function resolveExternalChatResponseWaitAuthorizationInTransaction( : actorQuery.for("update").limit(1)); const preserved = run && run.status !== "running" ? await readPreservedNativeResultFinalization(tx, binding) : null; + const liveOwner = run.status === "running" && issue?.executionRunId === binding.runId; + const settledOwner = !preserved && !liveOwner && issue + ? await settledRunOwnsResponseWait(tx, binding, run.status, issue) : false; if ( !issue || !actor || - (!preserved && run.status !== "running") || + !(preserved || liveOwner || settledOwner) || issue.assigneeAgentId !== binding.agentId || - (!preserved && issue.executionRunId !== binding.runId) || ["paused", "terminated", "pending_approval", "error"].includes( actor.status, ) @@ -1025,7 +1029,9 @@ export async function readPublishedGitHubReviewCompletionContinuationInTransacti eq(heartbeatRuns.agentId, binding.agentId), eq(heartbeatRuns.nativeIssueId, binding.issueId), eq(heartbeatRuns.runtimeMode, "native"), )).limit(1); - if (!run || run.status !== "running" && !await readPreservedNativeResultFinalization(tx, binding)) return null; + // Ownership itself is proven by the authorization below. + if (!run || !["running", "succeeded"].includes(run.status) && + !await readPreservedNativeResultFinalization(tx, binding)) return null; const wait = await readInheritedGitHubReviewWait(tx, run); if (wait?.kind !== "published") return null; if (wait.reviewRunId !== run.id) { diff --git a/server/src/services/native-runtime/external-chat-wait-authorization.ts b/server/src/services/native-runtime/external-chat-wait-authorization.ts new file mode 100644 index 00000000000..82ef50d92b2 --- /dev/null +++ b/server/src/services/native-runtime/external-chat-wait-authorization.ts @@ -0,0 +1,43 @@ +import { and, eq } from "drizzle-orm"; +import { nativeRunFinalizations, statusDecisions, type Db } from "@paperclipai/db"; +import { hasNewerIssueRun, type NativeRunBinding as RunBinding } from "./native-run-ownership.js"; +import { EXTERNAL_CHAT_RESPONSE_WAIT_AUTHORIZATION_LOST } from "./status-arbiter.js"; + +/** + * The heartbeat settles a run and releases its task execution independently + * of the run's native finalizer. When the finalizer's first status commit + * loses a race, its scheduled retry applies the same saved result after the + * run is already settled. That run still owns its response wait while no + * other run owns the task: either its own saved result is still being + * applied, or its committed decision recorded only that the wait authority + * was lost. The caller still checks the assignee, the agent, and current + * principal and destination policy. + */ +export async function settledRunOwnsResponseWait( + tx: Db, + binding: RunBinding, + runStatus: string, + issue: { executionRunId: string | null; checkoutRunId: string | null }, +): Promise { + if (!["running", "succeeded"].includes(runStatus)) return false; + if ((issue.executionRunId && issue.executionRunId !== binding.runId) || + (issue.checkoutRunId && issue.checkoutRunId !== binding.runId)) return false; + const [coordinator] = await tx.select({ + phase: nativeRunFinalizations.phase, + resultId: nativeRunFinalizations.resultId, + decisionId: nativeRunFinalizations.decisionId, + }).from(nativeRunFinalizations).where(and( + eq(nativeRunFinalizations.runId, binding.runId), + eq(nativeRunFinalizations.companyId, binding.companyId), + eq(nativeRunFinalizations.issueId, binding.issueId), + )).limit(1); + if (!coordinator?.resultId || coordinator.phase === "terminal_failure") return false; + if (await hasNewerIssueRun(tx, binding)) return false; + if (coordinator.phase !== "committed") return true; + if (!coordinator.decisionId) return false; + const [decision] = await tx.select({ reasonCode: statusDecisions.reasonCode }).from(statusDecisions) + .where(and(eq(statusDecisions.id, coordinator.decisionId), eq(statusDecisions.companyId, binding.companyId), + eq(statusDecisions.issueId, binding.issueId), eq(statusDecisions.runId, binding.runId), + eq(statusDecisions.applicationState, "applied"))).limit(1); + return decision?.reasonCode === EXTERNAL_CHAT_RESPONSE_WAIT_AUTHORIZATION_LOST; +} diff --git a/server/src/services/native-runtime/external-chat-wait.integration.test.ts b/server/src/services/native-runtime/external-chat-wait.integration.test.ts index c064e25e1b0..43ff8ddb3b9 100644 --- a/server/src/services/native-runtime/external-chat-wait.integration.test.ts +++ b/server/src/services/native-runtime/external-chat-wait.integration.test.ts @@ -83,6 +83,7 @@ import { resolveHeartbeatRunResponse } from "../heartbeat-run-summary.js"; import { issueService } from "../issues.js"; import { issueThreadInteractionService } from "../issue-thread-interactions.js"; import { reconcileNativeFinalizations } from "./native-finalization-reconciler.js"; +import { recoveryService } from "../recovery/service.js"; import { authorizeChatConversationForBoundRun, isExternalChatWaitAuthorizationContention, @@ -5848,6 +5849,203 @@ describe("native external-chat response wait", () => { ).resolves.toEqual([]); }); + it.each([ + ["run settled", { run: true, release: false }], + ["execution released", { run: false, release: true }], + ["run settled and execution released", { run: true, release: true }], + ] as const)("keeps the response wait when a contended finalization is retried after the %s", async (_label, settle) => { + const fixture = await seedWaitTurn(); + let releaseEndpoint!: () => void; + let endpointLocked!: () => void; + const endpointRelease = new Promise((resolve) => { releaseEndpoint = resolve; }); + const endpointLockObserved = new Promise((resolve) => { endpointLocked = resolve; }); + const endpointHolder = db.transaction(async (tx) => { + await tx.select({ id: chatEndpoints.id }).from(chatEndpoints) + .where(eq(chatEndpoints.id, fixture.endpointId)).for("update"); + endpointLocked(); + await endpointRelease; + }); + await endpointLockObserved; + try { + // The live heartbeat finalizes without projecting the run status. + await finalizeNativeRun({ db, runId: fixture.runId, workspaceFinalizeStatus: "succeeded" }); + } finally { + releaseEndpoint(); + } + await endpointHolder; + await expect(db.select({ phase: nativeRunFinalizations.phase, failureCode: nativeRunFinalizations.failureCode }) + .from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, fixture.runId))) + .resolves.toEqual([{ phase: "retryable_failure", failureCode: "status_cas_exhausted" }]); + // The heartbeat then settles its run and releases the task execution + // before the scheduled finalization retry applies the saved result. + if (settle.run) await db.update(heartbeatRuns).set({ status: "succeeded", finishedAt: new Date() }) + .where(eq(heartbeatRuns.id, fixture.runId)); + if (settle.release) await db.update(issues).set({ executionRunId: null, executionLockedAt: null }) + .where(eq(issues.id, fixture.issueId)); + await db.update(nativeRunFinalizations).set({ nextAttemptAt: new Date(0) }) + .where(eq(nativeRunFinalizations.runId, fixture.runId)); + + await finalizeNativeRun({ db, runId: fixture.runId, workspaceFinalizeStatus: "succeeded", projectRunStatus: true }); + + await expect(db.select({ reasonCode: statusDecisions.reasonCode }).from(statusDecisions) + .where(eq(statusDecisions.issueId, fixture.issueId))).resolves.toEqual([ + { reasonCode: "external_chat_response_waiting" }, + ]); + }); + + it.each([ + ["still allowed", true, 1], + ["revoked", false, 0], + ] as const)("continues a settled task whose response wait was lost while chat access is %s", async (_label, restoreAccess, wakes) => { + // Tasks that settled before the retry fix keep the lost decision. Losing + // access to the conversation still parks the task without a new run. + const fixture = await seedWaitTurn(); + await db.update(companyMemberships).set({ status: "suspended", updatedAt: new Date() }) + .where(eq(companyMemberships.principalId, fixture.userId)); + await finalizeNativeRun({ db, runId: fixture.runId, workspaceFinalizeStatus: "succeeded", projectRunStatus: true }); + await expect(db.select({ reasonCode: statusDecisions.reasonCode }).from(statusDecisions) + .where(eq(statusDecisions.issueId, fixture.issueId))).resolves.toEqual([ + { reasonCode: "external_chat_response_wait_authorization_lost" }, + ]); + await db.update(issues).set({ executionRunId: null, executionLockedAt: null, checkoutRunId: null }) + .where(eq(issues.id, fixture.issueId)); + if (restoreAccess) await db.update(companyMemberships).set({ status: "active", updatedAt: new Date() }) + .where(eq(companyMemberships.principalId, fixture.userId)); + const enqueueWakeup = vi.fn(async (agentId: string, wake: { contextSnapshot?: Record }) => + db.insert(heartbeatRuns).values({ companyId: fixture.companyId, agentId, invocationSource: "automation", + status: "queued", contextSnapshot: wake.contextSnapshot ?? {} }).returning().then(rows => rows[0]!)); + const recovery = recoveryService(db, { enqueueWakeup: enqueueWakeup as never }); + + for (let sweep = 0; sweep < 2; sweep += 1) { + await recovery.reconcileStrandedAssignedIssues({ companyId: fixture.companyId, issueId: fixture.issueId }); + } + + expect(enqueueWakeup).toHaveBeenCalledTimes(wakes); + if (wakes) expect(enqueueWakeup).toHaveBeenCalledWith(fixture.agentId, expect.objectContaining({ + reason: "issue_continuation_needed", + payload: expect.objectContaining({ issueId: fixture.issueId, retryOfRunId: fixture.runId }), + })); + }); + + it.each([ + ["no other owner", "authorized"], + ["another execution run", "revoked"], + ["another checkout run", "revoked"], + ["a terminal finalization", "revoked"], + ["a committed decision other than a lost wait", "revoked"], + ] as const)("authorizes a settled run's lost wait only with %s", async (gate, expected) => { + const fixture = await seedWaitTurn(); + await db.update(companyMemberships).set({ status: "suspended", updatedAt: new Date() }) + .where(eq(companyMemberships.principalId, fixture.userId)); + await finalizeNativeRun({ db, runId: fixture.runId, workspaceFinalizeStatus: "succeeded", projectRunStatus: true }); + await db.update(companyMemberships).set({ status: "active", updatedAt: new Date() }) + .where(eq(companyMemberships.principalId, fixture.userId)); + const [run] = await db.select({ createdAt: heartbeatRuns.createdAt }).from(heartbeatRuns) + .where(eq(heartbeatRuns.id, fixture.runId)); + // An older run, so only the named owner check can revoke the wait. + const [other] = await db.insert(heartbeatRuns).values({ companyId: fixture.companyId, agentId: fixture.agentId, + invocationSource: "automation", status: "succeeded", finishedAt: new Date(), + createdAt: new Date(run!.createdAt.getTime() - 60_000), contextSnapshot: {} }).returning(); + await db.update(issues).set({ + executionRunId: gate === "another execution run" ? other!.id : null, + checkoutRunId: gate === "another checkout run" ? other!.id : null, + }).where(eq(issues.id, fixture.issueId)); + if (gate === "a terminal finalization") await db.update(nativeRunFinalizations).set({ phase: "terminal_failure" }) + .where(eq(nativeRunFinalizations.runId, fixture.runId)); + if (gate === "a committed decision other than a lost wait") await db.update(statusDecisions) + .set({ reasonCode: "response_wake_waiting_for_input" }).where(eq(statusDecisions.runId, fixture.runId)); + + await expect(chatWaitAuthority.resolveExternalChatResponseWaitAuthorization({ db, binding: { + companyId: fixture.companyId, issueId: fixture.issueId, runId: fixture.runId, agentId: fixture.agentId, + } })).resolves.toBe(expected); + }); + + it("queues one continuation for a lost wait when recovery passes overlap through the real queue", async () => { + const fixture = await seedWaitTurn(); + await db.update(companyMemberships).set({ status: "suspended", updatedAt: new Date() }) + .where(eq(companyMemberships.principalId, fixture.userId)); + await finalizeNativeRun({ db, runId: fixture.runId, workspaceFinalizeStatus: "succeeded", projectRunStatus: true }); + await db.update(issues).set({ executionRunId: null, executionLockedAt: null, checkoutRunId: null }) + .where(eq(issues.id, fixture.issueId)); + await db.update(companyMemberships).set({ status: "active", updatedAt: new Date() }) + .where(eq(companyMemberships.principalId, fixture.userId)); + const heartbeat = heartbeatService(db); + // Both passes read the task before either queues its continuation. + let arrived = 0; + let releasePasses!: () => void; + const bothRead = new Promise((resolve) => { releasePasses = resolve; }); + const enqueueWakeup = vi.fn(async (...args: Parameters) => { + arrived += 1; + if (arrived === 2) releasePasses(); + await bothRead; + return heartbeat.wakeup(...args); + }); + const passes = [recoveryService(db, { enqueueWakeup: enqueueWakeup as never }), + recoveryService(db, { enqueueWakeup: enqueueWakeup as never })]; + + await Promise.all(passes.map(pass => pass.reconcileStrandedAssignedIssues({ + companyId: fixture.companyId, issueId: fixture.issueId, skipRelatedRecovery: true, + }))); + + expect(enqueueWakeup).toHaveBeenCalledTimes(2); + const continuations = await db.select({ status: agentWakeupRequests.status }).from(agentWakeupRequests).where(and( + eq(agentWakeupRequests.companyId, fixture.companyId), + sql`${agentWakeupRequests.payload}->>'retryOfRunId' = ${fixture.runId}`, + sql`${agentWakeupRequests.status} not in ('skipped', 'failed', 'cancelled')`, + )); + expect(continuations).toHaveLength(1); + // Let the started continuation settle before the database closes. + await vi.waitFor(async () => expect(await db.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(and( + eq(heartbeatRuns.companyId, fixture.companyId), sql`${heartbeatRuns.status} in ('queued', 'running')`, + ))).toEqual([]), { timeout: 15_000, interval: 50 }); + }); + + it.each([ + ["settled and released", false, "external_chat_response_waiting", "in_review"], + ["settled and released with a newer queued run", true, "external_chat_response_wait_authorization_lost", "in_progress"], + ] as const)("re-derives a published review wait when its contended finalization is retried after the run %s", async (_label, newerRun, reasonCode, status) => { + const fixture = await seedPublishedReviewCompletionTurn(); + const authority = new PaperclipRunnerToolAuthority(db, fixture); + const read = () => authority.execute({ tool: "get_task_context", callId: randomUUID(), arguments: {} }); + const { resolveCompletionContinuation } = await import(new URL("../../../../packages/paperclip-runner/src/drivers/completion-continuation.ts", import.meta.url).href); + const resolved = await resolveCompletionContinuation({ ...fixture.result, continuation: undefined }, fixture.runId, read) as PrpStructuredRunResult; + expect(resolved).toMatchObject({ reportedWorkDisposition: "yielded", continuation: { kind: "response_wake" } }); + await expect(nativeCompletionFeedback(db, fixture.runId, resolved)).resolves.toContain("accepted"); + await fixture.port.completeRun({ result: resolved, terminal: fixture.terminal, callerResultId: `wait-result-${fixture.runId}` }); + let releaseEndpoint!: () => void; + let endpointLocked!: () => void; + const endpointRelease = new Promise((resolve) => { releaseEndpoint = resolve; }); + const endpointLockObserved = new Promise((resolve) => { endpointLocked = resolve; }); + const endpointHolder = db.transaction(async (tx) => { + await tx.select({ id: chatEndpoints.id }).from(chatEndpoints) + .where(eq(chatEndpoints.id, fixture.endpointId)).for("update"); + endpointLocked(); + await endpointRelease; + }); + await endpointLockObserved; + try { + await finalizeNativeRun({ db, runId: fixture.runId, workspaceFinalizeStatus: "succeeded" }); + } finally { + releaseEndpoint(); + } + await endpointHolder; + await expect(db.select({ phase: nativeRunFinalizations.phase }).from(nativeRunFinalizations) + .where(eq(nativeRunFinalizations.runId, fixture.runId))).resolves.toEqual([{ phase: "retryable_failure" }]); + await db.update(heartbeatRuns).set({ status: "succeeded", finishedAt: new Date() }) + .where(eq(heartbeatRuns.id, fixture.runId)); + await db.update(issues).set({ executionRunId: null, executionLockedAt: null, checkoutRunId: null }) + .where(eq(issues.id, fixture.issueId)); + // A queued run of the task owns its next step before it records a decision. + if (newerRun) await db.insert(heartbeatRuns).values({ companyId: fixture.companyId, agentId: fixture.agentId, + invocationSource: "automation", status: "queued", contextSnapshot: { issueId: fixture.issueId } }); + + await finalizeNativeRun({ db, runId: fixture.runId, workspaceFinalizeStatus: "succeeded", projectRunStatus: true }); + + await expect(db.select({ reasonCode: statusDecisions.reasonCode }).from(statusDecisions) + .where(eq(statusDecisions.runId, fixture.runId))).resolves.toEqual([{ reasonCode }]); + expect((await db.select().from(issues).where(eq(issues.id, fixture.issueId)))[0]).toMatchObject({ status }); + }); + it("retries a contended endpoint proof without deadlocking or scheduling work", async () => { const fixture = await seedWaitTurn(); let releaseEndpoint!: () => void; diff --git a/server/src/services/native-runtime/native-run-ownership.ts b/server/src/services/native-runtime/native-run-ownership.ts new file mode 100644 index 00000000000..a9794061a48 --- /dev/null +++ b/server/src/services/native-runtime/native-run-ownership.ts @@ -0,0 +1,20 @@ +import { and, eq, ne, or, sql } from "drizzle-orm"; +import { heartbeatRuns, type Db } from "@paperclipai/db"; + +export type NativeRunBinding = { companyId: string; issueId: string; runId: string }; + +/** + * A run of the same task created at or after the given run, in any state. A + * queued or admitted run owns the task's next step even before it records a + * decision. Compared in SQL: run timestamps keep microseconds that a Date drops. + */ +export async function hasNewerIssueRun(db: Db, binding: NativeRunBinding): Promise { + const [newer] = await db.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(and( + eq(heartbeatRuns.companyId, binding.companyId), ne(heartbeatRuns.id, binding.runId), + sql`${heartbeatRuns.createdAt} >= (select own_run.created_at from heartbeat_runs own_run + where own_run.id = ${binding.runId} and own_run.company_id = ${binding.companyId})`, + or(eq(heartbeatRuns.issueId, binding.issueId), eq(heartbeatRuns.nativeIssueId, binding.issueId), + sql`${heartbeatRuns.contextSnapshot}->>'issueId' = ${binding.issueId}`), + )).limit(1); + return Boolean(newer); +} diff --git a/server/src/services/native-runtime/preserved-native-result-finalization.ts b/server/src/services/native-runtime/preserved-native-result-finalization.ts index 0631dafd861..23d8fd4d004 100644 --- a/server/src/services/native-runtime/preserved-native-result-finalization.ts +++ b/server/src/services/native-runtime/preserved-native-result-finalization.ts @@ -1,4 +1,4 @@ -import { and, eq, gte, inArray, ne, or, sql } from "drizzle-orm"; +import { and, eq, inArray, ne, sql } from "drizzle-orm"; import { nativeEffectiveRunTerminalStateSql } from "./native-accepted-outcome.js"; import { completionContracts, heartbeatRuns, issueRecoveryActions, issues, nativeRunFinalizations, nativeRunResults, type Db } from "@paperclipai/db"; @@ -8,6 +8,7 @@ import { remoteExecutionHasStopped } from "../remote-execution-termination.js"; import { readSystemRecovery } from "../system-recovery-state.js"; import { completedWorkspaceRecoveryCondition, readWorkspaceRecovery, verifiedWorkspaceRepairReceipt } from "../workspace-recovery-receipt.js"; import { nativeSha256 } from "./canonical.js"; +import { hasNewerIssueRun } from "./native-run-ownership.js"; export const nativeWorkspaceFinalizationBlockSchema = z.object({ schema: z.literal("paperclip.native-workspace-finalization-block.v1"), @@ -107,12 +108,7 @@ export async function readPreservedNativeResultFinalization(db: Db, binding: { const recovery = readSystemRecovery(row.evidence), workspace = readWorkspaceRecovery(row.evidence); if (recovery?.state !== "complete" || recovery.sourceRunId !== binding.runId || !recovery.preservationOperationIds.length || workspace?.status !== "recovered" || workspace.runId !== binding.runId) return null; - const [newer] = await db.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(and( - eq(heartbeatRuns.companyId, binding.companyId), ne(heartbeatRuns.id, binding.runId), - gte(heartbeatRuns.createdAt, row.run.createdAt), or(eq(heartbeatRuns.issueId, binding.issueId), - eq(heartbeatRuns.nativeIssueId, binding.issueId), sql`${heartbeatRuns.contextSnapshot}->>'issueId' = ${binding.issueId}`), - )).limit(1); - if (newer || await issueTreeControlService(db).getActivePauseHoldGate(binding.companyId, binding.issueId) + if (await hasNewerIssueRun(db, binding) || await issueTreeControlService(db).getActivePauseHoldGate(binding.companyId, binding.issueId) || !await remoteExecutionHasStopped(db, binding.companyId, binding.runId)) return null; const receiptId = await verifiedWorkspaceRepairReceipt(db, row.run); if (!receiptId || !recovery.preservationOperationIds.includes(receiptId)) return null; diff --git a/server/src/services/native-runtime/status-arbiter.ts b/server/src/services/native-runtime/status-arbiter.ts index 4cfd69bd2b8..9f89a43ee4a 100644 --- a/server/src/services/native-runtime/status-arbiter.ts +++ b/server/src/services/native-runtime/status-arbiter.ts @@ -14,6 +14,7 @@ export const NATIVE_STATUS_ARBITER_POLICY_VERSION = "phase6-v14"; /** The automatic continuation after a failed turn is used once per chain. */ export const NATIVE_RUN_FAILED_RETRY_CAUSE = "native_run_failed"; export const NATIVE_RESPONSE_WAKE_WAITING_REASON = "response_wake_waiting_for_input"; +export const EXTERNAL_CHAT_RESPONSE_WAIT_AUTHORIZATION_LOST = "external_chat_response_wait_authorization_lost"; export const NATIVE_BLOCKER_SUPERSEDED_BY_QUEUED_REQUEST_CODE = "native_blocker_superseded_by_queued_request"; export const NATIVE_RUN_FAILED_CONTINUATION_EXHAUSTED_ACTION = "The agent's turn failed again after Paperclip continued it automatically. The saved work is kept. Check the failed run, then Retry the task."; @@ -849,7 +850,7 @@ export function arbitrateNativeStatus(input: { policyVersion: NATIVE_STATUS_ARBITER_POLICY_VERSION, statusAction: "preserve", toStatus: input.priorIssueStatus, - reasonCode: "external_chat_response_wait_authorization_lost", + reasonCode: EXTERNAL_CHAT_RESPONSE_WAIT_AUTHORIZATION_LOST, unblockDescriptor: null, // Revocation cannot be converted into an unrequested background run. effects: [], diff --git a/server/src/services/recovery/service.ts b/server/src/services/recovery/service.ts index 6541272ea02..046d21d957e 100644 --- a/server/src/services/recovery/service.ts +++ b/server/src/services/recovery/service.ts @@ -70,7 +70,8 @@ import { hasCommittedNativeBoardResponseWait, readNativeBoardResponseWaitSource, } from "../native-runtime/native-board-response-wait.js"; -import { authorizeChatConversationForBoundRun } from "../native-runtime/chat-attachment-reuse.js"; +import { authorizeChatConversationForBoundRun, resolveExternalChatResponseWaitAuthorization } from "../native-runtime/chat-attachment-reuse.js"; +import { EXTERNAL_CHAT_RESPONSE_WAIT_AUTHORIZATION_LOST } from "../native-runtime/status-arbiter.js"; import { ONBOARDING_FIRST_TASK_ORIGIN_KIND, PROVIDER_QUOTA_MONITOR_SERVICE_NAME, @@ -256,6 +257,7 @@ const DEFERRED_WAKE_CONTEXT_KEY = "_paperclipWakeContext"; const EXECUTION_REVIEW_PARTICIPANT_RECOVERY_REASON = "execution_review_participant_recovery"; const STRANDED_BOARD_ESCALATION_POLICY = "board_escalation_no_takeover_v1"; +const EXTERNAL_CHAT_WAIT_RECOVERY_SOURCE = "issue.external_chat_wait_recovery"; const DISPOSITION_REPAIR_IDEMPOTENCY_INDEX = "agent_wakeup_requests_disposition_repair_idempotency_uq"; const RESOLVED_DEPENDENCY_WAKE_BACKSTOP_CANDIDATE_LIMIT = 500; @@ -286,6 +288,7 @@ type RecoveryWakeupOptions = { issueStateGuard?: { statuses: string[]; assigneeAgentId: string; + withoutSuccessorOfRunId?: string; }; allowRunCoalescing?: boolean; }; @@ -1991,6 +1994,48 @@ export function recoveryService( .then((rows) => Boolean(rows[0])); } + /** + * Continue a settled external-chat turn whose response wait was lost + * although its requester and destination are still allowed. No provider + * message owns its next wake, so the task would otherwise idle in progress. + * A wait lost because access was revoked stays parked: revocation never + * starts work. Returns null when the turn is not such a wait. + * + * Bounded to one continuation per turn: the successor run owns the task, so + * the wait is no longer authorized; the queue rechecks for a successor under + * the issue lock, so overlapping sweeps cannot both queue one. + */ + async function continueUnregisteredExternalChatWait( + issue: RecoveryIssue, + latestRun: LatestIssueRun, + agentId: string, + ): Promise<"queued" | "skipped" | null> { + if ( + issue.status !== "in_progress" || latestRun?.status !== "succeeded" || + latestRun.agentId !== agentId || latestRun.agentId !== issue.assigneeAgentId || + !isExternalChatPresentationContext(latestRun.contextSnapshot) || + parseObject(latestRun.resultJson).finalizationReasonCode !== EXTERNAL_CHAT_RESPONSE_WAIT_AUTHORIZATION_LOST + ) return null; + // The caller already proved the invocation budget clear for this task. + const [authorization, queuedWake] = await Promise.all([ + resolveExternalChatResponseWaitAuthorization({ db, binding: { + companyId: issue.companyId, issueId: issue.id, runId: latestRun.id, agentId, + } }), + hasQueuedIssueWake(issue.companyId, issue.id, agentId), + ]); + if (authorization !== "authorized") return null; + if (queuedWake) return "skipped"; + const queued = await enqueueStrandedIssueRecovery({ + issueId: issue.id, + agentId, + reason: "issue_continuation_needed", + retryReason: "issue_continuation_needed", + source: EXTERNAL_CHAT_WAIT_RECOVERY_SOURCE, + retryOfRunId: latestRun.id, + }); + return queued ? "queued" : "skipped"; + } + async function hasQueuedIssueWake( companyId: string, issueId: string, @@ -2261,7 +2306,16 @@ export function recoveryService( assigneeAgentId: input.agentId, }, } - : {}), + : input.source === EXTERNAL_CHAT_WAIT_RECOVERY_SOURCE && input.retryOfRunId + ? { + // One continuation per settled turn, even across overlapping sweeps. + issueStateGuard: { + statuses: ["in_progress"], + assigneeAgentId: input.agentId, + withoutSuccessorOfRunId: input.retryOfRunId, + }, + } + : {}), payload: withRecoveryContext( { issueId: input.issueId, @@ -5310,6 +5364,14 @@ export function recoveryService( } continue; } + const externalChatWait = await continueUnregisteredExternalChatWait(issue, latestRun, agentId); + if (externalChatWait) { + if (externalChatWait === "queued") { + result.continuationRequeued += 1; + result.issueIds.push(issue.id); + } else result.skipped += 1; + continue; + } if ( latestRun?.status === "succeeded" && (await hasPersistedDurableWaitPath(issue, latestRun, pass))