diff --git a/.claude/rules/cluster-topology.md b/.claude/rules/cluster-topology.md
index 830a70e4b..2d213b325 100644
--- a/.claude/rules/cluster-topology.md
+++ b/.claude/rules/cluster-topology.md
@@ -154,7 +154,7 @@ Things that carried over unchanged from the `ClusterClient` era, because they we
`DeploymentId` (re-acks if answered, ignores while applying / while its ack is held) — except a remembered
**Failed** ack, which it retries (#1111; only while that deployment is its latest answer and no other ack is held).
Central never lets a late `Failed` overwrite that node's arrived `Applied` for the same deployment (a stale
- duplicate); a late `Failed` that closes the deployment first is a documented residual. Re-sends carry
+ duplicate); a late `Failed` that would close the deployment first holds the PartiallyFailed seal ≤ 10 s when its node was re-sent to (#1114 — a retry's `Applied` slower than that is the residual). Re-sends carry
`DeadlineRemaining` (proto field 5, additive) so a late-reached node bounds its address-space wait to fit.
Remembered acks are in-memory only (a restarted node treats a re-send as fresh). The apply deadline and
boot-time replay remain the backstops. `docs/Redundancy.md` §"Dispatch re-send".
diff --git a/docs/Redundancy.md b/docs/Redundancy.md
index 2f30bac7a..dbe43044a 100644
--- a/docs/Redundancy.md
+++ b/docs/Redundancy.md
@@ -855,12 +855,23 @@ dial was dropped — either way the deployment sat until the 120 s deadline and
held for a persist retry. The late `Failed` is discarded before its row write (logged at Info), so neither the count
nor the node's `NodeDeploymentState` row flips back. The reverse is unchanged: an `Applied` arriving after a counted
`Failed` still replaces it, as long as the deployment is open.
-- **Residual: a late `Failed` that CLOSES the deployment first.** If the stale `Failed` reaches central before the
- retry's `Applied` and it completes the expected set (a one-node cluster, or the peer already acked), the deployment is
- marked `PartiallyFailed` at once and the retry's `Applied` is then discarded as a stale ack ("Discarding stale ApplyAck").
- The node runs the new revision, but central's `Deployment` row reads `PartiallyFailed` and that node's
- `NodeDeploymentState` row reads `Failed` (on a fused `Direct` node the node's own row write races central's, so it may
- read either). Deliberately NOT corrected after the fact: re-opening a terminal deployment would break
+- **A late `Failed` that would CLOSE the deployment first is held briefly (#1114).** If the stale `Failed` reaches
+ central before the retry's `Applied` and it completes the expected set (a one-node cluster, or the peer already
+ acked), the deployment used to be marked `PartiallyFailed` at once and the retry's `Applied` then discarded as a stale
+ ack — the node running the revision while central read `PartiallyFailed`. Now, when every `Failed` ack standing in the
+ way came from a node this deployment was **re-sent** to (so a retry may be in flight), `ConfigPublishCoordinator`
+ holds the `PartiallyFailed` seal for a grace (`DefaultFailedSealGrace` = 10 s, capped by what is left of the apply
+ deadline; logged at Info). An `Applied` from that node inside the grace replaces its `Failed` (the rule above) and
+ the deployment seals; otherwise it closes `PartiallyFailed` when the grace ends — once per deployment. A `Failed`
+ from a node that was never re-sent to (no retry can be coming) closes at once as before, as does a deployment
+ recovered by a new coordinator incarnation (it has re-sent nothing). Costs: a genuinely failed re-sent node's
+ `PartiallyFailed` lands up to 10 s later, and for those seconds the deployment is still in flight (a new deploy is
+ refused `AnotherDeploymentInFlight`).
+- **Residual: a retry slower than the grace.** If the retry's `Applied` arrives after the grace (a large apply, or
+ its address-space wait), the deployment is already `PartiallyFailed` and the `Applied` is discarded as stale
+ ("Discarding stale ApplyAck"): the node runs the new revision, but central's `Deployment` row reads `PartiallyFailed`
+ and that node's `NodeDeploymentState` row reads `Failed` (on a fused `Direct` node the node's own row write races
+ central's, so it may read either). Deliberately NOT corrected after the fact: re-opening a terminal deployment would break
"a terminal outcome is written once" (review L8), sealing it late would give an older deployment a newer
`SealedAtUtc` than one dispatched since — and "latest sealed" drives drift detection and the publish fallback — and
the coordinator keeps no per-deployment state past closure to judge it with. It needs a re-send to reach the node
@@ -868,7 +879,10 @@ dial was dropped — either way the deployment sat until the 120 s deadline and
same revision short-circuits to `Applied` on a node whose address space is confirmed, and re-applies otherwise).
- **A re-send carries what is left of the deadline (#1111).** `DispatchDeployment.DeadlineRemaining` (proto
`optional int64 deadline_remaining_ms = 5`, additive) is set on every re-send — a RELATIVE duration, so central's
- and the node's clocks need not agree — and left unset on the original. A node whose apply was started by such a
+ and the node's clocks need not agree — and left unset on the original. Central measures it (and the re-send
+ window, the persist-deferral cap and the failed-seal grace) on a **monotonic** clock (`TimeProvider.GetTimestamp`,
+ #1114), so a wall-clock step on central cannot stretch or collapse it; only crash recovery, which must compare
+ against the persisted `Deployment.CreatedAtUtc`, uses the wall clock. A node whose apply was started by such a
re-send bounds its held Applied ack's address-space wait to `DeadlineRemaining − 15 s` measured from **receipt**
(so the artifact read and reconcile count against it; floor 1 s), instead of the full 105 s. A node first reached
by the +35 s re-send (~85 s left) therefore releases an "outcome not reported in time" ack at ~70 s and the
diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/Coordinators/ConfigPublishCoordinator.cs b/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/Coordinators/ConfigPublishCoordinator.cs
index 41f32fff2..9dd1db756 100644
--- a/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/Coordinators/ConfigPublishCoordinator.cs
+++ b/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/Coordinators/ConfigPublishCoordinator.cs
@@ -113,6 +113,13 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU
/// Ceiling of the recovery-load retry backoff (lmxopcua#868).
public static readonly TimeSpan DefaultLoadRetryMax = TimeSpan.FromSeconds(30);
+ ///
+ /// #1114: how long a deployment whose last ack is a Failed from a node it was RE-SENT to waits for that
+ /// node's retry Applied before it is marked PartiallyFailed (capped by what is left of the apply deadline).
+ /// The late original Failed of a node whose retry succeeded used to close the deployment first.
+ ///
+ public static readonly TimeSpan DefaultFailedSealGrace = TimeSpan.FromSeconds(10);
+
///
/// #1107: the delays between successive dispatch RE-SENDS to nodes that have not acked — re-sends at
/// +5 s, +15 s and +35 s after the dispatch. Each re-send is also bounded by
@@ -138,15 +145,43 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU
/// #1107: how many re-sends of have gone out.
private int _redispatchAttempts;
- /// #1107: no re-send is scheduled to fire after this instant (a fraction of the apply deadline).
- private DateTime _redispatchWindowEndsUtc;
+ ///
+ /// #1114: the monotonic clock every in-memory deadline / elapsed computation is measured on
+ /// (), so a wall-clock step (NTP correction, manual change) can neither
+ /// stretch nor collapse the re-send window, the a re-send
+ /// reports, the persist-deferral cap or the failed-seal grace. Only the recovery path compares against
+ /// Deployment.CreatedAtUtc on the wall clock — a persisted instant has no monotonic counterpart.
+ ///
+ private readonly TimeProvider _time;
+
+ /// #1114: monotonic timestamp at which the current deployment's apply deadline was armed.
+ private long _deadlineArmedAt;
///
- /// #1111: when the current deployment's apply deadline falls (as armed; a later persist-deferral only
- /// lengthens it, so the remaining time a re-send reports is never an over-estimate). Each re-send carries
- /// computed from it.
+ /// #1111/#1114: the apply deadline as armed (a later persist-deferral only lengthens it, so the remaining time a
+ /// re-send reports is never an over-estimate). measures from .
///
- private DateTime _redispatchDeadlineUtc;
+ private TimeSpan _deadlineAtArm;
+
+ /// #1107: no re-send is scheduled to fire once this much of the armed deadline has elapsed.
+ private TimeSpan _redispatchWindow;
+
+ ///
+ /// #1114: the expected nodes the CURRENT deployment has been re-sent to. A node in this set whose ack is
+ /// Failed may have a retry in flight (#1111: a re-send of a deployment the node remembers as Failed is
+ /// retried), so a Failed ack from it that would complete the set holds the PartiallyFailed seal for
+ /// .
+ ///
+ private readonly HashSet _resentTo = new(NodeIdComparer);
+
+ /// #1114: how long a would-be PartiallyFailed seal waits for a re-sent node's retry; zero disables it.
+ private readonly TimeSpan _failedSealGrace;
+
+ /// #1114: a PartiallyFailed seal is currently held for a re-sent node's retry.
+ private bool _failedSealHeld;
+
+ /// #1114: the current deployment's one failed-seal grace has run out — never granted twice.
+ private bool _failedSealGraceSpent;
private readonly TimeSpan _applyDeadline;
private readonly TimeSpan _loadRetryMin;
private readonly TimeSpan _loadRetryMax;
@@ -185,7 +220,7 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU
private readonly Dictionary _memoryOnlyAcks = new(NodeIdComparer);
/// When the current deadline was first deferred on an unpersisted ack (bounds the deferral).
- private DateTime? _deadlineDeferredSinceUtc;
+ private long? _deadlineDeferredSince;
/// How long a deadline may wait on unpersisted acks before deciding from memory (10 × the retry ceiling).
private TimeSpan MaxDeadlineDeferral => TimeSpan.FromTicks(_loadRetryMax.Ticks * 10);
@@ -273,6 +308,11 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU
/// #1107: delays between dispatch re-sends to un-acked nodes; =
/// , empty = never re-send.
///
+ ///
+ /// #1114: how long a would-be PartiallyFailed seal waits for a re-sent node's retry; =
+ /// , = never hold.
+ ///
+ /// #1114: the monotonic clock; = .
/// The Akka.NET used to spawn this actor.
public static Props Props(
IDbContextFactory dbFactory,
@@ -281,11 +321,13 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU
ConfigPublishCoordinatorReadiness? readiness = null,
TimeSpan? loadRetryMin = null,
TimeSpan? loadRetryMax = null,
- IReadOnlyList? redispatchSchedule = null) =>
+ IReadOnlyList? redispatchSchedule = null,
+ TimeSpan? failedSealGrace = null,
+ TimeProvider? timeProvider = null) =>
Akka.Actor.Props.Create(() => new ConfigPublishCoordinator(
dbFactory, applyDeadline ?? DefaultApplyDeadline, meshRouter, readiness,
loadRetryMin ?? DefaultLoadRetryMin, loadRetryMax ?? DefaultLoadRetryMax,
- redispatchSchedule ?? DefaultRedispatchSchedule));
+ redispatchSchedule ?? DefaultRedispatchSchedule, failedSealGrace, timeProvider));
///
/// Initializes a new instance of the class.
@@ -297,6 +339,8 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU
/// First recovery-load retry delay.
/// Recovery-load retry ceiling.
/// #1107 re-send delays; = .
+ /// #1114 failed-seal grace; = .
+ /// #1114 monotonic clock; = .
public ConfigPublishCoordinator(
IDbContextFactory dbFactory,
TimeSpan applyDeadline,
@@ -304,9 +348,14 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU
ConfigPublishCoordinatorReadiness? readiness = null,
TimeSpan? loadRetryMin = null,
TimeSpan? loadRetryMax = null,
- IReadOnlyList? redispatchSchedule = null)
+ IReadOnlyList? redispatchSchedule = null,
+ TimeSpan? failedSealGrace = null,
+ TimeProvider? timeProvider = null)
{
_redispatchSchedule = redispatchSchedule ?? DefaultRedispatchSchedule;
+ var grace = failedSealGrace ?? DefaultFailedSealGrace;
+ _failedSealGrace = grace > TimeSpan.Zero ? grace : TimeSpan.Zero;
+ _time = timeProvider ?? TimeProvider.System;
_dbFactory = dbFactory;
_applyDeadline = applyDeadline;
_meshRouter = meshRouter;
@@ -349,6 +398,7 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU
Receive(HandleRetryAckPersist);
Receive(HandleDeadline);
Receive(HandleRedispatchTick);
+ Receive(HandleFailedSealGraceElapsed);
Receive(_ => { /* DPS subscribe confirmation */ });
// A late load outcome / retry tick cannot normally arrive once Ready; ignored, never stashed.
Receive(_ => { });
@@ -876,11 +926,13 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU
Timers.Cancel(RedispatchTimerKey);
_resendable = null;
_redispatchAttempts = 0;
+ // #1114: recorded even when no re-send is armed — the failed-seal grace is capped by it too.
+ _deadlineArmedAt = _time.GetTimestamp();
+ _deadlineAtArm = deadlineLeft;
+ _redispatchWindow = TimeSpan.FromTicks((long)(deadlineLeft.Ticks * RedispatchWindowFraction));
if (_expectedAcks.Count == 0 || _redispatchSchedule.Count == 0 || deadlineLeft <= TimeSpan.Zero) return;
_resendable = dispatch;
- _redispatchDeadlineUtc = DateTime.UtcNow + deadlineLeft;
- _redispatchWindowEndsUtc = DateTime.UtcNow + TimeSpan.FromTicks((long)(deadlineLeft.Ticks * RedispatchWindowFraction));
ScheduleNextRedispatch();
}
@@ -893,7 +945,7 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU
return;
}
var delay = _redispatchSchedule[_redispatchAttempts];
- if (DateTime.UtcNow + delay > _redispatchWindowEndsUtc)
+ if (_time.GetElapsedTime(_deadlineArmedAt) + delay > _redispatchWindow)
{
_resendable = null;
return;
@@ -936,7 +988,8 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU
ZB.MOM.WW.OtOpcUa.Commons.Observability.OtOpcUaTelemetry.DeploymentRedispatched.Add(outstanding.Count);
// #1111: tell the node how much of the deadline is left, so a node first reached by a late re-send bounds its
// address-space wait to fit inside it (it would otherwise wait its full 105 s and miss the deadline).
- var deadlineRemaining = _redispatchDeadlineUtc - DateTime.UtcNow;
+ var deadlineRemaining = DeadlineLeft();
+ foreach (var node in outstanding) _resentTo.Add(NodeId.Parse(node));
PublishDispatch(dispatch with
{
TargetNodes = outstanding,
@@ -945,6 +998,9 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU
ScheduleNextRedispatch();
}
+ /// #1114: what is left of the current deployment's apply deadline as armed, on the monotonic clock.
+ private TimeSpan DeadlineLeft() => _deadlineAtArm - _time.GetElapsedTime(_deadlineArmedAt);
+
/// Whether 's ack for the CURRENT deployment has arrived (counted or not yet persisted).
private bool AckReceivedFrom(NodeId node) =>
_acks.ContainsKey(node)
@@ -1097,7 +1153,7 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU
// A deadline that was deferred on unpersisted acks decides as soon as the last write lands, rather than
// waiting out its re-armed delay.
- if (_deadlineDeferredSinceUtc is not null && _unpersisted.Count == 0 && InFlightForCurrent() == 0)
+ if (_deadlineDeferredSince is not null && _unpersisted.Count == 0 && InFlightForCurrent() == 0)
{
Timers.Cancel(DeadlineTimerKey);
Self.Tell(new DeadlineElapsed(_current.Value));
@@ -1218,14 +1274,73 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU
}
/// Seals (all Applied) or marks partially failed — called once every expected ack is in.
- private void CompleteFromAcks()
+ ///
+ /// #1114: whether a would-be PartiallyFailed may be held for a re-sent node's retry (false once the grace or the
+ /// deadline has run out).
+ ///
+ private void CompleteFromAcks(bool allowGrace = true)
{
if (_acks.Values.All(o => o == ApplyAckOutcome.Applied))
SealDeployment();
+ else if (allowGrace && HoldFailedSeal())
+ return;
else
MarkPartiallyFailed();
}
+ ///
+ /// #1114: the residual #1111 left — a node's ORIGINAL Failed ack, delivered late, completes the expected
+ /// set while that node's re-send retry is still applying, so the deployment closed PartiallyFailed and the retry's
+ /// Applied was then discarded as stale although the node runs the revision. When every Failed ack that
+ /// stands in the way came from a node this deployment was RE-SENT to (so a retry may be in flight), the
+ /// PartiallyFailed seal is held for (capped by what is left of the apply deadline):
+ /// an Applied from that node inside the grace replaces its Failed (the existing Applied-after-Failed rule)
+ /// and the deployment seals. Nothing is reopened — the deployment simply stays open a few seconds longer. A Failed
+ /// from a node that was never re-sent to cannot have a retry coming, so it closes at once, as before (and so does
+ /// a recovered deployment: a new incarnation has re-sent nothing yet).
+ ///
+ /// when the seal is (still) held.
+ private bool HoldFailedSeal()
+ {
+ var failed = _acks.Where(kv => kv.Value == ApplyAckOutcome.Failed).Select(kv => kv.Key).ToList();
+ var retryPossible = _failedSealGrace > TimeSpan.Zero
+ && failed.Count > 0
+ && failed.All(_resentTo.Contains);
+ if (!retryPossible)
+ {
+ // A held seal whose premise is gone (e.g. a Failed from a node never re-sent to) closes now.
+ if (_failedSealHeld) Timers.Cancel(FailedSealGraceTimerKey);
+ _failedSealHeld = false;
+ return false;
+ }
+ if (_failedSealHeld) return true; // already waiting: the grace timer, the deadline or an Applied decides
+ if (_failedSealGraceSpent) return false; // one grace per deployment
+
+ var left = DeadlineLeft();
+ var grace = _failedSealGrace < left ? _failedSealGrace : left;
+ if (grace <= TimeSpan.Zero) return false;
+
+ _failedSealHeld = true;
+ Timers.StartSingleTimer(FailedSealGraceTimerKey, new FailedSealGraceElapsed(_current!.Value), grace);
+ _log.Info(
+ "Deployment {Id}: every ack is in but {Nodes} acked Failed after being re-sent the dispatch — holding the " +
+ "PartiallyFailed seal {Grace} for a retry's Applied (a late original Failed can overtake it)",
+ _current, string.Join(", ", failed.Select(n => n.Value).Order(StringComparer.OrdinalIgnoreCase)), grace);
+ return true;
+ }
+
+ /// #1114: the failed-seal grace ran out with no Applied from the re-sent node(s): close as PartiallyFailed.
+ private void HandleFailedSealGraceElapsed(FailedSealGraceElapsed msg)
+ {
+ if (_current != msg.DeploymentId || !_failedSealHeld) return;
+ _failedSealHeld = false;
+ _failedSealGraceSpent = true;
+ // An Applied from a Failed node that ARRIVED but is still being persisted completes the deployment itself when
+ // its write lands (HandleAckPersisted), so it is not closed out from under it here.
+ if (_acks.Where(kv => kv.Value == ApplyAckOutcome.Failed).Any(kv => HasAppliedAckFrom(kv.Key))) return;
+ if (_expectedAcks.Count > 0 && _acks.Count == _expectedAcks.Count) CompleteFromAcks(allowGrace: false);
+ }
+
private static string AckRetryTimerKey(NodeId node) => $"ack-retry:{node.Value.ToUpperInvariant()}";
/// Writes one node's ack row. Static and touching no actor state: it runs on a pool thread (#996 / H-6).
@@ -1319,8 +1434,8 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU
// #996 / H-6: kick the whole backlog off-thread at once (the connect timeouts overlap, they no longer
// serialise on this thread); the deadline is re-armed below and also fires early once the last write lands.
foreach (var pending in _unpersisted.Values.ToList()) StartAckPersist(pending.Ack);
- _deadlineDeferredSinceUtc ??= DateTime.UtcNow;
- var capped = DateTime.UtcNow - _deadlineDeferredSinceUtc.Value >= MaxDeadlineDeferral;
+ _deadlineDeferredSince ??= _time.GetTimestamp();
+ var capped = _time.GetElapsedTime(_deadlineDeferredSince.Value) >= MaxDeadlineDeferral;
if (capped)
{
// Third review #1: bounded. Past the cap the outcome is decided from what was RECEIVED — the nodes did
@@ -1357,8 +1472,9 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU
if (_expectedAcks.Count > 0 && _acks.Count == _expectedAcks.Count)
{
// Every ack is in but nothing completed it (a completion normally resets _current, so the stale-id
- // check above catches the ack-vs-deadline race). Complete it rather than leave it in flight forever.
- CompleteFromAcks();
+ // check above catches the ack-vs-deadline race). Complete it rather than leave it in flight forever —
+ // and at the deadline a held failed-seal grace (#1114) ends too.
+ CompleteFromAcks(allowGrace: false);
return;
}
@@ -1434,7 +1550,12 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU
Timers.Cancel(RedispatchTimerKey);
_resendable = null;
_redispatchAttempts = 0;
- _deadlineDeferredSinceUtc = null;
+ _deadlineDeferredSince = null;
+ // #1114: the failed-seal grace never outlives its deployment either.
+ Timers.Cancel(FailedSealGraceTimerKey);
+ _failedSealHeld = false;
+ _failedSealGraceSpent = false;
+ _resentTo.Clear();
foreach (var node in _unpersisted.Keys) Timers.Cancel(AckRetryTimerKey(node));
if (_unpersisted.Count > 0)
{
@@ -1462,6 +1583,10 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU
private const string DeadlineTimerKey = "apply-deadline";
private const string LoadRetryTimerKey = "recovery-load-retry";
private const string RedispatchTimerKey = "redispatch";
+ private const string FailedSealGraceTimerKey = "failed-seal-grace";
+
+ /// #1114: the failed-seal grace for this deployment has run out.
+ private sealed record FailedSealGraceElapsed(DeploymentId DeploymentId);
/// #1107: time to re-send the current dispatch to the nodes that have not acked it.
private sealed record RedispatchTick(DeploymentId DeploymentId);
diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/ConfigPublishCoordinatorRedispatchTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/ConfigPublishCoordinatorRedispatchTests.cs
index 21e2ea4b3..95d0907ea 100644
--- a/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/ConfigPublishCoordinatorRedispatchTests.cs
+++ b/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/ConfigPublishCoordinatorRedispatchTests.cs
@@ -250,6 +250,166 @@ public sealed class ConfigPublishCoordinatorRedispatchTests : ControlPlaneActorT
router.ExpectNoMsg(TimeSpan.FromMilliseconds(500), TestContext.Current.CancellationToken);
}
+ [Fact]
+ public void A_late_Failed_from_a_resent_node_holds_the_seal_for_the_retrys_Applied()
+ {
+ // #1114 (the #1111 residual): the node's ORIGINAL Failed was delayed, central re-sent, the node retried — and the
+ // late Failed reached central first, completing the set. It used to close the deployment PartiallyFailed at once
+ // and discard the retry's Applied as stale. The seal is now held for a short grace, so the Applied wins.
+ var dbFactory = NewInMemoryDbFactory();
+ var deploymentId = SeedDispatchingDeployment(dbFactory);
+ SeedNodes(dbFactory, "site-a-1:4053");
+ var router = CreateTestProbe();
+ var actor = Sys.ActorOf(ConfigPublishCoordinator.Props(
+ dbFactory, NoTimeout, router.Ref, redispatchSchedule: Every(TimeSpan.FromMilliseconds(150), 1),
+ failedSealGrace: TimeSpan.FromSeconds(30)));
+ actor.Tell(new DispatchDeployment(deploymentId, TestRevision, CorrelationId.NewId()));
+ ExpectDispatch(router).IsResend.ShouldBeFalse();
+ ExpectDispatch(router).TargetNodes.ShouldBe(["site-a-1:4053"]); // the re-send went out
+
+ actor.Tell(new ApplyAck(deploymentId, NodeId.Parse("site-a-1:4053"), ApplyAckOutcome.Failed, "fetch failed", CorrelationId.NewId()));
+ // The Failed is persisted (counted) — but the deployment stays open.
+ AwaitNodeStatus(dbFactory, "site-a-1:4053", NodeDeploymentStatus.Failed);
+ Thread.Sleep(400);
+ DeploymentRow(dbFactory, deploymentId).Status.ShouldBe(DeploymentStatus.AwaitingApplyAcks);
+
+ actor.Tell(new ApplyAck(deploymentId, NodeId.Parse("site-a-1:4053"), ApplyAckOutcome.Applied, null, CorrelationId.NewId()));
+ AwaitStatus(dbFactory, DeploymentStatus.Sealed);
+ AwaitNodeStatus(dbFactory, "site-a-1:4053", NodeDeploymentStatus.Applied);
+ }
+
+ [Fact]
+ public void A_held_failed_seal_closes_PartiallyFailed_when_the_grace_runs_out()
+ {
+ var dbFactory = NewInMemoryDbFactory();
+ var deploymentId = SeedDispatchingDeployment(dbFactory);
+ SeedNodes(dbFactory, "site-a-1:4053");
+ var router = CreateTestProbe();
+ var actor = Sys.ActorOf(ConfigPublishCoordinator.Props(
+ dbFactory, NoTimeout, router.Ref, redispatchSchedule: Every(TimeSpan.FromMilliseconds(150), 1),
+ failedSealGrace: TimeSpan.FromMilliseconds(1500)));
+ actor.Tell(new DispatchDeployment(deploymentId, TestRevision, CorrelationId.NewId()));
+ ExpectDispatch(router);
+ ExpectDispatch(router).IsResend.ShouldBeTrue();
+
+ var sw = System.Diagnostics.Stopwatch.StartNew();
+ actor.Tell(new ApplyAck(deploymentId, NodeId.Parse("site-a-1:4053"), ApplyAckOutcome.Failed, "boom", CorrelationId.NewId()));
+ AwaitNodeStatus(dbFactory, "site-a-1:4053", NodeDeploymentStatus.Failed);
+ DeploymentRow(dbFactory, deploymentId).Status.ShouldBe(DeploymentStatus.AwaitingApplyAcks); // held...
+ AwaitStatus(dbFactory, DeploymentStatus.PartiallyFailed); // ...then closed
+ sw.Elapsed.ShouldBeGreaterThan(TimeSpan.FromMilliseconds(1200));
+ }
+
+ [Fact]
+ public void A_Failed_from_a_node_that_was_never_resent_to_closes_at_once()
+ {
+ // No re-send ⇒ no retry can be coming ⇒ no hold (the grace here is long enough to time the test out).
+ var dbFactory = NewInMemoryDbFactory();
+ var deploymentId = SeedDispatchingDeployment(dbFactory);
+ SeedNodes(dbFactory, "site-a-1:4053");
+ var router = CreateTestProbe();
+ var actor = Sys.ActorOf(ConfigPublishCoordinator.Props(
+ dbFactory, NoTimeout, router.Ref, redispatchSchedule: Every(TimeSpan.FromMinutes(1), 1),
+ failedSealGrace: TimeSpan.FromMinutes(1)));
+ actor.Tell(new DispatchDeployment(deploymentId, TestRevision, CorrelationId.NewId()));
+ ExpectDispatch(router);
+ actor.Tell(new ApplyAck(deploymentId, NodeId.Parse("site-a-1:4053"), ApplyAckOutcome.Failed, "boom", CorrelationId.NewId()));
+ AwaitStatus(dbFactory, DeploymentStatus.PartiallyFailed);
+ }
+
+ [Fact]
+ public void A_Failed_from_a_node_never_resent_to_is_not_held_by_a_resent_peers_Failed()
+ {
+ // Two Failed nodes, only one of them re-sent to: the other's Failed cannot be repaired by a retry, so the
+ // deployment closes at once.
+ var dbFactory = NewInMemoryDbFactory();
+ var deploymentId = SeedDispatchingDeployment(dbFactory);
+ SeedNodes(dbFactory, "site-a-1:4053", "site-a-2:4053");
+ var router = CreateTestProbe();
+ var actor = Sys.ActorOf(ConfigPublishCoordinator.Props(
+ dbFactory, NoTimeout, router.Ref, redispatchSchedule: Every(TimeSpan.FromMilliseconds(300), 1),
+ failedSealGrace: TimeSpan.FromMinutes(1)));
+ actor.Tell(new DispatchDeployment(deploymentId, TestRevision, CorrelationId.NewId()));
+ ExpectDispatch(router);
+ actor.Tell(new ApplyAck(deploymentId, NodeId.Parse("site-a-2:4053"), ApplyAckOutcome.Failed, "boom", CorrelationId.NewId()));
+ ExpectDispatch(router).TargetNodes.ShouldBe(["site-a-1:4053"]);
+ actor.Tell(new ApplyAck(deploymentId, NodeId.Parse("site-a-1:4053"), ApplyAckOutcome.Failed, "boom", CorrelationId.NewId()));
+ AwaitStatus(dbFactory, DeploymentStatus.PartiallyFailed);
+ }
+
+ [Fact]
+ public void A_zero_grace_disables_the_hold()
+ {
+ var dbFactory = NewInMemoryDbFactory();
+ var deploymentId = SeedDispatchingDeployment(dbFactory);
+ SeedNodes(dbFactory, "site-a-1:4053");
+ var router = CreateTestProbe();
+ var actor = Sys.ActorOf(ConfigPublishCoordinator.Props(
+ dbFactory, NoTimeout, router.Ref, redispatchSchedule: Every(TimeSpan.FromMilliseconds(150), 1),
+ failedSealGrace: TimeSpan.Zero));
+ actor.Tell(new DispatchDeployment(deploymentId, TestRevision, CorrelationId.NewId()));
+ ExpectDispatch(router);
+ ExpectDispatch(router).IsResend.ShouldBeTrue();
+ actor.Tell(new ApplyAck(deploymentId, NodeId.Parse("site-a-1:4053"), ApplyAckOutcome.Failed, "boom", CorrelationId.NewId()));
+ AwaitStatus(dbFactory, DeploymentStatus.PartiallyFailed);
+ }
+
+ [Fact]
+ public void The_remaining_deadline_and_the_resend_window_run_on_the_monotonic_clock()
+ {
+ // #1114: DeadlineRemaining used to be computed from DateTime.UtcNow, so a wall-clock step moved it. It is now
+ // measured on TimeProvider.GetTimestamp: the fake's monotonic counter is frozen while its wall clock jumps a
+ // day, and the first re-send reports EXACTLY the armed deadline; advancing the monotonic counter 20 s is what
+ // (and the only thing that) shrinks the second.
+ var deadline = TimeSpan.FromSeconds(60);
+ var clock = new SteppableClock();
+ var dbFactory = NewInMemoryDbFactory();
+ var deploymentId = SeedDispatchingDeployment(dbFactory);
+ SeedNodes(dbFactory, "site-a-1:4053");
+ var router = CreateTestProbe();
+ Sys.ActorOf(ConfigPublishCoordinator.Props(
+ dbFactory, deadline, router.Ref, redispatchSchedule: Every(TimeSpan.FromMilliseconds(300), 4),
+ timeProvider: clock))
+ .Tell(new DispatchDeployment(deploymentId, TestRevision, CorrelationId.NewId()));
+
+ ExpectDispatch(router).DeadlineRemaining.ShouldBeNull();
+ clock.WallOffset = TimeSpan.FromDays(1); // a wall-clock jump forward: must change nothing
+ ExpectDispatch(router).DeadlineRemaining.ShouldBe(deadline);
+ clock.WallOffset = -TimeSpan.FromDays(2); // ...or backward
+ clock.Advance(TimeSpan.FromSeconds(20));
+ ExpectDispatch(router).DeadlineRemaining.ShouldBe(TimeSpan.FromSeconds(40));
+
+ // The re-send window (half the deadline = 30 s) is monotonic too: the third re-send was scheduled at 20 s (fits);
+ // at 35 s it reports 25 s left and the fourth schedule entry is NOT armed (35 s + 300 ms is past the window).
+ clock.Advance(TimeSpan.FromSeconds(15));
+ ExpectDispatch(router).DeadlineRemaining.ShouldBe(TimeSpan.FromSeconds(25));
+ router.ExpectNoMsg(TimeSpan.FromMilliseconds(800), TestContext.Current.CancellationToken);
+ }
+
+ /// A whose monotonic counter moves only when told, and whose wall clock can jump.
+ private sealed class SteppableClock : TimeProvider
+ {
+ private long _ticks = 1_000_000;
+ public TimeSpan WallOffset { get; set; }
+ public void Advance(TimeSpan by) => Interlocked.Add(ref _ticks, by.Ticks);
+ public override long TimestampFrequency => TimeSpan.TicksPerSecond;
+ public override long GetTimestamp() => Interlocked.Read(ref _ticks);
+ public override DateTimeOffset GetUtcNow() => DateTimeOffset.UtcNow + WallOffset;
+ }
+
+ private static Deployment DeploymentRow(IDbContextFactory dbFactory, DeploymentId id)
+ {
+ using var db = dbFactory.CreateDbContext();
+ return db.Deployments.AsNoTracking().Single(x => x.DeploymentId == id.Value);
+ }
+
+ private void AwaitNodeStatus(IDbContextFactory dbFactory, string node, NodeDeploymentStatus status) =>
+ AwaitAssert(() =>
+ {
+ using var db = dbFactory.CreateDbContext();
+ db.NodeDeploymentStates.Single(s => s.NodeId == node).Status.ShouldBe(status);
+ }, duration: Wait, cancellationToken: TestContext.Current.CancellationToken);
+
private static DispatchDeployment ExpectDispatch(TestProbe router)
{
var cmd = router.ExpectMsg(Wait, cancellationToken: TestContext.Current.CancellationToken);