Merge #1107: deploy dispatch is re-sent (+5/+15/+35 s, within half the remaining ApplyDeadline) to un-acked nodes only via TargetNodes; nodes replay a remembered ack instead of re-applying, ignore re-sends not addressed to them, and no longer double-apply a duplicate while an ack is held

This commit is contained in:
Joseph Doherty
2026-12-04 22:42:50 -05:00
14 changed files with 865 additions and 23 deletions
+6 -1
View File
@@ -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
+1 -1
View File
@@ -225,7 +225,7 @@ Security__Ldap__GroupToRole__<AD group>=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).
+37 -3
View File
@@ -809,10 +809,44 @@ 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 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.
### What an `Applied` ack means: the degraded-apply amendment (Gitea #601)
@@ -7,7 +7,32 @@ namespace ZB.MOM.WW.OtOpcUa.Commons.Messages.Deploy;
/// <c>DriverHostActor</c>. Tells the node to fetch the deployment artifact identified by
/// <paramref name="DeploymentId"/> + <paramref name="RevisionHash"/> and apply it.
/// </summary>
/// <param name="DeploymentId">The deployment to apply.</param>
/// <param name="RevisionHash">The revision (SHA-256 of the artifact bytes) the deployment carries.</param>
/// <param name="CorrelationId">Correlation for tracing the apply and its ack.</param>
/// <param name="TargetNodes">
/// #1107 — <see langword="null"/> (or empty) on the ORIGINAL dispatch, which every node applies. Set only on a
/// coordinator RE-SEND, naming the nodes (<c>ClusterNode.NodeId</c>, 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 <c>docs/Redundancy.md</c> §"Dispatch re-send").
/// </param>
public sealed record DispatchDeployment(
DeploymentId DeploymentId,
RevisionHash RevisionHash,
CorrelationId CorrelationId);
CorrelationId CorrelationId,
IReadOnlyList<string>? TargetNodes = null)
{
/// <summary>Whether this is a coordinator re-send (#1107) rather than the original dispatch.</summary>
public bool IsResend => TargetNodes is { Count: > 0 };
/// <summary>
/// Whether the node <paramref name="nodeId"/> should act on this dispatch: always for the original dispatch,
/// and for a re-send only when the node is named in <see cref="TargetNodes"/> (case-insensitive, matching the
/// coordinator's expected-ack comparison).
/// </summary>
/// <param name="nodeId">The receiving node's id (<c>host:port</c>).</param>
/// <returns><see langword="true"/> when the node should handle it.</returns>
public bool IsAddressedTo(string nodeId) =>
!IsResend || TargetNodes!.Any(t => string.Equals(t, nodeId, StringComparison.OrdinalIgnoreCase));
}
@@ -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;
}
/// <summary>Rebuilds the domain record from its wire form.</summary>
@@ -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
@@ -32,6 +32,11 @@ public static class OtOpcUaTelemetry
Meter.CreateCounter<long>("otopcua.deploy.applied", unit: "{deployment}",
description: "Deployments applied by a driver-role node (outcome=ack|reject).");
/// <summary>#1107: dispatch re-sends by the deploy coordinator, counted per targeted (un-acked) node.</summary>
public static readonly Counter<long> DeploymentRedispatched =
Meter.CreateCounter<long>("otopcua.deploy.redispatched", unit: "{node}",
description: "Deployment dispatches re-sent by the coordinator to nodes that had not acked yet.");
/// <summary>Time from DriverHostActor receiving DispatchDeployment to emitting the ack/reject.</summary>
public static readonly Histogram<double> DeploymentApplyDurationSec =
Meter.CreateHistogram<double>("otopcua.deploy.apply.duration", unit: "s",
@@ -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.
@@ -40,11 +40,12 @@ namespace ZB.MOM.WW.OtOpcUa.ControlPlane.Communication;
/// while the deployment seals green.
/// </para>
/// <para>
/// <b>Fire-and-forget, on both transports.</b> 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).
/// <b>Fire-and-forget, on both transports — at THIS layer.</b> 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 <c>ConfigPublishCoordinator</c> (#1107),
/// driven by the acks it has not received rather than by this actor's dial outcomes: a re-send
/// names its <see cref="DispatchDeployment.TargetNodes"/>, and the gRPC fan dials only those.
/// </para>
/// </remarks>
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);
}
@@ -86,6 +86,18 @@ namespace ZB.MOM.WW.OtOpcUa.ControlPlane.Coordinators;
/// outcome arrives, keeping the restart-and-recover contract. The recovery path (<see cref="ApplyRecovery"/>, once per
/// singleton start) runs the same work inline, so a failure there stays a failed load retried on the backoff.
/// </para>
/// <para>
/// <b>The dispatch is re-sent to nodes that have not acked (#1107).</b> It used to go out exactly once: on
/// DistributedPubSub a node whose <c>deployments</c> 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
/// <see cref="DefaultRedispatchSchedule"/> re-sends the SAME dispatch (same DeploymentId / RevisionHash / CorrelationId)
/// with <see cref="DispatchDeployment.TargetNodes"/> naming only the expected nodes whose ack has not arrived, bounded by
/// the schedule and by <see cref="RedispatchWindowFraction"/> 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.
/// </para>
/// </summary>
public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithUnboundedStash
{
@@ -101,7 +113,33 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU
/// <summary>Ceiling of the recovery-load retry backoff (lmxopcua#868).</summary>
public static readonly TimeSpan DefaultLoadRetryMax = TimeSpan.FromSeconds(30);
/// <summary>
/// #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
/// <see cref="RedispatchWindowFraction"/> of the apply deadline, so the last one always lands with most of
/// the deadline still left for the node to apply and ack.
/// </summary>
public static readonly IReadOnlyList<TimeSpan> DefaultRedispatchSchedule =
[TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(20)];
/// <summary>#1107: re-sends are only scheduled inside this fraction of the (remaining) apply deadline.</summary>
public const double RedispatchWindowFraction = 0.5;
private readonly IDbContextFactory<OtOpcUaConfigDbContext> _dbFactory;
private readonly IReadOnlyList<TimeSpan> _redispatchSchedule;
/// <summary>
/// #1107: the dispatch of the CURRENT deployment as it went out (same DeploymentId / RevisionHash /
/// CorrelationId), re-sent with <see cref="DispatchDeployment.TargetNodes"/> naming the un-acked nodes.
/// Null when nothing is in flight or no re-send is armed.
/// </summary>
private DispatchDeployment? _resendable;
/// <summary>#1107: how many re-sends of <see cref="_resendable"/> have gone out.</summary>
private int _redispatchAttempts;
/// <summary>#1107: no re-send is scheduled to fire after this instant (a fraction of the apply deadline).</summary>
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
/// <param name="readiness">Where the recovery-load state is reported for health, or <see langword="null"/>.</param>
/// <param name="loadRetryMin">First recovery-load retry delay; <see langword="null"/> = <see cref="DefaultLoadRetryMin"/>.</param>
/// <param name="loadRetryMax">Recovery-load retry ceiling; <see langword="null"/> = <see cref="DefaultLoadRetryMax"/>.</param>
/// <param name="redispatchSchedule">
/// #1107: delays between dispatch re-sends to un-acked nodes; <see langword="null"/> =
/// <see cref="DefaultRedispatchSchedule"/>, empty = never re-send.
/// </param>
/// <returns>The Akka.NET <see cref="Akka.Actor.Props"/> used to spawn this actor.</returns>
public static Props Props(
IDbContextFactory<OtOpcUaConfigDbContext> 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<TimeSpan>? redispatchSchedule = null) =>
Akka.Actor.Props.Create(() => new ConfigPublishCoordinator(
dbFactory, applyDeadline ?? DefaultApplyDeadline, meshRouter, readiness,
loadRetryMin ?? DefaultLoadRetryMin, loadRetryMax ?? DefaultLoadRetryMax));
loadRetryMin ?? DefaultLoadRetryMin, loadRetryMax ?? DefaultLoadRetryMax,
redispatchSchedule ?? DefaultRedispatchSchedule));
/// <summary>
/// Initializes a new instance of the <see cref="ConfigPublishCoordinator"/> class.
@@ -245,14 +289,17 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU
/// <param name="readiness">Where the recovery-load state is reported, or <see langword="null"/>.</param>
/// <param name="loadRetryMin">First recovery-load retry delay.</param>
/// <param name="loadRetryMax">Recovery-load retry ceiling.</param>
/// <param name="redispatchSchedule">#1107 re-send delays; <see langword="null"/> = <see cref="DefaultRedispatchSchedule"/>.</param>
public ConfigPublishCoordinator(
IDbContextFactory<OtOpcUaConfigDbContext> dbFactory,
TimeSpan applyDeadline,
IActorRef? meshRouter = null,
ConfigPublishCoordinatorReadiness? readiness = null,
TimeSpan? loadRetryMin = null,
TimeSpan? loadRetryMax = null)
TimeSpan? loadRetryMax = null,
IReadOnlyList<TimeSpan>? redispatchSchedule = null)
{
_redispatchSchedule = redispatchSchedule ?? DefaultRedispatchSchedule;
_dbFactory = dbFactory;
_applyDeadline = applyDeadline;
_meshRouter = meshRouter;
@@ -294,6 +341,7 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU
Receive<AckPersisted>(HandleAckPersisted);
Receive<RetryAckPersist>(HandleRetryAckPersist);
Receive<DeadlineElapsed>(HandleDeadline);
Receive<RedispatchTick>(HandleRedispatchTick);
Receive<SubscribeAck>(_ => { /* DPS subscribe confirmation */ });
// A late load outcome / retry tick cannot normally arrive once Ready; ignored, never stashed.
Receive<RecoveryLoaded>(_ => { });
@@ -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
}
}
/// <summary>
/// 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.
/// </summary>
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));
}
/// <summary>
/// #1107: arms the bounded re-send of <paramref name="dispatch"/> to nodes that have not acked. Re-sends follow
/// <see cref="_redispatchSchedule"/> 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 (<see cref="ResetForNext"/> cancels
/// the timer and every tick carries its deployment id), the schedule runs out, or the re-send window —
/// <see cref="RedispatchWindowFraction"/> of <paramref name="deadlineLeft"/> — closes.
/// </summary>
/// <param name="dispatch">The dispatch as originally sent (no targets).</param>
/// <param name="deadlineLeft">How long until this deployment's apply deadline.</param>
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();
}
/// <summary>Schedules the next re-send, unless the schedule is spent or it would land past the window.</summary>
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);
}
/// <summary>
/// #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).
/// </summary>
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();
}
/// <summary>Whether <paramref name="node"/>'s ack for the CURRENT deployment has arrived (counted or not yet persisted).</summary>
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));
/// <summary>
/// Writes one terminal status (and optional reason) for <paramref name="id"/>, 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";
/// <summary>#1107: time to re-send the current dispatch to the nodes that have not acked it.</summary>
private sealed record RedispatchTick(DeploymentId DeploymentId);
/// <summary>The outcome of an off-thread ack write (#996 / H-6): <see langword="null"/> error = persisted.</summary>
private sealed record AckPersisted(ApplyAck Ack, Exception? Error);
@@ -355,6 +355,21 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
private DeploymentId? _applyingDeploymentId;
/// <summary>How many recent deployments' final acks <see cref="_recentAcks"/> remembers (#1107).</summary>
private const int RecentAckCapacity = 16;
/// <summary>
/// #1107: the last ack this node SENT for each of its most recent deployments (bounded, oldest evicted). A
/// coordinator RE-SEND (<see cref="DispatchDeployment.IsResend"/>) 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.
/// </summary>
private readonly Dictionary<DeploymentId, ApplyAck> _recentAcks = new();
/// <summary>Insertion order of <see cref="_recentAcks"/>, for eviction.</summary>
private readonly Queue<DeploymentId> _recentAckOrder = new();
private readonly Dictionary<string, ChildEntry> _children = new(StringComparer.Ordinal);
/// <summary>Per-driver <see cref="DependencyConsumerMuxAdapter"/> children — one for each spawned driver
@@ -1920,6 +1935,9 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
Receive<DriverInstanceActor.AcquisitionDemandApplied>(_ => { });
Receive<DispatchDeployment>(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<DispatchDeployment>(_ =>
Receive<DispatchDeployment>(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.
@@ -5489,6 +5535,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);
}
/// <summary>#1107: records the newest ack per deployment, evicting the oldest deployment past the capacity.</summary>
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
@@ -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()
{
@@ -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()
{
@@ -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;
/// <summary>
/// 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.
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
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<TimeSpan> 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<MeshCommand>(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<MeshCommand>(m => ((DispatchDeployment)m.Message) is { DeploymentId: var id, IsResend: false } && id == second,
Wait, cancellationToken: TestContext.Current.CancellationToken);
var after = router.ReceiveWhile<MeshCommand>(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<MeshCommand>(Wait, cancellationToken: TestContext.Current.CancellationToken);
cmd.Topic.ShouldBe(ConfigPublishCoordinator.DeploymentsTopic);
return cmd.Message.ShouldBeOfType<DispatchDeployment>();
}
private void AwaitStatus(IDbContextFactory<OtOpcUaConfigDbContext> 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<OtOpcUaConfigDbContext> 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<OtOpcUaConfigDbContext> 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;
}
}
@@ -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;
/// <summary>
/// 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.
/// </summary>
[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<string> { "driver" },
opcUaPublishActor: publish.Ref));
var dispatch = new DispatchDeployment(deploymentId, RevA, CorrelationId.NewId());
actor.Tell(dispatch);
var rebuild = publish.FishForMessage<OpcUaPublishActor.RebuildAddressSpace>(_ => true, PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
publish.Reply(new OpcUaPublishActor.RebuildCompleted(rebuild.Correlation, rebuild.DeploymentId, true, "failedNodes=1"));
var first = coordinator.ExpectMsg<ApplyAck>(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<ApplyAck>(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<OpcUaPublishActor.RebuildAddressSpace>(_ => 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<string> { "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<OpcUaPublishActor.RebuildAddressSpace>(_ => true, PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
publish.Reply(new OpcUaPublishActor.RebuildCompleted(rebuild.Correlation, rebuild.DeploymentId, false, null));
coordinator.ExpectMsg<ApplyAck>(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<string> { "driver" },
opcUaPublishActor: publish.Ref));
var dispatch = new DispatchDeployment(deploymentId, RevA, CorrelationId.NewId());
actor.Tell(dispatch);
var rebuild = publish.FishForMessage<OpcUaPublishActor.RebuildAddressSpace>(_ => 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<ApplyAck>(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<object>() }));
var deploymentId = DeploymentId.NewId();
var coordinator = CreateTestProbe();
var actor = Sys.ActorOf(DriverHostActor.Props(
db, TestNode, coordinator.Ref,
localRoles: new HashSet<string> { "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<ApplyAck>(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<OtOpcUaConfigDbContext> 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);
}
/// <summary>A fetcher whose first fetch parks until <see cref="Release"/>.</summary>
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<byte[]?> 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<CachedDeploymentArtifact?> GetCurrentAsync(string clusterId, CancellationToken ct = default)
=> Task.FromResult<CachedDeploymentArtifact?>(null);
public Task<CachedDeploymentArtifact?> GetCurrentUnkeyedAsync(CancellationToken ct = default)
=> Task.FromResult<CachedDeploymentArtifact?>(null);
}
}