From 5506359bbbdeb482aff622932dddb4da6d822d5a Mon Sep 17 00:00:00 2001 From: Nicky Leach Date: Wed, 18 Nov 2026 20:05:15 -0800 Subject: [PATCH] perf(wake-queue): skip recovery lookup when no saved receipt can be adopted (#22279) ## Thinking Path > - Paperclip assigns tasks and saves input for agents. > - One admission can adopt previously deferred comments. > - Admission reads the task's recovery state before creating the run. > - It repeated that lookup even when there were no deferred receipts to adopt. > - Check for scoped receipts first. Verify the recovery hold when at least one exists. ## Linked Issues or Issue Description **What existing behavior does this improve?** Admitting board assignments and saved task comments. **Subsystem affected** Server task admission. **Current behavior** An empty candidate set triggers a second recovery lookup on the ordinary assignment and comment paths. **Proposed behavior** Check recovery only when the candidate lookup returns rows. **Additional context** Builds on #22268 and #22272. Related recovery work in #20163 addresses terminal tasks. ## What Changed - Query the same receipt scope under the existing issue lock. - Keep the handoff owner, receipt order, and reconstruction exception. - Exercise empty and nonempty exact scopes with an active recovery hold and verify the lock from a competing database session. ## Verification 162 tests passed across the PostgreSQL wake-queue adapter, issue-wake-admission, and heartbeat comment batching. A local occupied-slot benchmark on merged base f0caee6f95 and this change retained one run and all comment IDs. Warm median statements for assignment, one comment and two separately posted comments fell from 42/44/86 to 38/40/82 (17 repetitions per case after warmup). ## Risks A saved receipt behind a recovery hold must remain deferred. The test uses a real hold and verifies that reconstruction can still adopt the exact receipt. ## Model Used OpenAI GPT-6.2 Sol (gpt-6.2-sol) implemented the change. OpenAI Codex reviewed and qualified it. ## 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 - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --- .../wake-queue/adapters/postgres.test.ts | 43 +++++++++++++++++++ .../modules/wake-queue/adapters/postgres.ts | 5 ++- 2 files changed, 46 insertions(+), 2 deletions(-) diff --git a/server/src/modules/wake-queue/adapters/postgres.test.ts b/server/src/modules/wake-queue/adapters/postgres.test.ts index 81ddbb510c8..e2755b0f80a 100644 --- a/server/src/modules/wake-queue/adapters/postgres.test.ts +++ b/server/src/modules/wake-queue/adapters/postgres.test.ts @@ -1,6 +1,7 @@ import { resolveExternalTestDatabaseUrl } from "../../../__tests__/helpers/external-test-database.js"; import { DELIVERY_QUEUES } from "../../../services/delivery-work-notifications.js"; import { instanceSettingsService } from "../../../services/instance-settings.js"; +import * as executionBlocker from "../../../services/execution-blocker.js"; import { randomBytes, randomUUID } from "node:crypto"; import { and, eq, sql } from "drizzle-orm"; import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest"; @@ -26,6 +27,7 @@ import { startEmbeddedPostgresTestDatabase, } from "../../../__tests__/helpers/embedded-postgres.js"; import { + createPostgresIssueWakeAdmission, createPostgresWakeQueueAdapter, createWakeAdmissionWriter, } from "./postgres.js"; @@ -182,6 +184,47 @@ describeEmbeddedPostgres("wake-queue postgres adapter", () => { return id; } + it("checks execution holds only when the scoped saved receipt exists, inside the issue admission transaction", async () => { + const companyId = await seedCompany(); + const agentId = await seedAgent({ companyId }); + const formerAgentId = await seedAgent({ companyId, name: "Former owner" }); + const issueId = await seedIssue({ companyId, assigneeAgentId: agentId }); + const handoffRunId = await seedRun({ + companyId, agentId: formerAgentId, status: "cancelled", errorCode: "issue_reassigned", contextSnapshot: { issueId }, + }); + const wakeId = await seedDeferredWake({ companyId, agentId: formerAgentId, issueId }); + await db.insert(issueRecoveryActions).values({ + companyId, sourceIssueId: issueId, kind: "active_run_watchdog", ownerType: "board", status: "active", + cause: "legacy_execution_requires_reconciliation", fingerprint: handoffRunId, + nextAction: "Check the stopped execution.", + }); + + const blocker = vi.spyOn(executionBlocker, "getExecutionBlocker"); + const admit = createPostgresIssueWakeAdmission(db); + try { + await admit({ companyId, issueId }, async (tx, { fresh }) => { + await expect(db.execute(sql`select id from issues where id = ${issueId} for update nowait`)) + .rejects.toMatchObject({ cause: { code: "55P03" } }); + const input = { issueId, agentId, handoffRunId, checkExecutionBlocker: true }; + const receiptScope = { kind: "exact" as const, wakeId }; + await expect(fresh.readCommentCandidates({ ...input, receiptScope: { ...receiptScope, wakeId: randomUUID() } })) + .resolves.toEqual({ handoffAgentId: formerAgentId, candidates: [] }); + expect(blocker).not.toHaveBeenCalled(); + + await expect(fresh.readCommentCandidates({ ...input, receiptScope })) + .resolves.toEqual({ handoffAgentId: formerAgentId, candidates: [] }); + expect(blocker).toHaveBeenCalledExactlyOnceWith(tx, companyId, issueId); + + await expect(fresh.readCommentCandidates({ ...input, receiptScope, checkExecutionBlocker: false })) + .resolves.toMatchObject({ handoffAgentId: formerAgentId, candidates: [{ id: wakeId }] }); + expect(blocker).toHaveBeenCalledTimes(1); + return { kind: "skipped" }; + }); + } finally { + blocker.mockRestore(); + } + }); + function recordReleaseRunReads() { const rows: unknown[][] = []; function recordSelects>(executor: T): T { diff --git a/server/src/modules/wake-queue/adapters/postgres.ts b/server/src/modules/wake-queue/adapters/postgres.ts index 1a7463c04e3..9e29b287575 100644 --- a/server/src/modules/wake-queue/adapters/postgres.ts +++ b/server/src/modules/wake-queue/adapters/postgres.ts @@ -1598,7 +1598,7 @@ export function createFreshIssueRunStore( sql`${heartbeatRuns.contextSnapshot}->>'issueId' = ${issueId}`, or(isNull(heartbeatRuns.nativeIssueId), eq(heartbeatRuns.nativeIssueId, issueId)), )) : []; - const candidates = receiptScope && (!checkExecutionBlocker || !(await getExecutionBlocker(tx, companyId, issueId))) + const candidates = receiptScope ? await tx.select({ id: agentWakeupRequests.id, reason: agentWakeupRequests.reason, @@ -1612,7 +1612,8 @@ export function createFreshIssueRunStore( receiptScope.kind === "exact" ? eq(agentWakeupRequests.id, receiptScope.wakeId) : undefined, )).orderBy(asc(agentWakeupRequests.requestedAt)) : []; - return { handoffAgentId: handoff?.agentId ?? null, candidates }; + const blocked = candidates.length > 0 && checkExecutionBlocker && await getExecutionBlocker(tx, companyId, issueId); + return { handoffAgentId: handoff?.agentId ?? null, candidates: blocked ? [] : candidates }; }, readUndeliveredLegacyCommentIds(issueId, agentId, commentIds) { return undeliveredLegacyUserCommentIds(tx, companyId, issueId, agentId, commentIds);