Skip to content

Commit 880a2a6

Browse files
jchoi-atnjisubiobviyus
authored
fix(telegram): requeue aborted ingress claims (#122864)
Requeue Telegram ingress claims when their owner aborts before adoption, without spending retry attempts or misclassifying late aborts as delivery failures. During managed shutdown, drain active embedded model and tool runs before exit, with a 330-second generated systemd stop budget for the 315-second cooperative gateway drain. Co-authored-by: jisubi <[email protected]> Co-authored-by: Ayaan Zaidi <[email protected]>
1 parent ea78c24 commit 880a2a6

8 files changed

Lines changed: 94 additions & 27 deletions

File tree

‎extensions/telegram/src/telegram-ingress-drain.test.ts‎

Lines changed: 44 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -335,8 +335,8 @@ describe("createTelegramIngressMonitor", () => {
335335
expect(await queue.listPending({ limit: "all" })).toMatchObject([
336336
{
337337
id: eventId,
338-
attempts: 1,
339-
lastError: "Telegram ingress monitor is stopped.",
338+
attempts: 0,
339+
lastError: "turn-abandoned",
340340
},
341341
]),
342342
);
@@ -345,6 +345,46 @@ describe("createTelegramIngressMonitor", () => {
345345
},
346346
);
347347

348+
it("requeues an aborted deferred participant even when its late result is non-retryable", async () => {
349+
await withTempState(async (stateDir) => {
350+
const queue = createChannelIngressQueueForTests<TelegramSpooledUpdatePayload>({
351+
channelId: "telegram",
352+
accountId: "default",
353+
stateDir,
354+
});
355+
const eventId = "9".padStart(16, "0");
356+
const payload = updatePayload(9);
357+
const laneKey = telegramSpooledUpdateLaneKey(payload.update);
358+
await queue.enqueue(eventId, payload, { laneKey });
359+
const participant: { current?: TelegramSpooledReplayDeferredParticipant } = {};
360+
const monitor = createTelegramIngressMonitor({
361+
queue,
362+
cfg,
363+
accountId: "default",
364+
dispatch: async () => {
365+
participant.current =
366+
createTelegramSpooledReplayDeferredParticipant("test:aborted-non-retryable") ??
367+
undefined;
368+
},
369+
});
370+
371+
monitor.start();
372+
await vi.waitFor(() => expect(participant.current).toBeDefined());
373+
await monitor.stop();
374+
participant.current?.settle({
375+
kind: "failed-retryable",
376+
error: new TelegramIngressPayloadError("late invalid payload"),
377+
});
378+
379+
await vi.waitFor(async () =>
380+
expect(await queue.listPending({ limit: "all" })).toMatchObject([
381+
{ id: eventId, attempts: 0, lastError: "turn-abandoned" },
382+
]),
383+
);
384+
expect(await queue.listFailed?.({ limit: "all" })).toEqual([]);
385+
});
386+
});
387+
348388
it("releases when dispatch settles only after its owner was aborted", async () => {
349389
await withTempState(async (stateDir) => {
350390
const queue = createChannelIngressQueueForTests<TelegramSpooledUpdatePayload>({
@@ -386,8 +426,8 @@ describe("createTelegramIngressMonitor", () => {
386426
expect(await queue.listPending({ limit: "all" })).toMatchObject([
387427
{
388428
id: eventId,
389-
attempts: 1,
390-
lastError: "Telegram ingress monitor is stopped.",
429+
attempts: 0,
430+
lastError: "turn-abandoned",
391431
},
392432
]),
393433
);

‎extensions/telegram/src/telegram-ingress-drain.ts‎

Lines changed: 24 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -378,6 +378,20 @@ export function createTelegramIngressMonitor(params: CreateTelegramIngressMonito
378378
const removeAbortListener = () => {
379379
telegramLifecycle.abortSignal.removeEventListener("abort", onAbort);
380380
};
381+
const settleAfterOwnerAbort = async (error?: unknown) => {
382+
// A lost owner did not finish a delivery attempt. Preserve only the
383+
// rollback failure for which replay is unsafe after a dispatch key
384+
// committed but could not be removed.
385+
if (
386+
error !== undefined &&
387+
resolveTelegramIngressNonRetryableFailure(error)?.reason ===
388+
"dispatch-dedupe-rollback-failed"
389+
) {
390+
await telegramLifecycle.onFailed(error);
391+
return;
392+
}
393+
await telegramLifecycle.onAbandoned();
394+
};
381395
// Two-arg then: the rejection arm must observe only a participant.task
382396
// rejection. Chaining it as .catch would also swallow onFailed/onAdopted
383397
// settlement errors and re-drive them through onFailed with an
@@ -387,22 +401,24 @@ export function createTelegramIngressMonitor(params: CreateTelegramIngressMonito
387401
.then(
388402
async (terminal) => {
389403
removeAbortListener();
390-
if (terminal.kind === "failed-retryable") {
391-
await telegramLifecycle.onFailed(terminal.error);
392-
return;
393-
}
394404
if (abortedWhilePending) {
395-
await telegramLifecycle.onFailed(
396-
telegramLifecycle.abortSignal.reason instanceof Error
397-
? telegramLifecycle.abortSignal.reason
398-
: new Error("ingress-aborted"),
405+
await settleAfterOwnerAbort(
406+
terminal.kind === "failed-retryable" ? terminal.error : undefined,
399407
);
400408
return;
401409
}
410+
if (terminal.kind === "failed-retryable") {
411+
await telegramLifecycle.onFailed(terminal.error);
412+
return;
413+
}
402414
await lifecycle.onAdopted();
403415
},
404416
async (error: unknown) => {
405417
removeAbortListener();
418+
if (abortedWhilePending) {
419+
await settleAfterOwnerAbort(error);
420+
return;
421+
}
406422
await telegramLifecycle.onFailed(
407423
error instanceof Error ? error : new Error(String(error)),
408424
);

‎src/channels/message/ingress-drain.test.ts‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -157,13 +157,13 @@ describe("channel ingress drain", () => {
157157
expect(await queue.listClaims()).toHaveLength(1);
158158
expect(await queue.listPending()).toEqual([]);
159159

160-
// Abandon releases for retry (attempts increment).
160+
// Abandon loses ownership before delivery; replay must not spend an attempt.
161161
await expectDefined(capturedLifecycles[0], "deferred lifecycle").onAbandoned();
162162
await drain.waitForIdle();
163163
await vi.waitFor(async () => {
164164
const pending = await queue.listPending();
165165
expect(pending).toHaveLength(1);
166-
expect(pending[0]?.attempts).toBeGreaterThanOrEqual(1);
166+
expect(pending[0]?.attempts).toBe(0);
167167
});
168168
drain.dispose();
169169
});
@@ -461,7 +461,7 @@ describe("channel ingress drain", () => {
461461
});
462462
});
463463

464-
it("abandoned reply ownership releases claim with attempt increment", async () => {
464+
it("abandoned via turnAdoptionLifecycle releases claim without an attempt", async () => {
465465
await withTempState(async (stateDir) => {
466466
const queue = createTestIngressQueue(stateDir);
467467
await queue.enqueue("evt-q", { text: "x" }, { laneKey: "l1" });
@@ -481,6 +481,7 @@ describe("channel ingress drain", () => {
481481
await vi.waitFor(async () => {
482482
const pending = await queue.listPending();
483483
expect(pending).toHaveLength(1);
484+
expect(pending[0]?.attempts).toBe(0);
484485
expect(pending[0]?.lastError).toBe("turn-abandoned");
485486
});
486487
drain.dispose();
@@ -679,7 +680,7 @@ describe("channel ingress drain", () => {
679680
});
680681
});
681682

682-
it("keeps retry-accounted abandonment pending beyond the failure threshold", async () => {
683+
it("does not spend retry attempts on repeated abandonment", async () => {
683684
await withTempState(async (stateDir) => {
684685
let clock = 1;
685686
const queue = createTestIngressQueue(stateDir, { now: () => clock });
@@ -704,7 +705,7 @@ describe("channel ingress drain", () => {
704705
expect(await queue.listPending()).toEqual([
705706
expect.objectContaining({
706707
id: "abandoned",
707-
attempts: 3,
708+
attempts: 0,
708709
lastError: "turn-abandoned",
709710
}),
710711
]);

‎src/channels/message/ingress-drain.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -507,7 +507,10 @@ export function createChannelIngressDrain<
507507
await releaseUnadopted(state, { recordAttempt: false });
508508
},
509509
onAbandoned: async () => {
510-
await releaseUnadopted(state, { lastError: "turn-abandoned" });
510+
await releaseUnadopted(state, {
511+
lastError: "turn-abandoned",
512+
recordAttempt: false,
513+
});
511514
},
512515
};
513516
};

‎src/cli/gateway-cli/run-loop.test.ts‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -776,7 +776,7 @@ describe("runGatewayLoop", () => {
776776
);
777777

778778
expect(gatewayWorkAdmissionActual.isGatewayWorkAdmissionClosed()).toBe(true);
779-
expect(waitForGatewayActiveWork).toHaveBeenCalledWith(15_000, undefined);
779+
expect(waitForGatewayActiveWork).toHaveBeenCalledWith(315_000, undefined);
780780
expect(close).not.toHaveBeenCalled();
781781
expect(runtime.exit).not.toHaveBeenCalled();
782782

@@ -811,7 +811,7 @@ describe("runGatewayLoop", () => {
811811
captureSignal("SIGTERM")();
812812

813813
await expect(exited).resolves.toBe(0);
814-
expect(waitForGatewayActiveWork).toHaveBeenCalledWith(15_000, undefined);
814+
expect(waitForGatewayActiveWork).toHaveBeenCalledWith(315_000, undefined);
815815
expect(gatewayLog.warn).toHaveBeenCalledWith(
816816
"gateway active-work drain timeout reached; proceeding with shutdown: 2 active embedded run(s)",
817817
);
@@ -833,7 +833,7 @@ describe("runGatewayLoop", () => {
833833
captureSignal("SIGTERM")();
834834

835835
await expect(exited).resolves.toBe(0);
836-
expect(waitForGatewayActiveWork).toHaveBeenCalledWith(15_000, undefined);
836+
expect(waitForGatewayActiveWork).toHaveBeenCalledWith(315_000, undefined);
837837
expect(gatewayLog.warn).toHaveBeenCalledWith(
838838
"gateway active-work drain failed; proceeding with shutdown: active-work drain unavailable",
839839
);
@@ -1023,7 +1023,7 @@ describe("runGatewayLoop", () => {
10231023
setImmediate(resolve);
10241024
});
10251025

1026-
expectRestartCloseCall(close, 15_000);
1026+
expectRestartCloseCall(close, 315_000);
10271027
expect(start).toHaveBeenCalledTimes(2);
10281028

10291029
sigint();
@@ -1067,7 +1067,7 @@ describe("runGatewayLoop", () => {
10671067
await vi.waitFor(() => expect(start).toHaveBeenCalledTimes(2));
10681068

10691069
expect(waitForGatewayActiveWork).toHaveBeenCalledWith(undefined, expect.any(Object));
1070-
expectRestartCloseCall(close, 15_000);
1070+
expectRestartCloseCall(close, 315_000);
10711071

10721072
sigint();
10731073
await expect(exited).resolves.toBe(0);
@@ -1498,7 +1498,7 @@ describe("runGatewayLoop", () => {
14981498
expect(gatewayWorkAdmissionActual.isGatewayWorkAdmissionClosed()).toBe(true);
14991499
expect(runtime.exit).not.toHaveBeenCalled();
15001500

1501-
await vi.advanceTimersByTimeAsync(24_999);
1501+
await vi.advanceTimersByTimeAsync(324_999);
15021502
expect(runtime.exit).not.toHaveBeenCalled();
15031503
await vi.advanceTimersByTimeAsync(1);
15041504

‎src/cli/gateway-cli/run-loop.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -474,7 +474,11 @@ export async function runGatewayLoop(params: {
474474
}
475475
return reacquireAndResumeInProcessRestart();
476476
};
477-
const SUPERVISOR_STOP_TIMEOUT_MS = 30_000;
477+
// The managed unit grants this same budget to a graceful SIGTERM. A plain
478+
// supervisor restart does not carry a gateway restart intent, but it can
479+
// still interrupt an embedded model/tool turn; leave enough time for that
480+
// turn to settle before systemd resorts to SIGKILL.
481+
const SUPERVISOR_STOP_TIMEOUT_MS = 330_000;
478482
const SHUTDOWN_TIMEOUT_MS = SUPERVISOR_STOP_TIMEOUT_MS - 5_000;
479483
const clearPendingStartupForceExitTimer = () => {
480484
clearTimeout(pendingStartupForceExitTimer ?? undefined);

‎src/daemon/systemd-unit.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ describe("buildSystemdUnit", () => {
5858
environment: {},
5959
});
6060
expect(unit).toContain("KillMode=control-group");
61-
expect(unit).toContain("TimeoutStopSec=30");
61+
expect(unit).toContain("TimeoutStopSec=330");
6262
expect(unit).toContain("TimeoutStartSec=30");
6363
expect(unit).toContain("SuccessExitStatus=0 143");
6464
expect(unit).toContain("OOMPolicy=continue");

‎src/daemon/systemd-unit.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,10 @@ export function buildSystemdUnit({
8181
"Restart=always",
8282
"RestartSec=5",
8383
"RestartPreventExitStatus=78",
84-
"TimeoutStopSec=30",
84+
// Must cover the gateway's SIGTERM drain budget (five minutes) plus its
85+
// teardown reserve. Otherwise systemd kills the embedded model/tool
86+
// process before the gateway can finish the cooperative drain.
87+
"TimeoutStopSec=330",
8588
"TimeoutStartSec=30",
8689
"SuccessExitStatus=0 143",
8790
// Transient child processes may be selected by the OOM killer before the

0 commit comments

Comments
 (0)