Skip to content

Commit f75404e

Browse files
roboclaw-botVACIncobviyus
authored
fix(gateway): wait for restart recovery execution start (#128843)
* fix(gateway): wait for recovery execution start * fix(gateway): adopt exact channel recovery claims * fix(gateway): bound recovery execution start Co-authored-by: VACInc <[email protected]> * fix(gateway): close recovery edge cases * fix(gateway): adopt source-keyed recovery claims * fix(gateway): fence late recovery acceptance * fix(gateway): preserve claimed recovery routes * test(gateway): reject recovery aborts with errors --------- Co-authored-by: roboclaw-bot <[email protected]> Co-authored-by: VACInc <[email protected]> Co-authored-by: Ayaan Zaidi <[email protected]>
1 parent e901771 commit f75404e

20 files changed

Lines changed: 748 additions & 94 deletions

‎src/agents/agent-command-restart-recovery.test.ts‎

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -73,19 +73,26 @@ describe("buildCurrentRunRestartRecoveryClaim", () => {
7373
});
7474
});
7575

76-
it("rejects a route change after recovery ownership is claimed", () => {
77-
expect(() =>
76+
it("preserves the claimed route when delivery preparation resolves an alias", () => {
77+
expect(
7878
buildCurrentRunRestartRecoveryClaim({
79-
deliveryContext: { channel: "discord", to: "channel:other" },
79+
deliveryContext: {
80+
channel: "telegram",
81+
to: "telegram:-100123:topic:1",
82+
threadId: 1,
83+
},
8084
entry: {
8185
sessionId: "session-1",
8286
updatedAt: 1,
8387
restartRecoveryDeliveryRunId: "recovery-run",
84-
restartRecoveryDeliveryContext: { channel: "discord", to: "channel:123" },
88+
restartRecoveryDeliveryContext: { channel: "telegram", to: "-100123", threadId: 1 },
8589
},
8690
runId: "recovery-run",
8791
}),
88-
).toThrow("restart recovery delivery route changed after the run was claimed");
92+
).toMatchObject({
93+
restartRecoveryDeliveryContext: { channel: "telegram", to: "-100123", threadId: 1 },
94+
restartRecoveryDeliveryRunId: "recovery-run",
95+
});
8996
});
9097

9198
it("requires explicit ownership for a new source claim", () => {

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

Lines changed: 0 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -22,20 +22,6 @@ function normalizeOptionalThreadId(value: unknown): string | undefined {
2222
);
2323
}
2424

25-
function sameDeliveryContext(
26-
left: DeliveryContext | undefined,
27-
right: DeliveryContext | undefined,
28-
): boolean {
29-
return (
30-
left !== undefined &&
31-
right !== undefined &&
32-
left.channel === right.channel &&
33-
left.to === right.to &&
34-
left.accountId === right.accountId &&
35-
normalizeOptionalThreadId(left.threadId) === normalizeOptionalThreadId(right.threadId)
36-
);
37-
}
38-
3925
/** Replace model-selected media with the exact host-owned delivery set. */
4026
export function constrainRestartRecoveryDeliveryPayloads(
4127
payloads: ReplyPayload[] | undefined,
@@ -320,13 +306,6 @@ export function buildCurrentRunRestartRecoveryClaim(params: {
320306
// Recovery can preclaim a run by id. Preserve its original source semantics
321307
// while the resumed RPC replaces only the active delivery run id.
322308
const adoptsExistingClaim = params.entry.restartRecoveryDeliveryRunId === params.runId;
323-
if (
324-
adoptsExistingClaim &&
325-
params.deliveryContext !== undefined &&
326-
!sameDeliveryContext(params.entry.restartRecoveryDeliveryContext, params.deliveryContext)
327-
) {
328-
throw new Error("restart recovery delivery route changed after the run was claimed");
329-
}
330309
const createsTranscriptOnlySourceClaim =
331310
params.sourceRunId !== undefined && params.deliveryContext === undefined;
332311
const createsScopedDeliveryClaim = params.sourceRunId !== undefined;

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

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,9 @@ import { recoverStore } from "./main-session-restart-recovery-store.js";
1919

2020
const sessionKey = "agent:main:main";
2121
const unusedGatewayRuntime: GatewayRecoveryRuntime = {
22+
abortAgent: async () => {
23+
throw new Error("terminal residue must not abort");
24+
},
2225
dispatchAgent: async () => {
2326
throw new Error("terminal residue must not dispatch");
2427
},
Lines changed: 160 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,160 @@
1+
import type { GatewayRecoveryRuntime } from "../../gateway/server-instance-runtime.types.js";
2+
import type { AgentRunRequest } from "../../gateway/server-methods/agent-request-types.js";
3+
4+
const RESTART_RECOVERY_EXECUTION_START_TIMEOUT_MS = 10_000;
5+
const RESTART_RECOVERY_ABORT_TIMEOUT_MS = 2_000;
6+
7+
type RestartRecoveryDispatchResult = {
8+
runId: string;
9+
status?: unknown;
10+
};
11+
12+
type RestartRecoveryDispatchObservation = {
13+
dispatchAccepted: boolean;
14+
executionStarted: boolean;
15+
preStartAbortAttempted: boolean;
16+
preStartAbortConfirmed: boolean;
17+
};
18+
19+
export type RestartRecoveryDispatchStartOutcome =
20+
| {
21+
kind: "started";
22+
observation: RestartRecoveryDispatchObservation;
23+
}
24+
| {
25+
kind: "terminal";
26+
observation: RestartRecoveryDispatchObservation;
27+
result: RestartRecoveryDispatchResult;
28+
}
29+
| {
30+
kind: "failed";
31+
error: unknown;
32+
observation: RestartRecoveryDispatchObservation;
33+
};
34+
35+
export async function dispatchRestartRecoveryUntilStarted(params: {
36+
agentId: string;
37+
agentParams: AgentRunRequest;
38+
gatewayRuntime: GatewayRecoveryRuntime;
39+
recoveryRunId: string;
40+
sessionKey: string;
41+
}): Promise<RestartRecoveryDispatchStartOutcome> {
42+
let dispatchAccepted = false;
43+
let executionStarted = false;
44+
let executionStartTimedOut = false;
45+
let preStartAbortAttempted = false;
46+
let preStartAbortConfirmed = false;
47+
let preStartAbort: Promise<void> | undefined;
48+
const observe = (): RestartRecoveryDispatchObservation => ({
49+
dispatchAccepted,
50+
executionStarted,
51+
preStartAbortAttempted,
52+
preStartAbortConfirmed,
53+
});
54+
let resolveExecutionStarted!: () => void;
55+
const executionStartedPromise = new Promise<void>((resolve) => {
56+
resolveExecutionStarted = resolve;
57+
});
58+
const executionStartAbort = new AbortController();
59+
const abortBeforeStart = () => {
60+
if (!dispatchAccepted || executionStarted) {
61+
return Promise.resolve();
62+
}
63+
return (preStartAbort ??= (async () => {
64+
preStartAbortAttempted = true;
65+
const aborted = await params.gatewayRuntime.abortAgent(
66+
{
67+
agentId: params.agentId,
68+
runId: params.recoveryRunId,
69+
sessionKey: params.sessionKey,
70+
},
71+
RESTART_RECOVERY_ABORT_TIMEOUT_MS,
72+
);
73+
preStartAbortConfirmed = aborted.aborted === true;
74+
})());
75+
};
76+
let resolveExecutionStartTimeout!: (outcome: RestartRecoveryDispatchStartOutcome) => void;
77+
const executionStartTimeoutPromise = new Promise<RestartRecoveryDispatchStartOutcome>(
78+
(resolve) => {
79+
resolveExecutionStartTimeout = resolve;
80+
},
81+
);
82+
let executionStartTimer: ReturnType<typeof setTimeout> | undefined;
83+
const clearExecutionStartTimer = () => {
84+
if (executionStartTimer) {
85+
clearTimeout(executionStartTimer);
86+
executionStartTimer = undefined;
87+
}
88+
};
89+
executionStartTimer = setTimeout(() => {
90+
if (!executionStarted) {
91+
executionStartTimedOut = true;
92+
const error = new Error("restart recovery execution start timeout");
93+
void abortBeforeStart()
94+
.catch(() => undefined)
95+
.then(() => {
96+
executionStartAbort.abort(error);
97+
resolveExecutionStartTimeout({ kind: "failed", error, observation: observe() });
98+
});
99+
}
100+
}, RESTART_RECOVERY_EXECUTION_START_TIMEOUT_MS);
101+
executionStartTimer.unref?.();
102+
let dispatchPromise: Promise<RestartRecoveryDispatchResult>;
103+
try {
104+
dispatchPromise = params.gatewayRuntime.dispatchAgent<RestartRecoveryDispatchResult>(
105+
params.agentParams,
106+
undefined,
107+
{
108+
expectFinal: true,
109+
onAccepted: () => {
110+
dispatchAccepted = true;
111+
if (executionStartTimedOut) {
112+
void abortBeforeStart().catch(() => undefined);
113+
}
114+
},
115+
onExecutionStarted: () => {
116+
if (executionStartTimedOut) {
117+
return;
118+
}
119+
executionStarted = true;
120+
clearExecutionStartTimer();
121+
resolveExecutionStarted();
122+
},
123+
onSignalAbort: abortBeforeStart,
124+
signal: executionStartAbort.signal,
125+
},
126+
);
127+
} catch (error) {
128+
clearExecutionStartTimer();
129+
return { kind: "failed", error, observation: observe() };
130+
}
131+
const terminalDispatchOutcome = dispatchPromise.then<
132+
RestartRecoveryDispatchStartOutcome,
133+
RestartRecoveryDispatchStartOutcome
134+
>(
135+
(result) => {
136+
if (result.status === "in_flight") {
137+
// Cached acceptance is still queued work. Keep its exact claim under the
138+
// same start deadline as a newly accepted run.
139+
dispatchAccepted = true;
140+
return executionStartTimeoutPromise;
141+
}
142+
clearExecutionStartTimer();
143+
return { kind: "terminal", observation: observe(), result };
144+
},
145+
(error: unknown) => {
146+
clearExecutionStartTimer();
147+
return { kind: "failed", error, observation: observe() };
148+
},
149+
);
150+
return await Promise.race([
151+
terminalDispatchOutcome,
152+
executionStartTimeoutPromise,
153+
executionStartedPromise.then(
154+
(): RestartRecoveryDispatchStartOutcome => ({
155+
kind: "started",
156+
observation: observe(),
157+
}),
158+
),
159+
]);
160+
}

0 commit comments

Comments
 (0)