fix(deploy): #1111 retry a lost Failed ack on re-send; re-sends carry the remaining deadline

1. Node (DriverHostActor): a coordinator re-send of a deployment whose remembered ack is
   Failed now RE-ATTEMPTS the apply instead of replaying Failed — a failed apply left the
   node on last-good config, and a fetch failure and a lost ack usually share a cause.
   Once per re-send (a copy mid-retry is dropped by Applying), and only while that
   deployment is still the node's latest answer with no other ack held, so a stale re-send
   of an OLDER failed deployment replays Failed rather than rolling back a newer apply.
   Applied / Applied+degraded keep the replay (#601 unchanged).

2. DispatchDeployment gains additive DeadlineRemaining (proto optional int64
   deadline_remaining_ms = 5), set by ConfigPublishCoordinator on every re-send (relative,
   no clock agreement needed), unset on the original. A node whose apply was started by a
   re-send bounds its held Applied ack's address-space wait to remaining - 15 s from
   receipt (floor 1 s), so a node first reached at +35 s acks Applied (degraded) before
   central's deadline instead of sealing TimedOut. Old central -> field absent -> full
   105 s (today); old node ignores the field (limit documented).

3. Docs: remembered acks are in memory only (restart/supervision restart forgets them);
   Redundancy.md §Dispatch re-send + cluster-topology rule updated.

Tests: Failed-ack retry + later replay, stale older-failed guard with positive control,
re-send deadline bound with original-dispatch positive control (both behaviour tests
verified to fail with the change disabled), mapper presence round-trip, coordinator
DeadlineRemaining countdown.
This commit is contained in:
Joseph Doherty
2026-12-05 00:24:49 -05:00
parent 1cd98580ca
commit f5485f57d8
10 changed files with 335 additions and 15 deletions
+4 -1
View File
@@ -151,7 +151,10 @@ 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`
— central's gRPC fan dials only those; on DPS the others ignore it. ⚠️ Never re-send to an acked node (#601: a
same-revision dispatch re-applies a degraded revision); the node treats a re-send idempotently per
`DeploymentId` (re-acks if answered, ignores while applying / while its ack is held). The apply deadline and
`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). 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".
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.
+29 -4
View File
@@ -837,16 +837,41 @@ 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
(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.
- **…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.
- **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
rolling upgrade with central upgraded first it treats every re-send that reaches it as an original dispatch. On
**DPS** that includes re-sends meant for its peer. On **either** transport it includes the common case of its
OWN re-send while its Applied ack is still held on the address-space outcome (any apply slower than 5 s): the
old node re-applies the same revision (the pre-#1107 `_pendingAcks` revision check forces it) and supersedes
the held ack. The second apply's diff is empty, so this is redundant work rather than an outage, but
**upgrade the driver nodes before central** to avoid it. The node's memory
is process-local: a node that restarted after acking treats a re-send as a first dispatch (short-circuit,
or a re-apply if its revision is unconfirmed). A node that first receives the dispatch at +35 s still has
~85 s to ack; only a rebuild slower than that, which already acks degraded at 105 s, can miss the deadline.
**upgrade the driver nodes before central** to avoid it.
- **Remembered acks are in memory only — deliberately not persisted (#1111).** The last 16 acks live in the
`DriverHostActor` instance. A node that restarted (process restart, or a supervision restart of the actor) after
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)
@@ -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,7 +79,9 @@ 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.
proto.HasDeadlineRemainingMs ? TimeSpan.FromMilliseconds(proto.DeadlineRemainingMs) : null);
}
// ---------------------------------------------------------------- RestartDriver
@@ -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();
}
@@ -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 sent its most recent ack for (any outcome, including a re-delivery's
/// re-ack of the same deployment). 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
@@ -3281,7 +3302,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" : "");
@@ -3308,6 +3344,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);
@@ -3575,7 +3618,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}";
@@ -3600,7 +3643,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>
@@ -3641,7 +3709,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)
@@ -5549,6 +5617,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)
@@ -72,6 +72,30 @@ public class MeshTransportDtoMapperTests
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);
var original = Wire(MeshTransportDtoMapper.ToProto(resend with { TargetNodes = null, DeadlineRemaining = null }));
original.HasDeadlineRemainingMs.ShouldBeFalse();
MeshTransportDtoMapper.FromProto(original).DeadlineRemaining.ShouldBeNull();
}
[Fact]
public void DispatchDeployment_EncodesIdsInTheirHexNForm()
{
@@ -127,6 +127,31 @@ public sealed class ConfigPublishCoordinatorRedispatchTests : ControlPlaneActorT
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]
public void Resends_are_bounded_by_the_schedule()
{
@@ -144,6 +144,142 @@ 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_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()
{
var db = NewInMemoryDbFactory();