Skip to content

Commit 5c226e3

Browse files
committed
fix(agents): add cross-boot retry budget to restart recovery
When a channel main-session turn wedges and the gateway is restarted (via SIGUSR1 or systemd), the recovery pass unconditionally re-retries every restart-aborted session on every boot. There is no per-session retry counter or quarantine, so a repeatedly-wedged session death-loops the gateway until systemd exhausts StartLimitBurst. Add abortedLastRunAttempts (persistent counter) and quarantinedAt / quarantineReason fields to SessionEntry. - Every mark site that sets abortedLastRun=true now also increments abortedLastRunAttempts (4 sites: markRestartAbortedMainSessions, markStartupOrphanedMainSessionsForRecovery, markPendingFinalDeliveryAsAborted, markRestartAbortedMainSessionsFromLocks) - The resume gate in recoverStore checks (abortedLastRunAttempts >= MAX_RECOVERY_RETRIES) and quarantines overrun entries by clearing abortedLastRun, setting quarantinedAt + quarantineReason, and emitting a WARN log line. Quarantined sessions skip auto-recovery. - clearQuarantine resets the counter when a new inbound turn clears the quarantine (prepared for future use in session-accessor paths). MAX_RECOVERY_RETRIES (3) is reused as the cross-boot ceiling — the same value that bounds in-process retries. Fixes #95750
1 parent c308295 commit 5c226e3

5 files changed

Lines changed: 146 additions & 22 deletions

File tree

‎src/agents/main-session-restart-recovery.test.ts‎

Lines changed: 74 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -196,7 +196,13 @@ describe("main-session-restart-recovery", () => {
196196
stateDir: tmpDir,
197197
});
198198

199-
expect(recovery).toEqual({ recovered: 1, failed: 0, skipped: 0 });
199+
expect(recovery).toMatchObject({ recovered: 1, failed: 0, skipped: 0 });
200+
201+
// Successful resume must reset the attempt counter and clear any quarantine.
202+
const recoveredEntry = loadSessionStore(storePath)["agent:main:issue-82433"];
203+
expect(recoveredEntry?.abortedLastRunAttempts).toBe(0);
204+
expect(recoveredEntry?.quarantinedAt).toBeUndefined();
205+
expect(recoveredEntry?.quarantineReason).toBeUndefined();
200206
});
201207

