From f5485f57d834153c7cdef3ec1320467d4bfc1f35 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Sat, 5 Dec 2026 00:24:49 -0500 Subject: [PATCH 1/3] fix(deploy): #1111 retry a lost Failed ack on re-send; re-sends carry the remaining deadline MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1. Node (DriverHostActor): a coordinator re-send of a deployment whose remembered ack is Failed now RE-ATTEMPTS the apply instead of replaying Failed — a failed apply left the node on last-good config, and a fetch failure and a lost ack usually share a cause. Once per re-send (a copy mid-retry is dropped by Applying), and only while that deployment is still the node's latest answer with no other ack held, so a stale re-send of an OLDER failed deployment replays Failed rather than rolling back a newer apply. Applied / Applied+degraded keep the replay (#601 unchanged). 2. DispatchDeployment gains additive DeadlineRemaining (proto optional int64 deadline_remaining_ms = 5), set by ConfigPublishCoordinator on every re-send (relative, no clock agreement needed), unset on the original. A node whose apply was started by a re-send bounds its held Applied ack's address-space wait to remaining - 15 s from receipt (floor 1 s), so a node first reached at +35 s acks Applied (degraded) before central's deadline instead of sealing TimedOut. Old central -> field absent -> full 105 s (today); old node ignores the field (limit documented). 3. Docs: remembered acks are in memory only (restart/supervision restart forgets them); Redundancy.md §Dispatch re-send + cluster-topology rule updated. Tests: Failed-ack retry + later replay, stale older-failed guard with positive control, re-send deadline bound with original-dispatch positive control (both behaviour tests verified to fail with the change disabled), mapper presence round-trip, coordinator DeadlineRemaining countdown. --- .claude/rules/cluster-topology.md | 5 +- docs/Redundancy.md | 33 ++++- .../Messages/Deploy/DispatchDeployment.cs | 15 +- .../Messages/Mesh/MeshTransportDtoMapper.cs | 7 +- .../Protos/mesh_transport.proto | 5 + .../Coordinators/ConfigPublishCoordinator.cs | 21 ++- .../Drivers/DriverHostActor.cs | 79 +++++++++- .../MeshTransportDtoMapperTests.cs | 24 ++++ ...ConfigPublishCoordinatorRedispatchTests.cs | 25 ++++ .../Drivers/DriverHostActorRedispatchTests.cs | 136 ++++++++++++++++++ 10 files changed, 335 insertions(+), 15 deletions(-) diff --git a/.claude/rules/cluster-topology.md b/.claude/rules/cluster-topology.md index ed2cc51bd..f91d99a30 100644 --- a/.claude/rules/cluster-topology.md +++ b/.claude/rules/cluster-topology.md @@ -151,7 +151,10 @@ Things that carried over unchanged from the `ClusterClient` era, because they we within half the deadline) to the expected nodes whose ack has not arrived, via `DispatchDeployment.TargetNodes` — central's gRPC fan dials only those; on DPS the others ignore it. ⚠️ Never re-send to an acked node (#601: a same-revision dispatch re-applies a degraded revision); the node treats a re-send idempotently per - `DeploymentId` (re-acks if answered, ignores while applying / while its ack is held). The apply deadline and + `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). 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". The old `buffer-size = 0` decision this section used to describe is gone with the HOCON block that set it; the gRPC transport has nothing to buffer in the first place — a dial either lands or doesn't. diff --git a/docs/Redundancy.md b/docs/Redundancy.md index 08ec70247..6d1f01ba4 100644 --- a/docs/Redundancy.md +++ b/docs/Redundancy.md @@ -837,16 +837,41 @@ dial was dropped — either way the deployment sat until the 120 s deadline and 16 deployments) instead of applying again — so a lost ack is recovered and a duplicate ack is harmless (the coordinator re-persists the same outcome, or discards it as stale). An ORIGINAL dispatch is unchanged: re-dispatching a degraded revision still re-applies. +- **…except a lost `Failed` ack, which is RETRIED (#1111).** A failed apply leaves the node on its last-good + configuration, and the failure and the lost ack usually share a cause (a central blip during the fetch), so on a + re-send of a deployment whose remembered ack is `Failed` the node re-attempts the apply instead of replaying + `Failed`. Once per re-send, never concurrently (a copy arriving mid-retry is dropped as in-flight), and only while + that deployment is still the node's **latest** answer with no other apply's ack held — a stale re-send of an older + failed deployment after a newer one was applied replays `Failed` rather than rolling the node back. `Applied` and + `Applied`+degraded acks keep the replay, so #601's "no repeated re-apply of a degraded revision on re-sends" holds. +- **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 + 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 + deployment seals "Applied (degraded)" rather than `TimedOut`. Wire compatibility: an old central never sets the + field (absent ⇒ the node's full default wait, today's behaviour); an old node ignores it (gRPC unknown field / DPS + JSON extra member) and keeps its 105 s wait — the pre-#1111 limit below applies to it. Residual: a re-send for a + *different* deployment that arrives while the node is still applying another is stashed, and its wait is measured + from when it is unstashed, not received — that only happens when the node is applying a deployment central has + already superseded. - **Residuals.** A pre-#1107 node ignores `TargetNodes` and has none of the node-side idempotence, so during a rolling upgrade with central upgraded first it treats every re-send that reaches it as an original dispatch. On **DPS** that includes re-sends meant for its peer. On **either** transport it includes the common case of its OWN re-send while its Applied ack is still held on the address-space outcome (any apply slower than 5 s): the old node re-applies the same revision (the pre-#1107 `_pendingAcks` revision check forces it) and supersedes the held ack. The second apply's diff is empty, so this is redundant work rather than an outage, but - **upgrade the driver nodes before central** to avoid it. The node's memory - is process-local: a node that restarted after acking treats a re-send as a first dispatch (short-circuit, - or a re-apply if its revision is unconfirmed). A node that first receives the dispatch at +35 s still has - ~85 s to ack; only a rebuild slower than that, which already acks degraded at 105 s, can miss the deadline. + **upgrade the driver nodes before central** to avoid it. +- **Remembered acks are in memory only — deliberately not persisted (#1111).** The last 16 acks live in the + `DriverHostActor` instance. A node that restarted (process restart, or a supervision restart of the actor) after + acking has forgotten them and treats a re-send as a first dispatch: it short-circuits `Applied` if it is already + on that revision with a confirmed address space, and otherwise applies it (a re-apply if its revision is + unconfirmed/degraded — the one case a restart can turn a degraded replay into a re-apply). The boot-time replay + of an orphan `Applying` row is unaffected. +- **Pre-#1111 node: late-re-send deadline limit.** A node that does not read `DeadlineRemaining` and first receives + the dispatch at +35 s has ~85 s to ack but waits up to 105 s for its address-space outcome, so a rebuild slower + than ~85 s seals `TimedOut` at central instead of "Applied (degraded)". Upgraded nodes bound the wait (above). ### What an `Applied` ack means: the degraded-apply amendment (Gitea #601) diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Messages/Deploy/DispatchDeployment.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Messages/Deploy/DispatchDeployment.cs index 02a24fc33..49aab130e 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Messages/Deploy/DispatchDeployment.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Messages/Deploy/DispatchDeployment.cs @@ -14,14 +14,25 @@ namespace ZB.MOM.WW.OtOpcUa.Commons.Messages.Deploy; /// #1107 — (or empty) on the ORIGINAL dispatch, which every node applies. Set only on a /// coordinator RE-SEND, naming the nodes (ClusterNode.NodeId, compared case-insensitively) that have not /// acked this deployment yet: a node not named ignores the re-send, and a named node that already acked (its ack -/// was lost) or is still applying it re-sends its ack / keeps applying instead of applying a second time. Additive: +/// was lost) or is still applying it re-sends its ack / keeps applying instead of applying a second time — except +/// a remembered FAILED ack, which the node retries (#1111: a failed apply left it on last-good config). Additive: /// a pre-#1107 node ignores the member (see docs/Redundancy.md §"Dispatch re-send"). /// +/// +/// #1111 — on the ORIGINAL dispatch (the node assumes the full +/// ). Set only on a coordinator RE-SEND: how much of central's apply +/// deadline was left when the re-send went out. A RELATIVE duration, never an absolute instant, so central's and +/// the node's clocks need not agree. The node bounds its held Applied ack's address-space wait to this minus +/// (measured from receipt), so a node first reached by a late +/// re-send still acks "Applied (degraded)" before central's deadline instead of sealing TimedOut. Additive: +/// a pre-#1111 node ignores it and keeps its full 105 s wait. +/// public sealed record DispatchDeployment( DeploymentId DeploymentId, RevisionHash RevisionHash, CorrelationId CorrelationId, - IReadOnlyList? TargetNodes = null) + IReadOnlyList? TargetNodes = null, + TimeSpan? DeadlineRemaining = null) { /// Whether this is a coordinator re-send (#1107) rather than the original dispatch. public bool IsResend => TargetNodes is { Count: > 0 }; diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Messages/Mesh/MeshTransportDtoMapper.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Messages/Mesh/MeshTransportDtoMapper.cs index 2ee5a2e07..e3ffd7c1e 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Messages/Mesh/MeshTransportDtoMapper.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Messages/Mesh/MeshTransportDtoMapper.cs @@ -59,6 +59,9 @@ public static class MeshTransportDtoMapper // #1107: only a re-send names targets; the original dispatch leaves the repeated field empty. if (message.TargetNodes is { Count: > 0 } targets) proto.TargetNodes.AddRange(targets.Where(t => !string.IsNullOrWhiteSpace(t))); + // #1111: presence = a re-send carrying central's remaining deadline; absent = the full default. + if (message.DeadlineRemaining is { } remaining) + proto.DeadlineRemainingMs = Math.Max(0L, (long)remaining.TotalMilliseconds); return proto; } @@ -76,7 +79,9 @@ public static class MeshTransportDtoMapper RevisionHash.Parse(proto.RevisionHash), CorrelationId.Parse(proto.CorrelationId), // #1107: an empty repeated field is the original dispatch (null), never "addressed to nobody". - proto.TargetNodes.Count > 0 ? proto.TargetNodes.ToList() : null); + proto.TargetNodes.Count > 0 ? proto.TargetNodes.ToList() : null, + // #1111: absent (an original dispatch, or a pre-#1111 central) = null = the node's full default wait. + proto.HasDeadlineRemainingMs ? TimeSpan.FromMilliseconds(proto.DeadlineRemainingMs) : null); } // ---------------------------------------------------------------- RestartDriver diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Protos/mesh_transport.proto b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Protos/mesh_transport.proto index b70027f52..c5bebac09 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Protos/mesh_transport.proto +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Protos/mesh_transport.proto @@ -96,6 +96,11 @@ message DispatchDeploymentCommand { // re-send to the ClusterNode ids that have not acked yet. Central already dials only those nodes on // this transport, so this is belt-and-braces for the node; a pre-#1107 node ignores the field. repeated string target_nodes = 4; + // #1111 — ADDITIVE. Absent on the original dispatch; set on a re-send to the milliseconds of central's + // apply deadline left when it went out (RELATIVE — no clock agreement needed). The node bounds its + // address-space wait to this minus the 15 s safety margin. A pre-#1111 node ignores the field; a + // pre-#1111 central never sets it (the node then waits its full default). + optional int64 deadline_remaining_ms = 5; } // Mirrors ZB.MOM.WW.OtOpcUa.Commons.Messages.Admin.RestartDriver. 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 7e12c9dcd..ce8bcbcc6 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/Coordinators/ConfigPublishCoordinator.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/Coordinators/ConfigPublishCoordinator.cs @@ -140,6 +140,13 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU /// #1107: no re-send is scheduled to fire after this instant (a fraction of the apply deadline). private DateTime _redispatchWindowEndsUtc; + + /// + /// #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. + /// + private DateTime _redispatchDeadlineUtc; private readonly TimeSpan _applyDeadline; private readonly TimeSpan _loadRetryMin; private readonly TimeSpan _loadRetryMax; @@ -823,7 +830,9 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU _expectedAcks = outcome.Expected!; // The ORIGINAL dispatch addresses every node, whatever a (recovered/queued) message carried. - var original = msg.TargetNodes is null ? msg : msg with { TargetNodes = null }; + var original = msg.TargetNodes is null && msg.DeadlineRemaining is null + ? msg + : msg with { TargetNodes = null, DeadlineRemaining = null }; PublishDispatch(original); Timers.StartSingleTimer(DeadlineTimerKey, new DeadlineElapsed(msg.DeploymentId), _applyDeadline); ArmRedispatch(original, _applyDeadline); @@ -870,6 +879,7 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU 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(); } @@ -924,7 +934,14 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU "nodes that already acked are not re-sent to, and a node still applying ignores the copy", dispatch.DeploymentId, string.Join(", ", outstanding), _redispatchAttempts, _redispatchSchedule.Count); ZB.MOM.WW.OtOpcUa.Commons.Observability.OtOpcUaTelemetry.DeploymentRedispatched.Add(outstanding.Count); - PublishDispatch(dispatch with { TargetNodes = outstanding }); + // #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; + PublishDispatch(dispatch with + { + TargetNodes = outstanding, + DeadlineRemaining = deadlineRemaining > TimeSpan.Zero ? deadlineRemaining : TimeSpan.Zero, + }); ScheduleNextRedispatch(); } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs index 56ffd825e..5b44f974e 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs @@ -362,7 +362,8 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn /// #1107: the last ack this node SENT for each of its most recent deployments (bounded, oldest evicted). A /// coordinator RE-SEND () of a deployment found here means its ack was /// lost on the way, so the remembered ack is re-delivered rather than the deployment applied a second time — a - /// second apply of a degraded revision is exactly what #601 makes a same-revision dispatch do. Process-local: + /// second apply of a degraded revision is exactly what #601 makes a same-revision dispatch do. A remembered + /// Failed ack is the exception (#1111): see . Process-local: /// after a restart the node has nothing to remember and the boot replay owns the deployment. /// private readonly Dictionary _recentAcks = new(); @@ -370,6 +371,26 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn /// Insertion order of , for eviction. private readonly Queue _recentAckOrder = new(); + /// + /// #1111: the deployment this node sent its most recent ack for (any outcome, including a re-delivery's + /// re-ack of the same deployment). A re-send of a deployment whose remembered ack is Failed is + /// re-attempted only while that deployment is still this node's latest answer — retrying an OLDER failed + /// deployment after a newer one was applied would roll the node back. + /// + private DeploymentId? _lastAnsweredDeploymentId; + + /// + /// #1111: the address-space-wait bound for the apply started by a RE-SEND that carried + /// — its correlation and the local + /// instant (central's remaining deadline, measured from receipt, minus + /// ) by which the held Applied ack must be released. + /// for an original dispatch (the full applies). + /// + private (CorrelationId Correlation, long ReleaseByTick)? _applyOutcomeReleaseBy; + + /// #1111: the shortest address-space wait a late re-send's bound can shrink to. + internal static readonly TimeSpan MinBoundedApplyOutcomeTimeout = TimeSpan.FromSeconds(1); + private readonly Dictionary _children = new(StringComparer.Ordinal); /// Per-driver children — one for each spawned driver @@ -3281,7 +3302,22 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn // #1107: a re-send of a deployment this node already ANSWERED means the ack was lost — re-deliver it. Applying // again would re-apply a degraded revision (#601) and could ack a different outcome than the first time. - if (msg.IsResend && _recentAcks.TryGetValue(msg.DeploymentId, out var answered)) + // + // #1111: EXCEPT a Failed ack. A failed apply left this node on its last-good configuration, so retrying is safe — + // and the fetch failure and the lost ack typically share one cause (a central blip), so replaying Failed would + // seal the deployment Failed for a node that could now succeed. Retried once per re-send (never concurrently: + // a copy arriving while the retry runs is dropped by Applying), and only while that deployment is still this + // node's latest answer with no other apply's ack held — never after a newer deployment, which a retry would + // roll back. Applied / Applied-degraded keep the replay (#601: no repeated re-apply of a degraded revision). + if (msg.IsResend && _recentAcks.TryGetValue(msg.DeploymentId, out var failed) + && failed.Outcome == ApplyAckOutcome.Failed + && _lastAnsweredDeploymentId == msg.DeploymentId + && _pendingAcks.Count == 0) + { + _log.Info("DriverHost {Node}: re-send of {Id}, whose apply FAILED here ({Reason}) — retrying the apply (the node is still on its last-good configuration)", + _localNode, msg.DeploymentId, failed.FailureReason); + } + else if (msg.IsResend && _recentAcks.TryGetValue(msg.DeploymentId, out var answered)) { _log.Info("DriverHost {Node}: re-send of {Id}, which this node already acked ({Outcome}{Degraded}) — re-sending that ack instead of re-applying", _localNode, msg.DeploymentId, answered.Outcome, answered.Degraded ? ", degraded" : ""); @@ -3308,6 +3344,13 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn "DriverHost {Node}: dispatch {Id} matches current rev {Rev}, but its address-space apply was degraded or is unconfirmed — re-applying rather than acking clean", _localNode, msg.DeploymentId, msg.RevisionHash); + // #1111: a re-send names how much of central's deadline is left; bound this apply's address-space wait so its + // ack still lands in time. Measured from receipt, so the artifact read and reconcile count against it too. + _applyOutcomeReleaseBy = msg.DeadlineRemaining is { } remaining + ? (msg.CorrelationId, + Environment.TickCount64 + (long)(remaining - DeployTimings.ApplyOutcomeSafetyMargin).TotalMilliseconds) + : null; + if (_fetchAndCacheMode) { BeginFetchAndCacheApply(msg.DeploymentId, msg.RevisionHash, msg.CorrelationId); @@ -3575,7 +3618,7 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn private sealed record PendingAck(DeploymentId DeploymentId, RevisionHash Revision, CorrelationId Correlation); /// Self-timer: the address-space outcome for this correlation did not arrive in time. - private sealed record ApplyOutcomeTimedOut(CorrelationId Correlation); + private sealed record ApplyOutcomeTimedOut(CorrelationId Correlation, TimeSpan After); private static string ApplyOutcomeTimerKey(CorrelationId correlation) => $"apply-outcome-{correlation}"; @@ -3600,7 +3643,32 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn "DriverHost {Node}: a second apply reused correlation {Correlation} while deployment {Old}'s ack was still waiting for its address-space outcome — that ack is superseded", _localNode, correlation, superseded.DeploymentId); _pendingAcks[correlation] = new PendingAck(deploymentId, revision, correlation); - Timers.StartSingleTimer(ApplyOutcomeTimerKey(correlation), new ApplyOutcomeTimedOut(correlation), _applyOutcomeTimeout); + var wait = ApplyOutcomeWaitFor(correlation); + Timers.StartSingleTimer(ApplyOutcomeTimerKey(correlation), new ApplyOutcomeTimedOut(correlation, wait), wait); + } + + /// + /// #1111: how long the held ack of waits for its address-space outcome — the + /// configured , shortened (never below + /// ) when the apply was started by a re-send whose remaining + /// deadline would otherwise run out first. Consumes the bound. + /// + private TimeSpan ApplyOutcomeWaitFor(CorrelationId correlation) + { + var wait = _applyOutcomeTimeout; + if (_applyOutcomeReleaseBy is { } bound && bound.Correlation == correlation) + { + var left = TimeSpan.FromMilliseconds(bound.ReleaseByTick - Environment.TickCount64); + if (left < MinBoundedApplyOutcomeTimeout) left = MinBoundedApplyOutcomeTimeout; + if (left < wait) + { + _log.Info("DriverHost {Node}: apply {Correlation} came from a late re-send — waiting at most {Wait:0.#}s (not {Full:0}s) for its address-space outcome so the ack lands inside central's deadline", + _localNode, correlation, left.TotalSeconds, _applyOutcomeTimeout.TotalSeconds); + wait = left; + } + } + _applyOutcomeReleaseBy = null; + return wait; } /// Forgets a held ack (its apply failed after all, and acks Failed instead). @@ -3641,7 +3709,7 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn if (!_pendingAcks.Remove(msg.Correlation, out var pending)) return; ReleasePendingAck(pending, degraded: true, - $"{OutcomeNotReportedReasonPrefix} ({_applyOutcomeTimeout.TotalSeconds:0}s) — no sink failure was observed; the apply may still be running (slow) or its outcome was lost"); + $"{OutcomeNotReportedReasonPrefix} ({msg.After.TotalSeconds:0}s) — no sink failure was observed; the apply may still be running (slow) or its outcome was lost"); } private void ReleasePendingAck(PendingAck pending, bool degraded, string? reason) @@ -5549,6 +5617,7 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn _recentAcks.Remove(_recentAckOrder.Dequeue()); } _recentAcks[ack.DeploymentId] = ack; + _lastAnsweredDeploymentId = ack.DeploymentId; } private void DeliverAck(ApplyAck ack) diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/MeshTransportDtoMapperTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/MeshTransportDtoMapperTests.cs index 75da91048..01e436174 100644 --- a/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/MeshTransportDtoMapperTests.cs +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/MeshTransportDtoMapperTests.cs @@ -72,6 +72,30 @@ public class MeshTransportDtoMapperTests original.IsAddressedTo("site-b-1:4053").ShouldBeTrue(); } + [Fact] + public void DispatchDeployment_Resend_RoundTrips_ItsRemainingDeadline_AndAnOriginalCarriesNone() + { + // #1111: presence of deadline_remaining_ms is what distinguishes "central said N ms are left" from an original + // dispatch / a pre-#1111 central (absent => null => the node's full default wait). + var resend = new DispatchDeployment( + new DeploymentId(DeploymentGuid), new RevisionHash(Sha256Hex), new CorrelationId(CorrelationGuid), + ["site-a-1:4053"], TimeSpan.FromMilliseconds(84_500)); + + var proto = MeshTransportDtoMapper.ToProto(resend); + proto.HasDeadlineRemainingMs.ShouldBeTrue(); + proto.DeadlineRemainingMs.ShouldBe(84_500L); + MeshTransportDtoMapper.FromProto(Wire(proto)).DeadlineRemaining.ShouldBe(TimeSpan.FromMilliseconds(84_500)); + + // Zero is a real value (deadline already spent), not "absent". + var spent = Wire(MeshTransportDtoMapper.ToProto(resend with { DeadlineRemaining = TimeSpan.Zero })); + spent.HasDeadlineRemainingMs.ShouldBeTrue(); + MeshTransportDtoMapper.FromProto(spent).DeadlineRemaining.ShouldBe(TimeSpan.Zero); + + var original = Wire(MeshTransportDtoMapper.ToProto(resend with { TargetNodes = null, DeadlineRemaining = null })); + original.HasDeadlineRemainingMs.ShouldBeFalse(); + MeshTransportDtoMapper.FromProto(original).DeadlineRemaining.ShouldBeNull(); + } + [Fact] public void DispatchDeployment_EncodesIdsInTheirHexNForm() { 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 05e65fab1..21e2ea4b3 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/ConfigPublishCoordinatorRedispatchTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/ConfigPublishCoordinatorRedispatchTests.cs @@ -127,6 +127,31 @@ public sealed class ConfigPublishCoordinatorRedispatchTests : ControlPlaneActorT resend.IsResend.ShouldBeTrue(); } + [Fact] + public void Each_resend_carries_the_remaining_deadline_and_the_original_carries_none() + { + // #1111: a node first reached by a late re-send must bound its address-space wait to what is LEFT of central's + // deadline, so every re-send says how much that is; the original dispatch leaves it unset (full default). + var deadline = TimeSpan.FromSeconds(60); + 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(400), 2))) + .Tell(new DispatchDeployment(deploymentId, TestRevision, CorrelationId.NewId())); + + ExpectDispatch(router).DeadlineRemaining.ShouldBeNull(); + var first = ExpectDispatch(router).DeadlineRemaining.ShouldNotBeNull(); + var second = ExpectDispatch(router).DeadlineRemaining.ShouldNotBeNull(); + + first.ShouldBeLessThan(deadline); + first.ShouldBeGreaterThan(deadline - TimeSpan.FromSeconds(10)); + // Counts down between re-sends (by ~one schedule step), never resets to the full deadline. + second.ShouldBeLessThan(first); + (first - second).ShouldBeGreaterThan(TimeSpan.FromMilliseconds(200)); + } + [Fact] public void Resends_are_bounded_by_the_schedule() { diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostActorRedispatchTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostActorRedispatchTests.cs index 8b33f6a44..8ad1feea9 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostActorRedispatchTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostActorRedispatchTests.cs @@ -144,6 +144,142 @@ public sealed class DriverHostActorRedispatchTests : RuntimeActorTestBase } } + [Fact] + public void A_resend_of_a_deployment_whose_apply_FAILED_retries_the_apply_and_a_later_resend_replays_the_success() + { + // #1111: the first fetch fails (a central blip), the second succeeds. + var db = NewInMemoryDbFactory(); + var fetcher = new ScriptedFetcher(null, EmptyArtifact); + var deploymentId = DeploymentId.NewId(); + var coordinator = CreateTestProbe(); + var actor = Sys.ActorOf(DriverHostActor.Props( + db, TestNode, coordinator.Ref, + localRoles: new HashSet { "driver" }, + deploymentArtifactCache: new NullArtifactCache(), + fetchAndCacheMode: true, + artifactFetcher: fetcher)); + + var dispatch = new DispatchDeployment(deploymentId, RevA, CorrelationId.NewId()); + actor.Tell(dispatch); + coordinator.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken) + .Outcome.ShouldBe(ApplyAckOutcome.Failed); + + // The coordinator never saw the Failed ack and re-sends: the node RETRIES rather than replaying Failed. + actor.Tell(dispatch with { TargetNodes = [TestNode.Value] }); + coordinator.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken) + .Outcome.ShouldBe(ApplyAckOutcome.Applied); + fetcher.Calls.ShouldBe(2); + + // A further re-send (that Applied ack lost too) replays it — the retry did not turn re-sends into re-applies. + actor.Tell(dispatch with { TargetNodes = [TestNode.Value] }); + coordinator.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken) + .Outcome.ShouldBe(ApplyAckOutcome.Applied); + coordinator.ExpectNoMsg(Quiet, TestContext.Current.CancellationToken); + fetcher.Calls.ShouldBe(2); + } + + [Fact] + public void A_resend_of_an_OLDER_failed_deployment_replays_Failed_rather_than_rolling_back_a_newer_apply() + { + var db = NewInMemoryDbFactory(); + var fetcher = new ScriptedFetcher(null, EmptyArtifact); + var coordinator = CreateTestProbe(); + var actor = Sys.ActorOf(DriverHostActor.Props( + db, TestNode, coordinator.Ref, + localRoles: new HashSet { "driver" }, + deploymentArtifactCache: new NullArtifactCache(), + fetchAndCacheMode: true, + artifactFetcher: fetcher)); + + var older = new DispatchDeployment(DeploymentId.NewId(), RevA, CorrelationId.NewId()); + actor.Tell(older); + var failed = coordinator.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + failed.Outcome.ShouldBe(ApplyAckOutcome.Failed); + + // A newer deployment is applied after it. + actor.Tell(new DispatchDeployment(DeploymentId.NewId(), RevisionHash.Parse(new string('b', 64)), CorrelationId.NewId())); + coordinator.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken) + .Outcome.ShouldBe(ApplyAckOutcome.Applied); + fetcher.Calls.ShouldBe(2); + + // A stale re-send of the older, failed deployment: the remembered Failed is replayed, nothing is fetched. + actor.Tell(older with { TargetNodes = [TestNode.Value] }); + coordinator.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken) + .ShouldBe(failed); + coordinator.ExpectNoMsg(Quiet, TestContext.Current.CancellationToken); + fetcher.Calls.ShouldBe(2); + + // Positive control: an ORIGINAL dispatch of that same deployment does fetch and apply, so the silence above is + // the stale-retry guard, not a host that has stopped fetching. + actor.Tell(older); + coordinator.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken) + .Outcome.ShouldBe(ApplyAckOutcome.Applied); + fetcher.Calls.ShouldBe(3); + } + + [Fact] + public void A_late_resend_bounds_the_address_space_wait_to_the_deadline_it_carries() + { + var (db, deploymentId) = SeedOneTagDeployment(); + var coordinator = CreateTestProbe(); + var publish = CreateTestProbe(); + // A long configured wait, so a degraded ack within seconds can only be the re-send's bound. + var actor = Sys.ActorOf(DriverHostActor.Props( + db, TestNode, coordinator.Ref, localRoles: new HashSet { "driver" }, + opcUaPublishActor: publish.Ref, applyOutcomeTimeout: TimeSpan.FromSeconds(60))); + + // First reached by a re-send with 17 s of central's deadline left => 17 - 15 = 2 s of address-space wait. + actor.Tell(new DispatchDeployment(deploymentId, RevA, CorrelationId.NewId(), + TargetNodes: [TestNode.Value], DeadlineRemaining: TimeSpan.FromSeconds(17))); + publish.FishForMessage(_ => true, PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + // The outcome never arrives. + var ack = coordinator.ExpectMsg(TimeSpan.FromSeconds(10), cancellationToken: TestContext.Current.CancellationToken); + ack.Outcome.ShouldBe(ApplyAckOutcome.Applied); + ack.Degraded.ShouldBeTrue(); + ack.DegradedReason.ShouldNotBeNull(); + ack.DegradedReason.ShouldStartWith(DriverHostActor.OutcomeNotReportedReasonPrefix); + ack.DegradedReason.ShouldContain("(2s)"); + } + + [Fact] + public void An_original_dispatch_keeps_the_full_address_space_wait() + { + // Positive control for the bound above: same set-up, no DeadlineRemaining — the ack stays held past the + // re-send's 2 s, and is released (clean) only by the outcome. + var (db, deploymentId) = SeedOneTagDeployment(); + var coordinator = CreateTestProbe(); + var publish = CreateTestProbe(); + var actor = Sys.ActorOf(DriverHostActor.Props( + db, TestNode, coordinator.Ref, localRoles: new HashSet { "driver" }, + opcUaPublishActor: publish.Ref, applyOutcomeTimeout: TimeSpan.FromSeconds(60))); + + actor.Tell(new DispatchDeployment(deploymentId, RevA, CorrelationId.NewId())); + var rebuild = publish.FishForMessage(_ => true, PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + coordinator.ExpectNoMsg(TimeSpan.FromSeconds(4), TestContext.Current.CancellationToken); + + actor.Tell(new OpcUaPublishActor.RebuildCompleted(rebuild.Correlation, rebuild.DeploymentId, false, null), publish.Ref); + var ack = coordinator.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + ack.Outcome.ShouldBe(ApplyAckOutcome.Applied); + ack.Degraded.ShouldBeFalse(); + } + + private static readonly byte[] EmptyArtifact = + JsonSerializer.SerializeToUtf8Bytes(new { DriverInstances = Array.Empty() }); + + /// A fetcher answering each call with the next scripted result (null = "no answer"); the last repeats. + private sealed class ScriptedFetcher(params byte[]?[] results) : IDeploymentArtifactFetcher + { + private int _calls; + + public int Calls => Volatile.Read(ref _calls); + + public Task FetchAsync(string deploymentId, string expectedRevisionHash, CancellationToken ct) + { + var n = Interlocked.Increment(ref _calls); + return Task.FromResult(results[Math.Min(n, results.Length) - 1]); + } + } + private (IDbContextFactory Db, DeploymentId Id) SeedOneTagDeployment() { var db = NewInMemoryDbFactory(); From 9be85f5a94d60e50237aa246a515882e2b7ffa43 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Sat, 5 Dec 2026 00:40:47 -0500 Subject: [PATCH 2/3] =?UTF-8?q?fix(deploy):=20#1111=20review=20=E2=80=94?= =?UTF-8?q?=20cover=20the=20held-ack=20retry=20guard;=20clamp=20deadline?= =?UTF-8?q?=5Fremaining=5Fms=20off=20the=20wire?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - The _pendingAcks.Count == 0 guard (a stale re-send of an older FAILED deployment must not re-apply it while a NEWER apply's Applied ack is held on its address-space outcome) had no test: mutating it to true left every Runtime test green. New test fails under that mutation (the older revision is re-fetched and applied over the newer one, whose held Applied ack then goes out for a rolled-back node). - MeshTransportDtoMapper.FromProto clamps deadline_remaining_ms to [0, 1 day]: a long.MaxValue wire value threw from TimeSpan.FromMilliseconds; a hugely negative one could overflow the node's TimeSpan subtraction in HandleDispatchFromSteady (actor restart = remembered acks lost). - Doc fix: _lastAnsweredDeploymentId is moved by RememberAck only, not by a replay. --- .../Messages/Mesh/MeshTransportDtoMapper.cs | 11 +++- .../Drivers/DriverHostActor.cs | 4 +- .../MeshTransportDtoMapperTests.cs | 8 +++ .../Drivers/DriverHostActorRedispatchTests.cs | 51 +++++++++++++++++++ 4 files changed, 70 insertions(+), 4 deletions(-) diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Messages/Mesh/MeshTransportDtoMapper.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Messages/Mesh/MeshTransportDtoMapper.cs index e3ffd7c1e..42175c590 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Messages/Mesh/MeshTransportDtoMapper.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Messages/Mesh/MeshTransportDtoMapper.cs @@ -80,10 +80,17 @@ public static class MeshTransportDtoMapper CorrelationId.Parse(proto.CorrelationId), // #1107: an empty repeated field is the original dispatch (null), never "addressed to nobody". proto.TargetNodes.Count > 0 ? proto.TargetNodes.ToList() : null, - // #1111: absent (an original dispatch, or a pre-#1111 central) = null = the node's full default wait. - proto.HasDeadlineRemainingMs ? TimeSpan.FromMilliseconds(proto.DeadlineRemainingMs) : null); + // #1111: absent (an original dispatch, or a pre-#1111 central) = null = the node's full default wait. Clamped: + // the bound only ever SHORTENS the node's wait, and an out-of-range wire value must not throw here (a + // TimeSpan overflow) or overflow the node's tick arithmetic — negative is "spent", a day is "unbounded". + proto.HasDeadlineRemainingMs + ? TimeSpan.FromMilliseconds(Math.Clamp(proto.DeadlineRemainingMs, 0L, MaxDeadlineRemainingMs)) + : null); } + /// #1111: the largest deadline_remaining_ms taken off the wire (one day — far past any apply deadline). + private const long MaxDeadlineRemainingMs = 24L * 60 * 60 * 1000; + // ---------------------------------------------------------------- RestartDriver /// Projects onto its wire form. diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs index 5b44f974e..807daa0dd 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs @@ -372,8 +372,8 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn private readonly Queue _recentAckOrder = new(); /// - /// #1111: the deployment this node sent its most recent ack for (any outcome, including a re-delivery's - /// re-ack of the same deployment). A re-send of a deployment whose remembered ack is Failed is + /// #1111: the deployment this node most recently PRODUCED an ack for (any outcome; set by + /// — a replay of a remembered ack does not move it). A re-send of a deployment whose remembered ack is Failed is /// re-attempted only while that deployment is still this node's latest answer — retrying an OLDER failed /// deployment after a newer one was applied would roll the node back. /// diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/MeshTransportDtoMapperTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/MeshTransportDtoMapperTests.cs index 01e436174..13b98eb86 100644 --- a/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/MeshTransportDtoMapperTests.cs +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/MeshTransportDtoMapperTests.cs @@ -91,6 +91,14 @@ public class MeshTransportDtoMapperTests spent.HasDeadlineRemainingMs.ShouldBeTrue(); MeshTransportDtoMapper.FromProto(spent).DeadlineRemaining.ShouldBe(TimeSpan.Zero); + // Out-of-range wire values (only a buggy or hostile sender) are clamped, never thrown on. + var negative = Wire(MeshTransportDtoMapper.ToProto(resend)); + negative.DeadlineRemainingMs = long.MinValue; + MeshTransportDtoMapper.FromProto(negative).DeadlineRemaining.ShouldBe(TimeSpan.Zero); + var huge = Wire(MeshTransportDtoMapper.ToProto(resend)); + huge.DeadlineRemainingMs = long.MaxValue; + MeshTransportDtoMapper.FromProto(huge).DeadlineRemaining.ShouldBe(TimeSpan.FromDays(1)); + var original = Wire(MeshTransportDtoMapper.ToProto(resend with { TargetNodes = null, DeadlineRemaining = null })); original.HasDeadlineRemainingMs.ShouldBeFalse(); MeshTransportDtoMapper.FromProto(original).DeadlineRemaining.ShouldBeNull(); diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostActorRedispatchTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostActorRedispatchTests.cs index 8ad1feea9..a2615814c 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostActorRedispatchTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostActorRedispatchTests.cs @@ -217,6 +217,57 @@ public sealed class DriverHostActorRedispatchTests : RuntimeActorTestBase fetcher.Calls.ShouldBe(3); } + [Fact] + public void A_resend_of_a_failed_deployment_is_not_retried_while_a_NEWER_applys_ack_is_still_held() + { + // #1111 review: the newer deployment's Applied ack is held on its address-space outcome, so the failed one is + // still this node's latest ANSWER — only the held-ack guard stops the stale re-send from re-applying the older + // revision over the newer one (and the newer one's held Applied ack then going out for a rolled-back node). + var db = NewInMemoryDbFactory(); + var fetcher = new ScriptedFetcher(null, EmptyArtifact); + var coordinator = CreateTestProbe(); + var publish = CreateTestProbe(); + var actor = Sys.ActorOf(DriverHostActor.Props( + db, TestNode, coordinator.Ref, + localRoles: new HashSet { "driver" }, + deploymentArtifactCache: new NullArtifactCache(), + fetchAndCacheMode: true, + artifactFetcher: fetcher, + opcUaPublishActor: publish.Ref, + applyOutcomeTimeout: TimeSpan.FromSeconds(60))); + + var older = new DispatchDeployment(DeploymentId.NewId(), RevA, CorrelationId.NewId()); + actor.Tell(older); + var failed = coordinator.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + failed.Outcome.ShouldBe(ApplyAckOutcome.Failed); + + // The newer deployment applies; its Applied ack is HELD (the address-space outcome has not landed). + var newer = new DispatchDeployment(DeploymentId.NewId(), RevisionHash.Parse(new string('b', 64)), CorrelationId.NewId()); + actor.Tell(newer); + var rebuild = publish.FishForMessage(_ => true, PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + rebuild.DeploymentId.ShouldBe(newer.DeploymentId); + fetcher.Calls.ShouldBe(2); + + // A stale re-send of the older, failed deployment: replays Failed, fetches nothing, starts no rebuild. + actor.Tell(older with { TargetNodes = [TestNode.Value] }); + coordinator.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken) + .ShouldBe(failed); + coordinator.ExpectNoMsg(Quiet, TestContext.Current.CancellationToken); + fetcher.Calls.ShouldBe(2); + + // The held ack is still the newer deployment's, and goes out clean when its outcome lands. + actor.Tell(new OpcUaPublishActor.RebuildCompleted(rebuild.Correlation, rebuild.DeploymentId, false, null), publish.Ref); + var ack = coordinator.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + ack.DeploymentId.ShouldBe(newer.DeploymentId); + ack.Outcome.ShouldBe(ApplyAckOutcome.Applied); + ack.Degraded.ShouldBeFalse(); + + // Positive control: an ORIGINAL dispatch of the older deployment does fetch — the silence above was the guard. + actor.Tell(older); + publish.FishForMessage(r => r.DeploymentId == older.DeploymentId, PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + fetcher.Calls.ShouldBe(3); + } + [Fact] public void A_late_resend_bounds_the_address_space_wait_to_the_deadline_it_carries() { From 2fcaffd2ed86e88f9ee689789032c72457ec8df9 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Sat, 5 Dec 2026 00:52:44 -0500 Subject: [PATCH 3/3] =?UTF-8?q?fix(deploy):=20#1111=20review=20=E2=80=94?= =?UTF-8?q?=20Applied=20wins=20over=20a=20late=20Failed?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Since #1111 a node re-applies a deployment only after its own Failed (the re-send retry), so two acks from one node for one deployment can differ, and the ORIGINAL Failed can still land after the retry's Applied (GrpcApplyAckSender's endpoint walk: a timed-out call may have been delivered). ConfigPublishCoordinator.HandleAck now discards a Failed from a node whose Applied (clean or degraded) for the current deployment has arrived — counted, persisting, parked behind a write, or held for a persist retry — before the row write, so neither the count nor the NodeDeploymentState row flips back. A stale unpersisted Failed is dropped with it so the deadline never waits on a retry the guard always discards. Applied after a counted Failed still wins. Residual, documented in docs/Redundancy.md (not corrected after the fact): a late Failed that CLOSES the deployment before the retry's Applied arrives — re-opening or late-sealing a terminal deployment would break write-once terminal outcomes (L8) and latest-sealed ordering. Tests: late Failed after a persisted Applied (clean + degraded), back-to-back Failed racing the in-flight Applied write (all three fail with the guard disabled), and an Applied-after-Failed positive control. --- .claude/rules/cluster-topology.md | 4 +- docs/Redundancy.md | 19 +++++ .../Coordinators/ConfigPublishCoordinator.cs | 30 +++++++ ...onfigPublishCoordinatorDegradedAckTests.cs | 81 +++++++++++++++++++ 4 files changed, 133 insertions(+), 1 deletion(-) diff --git a/.claude/rules/cluster-topology.md b/.claude/rules/cluster-topology.md index f91d99a30..830a70e4b 100644 --- a/.claude/rules/cluster-topology.md +++ b/.claude/rules/cluster-topology.md @@ -152,7 +152,9 @@ Things that carried over unchanged from the `ClusterClient` era, because they we — central's gRPC fan dials only those; on DPS the others ignore it. ⚠️ Never re-send to an acked node (#601: a same-revision dispatch re-applies a degraded revision); the node treats a re-send idempotently per `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). Re-sends carry + **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 `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 6d1f01ba4..308e1d1ee 100644 --- a/docs/Redundancy.md +++ b/docs/Redundancy.md @@ -844,6 +844,25 @@ dial was dropped — either way the deployment sat until the 120 s deadline and that deployment is still the node's **latest** answer with no other apply's ack held — a stale re-send of an older failed deployment after a newer one was applied replays `Failed` rather than rolling the node back. `Applied` and `Applied`+degraded acks keep the replay, so #601's "no repeated re-apply of a degraded revision on re-sends" holds. +- **Central: Applied wins over a late Failed (#1111 review).** Because the node re-applies only after its own `Failed`, + two acks from one node for one deployment can now differ — and the ORIGINAL `Failed` can still arrive after the + retry's `Applied` (`GrpcApplyAckSender` walks the central endpoints, and a call that timed out may still have + landed). Within one deployment `ConfigPublishCoordinator` therefore never lets a `Failed` overwrite that node's + `Applied` (clean or degraded) once the Applied has **arrived** — counted, being persisted, parked behind a write, or + 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 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 + after its `Failed` was delivered-but-unacknowledged, so it is narrow; it heals on the next deploy (a dispatch of the + 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 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 ce8bcbcc6..41f32fff2 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/Coordinators/ConfigPublishCoordinator.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/Coordinators/ConfigPublishCoordinator.cs @@ -994,11 +994,41 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU return; } + // #1111 review: within one deployment an Applied (clean or degraded) ack from a node is never overwritten by a + // later Failed from that node. A node re-applies a deployment only after its OWN Failed (the re-send retry), so a + // Failed arriving after that node's Applied can only be a stale or duplicate delivery of the earlier Failed (the + // gRPC ack sender walks endpoints, and a timed-out call may still have landed). Discarded BEFORE the persist, so + // the row is not flipped back to Failed either. + if (msg.Outcome == ApplyAckOutcome.Failed && HasAppliedAckFrom(msg.NodeId)) + { + _log.Info( + "Discarding a late Failed ApplyAck from {Node} for {Id}: that node's Applied ack for this deployment " + + "already arrived (a Failed after Applied is a stale/duplicate delivery of the ack the re-send retry replaced)", + msg.NodeId, msg.DeploymentId); + // The stale Failed may itself be the node's unpersisted entry (its write failed and is on a retry tick that + // re-enters here): drop it, or the deadline would wait on a retry this guard now always discards. + if (_unpersisted.TryGetValue(msg.NodeId, out var parked) && parked.Ack.Outcome == ApplyAckOutcome.Failed) + DropUnpersisted(msg.NodeId); + return; + } + // Persist FIRST: the row is the system of record (driver-only nodes never write their own, and nodes do not // resend). A throw here used to restart the actor and drop the ack; it is re-queued instead. StartAckPersist(msg); } + /// + /// #1111 review: whether an Applied (clean or degraded) ack of the CURRENT deployment from + /// has arrived — counted, held for a persist retry, being persisted, or parked behind a write. + /// + private bool HasAppliedAckFrom(NodeId node) => + (_acks.TryGetValue(node, out var counted) && counted == ApplyAckOutcome.Applied) + || (_unpersisted.TryGetValue(node, out var held) && IsAppliedForCurrent(held.Ack)) + || (_persisting.TryGetValue(node, out var inflight) && IsAppliedForCurrent(inflight)) + || (_pendingBehind.TryGetValue(node, out var behind) && IsAppliedForCurrent(behind)); + + private bool IsAppliedForCurrent(ApplyAck ack) => ack.Outcome == ApplyAckOutcome.Applied && IsForCurrent(ack); + /// /// lmxopcua#996 (review H-6): the ack write runs OFF the actor thread and its outcome comes back as /// . The write used to be a blocking SaveChanges in the handler, so with the diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/ConfigPublishCoordinatorDegradedAckTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/ConfigPublishCoordinatorDegradedAckTests.cs index f67424b10..641b19f74 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/ConfigPublishCoordinatorDegradedAckTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/ConfigPublishCoordinatorDegradedAckTests.cs @@ -108,6 +108,87 @@ public sealed class ConfigPublishCoordinatorDegradedAckTests : ControlPlaneActor db.NodeDeploymentStates.Single(s => s.NodeId == NodeA).Status.ShouldBe(NodeDeploymentStatus.Failed); } + [Theory] + [InlineData(false)] + [InlineData(true)] + public void A_late_Failed_after_a_nodes_Applied_ack_does_not_overwrite_it(bool degraded) + { + // #1111 review: the node retried after its first (Failed) ack was not seen, and acked Applied; the ORIGINAL + // Failed then arrives late (a timed-out gRPC call that still landed). The node re-applies only after its own + // Failed, so a Failed after Applied is stale: it must neither flip the row nor fail the deployment. + var dbFactory = NewInMemoryDbFactory(); + var deploymentId = SeedDispatchingDeployment(dbFactory); + SeedNodes(dbFactory, NodeA, NodeB); + var actor = Sys.ActorOf(ConfigPublishCoordinator.Props(dbFactory, NoTimeout)); + actor.Tell(new DispatchDeployment(deploymentId, TestRevision, CorrelationId.NewId())); + AwaitStatus(dbFactory, DeploymentStatus.AwaitingApplyAcks); + + actor.Tell(new ApplyAck(deploymentId, NodeId.Parse(NodeA), ApplyAckOutcome.Applied, null, + CorrelationId.NewId(), Degraded: degraded, DegradedReason: degraded ? "x" : null)); + AwaitAssert(() => + { + using var db = dbFactory.CreateDbContext(); + db.NodeDeploymentStates.Single(s => s.NodeId == NodeA).Status.ShouldBe(NodeDeploymentStatus.Applied); + }, duration: PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + actor.Tell(new ApplyAck(deploymentId, NodeId.Parse(NodeA), ApplyAckOutcome.Failed, "fetch failed", CorrelationId.NewId())); + actor.Tell(new ApplyAck(deploymentId, NodeId.Parse(NodeB), ApplyAckOutcome.Applied, null, CorrelationId.NewId())); + + AwaitStatus(dbFactory, DeploymentStatus.Sealed); + using var verify = dbFactory.CreateDbContext(); + var rowA = verify.NodeDeploymentStates.Single(s => s.NodeId == NodeA); + rowA.Status.ShouldBe(NodeDeploymentStatus.Applied); + ConfigPublishCoordinator.IsDegraded(rowA.Status, rowA.FailureReason).ShouldBe(degraded); + } + + [Fact] + public void A_late_Failed_racing_an_in_flight_Applied_write_does_not_overwrite_it() + { + // Same policy, both acks back-to-back: the Failed lands while the Applied's write is still in flight. + var dbFactory = NewInMemoryDbFactory(); + var deploymentId = SeedDispatchingDeployment(dbFactory); + SeedNodes(dbFactory, NodeA, NodeB); + var actor = Sys.ActorOf(ConfigPublishCoordinator.Props(dbFactory, NoTimeout)); + actor.Tell(new DispatchDeployment(deploymentId, TestRevision, CorrelationId.NewId())); + AwaitStatus(dbFactory, DeploymentStatus.AwaitingApplyAcks); + + actor.Tell(new ApplyAck(deploymentId, NodeId.Parse(NodeA), ApplyAckOutcome.Applied, null, CorrelationId.NewId())); + actor.Tell(new ApplyAck(deploymentId, NodeId.Parse(NodeA), ApplyAckOutcome.Failed, "fetch failed", CorrelationId.NewId())); + actor.Tell(new ApplyAck(deploymentId, NodeId.Parse(NodeB), ApplyAckOutcome.Applied, null, CorrelationId.NewId())); + + AwaitStatus(dbFactory, DeploymentStatus.Sealed); + using var verify = dbFactory.CreateDbContext(); + verify.NodeDeploymentStates.Single(s => s.NodeId == NodeA).Status.ShouldBe(NodeDeploymentStatus.Applied); + } + + [Fact] + public void An_Applied_after_a_nodes_Failed_ack_still_replaces_it() + { + // Positive control for the guard above: the retry's Applied arriving AFTER the Failed was counted wins, so the + // guard is one-directional (Applied is never overwritten by Failed; Failed is still overwritten by Applied). + var dbFactory = NewInMemoryDbFactory(); + var deploymentId = SeedDispatchingDeployment(dbFactory); + SeedNodes(dbFactory, NodeA, NodeB); + var actor = Sys.ActorOf(ConfigPublishCoordinator.Props(dbFactory, NoTimeout)); + actor.Tell(new DispatchDeployment(deploymentId, TestRevision, CorrelationId.NewId())); + AwaitStatus(dbFactory, DeploymentStatus.AwaitingApplyAcks); + + actor.Tell(new ApplyAck(deploymentId, NodeId.Parse(NodeA), ApplyAckOutcome.Failed, "fetch failed", CorrelationId.NewId())); + AwaitAssert(() => + { + using var db = dbFactory.CreateDbContext(); + db.NodeDeploymentStates.Single(s => s.NodeId == NodeA).Status.ShouldBe(NodeDeploymentStatus.Failed); + }, duration: PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + actor.Tell(new ApplyAck(deploymentId, NodeId.Parse(NodeA), ApplyAckOutcome.Applied, null, CorrelationId.NewId())); + AwaitAssert(() => + { + using var db = dbFactory.CreateDbContext(); + db.NodeDeploymentStates.Single(s => s.NodeId == NodeA).Status.ShouldBe(NodeDeploymentStatus.Applied); + }, duration: PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + actor.Tell(new ApplyAck(deploymentId, NodeId.Parse(NodeB), ApplyAckOutcome.Applied, null, CorrelationId.NewId())); + + AwaitStatus(dbFactory, DeploymentStatus.Sealed); + } + [Fact] public void A_recovered_coordinator_remembers_a_degraded_ack_that_landed_before_failover() {