diff --git a/.claude/rules/cluster-topology.md b/.claude/rules/cluster-topology.md index 43c2a11c8..ed2cc51bd 100644 --- a/.claude/rules/cluster-topology.md +++ b/.claude/rules/cluster-topology.md @@ -147,7 +147,12 @@ Things that carried over unchanged from the `ClusterClient` era, because they we - **Fire-and-forget, no retry, on both transports.** A failed gRPC dispatch is logged (naming the node and the gRPC status) and dropped in the dispatch second. No queue, no ordering guarantee across - nodes — the deploy coordinator's apply deadline and a node's boot-time replay are the only recovery. + nodes. **Exception: deployments (#1107).** `ConfigPublishCoordinator` re-sends a dispatch (+5/+15/+35 s, + 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 + 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. - **One exception to one-way (#950):** an `alarm-commands` `AlarmCommandMessage` carrying `verdict_requested` (the diff --git a/docs/Configuration.md b/docs/Configuration.md index 618fcd6c6..7f22edfd5 100644 --- a/docs/Configuration.md +++ b/docs/Configuration.md @@ -225,7 +225,7 @@ Security__Ldap__GroupToRole__=Viewer | `Mode` | string | `Dps` | `Dps` = DistributedPubSub, pair-local only — cannot cross an application-`Cluster` boundary. `Grpc` = the `mesh_transport.v1` gRPC contract (below), required on any node carrying a `cluster-{ClusterId}` role. Any other value **refuses to start**, including the retired `ClusterClient` value — a node still configured for it is refused at boot rather than silently demoted to `Dps`, which on a split-topology node would deliver nothing at all. | | `ContactRefreshSeconds` | int | `60` | Central-side only: how often central rebuilds its node dispatch set — the gRPC dial targets and the known-cluster PSK gate — from the `ClusterNode` rows. Runs in every mode; under `Dps` it still keeps the inbound-ack endpoint's known-cluster gate current even though nothing dials out. While the known-cluster gate is still unpublished (PSK provider not yet resolvable at boot, or the first `ClusterNode` load failed) central also retries a refresh every 2 s, at most 15 times, until the first publish (#654); steady state adds no traffic. Load failures and an unresolvable provider share the one 15-retry (~30 s) budget; after it is spent, healing falls to the periodic refresh. | -**`Grpc` mode: central dials each node, a node posts its ack to central.** `CentralCommunicationActor` fans one `NodeCommandService.Execute` call per node — the target set is every enabled, non-maintenance `ClusterNode` row that carries a `GrpcPort` (dialled at `Host`+`GrpcPort`), rebuilt every `ContactRefreshSeconds`. There is no receptionist and no single fleet-wide (or per-cluster) client object: it is a plain per-node dial. A node posts its `ApplyAck` with `GrpcApplyAckSender`, which walks `CentralGrpcEndpoints` in order and stops at the first success — an availability list, not a fan-out list, so central normally sees one ack per node per dispatch (the walk as a whole is at-least-once on a slow-then-retried endpoint; `ConfigPublishCoordinator.HandleAck` absorbs a duplicate idempotently). Both directions are **fire-and-forget, with no retry**: a failed dispatch is logged (naming the node and the gRPC status) and dropped in the dispatch second — the deploy path's 2-minute apply deadline and a node's boot-time replay (`DriverHostActor.Bootstrap()` re-applying an orphan `Applying` row) are the only recovery mechanisms, exactly as they were under `ClusterClient`. +**`Grpc` mode: central dials each node, a node posts its ack to central.** `CentralCommunicationActor` fans one `NodeCommandService.Execute` call per node — the target set is every enabled, non-maintenance `ClusterNode` row that carries a `GrpcPort` (dialled at `Host`+`GrpcPort`), rebuilt every `ContactRefreshSeconds`. There is no receptionist and no single fleet-wide (or per-cluster) client object: it is a plain per-node dial. A node posts its `ApplyAck` with `GrpcApplyAckSender`, which walks `CentralGrpcEndpoints` in order and stops at the first success — an availability list, not a fan-out list, so central normally sees one ack per node per dispatch (the walk as a whole is at-least-once on a slow-then-retried endpoint; `ConfigPublishCoordinator.HandleAck` absorbs a duplicate idempotently). Both directions are **fire-and-forget at the transport, with no retry**: a failed dispatch is logged (naming the node and the gRPC status) and dropped in the dispatch second. Deployments are the exception one layer up: `ConfigPublishCoordinator` re-sends a dispatch to the nodes that have not acked (#1107, [Redundancy.md § Dispatch re-send](Redundancy.md#dispatch-re-send-gitea-1107)), and the 2-minute apply deadline and a node's boot-time replay (`DriverHostActor.Bootstrap()` re-applying an orphan `Applying` row) remain the backstops. The ack itself is sent only once the node's address-space apply outcome is known, and carries an additive `degraded` flag (`ApplyAckMessage` fields 6/7; trailing `ApplyAck.Degraded`/`DegradedReason` on DPS) — an old node's ack decodes clean, exactly as before. See [Redundancy.md § "What an `Applied` ack means"](Redundancy.md#what-an-applied-ack-means-the-degraded-apply-amendment-gitea-601) (Gitea #601). diff --git a/docs/Redundancy.md b/docs/Redundancy.md index 04b194e65..d68d57d07 100644 --- a/docs/Redundancy.md +++ b/docs/Redundancy.md @@ -809,10 +809,39 @@ Two properties are load-bearing and easy to break: - **Inbound commands go to the node-local `EventStream`, never back onto a DPS topic.** DPS is mesh-wide and central fans out to *every* node, so a DPS re-publish would deliver N copies of every command to every subscriber. -- **Both transports are fire-and-forget, with no retry or queue.** A failed gRPC dispatch is logged - (naming the node and the gRPC status) and dropped in the dispatch second — the deploy path's +- **Both transports are fire-and-forget at the transport layer, with no retry or queue.** A failed gRPC + dispatch is logged (naming the node and the gRPC status) and dropped in the dispatch second. Driver-control + and alarm commands stay that way. **Deployments are re-sent by the deploy coordinator** (below); the 2-minute apply deadline and a node's boot-time replay (`DriverHostActor.Bootstrap()` re-applying an - orphan `Applying` row) are the only recovery mechanisms, unchanged from the DPS/`ClusterClient` era. + orphan `Applying` row) remain the backstops. + +### Dispatch re-send (Gitea #1107) + +Until #1107 `ConfigPublishCoordinator` dispatched a deployment exactly once. On DPS a node whose +`deployments` registry entry had not yet gossiped to the publisher missed it (#1106); on gRPC a failed +dial was dropped — either way the deployment sat until the 120 s deadline and sealed `TimedOut`. Now: + +- **Re-sent, bounded, to un-acked nodes only.** At +5 s, +15 s and +35 s + (`ConfigPublishCoordinator.DefaultRedispatchSchedule`, and never past half of the remaining deadline) the + coordinator re-sends the SAME `DispatchDeployment` (same `DeploymentId`/`RevisionHash`/`CorrelationId`) + with `TargetNodes` naming the expected nodes whose ack has not **arrived** — an ack still being persisted + counts as arrived. Re-sends stop at the last ack, completion, time-out, supersede, or the end of the + schedule; a recovered in-flight deployment (singleton fail-over) gets the same re-send inside what is left + of its deadline. Counter: `otopcua.deploy.redispatched` (per targeted node). +- **Why only un-acked nodes:** under #601 a same-revision dispatch makes a node whose last apply was + degraded *re-apply*. On gRPC central dials only the named nodes; on DPS the publish reaches every node and + `DispatchDeployment.IsAddressedTo` makes the others ignore it. +- **A re-send is idempotent on the node, per `DeploymentId`.** Mid-apply it is dropped (the existing + in-flight dedup); while the Applied ack is held on the address-space outcome, ANY copy of that deployment + is ignored (no second apply); once the node has acked, a re-send re-delivers the remembered ack (the last + 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. +- **Residuals.** A pre-#1107 node on the **DPS** transport ignores `TargetNodes`, so during a rolling upgrade + it can re-apply on a re-send meant for its peer (gRPC is unaffected — central filters). 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. ### 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 616398f15..02a24fc33 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 @@ -7,7 +7,32 @@ namespace ZB.MOM.WW.OtOpcUa.Commons.Messages.Deploy; /// DriverHostActor. Tells the node to fetch the deployment artifact identified by /// + and apply it. /// +/// The deployment to apply. +/// The revision (SHA-256 of the artifact bytes) the deployment carries. +/// Correlation for tracing the apply and its ack. +/// +/// #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: +/// a pre-#1107 node ignores the member (see docs/Redundancy.md §"Dispatch re-send"). +/// public sealed record DispatchDeployment( DeploymentId DeploymentId, RevisionHash RevisionHash, - CorrelationId CorrelationId); + CorrelationId CorrelationId, + IReadOnlyList? TargetNodes = null) +{ + /// Whether this is a coordinator re-send (#1107) rather than the original dispatch. + public bool IsResend => TargetNodes is { Count: > 0 }; + + /// + /// Whether the node should act on this dispatch: always for the original dispatch, + /// and for a re-send only when the node is named in (case-insensitive, matching the + /// coordinator's expected-ack comparison). + /// + /// The receiving node's id (host:port). + /// when the node should handle it. + public bool IsAddressedTo(string nodeId) => + !IsResend || TargetNodes!.Any(t => string.Equals(t, nodeId, StringComparison.OrdinalIgnoreCase)); +} 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 1dc4af290..2ee5a2e07 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 @@ -50,12 +50,16 @@ public static class MeshTransportDtoMapper { ArgumentNullException.ThrowIfNull(message); - return new DispatchDeploymentCommand + var proto = new DispatchDeploymentCommand { DeploymentId = message.DeploymentId.ToString(), RevisionHash = message.RevisionHash.Value ?? "", CorrelationId = message.CorrelationId.ToString(), }; + // #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))); + return proto; } /// Rebuilds the domain record from its wire form. @@ -70,7 +74,9 @@ public static class MeshTransportDtoMapper return new DispatchDeployment( DeploymentId.Parse(proto.DeploymentId), RevisionHash.Parse(proto.RevisionHash), - CorrelationId.Parse(proto.CorrelationId)); + 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); } // ---------------------------------------------------------------- RestartDriver diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Observability/OtOpcUaTelemetry.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Observability/OtOpcUaTelemetry.cs index 96b6f2fe3..f28d8b5df 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Observability/OtOpcUaTelemetry.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Observability/OtOpcUaTelemetry.cs @@ -32,6 +32,11 @@ public static class OtOpcUaTelemetry Meter.CreateCounter("otopcua.deploy.applied", unit: "{deployment}", description: "Deployments applied by a driver-role node (outcome=ack|reject)."); + /// #1107: dispatch re-sends by the deploy coordinator, counted per targeted (un-acked) node. + public static readonly Counter DeploymentRedispatched = + Meter.CreateCounter("otopcua.deploy.redispatched", unit: "{node}", + description: "Deployment dispatches re-sent by the coordinator to nodes that had not acked yet."); + /// Time from DriverHostActor receiving DispatchDeployment to emitting the ack/reject. public static readonly Histogram DeploymentApplyDurationSec = Meter.CreateHistogram("otopcua.deploy.apply.duration", unit: "s", 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 4e8d6336b..b70027f52 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 @@ -92,6 +92,10 @@ message DispatchDeploymentCommand { string deployment_id = 1; // DeploymentId (Guid) in its "N" hex form string revision_hash = 2; // RevisionHash — lowercase 64-char SHA-256 hex string correlation_id = 3; // CorrelationId (Guid) in its "N" hex form + // #1107 — ADDITIVE. Empty on the original dispatch (every node applies it); set on a coordinator + // 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; } // Mirrors ZB.MOM.WW.OtOpcUa.Commons.Messages.Admin.RestartDriver. diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/Communication/CentralCommunicationActor.cs b/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/Communication/CentralCommunicationActor.cs index 14ab094fa..7bcc44101 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/Communication/CentralCommunicationActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/Communication/CentralCommunicationActor.cs @@ -40,11 +40,12 @@ namespace ZB.MOM.WW.OtOpcUa.ControlPlane.Communication; /// while the deployment seals green. /// /// -/// Fire-and-forget, on both transports. The gRPC branch pipes per-node results back to -/// itself for logging ONLY: a failure names the node and the status and is dropped. No retry, -/// no queue, no ordering guarantee across nodes. That is not an omission — it is the -/// DistributedPubSub semantic preserved exactly, and the backstops are unchanged (the deploy -/// coordinator's apply deadline, and a node's boot-time replay). +/// Fire-and-forget, on both transports — at THIS layer. The gRPC branch pipes per-node +/// results back to itself for logging ONLY: a failure names the node and the status and is +/// dropped. No retry, no queue, no ordering guarantee across nodes. The one command that IS +/// re-sent is a deployment, and the re-send is owned by ConfigPublishCoordinator (#1107), +/// driven by the acks it has not received rather than by this actor's dial outcomes: a re-send +/// names its , and the gRPC fan dials only those. /// /// public sealed class CentralCommunicationActor : ReceiveActor, IWithTimers @@ -453,6 +454,22 @@ public sealed class CentralCommunicationActor : ReceiveActor, IWithTimers // Captured before the fan: a contact refresh between here and the last dial must not change // the recipient set of a dispatch already under way. var targets = _targets; + + // #1107: a coordinator RE-SEND of a deployment goes only to the nodes it names (those that have not + // acked yet) — never to a node that already acked, which would otherwise re-apply a degraded revision. + if (cmd.Message is DispatchDeployment { IsResend: true } resend && targets.Count > 0) + { + targets = targets.Where(t => resend.IsAddressedTo(t.NodeId)).ToList(); + if (targets.Count == 0) + { + _log.Warning( + "Deployment {DeploymentId} re-send names {Targets}, none of which is in the gRPC dispatch set " + + "(no GrpcPort, disabled, or in maintenance since the dispatch); nothing was dialled", + resend.DeploymentId, string.Join(", ", resend.TargetNodes!)); + return; + } + } + if (targets.Count == 0) { // App-level drop. The command is NOT queued and will NOT be retried: a deploy fails at @@ -613,8 +630,9 @@ public sealed class CentralCommunicationActor : ReceiveActor, IWithTimers _log.Warning( "Mesh: {CommandType} (correlationId={CorrelationId}) was NOT delivered to {NodeId} " - + "({Status}: {Detail}). It is dropped and will NOT be retried — the deployment apply " - + "deadline and the node's boot-time replay are the backstops", + + "({Status}: {Detail}). This actor does not retry it; a deployment is re-sent by the deploy " + + "coordinator to every node that has not acked (#1107), and the apply deadline and the node's " + + "boot-time replay remain the backstops", result.CommandType, result.CorrelationId, result.NodeId, result.FailureStatus, result.FailureDetail); } 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 50b185964..7e12c9dcd 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/Coordinators/ConfigPublishCoordinator.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/Coordinators/ConfigPublishCoordinator.cs @@ -86,6 +86,18 @@ namespace ZB.MOM.WW.OtOpcUa.ControlPlane.Coordinators; /// outcome arrives, keeping the restart-and-recover contract. The recovery path (, once per /// singleton start) runs the same work inline, so a failure there stays a failed load retried on the backoff. /// +/// +/// The dispatch is re-sent to nodes that have not acked (#1107). It used to go out exactly once: on +/// DistributedPubSub a node whose deployments registry entry had not gossiped to this node yet missed it, and on +/// gRPC a failed dial was logged and dropped — either way the deployment sat until the apply deadline (#1106). Now +/// re-sends the SAME dispatch (same DeploymentId / RevisionHash / CorrelationId) +/// with naming only the expected nodes whose ack has not arrived, bounded by +/// the schedule and by of the deadline, and stopped by the last ack, completion, +/// time-out or supersede. Never re-sent to a node that acked: under #601 a same-revision dispatch makes a node whose +/// apply was degraded re-apply. The node side makes a re-send idempotent per DeploymentId (re-acks if it already +/// answered, ignores it while applying or while its ack waits on the address-space outcome), so a late or duplicate +/// re-send — and the duplicate ack it may produce — is harmless. +/// /// public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithUnboundedStash { @@ -101,7 +113,33 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU /// Ceiling of the recovery-load retry backoff (lmxopcua#868). public static readonly TimeSpan DefaultLoadRetryMax = TimeSpan.FromSeconds(30); + /// + /// #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 + /// of the apply deadline, so the last one always lands with most of + /// the deadline still left for the node to apply and ack. + /// + public static readonly IReadOnlyList DefaultRedispatchSchedule = + [TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(20)]; + + /// #1107: re-sends are only scheduled inside this fraction of the (remaining) apply deadline. + public const double RedispatchWindowFraction = 0.5; + private readonly IDbContextFactory _dbFactory; + private readonly IReadOnlyList _redispatchSchedule; + + /// + /// #1107: the dispatch of the CURRENT deployment as it went out (same DeploymentId / RevisionHash / + /// CorrelationId), re-sent with naming the un-acked nodes. + /// Null when nothing is in flight or no re-send is armed. + /// + private DispatchDeployment? _resendable; + + /// #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; private readonly TimeSpan _applyDeadline; private readonly TimeSpan _loadRetryMin; private readonly TimeSpan _loadRetryMax; @@ -224,6 +262,10 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU /// Where the recovery-load state is reported for health, or . /// First recovery-load retry delay; = . /// Recovery-load retry ceiling; = . + /// + /// #1107: delays between dispatch re-sends to un-acked nodes; = + /// , empty = never re-send. + /// /// The Akka.NET used to spawn this actor. public static Props Props( IDbContextFactory dbFactory, @@ -231,10 +273,12 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU IActorRef? meshRouter = null, ConfigPublishCoordinatorReadiness? readiness = null, TimeSpan? loadRetryMin = null, - TimeSpan? loadRetryMax = null) => + TimeSpan? loadRetryMax = null, + IReadOnlyList? redispatchSchedule = null) => Akka.Actor.Props.Create(() => new ConfigPublishCoordinator( dbFactory, applyDeadline ?? DefaultApplyDeadline, meshRouter, readiness, - loadRetryMin ?? DefaultLoadRetryMin, loadRetryMax ?? DefaultLoadRetryMax)); + loadRetryMin ?? DefaultLoadRetryMin, loadRetryMax ?? DefaultLoadRetryMax, + redispatchSchedule ?? DefaultRedispatchSchedule)); /// /// Initializes a new instance of the class. @@ -245,14 +289,17 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU /// Where the recovery-load state is reported, or . /// First recovery-load retry delay. /// Recovery-load retry ceiling. + /// #1107 re-send delays; = . public ConfigPublishCoordinator( IDbContextFactory dbFactory, TimeSpan applyDeadline, IActorRef? meshRouter = null, ConfigPublishCoordinatorReadiness? readiness = null, TimeSpan? loadRetryMin = null, - TimeSpan? loadRetryMax = null) + TimeSpan? loadRetryMax = null, + IReadOnlyList? redispatchSchedule = null) { + _redispatchSchedule = redispatchSchedule ?? DefaultRedispatchSchedule; _dbFactory = dbFactory; _applyDeadline = applyDeadline; _meshRouter = meshRouter; @@ -294,6 +341,7 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU Receive(HandleAckPersisted); Receive(HandleRetryAckPersist); Receive(HandleDeadline); + Receive(HandleRedispatchTick); Receive(_ => { /* DPS subscribe confirmation */ }); // A late load outcome / retry tick cannot normally arrive once Ready; ignored, never stashed. Receive(_ => { }); @@ -595,6 +643,13 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU } Timers.StartSingleTimer(DeadlineTimerKey, new DeadlineElapsed(_current.Value), remaining); + // #1107: the nodes still un-acked may have missed the dispatch the previous incarnation sent (that is often + // why it is still in flight), so the recovered deployment gets the same bounded re-send, inside what is left + // of its deadline. Targeted at the un-acked nodes only, as always. + if (!string.IsNullOrWhiteSpace(inflight.RevisionHash)) + ArmRedispatch( + new DispatchDeployment(_current.Value, RevisionHash.Parse(inflight.RevisionHash), CorrelationId.NewId()), + remaining); _log.Info("Coordinator recovered in-flight deployment {Id} ({Acked}/{Total} acks landed)", _current, _acks.Count, _expectedAcks.Count); } @@ -767,11 +822,11 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU _expectedAcks = outcome.Expected!; - // Per-cluster mesh Phase 2: hand off to the transport router rather than publishing - // directly, so this actor no longer knows which transport is in force. - if (_meshRouter is not null) _meshRouter.Tell(new MeshCommand(DeploymentsTopic, msg)); - else DistributedPubSub.Get(Context.System).Mediator.Tell(new Publish(DeploymentsTopic, msg)); + // The ORIGINAL dispatch addresses every node, whatever a (recovered/queued) message carried. + var original = msg.TargetNodes is null ? msg : msg with { TargetNodes = null }; + PublishDispatch(original); Timers.StartSingleTimer(DeadlineTimerKey, new DeadlineElapsed(msg.DeploymentId), _applyDeadline); + ArmRedispatch(original, _applyDeadline); if (_expectedAcks.Count == 0) { @@ -788,6 +843,98 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU } } + /// + /// Hands a dispatch (original or #1107 re-send) to the transport. Per-cluster mesh Phase 2: through the router + /// rather than publishing directly, so this actor does not know which transport is in force. + /// + private void PublishDispatch(DispatchDeployment msg) + { + if (_meshRouter is not null) _meshRouter.Tell(new MeshCommand(DeploymentsTopic, msg)); + else DistributedPubSub.Get(Context.System).Mediator.Tell(new Publish(DeploymentsTopic, msg)); + } + + /// + /// #1107: arms the bounded re-send of to nodes that have not acked. Re-sends follow + /// and stop at the first of: every expected node acked (the tick finds no + /// one to send to), the deployment completes / times out / is superseded ( cancels + /// the timer and every tick carries its deployment id), the schedule runs out, or the re-send window — + /// of — closes. + /// + /// The dispatch as originally sent (no targets). + /// How long until this deployment's apply deadline. + private void ArmRedispatch(DispatchDeployment dispatch, TimeSpan deadlineLeft) + { + Timers.Cancel(RedispatchTimerKey); + _resendable = null; + _redispatchAttempts = 0; + if (_expectedAcks.Count == 0 || _redispatchSchedule.Count == 0 || deadlineLeft <= TimeSpan.Zero) return; + + _resendable = dispatch; + _redispatchWindowEndsUtc = DateTime.UtcNow + TimeSpan.FromTicks((long)(deadlineLeft.Ticks * RedispatchWindowFraction)); + ScheduleNextRedispatch(); + } + + /// Schedules the next re-send, unless the schedule is spent or it would land past the window. + private void ScheduleNextRedispatch() + { + if (_resendable is not { } dispatch || _redispatchAttempts >= _redispatchSchedule.Count) + { + _resendable = null; + return; + } + var delay = _redispatchSchedule[_redispatchAttempts]; + if (DateTime.UtcNow + delay > _redispatchWindowEndsUtc) + { + _resendable = null; + return; + } + Timers.StartSingleTimer(RedispatchTimerKey, new RedispatchTick(dispatch.DeploymentId), delay); + } + + /// + /// #1107: re-sends the current dispatch to the expected nodes that have not acked it. A node counts as acked + /// once its ack ARRIVED — persisted, still being persisted, or held for a persist retry — so a slow ConfigDb + /// never causes a re-send to a node that already answered (whose re-apply of a degraded revision is exactly + /// what #601 makes a same-revision dispatch do). + /// + private void HandleRedispatchTick(RedispatchTick tick) + { + if (_resendable is not { } dispatch || _current != tick.DeploymentId || dispatch.DeploymentId != tick.DeploymentId) + { + _log.Debug("Discarding stale re-send tick for {Id} (current={Current})", tick.DeploymentId, _current); + return; + } + + var outstanding = _expectedAcks + .Where(n => !AckReceivedFrom(n)) + .Select(n => n.Value) + .Order(StringComparer.OrdinalIgnoreCase) + .ToList(); + if (outstanding.Count == 0) + { + _resendable = null; + return; + } + + _redispatchAttempts++; + // Info, not Warning: a node still mid-way through a large apply is also "not acked yet", and is unharmed by a + // re-send (it drops the duplicate). A node that never answers is named at Warning by the deadline. + _log.Info( + "Deployment {Id}: no ack yet from {Nodes} — re-sending the dispatch to them (re-send {Attempt} of {Max}); " + + "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 }); + ScheduleNextRedispatch(); + } + + /// Whether 's ack for the CURRENT deployment has arrived (counted or not yet persisted). + private bool AckReceivedFrom(NodeId node) => + _acks.ContainsKey(node) + || _unpersisted.ContainsKey(node) + || (_persisting.TryGetValue(node, out var inflight) && IsForCurrent(inflight)) + || (_pendingBehind.TryGetValue(node, out var behind) && IsForCurrent(behind)); + /// /// Writes one terminal status (and optional reason) for , conditioned on the row still being /// in flight (review L8: a terminal outcome is written once). Static: runs on a pool thread (#1051) or inline. @@ -1236,6 +1383,10 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU private void ResetForNext() { Timers.Cancel(DeadlineTimerKey); + // #1107: no re-send outlives its deployment (a tick that was already queued is discarded by id). + Timers.Cancel(RedispatchTimerKey); + _resendable = null; + _redispatchAttempts = 0; _deadlineDeferredSinceUtc = null; foreach (var node in _unpersisted.Keys) Timers.Cancel(AckRetryTimerKey(node)); if (_unpersisted.Count > 0) @@ -1263,6 +1414,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"; + + /// #1107: time to re-send the current dispatch to the nodes that have not acked it. + private sealed record RedispatchTick(DeploymentId DeploymentId); /// The outcome of an off-thread ack write (#996 / H-6): error = persisted. private sealed record AckPersisted(ApplyAck Ack, Exception? Error); 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 6bf55fbb0..784e59d5b 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs @@ -355,6 +355,21 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn private DeploymentId? _applyingDeploymentId; + /// How many recent deployments' final acks remembers (#1107). + private const int RecentAckCapacity = 16; + + /// + /// #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: + /// after a restart the node has nothing to remember and the boot replay owns the deployment. + /// + private readonly Dictionary _recentAcks = new(); + + /// Insertion order of , for eviction. + private readonly Queue _recentAckOrder = new(); + private readonly Dictionary _children = new(StringComparer.Ordinal); /// Per-driver children — one for each spawned driver @@ -1920,6 +1935,9 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn Receive(_ => { }); Receive(msg => { + // #1107: a re-send not addressed to this node is for a node that has not acked — never stash it here. + if (!msg.IsAddressedTo(_localNode.Value)) return; + if (_applyingDeploymentId is not null && msg.DeploymentId == _applyingDeploymentId.Value) { _log.Debug("DriverHost {Node}: duplicate DispatchDeployment for in-flight {Id}; ignoring", @@ -3083,8 +3101,9 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn // could not be reverted and the node would show Acknowledged for an ack no driver saw. Refuse it // synchronously at the node manager instead (cleared by BecomeSteady, the only way out of Stale). _ackPreflightView?.SetHostUnavailable("the driver host is stale (configuration database unreachable)"); - Receive(_ => + Receive(msg => { + if (!msg.IsAddressedTo(_localNode.Value)) return; // #1107: a re-send for another node _log.Warning("DriverHost {Node}: ignoring DispatchDeployment while Stale (DB unreachable)", _localNode); }); // A cache store started before this node fell Stale still pipes back here (see @@ -3243,6 +3262,33 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn private void HandleDispatchFromSteady(DispatchDeployment msg) { + // #1107: a coordinator re-send names the nodes it is for; any other node has already acked. + if (!msg.IsAddressedTo(_localNode.Value)) + { + _log.Debug("DriverHost {Node}: re-send of {Id} is not addressed to this node; ignoring", _localNode, msg.DeploymentId); + return; + } + + // #1107: THIS deployment was already applied here and its Applied ack is held until the address-space outcome + // lands. A second copy (a coordinator re-send, or a duplicate delivery) must not start a second apply of it — + // the held ack is this node's answer and goes out when the outcome does. + if (_pendingAcks.Values.Any(p => p.DeploymentId == msg.DeploymentId)) + { + _log.Debug("DriverHost {Node}: dispatch {Id} already applied here, its ack is waiting on the address-space outcome; ignoring the duplicate", + _localNode, msg.DeploymentId); + return; + } + + // #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)) + { + _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" : ""); + DeliverAck(answered); + return; + } + // The short-circuit claims a CLEAN Applied, so it is only honest while the current revision's // address space is known-good — not after a degraded apply, and not while its outcome is still // pending. Either way the dispatch re-applies instead, which is also what repairs a degraded apply. @@ -5459,6 +5505,24 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn bool degraded = false, string? degradedReason = null) { var ack = new ApplyAck(deploymentId, _localNode, outcome, failureReason, correlation, degraded, degradedReason); + RememberAck(ack); + DeliverAck(ack); + } + + /// #1107: records the newest ack per deployment, evicting the oldest deployment past the capacity. + private void RememberAck(ApplyAck ack) + { + if (!_recentAcks.ContainsKey(ack.DeploymentId)) + { + _recentAckOrder.Enqueue(ack.DeploymentId); + while (_recentAckOrder.Count > RecentAckCapacity) + _recentAcks.Remove(_recentAckOrder.Dequeue()); + } + _recentAcks[ack.DeploymentId] = ack; + } + + private void DeliverAck(ApplyAck ack) + { if (_ackRouter is not null) { // Either a direct coordinator handle (tests) or, under MeshTransport:Mode = Grpc, the 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 262d04565..75da91048 100644 --- a/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/MeshTransportDtoMapperTests.cs +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/MeshTransportDtoMapperTests.cs @@ -52,6 +52,26 @@ public class MeshTransportDtoMapperTests MeshTransportDtoMapper.FromProto(Wire(MeshTransportDtoMapper.ToProto(domain))).ShouldBe(domain); } + [Fact] + public void DispatchDeployment_Resend_RoundTrips_ItsTargetNodes() + { + // #1107: a coordinator re-send carries the un-acked nodes; the original dispatch carries none (null, not empty). + var resend = new DispatchDeployment( + new DeploymentId(DeploymentGuid), new RevisionHash(Sha256Hex), new CorrelationId(CorrelationGuid), + ["site-a-1:4053", "site-a-2:4053"]); + + var back = MeshTransportDtoMapper.FromProto(Wire(MeshTransportDtoMapper.ToProto(resend))); + + back.TargetNodes.ShouldBe(["site-a-1:4053", "site-a-2:4053"]); + back.IsResend.ShouldBeTrue(); + back.IsAddressedTo("SITE-A-2:4053").ShouldBeTrue(); + back.IsAddressedTo("site-b-1:4053").ShouldBeFalse(); + + var original = MeshTransportDtoMapper.FromProto(Wire(MeshTransportDtoMapper.ToProto(resend with { TargetNodes = null }))); + original.TargetNodes.ShouldBeNull(); + original.IsAddressedTo("site-b-1:4053").ShouldBeTrue(); + } + [Fact] public void DispatchDeployment_EncodesIdsInTheirHexNForm() { diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/Communication/CentralCommunicationActorTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/Communication/CentralCommunicationActorTests.cs index b28eba9fb..bec01cf4d 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/Communication/CentralCommunicationActorTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/Communication/CentralCommunicationActorTests.cs @@ -234,6 +234,40 @@ public class CentralCommunicationActorTests : ControlPlaneActorTestBase rig.Dialer.Calls.Count.ShouldBe(1); } + [Fact] + public void A_deployment_resend_dials_only_the_nodes_it_names() + { + // #1107: a coordinator re-send names the nodes that have not acked. Dialling an acked node would make it + // re-apply a degraded revision (#601), so the fan must narrow to the named nodes — case-insensitively, as the + // coordinator's expected-ack set compares node ids. + var factory = NewInMemoryDbFactory(); + SeedGrpcCluster( + factory, + "C1", + ("host-a:4053", "host-a", 4056, true, false), + ("host-b:4053", "host-b", 4056, true, false)); + var rig = SpawnGrpcRig(factory); + AwaitContactsLoaded(rig); + + // Positive control: the original dispatch (no targets) reaches both nodes. + var original = NewDispatch(); + rig.Actor.Tell(new MeshCommand(DeploymentsTopic, original)); + AwaitCondition(() => rig.Dialer.Calls.Count == 2, TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + + rig.Actor.Tell(new MeshCommand(DeploymentsTopic, original with { TargetNodes = ["HOST-B:4053"] })); + AwaitCondition(() => rig.Dialer.Calls.Count == 3, TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + var resend = rig.Dialer.Calls[2]; + resend.Endpoint.ShouldBe("http://host-b:4056"); + resend.Envelope.DispatchDeployment.TargetNodes.ShouldBe(["HOST-B:4053"]); + + // ...and host-a is not dialled late. A follow-up command to everyone is the positive control that the + // actor is still dialling (so the count staying put is not just a stalled fan). + rig.Actor.Tell(new MeshCommand(DeploymentsTopic, NewDispatch())); + AwaitCondition(() => rig.Dialer.Calls.Count == 5, TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + rig.Dialer.Calls.Count(c => c.Envelope.DispatchDeployment.DeploymentId == original.DeploymentId.ToString()) + .ShouldBe(3); + } + [Fact] public void A_node_with_no_GrpcPort_is_skipped_with_a_warning_and_the_others_are_still_dialled() { diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/ConfigPublishCoordinatorRedispatchTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/ConfigPublishCoordinatorRedispatchTests.cs new file mode 100644 index 000000000..05e65fab1 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/ConfigPublishCoordinatorRedispatchTests.cs @@ -0,0 +1,287 @@ +using Akka.Actor; +using Akka.TestKit; +using Microsoft.EntityFrameworkCore; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Commons.Messages.Deploy; +using ZB.MOM.WW.OtOpcUa.Commons.Messages.Mesh; +using ZB.MOM.WW.OtOpcUa.Commons.Types; +using ZB.MOM.WW.OtOpcUa.Configuration; +using ZB.MOM.WW.OtOpcUa.Configuration.Entities; +using ZB.MOM.WW.OtOpcUa.Configuration.Enums; +using ZB.MOM.WW.OtOpcUa.ControlPlane.Coordinators; +using ZB.MOM.WW.OtOpcUa.ControlPlane.Tests.Harness; + +namespace ZB.MOM.WW.OtOpcUa.ControlPlane.Tests; + +/// +/// Gitea #1107 — the deploy dispatch used to go out exactly once, so a node that missed it (a DistributedPubSub +/// registry entry not yet gossiped to central, #1106; a failed gRPC dial) timed the deployment out at the apply +/// deadline. The coordinator now re-sends it, bounded, to the expected nodes whose ack has not arrived — and ONLY to +/// them: under #601 a same-revision dispatch makes a node whose apply was degraded re-apply. +/// +/// +/// The mesh router is a probe, so every dispatch the coordinator hands to the transport (original or re-send) is +/// observed directly. Every absence assertion is paired with a positive control proving re-sends were flowing. +/// +public sealed class ConfigPublishCoordinatorRedispatchTests : ControlPlaneActorTestBase +{ + private static readonly RevisionHash TestRevision = RevisionHash.Parse(new string('c', 64)); + private static readonly TimeSpan NoTimeout = TimeSpan.FromMinutes(5); + private static readonly TimeSpan Wait = TimeSpan.FromSeconds(5); + + private static IReadOnlyList Every(TimeSpan delay, int count) => Enumerable.Repeat(delay, count).ToList(); + + [Fact] + public void A_resend_goes_only_to_the_nodes_that_have_not_acked() + { + 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), 3))); + + var correlation = CorrelationId.NewId(); + actor.Tell(new DispatchDeployment(deploymentId, TestRevision, correlation)); + + var original = ExpectDispatch(router); + original.TargetNodes.ShouldBeNull(); + original.IsResend.ShouldBeFalse(); + + // site-a-1 answers before the first re-send is due. + actor.Tell(new ApplyAck(deploymentId, NodeId.Parse("site-a-1:4053"), ApplyAckOutcome.Applied, null, correlation)); + + var resend = ExpectDispatch(router); + resend.DeploymentId.ShouldBe(deploymentId); + resend.RevisionHash.ShouldBe(TestRevision); + resend.CorrelationId.ShouldBe(original.CorrelationId); // the SAME dispatch, re-sent + resend.TargetNodes.ShouldBe(["site-a-2:4053"]); + } + + [Fact] + public void An_ack_whose_write_is_still_in_flight_already_counts_as_answered() + { + // The ack write is off-thread; a node whose ack ARRIVED must never be re-sent to, however slow the ConfigDb. + 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(250), 3))); + + actor.Tell(new DispatchDeployment(deploymentId, TestRevision, CorrelationId.NewId())); + ExpectDispatch(router); + actor.Tell(new ApplyAck(deploymentId, NodeId.Parse("SITE-A-2:4053"), ApplyAckOutcome.Applied, null, CorrelationId.NewId())); + + // Three re-sends (the positive control: re-sends ARE flowing), every one naming only site-a-1. + for (var i = 0; i < 3; i++) + ExpectDispatch(router).TargetNodes.ShouldBe(["site-a-1:4053"]); + } + + [Fact] + public void Resends_stop_once_every_expected_node_has_acked() + { + 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(200), 10))); + + actor.Tell(new DispatchDeployment(deploymentId, TestRevision, CorrelationId.NewId())); + ExpectDispatch(router); + // Positive control: the silent node IS being re-sent to. + ExpectDispatch(router).TargetNodes.ShouldBe(["site-a-1:4053"]); + + actor.Tell(new ApplyAck(deploymentId, NodeId.Parse("site-a-1:4053"), ApplyAckOutcome.Applied, null, CorrelationId.NewId())); + AwaitStatus(dbFactory, DeploymentStatus.Sealed); + + // Seven more re-sends were left on the schedule (1.4 s): none may go out after the seal. + router.ExpectNoMsg(TimeSpan.FromMilliseconds(800), TestContext.Current.CancellationToken); + } + + [Fact] + public void A_fully_acked_dispatch_is_never_resent_while_a_silent_one_is() + { + var dbFactory = NewInMemoryDbFactory(); + var schedule = Every(TimeSpan.FromMilliseconds(200), 3); + SeedNodes(dbFactory, "site-a-1:4053"); + + // Acked before the first re-send was due: nothing after the original. + var acked = SeedDispatchingDeployment(dbFactory); + var router = CreateTestProbe(); + var actor = Sys.ActorOf(ConfigPublishCoordinator.Props(dbFactory, NoTimeout, router.Ref, redispatchSchedule: schedule)); + actor.Tell(new DispatchDeployment(acked, TestRevision, CorrelationId.NewId())); + ExpectDispatch(router); + actor.Tell(new ApplyAck(acked, NodeId.Parse("site-a-1:4053"), ApplyAckOutcome.Applied, null, CorrelationId.NewId())); + AwaitStatus(dbFactory, DeploymentStatus.Sealed, acked); + router.ExpectNoMsg(TimeSpan.FromMilliseconds(700), TestContext.Current.CancellationToken); + + // Positive control on the same coordinator and schedule: a deployment nobody acks IS re-sent. + var silent = SeedDispatchingDeployment(dbFactory); + actor.Tell(new DispatchDeployment(silent, TestRevision, CorrelationId.NewId())); + ExpectDispatch(router).DeploymentId.ShouldBe(silent); + var resend = ExpectDispatch(router); + resend.DeploymentId.ShouldBe(silent); + resend.IsResend.ShouldBeTrue(); + } + + [Fact] + public void Resends_are_bounded_by_the_schedule() + { + var dbFactory = NewInMemoryDbFactory(); + var deploymentId = SeedDispatchingDeployment(dbFactory); + SeedNodes(dbFactory, "site-a-1:4053"); + var router = CreateTestProbe(); + Sys.ActorOf(ConfigPublishCoordinator.Props( + dbFactory, NoTimeout, router.Ref, redispatchSchedule: Every(TimeSpan.FromMilliseconds(150), 3))) + .Tell(new DispatchDeployment(deploymentId, TestRevision, CorrelationId.NewId())); + + ExpectDispatch(router).IsResend.ShouldBeFalse(); + for (var i = 0; i < 3; i++) ExpectDispatch(router).IsResend.ShouldBeTrue(); + router.ExpectNoMsg(TimeSpan.FromMilliseconds(600), TestContext.Current.CancellationToken); + } + + [Fact] + public void Resends_stay_inside_the_window_and_stop_at_the_deadline() + { + // A 1 s deadline ⇒ re-sends only in its first half; 100 ms steps ⇒ at most 4-5 re-sends, then the TimedOut + // seal, then silence — although the schedule has 30 entries. + var dbFactory = NewInMemoryDbFactory(); + var deploymentId = SeedDispatchingDeployment(dbFactory); + SeedNodes(dbFactory, "site-a-1:4053"); + var router = CreateTestProbe(); + Sys.ActorOf(ConfigPublishCoordinator.Props( + dbFactory, TimeSpan.FromSeconds(1), router.Ref, redispatchSchedule: Every(TimeSpan.FromMilliseconds(100), 30))) + .Tell(new DispatchDeployment(deploymentId, TestRevision, CorrelationId.NewId())); + + ExpectDispatch(router).IsResend.ShouldBeFalse(); + AwaitStatus(dbFactory, DeploymentStatus.TimedOut); + var resends = router.ReceiveWhile(TimeSpan.FromMilliseconds(100), m => (MeshCommand)m, cancellationToken: TestContext.Current.CancellationToken); + // Positive control: re-sends did happen before the deadline... + resends.Count.ShouldBeGreaterThanOrEqualTo(1); + resends.Count.ShouldBeLessThanOrEqualTo(5); + // ...and none after it. + router.ExpectNoMsg(TimeSpan.FromMilliseconds(600), TestContext.Current.CancellationToken); + } + + [Fact] + public void A_superseded_deployment_is_no_longer_resent() + { + var dbFactory = NewInMemoryDbFactory(); + SeedNodes(dbFactory, "site-a-1:4053"); + var first = SeedDispatchingDeployment(dbFactory); + var router = CreateTestProbe(); + var actor = Sys.ActorOf(ConfigPublishCoordinator.Props( + dbFactory, NoTimeout, router.Ref, redispatchSchedule: Every(TimeSpan.FromMilliseconds(150), 20))); + + actor.Tell(new DispatchDeployment(first, TestRevision, CorrelationId.NewId())); + ExpectDispatch(router).DeploymentId.ShouldBe(first); + ExpectDispatch(router).DeploymentId.ShouldBe(first); // positive control: the first IS being re-sent + + var second = SeedDispatchingDeployment(dbFactory); + actor.Tell(new DispatchDeployment(second, TestRevision, CorrelationId.NewId())); + // Drain up to the second's original (a first re-send may already have been queued ahead of it). + router.FishForMessage(m => ((DispatchDeployment)m.Message) is { DeploymentId: var id, IsResend: false } && id == second, + Wait, cancellationToken: TestContext.Current.CancellationToken); + + var after = router.ReceiveWhile(TimeSpan.FromMilliseconds(400), m => (MeshCommand)m, msgs: 6, + cancellationToken: TestContext.Current.CancellationToken); + after.ShouldNotBeEmpty(); // the second IS re-sent... + after.ShouldAllBe(m => ((DispatchDeployment)m.Message).DeploymentId == second); // ...the first never again + AwaitStatus(dbFactory, DeploymentStatus.TimedOut, first); + } + + [Fact] + public void A_recovered_in_flight_deployment_is_resent_to_its_unacked_nodes_only() + { + // A singleton fail-over: the new incarnation recovers the deployment and resumes re-sending to the node that + // has not acked — never to the one whose Applied row already landed. + var dbFactory = NewInMemoryDbFactory(); + var deploymentId = SeedDispatchingDeployment(dbFactory, DeploymentStatus.AwaitingApplyAcks); + using (var db = dbFactory.CreateDbContext()) + { + db.NodeDeploymentStates.Add(new NodeDeploymentState + { + NodeId = "site-a-1:4053", DeploymentId = deploymentId.Value, Status = NodeDeploymentStatus.Applied, + }); + db.NodeDeploymentStates.Add(new NodeDeploymentState + { + NodeId = "site-a-2:4053", DeploymentId = deploymentId.Value, Status = NodeDeploymentStatus.Applying, + }); + db.SaveChanges(); + } + + var router = CreateTestProbe(); + Sys.ActorOf(ConfigPublishCoordinator.Props( + dbFactory, NoTimeout, router.Ref, redispatchSchedule: Every(TimeSpan.FromMilliseconds(200), 2))); + + var first = ExpectDispatch(router); + first.DeploymentId.ShouldBe(deploymentId); + first.RevisionHash.ShouldBe(TestRevision); + first.TargetNodes.ShouldBe(["site-a-2:4053"]); + ExpectDispatch(router).TargetNodes.ShouldBe(["site-a-2:4053"]); + router.ExpectNoMsg(TimeSpan.FromMilliseconds(500), TestContext.Current.CancellationToken); + } + + private static DispatchDeployment ExpectDispatch(TestProbe router) + { + var cmd = router.ExpectMsg(Wait, cancellationToken: TestContext.Current.CancellationToken); + cmd.Topic.ShouldBe(ConfigPublishCoordinator.DeploymentsTopic); + return cmd.Message.ShouldBeOfType(); + } + + private void AwaitStatus(IDbContextFactory dbFactory, DeploymentStatus status, DeploymentId? id = null) => + AwaitAssert(() => + { + using var db = dbFactory.CreateDbContext(); + var row = id is { } d ? db.Deployments.Single(x => x.DeploymentId == d.Value) : db.Deployments.Single(); + row.Status.ShouldBe(status); + }, duration: Wait, cancellationToken: TestContext.Current.CancellationToken); + + private static void SeedNodes(IDbContextFactory dbFactory, params string[] nodeIds) + { + using var db = dbFactory.CreateDbContext(); + db.ServerClusters.Add(new ServerCluster + { + ClusterId = "SITE-A", + Name = "Site A", + Enterprise = "zb", + Site = "site-a", + NodeCount = (byte)nodeIds.Length, + RedundancyMode = RedundancyMode.Warm, + CreatedBy = "test", + }); + foreach (var nodeId in nodeIds) + { + db.ClusterNodes.Add(new ClusterNode + { + NodeId = nodeId, + ClusterId = "SITE-A", + Host = nodeId.Split(':')[0], + ApplicationUri = $"urn:OtOpcUa:{nodeId}", + Enabled = true, + CreatedBy = "test", + }); + } + db.SaveChanges(); + } + + private static DeploymentId SeedDispatchingDeployment( + IDbContextFactory dbFactory, DeploymentStatus status = DeploymentStatus.Dispatching) + { + var id = DeploymentId.NewId(); + using var db = dbFactory.CreateDbContext(); + db.Deployments.Add(new Deployment + { + DeploymentId = id.Value, + RevisionHash = TestRevision.Value, + Status = status, + CreatedBy = "test", + CreatedAtUtc = DateTime.UtcNow, + }); + db.SaveChanges(); + return id; + } +} 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 new file mode 100644 index 000000000..8b33f6a44 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostActorRedispatchTests.cs @@ -0,0 +1,185 @@ +using System.Text.Json; +using Akka.Actor; +using Microsoft.EntityFrameworkCore; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Commons.Interfaces; +using ZB.MOM.WW.OtOpcUa.Commons.Messages.Deploy; +using ZB.MOM.WW.OtOpcUa.Commons.Types; +using ZB.MOM.WW.OtOpcUa.Configuration; +using ZB.MOM.WW.OtOpcUa.Runtime.DeploymentCache; +using ZB.MOM.WW.OtOpcUa.Runtime.Drivers; +using ZB.MOM.WW.OtOpcUa.Runtime.OpcUa; +using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.Drivers; + +/// +/// Gitea #1107 — the node side of the coordinator's dispatch re-send. A re-send names the nodes that have not +/// acked; it must never make a node apply the same deployment twice (under #601 a second apply of a degraded +/// revision is a full re-apply), and a late or duplicate copy must be harmless. +/// +[Collection("opcua-publish-meters")] +public sealed class DriverHostActorRedispatchTests : RuntimeActorTestBase +{ + private static readonly NodeId TestNode = NodeId.Parse("driver-test"); + private static readonly RevisionHash RevA = RevisionHash.Parse(new string('a', 64)); + private static readonly TimeSpan Quiet = TimeSpan.FromMilliseconds(400); + + [Fact] + public void A_resend_of_a_deployment_already_acked_degraded_re_sends_the_ack_instead_of_re_applying() + { + 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)); + + var dispatch = new DispatchDeployment(deploymentId, RevA, CorrelationId.NewId()); + actor.Tell(dispatch); + var rebuild = publish.FishForMessage(_ => true, PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + publish.Reply(new OpcUaPublishActor.RebuildCompleted(rebuild.Correlation, rebuild.DeploymentId, true, "failedNodes=1")); + var first = coordinator.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + first.Degraded.ShouldBeTrue(); + + // The coordinator never saw that ack and re-sends to this node (node id case differs, as SQL/DNS may). + actor.Tell(dispatch with { TargetNodes = ["DRIVER-TEST"] }); + + var again = coordinator.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + again.ShouldBe(first); // the SAME answer, not a new apply's + publish.ExpectNoMsg(Quiet, TestContext.Current.CancellationToken); + + // Positive control: an ORIGINAL dispatch of a degraded revision still re-applies (#601) — so the silence above + // is the re-send being recognised, not a host that has stopped applying. + actor.Tell(new DispatchDeployment(deploymentId, RevA, CorrelationId.NewId())); + publish.FishForMessage(_ => true, PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + } + + [Fact] + public void A_resend_addressed_to_another_node_is_ignored() + { + 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)); + + actor.Tell(new DispatchDeployment(deploymentId, RevA, CorrelationId.NewId(), TargetNodes: ["driver-other"])); + publish.ExpectNoMsg(Quiet, TestContext.Current.CancellationToken); + coordinator.ExpectNoMsg(TimeSpan.Zero, TestContext.Current.CancellationToken); + + // Positive control: the same re-send naming THIS node (never acked here) is a first apply. + actor.Tell(new DispatchDeployment(deploymentId, RevA, CorrelationId.NewId(), TargetNodes: ["driver-other", "driver-test"])); + var rebuild = publish.FishForMessage(_ => true, PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + publish.Reply(new OpcUaPublishActor.RebuildCompleted(rebuild.Correlation, rebuild.DeploymentId, false, null)); + coordinator.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken) + .Outcome.ShouldBe(ApplyAckOutcome.Applied); + } + + [Fact] + public void A_duplicate_while_the_ack_waits_on_the_address_space_outcome_does_not_apply_twice() + { + 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)); + + var dispatch = new DispatchDeployment(deploymentId, RevA, CorrelationId.NewId()); + actor.Tell(dispatch); + var rebuild = publish.FishForMessage(_ => true, PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + + // The ack is held on the outcome. Neither a re-send nor a plain duplicate may start a second apply. + actor.Tell(dispatch with { TargetNodes = [TestNode.Value] }); + actor.Tell(dispatch); + publish.ExpectNoMsg(Quiet, TestContext.Current.CancellationToken); + coordinator.ExpectNoMsg(TimeSpan.Zero, TestContext.Current.CancellationToken); + + // Exactly one ack, when the one apply's outcome lands. + actor.Tell(new OpcUaPublishActor.RebuildCompleted(rebuild.Correlation, rebuild.DeploymentId, false, null), publish.Ref); + coordinator.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken) + .Outcome.ShouldBe(ApplyAckOutcome.Applied); + coordinator.ExpectNoMsg(Quiet, TestContext.Current.CancellationToken); + publish.ExpectNoMsg(TimeSpan.Zero, TestContext.Current.CancellationToken); + } + + [Fact] + public void A_resend_arriving_mid_apply_does_not_start_a_second_apply() + { + var db = NewInMemoryDbFactory(); + var fetcher = new GatedFetcher(JsonSerializer.SerializeToUtf8Bytes(new { DriverInstances = Array.Empty() })); + 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)); + + try + { + var dispatch = new DispatchDeployment(deploymentId, RevA, CorrelationId.NewId()); + actor.Tell(dispatch); + AwaitAssert(() => fetcher.Calls.ShouldBe(1), duration: PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + + // Re-sends while the artifact fetch is still parked. + actor.Tell(dispatch with { TargetNodes = [TestNode.Value] }); + actor.Tell(dispatch with { TargetNodes = [TestNode.Value] }); + + fetcher.Release(); + // Presence: the one apply acks... + coordinator.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken) + .Outcome.ShouldBe(ApplyAckOutcome.Applied); + // ...absence: no second fetch, no second ack. + coordinator.ExpectNoMsg(Quiet, TestContext.Current.CancellationToken); + fetcher.Calls.ShouldBe(1); + } + finally + { + fetcher.Release(); + } + } + + private (IDbContextFactory Db, DeploymentId Id) SeedOneTagDeployment() + { + var db = NewInMemoryDbFactory(); + var id = V3ArtifactSeeder.SeedV3Deployment(db, RevA, + rawTags: new[] { (Driver: "drv-1", DriverName: "Modbus", Device: "dev1", Tag: "speed", DataType: "Double", Writable: false) }, + unsRefs: new[] { (Area: "filling", Line: "line1", Equip: "station1", BackingTag: "speed", Effective: (string?)null) }); + return (db, id); + } + + /// A fetcher whose first fetch parks until . + private sealed class GatedFetcher(byte[] bytes) : IDeploymentArtifactFetcher + { + private readonly TaskCompletionSource _gate = new(TaskCreationOptions.RunContinuationsAsynchronously); + private int _calls; + + public int Calls => Volatile.Read(ref _calls); + + public void Release() => _gate.TrySetResult(); + + public async Task FetchAsync(string deploymentId, string expectedRevisionHash, CancellationToken ct) + { + if (Interlocked.Increment(ref _calls) == 1) await _gate.Task.ConfigureAwait(false); + return bytes; + } + } + + private sealed class NullArtifactCache : IDeploymentArtifactCache + { + public Task StoreAsync(string clusterId, string deploymentId, string revisionHash, + byte[] artifact, CancellationToken ct = default) + => Task.CompletedTask; + + public Task GetCurrentAsync(string clusterId, CancellationToken ct = default) + => Task.FromResult(null); + + public Task GetCurrentUnkeyedAsync(CancellationToken ct = default) + => Task.FromResult(null); + } +}