Skip to content

Commit 5e1a28b

Browse files
fix(outbound): prevent duplicate sends from proven-not-sent message-tool failures (#124310)
A message-tool send that failed with proven-not-sent evidence (pre-connect ECONNREFUSED/ETIMEDOUT, PlatformMessageNotDispatchedError) was retried twice: the model resent it after seeing the error, and the durable outbound queue row stayed replay-eligible, so the reconnect/poll drain sent it again. Record retry ownership at the two producers of model-authored sends and dead-letter caller-owned rows in the queue executor: - in-process sends derive `deliveryRetryOwner: "caller"` from `actionOrigin: "message-tool"` in message-action-send; - gateway-owned plugin sends (telegram runs `message.action` in gateway mode) derive it from the signed agent-runtime turn context (`runtimeAgentId`) in the gateway handler and forward it through ChannelMessageActionContext into the plugin's durable send. Reporting-only callers (CLI, RPC clients, cron reusable intents) carry no owner and keep recovery's replay (#100979). Remote gateway mode mints no runtime identity and keeps the replayable row; tracked as a follow-up. Fixes #124279 Co-authored-by: synthclaw <[email protected]> Co-authored-by: Ayaan Zaidi <[email protected]>
1 parent d26e097 commit 5e1a28b

15 files changed

Lines changed: 340 additions & 143 deletions

‎extensions/telegram/src/action-runtime.test.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -868,6 +868,7 @@ describe("handleTelegramAction", () => {
868868
telegramConfig(),
869869
{
870870
gatewayClientScopes: ["operator.write"],
871+
deliveryRetryOwner: "caller",
871872
sessionKey: "agent:main:telegram:direct:123",
872873
reply: {
873874
replyToId: "456",
@@ -888,6 +889,9 @@ describe("handleTelegramAction", () => {
888889
to: "@testchannel",
889890
durability: "required",
890891
gatewayClientScopes: ["operator.write"],
892+
// The gateway-owned plugin send must inherit the caller's retry ownership,
893+
// or the failed row stays replay-eligible and duplicates (#124279).
894+
deliveryRetryOwner: "caller",
891895
session: { key: "agent:main:telegram:direct:123", agentId: "main" },
892896
reply: { replyToId: "456", source: "implicit", mode: "first" },
893897
payloads: [{ text: "Hello, Telegram!" }],

‎extensions/telegram/src/action-runtime.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -393,6 +393,7 @@ export async function handleTelegramAction(
393393
sessionKey?: string | null;
394394
inboundEventKind?: string;
395395
gatewayClientScopes?: readonly string[];
396+
deliveryRetryOwner?: ChannelMessageActionContext["deliveryRetryOwner"];
396397
conversationReadOrigin?: ConversationReadInvocationOrigin;
397398
requesterAccountId?: string | null;
398399
reply?: ChannelMessageActionContext["reply"];
@@ -646,6 +647,7 @@ export async function handleTelegramAction(
646647
silent: sendOptions.silent,
647648
durability: "required",
648649
gatewayClientScopes: options?.gatewayClientScopes,
650+
deliveryRetryOwner: options?.deliveryRetryOwner,
649651
...(mediaAccess ? { mediaAccess } : {}),
650652
...(outboundSession ? { session: outboundSession } : {}),
651653
});

‎extensions/telegram/src/channel-actions.test.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,7 @@ describe("telegramMessageActions", () => {
6464
mediaLocalRoots: ["/tmp/conflicting-root"],
6565
requesterAccountId: "work",
6666
conversationReadOrigin: "delegated",
67+
deliveryRetryOwner: "caller",
6768
reply: { replyToId: "9001", source: "implicit", mode: "first" },
6869
toolContext: {
6970
currentChannelProvider: "telegram",
@@ -77,6 +78,7 @@ describe("telegramMessageActions", () => {
7778
expect.anything(),
7879
expect.objectContaining({
7980
conversationReadOrigin: "delegated",
81+
deliveryRetryOwner: "caller",
8082
mediaAccess,
8183
reply: { replyToId: "9001", source: "implicit", mode: "first" },
8284
requesterAccountId: "work",

‎extensions/telegram/src/channel-actions.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -258,6 +258,7 @@ export const telegramMessageActions: ChannelMessageActionAdapter = {
258258
conversationReadOrigin,
259259
requesterAccountId,
260260
gatewayClientScopes,
261+
deliveryRetryOwner,
261262
}) => {
262263
const telegramAction = resolveTelegramMessageActionName(action);
263264
if (!telegramAction) {
@@ -292,6 +293,7 @@ export const telegramMessageActions: ChannelMessageActionAdapter = {
292293
sessionKey,
293294
inboundEventKind,
294295
gatewayClientScopes,
296+
deliveryRetryOwner,
295297
...(conversationReadOrigin ? { conversationReadOrigin } : {}),
296298
...(requesterAccountId ? { requesterAccountId } : {}),
297299
...(reply ? { reply } : {}),

‎src/channels/plugins/types.core.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -747,6 +747,11 @@ export type ChannelMessageActionContext = {
747747
toolContext?: ChannelThreadingToolContext;
748748
dryRun?: boolean;
749749
gatewayClientScopes?: readonly string[];
750+
/**
751+
* Server-owned fact: this caller receives proven-not-sent failures and resends
752+
* them. Plugins forward it into durable sends so recovery does not replay too.
753+
*/
754+
deliveryRetryOwner?: "caller";
750755
};
751756

752757
export type ChannelToolSend = {

‎src/gateway/server-methods/send.test.ts‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1426,6 +1426,36 @@ describe("gateway send mirroring", () => {
14261426
expect(lastDispatchChannelMessageActionCall()?.conversationReadOrigin).toBe("delegated");
14271427
});
14281428

1429+
it.each([
1430+
["an agent runtime message tool", true, "caller"],
1431+
["an operator CLI client", false, undefined],
1432+
])(
1433+
"hands gateway-owned plugin deliveries the retry owner for %s",
1434+
async (_label, isAgentRuntime, expected) => {
1435+
const sessionKey = "agent:main:slack:channel:C1";
1436+
mocks.dispatchChannelMessageAction.mockResolvedValueOnce({
1437+
details: { action: "handled" },
1438+
});
1439+
1440+
await runMessageActionRequest(
1441+
{
1442+
channel: "slack",
1443+
action: "send",
1444+
params: { channelId: "C1", message: "hi" },
1445+
sessionKey,
1446+
agentId: "main",
1447+
idempotencyKey: `idem-retry-owner-${expected ?? "reporting-only"}`,
1448+
},
1449+
isAgentRuntime ? agentRuntimeClient(sessionKey) : (directCliClient() as never),
1450+
);
1451+
1452+
// Only the message tool resends a proven-not-sent failure; leaving its
1453+
// queue row replayable is what duplicated the send (#124279), and marking
1454+
// a reporting-only caller would strand its row instead (#100979).
1455+
expect(lastDispatchChannelMessageActionCall()?.deliveryRetryOwner).toBe(expected);
1456+
},
1457+
);
1458+
14291459
it("does not send after delegated authority closes during session preparation", async () => {
14301460
const preparation = createDeferred<null>();
14311461
mocks.resolveOutboundSessionRoute.mockReturnValueOnce(preparation.promise);

‎src/gateway/server-methods/send.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1067,6 +1067,11 @@ export const sendHandlers: GatewayRequestHandlers = {
10671067
params: request.params,
10681068
reply: request.reply,
10691069
accountId,
1070+
// Only the model's message tool mints an agent-runtime turn context, and
1071+
// it resends proven-not-sent failures itself, so its gateway-owned plugin
1072+
// delivery must not also stay replayable (#124279). Operator, CLI, and
1073+
// external RPC clients carry none and keep recovery's replay (#100979).
1074+
deliveryRetryOwner: trustedContext.runtimeAgentId ? ("caller" as const) : undefined,
10701075
...selectMessageActionRequesterIdentity(trustedContext),
10711076
senderIsOwner: gatewayClientScopes.includes(ADMIN_SCOPE)
10721077
? request.senderIsOwner === true

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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -201,6 +201,8 @@ export type DeliverOutboundPayloadsCoreParams = {
201201
reusePendingDeliveryIntent?: boolean;
202202
/** @internal Serializable owner state finalized after live or recovered delivery. */
203203
deliveryCompletion?: DurableDeliveryCompletion;
204+
/** @internal The caller resends proven-not-sent payloads itself, so recovery must not. */
205+
deliveryRetryOwner?: "caller";
204206
/** @internal Ephemeral route authority for a recovered attempt; never owns completion. */
205207
conversationDeliveryAttemptAuthority?: ConversationDeliveryAttemptAuthority;
206208
/** @internal Revalidates authority once per durable queue execution, before adapter fanout. */

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

Lines changed: 59 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
// Owns queued delivery execution, custody transitions, and terminal cleanup.
2+
import type { AuditMessageFailureStage } from "../../audit/audit-event-types.js";
23
import { hasTrustedMessageAuditListeners } from "../../audit/message-audit-events.js";
34
import { createSubsystemLogger } from "../../logging/subsystem.js";
45
import { getGlobalHookRunner } from "../../plugins/hook-runner-global.js";
@@ -26,11 +27,13 @@ import {
2627
} from "./deliver-types.js";
2728
import { runOutboundDeliveryCommitHooks } from "./delivery-commit-hooks.js";
2829
import { rejectDurableDelivery, settleDurableDelivery } from "./delivery-completion.js";
30+
import { releaseSpoolArtifacts } from "./delivery-queue-media-spool.js";
2931
import {
3032
failDelivery,
3133
failDeliveryAfterPlatformSend,
3234
failDeliveryBeforePlatformSend,
3335
markDeliveryPlatformSendDispatched,
36+
moveToFailed,
3437
} from "./delivery-queue-storage.js";
3538
import { createMessageSentEmitter, type MessageSentEvent } from "./message-sent-hook.js";
3639
import {
@@ -491,19 +494,24 @@ export async function deliverOutboundPayloadsWithQueueCleanup(
491494
queuedPostSendState === "marked" ||
492495
(err instanceof OutboundDeliveryError && err.sentBeforeError) ||
493496
stablePayloadOutcomes?.some((outcome) => outcome.status === "sent") === true;
497+
// Every terminal below reports the same failed batch; only the stage differs.
498+
const emitFailedTerminals = (failureStage: AuditMessageFailureStage) =>
499+
emitTerminals(() =>
500+
failedOutboundAuditTerminals({
501+
payloadCount,
502+
results: deliveredResults,
503+
payloadOutcomes: auditPayloadOutcomes ?? [],
504+
failureStage,
505+
}),
506+
);
507+
const platformSendFailureStage: AuditMessageFailureStage =
508+
err instanceof OutboundDeliveryError ? err.stage : "platform_send";
494509
if (queueId) {
495510
if (queuedPreSendState === "acked") {
496511
// Best-effort fallback removed durable custody before provider I/O.
497512
// This process is now the only owner that can publish terminal observers.
498513
await runCommitHooksAfterAck();
499-
emitTerminals(() =>
500-
failedOutboundAuditTerminals({
501-
payloadCount,
502-
results: deliveredResults,
503-
payloadOutcomes: auditPayloadOutcomes ?? [],
504-
failureStage: err instanceof OutboundDeliveryError ? err.stage : "platform_send",
505-
}),
506-
);
514+
emitFailedTerminals(platformSendFailureStage);
507515
} else if (isDeliveryAbortError(err)) {
508516
if (hasPlatformSendEvidence) {
509517
if (queuedPostSendState !== "failed") {
@@ -530,14 +538,7 @@ export async function deliverOutboundPayloadsWithQueueCleanup(
530538
) {
531539
queuedPostSendState = "acked";
532540
await runCommitHooksAfterAck();
533-
emitTerminals(() =>
534-
failedOutboundAuditTerminals({
535-
payloadCount,
536-
results: deliveredResults,
537-
payloadOutcomes: auditPayloadOutcomes ?? [],
538-
failureStage: "queue",
539-
}),
540-
);
541+
emitFailedTerminals("queue");
541542
}
542543
} else if (!platformResultsReturned) {
543544
const sendEvidence =
@@ -559,14 +560,7 @@ export async function deliverOutboundPayloadsWithQueueCleanup(
559560
}
560561
await runCommitHooksAfterAck();
561562
if (queuedPostSendState === "acked") {
562-
emitTerminals(() =>
563-
failedOutboundAuditTerminals({
564-
payloadCount,
565-
results: deliveredResults,
566-
payloadOutcomes: auditPayloadOutcomes ?? [],
567-
failureStage: err instanceof OutboundDeliveryError ? err.stage : "platform_send",
568-
}),
569-
);
563+
emitFailedTerminals(platformSendFailureStage);
570564
}
571565
} else {
572566
const permanentRejection = findPlatformMessageRejectedError(err);
@@ -610,40 +604,57 @@ export async function deliverOutboundPayloadsWithQueueCleanup(
610604
if (queueAcked) {
611605
queuedPostSendState = "acked";
612606
await runCommitHooksAfterAck();
613-
emitTerminals(() =>
614-
failedOutboundAuditTerminals({
615-
payloadCount,
616-
results: deliveredResults,
617-
payloadOutcomes: auditPayloadOutcomes ?? [],
618-
failureStage: "platform_send",
619-
}),
620-
);
607+
emitFailedTerminals("platform_send");
621608
}
622609
}
623610
if (!terminalRejectionHandled) {
624-
const recordFailure = isProvenDeliveryNotSentError(err)
625-
? failDeliveryBeforePlatformSend
626-
: failDelivery;
627-
await recordOwnedQueueFailure(recordFailure, formatErrorMessage(err)).catch(
628-
(failErr: unknown) => {
611+
// A caller that resends this failure itself must not leave a row
612+
// behind: the recovery drain would send the same message again
613+
// behind that retry (#124279). Callers that only report the error
614+
// (CLI, gateway RPC) and durable completions keep their own owner,
615+
// so their rows stay replayable (#100979).
616+
const callerOwnsRetry =
617+
isProvenDeliveryNotSentError(err) &&
618+
params.deliveryRetryOwner === "caller" &&
619+
!params.deliveryCompletion;
620+
if (callerOwnsRetry) {
621+
try {
622+
throwIfProducerLeaseLost();
623+
// Claim-fenced removal: the row is gone, so nothing replays it.
624+
// That also retires recovery's chance to report this delivery,
625+
// so the terminal audit fact is owed right here.
626+
const spooled = await moveToFailed(
627+
queueId,
628+
platformQueueStateDir,
629+
producerClaimId ?? null,
630+
);
631+
await releaseSpoolArtifacts(spooled, platformQueueStateDir);
632+
emitFailedTerminals(platformSendFailureStage);
633+
} catch (failErr: unknown) {
634+
// Claim loss or a failed removal leaves the row with its owner;
635+
// no terminal is emitted because recovery still owns the entry.
629636
log.warn(
630-
`failed to mark queued delivery ${queueId} as failed: ${formatErrorMessage(failErr)}`,
637+
`failed to dead-letter queued delivery ${queueId} after proven-not-sent failure: ${formatErrorMessage(failErr)}`,
631638
);
632-
},
633-
);
639+
}
640+
} else {
641+
const recordFailure = isProvenDeliveryNotSentError(err)
642+
? failDeliveryBeforePlatformSend
643+
: failDelivery;
644+
await recordOwnedQueueFailure(recordFailure, formatErrorMessage(err)).catch(
645+
(failErr: unknown) => {
646+
log.warn(
647+
`failed to mark queued delivery ${queueId} as failed: ${formatErrorMessage(failErr)}`,
648+
);
649+
},
650+
);
651+
}
634652
}
635653
}
636654
}
637655
} else {
638656
flushMessageSentEvents();
639-
emitTerminals(() =>
640-
failedOutboundAuditTerminals({
641-
payloadCount,
642-
results: deliveredResults,
643-
payloadOutcomes: auditPayloadOutcomes ?? [],
644-
failureStage: err instanceof OutboundDeliveryError ? err.stage : "platform_send",
645-
}),
646-
);
657+
emitFailedTerminals(platformSendFailureStage);
647658
}
648659
throw err;
649660
}

0 commit comments

Comments
 (0)