diff --git a/doc/idle-approved-tool-recovery.md b/doc/idle-approved-tool-recovery.md index 571cb3f1d12..5f1831a3ca2 100644 --- a/doc/idle-approved-tool-recovery.md +++ b/doc/idle-approved-tool-recovery.md @@ -115,3 +115,36 @@ checks supplement the earlier execution, transaction, and paging evidence above. After company scoping, the complete gateway-service and startup selection passes 149 tests against a disposable PostgreSQL database, and server typecheck passes. Stack integration, workspace checks, and fresh remote CI remain separate gates. + +## Preparation failures retain an approved Test-tab action + +A real PostgreSQL policy-read timeout reproduced a permanent-failure bug after +claiming a Test-tab action: the provider had never been called, but both request +and invocation were saved as failed, so approved recovery could not retry them. + +The preparation boundary now distinguishes explicit validation/access rejections +from unexpected dependency errors and transient HTTP errors. The existing +`tool-test-approval` owner releases only its exact claim: invocation and request +are locked in the established order, their link/company/claim timestamp must +match, and the invocation must still await approval with no recorded start. +The request returns to `approved` with a transaction-aware notification. Signed +arguments and the human approval remain unchanged; the error propagates so the +existing recovery worker retains its retry obligation. + +This boundary ends before `runTestToolInvocation`. Provider dispatch and outcome +persistence keep their existing conservative no-replay behavior. A changed claim, +started invocation or prior-dispatch evidence cannot be released by this path. +If the requeue transaction itself fails, the error propagates and no terminal +failure is fabricated; existing interrupted-execution reconciliation remains the +fallback. This change does not infer replay safety from a failed requeue. + +Before the fix, both foreground and recovery timeout regressions failed. They +now observe the committed claim under a real PostgreSQL table lock, wait for +`55P03`, verify unchanged approval and no provider call, then prove automatic +recovery invokes the provider once and becomes quiet. Additional real-row cases +cover changed ownership, mismatched invocation, a started call, prior-dispatch +history, and outer-transaction rollback. A released claim cannot start execution. +All 117 gateway-service cases pass on the owning slice, including existing target +invalidation, provider-outcome persistence failures and unknown-outcome no-replay +cases. Integrated consumer checks, workspace verification and remote PR gates +must still be recorded after propagation. diff --git a/server/src/__tests__/tool-gateway-service.test.ts b/server/src/__tests__/tool-gateway-service.test.ts index bbf5bacaf4a..3e2bc06e54d 100644 --- a/server/src/__tests__/tool-gateway-service.test.ts +++ b/server/src/__tests__/tool-gateway-service.test.ts @@ -47,6 +47,7 @@ import { initializeRunIdentity, reserveSteeredIdentity, reconcileSteeredIdentity import { issueService } from "../services/issues.js"; import { approvalService } from "../services/approvals.js"; import { commitToolActionReview } from "../services/tool-action-review.js"; +import { claimToolTestApproval, releaseToolTestApproval, startToolTestInvocation } from "../services/tool-test-approval.js"; import { materializeNativeInteractionResponses } from "../services/native-runtime/native-interaction-bridge.js"; import { toolActionDeliveryService } from "../services/tool-action-delivery.js"; import { secretService } from "../services/secrets.js"; @@ -1027,6 +1028,78 @@ describeEmbeddedPostgres("tool gateway service", () => { draining = false; await settle(); await executed(pending); await quiet(); }); + it.each(["foreground", "recovery"] as const)("retries a Test-tab %s approval after a real pre-dispatch database timeout", async mode => { + const remoteCall = providerFixture(); remoteCall.release(); + const { pending } = await testRequest(remoteCall.provider); await approve(pending); + const preparationDb = createDb(externalDatabaseUrl ?? tempDb!.connectionString, { + maxConnections: 1, idleTimeoutSeconds: 0, maxLifetimeSeconds: 0, + }); + const preparingGateway = createTestToolGatewayService(preparationDb, { remoteHttpRequest: remoteCall.provider }); + let unlock!: () => void, locked!: () => void; + const gate = new Promise(resolve => { unlock = resolve; }); + const acquired = new Promise(resolve => { locked = resolve; }); + const lock = db.transaction(async tx => { + await tx.execute(sql`lock table tool_policies in access exclusive mode`); + locked(); await gate; + }); + await acquired; + try { + await preparationDb.execute(sql`set lock_timeout = '2s'`); + const attempting = mode === "foreground" + ? preparingGateway.approveActionRequest({ companyId: fixture.company.id, actionRequestId: pending.id, actor: { userId: "board" } }) + : preparingGateway.recoverApprovedActionReviews(fixture.company.id); + // Observe the real committed claim while its subsequent policy read + // is blocked. Provider execution has not started. + void attempting.catch(() => undefined); + await vi.waitFor(async () => { + expect((await db.select().from(toolActionRequests).where(eq(toolActionRequests.id, pending.id)))[0].status).toBe("executing"); + }); + if (mode === "foreground") await expect(attempting).rejects.toMatchObject({ cause: { code: "55P03" } }); + else expect(await attempting).toEqual({ scanned: 1, retry: true }); + expect((await db.select().from(toolActionRequests).where(eq(toolActionRequests.id, pending.id)))[0]) + .toMatchObject({ status: "approved", signedArguments: pending.signedArguments }); + expect((await db.select().from(toolInvocations).where(eq(toolInvocations.id, pending.invocationId)))[0]) + .toMatchObject({ status: "awaiting_approval", startedAt: null }); + expect(remoteCall.provider).not.toHaveBeenCalled(); + } finally { unlock(); await lock; await preparationDb.$client.end({ timeout: 1 }); } + await startRecovery(); await settle(); await executed(pending); await quiet(); + expect(remoteCall.provider).toHaveBeenCalledOnce(); + }, 15_000); + + it.each(["started", "reclaimed", "mismatched", "prior_dispatch"] as const)("refuses to release a Test-tab preparation claim with %s ownership evidence", async state => { + const remoteCall = providerFixture(); remoteCall.release(); + const { pending } = await testRequest(remoteCall.provider); await approve(pending); + const claim = await claimToolTestApproval(db, pending.id, pending.invocationId); + expect(claim).not.toBeNull(); + if (state === "started") expect(await startToolTestInvocation(db, pending.invocationId, claim!)).toBe(true); + if (state === "reclaimed") await db.update(toolActionRequests) + .set({ updatedAt: new Date(claim!.claimedAt.getTime() + 1000) }).where(eq(toolActionRequests.id, pending.id)); + if (state === "prior_dispatch") await db.update(toolInvocations) + .set({ startedAt: new Date() }).where(eq(toolInvocations.id, pending.invocationId)); + const beforeRequest = (await db.select().from(toolActionRequests).where(eq(toolActionRequests.id, pending.id)))[0]; + const beforeInvocation = (await db.select().from(toolInvocations).where(eq(toolInvocations.id, pending.invocationId)))[0]; + expect(await releaseToolTestApproval(db, state === "mismatched" ? { ...claim!, invocationId: randomUUID() } : claim!)).toBe(false); + expect((await db.select().from(toolActionRequests).where(eq(toolActionRequests.id, pending.id)))[0]).toEqual(beforeRequest); + expect((await db.select().from(toolInvocations).where(eq(toolInvocations.id, pending.invocationId)))[0]).toEqual(beforeInvocation); + expect(remoteCall.provider).not.toHaveBeenCalled(); + }); + + it("rolls a Test-tab preparation release back with its transaction and invalidates the released claim", async () => { + const remoteCall = providerFixture(); remoteCall.release(); + const { pending } = await testRequest(remoteCall.provider); await approve(pending); + const claim = await claimToolTestApproval(db, pending.id, pending.invocationId); + expect(claim).not.toBeNull(); + await expect(db.transaction(async tx => { + expect(await releaseToolTestApproval(tx as unknown as typeof db, claim!)).toBe(true); + throw new Error("release rollback"); + })).rejects.toThrow("release rollback"); + expect((await db.select().from(toolActionRequests).where(eq(toolActionRequests.id, pending.id)))[0].status).toBe("executing"); + expect(await releaseToolTestApproval(db, claim!)).toBe(true); + expect(await startToolTestInvocation(db, pending.invocationId, claim!)).toBe(false); + await startRecovery(); await settle(); await executed(pending); await quiet(); + expect(remoteCall.provider).toHaveBeenCalledOnce(); + }); + it.each(["foreground", "recovery"] as const)("claims a Test-tab action once when %s wins", async winner => { const remoteCall = providerFixture(); const { pending } = await testRequest(remoteCall.provider); diff --git a/server/src/services/tool-gateway.ts b/server/src/services/tool-gateway.ts index ff7762eb9c2..111eb4f0c33 100644 --- a/server/src/services/tool-gateway.ts +++ b/server/src/services/tool-gateway.ts @@ -1,6 +1,6 @@ import { toolReviewProjectionService } from "./tool-review-projection.js"; import { toolReviewInterruptionService } from "./tool-review-interruption.js"; -import { claimToolTestApproval, persistToolTestOutcome, startToolTestInvocation, type ToolTestApprovalClaim } from "./tool-test-approval.js"; +import { claimToolTestApproval, releaseToolTestApproval, persistToolTestOutcome, startToolTestInvocation, type ToolTestApprovalClaim } from "./tool-test-approval.js"; import { approvedToolReviewCompanies, prepareApprovedToolReview, recoverApprovedToolReviews } from "./tool-review-recovery.js"; import { toolReviewExpiryService } from "./tool-review-expiry.js"; import { notifyToolReviewChange, writeToolReviewChange } from "./tool-review-work-notifications.js"; @@ -7671,6 +7671,15 @@ export function createToolGatewayService( companyId: invocation.companyId, agentId, userId, argumentsSummary, reasonCode: "approval_granted", approvedClaim: claim, matchedPolicyIds: invocation.matchedPolicyIds ?? [] }; } catch (err) { + const rejected = err instanceof ToolContentValidationError || + err instanceof ToolGatewayHttpError && err.status >= 400 && err.status < 500 && + ![408, 425, 429].includes(err.status); + if (!rejected) { + // Preparation has not entered runTestToolInvocation. Preserve approval + // through dependency failures; the claim owner still verifies no dispatch. + await releaseToolTestApproval(db, claim); + throw err; + } const message = err instanceof Error ? err.message : String(err); const errorCode = err instanceof ToolGatewayHttpError || err instanceof ToolContentValidationError ? err.reasonCode : "tool_execution_failed"; diff --git a/server/src/services/tool-test-approval.ts b/server/src/services/tool-test-approval.ts index 89828404b8d..da78f5d722d 100644 --- a/server/src/services/tool-test-approval.ts +++ b/server/src/services/tool-test-approval.ts @@ -36,6 +36,24 @@ export async function claimToolTestApproval(db: Db, actionRequestId: string, inv }); } +/** Return only this still-undispatched claim to its existing approval queue. */ +export async function releaseToolTestApproval(db: Db, claim: ToolTestApprovalClaim) { + return db.transaction(async tx => { + const [invocation] = await tx.select().from(toolInvocations) + .where(eq(toolInvocations.id, claim.invocationId)).for("update"); + const [request] = await tx.select().from(toolActionRequests) + .where(and(eq(toolActionRequests.id, claim.actionRequestId), + eq(toolActionRequests.invocationId, claim.invocationId))).for("update"); + if (invocation?.status !== "awaiting_approval" || invocation.startedAt !== null || + request?.status !== "executing" || request.companyId !== invocation.companyId || + request.updatedAt.getTime() !== claim.claimedAt.getTime()) return false; + await notifyToolReviewChange(tx, request.companyId); + await tx.update(toolActionRequests).set({ status: "approved", updatedAt: new Date() }) + .where(eq(toolActionRequests.id, request.id)); + return true; + }); +} + export async function startToolTestInvocation(db: Db, invocationId: string, claim?: ToolTestApprovalClaim) { const now = new Date(); if (!claim) {