From c2c53b839497be6f5e28aa2cd5ba50cfd1d76d4a Mon Sep 17 00:00:00 2001 From: Dotta Date: Wed, 28 Oct 2026 12:40:43 -0500 Subject: [PATCH] Bound failed retry discovery and record current acceptance Preserve bounded projection with one candidate predicate, zero task discovery SQL and distinct company/startup scopes. Real PostgreSQL budgets and all 404 selected compatibility/producer cases pass. Co-Authored-By: Paperclip --- ...-10-25-failed-retry-notices-sleep-audit.md | 44 +++++++++++++++ .../chat-channels.integration.test.ts | 56 ++++++++++++++++++- .../chat-channels/failed-retry-notices.ts | 26 ++++----- 3 files changed, 110 insertions(+), 16 deletions(-) diff --git a/doc/plans/2026-10-25-failed-retry-notices-sleep-audit.md b/doc/plans/2026-10-25-failed-retry-notices-sleep-audit.md index 429f6925257..765bf9e4801 100644 --- a/doc/plans/2026-10-25-failed-retry-notices-sleep-audit.md +++ b/doc/plans/2026-10-25-failed-retry-notices-sleep-audit.md @@ -372,3 +372,47 @@ pause, and resume through the real lifecycle. Its initial failure is retained in `/tmp/sleep-agent-resume-lifecycle.log`. Server typecheck passed in `/tmp/sleep-agent-resume-types.log`. These results establish worker and transaction behavior only; final-stack acceptance and latest-head CI still apply. + + +## Current integration and discovery acceptance — October 28 + +The prepared local slice follows current inbound parent +`661f2f6da8c6c22cdcc25edccd57502ee6fa8c4b`, including actual master +`a2fbce9305c48f5242e6bafb19d049d29edc1d72`. Normal merges preserve the +19-path slice. Two conflicts retained current lifecycle fixture migrations/client +cleanup and the extracted retry notice import; duplicate imports were removed. +The identical producer helper copied forward to the parent is retained once at +this slice's original location, with both parent producer regressions intact. +An initial raw binary-patch comparison failed after parent test additions changed +blob hashes and hunk offsets. A full-context comparison excluding only those +representation fields passes; `/tmp/sleep31-discovery-parent-update-proof.json` +records the exception rather than claiming raw binary identity. + +The discovery-cost finding in #17647 also existed in this owner's page loop. +Three new real PostgreSQL regressions with 250 retained candidates and a second +company fail before the fix. Known task hints now require zero discovery SQL; +company/startup discovery selects DISTINCT company/task identifiers using the +same candidate predicate as bounded projection. The first SQL version failed +with PostgreSQL 42702 because both joined tables project company_id; an explicit +projection alias fixes the ambiguity. The final four targeted discovery/history +cases pass. This does not claim constant database work for broad discovery. + +Current focused acceptance passes **404 distinct cases** on the integrated owner: +259 across six complete consumer/lifecycle/environment suites, 20 failed-retry +notice and native-lease producer cases, 53 ordinary-notice compatibility cases, +and 72 separate retry/budget compatibility cases. The three chat selections skip +1,651, 1,618 and 1,599 cases respectively; skipped cases are not passes. +Each group uses separate PostgreSQL fixtures; lifecycle and control apply their +own migrations, while chat and environment fixtures are explicitly premigrated. +Final server typechecking/build and module boundaries pass. + +Exact commands/fixtures are `/tmp/sleep31-final-acceptance-command.json`; logs and +exit receipts are `/tmp/sleep31-final-{consumers,notices,ordinary,compatibility}.*` +and `/tmp/sleep31-alias-final-{types,build}.*`. The original query-budget failures, +first ambiguous-column failure, and final green result remain in +`/tmp/sleep31-discovery-{red,green,alias-green}.log`. Prior historical counts and +failures above retain their original revision scope. This local preparation has +not been published, and the parent has a new current-head P1 about ordinary input +restoration that must be repaired and adopted before this slice can merge. +Fresh exact-head remote CI/review, full repository acceptance and deployed sleep +are separate claims; no live provider or physical sleep result is asserted here. diff --git a/server/src/__tests__/chat-channels.integration.test.ts b/server/src/__tests__/chat-channels.integration.test.ts index eeb3aec3c27..9595f4a8f72 100644 --- a/server/src/__tests__/chat-channels.integration.test.ts +++ b/server/src/__tests__/chat-channels.integration.test.ts @@ -65178,6 +65178,58 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => { } }); + it.each(["task", "company", "startup"] as const)("bounds failed retry notice scope discovery with retained candidates (%s)", async mode => { + const context = await failedChatRetryFixture("telegram"); + const other = await failedChatRetryFixture("telegram"); + const copiedIds = Array.from({ length: 250 }, () => randomUUID()); + const stagedIds: string[] = []; + try { + for (const target of [context, other]) { + const staged = await db.transaction(tx => target.service.prepareFailedChatRunRetry(tx, { + companyId: target.fixture.companyId, issueId: target.issue.id, + agentId: target.fixture.assignedAgentId, failedRunId: target.runId, initiatedByUserId: "owner-user", + })); + await target.service.processFailedChatRunRetry(staged.actionId); + await db.update(agentWakeupRequests).set({ status: "deferred_issue_execution" }) + .where(eq(agentWakeupRequests.id, staged.actionId)); + stagedIds.push(staged.actionId); + } + const [action] = await db.select().from(chatActions).where(eq(chatActions.id, stagedIds[0])); + const [receipt] = await readAgentWakeupRequestsById(stagedIds[0]); + await db.insert(chatActions).values(copiedIds.map(id => ({ + ...action, id, providerActionId: `failed_run_retry:${id}`, + }))); + await db.insert(agentWakeupRequests).values(copiedIds.map(id => ({ + ...receipt, id, idempotencyKey: `retry-discovery-budget:${id}`, + }))); + const scope = { companyId: context.fixture.companyId, issueId: context.issue.id }; + const events: Array> = [], now = Date.now(); + const capture = createDatabaseResponseCapture({ start: now - 1, end: now + 59_000 }, event => events.push(event)); + installDatabaseResponseCapture(db, { chatActions, agentWakeupRequests }, capture); + let scopes: Array<{ companyId: string; issueId: string }>; + try { + scopes = await context.service.loadFailedRetryNoticeScopes( + mode === "task" ? scope : mode === "company" ? { companyId: scope.companyId } : undefined, + ); + } finally { capture.flush(); } + if (mode === "startup") { + expect(scopes).toEqual(expect.arrayContaining([scope, { + companyId: other.fixture.companyId, issueId: other.issue.id, + }])); + } else { + expect(scopes).toEqual([scope]); + } + expect(events.at(-1)).toMatchObject({ startedQueries: mode === "task" ? 0 : 1, + completedQueries: mode === "task" ? 0 : 1, inFlightAtEnd: 0 }); + expect(events.filter(event => event.event === "paperclip.db_response_capture.entry.v1") + .reduce((count, event) => count + Number(event.rows), 0)).toBe(mode === "task" ? 0 : scopes.length); + } finally { + await context.service.shutdown(); await other.service.shutdown(); + await db.delete(chatActions).where(inArray(chatActions.id, copiedIds)); + await db.delete(agentWakeupRequests).where(inArray(agentWakeupRequests.id, copiedIds)); + } + }); + it("scopes failed retry notices and retains receipt contention without retrying settled history", async () => { const context = await failedChatRetryFixture("telegram"); const other = await failedChatRetryFixture("telegram"); @@ -65211,7 +65263,7 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => { release(); await holder; expect(await context.service.reconcileFailedRetryNotices({ scope })) .toEqual({ inserted: 1, contended: false, nextCursor: null }); - expect(await context.service.loadFailedRetryNoticeScopes(scope)).toEqual([]); + expect(await context.service.loadFailedRetryNoticeScopes({ companyId: scope.companyId })).toEqual([]); expect(await readChatPublicationsByEndpointId(other.endpoint.id)).toEqual([]); await db.update(agentWakeupRequests).set({ status: "cancelled" }) .where(eq(agentWakeupRequests.id, staged[0].actionId)); @@ -65222,7 +65274,7 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => { })])); expect(await context.service.reconcileFailedRetryNotices({ scope })) .toEqual({ inserted: 0, contended: false, nextCursor: null }); - expect(await context.service.loadFailedRetryNoticeScopes(scope)).toEqual([]); + expect(await context.service.loadFailedRetryNoticeScopes({ companyId: scope.companyId })).toEqual([]); await db.update(agentWakeupRequests).set({ runId: other.runId }) .where(eq(agentWakeupRequests.id, staged[1].actionId)); expect(await other.service.loadFailedRetryNoticeScopes({ companyId: other.fixture.companyId })).toEqual([]); diff --git a/server/src/services/chat-channels/failed-retry-notices.ts b/server/src/services/chat-channels/failed-retry-notices.ts index cf2068079d2..effab8776ef 100644 --- a/server/src/services/chat-channels/failed-retry-notices.ts +++ b/server/src/services/chat-channels/failed-retry-notices.ts @@ -19,9 +19,11 @@ type Options = { export function createFailedRetryNotices(db: Db, options: Options) { let manualCursor: FailedRetryNoticeCursor | null = null; - async function candidates(limit: number, cursor: FailedRetryNoticeCursor | null, scope?: FailedRetryNoticeScope) { + function candidateQuery(cursor: FailedRetryNoticeCursor | null, scope?: FailedRetryNoticeScope) { return db.select({ action: chatActions, receipt: agentWakeupRequests, cursorCreatedAt: sql`${chatActions.createdAt}::text`, + companyId: sql`${chatActions.companyId}`.as("retry_notice_company_id"), + issueId: sql`${chatActions.payload}->>'issueId'`.as("retry_notice_issue_id"), }).from(chatActions).innerJoin(agentWakeupRequests, and( eq(agentWakeupRequests.id, chatActions.id), eq(agentWakeupRequests.companyId, chatActions.companyId), )).where(and( @@ -35,7 +37,10 @@ export function createFailedRetryNotices(db: Db, options: Options) { and retry_notice.idempotency_key = 'wake:' || ${chatActions.id}::text || ':' || case when ${agentWakeupRequests.status} = 'deferred_issue_execution' then 'queued' else 'not_started' end || ':' || ${chatActions.endpointId}::text || ':' || ${chatActions.conversationId}::text)`, - )).orderBy(asc(chatActions.createdAt), asc(chatActions.id)).limit(limit); + )); + } + async function candidates(limit: number, cursor: FailedRetryNoticeCursor | null, scope?: FailedRetryNoticeScope) { + return candidateQuery(cursor, scope).orderBy(asc(chatActions.createdAt), asc(chatActions.id)).limit(limit); } type Candidates = Awaited>; function continuation(rows: Candidates, limit: number): FailedRetryNoticeCursor | null { @@ -84,18 +89,11 @@ export function createFailedRetryNotices(db: Db, options: Options) { return (await project(rows)).inserted; } async function loadFailedRetryNoticeScopes(scope?: FailedRetryNoticeScope, signal?: AbortSignal) { - const scopes = new Map(); - let cursor: FailedRetryNoticeCursor | null = null; - do { - signal?.throwIfAborted(); - const rows = await candidates(200, cursor, scope); - for (const { action } of rows) { - const issueId = String(action.payload.issueId); - scopes.set(`${action.companyId}:${issueId}`, { companyId: action.companyId, issueId }); - } - cursor = continuation(rows, 200); - } while (cursor); - return [...scopes.values()]; + signal?.throwIfAborted(); + if (scope?.issueId) return [{ companyId: scope.companyId, issueId: scope.issueId }]; + const candidates = candidateQuery(null, scope).as("failed_retry_notice_candidates"); + return db.selectDistinct({ companyId: candidates.companyId, issueId: candidates.issueId }) + .from(candidates); } async function reconcileFailedRetryNotices(input: { scope: FailedRetryNoticeScope; limit?: number; cursor?: FailedRetryNoticeCursor | null; signal?: AbortSignal;