diff --git a/docs/requirements/Component-NotificationOutbox.md b/docs/requirements/Component-NotificationOutbox.md
index 72fdb4c7..b07e68ba 100644
--- a/docs/requirements/Component-NotificationOutbox.md
+++ b/docs/requirements/Component-NotificationOutbox.md
@@ -111,6 +111,8 @@ The site→central handoff is **at-least-once**. Central ingests an inbound noti
Delivery has no row-level claim or lease: dispatchers read due rows and persist delivery status after sending. An interrupted delivery can therefore be sent again after failover. During a dual-active partition permitted by the auto-down policy, both central singletons can repeatedly select overlapping batches and deliver duplicate notifications across multiple sweeps; exposure is not limited to one notification or one handover. The `NotificationId` deduplication above protects ingestion, not external Email/SMS delivery. This remains an accepted at-least-once delivery limitation; there is no dispatcher fencing or exactly-once guarantee.
+A **graceful** handover no longer widens that window (NTF-1, 2026-12): the actor's shutdown token is passed to the channel adapter (so CoordinatedShutdown cuts an in-flight send short) but **not** to the write that records the adapter's outcome. Once the adapter has returned — for a success, after the relay accepted the message — the status write runs on its own token bounded by a 30 s timeout, and the audit rows are emitted the same way. Previously that write was cancelled with the shutdown token, the row stayed `Pending`/`Retrying` with no record of the send, and the new active node's first sweep sent the email or SMS again.
+
## Dispatcher
The dispatcher loop runs on a fixed interval. On each tick the `NotificationOutboxActor`:
diff --git a/src/ZB.MOM.WW.ScadaBridge.NotificationOutbox/NotificationOutboxActor.cs b/src/ZB.MOM.WW.ScadaBridge.NotificationOutbox/NotificationOutboxActor.cs
index 5d37cdcc..09823b53 100644
--- a/src/ZB.MOM.WW.ScadaBridge.NotificationOutbox/NotificationOutboxActor.cs
+++ b/src/ZB.MOM.WW.ScadaBridge.NotificationOutbox/NotificationOutboxActor.cs
@@ -683,7 +683,7 @@ public class NotificationOutboxActor : ReceiveActor, IWithTimers
notification.Status = NotificationStatus.Parked;
notification.LastError = missingAdapterError;
notification.LastAttemptAt = parkedAt;
- await WarnIfVanishedAsync(outboxRepository, notification, cancellationToken);
+ await WarnIfVanishedAsync(outboxRepository, notification);
await EmitAttemptAuditAsync(
notification,
parkedAt,
@@ -741,7 +741,12 @@ public class NotificationOutboxActor : ReceiveActor, IWithTimers
break;
}
- await WarnIfVanishedAsync(outboxRepository, notification, cancellationToken);
+ // NTF-1: from here on the shutdown token is NOT used. The adapter has returned an
+ // outcome — for a Success the email/SMS has already been accepted by the relay — so
+ // the write that records it must land even when a singleton handover cancelled the
+ // token mid-delivery. With the shutdown token the write threw, the row stayed
+ // Pending/Retrying with no record of the send, and the new active node re-sent it.
+ await WarnIfVanishedAsync(outboxRepository, notification);
// Emit the per-attempt Attempted row exactly once regardless of the
// outcome (B2). The error message comes from the outcome, not from
@@ -767,6 +772,14 @@ public class NotificationOutboxActor : ReceiveActor, IWithTimers
}
}
+ ///
+ /// Upper bound on the write that records a delivery outcome (NTF-1). That write runs on
+ /// its own token rather than the actor's shutdown token, so a handover cannot cancel the
+ /// record of a send that already happened; this keeps a wedged database from pinning a
+ /// stopping actor's delivery task forever. Settable for tests.
+ ///
+ internal static TimeSpan OutcomePersistTimeout { get; set; } = TimeSpan.FromSeconds(30);
+
///
/// Persists the dispatcher's delivery-state write and logs when the row has
/// VANISHED underneath it —
@@ -783,10 +796,12 @@ public class NotificationOutboxActor : ReceiveActor, IWithTimers
///
private async Task WarnIfVanishedAsync(
INotificationOutboxRepository repository,
- Notification notification,
- CancellationToken cancellationToken)
+ Notification notification)
{
- var persisted = await repository.UpdateAsync(notification, cancellationToken);
+ // Deliberately NOT the actor's shutdown token (NTF-1): this records an outcome the
+ // channel already produced, so it is bounded by its own timeout instead.
+ using var persistCts = new CancellationTokenSource(OutcomePersistTimeout);
+ var persisted = await repository.UpdateAsync(notification, persistCts.Token);
if (!persisted)
{
_logger.LogWarning(
diff --git a/tests/ZB.MOM.WW.ScadaBridge.NotificationOutbox.Tests/NotificationOutboxActorDispatchTests.cs b/tests/ZB.MOM.WW.ScadaBridge.NotificationOutbox.Tests/NotificationOutboxActorDispatchTests.cs
index a2aca4ee..1e34ac23 100644
--- a/tests/ZB.MOM.WW.ScadaBridge.NotificationOutbox.Tests/NotificationOutboxActorDispatchTests.cs
+++ b/tests/ZB.MOM.WW.ScadaBridge.NotificationOutbox.Tests/NotificationOutboxActorDispatchTests.cs
@@ -116,6 +116,69 @@ public class NotificationOutboxActorDispatchTests : TestKit
.Returns(new[] { config });
}
+ ///
+ /// Adapter whose send completes only when the test releases it, ignoring the cancellation
+ /// token — the shape of a relay that has already accepted the message when shutdown lands.
+ ///
+ private sealed class GatedAdapter : INotificationDeliveryAdapter
+ {
+ public readonly TaskCompletionSource Entered = new(TaskCreationOptions.RunContinuationsAsynchronously);
+ public readonly TaskCompletionSource Release = new(TaskCreationOptions.RunContinuationsAsynchronously);
+
+ ///
+ public NotificationType Type => NotificationType.Email;
+
+ ///
+ public async Task DeliverAsync(
+ Notification notification, CancellationToken cancellationToken = default)
+ {
+ Entered.TrySetResult();
+ await Release.Task;
+ return DeliveryOutcome.Success("ops@example.com");
+ }
+ }
+
+ ///
+ /// NTF-1 regression: the singleton is stopped (handover) while a send is in flight; the relay
+ /// has already accepted it. The Delivered write must still land — on a token the shutdown did
+ /// not cancel — or the next active node re-sends the email/SMS.
+ ///
+ /// A task that represents the asynchronous operation.
+ [Fact]
+ public async Task ShutdownMidDelivery_StillPersistsTheDeliveredOutcome()
+ {
+ SetupSmtpRetryPolicy(maxRetries: 5, retryDelay: TimeSpan.FromMinutes(1));
+ var notification = MakeNotification();
+ _outboxRepository.GetDueAsync(Arg.Any(), Arg.Any(), Arg.Any())
+ .Returns(new[] { notification });
+
+ // A real EF ExecuteUpdateAsync throws on a cancelled token; model that.
+ var persisted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
+ _outboxRepository.UpdateAsync(Arg.Any(), Arg.Any())
+ .Returns(ci =>
+ {
+ ((CancellationToken)ci[1]).ThrowIfCancellationRequested();
+ persisted.TrySetResult(((Notification)ci[0]).Status);
+ return Task.FromResult(true);
+ });
+
+ var adapter = new GatedAdapter();
+ var actor = CreateActor([adapter]);
+ Watch(actor);
+
+ actor.Tell(InternalMessages.DispatchTick.Instance);
+ await adapter.Entered.Task.WaitAsync(TimeSpan.FromSeconds(5));
+
+ // Handover: PostStop cancels the shutdown token while the send is in flight.
+ Sys.Stop(actor);
+ ExpectTerminated(actor);
+
+ adapter.Release.TrySetResult();
+
+ var status = await persisted.Task.WaitAsync(TimeSpan.FromSeconds(5));
+ Assert.Equal(NotificationStatus.Delivered, status);
+ }
+
/// Verifies that a dispatch tick claims due notifications and invokes the adapter.
[Fact]
public void DispatchTick_ClaimsDueNotifications_AndInvokesAdapter()