From 7dd8c2e539f2cc60c8f90ce16dd6d4af4ba88923 Mon Sep 17 00:00:00 2001 From: Dotta Date: Wed, 28 Oct 2026 11:50:45 -0500 Subject: [PATCH] Cover shared retry receipts before removing inbound notice polling Move the existing authorization and retirement notifications forward from the following failed-retry slice. Prove both transaction boundaries and retain the matching budget fixture correction; 264 selected cases and server types/build/boundaries pass. Co-Authored-By: Paperclip --- ...-10-25-inbound-wake-notices-sleep-audit.md | 89 ++++++++++++ .../chat-channels.integration.test.ts | 136 +++++++++++++++++- .../chat-channels/failed-run-retry.ts | 19 ++- 3 files changed, 231 insertions(+), 13 deletions(-) diff --git a/doc/plans/2026-10-25-inbound-wake-notices-sleep-audit.md b/doc/plans/2026-10-25-inbound-wake-notices-sleep-audit.md index 9f054da3bd5..55e7741d810 100644 --- a/doc/plans/2026-10-25-inbound-wake-notices-sleep-audit.md +++ b/doc/plans/2026-10-25-inbound-wake-notices-sleep-audit.md @@ -367,3 +367,92 @@ transaction behavior rather than claiming those receipts cannot be shared. Final producer disposition, updated acceptance, actual landed-parent integration, and fresh exact-head remote gates remain required. No complete local repository matrix, live provider, host/database suspension, or savings claim is made. + + +## Shared retry-receipt producer gap resolved (October 28) + +The current preparation adopts verified cancellation parent +`60ba892ae9fc5faaf8cd0833694b4a66c13323c3`. Its complete original inbound-notice +baseline patch remains identical through that parent update. The following +producer repair closes the explicitly open question above before this owner +is published. + +`findExistingDeferredWake` can select a deferred retry receipt for a later +ordinary admission with matching task, conversation, and actor. The retry's own +`allowRunCoalescing: false` controls its initial admission, not that later read. +Ordinary receipt resolution follows `coalescedIntoWakeupRequestId` to its owner; +owner retirement can therefore change an ordinary notice. Do not exempt retry +writers merely because their initial admission disables coalescing. + +Two already-implemented writer fixes are moved forward from the following +failed-retry slice (#17649, source `b47169855cc712e029df7e5c4c34f7b6fa04b9d4`): + +- The durable retry authorization callback registers ordinary-notice work after + validation and before its caller writes the receipt. This keeps the contract + central for both real heartbeat admission and supported callback-owned writes. +- Retry authorization denial retires the exact unadmitted receipt in a transaction + that registers its company/task notice intent before the existing guarded update. + Pending-status, absent-run, and request-correlation conditions are preserved. + +No new worker, table, scheduler, polling fallback, or per-caller recovery wrapper +is added. These production hunks match the already-existing following slice. +Its remaining failed-retry projection and lifecycle/lease producers keep their +separate ownership. Ordinary notice authorization does not read native lease or +coordinator retry eligibility, so those later predicates are not copied here. + +Two new real producer regressions fail before repair and pass afterward: + +1. A supported callback authorizes and writes a real deferred retry receipt in + its own transaction. There was no notice intent before the write. The fixed + callback emits intent before the write and settlement after outer commit. +2. Real heartbeat admission creates the retry receipt. After actual retry receipt + reconciliation, denial reaches its conditional retirement. A second PostgreSQL + transaction holds that receipt row: the fixed writer emits exact company/task + intent while the outside connection still sees deferred status, remains unsettled + while blocked, then publishes settlement only after the failed-status write commits. + +These verify actual producers and transaction timing. They do not claim a complete +mixed ordinary/retry ingress walkthrough; the admission reader, receipt resolver, +scoped consumer tests, and the shared owner writes establish the audited boundary. +The first lock fixture acquired the row too early and blocked admission itself; +that invalid before-fix attempt is preserved at +`/tmp/sleep30-retry-owner-red.log`. The corrected missing-intent failure is +`/tmp/sleep30-retry-owner-actual-red.log`. The callback failure is +`/tmp/sleep30-retry-admission-red.log`; both pass together in +`/tmp/sleep30-retry-producers-green.log`. + +Moving the callback contract also exposes the existing budget-refusal test mock's +root `request.authorize(db)` call. The real writer passes its transaction. The +local still-budget-blocked case failed with no skipped receipt and a contended +retry classification (`/tmp/sleep30-retry-budget-red.log`). Its correction is the +same transaction fixture fix already present in #17649: authorize and persist +inside one transaction. All requester, comment, skipped-status, and budget checks +remain; production budget behavior is unchanged. The reusable deferred-retry +fixture is copied from that following slice for the two new producer cases. +When reconciling #17649, retain one identical helper and do not duplicate it. + +### Final current-parent acceptance + +**264 distinct selected cases pass**, with separate newly created PostgreSQL +fixtures for reconstruction, broader retries, and cancellation consumers: + +- **142 complete consumer cases** across cancellation/run control, app admission + wiring, wake admission use cases, and queued-comment admission use cases. +- **50 selected ordinary-notice cases**, including both new producer regressions; + the other 1,598 chat cases were skipped. +- **72 different retry cases**, covering the full newer-input budget-hold family, + current GitHub Retry, and persisted Retry authority loss; the other 1,576 chat + cases were skipped. These selected names do not overlap the 50-case group. + +Server typechecking, build, and module-boundary checks pass. The tests under +`src/__tests__` were executed separately from production typechecking. The exact +commands, fixtures, logs, and zero exit receipts are in +`/tmp/sleep30-final-acceptance-command.json` and `/tmp/sleep30-final-*`. +`/tmp/sleep30-final-tested-source-sha256.json` records the 20 owned source/test +hashes held stable throughout the final validation. + +The earlier 190-case baseline and older full-suite counts retain their stated +revision scope and are not added to 264. This completes the named producer audit +for this owner; actual landed-parent reconciliation and fresh exact-head CI/review +remain publication and merge gates. There is no full local repository matrix, +live provider tenant, external-alarm, physical suspension, or savings claim. diff --git a/server/src/__tests__/chat-channels.integration.test.ts b/server/src/__tests__/chat-channels.integration.test.ts index 8460bae16bc..adc41200f52 100644 --- a/server/src/__tests__/chat-channels.integration.test.ts +++ b/server/src/__tests__/chat-channels.integration.test.ts @@ -61697,6 +61697,126 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => { ); }); + async function deferredFailedRetryNoticeFixture(wakeOnDemand = true) { + const context = await failedChatRetryFixture("telegram", undefined, true); + const companyId = context.fixture.companyId, issueId = context.issue.id, leaseId = randomUUID(); + await db.update(heartbeatRuns).set({ runtimeMode: "native", nativeIssueId: issueId, + nativePhase: "terminal_failure", runnerProfileJson: {}, + resultJson: { workspaceRestoreFailure: "restore_failed", workspaceRestoreRecovery: { + schema: "paperclip.workspace-restore-recovery.v1", runId: context.runId, leaseIds: [leaseId], + } }, + }).where(eq(heartbeatRuns.id, context.runId)); + await db.insert(nativeRunFinalizations).values({ companyId, issueId, runId: context.runId, phase: "terminal_failure" }); + await db.insert(environmentLeases).values({ id: leaseId, companyId, issueId, + heartbeatRunId: context.runId, provider: "daytona", providerLeaseId: randomUUID(), + status: "pending_cleanup", cleanupStatus: "failed", leasePolicy: "retain_on_failure", + metadata: { remoteCwd: "/home/daytona/paperclip-workspace", pendingCleanupInFlight: false }, + }); + await db.insert(issueRecoveryActions).values({ companyId, sourceIssueId: issueId, + kind: "active_run_watchdog", status: "resolved", ownerType: "system", + cause: "native_continuation_requires_reconciliation", fingerprint: randomUUID(), + nextAction: "Verify and preserve the retained source before continuing.", + evidence: { runId: context.runId, automaticRecovery: { replay: "blocked" }, + workspaceRestoreRecovery: { schema: "paperclip.workspace-restore-recovery.v1", leaseIds: [leaseId] }, + historicalWorkspaceSource: { schema: "paperclip.historical-workspace-source.v1", runId: context.runId, leaseIds: [leaseId] }, + systemRecovery: { ...createSystemRecovery(context.runId), state: "exhausted", attempts: 2, retriesUsed: 1, + attemptId: randomUUID(), firstFailureAt: Date.now() - 1000, deadlineAt: Date.now() + 60_000, + preservationOperationIds: [randomUUID()] }, + }, + }); + const retry = await requestTaskRetry({ db, companyId, issueId, actorId: "owner-user", + actorSource: "cloud_tenant", observedRunId: context.runId, idempotencyKey: randomUUID(), + prepareChatRetry: context.service.prepareFailedChatRunRetry }); + await db.update(agents).set({ adapterType: "paperclip_runner", status: "running", + runtimeConfig: { heartbeat: { wakeOnDemand, maxConcurrentRuns: 1 } }, + }).where(eq(agents.id, context.fixture.assignedAgentId)); + await db.insert(heartbeatRuns).values({ companyId, agentId: context.fixture.assignedAgentId, + status: "running", startedAt: new Date() }); + context.wakeup.mockImplementation(heartbeatService(db).wakeup); + return { ...context, retry, admit: () => context.service.processFailedChatRunRetry(retry.chatActionId!) }; + } + + it("registers ordinary-notice work through the retry admission transaction", async () => { + const context = await deferredFailedRetryNoticeFixture(); + const events: string[] = []; + let eventsBeforeWrite: string[] = []; + const unsubscribe = subscribeDatabaseWork(db, DELIVERY_QUEUES.chatInboundWakeNotices, (event, scopes) => { + if ([...scopes ?? []].some(scope => scope !== "*" && JSON.parse(scope).companyId === context.fixture.companyId)) events.push(event); + }); + context.wakeup.mockImplementationOnce(async (_agentId, options) => { + const request = options!.durableChatRequest!; + await db.transaction(async tx => { + events.length = 0; + await request.authorize(tx as unknown as Parameters[0]); + eventsBeforeWrite = [...events]; + await tx.insert(agentWakeupRequests).values({ + id: request.id, companyId: context.fixture.companyId, agentId: request.agentId, + source: options!.source, triggerDetail: options!.triggerDetail, reason: options!.reason, + requestedByActorType: request.requestedByActorType, requestedByActorId: request.requestedByActorId, + requestedAt: request.requestedAt, idempotencyKey: request.idempotencyKey, + status: "deferred_issue_execution", payload: { ...options!.payload, + taskRetryRequestId: context.retry.requestId, _paperclipWakeContext: options!.contextSnapshot }, + }); + }); + return null; + }); + try { + await expect(context.admit()).resolves.toMatchObject({ status: "deferred" }); + expect(eventsBeforeWrite).toContain("intent"); + expect(eventsBeforeWrite).not.toContain("settled"); + expect(events).toContain("settled"); + expect((await readAgentWakeupRequestsById(context.retry.chatActionId!))[0]).toMatchObject({ status: "deferred_issue_execution", runId: null }); + } finally { unsubscribe(); await context.service.shutdown(); } + }); + + it("registers ordinary-notice intent before a retry-owned receipt is retired", async () => { + const context = await deferredFailedRetryNoticeFixture(); + let release = () => {}; + let holding: Promise | undefined; + let retiring: ReturnType | undefined; + let unsubscribe = () => {}; + const events: string[] = []; + const signalledScopes: string[] = []; + try { + expect(await context.admit()).toMatchObject({ status: "deferred" }); + await reconcileTaskChatRetryReceipts(db); + context.wakeup.mockClear(); + let locked!: () => void; + const acquired = new Promise(resolve => { locked = resolve; }); + const held = new Promise(resolve => { release = resolve; }); + context.wakeup.mockImplementationOnce(async () => { + holding = db.transaction(async tx => { + await tx.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, context.retry.chatActionId!)).for("update"); + locked(); + await held; + }); + await acquired; + throw Object.assign(new Error("denied at resume"), { + details: { code: "chat_failed_run_retry_not_authorized" }, + }); + }); + unsubscribe = subscribeDatabaseWork(db, DELIVERY_QUEUES.chatInboundWakeNotices, (event, scopes) => { + if ([...scopes ?? []].some(scope => scope !== "*" && JSON.parse(scope).companyId === context.fixture.companyId)) { + events.push(event); signalledScopes.push(...scopes ?? []); + } + }); + retiring = context.admit(); + void retiring.catch(() => undefined); + await vi.waitFor(() => expect(context.wakeup).toHaveBeenCalledOnce()); + await vi.waitFor(() => expect(events).toContain("intent"), { timeout: 2000 }); + expect(signalledScopes.map(scope => JSON.parse(scope))).toContainEqual({ companyId: context.fixture.companyId, issueId: context.issue.id }); + expect(events).not.toContain("settled"); + expect((await readAgentWakeupRequestsById(context.retry.chatActionId!))[0]).toMatchObject({ status: "deferred_issue_execution", runId: null }); + release(); await holding; + await expect(retiring).resolves.toMatchObject({ status: "failed" }); + expect((await readAgentWakeupRequestsById(context.retry.chatActionId!))[0]).toMatchObject({ status: "failed", runId: null }); + expect(events).toContain("settled"); + } finally { + release(); await holding; await retiring?.catch(() => undefined); + unsubscribe(); await context.service.shutdown(); + } + }); + async function failedChatRetryFixture( provider: "slack" | "telegram" | "github", externalActorId?: string, @@ -62637,13 +62757,15 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => { context.wakeup.mockImplementation(heartbeatService(db).wakeup); } else context.wakeup.mockImplementation(async (agentId, opts) => { const request = opts.durableChatRequest!; - await request.authorize(db); - await db.insert(agentWakeupRequests).values({ id: request.id, companyId, - agentId, source: opts.source!, triggerDetail: opts.triggerDetail, reason: "budget.blocked", - requestedByActorType: request.requestedByActorType, requestedByActorId: request.requestedByActorId, - requestedAt: request.requestedAt, idempotencyKey: request.idempotencyKey, - payload: { ...opts.payload, executionWait: { scopeType: "agent", scopeId: agentId } }, - status: "skipped", finishedAt: new Date() }); + await db.transaction(async tx => { + await request.authorize(tx); + await tx.insert(agentWakeupRequests).values({ id: request.id, companyId, + agentId, source: opts.source!, triggerDetail: opts.triggerDetail, reason: "budget.blocked", + requestedByActorType: request.requestedByActorType, requestedByActorId: request.requestedByActorId, + requestedAt: request.requestedAt, idempotencyKey: request.idempotencyKey, + payload: { ...opts.payload, executionWait: { scopeType: "agent", scopeId: agentId } }, + status: "skipped", finishedAt: new Date() }); + }); return null; }); if (realBudgetIngress) { diff --git a/server/src/services/chat-channels/failed-run-retry.ts b/server/src/services/chat-channels/failed-run-retry.ts index cd5cf7c0bf5..26b53a0e1e8 100644 --- a/server/src/services/chat-channels/failed-run-retry.ts +++ b/server/src/services/chat-channels/failed-run-retry.ts @@ -1,3 +1,4 @@ +import { notifyChatInboundWakeNotices } from "../chat-inbound-wake-notice-notifications.js"; import { safeChatWakeAuthorityReason, type ChatWakeAuthorityReason } from "./inbound/wakeup-authorization-error.js"; import { adapterExecutionControls } from "../adapter-execution-control.js"; import { admitExplicitNativeContinuation } from "../explicit-native-continuation.js"; @@ -1871,6 +1872,7 @@ export function createChatFailedRunRetry(db: Db, options: ChatFailedRunRetryOpti typeof claimed.payload.taskRetryIntentId === "string" ? claimed.payload.taskRetryIntentId : undefined, true, // The durable wake callback validates admission; later phases recheck containment. ); + await notifyChatInboundWakeNotices(tx, { companyId: scope.companyId, issueId: scope.issueId }); }, onAdmitted: async (tx, receipt) => { if (!source.taskRetryInput) return; @@ -1915,12 +1917,17 @@ export function createChatFailedRunRetry(db: Db, options: ChatFailedRunRetryOpti receipt.payload?.taskRetryRequestId === claimed.payload.taskRetryIntentId) { // Receipt existence proves the earlier wait, not current authority. // Retire only this unadmitted wake; an admitted run keeps its history. - await db.update(agentWakeupRequests).set({ - status: "failed", error: "chat_failed_run_retry_not_authorized", - finishedAt: new Date(), updatedAt: new Date(), - }).where(and(eq(agentWakeupRequests.id, receipt.id), - eq(agentWakeupRequests.companyId, claimed.companyId), - eq(agentWakeupRequests.status, "deferred_issue_execution"), isNull(agentWakeupRequests.runId))); + await db.transaction(async tx => { + await notifyChatInboundWakeNotices(tx, { + companyId: claimed.companyId, issueId: String(claimed.payload.issueId), + }); + await tx.update(agentWakeupRequests).set({ + status: "failed", error: "chat_failed_run_retry_not_authorized", + finishedAt: new Date(), updatedAt: new Date(), + }).where(and(eq(agentWakeupRequests.id, receipt.id), + eq(agentWakeupRequests.companyId, claimed.companyId), + eq(agentWakeupRequests.status, "deferred_issue_execution"), isNull(agentWakeupRequests.runId))); + }); return settle("failed", { code: "failed_chat_retry_not_authorized", attemptCount }); } return settle(["skipped", "failed", "cancelled"].includes(receipt.status) ? "failed" : "processed", {