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
+6 -1
View File
@@ -151,7 +151,12 @@ Things that carried over unchanged from the `ClusterClient` era, because they we
within half the deadline) to the expected nodes whose ack has not arrived, via `DispatchDeployment.TargetNodes` 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 — 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 same-revision dispatch re-applies a degraded revision); the node treats a re-send idempotently per
`DeploymentId` (re-acks if answered, ignores while applying / while its ack is held). The apply deadline and `DeploymentId` (re-acks if answered, ignores while applying / while its ack is held) — except a remembered
**Failed** ack, which it retries (#1111; only while that deployment is its latest answer and no other ack is held).
Central never lets a late `Failed` overwrite that node's arrived `Applied` for the same deployment (a stale
duplicate); a late `Failed` that closes the deployment first is a documented residual. Re-sends carry
`DeadlineRemaining` (proto field 5, additive) so a late-reached node bounds its address-space wait to fit.
Remembered acks are in-memory only (a restarted node treats a re-send as fresh). The apply deadline and
boot-time replay remain the backstops. `docs/Redundancy.md` §"Dispatch re-send". 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 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. set it; the gRPC transport has nothing to buffer in the first place — a dial either lands or doesn't.
+48 -4
View File
@@ -837,16 +837,60 @@ dial was dropped — either way the deployment sat until the 120 s deadline and
16 deployments) instead of applying again — so a lost ack is recovered and a duplicate ack is harmless 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: (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. re-dispatching a degraded revision still re-applies.
- **…except a lost `Failed` ack, which is RETRIED (#1111).** A failed apply leaves the node on its last-good
configuration, and the failure and the lost ack usually share a cause (a central blip during the fetch), so on a
re-send of a deployment whose remembered ack is `Failed` the node re-attempts the apply instead of replaying
`Failed`. Once per re-send, never concurrently (a copy arriving mid-retry is dropped as in-flight), and only while
that deployment is still the node's **latest** answer with no other apply's ack held — a stale re-send of an older
failed deployment after a newer one was applied replays `Failed` rather than rolling the node back. `Applied` and
`Applied`+degraded acks keep the replay, so #601's "no repeated re-apply of a degraded revision on re-sends" holds.
- **Central: Applied wins over a late Failed (#1111 review).** Because the node re-applies only after its own `Failed`,
two acks from one node for one deployment can now differ — and the ORIGINAL `Failed` can still arrive after the
retry's `Applied` (`GrpcApplyAckSender` walks the central endpoints, and a call that timed out may still have
landed). Within one deployment `ConfigPublishCoordinator` therefore never lets a `Failed` overwrite that node's
`Applied` (clean or degraded) once the Applied has **arrived** — counted, being persisted, parked behind a write, or
held for a persist retry. The late `Failed` is discarded before its row write (logged at Info), so neither the count
nor the node's `NodeDeploymentState` row flips back. The reverse is unchanged: an `Applied` arriving after a counted
`Failed` still replaces it, as long as the deployment is open.
- **Residual: a late `Failed` that CLOSES the deployment first.** If the stale `Failed` reaches central before the
retry's `Applied` and it completes the expected set (a one-node cluster, or the peer already acked), the deployment is
marked `PartiallyFailed` at once and the retry's `Applied` is then discarded as a stale ack ("Discarding stale ApplyAck").
The node runs the new revision, but central's `Deployment` row reads `PartiallyFailed` and that node's
`NodeDeploymentState` row reads `Failed` (on a fused `Direct` node the node's own row write races central's, so it may
read either). Deliberately NOT corrected after the fact: re-opening a terminal deployment would break
"a terminal outcome is written once" (review L8), sealing it late would give an older deployment a newer
`SealedAtUtc` than one dispatched since — and "latest sealed" drives drift detection and the publish fallback — and
the coordinator keeps no per-deployment state past closure to judge it with. It needs a re-send to reach the node
after its `Failed` was delivered-but-unacknowledged, so it is narrow; it heals on the next deploy (a dispatch of the
same revision short-circuits to `Applied` on a node whose address space is confirmed, and re-applies otherwise).
- **A re-send carries what is left of the deadline (#1111).** `DispatchDeployment.DeadlineRemaining` (proto
`optional int64 deadline_remaining_ms = 5`, additive) is set on every re-send — a RELATIVE duration, so central's
and the node's clocks need not agree — and left unset on the original. A node whose apply was started by such a
re-send bounds its held Applied ack's address-space wait to `DeadlineRemaining − 15 s` measured from **receipt**
(so the artifact read and reconcile count against it; floor 1 s), instead of the full 105 s. A node first reached
by the +35 s re-send (~85 s left) therefore releases an "outcome not reported in time" ack at ~70 s and the
deployment seals "Applied (degraded)" rather than `TimedOut`. Wire compatibility: an old central never sets the
field (absent ⇒ the node's full default wait, today's behaviour); an old node ignores it (gRPC unknown field / DPS
JSON extra member) and keeps its 105 s wait — the pre-#1111 limit below applies to it. Residual: a re-send for a
*different* deployment that arrives while the node is still applying another is stashed, and its wait is measured
from when it is unstashed, not received — that only happens when the node is applying a deployment central has
already superseded.
- **Residuals.** A pre-#1107 node ignores `TargetNodes` and has none of the node-side idempotence, so during a - **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 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 **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 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 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 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 **upgrade the driver nodes before central** to avoid it.
is process-local: a node that restarted after acking treats a re-send as a first dispatch (short-circuit, - **Remembered acks are in memory only — deliberately not persisted (#1111).** The last 16 acks live in the
or a re-apply if its revision is unconfirmed). A node that first receives the dispatch at +35 s still has `DriverHostActor` instance. A node that restarted (process restart, or a supervision restart of the actor) after
~85 s to ack; only a rebuild slower than that, which already acks degraded at 105 s, can miss the deadline. acking has forgotten them and treats a re-send as a first dispatch: it short-circuits `Applied` if it is already
on that revision with a confirmed address space, and otherwise applies it (a re-apply if its revision is
unconfirmed/degraded — the one case a restart can turn a degraded replay into a re-apply). The boot-time replay
of an orphan `Applying` row is unaffected.
- **Pre-#1111 node: late-re-send deadline limit.** A node that does not read `DeadlineRemaining` and first receives
the dispatch at +35 s has ~85 s to ack but waits up to 105 s for its address-space outcome, so a rebuild slower
than ~85 s seals `TimedOut` at central instead of "Applied (degraded)". Upgraded nodes bound the wait (above).
### What an `Applied` ack means: the degraded-apply amendment (Gitea #601) ### What an `Applied` ack means: the degraded-apply amendment (Gitea #601)
@@ -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 /// #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 /// 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 /// 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"). /// a pre-#1107 node ignores the member (see <c>docs/Redundancy.md</c> §"Dispatch re-send").
/// </param> /// </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( public sealed record DispatchDeployment(
DeploymentId DeploymentId, DeploymentId DeploymentId,
RevisionHash RevisionHash, RevisionHash RevisionHash,
CorrelationId CorrelationId, 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> /// <summary>Whether this is a coordinator re-send (#1107) rather than the original dispatch.</summary>
public bool IsResend => TargetNodes is { Count: > 0 }; 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. // #1107: only a re-send names targets; the original dispatch leaves the repeated field empty.
if (message.TargetNodes is { Count: > 0 } targets) if (message.TargetNodes is { Count: > 0 } targets)
proto.TargetNodes.AddRange(targets.Where(t => !string.IsNullOrWhiteSpace(t))); 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; return proto;
} }
@@ -76,9 +79,18 @@ public static class MeshTransportDtoMapper
RevisionHash.Parse(proto.RevisionHash), 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". // #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 // ---------------------------------------------------------------- RestartDriver
/// <summary>Projects <paramref name="message"/> onto its wire form.</summary> /// <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 // 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. // this transport, so this is belt-and-braces for the node; a pre-#1107 node ignores the field.
repeated string target_nodes = 4; 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. // 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> /// <summary>#1107: no re-send is scheduled to fire after this instant (a fraction of the apply deadline).</summary>
private DateTime _redispatchWindowEndsUtc; 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 _applyDeadline;
private readonly TimeSpan _loadRetryMin; private readonly TimeSpan _loadRetryMin;
private readonly TimeSpan _loadRetryMax; private readonly TimeSpan _loadRetryMax;
@@ -823,7 +830,9 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU
_expectedAcks = outcome.Expected!; _expectedAcks = outcome.Expected!;
// The ORIGINAL dispatch addresses every node, whatever a (recovered/queued) message carried. // 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); PublishDispatch(original);
Timers.StartSingleTimer(DeadlineTimerKey, new DeadlineElapsed(msg.DeploymentId), _applyDeadline); Timers.StartSingleTimer(DeadlineTimerKey, new DeadlineElapsed(msg.DeploymentId), _applyDeadline);
ArmRedispatch(original, _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; if (_expectedAcks.Count == 0 || _redispatchSchedule.Count == 0 || deadlineLeft <= TimeSpan.Zero) return;
_resendable = dispatch; _resendable = dispatch;
_redispatchDeadlineUtc = DateTime.UtcNow + deadlineLeft;
_redispatchWindowEndsUtc = DateTime.UtcNow + TimeSpan.FromTicks((long)(deadlineLeft.Ticks * RedispatchWindowFraction)); _redispatchWindowEndsUtc = DateTime.UtcNow + TimeSpan.FromTicks((long)(deadlineLeft.Ticks * RedispatchWindowFraction));
ScheduleNextRedispatch(); 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", "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); dispatch.DeploymentId, string.Join(", ", outstanding), _redispatchAttempts, _redispatchSchedule.Count);
ZB.MOM.WW.OtOpcUa.Commons.Observability.OtOpcUaTelemetry.DeploymentRedispatched.Add(outstanding.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(); ScheduleNextRedispatch();
} }
@@ -977,11 +994,41 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU
return; 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 // 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. // resend). A throw here used to restart the actor and drop the ack; it is re-queued instead.
StartAckPersist(msg); 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> /// <summary>
/// lmxopcua#996 (review H-6): the ack write runs OFF the actor thread and its outcome comes back as /// 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 /// <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 /// #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 /// 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 /// 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. /// after a restart the node has nothing to remember and the boot replay owns the deployment.
/// </summary> /// </summary>
private readonly Dictionary<DeploymentId, ApplyAck> _recentAcks = new(); 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> /// <summary>Insertion order of <see cref="_recentAcks"/>, for eviction.</summary>
private readonly Queue<DeploymentId> _recentAckOrder = new(); 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); private readonly Dictionary<string, ChildEntry> _children = new(StringComparer.Ordinal);
/// <summary>Per-driver <see cref="DependencyConsumerMuxAdapter"/> children — one for each spawned driver /// <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 // #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. // 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", _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" : ""); _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", "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); _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) if (_fetchAndCacheMode)
{ {
BeginFetchAndCacheApply(msg.DeploymentId, msg.RevisionHash, msg.CorrelationId); 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); 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> /// <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}"; 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", "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); _localNode, correlation, superseded.DeploymentId);
_pendingAcks[correlation] = new PendingAck(deploymentId, revision, correlation); _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> /// <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; if (!_pendingAcks.Remove(msg.Correlation, out var pending)) return;
ReleasePendingAck(pending, degraded: true, 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) 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.Remove(_recentAckOrder.Dequeue());
} }
_recentAcks[ack.DeploymentId] = ack; _recentAcks[ack.DeploymentId] = ack;
_lastAnsweredDeploymentId = ack.DeploymentId;
} }
private void DeliverAck(ApplyAck ack) private void DeliverAck(ApplyAck ack)
@@ -72,6 +72,38 @@ public class MeshTransportDtoMapperTests
original.IsAddressedTo("site-b-1:4053").ShouldBeTrue(); original.IsAddressedTo("site-b-1:4053").ShouldBeTrue();
} }
[Fact]
public void DispatchDeployment_Resend_RoundTrips_ItsRemainingDeadline_AndAnOriginalCarriesNone()
{
// #1111: presence of deadline_remaining_ms is what distinguishes "central said N ms are left" from an original
// dispatch / a pre-#1111 central (absent => null => the node's full default wait).
var resend = new DispatchDeployment(
new DeploymentId(DeploymentGuid), new RevisionHash(Sha256Hex), new CorrelationId(CorrelationGuid),
["site-a-1:4053"], TimeSpan.FromMilliseconds(84_500));
var proto = MeshTransportDtoMapper.ToProto(resend);
proto.HasDeadlineRemainingMs.ShouldBeTrue();
proto.DeadlineRemainingMs.ShouldBe(84_500L);
MeshTransportDtoMapper.FromProto(Wire(proto)).DeadlineRemaining.ShouldBe(TimeSpan.FromMilliseconds(84_500));
// Zero is a real value (deadline already spent), not "absent".
var spent = Wire(MeshTransportDtoMapper.ToProto(resend with { DeadlineRemaining = TimeSpan.Zero }));
spent.HasDeadlineRemainingMs.ShouldBeTrue();
MeshTransportDtoMapper.FromProto(spent).DeadlineRemaining.ShouldBe(TimeSpan.Zero);
// Out-of-range wire values (only a buggy or hostile sender) are clamped, never thrown on.
var negative = Wire(MeshTransportDtoMapper.ToProto(resend));
negative.DeadlineRemainingMs = long.MinValue;
MeshTransportDtoMapper.FromProto(negative).DeadlineRemaining.ShouldBe(TimeSpan.Zero);
var huge = Wire(MeshTransportDtoMapper.ToProto(resend));
huge.DeadlineRemainingMs = long.MaxValue;
MeshTransportDtoMapper.FromProto(huge).DeadlineRemaining.ShouldBe(TimeSpan.FromDays(1));
var original = Wire(MeshTransportDtoMapper.ToProto(resend with { TargetNodes = null, DeadlineRemaining = null }));
original.HasDeadlineRemainingMs.ShouldBeFalse();
MeshTransportDtoMapper.FromProto(original).DeadlineRemaining.ShouldBeNull();
}
[Fact] [Fact]
public void DispatchDeployment_EncodesIdsInTheirHexNForm() public void DispatchDeployment_EncodesIdsInTheirHexNForm()
{ {
@@ -108,6 +108,87 @@ public sealed class ConfigPublishCoordinatorDegradedAckTests : ControlPlaneActor
db.NodeDeploymentStates.Single(s => s.NodeId == NodeA).Status.ShouldBe(NodeDeploymentStatus.Failed); db.NodeDeploymentStates.Single(s => s.NodeId == NodeA).Status.ShouldBe(NodeDeploymentStatus.Failed);
} }
[Theory]
[InlineData(false)]
[InlineData(true)]
public void A_late_Failed_after_a_nodes_Applied_ack_does_not_overwrite_it(bool degraded)
{
// #1111 review: the node retried after its first (Failed) ack was not seen, and acked Applied; the ORIGINAL
// Failed then arrives late (a timed-out gRPC call that still landed). The node re-applies only after its own
// Failed, so a Failed after Applied is stale: it must neither flip the row nor fail the deployment.
var dbFactory = NewInMemoryDbFactory();
var deploymentId = SeedDispatchingDeployment(dbFactory);
SeedNodes(dbFactory, NodeA, NodeB);
var actor = Sys.ActorOf(ConfigPublishCoordinator.Props(dbFactory, NoTimeout));
actor.Tell(new DispatchDeployment(deploymentId, TestRevision, CorrelationId.NewId()));
AwaitStatus(dbFactory, DeploymentStatus.AwaitingApplyAcks);
actor.Tell(new ApplyAck(deploymentId, NodeId.Parse(NodeA), ApplyAckOutcome.Applied, null,
CorrelationId.NewId(), Degraded: degraded, DegradedReason: degraded ? "x" : null));
AwaitAssert(() =>
{
using var db = dbFactory.CreateDbContext();
db.NodeDeploymentStates.Single(s => s.NodeId == NodeA).Status.ShouldBe(NodeDeploymentStatus.Applied);
}, duration: PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
actor.Tell(new ApplyAck(deploymentId, NodeId.Parse(NodeA), ApplyAckOutcome.Failed, "fetch failed", CorrelationId.NewId()));
actor.Tell(new ApplyAck(deploymentId, NodeId.Parse(NodeB), ApplyAckOutcome.Applied, null, CorrelationId.NewId()));
AwaitStatus(dbFactory, DeploymentStatus.Sealed);
using var verify = dbFactory.CreateDbContext();
var rowA = verify.NodeDeploymentStates.Single(s => s.NodeId == NodeA);
rowA.Status.ShouldBe(NodeDeploymentStatus.Applied);
ConfigPublishCoordinator.IsDegraded(rowA.Status, rowA.FailureReason).ShouldBe(degraded);
}
[Fact]
public void A_late_Failed_racing_an_in_flight_Applied_write_does_not_overwrite_it()
{
// Same policy, both acks back-to-back: the Failed lands while the Applied's write is still in flight.
var dbFactory = NewInMemoryDbFactory();
var deploymentId = SeedDispatchingDeployment(dbFactory);
SeedNodes(dbFactory, NodeA, NodeB);
var actor = Sys.ActorOf(ConfigPublishCoordinator.Props(dbFactory, NoTimeout));
actor.Tell(new DispatchDeployment(deploymentId, TestRevision, CorrelationId.NewId()));
AwaitStatus(dbFactory, DeploymentStatus.AwaitingApplyAcks);
actor.Tell(new ApplyAck(deploymentId, NodeId.Parse(NodeA), ApplyAckOutcome.Applied, null, CorrelationId.NewId()));
actor.Tell(new ApplyAck(deploymentId, NodeId.Parse(NodeA), ApplyAckOutcome.Failed, "fetch failed", CorrelationId.NewId()));
actor.Tell(new ApplyAck(deploymentId, NodeId.Parse(NodeB), ApplyAckOutcome.Applied, null, CorrelationId.NewId()));
AwaitStatus(dbFactory, DeploymentStatus.Sealed);
using var verify = dbFactory.CreateDbContext();
verify.NodeDeploymentStates.Single(s => s.NodeId == NodeA).Status.ShouldBe(NodeDeploymentStatus.Applied);
}
[Fact]
public void An_Applied_after_a_nodes_Failed_ack_still_replaces_it()
{
// Positive control for the guard above: the retry's Applied arriving AFTER the Failed was counted wins, so the
// guard is one-directional (Applied is never overwritten by Failed; Failed is still overwritten by Applied).
var dbFactory = NewInMemoryDbFactory();
var deploymentId = SeedDispatchingDeployment(dbFactory);
SeedNodes(dbFactory, NodeA, NodeB);
var actor = Sys.ActorOf(ConfigPublishCoordinator.Props(dbFactory, NoTimeout));
actor.Tell(new DispatchDeployment(deploymentId, TestRevision, CorrelationId.NewId()));
AwaitStatus(dbFactory, DeploymentStatus.AwaitingApplyAcks);
actor.Tell(new ApplyAck(deploymentId, NodeId.Parse(NodeA), ApplyAckOutcome.Failed, "fetch failed", CorrelationId.NewId()));
AwaitAssert(() =>
{
using var db = dbFactory.CreateDbContext();
db.NodeDeploymentStates.Single(s => s.NodeId == NodeA).Status.ShouldBe(NodeDeploymentStatus.Failed);
}, duration: PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
actor.Tell(new ApplyAck(deploymentId, NodeId.Parse(NodeA), ApplyAckOutcome.Applied, null, CorrelationId.NewId()));
AwaitAssert(() =>
{
using var db = dbFactory.CreateDbContext();
db.NodeDeploymentStates.Single(s => s.NodeId == NodeA).Status.ShouldBe(NodeDeploymentStatus.Applied);
}, duration: PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
actor.Tell(new ApplyAck(deploymentId, NodeId.Parse(NodeB), ApplyAckOutcome.Applied, null, CorrelationId.NewId()));
AwaitStatus(dbFactory, DeploymentStatus.Sealed);
}
[Fact] [Fact]
public void A_recovered_coordinator_remembers_a_degraded_ack_that_landed_before_failover() public void A_recovered_coordinator_remembers_a_degraded_ack_that_landed_before_failover()
{ {
@@ -127,6 +127,31 @@ public sealed class ConfigPublishCoordinatorRedispatchTests : ControlPlaneActorT
resend.IsResend.ShouldBeTrue(); resend.IsResend.ShouldBeTrue();
} }
[Fact]
public void Each_resend_carries_the_remaining_deadline_and_the_original_carries_none()
{
// #1111: a node first reached by a late re-send must bound its address-space wait to what is LEFT of central's
// deadline, so every re-send says how much that is; the original dispatch leaves it unset (full default).
var deadline = TimeSpan.FromSeconds(60);
var dbFactory = NewInMemoryDbFactory();
var deploymentId = SeedDispatchingDeployment(dbFactory);
SeedNodes(dbFactory, "site-a-1:4053");
var router = CreateTestProbe();
Sys.ActorOf(ConfigPublishCoordinator.Props(
dbFactory, deadline, router.Ref, redispatchSchedule: Every(TimeSpan.FromMilliseconds(400), 2)))
.Tell(new DispatchDeployment(deploymentId, TestRevision, CorrelationId.NewId()));
ExpectDispatch(router).DeadlineRemaining.ShouldBeNull();
var first = ExpectDispatch(router).DeadlineRemaining.ShouldNotBeNull();
var second = ExpectDispatch(router).DeadlineRemaining.ShouldNotBeNull();
first.ShouldBeLessThan(deadline);
first.ShouldBeGreaterThan(deadline - TimeSpan.FromSeconds(10));
// Counts down between re-sends (by ~one schedule step), never resets to the full deadline.
second.ShouldBeLessThan(first);
(first - second).ShouldBeGreaterThan(TimeSpan.FromMilliseconds(200));
}
[Fact] [Fact]
public void Resends_are_bounded_by_the_schedule() public void Resends_are_bounded_by_the_schedule()
{ {
@@ -144,6 +144,193 @@ public sealed class DriverHostActorRedispatchTests : RuntimeActorTestBase
} }
} }
[Fact]
public void A_resend_of_a_deployment_whose_apply_FAILED_retries_the_apply_and_a_later_resend_replays_the_success()
{
// #1111: the first fetch fails (a central blip), the second succeeds.
var db = NewInMemoryDbFactory();
var fetcher = new ScriptedFetcher(null, EmptyArtifact);
var deploymentId = DeploymentId.NewId();
var coordinator = CreateTestProbe();
var actor = Sys.ActorOf(DriverHostActor.Props(
db, TestNode, coordinator.Ref,
localRoles: new HashSet<string> { "driver" },
deploymentArtifactCache: new NullArtifactCache(),
fetchAndCacheMode: true,
artifactFetcher: fetcher));
var dispatch = new DispatchDeployment(deploymentId, RevA, CorrelationId.NewId());
actor.Tell(dispatch);
coordinator.ExpectMsg<ApplyAck>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken)
.Outcome.ShouldBe(ApplyAckOutcome.Failed);
// The coordinator never saw the Failed ack and re-sends: the node RETRIES rather than replaying Failed.
actor.Tell(dispatch with { TargetNodes = [TestNode.Value] });
coordinator.ExpectMsg<ApplyAck>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken)
.Outcome.ShouldBe(ApplyAckOutcome.Applied);
fetcher.Calls.ShouldBe(2);
// A further re-send (that Applied ack lost too) replays it — the retry did not turn re-sends into re-applies.
actor.Tell(dispatch with { TargetNodes = [TestNode.Value] });
coordinator.ExpectMsg<ApplyAck>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken)
.Outcome.ShouldBe(ApplyAckOutcome.Applied);
coordinator.ExpectNoMsg(Quiet, TestContext.Current.CancellationToken);
fetcher.Calls.ShouldBe(2);
}
[Fact]
public void A_resend_of_an_OLDER_failed_deployment_replays_Failed_rather_than_rolling_back_a_newer_apply()
{
var db = NewInMemoryDbFactory();
var fetcher = new ScriptedFetcher(null, EmptyArtifact);
var coordinator = CreateTestProbe();
var actor = Sys.ActorOf(DriverHostActor.Props(
db, TestNode, coordinator.Ref,
localRoles: new HashSet<string> { "driver" },
deploymentArtifactCache: new NullArtifactCache(),
fetchAndCacheMode: true,
artifactFetcher: fetcher));
var older = new DispatchDeployment(DeploymentId.NewId(), RevA, CorrelationId.NewId());
actor.Tell(older);
var failed = coordinator.ExpectMsg<ApplyAck>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
failed.Outcome.ShouldBe(ApplyAckOutcome.Failed);
// A newer deployment is applied after it.
actor.Tell(new DispatchDeployment(DeploymentId.NewId(), RevisionHash.Parse(new string('b', 64)), CorrelationId.NewId()));
coordinator.ExpectMsg<ApplyAck>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken)
.Outcome.ShouldBe(ApplyAckOutcome.Applied);
fetcher.Calls.ShouldBe(2);
// A stale re-send of the older, failed deployment: the remembered Failed is replayed, nothing is fetched.
actor.Tell(older with { TargetNodes = [TestNode.Value] });
coordinator.ExpectMsg<ApplyAck>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken)
.ShouldBe(failed);
coordinator.ExpectNoMsg(Quiet, TestContext.Current.CancellationToken);
fetcher.Calls.ShouldBe(2);
// Positive control: an ORIGINAL dispatch of that same deployment does fetch and apply, so the silence above is
// the stale-retry guard, not a host that has stopped fetching.
actor.Tell(older);
coordinator.ExpectMsg<ApplyAck>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken)
.Outcome.ShouldBe(ApplyAckOutcome.Applied);
fetcher.Calls.ShouldBe(3);
}
[Fact]
public void A_resend_of_a_failed_deployment_is_not_retried_while_a_NEWER_applys_ack_is_still_held()
{
// #1111 review: the newer deployment's Applied ack is held on its address-space outcome, so the failed one is
// still this node's latest ANSWER — only the held-ack guard stops the stale re-send from re-applying the older
// revision over the newer one (and the newer one's held Applied ack then going out for a rolled-back node).
var db = NewInMemoryDbFactory();
var fetcher = new ScriptedFetcher(null, EmptyArtifact);
var coordinator = CreateTestProbe();
var publish = CreateTestProbe();
var actor = Sys.ActorOf(DriverHostActor.Props(
db, TestNode, coordinator.Ref,
localRoles: new HashSet<string> { "driver" },
deploymentArtifactCache: new NullArtifactCache(),
fetchAndCacheMode: true,
artifactFetcher: fetcher,
opcUaPublishActor: publish.Ref,
applyOutcomeTimeout: TimeSpan.FromSeconds(60)));
var older = new DispatchDeployment(DeploymentId.NewId(), RevA, CorrelationId.NewId());
actor.Tell(older);
var failed = coordinator.ExpectMsg<ApplyAck>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
failed.Outcome.ShouldBe(ApplyAckOutcome.Failed);
// The newer deployment applies; its Applied ack is HELD (the address-space outcome has not landed).
var newer = new DispatchDeployment(DeploymentId.NewId(), RevisionHash.Parse(new string('b', 64)), CorrelationId.NewId());
actor.Tell(newer);
var rebuild = publish.FishForMessage<OpcUaPublishActor.RebuildAddressSpace>(_ => true, PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
rebuild.DeploymentId.ShouldBe(newer.DeploymentId);
fetcher.Calls.ShouldBe(2);
// A stale re-send of the older, failed deployment: replays Failed, fetches nothing, starts no rebuild.
actor.Tell(older with { TargetNodes = [TestNode.Value] });
coordinator.ExpectMsg<ApplyAck>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken)
.ShouldBe(failed);
coordinator.ExpectNoMsg(Quiet, TestContext.Current.CancellationToken);
fetcher.Calls.ShouldBe(2);
// The held ack is still the newer deployment's, and goes out clean when its outcome lands.
actor.Tell(new OpcUaPublishActor.RebuildCompleted(rebuild.Correlation, rebuild.DeploymentId, false, null), publish.Ref);
var ack = coordinator.ExpectMsg<ApplyAck>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
ack.DeploymentId.ShouldBe(newer.DeploymentId);
ack.Outcome.ShouldBe(ApplyAckOutcome.Applied);
ack.Degraded.ShouldBeFalse();
// Positive control: an ORIGINAL dispatch of the older deployment does fetch — the silence above was the guard.
actor.Tell(older);
publish.FishForMessage<OpcUaPublishActor.RebuildAddressSpace>(r => r.DeploymentId == older.DeploymentId, PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
fetcher.Calls.ShouldBe(3);
}
[Fact]
public void A_late_resend_bounds_the_address_space_wait_to_the_deadline_it_carries()
{
var (db, deploymentId) = SeedOneTagDeployment();
var coordinator = CreateTestProbe();
var publish = CreateTestProbe();
// A long configured wait, so a degraded ack within seconds can only be the re-send's bound.
var actor = Sys.ActorOf(DriverHostActor.Props(
db, TestNode, coordinator.Ref, localRoles: new HashSet<string> { "driver" },
opcUaPublishActor: publish.Ref, applyOutcomeTimeout: TimeSpan.FromSeconds(60)));
// First reached by a re-send with 17 s of central's deadline left => 17 - 15 = 2 s of address-space wait.
actor.Tell(new DispatchDeployment(deploymentId, RevA, CorrelationId.NewId(),
TargetNodes: [TestNode.Value], DeadlineRemaining: TimeSpan.FromSeconds(17)));
publish.FishForMessage<OpcUaPublishActor.RebuildAddressSpace>(_ => true, PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
// The outcome never arrives.
var ack = coordinator.ExpectMsg<ApplyAck>(TimeSpan.FromSeconds(10), cancellationToken: TestContext.Current.CancellationToken);
ack.Outcome.ShouldBe(ApplyAckOutcome.Applied);
ack.Degraded.ShouldBeTrue();
ack.DegradedReason.ShouldNotBeNull();
ack.DegradedReason.ShouldStartWith(DriverHostActor.OutcomeNotReportedReasonPrefix);
ack.DegradedReason.ShouldContain("(2s)");
}
[Fact]
public void An_original_dispatch_keeps_the_full_address_space_wait()
{
// Positive control for the bound above: same set-up, no DeadlineRemaining — the ack stays held past the
// re-send's 2 s, and is released (clean) only by the outcome.
var (db, deploymentId) = SeedOneTagDeployment();
var coordinator = CreateTestProbe();
var publish = CreateTestProbe();
var actor = Sys.ActorOf(DriverHostActor.Props(
db, TestNode, coordinator.Ref, localRoles: new HashSet<string> { "driver" },
opcUaPublishActor: publish.Ref, applyOutcomeTimeout: TimeSpan.FromSeconds(60)));
actor.Tell(new DispatchDeployment(deploymentId, RevA, CorrelationId.NewId()));
var rebuild = publish.FishForMessage<OpcUaPublishActor.RebuildAddressSpace>(_ => true, PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
coordinator.ExpectNoMsg(TimeSpan.FromSeconds(4), TestContext.Current.CancellationToken);
actor.Tell(new OpcUaPublishActor.RebuildCompleted(rebuild.Correlation, rebuild.DeploymentId, false, null), publish.Ref);
var ack = coordinator.ExpectMsg<ApplyAck>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
ack.Outcome.ShouldBe(ApplyAckOutcome.Applied);
ack.Degraded.ShouldBeFalse();
}
private static readonly byte[] EmptyArtifact =
JsonSerializer.SerializeToUtf8Bytes(new { DriverInstances = Array.Empty<object>() });
/// <summary>A fetcher answering each call with the next scripted result (null = "no answer"); the last repeats.</summary>
private sealed class ScriptedFetcher(params byte[]?[] results) : IDeploymentArtifactFetcher
{
private int _calls;
public int Calls => Volatile.Read(ref _calls);
public Task<byte[]?> FetchAsync(string deploymentId, string expectedRevisionHash, CancellationToken ct)
{
var n = Interlocked.Increment(ref _calls);
return Task.FromResult(results[Math.Min(n, results.Length) - 1]);
}
}
private (IDbContextFactory<OtOpcUaConfigDbContext> Db, DeploymentId Id) SeedOneTagDeployment() private (IDbContextFactory<OtOpcUaConfigDbContext> Db, DeploymentId Id) SeedOneTagDeployment()
{ {
var db = NewInMemoryDbFactory(); var db = NewInMemoryDbFactory();