Skip to content

Commit a8e7e8c

Browse files
Feelw00claude
andcommitted
fix(infra): refuse blind replay of a recovered session delivery once its turn has run
The session-delivery recovery path drainQueuedEntry (src/infra/session-delivery-queue-recovery.ts) delivers an entry then acks it (at-least-once). If the agent turn re-runs (dispatchAssembledChannelTurn, which can send via the message tool) but the process dies before ack, the entry stays pending and the next recovery blind-replays it: the same turn runs twice (non-idempotent LLM/tool side effects) and its reply is sent twice. #88665 moved both delivery queues onto a shared SQLite backing with a recovery_state column; the parallel outbound queue uses it to refuse a blind replay without adapter reconciliation, but the session-delivery drain neither set nor read it. Wire recovery_state into the session drain at the turn-execution boundary so the refuse decision is precise: - The deliver seam (server-restart-sentinel.ts) reports onSendAttemptStart right before the agent turn runs, and onSendDeferred if that attempt was merely deferred because the session was busy (the busy turn produces a busy-retry response, no durable work). The no-op deliver paths (systemEvent / changed-session / no-route) never run the turn and report neither. - drainQueuedEntry persists the send marker on onSendAttemptStart (and clears it on onSendDeferred). A recovered entry still carrying the marker is refused (fail-safe moveToFailed). On a thrown deliver, a turn that began running (sendAttempted) is refused even if it threw after sending, while a pre-send / busy-deferred / no-op failure stays retryable (at-least-once preserved for genuine pre-send failures). This matches the outbound queue's no-reconcile contract and addresses the sent-before-error case (a turn that sends then throws is no longer cleared and replayed). Tradeoff: a crash in the narrow window after the turn starts but before ack moves the entry to failed/ rather than replaying it (fail-safe over at-least-once), the same product choice the outbound queue makes without a reconcile capability. Adds regression tests: crash-before-ack, recovered-marker refuse, sent-before-error throw refuse, and pre-send failure stays retryable. AI-assisted: drafted with claude code (claude-opus-4-8). Co-Authored-By: Claude Opus 4.8 <[email protected]>
1 parent 2dbbef4 commit a8e7e8c

4 files changed

Lines changed: 329 additions & 4 deletions

File tree

‎src/gateway/server-restart-sentinel.ts‎

