11// Owns queued delivery execution, custody transitions, and terminal cleanup.
2+ import type { AuditMessageFailureStage } from "../../audit/audit-event-types.js" ;
23import { hasTrustedMessageAuditListeners } from "../../audit/message-audit-events.js" ;
34import { createSubsystemLogger } from "../../logging/subsystem.js" ;
45import { getGlobalHookRunner } from "../../plugins/hook-runner-global.js" ;
@@ -26,11 +27,13 @@ import {
2627} from "./deliver-types.js" ;
2728import { runOutboundDeliveryCommitHooks } from "./delivery-commit-hooks.js" ;
2829import { rejectDurableDelivery , settleDurableDelivery } from "./delivery-completion.js" ;
30+ import { releaseSpoolArtifacts } from "./delivery-queue-media-spool.js" ;
2931import {
3032 failDelivery ,
3133 failDeliveryAfterPlatformSend ,
3234 failDeliveryBeforePlatformSend ,
3335 markDeliveryPlatformSendDispatched ,
36+ moveToFailed ,
3437} from "./delivery-queue-storage.js" ;
3538import { createMessageSentEmitter , type MessageSentEvent } from "./message-sent-hook.js" ;
3639import {
@@ -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