Skip to content

Commit 820bcb7

Browse files
authored
fix(outbound): record queue-write loss and fail every payload on prep abort (#124756)
* fix(outbound): record queue-write loss and fail every payload on prep abort Two silent-observer gaps in the outbound queue admission path: 1. Best-effort staging/queue-write failures were swallowed with a bare 'return null'. The send proceeded live-only, so a crash mid-send lost the message with zero forensic trace of why the write-ahead row was missing. Every sibling degradation on this boundary logs (persistQueuedPreSendState, the dispatch-refresh fallback); this one now warns with channel/target and the error. 2. Batch preparation failure emitted message_sent for only the first payload while audit emitted per-payload terminals, so plugins with message_sent hooks saw 1 failure for an N-payload batch. The failure path now emits one hook failure per logical payload, matching the audit terminals and the recovery sibling's queuedTerminalFailureEvents. The unused error.payload pick and its OutboundPayloadPreparationError import went with it. Regressions: queue-write warn asserted in the existing best-effort fallback test; new multi-payload prep-failure test asserts 2 hook failures. Both fail pre-fix. * chore(outbound): keep OutboundPayloadPreparationError module-local Last external consumer went away with the per-payload emit; the deadcode:exports gate rejects unused exports.
1 parent 12138d2 commit 820bcb7

3 files changed

Lines changed: 59 additions & 12 deletions

File tree

‎src/infra/outbound/deliver-prepare.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ import {
2121
} from "./prepared-batch.js";
2222
import { createReplyToDeliveryPolicy } from "./reply-policy.js";
2323

24-
export class OutboundPayloadPreparationError extends Error {
24+
class OutboundPayloadPreparationError extends Error {
2525
readonly sourceIndex: number;
2626
readonly payload: ReplyPayload;
2727

‎src/infra/outbound/deliver-queue.ts‎

Lines changed: 22 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,15 @@
11
// Owns durable queue admission and hands stable custody to the execution loop.
22
import { deriveDurableFinalDeliveryRequirementsForBatch } from "../../channels/message/capabilities.js";
33
import { createRenderedMessageBatchPlan } from "../../channels/message/rendered-batch.js";
4+
import { createSubsystemLogger } from "../../logging/subsystem.js";
45
import { getGlobalHookRunner } from "../../plugins/hook-runner-global.js";
56
import { formatErrorMessage } from "../errors.js";
67
import { resolveDeferredDeliveryAdmission } from "./deferred-delivery-admission.js";
78
import { resolveOutboundDurableFinalDeliverySupport } from "./deliver-channel.js";
89
import type { DeliverOutboundPayloadsParams } from "./deliver-contracts.js";
910
import { OUTBOUND_DELIVERY_LOG_SCOPE } from "./deliver-log.js";
1011
import { buildPayloadSummary } from "./deliver-payload.js";
11-
import { OutboundPayloadPreparationError, prepareOutboundPayloadBatch } from "./deliver-prepare.js";
12+
import { prepareOutboundPayloadBatch } from "./deliver-prepare.js";
1213
import {
1314
restoreQueuedDeliveryCustody,
1415
stageAndEnqueueOutboundDelivery,
@@ -33,6 +34,8 @@ import { createMessageSentEmitter } from "./message-sent-hook.js";
3334
import { emitOutboundAuditTerminals, uniformOutboundAuditTerminals } from "./outbound-audit.js";
3435
import { acceptedPreparedOutboundEntries } from "./prepared-batch.js";
3536

37+
const log = createSubsystemLogger("outbound/deliver");
38+
3639
export async function runOutboundDelivery(
3740
params: DeliverOutboundPayloadsParams,
3841
): Promise<OutboundDeliveryResult[]> {
@@ -186,10 +189,10 @@ async function runOutboundDeliveryWithQueue(
186189
stablePreparationOwner?.markPrepared();
187190
} catch (error) {
188191
emitPreQueueFailure();
189-
const failedPayload =
190-
error instanceof OutboundPayloadPreparationError ? error.payload : params.payloads[0];
191-
if (failedPayload) {
192-
const summary = buildPayloadSummary(failedPayload);
192+
// Preparation aborts the whole batch, so hooks get one failure per
193+
// logical payload — matching the per-payload audit terminals above and
194+
// the recovery sibling's queuedTerminalFailureEvents.
195+
if (params.payloads.length > 0) {
193196
const { emitMessageSent } = createMessageSentEmitter({
194197
hookRunner: getGlobalHookRunner(),
195198
channel,
@@ -201,11 +204,14 @@ async function runOutboundDeliveryWithQueue(
201204
runId: params.replyPayloadSendingHook?.runId,
202205
logPrefix: OUTBOUND_DELIVERY_LOG_SCOPE,
203206
});
204-
emitMessageSent({
205-
success: false,
206-
content: summary.hookContent ?? summary.text,
207-
error: formatErrorMessage(error),
208-
});
207+
for (const payload of params.payloads) {
208+
const summary = buildPayloadSummary(payload);
209+
emitMessageSent({
210+
success: false,
211+
content: summary.hookContent ?? summary.text,
212+
error: formatErrorMessage(error),
213+
});
214+
}
209215
}
210216
throw error;
211217
}
@@ -271,8 +277,13 @@ async function runOutboundDeliveryWithQueue(
271277
emitPreQueueFailure();
272278
throw err;
273279
}
280+
// Best-effort delivery continues live-only, but a crash mid-send now
281+
// loses the message — record why the write-ahead row is missing.
282+
log.warn(
283+
`outbound queue write failed; continuing without durability (channel=${params.channel} to=${params.to}): ${formatErrorMessage(err)}`,
284+
);
274285
return null;
275-
}); // Best-effort delivery falls back to direct send if staging or the queue write fails.
286+
});
276287

277288
const queueId = queued?.id ?? null;
278289
if (queued?.created && stablePreparationOwner) {

‎src/infra/outbound/deliver.test.ts‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1758,6 +1758,42 @@ describe("deliverOutboundPayloads", () => {
17581758
expect(results[0]?.messageId).toBe("m1");
17591759

17601760
expect(sendMatrix).toHaveBeenCalled();
1761+
// The lost write-ahead durability must leave a recorded reason: a crash
1762+
// mid-send now loses the message with no queue row to recover.
1763+
const warnLines = logMocks.warn.mock.calls.map((call) => String(call[0]));
1764+
const queueWarn = warnLines.find((line) => line.includes("outbound queue write failed"));
1765+
expect(queueWarn).toBeDefined();
1766+
expect(queueWarn).toContain("channel=matrix");
1767+
expect(queueWarn).toContain("queue offline");
1768+
});
1769+
1770+
it("emits one message_sent failure per payload when batch preparation fails", async () => {
1771+
hookMocks.runner.hasHooks.mockImplementation(
1772+
(hookName?: string) => hookName === "message_sent" || hookName === "reply_payload_sending",
1773+
);
1774+
hookMocks.runner.runReplyPayloadSending.mockRejectedValueOnce(new Error("modifier exploded"));
1775+
const sendMatrix = vi.fn();
1776+
1777+
await expect(
1778+
deliverMatrix({
1779+
payloads: [{ text: "first payload" }, { text: "second payload" }],
1780+
deps: { matrix: sendMatrix },
1781+
replyPayloadSendingHook: {
1782+
kind: "final",
1783+
channel: "matrix",
1784+
context: { channelId: "matrix", conversationId: "!room:example" },
1785+
},
1786+
}),
1787+
).rejects.toThrow("modifier exploded");
1788+
1789+
expect(sendMatrix).not.toHaveBeenCalled();
1790+
// Preparation aborts the whole batch: hooks must see every logical
1791+
// payload fail, matching the per-payload audit terminals.
1792+
expect(hookMocks.runner.runMessageSent).toHaveBeenCalledTimes(2);
1793+
const contents = hookMocks.runner.runMessageSent.mock.calls.map(
1794+
(call) => (call[0] as { content?: string }).content,
1795+
);
1796+
expect(contents).toEqual(["first payload", "second payload"]);
17611797
});
17621798

17631799
it("runs afterCommit hooks after best-effort queue fallback direct sends", async () => {

0 commit comments

Comments
 (0)