Skip to content

Commit 7c4961b

Browse files
Feelw00claude
andcommitted
fix(infra): signal sent-before-error via a typed error so replay is refused even if the marker write fails
Address a clawsweeper [P1]: on partial_failed the sentinel persisted unknown_after_send before throwing, but if that marker write itself failed, deliver threw before drainQueuedEntry set `delivered`, the entry stayed at send_attempt_started, and the recovery catch cleared the marker and requeued an already-sent reply. Carry the sent-before-error signal with the thrown error instead of depending on a durable write that can fail: the delivery seam throws SessionDeliverySendUncertainError on partial_failed (marker write is now best-effort, kept for crash durability), and the recovery catch refuses a blind replay when delivered || isSessionDeliverySendUncertainError(err) (with the unknown_after_send marker re-read kept as a secondary guard). A pre-send throw still clears the marker and stays retryable. Adds a regression test for partial_failed where the marker write also fails; updates the partial_failed test to throw the typed signal; adds the new export to the sentinel test mock. AI-assisted: drafted with claude code (claude-opus-4-8). Co-Authored-By: Claude Opus 4.8 <[email protected]>
1 parent 86711f9 commit 7c4961b

5 files changed

Lines changed: 124 additions & 19 deletions

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

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -185,6 +185,9 @@ vi.mock("../infra/session-delivery-queue.js", () => ({
185185
drainPendingSessionDeliveries: mocks.drainPendingSessionDeliveries,
186186
recoverPendingSessionDeliveries: mocks.recoverPendingSessionDeliveries,
187187
markSessionDeliveryPlatformOutcomeUnknown: mocks.markSessionDeliveryPlatformOutcomeUnknown,
188+
SessionDeliverySendUncertainError: class SessionDeliverySendUncertainError extends Error {
189+
readonly code = "session-delivery-send-uncertain";
190+
},
188191
}));
189192

