Merge #1111 deploy re-send residuals: a re-send retries a Failed apply (newest-answered, no held ack); re-sends carry DeadlineRemaining so a late-reached node caps its address-space wait; coordinator keeps a node's Applied over a late stale Failed; in-memory acks + late-Failed-seal residual documented

This commit is contained in:
Joseph Doherty
2026-12-05 00:53:03 -05:00
11 changed files with 533 additions and 15 deletions
@@ -14,14 +14,25 @@ namespace ZB.MOM.WW.OtOpcUa.Commons.Messages.Deploy;
/// #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:
/// was lost) or is still applying it re-sends its ack / keeps applying instead of applying a second time — except
/// a remembered FAILED ack, which the node retries (#1111: a failed apply left it on last-good config). Additive:
/// a pre-#1107 node ignores the member (see <c>docs/Redundancy.md</c> §"Dispatch re-send").
/// </param>
/// <param name="DeadlineRemaining">
/// #1111 — <see langword="null"/> on the ORIGINAL dispatch (the node assumes the full
/// <see cref="DeployTimings.ApplyDeadline"/>). Set only on a coordinator RE-SEND: how much of central's apply
/// deadline was left when the re-send went out. A RELATIVE duration, never an absolute instant, so central's and
/// the node's clocks need not agree. The node bounds its held Applied ack's address-space wait to this minus
/// <see cref="DeployTimings.ApplyOutcomeSafetyMargin"/> (measured from receipt), so a node first reached by a late
/// re-send still acks "Applied (degraded)" before central's deadline instead of sealing <c>TimedOut</c>. Additive:
/// a pre-#1111 node ignores it and keeps its full 105 s wait.
/// </param>
public sealed record DispatchDeployment(
DeploymentId DeploymentId,
RevisionHash RevisionHash,
CorrelationId CorrelationId,
IReadOnlyList<string>? TargetNodes = null)
IReadOnlyList<string>? TargetNodes = null,
TimeSpan? DeadlineRemaining = null)
{
/// <summary>Whether this is a coordinator re-send (#1107) rather than the original dispatch.</summary>
public bool IsResend => TargetNodes is { Count: > 0 };
@@ -59,6 +59,9 @@ public static class MeshTransportDtoMapper
// #1107: only a re-send names targets; the original dispatch leaves the repeated field empty.
if (message.TargetNodes is { Count: > 0 } targets)
proto.TargetNodes.AddRange(targets.Where(t => !string.IsNullOrWhiteSpace(t)));
// #1111: presence = a re-send carrying central's remaining deadline; absent = the full default.
if (message.DeadlineRemaining is { } remaining)
proto.DeadlineRemainingMs = Math.Max(0L, (long)remaining.TotalMilliseconds);
return proto;
}
@@ -76,9 +79,18 @@ public static class MeshTransportDtoMapper
RevisionHash.Parse(proto.RevisionHash),
CorrelationId.Parse(proto.CorrelationId),
// #1107: an empty repeated field is the original dispatch (null), never "addressed to nobody".
proto.TargetNodes.Count > 0 ? proto.TargetNodes.ToList() : null);
proto.TargetNodes.Count > 0 ? proto.TargetNodes.ToList() : null,
// #1111: absent (an original dispatch, or a pre-#1111 central) = null = the node's full default wait. Clamped:
// the bound only ever SHORTENS the node's wait, and an out-of-range wire value must not throw here (a
// TimeSpan overflow) or overflow the node's tick arithmetic — negative is "spent", a day is "unbounded".
proto.HasDeadlineRemainingMs
? TimeSpan.FromMilliseconds(Math.Clamp(proto.DeadlineRemainingMs, 0L, MaxDeadlineRemainingMs))
: null);
}
/// <summary>#1111: the largest <c>deadline_remaining_ms</c> taken off the wire (one day — far past any apply deadline).</summary>
private const long MaxDeadlineRemainingMs = 24L * 60 * 60 * 1000;
// ---------------------------------------------------------------- RestartDriver
/// <summary>Projects <paramref name="message"/> onto its wire form.</summary>
@@ -96,6 +96,11 @@ message DispatchDeploymentCommand {
// re-send to the ClusterNode ids that have not acked yet. Central already dials only those nodes on
// this transport, so this is belt-and-braces for the node; a pre-#1107 node ignores the field.
repeated string target_nodes = 4;
// #1111 — ADDITIVE. Absent on the original dispatch; set on a re-send to the milliseconds of central's
// apply deadline left when it went out (RELATIVE — no clock agreement needed). The node bounds its
// address-space wait to this minus the 15 s safety margin. A pre-#1111 node ignores the field; a
// pre-#1111 central never sets it (the node then waits its full default).
optional int64 deadline_remaining_ms = 5;
}
// Mirrors ZB.MOM.WW.OtOpcUa.Commons.Messages.Admin.RestartDriver.
@@ -140,6 +140,13 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU
/// <summary>#1107: no re-send is scheduled to fire after this instant (a fraction of the apply deadline).</summary>
private DateTime _redispatchWindowEndsUtc;
/// <summary>
/// #1111: when the current deployment's apply deadline falls (as armed; a later persist-deferral only
/// lengthens it, so the remaining time a re-send reports is never an over-estimate). Each re-send carries
/// <see cref="DispatchDeployment.DeadlineRemaining"/> computed from it.
/// </summary>
private DateTime _redispatchDeadlineUtc;
private readonly TimeSpan _applyDeadline;
private readonly TimeSpan _loadRetryMin;
private readonly TimeSpan _loadRetryMax;
@@ -823,7 +830,9 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU
_expectedAcks = outcome.Expected!;
// The ORIGINAL dispatch addresses every node, whatever a (recovered/queued) message carried.
var original = msg.TargetNodes is null ? msg : msg with { TargetNodes = null };
var original = msg.TargetNodes is null && msg.DeadlineRemaining is null
? msg
: msg with { TargetNodes = null, DeadlineRemaining = null };
PublishDispatch(original);
Timers.StartSingleTimer(DeadlineTimerKey, new DeadlineElapsed(msg.DeploymentId), _applyDeadline);
ArmRedispatch(original, _applyDeadline);
@@ -870,6 +879,7 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU
if (_expectedAcks.Count == 0 || _redispatchSchedule.Count == 0 || deadlineLeft <= TimeSpan.Zero) return;
_resendable = dispatch;
_redispatchDeadlineUtc = DateTime.UtcNow + deadlineLeft;
_redispatchWindowEndsUtc = DateTime.UtcNow + TimeSpan.FromTicks((long)(deadlineLeft.Ticks * RedispatchWindowFraction));
ScheduleNextRedispatch();
}
@@ -924,7 +934,14 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU
"nodes that already acked are not re-sent to, and a node still applying ignores the copy",
dispatch.DeploymentId, string.Join(", ", outstanding), _redispatchAttempts, _redispatchSchedule.Count);
ZB.MOM.WW.OtOpcUa.Commons.Observability.OtOpcUaTelemetry.DeploymentRedispatched.Add(outstanding.Count);
PublishDispatch(dispatch with { TargetNodes = outstanding });
// #1111: tell the node how much of the deadline is left, so a node first reached by a late re-send bounds its
// address-space wait to fit inside it (it would otherwise wait its full 105 s and miss the deadline).
var deadlineRemaining = _redispatchDeadlineUtc - DateTime.UtcNow;
PublishDispatch(dispatch with
{
TargetNodes = outstanding,
DeadlineRemaining = deadlineRemaining > TimeSpan.Zero ? deadlineRemaining : TimeSpan.Zero,
});
ScheduleNextRedispatch();
}
@@ -977,11 +994,41 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU
return;
}
// #1111 review: within one deployment an Applied (clean or degraded) ack from a node is never overwritten by a
// later Failed from that node. A node re-applies a deployment only after its OWN Failed (the re-send retry), so a
// Failed arriving after that node's Applied can only be a stale or duplicate delivery of the earlier Failed (the
// gRPC ack sender walks endpoints, and a timed-out call may still have landed). Discarded BEFORE the persist, so
// the row is not flipped back to Failed either.
if (msg.Outcome == ApplyAckOutcome.Failed && HasAppliedAckFrom(msg.NodeId))
{
_log.Info(
"Discarding a late Failed ApplyAck from {Node} for {Id}: that node's Applied ack for this deployment " +
"already arrived (a Failed after Applied is a stale/duplicate delivery of the ack the re-send retry replaced)",
msg.NodeId, msg.DeploymentId);
// The stale Failed may itself be the node's unpersisted entry (its write failed and is on a retry tick that
// re-enters here): drop it, or the deadline would wait on a retry this guard now always discards.
if (_unpersisted.TryGetValue(msg.NodeId, out var parked) && parked.Ack.Outcome == ApplyAckOutcome.Failed)
DropUnpersisted(msg.NodeId);
return;
}
// Persist FIRST: the row is the system of record (driver-only nodes never write their own, and nodes do not
// resend). A throw here used to restart the actor and drop the ack; it is re-queued instead.
StartAckPersist(msg);
}
/// <summary>
/// #1111 review: whether an Applied (clean or degraded) ack of the CURRENT deployment from <paramref name="node"/>
/// has arrived — counted, held for a persist retry, being persisted, or parked behind a write.
/// </summary>
private bool HasAppliedAckFrom(NodeId node) =>
(_acks.TryGetValue(node, out var counted) && counted == ApplyAckOutcome.Applied)
|| (_unpersisted.TryGetValue(node, out var held) && IsAppliedForCurrent(held.Ack))
|| (_persisting.TryGetValue(node, out var inflight) && IsAppliedForCurrent(inflight))
|| (_pendingBehind.TryGetValue(node, out var behind) && IsAppliedForCurrent(behind));
private bool IsAppliedForCurrent(ApplyAck ack) => ack.Outcome == ApplyAckOutcome.Applied && IsForCurrent(ack);
/// <summary>
/// lmxopcua#996 (review H-6): the ack write runs OFF the actor thread and its outcome comes back as
/// <see cref="AckPersisted"/>. The write used to be a blocking <c>SaveChanges</c> in the handler, so with the
@@ -362,7 +362,8 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
/// #1107: the last ack this node SENT for each of its most recent deployments (bounded, oldest evicted). A
/// coordinator RE-SEND (<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:
/// second apply of a degraded revision is exactly what #601 makes a same-revision dispatch do. A remembered
/// <c>Failed</c> ack is the exception (#1111): see <see cref="_lastAnsweredDeploymentId"/>. 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();
@@ -370,6 +371,26 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
/// <summary>Insertion order of <see cref="_recentAcks"/>, for eviction.</summary>
private readonly Queue<DeploymentId> _recentAckOrder = new();
/// <summary>
/// #1111: the deployment this node most recently PRODUCED an ack for (any outcome; set by
/// <see cref="RememberAck"/> — a replay of a remembered ack does not move it). A re-send of a deployment whose remembered ack is <c>Failed</c> is
/// re-attempted only while that deployment is still this node's latest answer — retrying an OLDER failed
/// deployment after a newer one was applied would roll the node back.
/// </summary>
private DeploymentId? _lastAnsweredDeploymentId;
/// <summary>
/// #1111: the address-space-wait bound for the apply started by a RE-SEND that carried
/// <see cref="DispatchDeployment.DeadlineRemaining"/> — its correlation and the local
/// <see cref="Environment.TickCount64"/> instant (central's remaining deadline, measured from receipt, minus
/// <see cref="DeployTimings.ApplyOutcomeSafetyMargin"/>) by which the held Applied ack must be released.
/// <see langword="null"/> for an original dispatch (the full <see cref="_applyOutcomeTimeout"/> applies).
/// </summary>
private (CorrelationId Correlation, long ReleaseByTick)? _applyOutcomeReleaseBy;
/// <summary>#1111: the shortest address-space wait a late re-send's bound can shrink to.</summary>
internal static readonly TimeSpan MinBoundedApplyOutcomeTimeout = TimeSpan.FromSeconds(1);
private readonly Dictionary<string, ChildEntry> _children = new(StringComparer.Ordinal);
/// <summary>Per-driver <see cref="DependencyConsumerMuxAdapter"/> children — one for each spawned driver
@@ -3286,7 +3307,22 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
// #1107: a re-send of a deployment this node already ANSWERED means the ack was lost — re-deliver it. Applying
// again would re-apply a degraded revision (#601) and could ack a different outcome than the first time.
if (msg.IsResend && _recentAcks.TryGetValue(msg.DeploymentId, out var answered))
//
// #1111: EXCEPT a Failed ack. A failed apply left this node on its last-good configuration, so retrying is safe —
// and the fetch failure and the lost ack typically share one cause (a central blip), so replaying Failed would
// seal the deployment Failed for a node that could now succeed. Retried once per re-send (never concurrently:
// a copy arriving while the retry runs is dropped by Applying), and only while that deployment is still this
// node's latest answer with no other apply's ack held — never after a newer deployment, which a retry would
// roll back. Applied / Applied-degraded keep the replay (#601: no repeated re-apply of a degraded revision).
if (msg.IsResend && _recentAcks.TryGetValue(msg.DeploymentId, out var failed)
&& failed.Outcome == ApplyAckOutcome.Failed
&& _lastAnsweredDeploymentId == msg.DeploymentId
&& _pendingAcks.Count == 0)
{
_log.Info("DriverHost {Node}: re-send of {Id}, whose apply FAILED here ({Reason}) — retrying the apply (the node is still on its last-good configuration)",
_localNode, msg.DeploymentId, failed.FailureReason);
}
else if (msg.IsResend && _recentAcks.TryGetValue(msg.DeploymentId, out var answered))
{
_log.Info("DriverHost {Node}: re-send of {Id}, which this node already acked ({Outcome}{Degraded}) — re-sending that ack instead of re-applying",
_localNode, msg.DeploymentId, answered.Outcome, answered.Degraded ? ", degraded" : "");
@@ -3313,6 +3349,13 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
"DriverHost {Node}: dispatch {Id} matches current rev {Rev}, but its address-space apply was degraded or is unconfirmed — re-applying rather than acking clean",
_localNode, msg.DeploymentId, msg.RevisionHash);
// #1111: a re-send names how much of central's deadline is left; bound this apply's address-space wait so its
// ack still lands in time. Measured from receipt, so the artifact read and reconcile count against it too.
_applyOutcomeReleaseBy = msg.DeadlineRemaining is { } remaining
? (msg.CorrelationId,
Environment.TickCount64 + (long)(remaining - DeployTimings.ApplyOutcomeSafetyMargin).TotalMilliseconds)
: null;
if (_fetchAndCacheMode)
{
BeginFetchAndCacheApply(msg.DeploymentId, msg.RevisionHash, msg.CorrelationId);
@@ -3580,7 +3623,7 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
private sealed record PendingAck(DeploymentId DeploymentId, RevisionHash Revision, CorrelationId Correlation);
/// <summary>Self-timer: the address-space outcome for this correlation did not arrive in time.</summary>
private sealed record ApplyOutcomeTimedOut(CorrelationId Correlation);
private sealed record ApplyOutcomeTimedOut(CorrelationId Correlation, TimeSpan After);
private static string ApplyOutcomeTimerKey(CorrelationId correlation) => $"apply-outcome-{correlation}";
@@ -3605,7 +3648,32 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
"DriverHost {Node}: a second apply reused correlation {Correlation} while deployment {Old}'s ack was still waiting for its address-space outcome — that ack is superseded",
_localNode, correlation, superseded.DeploymentId);
_pendingAcks[correlation] = new PendingAck(deploymentId, revision, correlation);
Timers.StartSingleTimer(ApplyOutcomeTimerKey(correlation), new ApplyOutcomeTimedOut(correlation), _applyOutcomeTimeout);
var wait = ApplyOutcomeWaitFor(correlation);
Timers.StartSingleTimer(ApplyOutcomeTimerKey(correlation), new ApplyOutcomeTimedOut(correlation, wait), wait);
}
/// <summary>
/// #1111: how long the held ack of <paramref name="correlation"/> waits for its address-space outcome — the
/// configured <see cref="_applyOutcomeTimeout"/>, shortened (never below
/// <see cref="MinBoundedApplyOutcomeTimeout"/>) when the apply was started by a re-send whose remaining
/// deadline would otherwise run out first. Consumes the bound.
/// </summary>
private TimeSpan ApplyOutcomeWaitFor(CorrelationId correlation)
{
var wait = _applyOutcomeTimeout;
if (_applyOutcomeReleaseBy is { } bound && bound.Correlation == correlation)
{
var left = TimeSpan.FromMilliseconds(bound.ReleaseByTick - Environment.TickCount64);
if (left < MinBoundedApplyOutcomeTimeout) left = MinBoundedApplyOutcomeTimeout;
if (left < wait)
{
_log.Info("DriverHost {Node}: apply {Correlation} came from a late re-send — waiting at most {Wait:0.#}s (not {Full:0}s) for its address-space outcome so the ack lands inside central's deadline",
_localNode, correlation, left.TotalSeconds, _applyOutcomeTimeout.TotalSeconds);
wait = left;
}
}
_applyOutcomeReleaseBy = null;
return wait;
}
/// <summary>Forgets a held ack (its apply failed after all, and acks Failed instead).</summary>
@@ -3646,7 +3714,7 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
if (!_pendingAcks.Remove(msg.Correlation, out var pending)) return;
ReleasePendingAck(pending, degraded: true,
$"{OutcomeNotReportedReasonPrefix} ({_applyOutcomeTimeout.TotalSeconds:0}s) — no sink failure was observed; the apply may still be running (slow) or its outcome was lost");
$"{OutcomeNotReportedReasonPrefix} ({msg.After.TotalSeconds:0}s) — no sink failure was observed; the apply may still be running (slow) or its outcome was lost");
}
private void ReleasePendingAck(PendingAck pending, bool degraded, string? reason)
@@ -5622,6 +5690,7 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
_recentAcks.Remove(_recentAckOrder.Dequeue());
}
_recentAcks[ack.DeploymentId] = ack;
_lastAnsweredDeploymentId = ack.DeploymentId;
}
private void DeliverAck(ApplyAck ack)