From 7436d29cc9494d6599c2f93331068b5b27687c2b Mon Sep 17 00:00:00 2001 From: Dotta Date: Tue, 27 Oct 2026 00:31:39 -0500 Subject: [PATCH] fix(server): bound credential expiry cleanup and write notifications Coalesce credential changes within the former cleanup cadence while preserving loaded deadlines and authentication expiry. Limit session deletion to 500 rows and prove sequential writes, backlog recovery, and early deadlines with real PostgreSQL. Co-Authored-By: Paperclip --- doc/idle-gateway-credential-expiry.md | 35 +++++++- .../gateway-credential-expiry.test.ts | 81 ++++++++++++++++++- server/src/services/deadline-work.ts | 8 ++ .../gateway-credential-expiry-work.ts | 1 + server/src/services/tool-gateway.ts | 9 ++- 5 files changed, 129 insertions(+), 5 deletions(-) diff --git a/doc/idle-gateway-credential-expiry.md b/doc/idle-gateway-credential-expiry.md index f996cd6acbb..04c48991e65 100644 --- a/doc/idle-gateway-credential-expiry.md +++ b/doc/idle-gateway-credential-expiry.md @@ -39,14 +39,24 @@ enabled, committed changes and actual expiry times replace the recurring cleanup call. With heartbeat scheduling disabled, the existing startup-only cleanup is preserved. Tool action-review recovery is a separate obligation and is unchanged. -Existing token deletion is bounded to 500 rows per pass. A remaining overdue -expiry schedules another pass after 30 seconds. Failed reconciliation also +Token and session deletion are each bounded to 500 rows per pass. Session +selection orders by expiry and rechecks expiry when deleting the selected IDs. +A remaining overdue expiry schedules another pass after 30 seconds. Failed reconciliation also retries at that bound. No unfinished reconciliation or future expiry means no recurring SQL. A generation retains writes arriving during reconciliation. Startup restores deadlines; drain retains first writes without passive SQL; resume completes overdue cleanup. The coordinator owns shutdown and waits for in-flight work. +Sequential committed writes are coalesced for up to 30 seconds after a +successful cleanup pass, matching the former heartbeat cleanup cadence. A +previously loaded expiry can preempt that window. A newly reported credential +may physically remain until that bounded follow-up; authentication still rejects +it immediately at expiry. A successful pass with no future expiry and no new +notifications creates no timer. This uses the shared optional notification +coalescing capability, promoted from the later plugin/decision recovery slices; +workers that omit it retain their existing behavior. + ## Evidence and limits The concurrent session index runs through the migration executor's existing @@ -80,3 +90,24 @@ producer signals must use the same token eligibility as cleanup: run-token idle markers must not schedule the operator-token expiry worker. Keep the run-liveness reaper with its own owner and retain both regression suites. A conflict-free text merge alone does not prove this integration. + +## Notification amplification review repair (2026-10-27) + +Ten sequential real session/token creation transactions reproduced ten extra +instance-wide cleanup passes. With coalescing they cause one follow-up pass. +A separate 501-session fixture reproduced the unbounded delete, then passed +with 500 removed initially and the remaining overdue row removed at the saved +30-second retry. A still-valid session survives both passes. The tests also +preserve an already loaded expiry only 500 milliseconds away and verify that a +new one-second session is rejected while physical cleanup waits for coalescing. + +The initial full run exposed four outer-transaction tests whose fake-clock wait +expected the intent hold to release before the new coalescing follow-up. Their +settlement helper now advances the clock through that window while preserving +the original commit/rollback assertions. The complete gateway expiry, gateway +acceptance, custom-image deadline, and startup suites pass: 147 tests in four +files. Server typechecking also passes on the owning branch. This is local +behavioral evidence; combined-stack and fresh remote checks remain required. +The full local test:run remains unverified because of embedded PostgreSQL +startup/capacity limits; the two real gateway suites used separate migrated, +task-owned disposable PostgreSQL databases. diff --git a/server/src/__tests__/gateway-credential-expiry.test.ts b/server/src/__tests__/gateway-credential-expiry.test.ts index af16c68659c..39e3590f9ad 100644 --- a/server/src/__tests__/gateway-credential-expiry.test.ts +++ b/server/src/__tests__/gateway-credential-expiry.test.ts @@ -59,7 +59,11 @@ describe.skipIf(!supported)("gateway credential expiry", () => { } async function settle(ms = 60_000) { await vi.advanceTimersByTimeAsync(ms); - if (!draining) await vi.waitFor(() => expect(idleWorkSnapshot().active).toBe(0), { timeout: 5000 }); + if (!draining) await vi.waitFor(async () => { + // SQL may finish after the clock jump and arm a coalesced follow-up pass. + if (idleWorkSnapshot().active > 0) await vi.advanceTimersByTimeAsync(30_000); + expect(idleWorkSnapshot().active).toBe(0); + }, { timeout: 5000 }); } async function quiet() { await settle(); expect(coordinator!.nextWakeAt()).toBeNull(); @@ -122,6 +126,81 @@ describe.skipIf(!supported)("gateway credential expiry", () => { } }); + it("coalesces sequential credential writes within the former cleanup cadence", async () => { + vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout", "setInterval", "clearInterval"], shouldAdvanceTime: false }); + const cleanup = vi.spyOn(gateway, "cleanupExpiredSessions"); + const next = vi.spyOn(gateway, "nextCredentialExpiryAt"); + await start(); + const firstPassAt = Date.now(); + for (let i = 0; i < 10; i++) { + if (i % 2 === 0) await session(); + else await token(new Date(Date.now() + 5 * 60_000)); + await vi.advanceTimersByTimeAsync(1); + // Let each old scan finish so this measures sequential writes, not overlapping calls. + await db.execute(sql`select pg_sleep(0.01)`); + } + expect(cleanup).toHaveBeenCalledTimes(1); + expect(next).toHaveBeenCalledTimes(1); + expect(coordinator!.nextWakeAt()).toBe(firstPassAt + 30_000); + await vi.advanceTimersByTimeAsync(30_000); + await vi.waitFor(() => expect(next).toHaveBeenCalledTimes(2)); + await db.execute(sql`select pg_sleep(0.01)`); + expect(cleanup).toHaveBeenCalledTimes(2); + expect(coordinator!.nextWakeAt()).toBeGreaterThan(Date.now()); + await settle(5 * 60_000); await quiet(); + }); + + it("keeps a loaded expiry deadline ahead of credential notification coalescing", async () => { + vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout", "setInterval", "clearInterval"], shouldAdvanceTime: false }); + const deadline = Date.now() + 500; + await token(new Date(deadline)); + await start(); + expect(coordinator!.nextWakeAt()).toBe(deadline); + await session(); + 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 () => expect(await db.select().from(toolMcpGatewayTokens)).toEqual([])); + expect(await db.select().from(toolGatewaySessions)).toHaveLength(1); + await settle(5 * 60_000); await quiet(); + }); + + it("rejects a newly expired credential while physical cleanup is coalesced", async () => { + vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout", "setInterval", "clearInterval"], shouldAdvanceTime: false }); + const cleanup = vi.spyOn(gateway, "cleanupExpiredSessions"); + await start(); + const at = Date.now(); + const active = await gateway.createSession({ companyId, agentId, runId, ttlMs: 1000 }); + await vi.advanceTimersByTimeAsync(1000); + await db.execute(sql`select pg_sleep(0.01)`); + expect(cleanup).toHaveBeenCalledTimes(1); + expect(await db.select().from(toolGatewaySessions)).toHaveLength(1); + await expect(gateway.listToolsForSession(active.token)).rejects.toMatchObject({ status: 401, reasonCode: "session_expired" }); + expect(coordinator!.nextWakeAt()).toBe(at + 30_000); + await vi.advanceTimersByTimeAsync(29_000); + await vi.waitFor(async () => expect(await db.select().from(toolGatewaySessions)).toEqual([])); + await quiet(); + }); + + it("bounds session cleanup and schedules the remaining overdue batch", async () => { + vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout", "setInterval", "clearInterval"], shouldAdvanceTime: false }); + await db.insert(toolGatewaySessions).values(Array.from({ length: 501 }, () => ({ + companyId, agentId, runId, tokenHash: randomUUID(), expiresAt: new Date(Date.now() - 1), + }))); + const future = await session(); + const cleanup = vi.spyOn(gateway, "cleanupExpiredSessions"); + await start(); + expect(cleanup).toHaveResolvedWith({ deletedCount: 500 }); + expect(await db.select().from(toolGatewaySessions)).toHaveLength(2); + expect(coordinator!.nextWakeAt()).toBe(Date.now() + 30_000); + await vi.advanceTimersByTimeAsync(29_999); + expect(cleanup).toHaveBeenCalledTimes(1); + await vi.advanceTimersByTimeAsync(1); + await vi.waitFor(async () => expect((await db.select().from(toolGatewaySessions)).map(row => row.id)).toEqual([future.id])); + await settle(5 * 60_000); await quiet(); + }); + it("reconstructs saved token expiry on startup", async () => { const due = new Date(Date.now() + 5 * 60_000); await token(due); diff --git a/server/src/services/deadline-work.ts b/server/src/services/deadline-work.ts index 9f1de1b2a24..044c3cbfce4 100644 --- a/server/src/services/deadline-work.ts +++ b/server/src/services/deadline-work.ts @@ -9,11 +9,14 @@ export function registerDeadlineWork( next: () => Promise; canRun: () => boolean; retryMs: number; + // Optional batching latency for notifications; already-known deadlines still preempt it. + notificationCoalesceMs?: number; }, ) { let requested = 1, reconciled = 0; let next: number | null = null; let earliest = 0; + let coalesceUntil = 0; return coordinator.register(queue, { retryMs: task.retryMs, pausePassiveMaintenance: true, @@ -21,6 +24,10 @@ export function registerDeadlineWork( run: async () => { if (!task.canRun()) { requested++; return; } if (Date.now() < earliest) { next = earliest; return; } + if (Date.now() < coalesceUntil && (next === null || next > Date.now())) { + next = next === null ? coalesceUntil : Math.min(next, coalesceUntil); + return; + } const generation = ++requested; earliest = Date.now() + task.retryMs; await task.run(); @@ -28,6 +35,7 @@ export function registerDeadlineWork( // Back off failed or still-overdue work, not a successfully read future deadline. if (deadline === null || deadline > Date.now()) earliest = 0; next = deadline === null ? null : Math.max(earliest, deadline); + coalesceUntil = Date.now() + (task.notificationCoalesceMs ?? 0); reconciled = generation; }, hasPending: async () => requested !== reconciled, diff --git a/server/src/services/gateway-credential-expiry-work.ts b/server/src/services/gateway-credential-expiry-work.ts index 48ddeedfa4b..cbca7f17862 100644 --- a/server/src/services/gateway-credential-expiry-work.ts +++ b/server/src/services/gateway-credential-expiry-work.ts @@ -10,6 +10,7 @@ export function registerGatewayCredentialExpiryWork( ) { return registerDeadlineWork(coordinator, DELIVERY_QUEUES.gatewayCredentialExpiry, { retryMs: 30_000, + notificationCoalesceMs: 30_000, canRun, run: () => gateway.cleanupExpiredSessions(), next: () => gateway.nextCredentialExpiryAt(), diff --git a/server/src/services/tool-gateway.ts b/server/src/services/tool-gateway.ts index a92651b0bae..3d44cf196b7 100644 --- a/server/src/services/tool-gateway.ts +++ b/server/src/services/tool-gateway.ts @@ -11631,9 +11631,14 @@ export function createToolGatewayService( .where(and(inArray(toolMcpGatewayTokens.id, expiredTokens.map((token) => token.id)), lte(toolMcpGatewayTokens.expiresAt, now))) .returning({ id: toolMcpGatewayTokens.id }); } - const rows = await db - .delete(toolGatewaySessions) + const expiredSessions = await db.select({ id: toolGatewaySessions.id }) + .from(toolGatewaySessions) .where(lte(toolGatewaySessions.expiresAt, now)) + .orderBy(asc(toolGatewaySessions.expiresAt), asc(toolGatewaySessions.id)) + .limit(500); + if (expiredSessions.length === 0) return { deletedCount: 0 }; + const rows = await db.delete(toolGatewaySessions) + .where(and(inArray(toolGatewaySessions.id, expiredSessions.map((session) => session.id)), lte(toolGatewaySessions.expiresAt, now))) .returning({ id: toolGatewaySessions.id }); return { deletedCount: rows.length }; },