Skip to content

Commit a97754b

Browse files
committed
fix(gateway): resume durable outbound delivery retries
1 parent 096c929 commit a97754b

3 files changed

Lines changed: 313 additions & 25 deletions

File tree

‎src/gateway/server-runtime-services.test.ts‎

Lines changed: 146 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
55
import {
66
getActiveGatewayRootWorkCount,
77
resetGatewayWorkAdmission,
8+
tryBeginGatewaySuspendAdmission,
89
tryBeginGatewayRootWorkAdmission,
910
} from "../process/gateway-work-admission.js";
1011

@@ -17,6 +18,8 @@ function waitForFast<T>(
1718

1819
type StartSessionDeliveryRuntime =
1920
typeof import("../infra/session-delivery-queue-runtime.js").startSessionDeliveryRuntime;
21+
type DrainPendingDeliveries =
22+
typeof import("../infra/outbound/delivery-queue.js").drainPendingDeliveries;
2023

2124
const hoisted = vi.hoisted(() => {
2225
const heartbeatRunner = {
@@ -40,7 +43,13 @@ const hoisted = vi.hoisted(() => {
4043
),
4144
schedulePendingSessionDeliveries: vi.fn(async () => undefined),
4245
startSessionUpstreamMonitor: vi.fn(() => ({ stop: stopSessionUpstreamMonitor })),
43-
recoverPendingDeliveries: vi.fn(async () => undefined),
46+
recoverPendingDeliveries: vi.fn(async () => ({
47+
recovered: 0,
48+
failed: 0,
49+
skippedMaxRetries: 0,
50+
deferredBackoff: 0,
51+
})),
52+
drainPendingDeliveries: vi.fn<DrainPendingDeliveries>(async () => undefined),
4453
recoverPendingRestartContinuationDeliveries: vi.fn(async () => undefined),
4554
deliverQueuedSessionDelivery: vi.fn(async () => undefined),
4655
settleQueuedSessionDelivery: vi.fn(async () => undefined),
@@ -71,6 +80,7 @@ vi.mock("../infra/outbound/deliver.js", () => ({
7180

7281
vi.mock("../infra/outbound/delivery-queue.js", () => ({
7382
recoverPendingDeliveries: hoisted.recoverPendingDeliveries,
83+
drainPendingDeliveries: hoisted.drainPendingDeliveries,
7484
}));
7585

7686
vi.mock("../infra/session-delivery-queue-runtime.js", () => ({
@@ -116,6 +126,8 @@ describe("server-runtime-services", () => {
116126
hoisted.startSessionDeliveryRuntime.mockClear();
117127
hoisted.schedulePendingSessionDeliveries.mockClear();
118128
hoisted.recoverPendingDeliveries.mockClear();
129+
hoisted.drainPendingDeliveries.mockReset();
130+
hoisted.drainPendingDeliveries.mockResolvedValue(undefined);
119131
hoisted.recoverPendingRestartContinuationDeliveries.mockClear();
120132
hoisted.deliverQueuedSessionDelivery.mockClear();
121133
hoisted.settleQueuedSessionDelivery.mockClear();
@@ -410,6 +422,139 @@ describe("server-runtime-services", () => {
410422
expect(hoisted.recoverPendingDeliveries).toHaveBeenCalledTimes(1);
411423
});
412424

425+
it.each([
426+
{
427+
name: "startup recovery deferred an existing delivery for backoff",
428+
deferredBackoff: 1,
429+
},
430+
{
431+
name: "a new delivery failed after an empty startup scan",
432+
deferredBackoff: 0,
433+
},
434+
])("retries outbound deliveries when $name", async ({ deferredBackoff }) => {
435+
vi.useFakeTimers();
436+
hoisted.recoverPendingDeliveries.mockResolvedValueOnce({
437+
recovered: 0,
438+
failed: 0,
439+
skippedMaxRetries: 0,
440+
deferredBackoff,
441+
});
442+
const { services } = activateScheduledServicesForTest({ startCron: false });
443+
444+
await vi.advanceTimersByTimeAsync(4_999);
445+
expect(hoisted.recoverPendingDeliveries).toHaveBeenCalledOnce();
446+
expect(hoisted.drainPendingDeliveries).not.toHaveBeenCalled();
447+
448+
await vi.advanceTimersByTimeAsync(1);
449+
450+
expect(hoisted.drainPendingDeliveries).toHaveBeenCalledOnce();
451+
const [drain] = hoisted.drainPendingDeliveries.mock.calls[0] ?? [];
452+
expect(drain).toMatchObject({
453+
drainKey: "gateway:outbound",
454+
deliver: hoisted.deliverOutboundPayloads,
455+
});
456+
expect(drain?.selectEntry({ channel: "discord" } as never, Date.now())).toEqual({
457+
match: true,
458+
bypassBackoff: false,
459+
});
460+
services.heartbeatRunner.stop();
461+
});
462+
463+
it("uses the current runtime config when retrying queued outbound deliveries", async () => {
464+
vi.useFakeTimers();
465+
const configModule = await import("../config/config.js");
466+
const reloadedConfig = { channels: { discord: { enabled: false } } };
467+
const runtimeConfig = vi
468+
.spyOn(configModule, "getRuntimeConfig")
469+
.mockReturnValue(reloadedConfig as never);
470+
const { services } = activateScheduledServicesForTest({
471+
startCron: false,
472+
cfgAtStart: { channels: { discord: { enabled: true } } } as never,
473+
});
474+
475+
try {
476+
await vi.advanceTimersByTimeAsync(5_000);
477+
478+
expect(hoisted.drainPendingDeliveries).toHaveBeenCalledWith(
479+
expect.objectContaining({ cfg: reloadedConfig }),
480+
);
481+
expect(runtimeConfig).toHaveBeenCalledOnce();
482+
} finally {
483+
services.heartbeatRunner.stop();
484+
runtimeConfig.mockRestore();
485+
}
486+
});
487+
488+
it("never overlaps outbound retry drains or admits work between timer firings", async () => {
489+
vi.useFakeTimers();
490+
let finishDrain: (() => void) | undefined;
491+
hoisted.drainPendingDeliveries.mockImplementationOnce(
492+
() =>
493+
new Promise<void>((resolve) => {
494+
finishDrain = resolve;
495+
}),
496+
);
497+
const { services } = activateScheduledServicesForTest({ startCron: false });
498+
499+
await vi.advanceTimersByTimeAsync(1_250);
500+
expect(getActiveGatewayRootWorkCount()).toBe(0);
501+
502+
await vi.advanceTimersByTimeAsync(3_750);
503+
expect(hoisted.drainPendingDeliveries).toHaveBeenCalledOnce();
504+
expect(getActiveGatewayRootWorkCount()).toBe(1);
505+
506+
await vi.advanceTimersByTimeAsync(10_000);
507+
expect(hoisted.drainPendingDeliveries).toHaveBeenCalledOnce();
508+
expect(getActiveGatewayRootWorkCount()).toBe(1);
509+
510+
if (!finishDrain) {
511+
throw new Error("Expected the outbound retry drain to be pending");
512+
}
513+
finishDrain();
514+
await vi.advanceTimersByTimeAsync(0);
515+
expect(getActiveGatewayRootWorkCount()).toBe(0);
516+
517+
await vi.advanceTimersByTimeAsync(5_000);
518+
expect(hoisted.drainPendingDeliveries).toHaveBeenCalledTimes(2);
519+
services.heartbeatRunner.stop();
520+
});
521+
522+
it("stops outbound delivery retry timers with the gateway lifecycle", async () => {
523+
vi.useFakeTimers();
524+
const { services } = activateScheduledServicesForTest({ startCron: false });
525+
526+
await vi.advanceTimersByTimeAsync(5_000);
527+
expect(hoisted.drainPendingDeliveries).toHaveBeenCalledOnce();
528+
529+
services.heartbeatRunner.stop();
530+
await vi.advanceTimersByTimeAsync(15_000);
531+
532+
expect(hoisted.drainPendingDeliveries).toHaveBeenCalledOnce();
533+
expect(hoisted.heartbeatRunner.stop).toHaveBeenCalledOnce();
534+
expect(getActiveGatewayRootWorkCount()).toBe(0);
535+
});
536+
537+
it("skips outbound retry ticks while gateway work admission is suspended", async () => {
538+
vi.useFakeTimers();
539+
const { services } = activateScheduledServicesForTest({ startCron: false });
540+
await vi.advanceTimersByTimeAsync(1_250);
541+
542+
const suspension = tryBeginGatewaySuspendAdmission(() => {});
543+
if (!suspension?.commit()) {
544+
throw new Error("Expected gateway suspension admission to be acquired");
545+
}
546+
await vi.advanceTimersByTimeAsync(13_750);
547+
548+
expect(hoisted.drainPendingDeliveries).not.toHaveBeenCalled();
549+
expect(getActiveGatewayRootWorkCount()).toBe(0);
550+
551+
suspension.release();
552+
await vi.advanceTimersByTimeAsync(5_000);
553+
554+
expect(hoisted.drainPendingDeliveries).toHaveBeenCalledOnce();
555+
services.heartbeatRunner.stop();
556+
});
557+
413558
it("starts cron and records memory when post-ready maintenance fails", async () => {
414559
const cron = { start: vi.fn(async () => undefined) };
415560
const log = createLog();

‎src/gateway/server-runtime-services.ts‎

Lines changed: 67 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
// Starts delayed maintenance, cron, heartbeat, recovery, and pricing refresh work.
33
import { getRuntimeConfig } from "../config/config.js";
44
import type { OpenClawConfig } from "../config/types.openclaw.js";
5+
import { computeBackoffMs } from "../infra/delivery-recovery.shared.js";
56
import {
67
resolveHeartbeatAgents,
78
startHeartbeatRunner,
@@ -12,7 +13,10 @@ import {
1213
schedulePendingSessionDeliveries,
1314
startSessionDeliveryRuntime,
1415
} from "../infra/session-delivery-queue-runtime.js";
15-
import { runWithGatewayIndependentRootWorkAdmission } from "../process/gateway-work-admission.js";
16+
import {
17+
isGatewayWorkAdmissionClosed,
18+
runWithGatewayIndependentRootWorkAdmission,
19+
} from "../process/gateway-work-admission.js";
1620
import { startSessionUpstreamMonitor } from "../sessions/session-upstream-monitor.js";
1721
import type { GatewayCronReconciliation } from "./server-cron-reconciled.js";
1822
import type { GatewayCronState } from "./server-cron.js";
@@ -181,19 +185,58 @@ export function scheduleGatewayPostReadyMaintenance(params: {
181185
function recoverPendingOutboundDeliveries(params: {
182186
cfg: OpenClawConfig;
183187
log: GatewayRuntimeServiceLogger;
184-
}): void {
185-
// Recovery is best-effort background work; startup must continue even if outbound modules fail
186-
// to import or queued delivery replay fails.
187-
void runWithGatewayIndependentRootWorkAdmission(async () => {
188-
const { recoverPendingDeliveries } = await import("../infra/outbound/delivery-queue.js");
189-
const { deliverOutboundPayloadsInternal } = await import("../infra/outbound/deliver.js");
190-
const logRecovery = params.log.child("delivery-recovery");
191-
await recoverPendingDeliveries({
192-
deliver: deliverOutboundPayloadsInternal,
193-
log: logRecovery,
194-
cfg: params.cfg,
195-
});
196-
}).catch((err: unknown) => params.log.error(`Delivery recovery failed: ${String(err)}`));
188+
}): () => void {
189+
let stopped = false;
190+
let recoveryInFlight = false;
191+
let logRecovery: ReturnType<GatewayRuntimeServiceLogger["child"]> | undefined;
192+
193+
const recover = (startup: boolean): void => {
194+
if (stopped || recoveryInFlight || isGatewayWorkAdmissionClosed()) {
195+
return;
196+
}
197+
recoveryInFlight = true;
198+
void runWithGatewayIndependentRootWorkAdmission(async () => {
199+
const { drainPendingDeliveries, recoverPendingDeliveries } =
200+
await import("../infra/outbound/delivery-queue.js");
201+
const { deliverOutboundPayloadsInternal } = await import("../infra/outbound/deliver.js");
202+
if (stopped) {
203+
return;
204+
}
205+
logRecovery ??= params.log.child("delivery-recovery");
206+
if (startup) {
207+
await recoverPendingDeliveries({
208+
deliver: deliverOutboundPayloadsInternal,
209+
log: logRecovery,
210+
cfg: params.cfg,
211+
});
212+
return;
213+
}
214+
// Startup migration runs once. Normal retries use fresh config so revoked
215+
// accounts cannot inherit the authority captured at gateway startup.
216+
await drainPendingDeliveries({
217+
drainKey: "gateway:outbound",
218+
logLabel: "Outbound delivery retry",
219+
cfg: getRuntimeConfig(),
220+
log: logRecovery,
221+
deliver: deliverOutboundPayloadsInternal,
222+
selectEntry: () => ({ match: true, bypassBackoff: false }),
223+
});
224+
})
225+
.catch((err: unknown) => params.log.error(`Delivery recovery failed: ${String(err)}`))
226+
.finally(() => {
227+
recoveryInFlight = false;
228+
});
229+
};
230+
231+
// Match the queue's first backoff window without holding admission between
232+
// ticks; otherwise suspended/restarting gateways retain invisible work.
233+
const retryTimer = setInterval(() => recover(false), computeBackoffMs(1));
234+
retryTimer.unref?.();
235+
recover(true);
236+
return () => {
237+
stopped = true;
238+
clearInterval(retryTimer);
239+
};
197240
}
198241

199242
function startPendingSessionDeliveryRuntime(params: {
@@ -291,14 +334,6 @@ export function activateGatewayScheduledServices(params: {
291334
log: params.log,
292335
maxEnqueuedAt: params.sessionDeliveryRecoveryMaxEnqueuedAt,
293336
});
294-
const heartbeatRunnerWithUpstreamMonitor: HeartbeatRunner = {
295-
updateConfig: heartbeatRunner.updateConfig,
296-
stop: () => {
297-
stopSessionDeliveryRuntime();
298-
sessionUpstreamMonitor.stop();
299-
heartbeatRunner.stop();
300-
},
301-
};
302337
if (params.startCron !== false) {
303338
startGatewayCronWithLogging({
304339
cronState: params.cronState,
@@ -308,11 +343,19 @@ export function activateGatewayScheduledServices(params: {
308343
logCron: params.logCron,
309344
});
310345
}
311-
recoverPendingOutboundDeliveries({
346+
const stopOutboundDeliveryRecovery = recoverPendingOutboundDeliveries({
312347
cfg: params.cfgAtStart,
313348
log: params.log,
314349
});
315350
return {
316-
heartbeatRunner: heartbeatRunnerWithUpstreamMonitor,
351+
heartbeatRunner: {
352+
updateConfig: heartbeatRunner.updateConfig,
353+
stop: () => {
354+
stopOutboundDeliveryRecovery();
355+
stopSessionDeliveryRuntime();
356+
sessionUpstreamMonitor.stop();
357+
heartbeatRunner.stop();
358+
},
359+
},
317360
};
318361
}

0 commit comments

Comments
 (0)