diff --git a/doc/idle-interrupted-tool-recovery.md b/doc/idle-interrupted-tool-recovery.md index 885c3cf4d44..798ce32f1b8 100644 --- a/doc/idle-interrupted-tool-recovery.md +++ b/doc/idle-interrupted-tool-recovery.md @@ -73,3 +73,44 @@ The ten-minute policy is unchanged. Active provider execution, unknown external outcomes, and other worker obligations still prevent unsafe sleep. No Cloud eligibility or external-alarm coverage changes here. Worker quiet is not evidence of whole-instance or database suspension. + +## Sequential-write cost correction (October 27) + +Review found that sequential tenant writes could each request a global +interruption pass, even when no execution was stale. A real-SQL regression +created ten tool review requests through the gateway and allowed each preceding +pass to finish. It measured 11 stale-claim scans including startup. Concurrent +notification coalescing alone did not cover this sequence. + +The worker now uses the existing deadline helper's 30-second notification +coalescing window, matching the former default maintenance cadence. The same +regression measures one startup scan and one follow-up scan for those ten +requests, then no worker SQL through an additional idle hour. A loaded stale +claim deadline only 500 milliseconds away still preempts the window and +quarantines the unknown outcome without invoking the provider. Foreground +execution and result settlement remain immediate. Newly discovered work can +wait up to this window; the ten-minute stale-claim policy is unchanged. + +This is the bounded-frequency alternative raised in review. Discovery is still +instance-wide, and real stale backlogs still drain through the existing pages. +It does not claim company-isolated scans or constant cost for a real backlog. +No notification and no saved execution deadline means no periodic scan. No new +table, index, or scheduler is added. Startup, drain, retry and shutdown retain +the existing owners. + +The first full verification passed 175 cases and failed three fake-clock waits: +settlement writes leave a notification pending for its coalesced follow-up, so +waiting for the idle hold without advancing that armed deadline cannot finish. +An initial shared clock adjustment then advanced an unrelated five-second +expiry test too far (177 passed, one failed). The adjustment is now confined to +the interruption tests. It lets real SQL finish and advances only to an actually +armed short follow-up. The imminent-deadline test checks quarantine before that +30-second window and separately waits for eventual quiet. Product assertions +were retained. + +The final complete gateway-service and startup-wiring suites pass all 178 cases +without skips, and server typechecking passes, on owner source based on +`e255d8eff3363cf0bb63541bdc7ef055d4321f83`. The attempted third test selector +`deadline-work.test.ts` did not exist at this owner; no separate helper-suite +pass is claimed. The shared helper is exercised by the full gateway suites. +Fresh combined-source checks and remote review remain required. diff --git a/server/src/__tests__/tool-gateway-service.test.ts b/server/src/__tests__/tool-gateway-service.test.ts index 8546b18dbe9..2bc01221233 100644 --- a/server/src/__tests__/tool-gateway-service.test.ts +++ b/server/src/__tests__/tool-gateway-service.test.ts @@ -596,6 +596,28 @@ describeEmbeddedPostgres("tool gateway service", () => { canReconcile: () => true, onError: error => errors.push(error) }); await registerToolReviewInterruptionWork(coordinator, gateway, () => !draining).ready; } + async function settle(ms = 60_000) { + await vi.advanceTimersByTimeAsync(ms); + if (!draining) await vi.waitFor(async () => { + // Finish real SQL before following an armed coalescing/retry deadline. + // Do not jump across a future business deadline while waiting for I/O. + if (idleWorkSnapshot().active > 0) { + await db.execute(sql`select pg_sleep(0.01)`); + const next = coordinator!.nextWakeAt(); + if (next !== null && next <= Date.now() + 30_000) { + await vi.advanceTimersByTimeAsync(Math.max(0, next - Date.now())); + } + } + expect(idleWorkSnapshot().active).toBe(0); + }, { timeout: 5000 }); + } + async function quiet() { + await settle(); expect(coordinator!.nextWakeAt()).toBeNull(); + const selects = vi.spyOn(db, "select"), executes = vi.spyOn(db, "execute"); + await settle(60 * 60_000); + expect(selects).not.toHaveBeenCalled(); expect(executes).not.toHaveBeenCalled(); + selects.mockRestore(); executes.mockRestore(); + } async function savedClaim(source = db, age = 0) { const pending = await request(); const claimedAt = new Date(Date.now() - age); @@ -613,6 +635,52 @@ describeEmbeddedPostgres("tool gateway service", () => { .toMatchObject({ status: "failed", errorCode: "tool_execution_outcome_unknown" }); } + it("coalesces sequential review writes into one interruption scan per window", async () => { + vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout", "setInterval", "clearInterval"], shouldAdvanceTime: false }); + const previous = db.$client.options.debug; + const scans: string[] = []; + db.$client.options.debug = (_connection, query) => { + if (query.includes('from "tool_action_requests"') && query.includes('"updated_at" <=')) scans.push(query); + }; + try { + await startInterruption(); + const firstPassAt = Date.now(); + expect(scans).toHaveLength(1); + for (let i = 0; i < 10; i++) { + await request(); + await vi.advanceTimersByTimeAsync(1); + // Let each previous pass finish; overlapping calls already coalesce. + await db.execute(sql`select pg_sleep(0.01)`); + } + expect(scans).toHaveLength(1); + expect(coordinator!.nextWakeAt()).toBe(firstPassAt + 30_000); + await vi.advanceTimersByTimeAsync(30_000); + await vi.waitFor(() => { + expect(scans).toHaveLength(2); + expect(idleWorkSnapshot().active).toBe(0); + expect(coordinator!.nextWakeAt()).toBeNull(); + }); + await quiet(); + expect(scans).toHaveLength(2); + } finally { db.$client.options.debug = previous; } + }); + + it("keeps a loaded stale-claim deadline ahead of review notification coalescing", async () => { + vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout", "setInterval", "clearInterval"], shouldAdvanceTime: false }); + const pending = await savedClaim(db, 10 * 60_000 - 500); + const deadline = pending.updatedAt.getTime() + 10 * 60_000; + await startInterruption(); + expect(coordinator!.nextWakeAt()).toBe(deadline); + await request(); + await vi.advanceTimersByTimeAsync(1); + await db.execute(sql`select pg_sleep(0.01)`); + expect(coordinator!.nextWakeAt()).toBe(deadline); + await vi.advanceTimersByTimeAsync(499); + await vi.waitFor(async () => { await unknown(pending); }); + expect(Date.now()).toBeLessThan(deadline + 1000); + await quiet(); + }); + it("arms from a real execution claim and disarms after the provider result", async () => { await startInterruption(); await quiet(); const remote = providerFixture(); diff --git a/server/src/services/tool-review-interruption-work.ts b/server/src/services/tool-review-interruption-work.ts index 204ce092fb7..9053cb1c4dd 100644 --- a/server/src/services/tool-review-interruption-work.ts +++ b/server/src/services/tool-review-interruption-work.ts @@ -9,7 +9,7 @@ export function registerToolReviewInterruptionWork( canRun: () => boolean, ) { return registerDeadlineWork(coordinator, DELIVERY_QUEUES.toolReviewInterruption, { - retryMs: 30_000, canRun, + retryMs: 30_000, notificationCoalesceMs: 30_000, canRun, run: () => gateway.settleInterruptedActionReviews(), next: () => gateway.nextActionReviewInterruptionAt(), });