From d4706fbf2a04a00ade30181eb1bd9322e8455818 Mon Sep 17 00:00:00 2001 From: Dotta Date: Tue, 27 Oct 2026 16:58:36 -0500 Subject: [PATCH] Back off unresolved tool review projections and reduce empty reads Co-Authored-By: Paperclip --- doc/idle-tool-review-projection.md | 28 +++++++++++- ...2026-10-24-recurring-server-sleep-stack.md | 9 ++++ .../__tests__/tool-gateway-service.test.ts | 44 +++++++++++++++++++ .../services/tool-review-projection-work.ts | 16 +++++-- server/src/services/tool-review-projection.ts | 3 +- 5 files changed, 95 insertions(+), 5 deletions(-) diff --git a/doc/idle-tool-review-projection.md b/doc/idle-tool-review-projection.md index c59310ccb1f..f1d431ea920 100644 --- a/doc/idle-tool-review-projection.md +++ b/doc/idle-tool-review-projection.md @@ -172,7 +172,8 @@ request ID for each unfinished company, including after a failed pass, so a poisoned early page cannot hide later healthy cards. A truncated pass schedules a one-second continuation; the existing shared per-company fairness and failure backoff remain in force. A completed pass that still has an unprojectable card -retains the existing thirty-second retry. These are real unresolved projections, +backs off from thirty seconds to five minutes. Fresh committed company changes +reset that delay and wake the affected scope promptly. These are real unresolved projections, not an unconditional empty-history scan. Reconstruction clears continuation state for companies that no longer have @@ -201,3 +202,28 @@ identity-read tests. Server types and build pass. Thirty-five independent master performance files are preserved exactly; the gateway's narrowed identity read is preserved alongside the projection extraction. The pre-integration 220-case selection above remains evidence for its stated revision. + + +## Review efficiency follow-up + +A company-scoped hint now enters the bounded owner directly rather than first +repeating company discovery. Startup/global reconstruction still discovers +companies from existing rows. An empty sweep with no saved cursor returns after +one candidate query; a resumed cursor or attempted reflection still needs the +final query to detect unresolved earlier cards. The reflection callback returns +no settlement result, so an attempted reflection cannot establish that a card +was repaired. + +Returned unresolved work now backs off through 30, 60, 120, 240 and 300 seconds, +matching the shared error-backoff cap. Truncated backlog continuation remains +one second. Settlement removes the retry; a new committed hint resets backoff. +No pending row is discarded, and no independent timer or table is added. + +The fixed-cadence regression failed before repair and now verifies the full +backoff cap, producer reactivation and quiet after settlement. An initial scan +assertion incorrectly assumed that a complete approval emitted only one wake; +its separate legitimate writes caused two scans even after optimization. The +corrected case isolates one committed hint and verifies one candidate scan with +matching history, followed by an empty direct sweep with one query. All 222 +cases in the full gateway, startup and scoped-deadline suites pass without skips; +server typecheck and build pass. Fresh-head CI and both reviews are still required. diff --git a/doc/plans/2026-10-24-recurring-server-sleep-stack.md b/doc/plans/2026-10-24-recurring-server-sleep-stack.md index 6d2809504c9..25d3ebf70bc 100644 --- a/doc/plans/2026-10-24-recurring-server-sleep-stack.md +++ b/doc/plans/2026-10-24-recurring-server-sleep-stack.md @@ -326,3 +326,12 @@ the fixes. All 320 integrated gateway/projection/startup/deadline/identity/HTTP cases, server types and build pass; 35 independent master files are preserved exactly. Current-head CI and Greptile/Ponytail review remain required. Earlier case counts above describe the broader selections at their original revisions. + + +Slice 07 follow-up: scoped hints avoid redundant discovery, empty sweeps avoid a +second candidate read, and unresolved-card retries back off to five minutes. +Fresh writes reactivate promptly and settlement is quiet. The full affected +gateway/startup/deadline selection passes 222 cases; server types/build pass. +The initial invalid one-wake-per-approval assertion and corrected isolated-hint +measurement are retained in the behavior document. Current-head CI/reviews remain +required before this slice can merge. diff --git a/server/src/__tests__/tool-gateway-service.test.ts b/server/src/__tests__/tool-gateway-service.test.ts index b28aabb3d90..0d277ee4dbf 100644 --- a/server/src/__tests__/tool-gateway-service.test.ts +++ b/server/src/__tests__/tool-gateway-service.test.ts @@ -424,6 +424,50 @@ describeEmbeddedPostgres("tool gateway service", () => { expect(await projection(foreign)).toEqual(before); await quiet(); }); + it("uses one candidate scan for a committed company hint with matching retained history", async () => { + const pending = await request(); + await gateway.approveActionRequest({ companyId: fixture.company.id, actionRequestId: pending.id, actor: { userId: "board" } }); + await startProjection(); await quiet(); + const reads: string[] = []; + const debug = db.$client.options.debug; + db.$client.options.debug = (_id, query) => { + if (/^select/i.test(query) && query.includes('"tool_action_requests"') && query.includes("coalesce(")) reads.push(query); + }; + try { + await writeToolReviewChange(db, pending.companyId, async tx => { + await tx.update(toolActionRequests).set({ updatedAt: new Date() }).where(eq(toolActionRequests.id, pending.id)); + }); + await settle(); + expect(reads).toHaveLength(1); + await quiet(); + expect(reads).toHaveLength(1); + reads.length = 0; + expect(await gateway.repairActionReviewProjections(fixture.company.id)).toMatchObject({ scanned: 0, retry: false }); + expect(reads).toHaveLength(1); + } finally { db.$client.options.debug = debug; } + }); + + it("backs off unresolved cards to five minutes and clears the retry after settlement", async () => { + const pending = await request(); + await savedOutcome(pending, db, "failed"); + await startProjection(); + for (const delay of [30_000, 60_000, 120_000, 240_000, 300_000, 300_000]) { + const next = coordinator!.nextWakeAt(); + expect(next).not.toBeNull(); + expect(next! - Date.now()).toBeGreaterThan(delay - 1500); + expect(next! - Date.now()).toBeLessThanOrEqual(delay); + await settle(next! - Date.now() + 100); + } + expect(await projection(pending)).toBeUndefined(); + await acceptedCard(pending); + await writeToolReviewChange(db, pending.companyId, async tx => { + await tx.update(toolActionRequests).set({ updatedAt: new Date() }).where(eq(toolActionRequests.id, pending.id)); + }); + await settle(); + expect(await projection(pending)).toMatchObject({ status: "failed" }); + await quiet(); + }); + it("does not wake projection repair for ordinary confirmation creation, replacement, or cancellation", async () => { await startProjection(); await quiet(); const interactions = issueThreadInteractionService(db); diff --git a/server/src/services/tool-review-projection-work.ts b/server/src/services/tool-review-projection-work.ts index d6470f16892..b400f19f615 100644 --- a/server/src/services/tool-review-projection-work.ts +++ b/server/src/services/tool-review-projection-work.ts @@ -8,16 +8,26 @@ export function registerToolReviewProjectionWork( service: ReturnType, canRun: () => boolean, ) { + const unresolvedPasses = new Map(); return registerScopedDeadlineWork(coordinator, { queue: DELIVERY_QUEUES.toolReviewProjection, batchSize: 1, decodeScope: hint => hint === "*" ? undefined : hint, matches: (entry, companyId?: string) => companyId === undefined || entry.companyId === companyId, - load: async (companyId?: string) => (await service.companies(companyId)) - .map(row => ({ ...row, id: row.companyId, dueAt: Date.now() })), + load: async (companyId?: string) => { + const rows = companyId ? [{ companyId }] : await service.companies(); + for (const scope of unresolvedPasses.keys()) { + if (!companyId || scope === companyId) unresolvedPasses.delete(scope); + } + return rows.map(row => ({ ...row, id: row.companyId, dueAt: Date.now() })); + }, check: async (entry, signal) => { const result = await service.sweep(entry.companyId, { maxRows: 500, signal, shouldContinue: canRun }); - return result.retry ? { ...entry, dueAt: Date.now() + (result.truncated ? 1000 : 30_000) } : null; + if (!result.retry) { unresolvedPasses.delete(entry.id); return null; } + if (result.truncated) return { ...entry, dueAt: Date.now() + 1000 }; + const count = Math.min((unresolvedPasses.get(entry.id) ?? 0) + 1, 5); + unresolvedPasses.set(entry.id, count); + return { ...entry, dueAt: Date.now() + Math.min(300_000, 30_000 * 2 ** (count - 1)) }; }, }, canRun); } diff --git a/server/src/services/tool-review-projection.ts b/server/src/services/tool-review-projection.ts index ca1f81f5578..32644929cac 100644 --- a/server/src/services/tool-review-projection.ts +++ b/server/src/services/tool-review-projection.ts @@ -44,6 +44,7 @@ export function toolReviewProjectionService(db: Db, reflect: (input: { const maxRows = options.maxRows ?? Infinity; const scope = companyId ?? "*"; let cursor = maxRows === Infinity ? undefined : continuations.get(scope); + const resumed = cursor !== undefined; let scanned = 0, completed = false; const canContinue = () => !options.signal?.aborted && (options.shouldContinue?.() ?? true); const failures: unknown[] = []; @@ -70,7 +71,7 @@ export function toolReviewProjectionService(db: Db, reflect: (input: { } if (failures.length) throw new AggregateError(failures, "Tool review projection repair failed"); return { scanned, truncated: !completed, - retry: !completed || (await candidates(companyId).limit(1)).length > 0 }; + retry: !completed || ((scanned > 0 || resumed) && (await candidates(companyId).limit(1)).length > 0) }; }, }; }