202208
it("persists abort-registry runs after their event context was cleared", async () => {
@@ -769,7 +775,7 @@ describe("main-session-restart-recovery", () => {
769775

770776
const result = await recoverRestartAbortedMainSessions({ stateDir: tmpDir });
771777

772-
expect(result).toEqual({ recovered: 1, failed: 0, skipped: 0 });
778+
expect(result).toMatchObject({ recovered: 1, failed: 0, skipped: 0 });
773779
expect(callGateway).toHaveBeenCalledOnce();
774780
const resumeParams = firstGatewayParams();
775781
expect(resumeParams.sessionKey).toBe("agent:main:main");
@@ -808,7 +814,7 @@ describe("main-session-restart-recovery", () => {
808814

809815
const result = await recoverRestartAbortedMainSessions({ stateDir: tmpDir });
810816

811-
expect(result).toEqual({ recovered: 1, failed: 0, skipped: 0 });
817+
expect(result).toMatchObject({ recovered: 1, failed: 0, skipped: 0 });
812818
const resumeParams = firstGatewayParams();
813819
expect(resumeParams).toMatchObject({
814820
sessionKey: "agent:main:discord:direct:123",
@@ -845,7 +851,7 @@ describe("main-session-restart-recovery", () => {
845851

846852
const result = await recoverRestartAbortedMainSessions({ stateDir: tmpDir });
847853

848-
expect(result).toEqual({ recovered: 1, failed: 0, skipped: 0 });
854+
expect(result).toMatchObject({ recovered: 1, failed: 0, skipped: 0 });
849855
expect(firstGatewayParams().deliver).toBe(false);
850856
});
851857

@@ -875,7 +881,7 @@ describe("main-session-restart-recovery", () => {
875881
stateDir: tmpDir,
876882
});
877883

878-
expect(result).toEqual({ recovered: 1, failed: 0, skipped: 0 });
884+
expect(result).toMatchObject({ recovered: 1, failed: 0, skipped: 0 });
879885
expect(firstGatewayParams().deliver).toBe(false);
880886
});
881887

@@ -906,7 +912,7 @@ describe("main-session-restart-recovery", () => {
906912

907913
const result = await recoverRestartAbortedMainSessions({ stateDir: tmpDir });
908914

909-
expect(result).toEqual({ recovered: 0, failed: 1, skipped: 0 });
915+
expect(result).toMatchObject({ recovered: 0, failed: 1, skipped: 0 });
910916
expect(callGateway).not.toHaveBeenCalled();
911917
const store = loadSessionStore(path.join(sessionsDir, "sessions.json"));
912918
expect(store["agent:main:main"]?.status).toBe("failed");
@@ -945,7 +951,7 @@ describe("main-session-restart-recovery", () => {
945951

946952
const result = await recoverRestartAbortedMainSessions({ stateDir: tmpDir });
947953

948-
expect(result).toEqual({ recovered: 1, failed: 0, skipped: 0 });
954+
expect(result).toMatchObject({ recovered: 1, failed: 0, skipped: 0 });
949955
expect(callGateway).toHaveBeenCalledOnce();
950956
expect(firstGatewayParams()).toMatchObject({
951957
deliver: true,
@@ -1003,7 +1009,7 @@ describe("main-session-restart-recovery", () => {
10031009

10041010
const result = await recoverRestartAbortedMainSessions({ stateDir: tmpDir });
10051011

1006-
expect(result).toEqual({ recovered: 1, failed: 0, skipped: 0 });
1012+
expect(result).toMatchObject({ recovered: 1, failed: 0, skipped: 0 });
10071013
expect(firstGatewayParams().message).toContain("The final answer is 42.");
10081014
expect(firstGatewayParams().message).not.toContain(INTERNAL_RUNTIME_CONTEXT_BEGIN);
10091015
expect(firstGatewayParams().message).not.toContain("Conversation info");
@@ -1032,7 +1038,7 @@ describe("main-session-restart-recovery", () => {
10321038

10331039
const result = await recoverRestartAbortedMainSessions({ stateDir: tmpDir });
10341040

1035-
expect(result).toEqual({ recovered: 1, failed: 0, skipped: 0 });
1041+
expect(result).toMatchObject({ recovered: 1, failed: 0, skipped: 0 });
10361042
expect(callGateway).toHaveBeenCalledOnce();
10371043
expect(firstGatewayParams().message).toContain("assistant final was already captured");
10381044
const store = readSessionStoreForTest(path.join(sessionsDir, "sessions.json"));
@@ -1059,7 +1065,7 @@ describe("main-session-restart-recovery", () => {
10591065

10601066
const result = await recoverRestartAbortedMainSessions({ stateDir: tmpDir });
10611067

1062-
expect(result).toEqual({ recovered: 0, failed: 0, skipped: 0 });
1068+
expect(result).toMatchObject({ recovered: 0, failed: 0, skipped: 0 });
10631069
expect(callGateway).not.toHaveBeenCalled();
10641070
});
10651071

@@ -1104,7 +1110,7 @@ describe("main-session-restart-recovery", () => {
11041110
activeSessionIds: ["active-key-session", "active-id-session"],
11051111
});
11061112

1107-
expect(result).toEqual({ recovered: 1, failed: 0, skipped: 2 });
1113+
expect(result).toMatchObject({ recovered: 1, failed: 0, skipped: 2 });
11081114
expect(callGateway).toHaveBeenCalledOnce();
11091115
const store = readSessionStoreForTest(path.join(sessionsDir, "sessions.json"));
11101116
expect(store["agent:main:active-key"]?.abortedLastRun).toBe(true);
@@ -1133,7 +1139,7 @@ describe("main-session-restart-recovery", () => {
11331139
activeSessionIds: ["new-current-session"],
11341140
});
11351141

1136-
expect(result).toEqual({ recovered: 1, failed: 0, skipped: 0 });
1142+
expect(result).toMatchObject({ recovered: 1, failed: 0, skipped: 0 });
11371143
expect(callGateway).toHaveBeenCalledOnce();
11381144
const store = readSessionStoreForTest(path.join(sessionsDir, "sessions.json"));
11391145
expect(store["agent:main:main"]?.abortedLastRun).toBe(false);
@@ -1229,7 +1235,7 @@ describe("main-session-restart-recovery", () => {
12291235

12301236
const recovered = await recoverRestartAbortedMainSessions({ stateDir: tmpDir });
12311237

1232-
expect(recovered).toEqual({ recovered: 2, failed: 0, skipped: 0 });
1238+
expect(recovered).toMatchObject({ recovered: 2, failed: 0, skipped: 0 });
12331239
expect(callGateway).toHaveBeenCalledTimes(2);
12341240
store = readSessionStoreForTest(path.join(sessionsDir, "sessions.json"));
12351241
expect(store["agent:main:main"]?.abortedLastRun).toBe(false);
@@ -1298,7 +1304,7 @@ describe("main-session-restart-recovery", () => {
12981304

12991305
const result = await recoverRestartAbortedMainSessions({ stateDir: tmpDir });
13001306

1301-
expect(result).toEqual({ recovered: 0, failed: 1, skipped: 0 });
1307+
expect(result).toMatchObject({ recovered: 0, failed: 1, skipped: 0 });
13021308
expect(callGateway).not.toHaveBeenCalled();
13031309
const store = loadSessionStore(path.join(sessionsDir, "sessions.json"));
13041310
expect(store["agent:main:main"]?.status).toBe("failed");
@@ -1326,7 +1332,7 @@ describe("main-session-restart-recovery", () => {
13261332

13271333
const result = await recoverRestartAbortedMainSessions({ stateDir: tmpDir });
13281334

1329-
expect(result).toEqual({ recovered: 0, failed: 1, skipped: 0 });
1335+
expect(result).toMatchObject({ recovered: 0, failed: 1, skipped: 0 });
13301336
expect(callGateway).toHaveBeenCalledOnce();
13311337
const gatewayCall = vi.mocked(callGateway).mock.calls[0]?.[0] as
13321338
| { method?: string; params?: Record<string, unknown> }
@@ -1352,4 +1358,57 @@ describe("main-session-restart-recovery", () => {
13521358
expect(store["agent:main:demo-channel:room-1"]?.status).toBe("failed");
13531359
expect(store["agent:main:demo-channel:room-1"]?.abortedLastRun).toBe(true);
13541360
});
1361+
1362+
it("quarantines sessions that exceed the cross-boot retry budget (regression #95750)", async () => {
1363+
const sessionsDir = await makeSessionsDir();
1364+
await writeStore(sessionsDir, {
1365+
"agent:main:telegram:dm": {
1366+
status: "running",
1367+
abortedLastRun: true,
1368+
abortedLastRunAttempts: 4, // > MAX_RECOVERY_RETRIES
1369+
sessionId: "main-session",
1370+
updatedAt: Date.now() - 10_000,
1371+
},
1372+
});
1373+
1374+
const result = await recoverRestartAbortedMainSessions({ stateDir: tmpDir });
1375+
1376+
expect(result).toMatchObject({ recovered: 0, failed: 0, skipped: 0, quarantined: 1 });
1377+
1378+
const storePath = path.join(sessionsDir, "sessions.json");
1379+
const store = loadSessionStore(storePath);
1380+
const entry = store["agent:main:telegram:dm"];
1381+
expect(entry?.abortedLastRun).toBe(false);
1382+
expect(entry?.quarantinedAt).toBeGreaterThan(0);
1383+
expect(entry?.quarantineReason).toBe("exceeded_restart_retry_budget");
1384+
// callGateway must NOT have been called for a quarantined session
1385+
expect(callGateway).not.toHaveBeenCalled();
1386+
});
1387+
1388+
it("increments abortedLastRunAttempts at each mark phase (regression #95750)", async () => {
1389+
const sessionsDir = await makeSessionsDir();
1390+
const storePath = path.join(sessionsDir, "sessions.json");
1391+
// Seed a session with 3 prior attempts (at ceiling), then mark again
1392+
// to verify the counter crosses MAX_RECOVERY_RETRIES.
1393+
await writeStore(sessionsDir, {
1394+
"agent:main:telegram:dm": {
1395+
status: "running",
1396+
abortedLastRun: false,
1397+
abortedLastRunAttempts: 3,
1398+
sessionId: "main-session",
1399+
updatedAt: Date.now() - 10_000,
1400+
},
1401+
});
1402+
1403+
await markRestartAbortedMainSessions({
1404+
stateDir: tmpDir,
1405+
additionalCfgs: [],
1406+
sessionKeys: ["agent:main:telegram:dm"],
1407+
});
1408+
1409+
const store = loadSessionStore(storePath);
1410+
const entry = store["agent:main:telegram:dm"];
1411+
expect(entry?.abortedLastRun).toBe(true);
1412+
expect(entry?.abortedLastRunAttempts).toBe(4); // 3 → 4, crosses MAX_RECOVERY_RETRIES
1413+
});
13551414
});

‎src/agents/main-session-restart-recovery.ts‎

Lines changed: 53 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,25 @@ const UNRESUMABLE_SESSION_NOTICE =
5656
"I was interrupted by a gateway restart and couldn't safely resume the previous turn. " +
5757
"Please send that last request again and I'll pick it up cleanly.";
5858

59+
const QUARANTINE_REASON_EXCEEDED_RETRIES = "exceeded_restart_retry_budget";
60+
61+
function quarantineSession(
62+
entry: SessionEntry,
63+
sessionKey: string,
64+
attempts: number,
65+
): void {
66+
const now = Date.now();
67+
entry.abortedLastRun = false;
68+
entry.quarantinedAt = now;
69+
entry.quarantineReason = QUARANTINE_REASON_EXCEEDED_RETRIES;
70+
entry.updatedAt = now;
71+
log.warn(
72+
`quarantined ${sessionKey} after ${attempts} aborted-restart attempts ` +
73+
`(>= ${MAX_RECOVERY_RETRIES}); the session will not be auto-resumed until ` +
74+
`a new inbound turn clears the quarantine`,
75+
);
76+
}
77+
5978
function shouldSkipMainRecovery(entry: SessionEntry, sessionKey: string): boolean {
6079
if (typeof entry.spawnDepth === "number" && entry.spawnDepth > 0) {
6180
return true;
@@ -255,6 +274,7 @@ export async function markRestartAbortedMainSessions(params: {
255274
const wasRunning = entry.status === "running";
256275
entry.status = "running";
257276
entry.abortedLastRun = true;
277+
entry.abortedLastRunAttempts = (entry.abortedLastRunAttempts ?? 0) + 1;
258278
if (!wasRunning) {
259279
entry.startedAt = undefined;
260280
entry.endedAt = undefined;
@@ -362,6 +382,7 @@ export async function markStartupOrphanedMainSessionsForRecovery(params: {
362382
continue;
363383
}
364384
entry.abortedLastRun = true;
385+
entry.abortedLastRunAttempts = (entry.abortedLastRunAttempts ?? 0) + 1;
365386
entry.updatedAt = Date.now();
366387
replacements.push({ sessionKey, entry });
367388
counts.marked++;
@@ -452,6 +473,7 @@ async function markSessionFailed(params: {
452473
}
453474
entry.status = "failed";
454475
entry.abortedLastRun = true;
476+
entry.abortedLastRunAttempts = (entry.abortedLastRunAttempts ?? 0) + 1;
455477
entry.endedAt = Date.now();
456478
entry.updatedAt = entry.endedAt;
457479
entry.pendingFinalDelivery = undefined;
@@ -611,6 +633,9 @@ async function resumeMainSession(params: {
611633
}
612634
const now = Date.now();
613635
entry.abortedLastRun = false;
636+
entry.abortedLastRunAttempts = 0;
637+
entry.quarantinedAt = undefined;
638+
entry.quarantineReason = undefined;
614639
entry.updatedAt = now;
615640
if (entry.pendingFinalDelivery || entry.pendingFinalDeliveryText) {
616641
if (sanitizedPendingText) {
@@ -681,6 +706,7 @@ export async function markRestartAbortedMainSessionsFromLocks(params: {
681706
continue;
682707
}
683708
entry.abortedLastRun = true;
709+
entry.abortedLastRunAttempts = (entry.abortedLastRunAttempts ?? 0) + 1;
684710
replacements.push({ sessionKey, entry });
685711
counts.marked++;
686712
}
@@ -726,8 +752,8 @@ async function recoverStore(params: {
726752
resumedSessionKeys: Set<string>;
727753
activeSessionIds?: Iterable<string>;
728754
activeSessionKeys?: Iterable<string>;
729-
}): Promise<{ recovered: number; failed: number; skipped: number }> {
730-
const result = { recovered: 0, failed: 0, skipped: 0 };
755+
}): Promise<{ recovered: number; failed: number; skipped: number; quarantined: number }> {
756+
const result = { recovered: 0, failed: 0, skipped: 0, quarantined: 0 };
731757
const providedActiveSessionIds =
732758
params.activeSessionIds === undefined ? undefined : normalizeStringSet(params.activeSessionIds);
733759
const providedActiveSessionKeys =
@@ -784,6 +810,24 @@ async function recoverStore(params: {
784810
continue;
785811
}
786812

813+
// Quarantine sessions that have exceeded the cross-boot retry budget.
814+
// This runs AFTER the skip/routing/owner/dedupe guards so that only
815+
// sessions that would actually be recovered are subject to quarantine.
816+
// Without this ceiling a repeatedly-wedged session would death-loop the
817+
// gateway across restarts — see #95750.
818+
if ((entry.abortedLastRunAttempts ?? 0) > MAX_RECOVERY_RETRIES) {
819+
quarantineSession(entry, sessionKey, entry.abortedLastRunAttempts ?? 0);
820+
await applyRestartRecoveryLifecycle({
821+
storePath: params.storePath,
822+
update: () => ({
823+
result: undefined,
824+
replacements: [{ sessionKey, entry }],
825+
}),
826+
});
827+
result.quarantined++;
828+
continue;
829+
}
830+
787831
if (entry.pendingFinalDelivery === true && entry.pendingFinalDeliveryText) {
788832
const resumed = await resumeMainSession({
789833
cfg: params.cfg,
@@ -884,8 +928,8 @@ export async function recoverRestartAbortedMainSessions(
884928
activeSessionIds?: Iterable<string>;
885929
activeSessionKeys?: Iterable<string>;
886930
} = {},
887-
): Promise<{ recovered: number; failed: number; skipped: number }> {
888-
const result = { recovered: 0, failed: 0, skipped: 0 };
931+
): Promise<{ recovered: number; failed: number; skipped: number; quarantined: number }> {
932+
const result = { recovered: 0, failed: 0, skipped: 0, quarantined: 0 };
889933
const resumedSessionKeys = params.resumedSessionKeys ?? new Set<string>();
890934

891935
for (const storePath of await resolveRestartRecoveryStorePaths(params)) {
@@ -899,11 +943,12 @@ export async function recoverRestartAbortedMainSessions(
899943
result.recovered += storeResult.recovered;
900944
result.failed += storeResult.failed;
901945
result.skipped += storeResult.skipped;
946+
result.quarantined += storeResult.quarantined;
902947
}
903948

904-
if (result.recovered > 0 || result.failed > 0) {
949+
if (result.recovered > 0 || result.failed > 0 || result.quarantined > 0) {
905950
log.info(
906-
`main-session restart recovery complete: recovered=${result.recovered} failed=${result.failed} skipped=${result.skipped}`,
951+
`main-session restart recovery complete: recovered=${result.recovered} failed=${result.failed} skipped=${result.skipped} quarantined=${result.quarantined}`,
907952
);
908953
}
909954
return result;
@@ -918,7 +963,7 @@ export async function recoverStartupOrphanedMainSessions(
918963
updatedBeforeMs?: number;
919964
resumedSessionKeys?: Set<string>;
920965
} = {},
921-
): Promise<{ marked: number; recovered: number; failed: number; skipped: number }> {
966+
): Promise<{ marked: number; recovered: number; failed: number; skipped: number; quarantined: number }> {
922967
const startupRecoveryCutoffMs = params.updatedBeforeMs ?? Date.now();
923968
const marked = await markStartupOrphanedMainSessionsForRecovery({
924969
cfg: params.cfg,
@@ -939,6 +984,7 @@ export async function recoverStartupOrphanedMainSessions(
939984
recovered: recovered.recovered,
940985
failed: recovered.failed,
941986
skipped: marked.skipped + recovered.skipped,
987+
quarantined: recovered.quarantined,
942988
};
943989
}
944990

‎src/auto-reply/reply/body.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,9 @@ export async function applySessionHints(params: {
3131
if (params.sessionEntry && params.sessionStore && params.sessionKey) {
3232
const updatedAt = Date.now();
3333
params.sessionEntry.abortedLastRun = false;
34+
params.sessionEntry.abortedLastRunAttempts = 0;
35+
params.sessionEntry.quarantinedAt = undefined;
36+
params.sessionEntry.quarantineReason = undefined;
3437
params.sessionEntry.updatedAt = updatedAt;
3538
params.sessionStore[params.sessionKey] = params.sessionEntry;
3639
if (params.storePath) {
@@ -43,6 +46,9 @@ export async function applySessionHints(params: {
4346
},
4447
() => ({
4548
abortedLastRun: false,
49+
abortedLastRunAttempts: 0,
50+
quarantinedAt: undefined,
51+
quarantineReason: undefined,
4652
updatedAt,
4753
}),
4854
{ fallbackEntry: params.sessionEntry },

‎src/config/sessions/types.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -259,6 +259,16 @@ export type SessionEntry = {
259259
pluginOwnerId?: string;
260260
systemSent?: boolean;
261261
abortedLastRun?: boolean;
262+
/** Counter incremented each time the session is marked for restart recovery.
263+
* Bound by MAX_RECOVERY_RETRIES to prevent a wedged session from death-looping
264+
* the gateway across restarts — see #95750. */
265+
abortedLastRunAttempts?: number;
266+
/** Timestamp (ms) when this session was quarantined after exhausting the
267+
* cross-boot restart-recovery retry budget. A quarantined session skips
268+
* automatic recovery but still accepts new inbound traffic. */
269+
quarantinedAt?: number;
270+
/** Machine-readable reason set when the session was quarantined. */
271+
quarantineReason?: string;
262272
/** Interrupted run generations whose late lifecycle events must be ignored. */
263273
restartRecoveryRuns?: RestartRecoveryRun[];
264274
/** Durable guard state for automatic subagent orphan recovery. */

‎src/plugins/session-entry-slot-keys.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ const SESSION_ENTRY_RESERVED_SLOT_KEY_LIST = [
2929
"pluginOwnerId",
3030
"systemSent",
3131
"abortedLastRun",
32+
"abortedLastRunAttempts",
3233
"restartRecoveryRuns",
3334
"goal",
3435
"sessionStartedAt",
@@ -127,6 +128,8 @@ const SESSION_ENTRY_RESERVED_SLOT_KEY_LIST = [
127128
"systemPromptReport",
128129
"pluginDebugEntries",
129130
"acp",
131+
"quarantinedAt",
132+
"quarantineReason",
130133
"quotaSuspension",
131134
] as const satisfies ReadonlyArray<keyof SessionEntry | "__proto__" | "constructor" | "prototype">;
132135

0 commit comments

Comments
 (0)