Skip to content

Commit b7f0df0

Browse files
authored
refactor(agents): consolidate main-session recovery ownership (#117383)
* refactor(agents): consolidate main-session recovery ownership * test(agents): cover recovery owner boundaries
1 parent 685a3db commit b7f0df0

22 files changed

Lines changed: 1163 additions & 1475 deletions

‎src/agents/agent-command-recovery-owner.ts‎

Lines changed: 14 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -3,16 +3,12 @@ import type { InternalSessionEntry } from "../config/sessions.js";
33
import { formatErrorMessage } from "../infra/errors.js";
44
import { createSubsystemLogger } from "../logging/subsystem.js";
55
import type { AgentCommandOpts } from "./command/types.js";
6+
import { repairMainSessionRecoveryMutation } from "./main-session-recovery-lifecycle.js";
67
import { scheduleMainSessionRecoveryPendingTarget } from "./main-session-recovery-owner-release.js";
78
import {
8-
restoreAdmittedRecoveryWithRetries,
9-
scheduleAdmittedRecoveryRestore,
10-
} from "./main-session-recovery-restore.js";
11-
import {
12-
bindMainSessionRecoveryOwnerRun,
139
claimMainSessionRecoveryOwner,
1410
inspectMainSessionRecoveryRequired,
15-
readMainSessionRecoveryOwner,
11+
refreshMainSessionRecoveryOwner,
1612
releaseMainSessionRecoveryOwner,
1713
type MainSessionRecoveryOwnerLease,
1814
type MainSessionRecoveryPendingTarget,
@@ -85,14 +81,11 @@ async function claimAgentCommandRecoveryOwner(params: {
8581
// session resolution so rollover or rerouting cannot execute under another row's lease.
8682
throw new Error("main-session recovery owner changed during ingress preparation; retry");
8783
}
88-
if (params.opts.runId) {
89-
return await bindMainSessionRecoveryOwnerRun(transferredLease, params.opts.runId);
90-
}
91-
const snapshot = await readMainSessionRecoveryOwner(transferredLease);
84+
const snapshot = await refreshMainSessionRecoveryOwner(transferredLease, params.opts.runId);
9285
if (!snapshot) {
9386
throw new Error("main-session recovery owner changed during ingress preparation; retry");
9487
}
95-
return { ...snapshot, lease: transferredLease };
88+
return snapshot;
9689
}
9790
if (params.opts.sessionEffects === "internal") {
9891
return undefined;
@@ -167,17 +160,16 @@ export async function runWithAgentCommandRecoveryOwner<
167160
} catch (error) {
168161
// Gateway admission consumes the durable reservation before command
169162
// preparation. Restore it when preparation fails before a run exists.
170-
if (params.restoreAdmittedRecovery) {
171-
try {
172-
pendingRecovery = await restoreAdmittedRecoveryWithRetries(
173-
params.restoreAdmittedRecovery,
174-
);
175-
} catch (restoreError) {
176-
log.warn(
177-
`failed to restore admitted recovery after command preparation: ${formatErrorMessage(restoreError)}`,
178-
);
179-
scheduleAdmittedRecoveryRestore(params.restoreAdmittedRecovery);
180-
}
163+
const restoreAdmittedRecovery = params.restoreAdmittedRecovery;
164+
if (restoreAdmittedRecovery) {
165+
pendingRecovery = await repairMainSessionRecoveryMutation({
166+
mutation: restoreAdmittedRecovery,
167+
onDeferredSuccess: scheduleMainSessionRecoveryPendingTarget,
168+
onError: (restoreError) =>
169+
log.warn(
170+
`failed to restore admitted recovery after command preparation: ${formatErrorMessage(restoreError)}`,
171+
),
172+
});
181173
}
182174
throw error;
183175
}
Lines changed: 119 additions & 109 deletions
Original file line numberDiff line numberDiff line change
@@ -1,39 +1,59 @@
11
import type { InternalSessionEntry as SessionEntry } from "../config/sessions.js";
22
import { mergeRestartRecoveryTerminalRunIds } from "../config/sessions/restart-recovery-state.js";
3+
import { retryAsync } from "../infra/retry.js";
34
import {
45
buildMainSessionRecoveryClearPatch,
56
type MainRecoveryStateFields,
67
} from "./main-session-recovery-clear.js";
78

8-
const MAIN_RESTART_RECOVERY_WEDGED_FALLBACK_REASON =
9-
"main-session restart recovery is tombstoned for this session";
9+
const MAIN_SESSION_RECOVERY_RETRY_DELAY_MS = 1_000;
10+
const MAIN_SESSION_RECOVERY_RETRY_MAX_DELAY_MS = 30_000;
1011

1112
type MainRecoveryLifecycleEvent = {
1213
runId?: string;
1314
lifecycleGeneration?: string;
1415
data?: { error?: unknown; phase?: unknown; stopReason?: unknown };
1516
};
1617

17-
export function inspectMainSessionRecoveryHealth(entry: SessionEntry):
18-
| { status: "none" }
19-
| { status: "active" }
20-
| {
21-
status: "tombstoned";
22-
reason: string;
23-
repair: "clear_stale_abort" | null;
24-
} {
25-
const state = entry.mainRestartRecovery;
26-
if (!state) {
27-
return { status: "none" };
28-
}
29-
if (!state.tombstone) {
30-
return { status: "active" };
18+
export async function retryMainSessionRecoveryMutation<T>(mutation: () => Promise<T>): Promise<T> {
19+
return await retryAsync(mutation, 3, 25);
20+
}
21+
22+
/** Retries now, then leaves an exact idempotent repair queued after transient failure. */
23+
export async function repairMainSessionRecoveryMutation<T>(params: {
24+
mutation: () => Promise<T>;
25+
onDeferredSuccess: (result: T) => void | Promise<void>;
26+
onError: (error: unknown) => void;
27+
}): Promise<T | undefined> {
28+
try {
29+
return await retryMainSessionRecoveryMutation(params.mutation);
30+
} catch (error) {
31+
params.onError(error);
32+
scheduleMainSessionRecoveryMutation({
33+
mutation: () => retryMainSessionRecoveryMutation(params.mutation),
34+
onSuccess: params.onDeferredSuccess,
35+
});
36+
return undefined;
3137
}
32-
return {
33-
status: "tombstoned",
34-
reason: state.tombstone.reason.trim() || MAIN_RESTART_RECOVERY_WEDGED_FALLBACK_REASON,
35-
repair: entry.abortedLastRun === true ? "clear_stale_abort" : null,
36-
};
38+
}
39+
40+
/** Keeps an idempotent durable-state repair alive until it succeeds or restart retires it. */
41+
export function scheduleMainSessionRecoveryMutation<T>(params: {
42+
mutation: () => Promise<T>;
43+
onError?: (error: unknown) => void;
44+
onSuccess: (result: T) => void | Promise<void>;
45+
delayMs?: number;
46+
}): void {
47+
const delayMs = params.delayMs ?? MAIN_SESSION_RECOVERY_RETRY_DELAY_MS;
48+
setTimeout(() => {
49+
void params.mutation().then(params.onSuccess, (error: unknown) => {
50+
params.onError?.(error);
51+
scheduleMainSessionRecoveryMutation({
52+
...params,
53+
delayMs: Math.min(delayMs * 2, MAIN_SESSION_RECOVERY_RETRY_MAX_DELAY_MS),
54+
});
55+
});
56+
}, delayMs).unref?.();
3757
}
3858

3959
function lifecyclePhase(event: MainRecoveryLifecycleEvent): "start" | "end" | "error" | null {
@@ -61,6 +81,47 @@ export function isMainSessionRecoveryLifecycleEvent(params: {
6181
);
6282
}
6383

84+
function settleForegroundOwner(
85+
entry: MainRecoveryStateFields,
86+
runId: string,
87+
lifecycleGeneration: string,
88+
currentLifecycleGeneration: string,
89+
) {
90+
const state = entry.mainRestartRecovery;
91+
const claims = state?.foregroundClaims;
92+
const claimId =
93+
lifecycleGeneration === currentLifecycleGeneration &&
94+
claims?.lifecycleGeneration === lifecycleGeneration
95+
? claims.tokens.find((token) => claims.runIdsByClaimId?.[token] === runId)
96+
: undefined;
97+
if (!state || !claims || !claimId) {
98+
return {
99+
hasCurrentOwner:
100+
Boolean(
101+
claims?.lifecycleGeneration === currentLifecycleGeneration && claims.tokens.length,
102+
) || state?.reservation?.lifecycleGeneration === currentLifecycleGeneration,
103+
};
104+
}
105+
const tokens = claims.tokens.filter((token) => token !== claimId);
106+
const runIdsByClaimId = Object.fromEntries(
107+
Object.entries(claims.runIdsByClaimId ?? {}).filter(([token]) => token !== claimId),
108+
);
109+
const foregroundClaims = tokens.length
110+
? {
111+
lifecycleGeneration: claims.lifecycleGeneration,
112+
tokens,
113+
...(Object.keys(runIdsByClaimId).length ? { runIdsByClaimId } : {}),
114+
}
115+
: undefined;
116+
return {
117+
claimId,
118+
state: { ...state, revision: state.revision + 1, foregroundClaims },
119+
hasCurrentOwner:
120+
Boolean(foregroundClaims) ||
121+
state.reservation?.lifecycleGeneration === currentLifecycleGeneration,
122+
};
123+
}
124+
64125
export function projectMainSessionRecoveryLifecycle(params: {
65126
currentLifecycleGeneration: string;
66127
entry?:
@@ -73,19 +134,17 @@ export function projectMainSessionRecoveryLifecycle(params: {
73134
event: MainRecoveryLifecycleEvent;
74135
snapshotPatch: Partial<SessionEntry>;
75136
}): { action: "suppress" } | { action: "apply"; patch: Partial<SessionEntry> } {
137+
const apply = (patch: Partial<SessionEntry>) => ({ action: "apply" as const, patch });
76138
if (params.entry?.mainRestartRecovery?.tombstone) {
77139
// Keep the operator boundary while allowing unrelated lifecycle status to settle.
78140
return isMainSessionRecoveryLifecycleEvent(params)
79141
? { action: "suppress" }
80-
: {
81-
action: "apply",
82-
patch: {
83-
...params.snapshotPatch,
84-
abortedLastRun: params.entry.abortedLastRun,
85-
restartRecoveryRuns: params.entry.restartRecoveryRuns,
86-
mainRestartRecovery: params.entry.mainRestartRecovery,
87-
},
88-
};
142+
: apply({
143+
...params.snapshotPatch,
144+
abortedLastRun: params.entry.abortedLastRun,
145+
restartRecoveryRuns: params.entry.restartRecoveryRuns,
146+
mainRestartRecovery: params.entry.mainRestartRecovery,
147+
});
89148
}
90149
if (isMainSessionRecoveryLifecycleEvent(params)) {
91150
return { action: "suppress" };
@@ -113,8 +172,13 @@ export function projectMainSessionRecoveryLifecycle(params: {
113172
)
114173
: runs;
115174
if (settlesRecovery) {
175+
if (!matchesFence || !runId || !lifecycleGeneration) {
176+
// No terminal snapshot may settle a recovery row it cannot identify.
177+
return params.entry?.mainRestartRecovery || runs?.length
178+
? { action: "suppress" }
179+
: apply(patch);
180+
}
116181
if (
117-
matchesFence &&
118182
lifecycleGeneration !== params.currentLifecycleGeneration &&
119183
remaining?.some(
120184
(run) =>
@@ -123,88 +187,34 @@ export function projectMainSessionRecoveryLifecycle(params: {
123187
) {
124188
// Older generations share the live owner's run id. Consume only their
125189
// fence; recording that id as terminal would also tombstone its replacement.
126-
return { action: "apply", patch: { restartRecoveryRuns: remaining } };
190+
return apply({ restartRecoveryRuns: remaining });
127191
}
128-
const foregroundClaims = params.entry?.mainRestartRecovery?.foregroundClaims;
129-
const foregroundOwnerClaimId =
130-
runId &&
131-
lifecycleGeneration &&
132-
lifecycleGeneration === params.currentLifecycleGeneration &&
133-
foregroundClaims?.lifecycleGeneration === lifecycleGeneration
134-
? foregroundClaims.tokens.find(
135-
(claimId) => foregroundClaims.runIdsByClaimId?.[claimId] === runId,
136-
)
137-
: undefined;
138-
const remainingForegroundClaimIds = foregroundOwnerClaimId
139-
? foregroundClaims!.tokens.filter((claimId) => claimId !== foregroundOwnerClaimId)
140-
: foregroundClaims?.tokens;
141-
const remainingForegroundRunIds = foregroundOwnerClaimId
142-
? Object.fromEntries(
143-
Object.entries(foregroundClaims?.runIdsByClaimId ?? {}).filter(
144-
([claimId]) => claimId !== foregroundOwnerClaimId,
145-
),
146-
)
147-
: foregroundClaims?.runIdsByClaimId;
148-
const remainingForegroundClaims = remainingForegroundClaimIds?.length
149-
? {
150-
lifecycleGeneration: foregroundClaims!.lifecycleGeneration,
151-
tokens: remainingForegroundClaimIds,
152-
...(remainingForegroundRunIds && Object.keys(remainingForegroundRunIds).length > 0
153-
? { runIdsByClaimId: remainingForegroundRunIds }
154-
: {}),
155-
}
156-
: undefined;
157-
const recoveryStateAfterForegroundSettlement = foregroundOwnerClaimId
158-
? {
159-
...params.entry!.mainRestartRecovery!,
160-
revision: params.entry!.mainRestartRecovery!.revision + 1,
161-
foregroundClaims: remainingForegroundClaims,
162-
}
163-
: params.entry?.mainRestartRecovery;
164-
const hasForegroundOwners = Boolean(
165-
remainingForegroundClaims?.lifecycleGeneration === params.currentLifecycleGeneration &&
166-
remainingForegroundClaims.tokens.length,
192+
const foreground = settleForegroundOwner(
193+
params.entry ?? {},
194+
runId,
195+
lifecycleGeneration,
196+
params.currentLifecycleGeneration,
167197
);
168-
const reservation = params.entry?.mainRestartRecovery?.reservation;
169-
const hasCurrentReservation =
170-
reservation?.lifecycleGeneration === params.currentLifecycleGeneration;
171-
const hasCurrentOwner = hasForegroundOwners || hasCurrentReservation;
172-
if (!matchesFence) {
173-
// No terminal snapshot may settle a recovery row it cannot identify.
174-
return params.entry?.mainRestartRecovery || runs?.length
175-
? { action: "suppress" }
176-
: { action: "apply", patch };
177-
}
178-
if (hasCurrentOwner) {
198+
if (foreground.hasCurrentOwner) {
179199
// A terminal event may consume its own claim. Another owner still keeps
180200
// the aggregate live until that owner's terminal event or release.
181-
return {
182-
action: "apply",
183-
patch: {
184-
restartRecoveryRuns: remaining?.length ? remaining : undefined,
185-
restartRecoveryTerminalRunIds: mergeRestartRecoveryTerminalRunIds(
186-
params.entry?.restartRecoveryTerminalRunIds,
187-
[runId],
188-
),
189-
...(foregroundOwnerClaimId
190-
? { mainRestartRecovery: recoveryStateAfterForegroundSettlement }
191-
: {}),
192-
},
193-
};
201+
return apply({
202+
restartRecoveryRuns: remaining?.length ? remaining : undefined,
203+
restartRecoveryTerminalRunIds: mergeRestartRecoveryTerminalRunIds(
204+
params.entry?.restartRecoveryTerminalRunIds,
205+
[runId],
206+
),
207+
...(foreground.claimId ? { mainRestartRecovery: foreground.state } : {}),
208+
});
194209
}
195-
if (foregroundOwnerClaimId) {
210+
if (foreground.claimId) {
196211
// This exact foreground run completed while its release lease was still
197212
// active. Its terminal snapshot is authoritative and consumes the cycle.
198213
Object.assign(patch, buildMainSessionRecoveryClearPatch(params.entry));
199-
return { action: "apply", patch };
214+
return apply(patch);
200215
}
201-
if (
202-
!hasForegroundOwners &&
203-
!hasCurrentReservation &&
204-
params.entry?.abortedLastRun === true &&
205-
(remaining?.length ?? 0) > 0
206-
) {
207-
return { action: "apply", patch: { restartRecoveryRuns: remaining } };
216+
if (params.entry?.abortedLastRun === true && (remaining?.length ?? 0) > 0) {
217+
return apply({ restartRecoveryRuns: remaining });
208218
}
209219
const recoveryDeliveryRunId =
210220
typeof params.entry?.restartRecoveryDeliveryRunId === "string"
@@ -216,19 +226,19 @@ export function projectMainSessionRecoveryLifecycle(params: {
216226
patch.abortedLastRun = false;
217227
patch.restartRecoveryRuns = remaining;
218228
patch.mainRestartRecovery = params.entry?.mainRestartRecovery;
219-
return { action: "apply", patch };
229+
return apply(patch);
220230
}
221231
// An admitted recovery clears the interruption flag before it runs. With
222232
// no live owner left, that exact delivery run is the durable cleanup boundary.
223233
Object.assign(patch, buildMainSessionRecoveryClearPatch(params.entry));
224-
return { action: "apply", patch };
234+
return apply(patch);
225235
}
226236
if (phase === "start" || !matchesFence || !remaining) {
227-
return { action: "apply", patch };
237+
return apply(patch);
228238
}
229239
if (params.entry?.abortedLastRun === true && remaining.length > 0) {
230-
return { action: "apply", patch: { restartRecoveryRuns: remaining } };
240+
return apply({ restartRecoveryRuns: remaining });
231241
}
232242
patch.restartRecoveryRuns = remaining.length > 0 ? remaining : undefined;
233-
return { action: "apply", patch };
243+
return apply(patch);
234244
}
Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
import { getRuntimeConfig } from "../config/io.js";
2-
import { getGatewayRecoveryRuntime } from "../gateway/server-recovery-runtime-context.js";
31
import type { MainSessionRecoveryPendingTarget } from "./main-session-recovery-store.js";
42

53
/** Schedules exact-row recovery only after the caller releases its lifecycle admission. */
@@ -10,17 +8,16 @@ export function scheduleMainSessionRecoveryPendingTarget(
108
return;
119
}
1210
void import("./main-session-restart-recovery.js").then(
13-
({ scheduleRestartAbortedMainSessionRecoveryAfterOwnerRelease }) => {
14-
scheduleRestartAbortedMainSessionRecoveryAfterOwnerRelease({
11+
({ scheduleRestartAbortedMainSessionRecoveryAfterOwnerRelease: schedule }) =>
12+
schedule({
1513
expectedSessionId: target.sessionId,
1614
getConfig: getRuntimeConfig,
1715
getGatewayRuntime: getGatewayRecoveryRuntime,
1816
sessionKey: target.sessionKey,
1917
storePath: target.storePath,
20-
});
21-
},
22-
() => {
23-
// Startup recovery remains the fallback if the optional recovery module cannot load.
24-
},
18+
}),
19+
() => {}, // Startup recovery remains the fallback if this optional module cannot load.
2520
);
2621
}
22+
import { getRuntimeConfig } from "../config/io.js";
23+
import { getGatewayRecoveryRuntime } from "../gateway/server-recovery-runtime-context.js";

0 commit comments

Comments
 (0)