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
@@ -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