Skip to content

Commit 38d9638

Browse files
author
Peter Steinberger
committed
fix(agents): unblock channel turns after restart recovery
1 parent fcf2e7a commit 38d9638

7 files changed

Lines changed: 183 additions & 42 deletions

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

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -102,8 +102,15 @@ export function projectMainSessionRecoveryLifecycle(params: {
102102
lifecycleGeneration &&
103103
runs?.some((run) => run.runId === runId && run.lifecycleGeneration === lifecycleGeneration),
104104
);
105+
// The current owner retires stale generations of its own run id. An older
106+
// delayed event consumes only its matching fence and cannot settle its replacement.
105107
const remaining = matchesFence
106-
? runs?.filter((run) => run.runId !== runId || run.lifecycleGeneration !== lifecycleGeneration)
108+
? runs?.filter(
109+
(run) =>
110+
run.runId !== runId ||
111+
(lifecycleGeneration !== params.currentLifecycleGeneration &&
112+
run.lifecycleGeneration !== lifecycleGeneration),
113+
)
107114
: runs;
108115
if (settlesRecovery) {
109116
const foregroundClaims = params.entry?.mainRestartRecovery?.foregroundClaims;
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
import { describe, expect, it } from "vitest";
2+
import type { InternalSessionEntry as SessionEntry } from "../config/sessions.js";
3+
import { projectMainSessionRecoveryLifecycle } from "./main-session-recovery-lifecycle.js";
4+
5+
function recoveryEntry(params?: { hasCurrentOwner?: boolean }): SessionEntry {
6+
return {
7+
sessionId: "session-1",
8+
updatedAt: 100,
9+
status: "running",
10+
abortedLastRun: false,
11+
restartRecoveryRuns: [
12+
{ runId: "recovery", lifecycleGeneration: "generation-old" },
13+
{ runId: "recovery", lifecycleGeneration: "generation-current" },
14+
],
15+
mainRestartRecovery: {
16+
cycleId: "cycle-1",
17+
revision: 5,
18+
chargedAttempts: 2,
19+
...(params?.hasCurrentOwner
20+
? {
21+
foregroundClaims: {
22+
lifecycleGeneration: "generation-current",
23+
tokens: ["current-owner"],
24+
},
25+
}
26+
: {}),
27+
},
28+
};
29+
}
30+
31+
describe("main-session recovery run ownership", () => {
32+
it("settles a resumed run once when older generations retain the same run id", () => {
33+
expect(
34+
projectMainSessionRecoveryLifecycle({
35+
currentLifecycleGeneration: "generation-current",
36+
entry: recoveryEntry(),
37+
event: {
38+
runId: "recovery",
39+
lifecycleGeneration: "generation-current",
40+
data: { phase: "end" },
41+
},
42+
snapshotPatch: { status: "done", abortedLastRun: false },
43+
}),
44+
).toEqual({
45+
action: "apply",
46+
patch: {
47+
status: "done",
48+
abortedLastRun: false,
49+
restartRecoveryRuns: undefined,
50+
mainRestartRecovery: undefined,
51+
},
52+
});
53+
});
54+
55+
it("does not let an older same-id terminal settle its replacement generation", () => {
56+
expect(
57+
projectMainSessionRecoveryLifecycle({
58+
currentLifecycleGeneration: "generation-current",
59+
entry: recoveryEntry({ hasCurrentOwner: true }),
60+
event: {
61+
runId: "recovery",
62+
lifecycleGeneration: "generation-old",
63+
data: { phase: "end" },
64+
},
65+
snapshotPatch: { status: "done", abortedLastRun: false },
66+
}),
67+
).toEqual({
68+
action: "apply",
69+
patch: {
70+
restartRecoveryRuns: [{ runId: "recovery", lifecycleGeneration: "generation-current" }],
71+
restartRecoveryTerminalRunIds: ["recovery"],
72+
},
73+
});
74+
});
75+
});

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,7 @@ describe("main session recovery state", () => {
9292
expect(entry).toEqual(before);
9393
});
9494

95-
it("marks without charging and preserves generation-scoped lifecycle fences", () => {
95+
it("marks without charging and replaces an older lifecycle owner for the same run", () => {
9696
const entry = interruptedEntry({
9797
restartRecoveryRuns: [
9898
{ runId: "older-run", lifecycleGeneration: "generation-old" },
@@ -123,7 +123,6 @@ describe("main session recovery state", () => {
123123
expect(entry.restartRecoveryRuns).toEqual([
124124
{ runId: "new-run", lifecycleGeneration: "generation-2" },
125125
{ runId: "older-run", lifecycleGeneration: "generation-old" },
126-
{ runId: "shared-run", lifecycleGeneration: "generation-1" },
127126
{ runId: "shared-run", lifecycleGeneration: "generation-2" },
128127
]);
129128
});
@@ -422,6 +421,7 @@ describe("main session recovery state", () => {
422421
pendingFinalDelivery: { kind: "replayable", text: " captured reply ", createdAt: 1 },
423422
restartRecoveryDeliveryRunId: "recovery-1",
424423
restartRecoveryDeliverySourceRunId: "source-1",
424+
restartRecoveryRuns: [{ runId: "recovery-1", lifecycleGeneration: "generation-old" }],
425425
mainRestartRecovery: recoveryState({
426426
revision: 2,
427427
chargedAttempts: 1,

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

Lines changed: 18 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -102,20 +102,28 @@ function validateRecoveryAdmission(
102102
return hasCurrentForegroundClaim(state, command.lifecycleGeneration) ? "foreground_active" : null;
103103
}
104104

105-
function recordLifecycleFence(entry: SessionEntry, run: RestartRecoveryRun): void {
106-
// Lifecycle fences can overlap and are consumed independently by their matching events.
107-
const runs = new Map<string, RestartRecoveryRun>();
108-
for (const existing of entry.restartRecoveryRuns ?? []) {
109-
runs.set(`${existing.runId}\u0000${existing.lifecycleGeneration}`, existing);
105+
/** Keeps distinct concurrent runs while transferring each run id to its newest lifecycle owner. */
106+
export function normalizeMainSessionRecoveryRunFences(
107+
runs: Iterable<RestartRecoveryRun>,
108+
): RestartRecoveryRun[] {
109+
const ownersByRunId = new Map<string, RestartRecoveryRun>();
110+
for (const run of runs) {
111+
ownersByRunId.set(run.runId, run);
110112
}
111-
runs.set(`${run.runId}\u0000${run.lifecycleGeneration}`, run);
112-
entry.restartRecoveryRuns = [...runs.values()].toSorted((a, b) =>
113-
a.runId === b.runId
114-
? a.lifecycleGeneration.localeCompare(b.lifecycleGeneration)
115-
: a.runId.localeCompare(b.runId),
113+
return [...ownersByRunId.values()].toSorted((left, right) =>
114+
left.runId.localeCompare(right.runId),
116115
);
117116
}
118117

118+
function recordLifecycleFence(entry: SessionEntry, run: RestartRecoveryRun): void {
119+
// A resumed run keeps its id across Gateway generations. Leaving its old fence
120+
// behind makes terminal settlement preserve a dead owner and blocks every later turn.
121+
entry.restartRecoveryRuns = normalizeMainSessionRecoveryRunFences([
122+
...(entry.restartRecoveryRuns ?? []),
123+
run,
124+
]);
125+
}
126+
119127
function hasLifecycleFence(entry: SessionEntry, run: RestartRecoveryRun): boolean {
120128
return Boolean(
121129
entry.restartRecoveryRuns?.some(

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

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -241,6 +241,35 @@ describe("main session recovery store", () => {
241241
expect(readStore()[legacyKey]).toMatchObject({ abortedLastRun: true });
242242
});
243243

244+
it("transfers a resumed recovery run to one durable lifecycle owner", async () => {
245+
await write(
246+
interruptedEntry({
247+
restartRecoveryRuns: [{ runId: "recovery-1", lifecycleGeneration: "generation-old" }],
248+
mainRestartRecovery: {
249+
cycleId: "cycle-1",
250+
revision: 2,
251+
chargedAttempts: 1,
252+
reservation: { runId: "recovery-1", attempt: 1, lifecycleGeneration },
253+
},
254+
}),
255+
);
256+
257+
const admitted = await commitMainSessionRecovery({
258+
command: {
259+
kind: "admit_recovery",
260+
lifecycleGeneration,
261+
now: 300,
262+
runId: "recovery-1",
263+
sessionId: "session-1",
264+
},
265+
target: { sessionKey, storePath },
266+
});
267+
268+
expect(admitted.transition).toEqual({ kind: "admitted_recovery" });
269+
expect(read().restartRecoveryRuns).toEqual([{ runId: "recovery-1", lifecycleGeneration }]);
270+
expect(read().abortedLastRun).toBe(false);
271+
});
272+
244273
it("rejects an observation after the session is replaced", async () => {
245274
await write({
246275
sessionId: "session-2",

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

Lines changed: 14 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,10 @@ import {
2020
listActiveEmbeddedRunSessionIds,
2121
listActiveEmbeddedRunSessionKeys,
2222
} from "./embedded-agent-runner/run-state.js";
23-
import { transitionMainSessionRecovery } from "./main-session-recovery-state.js";
23+
import {
24+
normalizeMainSessionRecoveryRunFences,
25+
transitionMainSessionRecovery,
26+
} from "./main-session-recovery-state.js";
2427
import {
2528
hasCurrentProcessOwner,
2629
log,
@@ -189,34 +192,16 @@ export async function markRestartAbortedMainSessions(params: {
189192
continue;
190193
}
191194
const wasRunning = entry.status === "running";
192-
const recoveryRuns = new Map<string, RestartRecoveryRun>();
193-
for (const run of entry.restartRecoveryRuns ?? []) {
194-
if (run.lifecycleGeneration === currentLifecycleGeneration) {
195-
recoveryRuns.set(`${run.runId}\u0000${run.lifecycleGeneration}`, run);
196-
}
197-
}
198-
const replaceActiveRunMarker = (run: RestartRecoveryRun) => {
199-
for (const [key, existingRun] of recoveryRuns) {
200-
if (existingRun.runId === run.runId) {
201-
recoveryRuns.delete(key);
202-
}
203-
}
204-
recoveryRuns.set(`${run.runId}\u0000${run.lifecycleGeneration}`, run);
205-
};
206-
for (const run of registeredActiveRuns) {
207-
replaceActiveRunMarker(run);
208-
}
209-
for (const run of matchingActiveRuns) {
210-
replaceActiveRunMarker({
211-
runId: run.runId,
212-
lifecycleGeneration: run.lifecycleGeneration,
213-
});
214-
}
215-
entry.restartRecoveryRuns = [...recoveryRuns.values()].toSorted((a, b) =>
216-
a.runId === b.runId
217-
? a.lifecycleGeneration.localeCompare(b.lifecycleGeneration)
218-
: a.runId.localeCompare(b.runId),
219-
);
195+
entry.restartRecoveryRuns = normalizeMainSessionRecoveryRunFences([
196+
...(entry.restartRecoveryRuns ?? []).filter(
197+
(run) => run.lifecycleGeneration === currentLifecycleGeneration,
198+
),
199+
...registeredActiveRuns,
200+
...matchingActiveRuns.map(({ runId, lifecycleGeneration }) => ({
201+
runId,
202+
lifecycleGeneration,
203+
})),
204+
]);
220205
transitionMainSessionRecovery(entry, {
221206
kind: "mark_interrupted",
222207
cycleId: randomUUID(),

‎src/gateway/session-lifecycle-state.test.ts‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -397,6 +397,43 @@ describe("session lifecycle state", () => {
397397
expect(persisted.mainRestartRecovery).toBeUndefined();
398398
});
399399

400+
it("clears every generation of a resumed run when its current owner completes", async () => {
401+
const lifecycleGeneration = getAgentEventLifecycleGeneration();
402+
const persisted = await persistLifecycle(
403+
{
404+
sessionId: "session-id",
405+
updatedAt: 1_000,
406+
startedAt: 1_050,
407+
status: "running",
408+
abortedLastRun: false,
409+
restartRecoveryRuns: [
410+
{ runId: "recovery-run", lifecycleGeneration: "pre-restart" },
411+
{ runId: "recovery-run", lifecycleGeneration },
412+
],
413+
mainRestartRecovery: {
414+
cycleId: "cycle-1",
415+
revision: 5,
416+
chargedAttempts: 2,
417+
},
418+
},
419+
{
420+
ts: 2_000,
421+
sessionId: "session-id",
422+
runId: "recovery-run",
423+
lifecycleGeneration,
424+
data: { phase: "end", endedAt: 1_800 },
425+
},
426+
);
427+
428+
expect(persisted).toMatchObject({
429+
status: "done",
430+
endedAt: 1_800,
431+
abortedLastRun: false,
432+
});
433+
expect(persisted.restartRecoveryRuns).toBeUndefined();
434+
expect(persisted.mainRestartRecovery).toBeUndefined();
435+
});
436+
400437
it("does not settle a foreground owner from a stale lifecycle generation", async () => {
401438
const persisted = await persistLifecycle(
402439
{

0 commit comments

Comments
 (0)