Merge gateway cleanup fix into sleep-05-approved-tool-recovery

Co-Authored-By: Paperclip <noreply@paperclip.ing>

* codex/sleep-04-tool-review-expiry:
  fix(server): drain gateway expiry during one-shot cleanup
This commit is contained in:
DottaandPaperclip committed 2026-10-27 02:34:11 -05:00
commit c19e09bd16
4 files changed
+67 -19

No files matched your search

@@ -190,6 +190,25 @@ describe.skipIf(!supported)("gateway credential expiry", () => {
await quiet();
});
it.each(["sessions", "tokens", "both"] as const)("drains the full %s backlog without a registered scheduler", async kind => {
vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout", "setInterval", "clearInterval"], shouldAdvanceTime: false });
const now = new Date();
const futureSession = await session();
const futureToken = await token(new Date(now.getTime() + 60_000));
const nonexpiringToken = await token();
if (kind !== "tokens") await db.insert(toolGatewaySessions).values(Array.from({ length: 1001 }, () => ({
companyId, agentId, runId, tokenHash: randomUUID(), expiresAt: new Date(now.getTime() - 1),
})));
if (kind !== "sessions") await db.insert(toolMcpGatewayTokens).values(Array.from({ length: 1001 }, () => ({
companyId, gatewayId: namedId, name: "Expired", tokenHash: randomUUID(), expiresAt: new Date(now.getTime() - 1),
})));
await expect(gateway.cleanupExpiredSessions({ now })).resolves.toEqual({ deletedCount: kind === "tokens" ? 0 : 1001 });
expect((await db.select().from(toolGatewaySessions)).map(row => row.id)).toEqual([futureSession.id]);
expect((await db.select().from(toolMcpGatewayTokens)).map(row => row.id).sort()).toEqual([futureToken.id, nonexpiringToken.id].sort());
expect(coordinator).toBeUndefined();
expect(idleWorkSnapshot().active).toBe(0);
});
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 }, () => ({
@@ -12,7 +12,7 @@ export function registerGatewayCredentialExpiryWork(
retryMs: 30_000,
notificationCoalesceMs: 30_000,
canRun,
run: () => gateway.cleanupExpiredSessions(),
run: () => gateway.cleanupExpiredSessions({ singleBatch: true }),
next: () => gateway.nextCredentialExpiryAt(),
});
}
+26 -18
View File
@@ -11545,28 +11545,36 @@ export function createToolGatewayService(
return row?.at == null ? null : new Date(row.at).getTime();
},
async cleanupExpiredSessions(input: { now?: Date } = {}) {
async cleanupExpiredSessions(input: { now?: Date; singleBatch?: boolean } = {}) {
const now = input.now ?? new Date();
const expiredTokens = await db.select({ id: toolMcpGatewayTokens.id })
.from(toolMcpGatewayTokens)
.where(lte(toolMcpGatewayTokens.expiresAt, now))
.orderBy(asc(toolMcpGatewayTokens.expiresAt), asc(toolMcpGatewayTokens.id))
.limit(500);
if (expiredTokens.length > 0) {
await db.delete(toolMcpGatewayTokens)
let deletedCount = 0;
while (true) {
const expiredTokens = await db.select({ id: toolMcpGatewayTokens.id })
.from(toolMcpGatewayTokens)
.where(lte(toolMcpGatewayTokens.expiresAt, now))
.orderBy(asc(toolMcpGatewayTokens.expiresAt), asc(toolMcpGatewayTokens.id))
.limit(500);
if (expiredTokens.length > 0) {
await db.delete(toolMcpGatewayTokens)
.where(and(inArray(toolMcpGatewayTokens.id, expiredTokens.map((token) => token.id)), lte(toolMcpGatewayTokens.expiresAt, now)))
.returning({ id: toolMcpGatewayTokens.id });
}
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) {
const rows = await db.delete(toolGatewaySessions)
.where(and(inArray(toolGatewaySessions.id, expiredSessions.map((session) => session.id)), lte(toolGatewaySessions.expiresAt, now)))
.returning({ id: toolGatewaySessions.id });
deletedCount += rows.length;
}
// The worker schedules the next page; one-shot startup/manual callers
// must finish the backlog without relying on another scheduled pass.
if (input.singleBatch || (expiredTokens.length < 500 && expiredSessions.length < 500)) break;
}
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 };
return { deletedCount };
},
async listRuntimeSlots(companyId?: string) {