From 50633695e7ca67b4682a2b524884260b666fe4c3 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Thu, 26 Nov 2026 14:00:22 +0000 Subject: [PATCH] fix(native-runtime): keep external chat waits when finalization retries after the run settles (#23049) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Native runs can end by waiting for the next external chat message, for example a GitHub review agent that waits for the next push > - The finalizer must prove that the run still owns the task before it records that wait > - When the first status commit loses a lock race, the finalizer retries later. By then the heartbeat has settled the run and released the task execution > - The retry then reads "authorization lost", so the task stays `in_progress` with no run and no registered wait > - This pull request keeps the wait authority for a settled run whose own saved result is still being applied, and gives tasks already in this state one bounded continuation > - The benefit is that these tasks never sit idle with no next step ## Linked Issues or Issue Description **What happened?** A GitHub review agent published a review and yielded with a `response_wake` continuation. The run ended with `finalizationReasonCode: external_chat_response_wait_authorization_lost` and `finalizationFailureCount: 1`. The task stayed `in_progress` with no run for more than 16 hours. Earlier runs on the same tasks ended with `external_chat_response_waiting`. Two tasks showed this on staging. **Expected behavior** The run records `external_chat_response_waiting`, and the task waits for the next GitHub event. If the wait truly cannot be registered while chat access is still allowed, the task gets one continuation instead of an idle `in_progress` state. **Steps to reproduce** 1. Start a native external-chat turn that yields with `response_wake`. 2. Hold a row lock that the status committer needs (for example the chat endpoint) until the finalizer's quick retries end with `status_cas_exhausted`. 3. Settle the run as `succeeded` and release the task execution, as the heartbeat does. 4. Let the scheduled finalization retry run. The decision is `external_chat_response_wait_authorization_lost`. **Paperclip version or commit** `master` at 85ad16b47e. ## What Changed - `resolveExternalChatResponseWaitAuthorizationInTransaction` accepts a settled owner in addition to a live owner. The check is `settledRunOwnsResponseWait` in the new `external-chat-wait-authorization.ts`. A settled owner is a `running` or `succeeded` run with no other execution or checkout run on the task and no newer run of the task in any state, and either: - its own saved result is still being finalized, or - its committed decision is `external_chat_response_wait_authorization_lost`. The assignee, agent status, inbound message links, and current principal and destination policy are still checked as before. - The newer-run check is one shared predicate, `hasNewerIssueRun` in the new `native-run-ownership.ts`. `readPreservedNativeResultFinalization` now uses it too, and it compares timestamps in SQL. - `readPublishedGitHubReviewCompletionContinuationInTransaction` lets the same authorization decide ownership for a `succeeded` run. - `EXTERNAL_CHAT_RESPONSE_WAIT_AUTHORIZATION_LOST` moves to `status-arbiter.ts`, which owns the reason. - The stranded-task sweep (`continueUnregisteredExternalChatWait`) now finds a settled external-chat turn whose wait was lost while chat access is still allowed. It queues one continuation (`issue.external_chat_wait_recovery`) with `retryOfRunId` set to that turn. It skips the task when a wake is already queued. The sweep has already checked the budget at that point. A wait lost because chat access was revoked stays parked, as before. - The continuation uses an issue-state guard. Under the issue lock, the queue checks that the task is still `in_progress` for the same assignee, and that no wake or run already continues the source run (new `withoutSuccessorOfRunId`). Overlapping sweeps therefore queue at most one continuation. - `chat-attachment-reuse.ts`, `recovery/service.ts` and `heartbeat/queue.ts` were already over 1,000 lines. The new ownership check is in its own module. The sweep helper and the queue guard stay next to the code they extend. ## Verification - Red, then green: `keeps the response wait when a contended finalization is retried after the {run settled, execution released, run settled and execution released}` in `server/src/services/native-runtime/external-chat-wait.integration.test.ts`. Before the fix all three cases recorded `external_chat_response_wait_authorization_lost`. - Red, then green: `continues a settled task whose response wait was lost while chat access is still allowed` queues exactly one continuation over two sweeps. The `revoked` case queues none. - Red, then green: `queues one continuation for a lost wait when recovery passes overlap through the real queue`. Without the queue guard it saved two continuation wakes. - `re-derives a published review wait when its contended finalization is retried after the run …`: a settled published-review turn records `external_chat_response_waiting` in `in_review`; with a newer queued run it records `external_chat_response_wait_authorization_lost`. - `authorizes a settled run's lost wait only with …`: another execution run, another checkout run, a terminal finalization, or a committed decision with another reason revokes the wait. - `npx vitest run src/services/native-runtime/external-chat-wait.integration.test.ts src/__tests__/issue-list-review-wait-authorization.integration.test.ts src/__tests__/chat-channels/github-review-response-maintenance.integration.test.ts src/services/native-runtime/status-arbiter.test.ts` (in `server/`): 389 passed. - `npx tsc --noEmit -p server/tsconfig.json`. ## Risks - A settled run can now authorize its wait when no newer run owns the task. A newer run in any state, another execution or checkout run, or a run that is not `running` or `succeeded` still revokes the wait. - Tasks already in this state get one continuation run after deploy. The sweep skips the task when the budget blocks new work, and it queues at most one continuation per stranded turn. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), with tool use and code execution in Claude Code. ## 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 - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- server/src/services/heartbeat/queue.ts | 14 ++ .../src/services/heartbeat/run-preparation.ts | 2 + .../native-runtime/chat-attachment-reuse.ts | 12 +- .../external-chat-wait-authorization.ts | 43 ++++ .../external-chat-wait.integration.test.ts | 198 ++++++++++++++++++ .../native-runtime/native-run-ownership.ts | 20 ++ .../preserved-native-result-finalization.ts | 10 +- .../services/native-runtime/status-arbiter.ts | 3 +- server/src/services/recovery/service.ts | 66 +++++- 9 files changed, 355 insertions(+), 13 deletions(-) create mode 100644 server/src/services/native-runtime/external-chat-wait-authorization.ts create mode 100644 server/src/services/native-runtime/native-run-ownership.ts 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))