Lines changed: 34 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -241,6 +241,13 @@ function resolveQueuedSessionDeliveryContext(entry: QueuedSessionDelivery):
241241
async function deliverQueuedSessionDelivery(params: {
242242
deps: CliDeps;
243243
entry: QueuedSessionDelivery;
244+
// Recovery hooks: signal when the agent-turn re-run is actually about to run so the
245+
// recovery layer can persist its send marker (and clear it if the attempt is merely
246+
// deferred because the session is busy). Only the agentTurn dispatch path reports
247+
// these; the no-op early-return paths (systemEvent / changed-session / no-route) do
248+
// not run the turn and stay retryable.
249+
onSendAttemptStart?: () => Promise<void>;
250+
onSendDeferred?: () => Promise<void>;
244251
}) {
245252
const { cfg, entry, storePath, canonicalKey } = loadSessionEntry(params.entry.sessionKey);
246253
const queuedDeliveryContext = resolveQueuedSessionDeliveryContext(params.entry);
@@ -313,6 +320,10 @@ async function deliverQueuedSessionDelivery(params: {
313320
forceChatType: true,
314321
},
315322
);
323+
// The agent turn is about to run (it may do non-idempotent work and send its reply
324+
// via the message tool). Signal recovery to persist the send marker now; if the run
325+
// turns out to be busy-deferred, the dispatchError branch below clears it again.
326+
await params.onSendAttemptStart?.();
316327
await dispatchAssembledChannelTurn({
317328
cfg,
318329
channel: route.channel,
@@ -353,6 +364,15 @@ async function deliverQueuedSessionDelivery(params: {
353364
},
354365
});
355366
if (dispatchError) {
367+
// A busy continuation merely defers — the turn produced a busy-retry response, not
368+
// durable work — so clear the send marker and let recovery retry instead of
369+
// fail-safing it to failed/. Any other thrown error means the turn may have run.
370+
if (
371+
dispatchError instanceof Error &&
372+
dispatchError.message === RESTART_CONTINUATION_BUSY_RETRY_ERROR
373+
) {
374+
await params.onSendDeferred?.();
375+
}
356376
throw toLintErrorObject(dispatchError, "Non-Error thrown");
357377
}
358378
}
@@ -408,7 +428,13 @@ async function drainRestartContinuationQueue(params: {
408428
drainKey: `restart-continuation:${params.entryId}`,
409429
logLabel: "restart continuation",
410430
log: params.log,
411-
deliver: (entry) => deliverQueuedSessionDelivery({ deps: params.deps, entry }),
431+
deliver: (entry, hooks) =>
432+
deliverQueuedSessionDelivery({
433+
deps: params.deps,
434+
entry,
435+
onSendAttemptStart: hooks?.onSendAttemptStart,
436+
onSendDeferred: hooks?.onSendDeferred,
437+
}),
412438
selectEntry: (entry) => ({
413439
match: entry.id === params.entryId,
414440
bypassBackoff: true,
@@ -435,7 +461,13 @@ export async function recoverPendingRestartContinuationDeliveries(params: {
435461
maxEnqueuedAt?: number;
436462
}) {
437463
await recoverPendingSessionDeliveries({
438-
deliver: (entry) => deliverQueuedSessionDelivery({ deps: params.deps, entry }),
464+
deliver: (entry, hooks) =>
465+
deliverQueuedSessionDelivery({
466+
deps: params.deps,
467+
entry,
468+
onSendAttemptStart: hooks?.onSendAttemptStart,
469+
onSendDeferred: hooks?.onSendDeferred,
470+
}),
439471
log: params.log ?? log,
440472
maxEnqueuedAt: params.maxEnqueuedAt,
441473
});

‎src/infra/session-delivery-queue-recovery.ts‎

Lines changed: 75 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,11 @@ import {
77
import { formatErrorMessage } from "./errors.js";
88
import {
99
ackSessionDelivery,
10+
clearSessionDeliveryRecoveryState,
1011
failSessionDelivery,
1112
loadPendingSessionDelivery,
1213
loadPendingSessionDeliveries,
14+
markSessionDeliveryPlatformSendAttemptStarted,
1315
moveSessionDeliveryToFailed,
1416
type QueuedSessionDelivery,
1517
} from "./session-delivery-queue-storage.js";
@@ -23,7 +25,21 @@ type SessionDeliveryRecoverySummary = {
2325
deferredBackoff: number;
2426
};
2527

26-
type DeliverSessionDeliveryFn = (entry: QueuedSessionDelivery) => Promise<void>;
28+
// Hooks let the deliver seam signal the send boundary to recovery: it calls
29+
// onSendAttemptStart once the turn is actually about to run (past any pre-send/busy
30+
// gate), and onSendDeferred if that attempt was deferred without running (e.g. the
31+
// session was busy). Recovery uses these to mark/clear the durable recovery_state
32+
// and to decide, on a thrown deliver, whether the turn may have run (refuse) or was
33+
// a pre-send no-op (safe to retry).
34+
export interface SessionDeliveryDeliverHooks {
35+
onSendAttemptStart: () => Promise<void>;
36+
onSendDeferred: () => Promise<void>;
37+
}
38+
39+
type DeliverSessionDeliveryFn = (
40+
entry: QueuedSessionDelivery,
41+
hooks?: SessionDeliveryDeliverHooks,
42+
) => Promise<void>;
2743

2844
export interface SessionDeliveryRecoveryLogger {
2945
info(msg: string): void;
@@ -111,6 +127,21 @@ export function isSessionDeliveryEligibleForRetry(
111127
return { eligible: false, remainingBackoffMs: nextEligibleAt - now };
112128
}
113129

130+
async function moveSessionDeliveryToFailedSafe(
131+
id: string,
132+
stateDir: string | undefined,
133+
): Promise<"moved-to-failed" | "already-gone"> {
134+
try {
135+
await moveSessionDeliveryToFailed(id, stateDir);
136+
return "moved-to-failed";
137+
} catch (err) {
138+
if (getErrnoCode(err) === "ENOENT") {
139+
return "already-gone";
140+
}
141+
throw err;
142+
}
143+
}
144+
114145
async function drainQueuedEntry(opts: {
115146
entry: QueuedSessionDelivery;
116147
deliver: DeliverSessionDeliveryFn;
@@ -119,15 +150,57 @@ async function drainQueuedEntry(opts: {
119150
onFailed?: (entry: QueuedSessionDelivery, errMsg: string) => void;
120151
}): Promise<"recovered" | "failed" | "moved-to-failed" | "already-gone"> {
121152
const { entry } = opts;
153+
154+
// An entry recovered while still carrying the send marker was interrupted (crash)
155+
// after the turn began running but before it acked. The deliver seam persists the
156+
// marker only once the turn is actually about to run (past the busy/pre-send gate),
157+
// so its presence on a recovered entry means a non-idempotent turn may have run and
158+
// its reply may already have been sent. Without an adapter reconciliation capability
159+
// we cannot confirm, so we refuse a blind replay and fail-safe to failed/, matching
160+
// the outbound queue's no-reconcile contract. (Tradeoff: a crash in the narrow window
161+
// after the turn starts but before ack moves the entry to failed/ rather than
162+
// replaying it — fail-safe over at-least-once for that window.)
163+
if (entry.recoveryState === "send_attempt_started") {
164+
const errMsg =
165+
"session delivery was interrupted after the turn began (send_attempt_started); refusing blind replay without adapter reconciliation";
166+
opts.onFailed?.(entry, errMsg);
167+
return moveSessionDeliveryToFailedSafe(entry.id, opts.stateDir);
168+
}
169+
170+
// sendAttempted flips true only when the deliver seam reports the turn is actually
171+
// running (onSendAttemptStart), and back to false if that attempt was deferred
172+
// without running (onSendDeferred, e.g. the session was busy). It mirrors the durable
173+
// marker in-process and decides a thrown deliver: turn-may-have-run (refuse) vs a
174+
// pre-send / busy-deferred / no-op deliver (safe to retry).
175+
let sendAttempted = false;
122176
try {
123-
await opts.deliver(entry);
177+
await opts.deliver(entry, {
178+
onSendAttemptStart: async () => {
179+
sendAttempted = true;
180+
await markSessionDeliveryPlatformSendAttemptStarted(entry.id, opts.stateDir);
181+
},
182+
onSendDeferred: async () => {
183+
sendAttempted = false;
184+
await clearSessionDeliveryRecoveryState(entry.id, opts.stateDir);
185+
},
186+
});
124187
await ackSessionDelivery(entry.id, opts.stateDir);
125188
opts.onRecovered?.(entry);
126189
return "recovered";
127190
} catch (err) {
128191
const errMsg = formatErrorMessage(err);
129192
opts.onFailed?.(entry, errMsg);
130193
try {
194+
if (sendAttempted) {
195+
// The turn began running (and may have done non-idempotent work / sent its
196+
// reply) before this throw — refuse a blind replay and fail-safe to failed/.
197+
// The durable marker also persisted, so a crash here is refused on the next
198+
// recovery by the guard above.
199+
return await moveSessionDeliveryToFailedSafe(entry.id, opts.stateDir);
200+
}
201+
// The turn never started (pre-send / busy-deferred / no-op deliver path): no
202+
// marker was persisted and nothing ran, so the entry stays retryable
203+
// (at-least-once preserved for genuine pre-send failures).
131204
await failSessionDelivery(entry.id, errMsg, opts.stateDir);
132205
return "failed";
133206
} catch (failErr) {

‎src/infra/session-delivery-queue-storage.ts‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,14 @@ export type QueuedSessionDelivery = QueuedSessionDeliveryPayload & {
6262
retryCount: number;
6363
lastAttemptAt?: number;
6464
lastError?: string;
65+
// Durable recovery marker, persisted on the shared delivery-queue SQLite
66+
// `recovery_state` column. Set to `send_attempt_started` while a delivery is
67+
// mid-flight (the drain has begun deliver but not yet acked); a recovered entry
68+
// carrying it is refused a blind replay (see session-delivery-queue-recovery.ts).
69+
// Unlike the outbound queue we keep a single state: the drain refuses on this
70+
// marker alone, so a post-deliver `unknown_after_send` upgrade would change no
71+
// decision (the in-process `delivered` flag already covers a post-return failure).
72+
recoveryState?: "send_attempt_started";
6573
};
6674

6775
function buildEntryId(idempotencyKey?: string): string {
@@ -149,3 +157,28 @@ export async function loadPendingSessionDeliveries(
149157
export async function moveSessionDeliveryToFailed(id: string, stateDir?: string): Promise<void> {
150158
moveDeliveryQueueEntryToFailed(QUEUE_NAME, id, stateDir);
151159
}
160+
161+
// Persist the send-attempt marker before the drain invokes the deliver seam, so a
162+
// crash anywhere between here and the ack leaves durable evidence that the delivery
163+
// may already have run. Mirrors the outbound queue's send_attempt_started.
164+
export async function markSessionDeliveryPlatformSendAttemptStarted(
165+
id: string,
166+
stateDir?: string,
167+
): Promise<void> {
168+
updateDeliveryQueueEntry(QUEUE_NAME, id, stateDir, (entry) => ({
169+
...(entry as QueuedSessionDelivery),
170+
recoveryState: "send_attempt_started",
171+
}));
172+
}
173+
174+
// Clear the recovery marker. Used only on a proven pre-send failure (deliver threw
175+
// before anything reached the platform), so the entry stays replayable.
176+
export async function clearSessionDeliveryRecoveryState(
177+
id: string,
178+
stateDir?: string,
179+
): Promise<void> {
180+
updateDeliveryQueueEntry(QUEUE_NAME, id, stateDir, (entry) => ({
181+
...(entry as QueuedSessionDelivery),
182+
recoveryState: undefined,
183+
}));
184+
}

0 commit comments

Comments
 (0)