190193
vi.mock("../config/sessions.js", () => ({

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

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ import {
3131
loadPendingSessionDelivery,
3232
markSessionDeliveryPlatformOutcomeUnknown,
3333
recoverPendingSessionDeliveries,
34+
SessionDeliverySendUncertainError,
3435
type QueuedSessionDelivery,
3536
type QueuedSessionDeliveryPayload,
3637
type SessionDeliveryRecoveryLogger,
@@ -371,13 +372,21 @@ async function deliverQueuedSessionDelivery(params: {
371372
if (send.status === "partial_failed") {
372373
// Some payloads were already delivered to the platform before this
373374
// failure (send.sentBeforeError === true). Persist the
374-
// unknown_after_send marker on the queue entry before throwing so the
375-
// recovery layer refuses a blind replay of an already-sent turn
376-
// instead of clearing the marker and re-running the turn / re-sending
377-
// the reply. Mirrors the outbound queue, which keeps the send-attempt
378-
// marker once the platform send has started.
379-
await markSessionDeliveryPlatformOutcomeUnknown(params.entry.id);
380-
throw send.error;
375+
// unknown_after_send marker (best-effort, so a later crash before the
376+
// next recovery still refuses replay) and throw a typed
377+
// sent-before-error signal. Throwing the signal - rather than relying
378+
// solely on the marker write - means recovery refuses a blind replay
379+
// even if this marker write fails. Mirrors the outbound queue, which
380+
// keeps the send-attempt marker once the platform send has started.
381+
try {
382+
await markSessionDeliveryPlatformOutcomeUnknown(params.entry.id);
383+
} catch (markErr) {
384+
log.warn(
385+
`restart continuation: failed to persist unknown_after_send marker for ${params.entry.id}; recovery still refuses replay via the sent-before-error signal: ${String(markErr)}`,
386+
{ sessionKey: canonicalKey },
387+
);
388+
}
389+
throw new SessionDeliverySendUncertainError(send.error);
381390
}
382391
if (send.status === "failed") {
383392
throw send.error;

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

Lines changed: 43 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,40 @@ import {
1111
type QueuedSessionDelivery,
1212
} from "./session-delivery-queue-storage.js";
1313

14+
const SESSION_DELIVERY_SEND_UNCERTAIN_CODE = "session-delivery-send-uncertain";
15+
16+
/**
17+
* Thrown by the delivery seam when a platform send already partially happened
18+
* (sendDurableMessageBatch returned `partial_failed`, i.e. `sentBeforeError`).
19+
* It signals recovery to refuse a blind replay even if the durable
20+
* `unknown_after_send` marker write failed: the signal travels with the thrown
21+
* error rather than depending on a disk write that can itself fail.
22+
*/
23+
export class SessionDeliverySendUncertainError extends Error {
24+
readonly code = SESSION_DELIVERY_SEND_UNCERTAIN_CODE;
25+
constructor(cause?: unknown) {
26+
super("session delivery platform send outcome uncertain (sent before error)", { cause });
27+
this.name = "SessionDeliverySendUncertainError";
28+
}
29+
}
30+
31+
/** True if `err` is (or wraps) a {@link SessionDeliverySendUncertainError}. */
32+
export function isSessionDeliverySendUncertainError(err: unknown): boolean {
33+
for (let cur: unknown = err, depth = 0; cur != null && depth < 5; depth += 1) {
34+
if (cur instanceof SessionDeliverySendUncertainError) {
35+
return true;
36+
}
37+
if (
38+
typeof cur === "object" &&
39+
(cur as { code?: unknown }).code === SESSION_DELIVERY_SEND_UNCERTAIN_CODE
40+
) {
41+
return true;
42+
}
43+
cur = (cur as { cause?: unknown }).cause;
44+
}
45+
return false;
46+
}
47+
1448
type SessionDeliveryRecoverySummary = {
1549
recovered: number;
1650
failed: number;
@@ -159,15 +193,15 @@ async function drainQueuedEntry(opts: {
159193
const errMsg = formatErrorMessage(err);
160194
opts.onFailed?.(entry, errMsg);
161195
try {
162-
// If deliver returned, the turn ran and the reply may already have been
163-
// sent; a failure in the marker write or ack after that point must not
164-
// requeue the entry. Likewise, if the delivery seam advanced the marker to
165-
// unknown_after_send (sendDurableMessageBatch -> partial_failed, a
166-
// sent-before-error throw), the send partially happened. In both cases we
167-
// refuse a blind replay and fail-safe to failed/, exactly like an entry
168-
// recovered with a marker (and like the outbound queue, which never clears
169-
// the marker once the platform send has started).
170-
if (delivered) {
196+
// Refuse a blind replay whenever the platform send may already have
197+
// happened: (a) deliver returned, so the turn ran and the reply may be out
198+
// and a later marker-write/ack failure must not requeue it; (b) the
199+
// delivery seam threw a sent-before-error signal (sendDurableMessageBatch
200+
// -> partial_failed) - this travels with the error so it holds even if the
201+
// unknown_after_send marker write itself failed; (c) the durable marker
202+
// reads back as unknown_after_send. Fail-safe to failed/, like the outbound
203+
// queue, which never clears its marker once the send has started.
204+
if (delivered || isSessionDeliverySendUncertainError(err)) {
171205
return await moveSessionDeliveryToFailedWithEnoent(entry.id, opts.stateDir);
172206
}
173207
const current = await loadPendingSessionDelivery(entry.id, opts.stateDir);

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

Lines changed: 61 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import {
88
loadPendingSessionDeliveries,
99
markSessionDeliveryPlatformOutcomeUnknown,
1010
recoverPendingSessionDeliveries,
11+
SessionDeliverySendUncertainError,
1112
} from "./session-delivery-queue.js";
1213

1314
describe("session-delivery queue recovery", () => {
@@ -219,12 +220,14 @@ describe("session-delivery queue recovery", () => {
219220
// Model the production delivery seam on a partial_failed send: some
220221
// payloads already reached the platform (sentBeforeError), so
221222
// deliverQueuedSessionDelivery persists the unknown_after_send marker and
222-
// then throws. Recovery must refuse a blind replay rather than clearing the
223-
// marker and re-running the turn / re-sending the already-sent reply.
223+
// throws a SessionDeliverySendUncertainError. Recovery must refuse a blind
224+
// replay rather than clearing the marker and re-sending the already-sent reply.
224225
const deliver = vi.fn(async () => {
225226
deliverCount += 1;
226227
await markSessionDeliveryPlatformOutcomeUnknown(id, tempDir);
227-
throw new Error("partial_failed: reply chunk sent before error");
228+
throw new SessionDeliverySendUncertainError(
229+
new Error("partial_failed: reply chunk sent before error"),
230+
);
228231
});
229232
const log = { info: vi.fn(), warn: vi.fn(), error: vi.fn() };
230233

@@ -256,6 +259,61 @@ describe("session-delivery queue recovery", () => {
256259
});
257260
});
258261

262+
it("does not re-deliver a partially sent entry even if persisting the unknown marker fails", async () => {
263+
await withTempDir({ prefix: "openclaw-session-delivery-" }, async (tempDir) => {
264+
const id = await enqueueSessionDelivery(
265+
{
266+
kind: "agentTurn",
267+
sessionKey: "agent:main:main",
268+
message: "continue",
269+
messageId: "restart-sentinel:agent:main:main:agentTurn:654",
270+
route: { channel: "telegram", to: "chat-1", chatType: "direct" },
271+
},
272+
tempDir,
273+
);
274+
275+
let deliverCount = 0;
276+
// Model a partial_failed send whose unknown_after_send marker write ALSO
277+
// fails: the delivery seam still throws the sent-before-error signal, but
278+
// the entry is left at send_attempt_started (the marker was not advanced).
279+
// Recovery must refuse the blind replay from the thrown signal alone, not
280+
// from the (missing) durable marker.
281+
const deliver = vi.fn(async () => {
282+
deliverCount += 1;
283+
// No markSessionDeliveryPlatformOutcomeUnknown call here: the marker write failed.
284+
throw new SessionDeliverySendUncertainError(
285+
new Error("partial_failed with marker write failure"),
286+
);
287+
});
288+
const log = { info: vi.fn(), warn: vi.fn(), error: vi.fn() };
289+
290+
const drainOnce = () =>
291+
drainPendingSessionDeliveries({
292+
drainKey: "test-sent-before-error-marker-fail",
293+
logLabel: "test sent-before-error marker fail",
294+
deliver,
295+
stateDir: tempDir,
296+
log,
297+
selectEntry: (entry) => ({ match: entry.id === id, bypassBackoff: true }),
298+
});
299+
300+
// PASS 1: delivery partially sends but the marker write failed, so the
301+
// entry is left at send_attempt_started.
302+
await drainOnce();
303+
// It must still be moved to failed/, not requeued.
304+
expect(await loadPendingSessionDeliveries(tempDir)).toStrictEqual([]);
305+
306+
// PASS 2: restart recovery re-entry.
307+
await drainOnce();
308+
309+
// Before the fix: the catch saw only send_attempt_started (the marker write
310+
// failed) and requeued, so PASS 2 blind-replays -> deliverCount === 2.
311+
// After the fix: the thrown sent-before-error signal makes it
312+
// non-replayable -> deliverCount === 1.
313+
expect(deliverCount).toBe(1);
314+
});
315+
});
316+
259317
it("does not re-deliver when the outcome-marker write fails after a successful delivery", async () => {
260318
await withTempDir({ prefix: "openclaw-session-delivery-" }, async (tempDir) => {
261319
const id = await enqueueSessionDelivery(

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,5 +16,6 @@ export {
1616
drainPendingSessionDeliveries,
1717
isSessionDeliveryEligibleForRetry,
1818
recoverPendingSessionDeliveries,
19+
SessionDeliverySendUncertainError,
1920
} from "./session-delivery-queue-recovery.js";
2021
export type { SessionDeliveryRecoveryLogger } from "./session-delivery-queue-recovery.js";

0 commit comments

Comments
 (0)