Merge review fixes: superseded deployment's ack write no longer drops successor's ack (#996); degraded-apply repair re-pushes drivers (#995)

This commit is contained in:
Joseph Doherty
2026-12-03 12:01:14 -05:00
8 changed files with 576 additions and 23 deletions
@@ -109,10 +109,18 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU
private readonly Dictionary<NodeId, PendingPersist> _unpersisted = new(NodeIdComparer);
private string? _lastPersistError;
/// <summary>Acks whose ConfigDb write is in flight on a pool thread (#996 / H-6), one per node.</summary>
/// <summary>
/// Acks of the CURRENT deployment whose ConfigDb write is in flight on a pool thread (#996 / H-6), one per node.
/// Cleared by <see cref="ResetForNext"/>: a write still running for a closed or superseded deployment updates that
/// deployment's own row, so it must neither hold back the next deployment's ack for the same node nor count towards
/// its deadline (#996 x #977 review). Its late <see cref="AckPersisted"/> matches no entry and is discarded.
/// </summary>
private readonly Dictionary<NodeId, ApplyAck> _persisting = new(NodeIdComparer);
/// <summary>A newer ack for a node that already has a write in flight; started when that write returns (newest wins).</summary>
/// <summary>
/// A newer ack for a node that already has a write in flight FOR THE SAME DEPLOYMENT; started when that write
/// returns (newest wins).
/// </summary>
private readonly Dictionary<NodeId, ApplyAck> _pendingBehind = new(NodeIdComparer);
/// <summary>
@@ -687,12 +695,14 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU
/// ConfigDb unreachable (no retry strategy ⇒ a full connect timeout per call) N acks, N retry ticks and the
/// deadline's backlog re-try serialised N × timeout on the one coordinator thread, delaying every other message
/// (a new dispatch, the deadline decision) by minutes. Now the timeouts overlap and the mailbox stays live.
/// One write per node at a time; a newer ack for a node with a write in flight is held in
/// <see cref="_pendingBehind"/> and started when that write returns.
/// One write per node per deployment at a time; a newer ack for a node with a write of the same deployment in
/// flight is held in <see cref="_pendingBehind"/> and started when that write returns. A write still in flight
/// for ANOTHER deployment (one that closed or was superseded while it ran) never holds an ack back: it updates a
/// different row, and parking behind it let its stale outcome discard the successor's ack (#996 x #977 review).
/// </summary>
private void StartAckPersist(ApplyAck msg)
{
if (_persisting.ContainsKey(msg.NodeId))
if (_persisting.TryGetValue(msg.NodeId, out var inflight) && inflight.DeploymentId == msg.DeploymentId)
{
_pendingBehind[msg.NodeId] = msg;
return;
@@ -710,12 +720,26 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU
private void HandleAckPersisted(AckPersisted result)
{
var node = result.Ack.NodeId;
_persisting.Remove(node);
// Only THIS write's entry: a reset, or a newer deployment's ack, may have replaced it while it ran (#996 x #977).
if (_persisting.TryGetValue(node, out var tracked) && ReferenceEquals(tracked, result.Ack)) _persisting.Remove(node);
if (_current is null || result.Ack.DeploymentId != _current.Value)
{
// The deployment closed (or was superseded) while the write ran: nothing to count or retry.
_pendingBehind.Remove(node);
// The deployment closed (or was superseded) while the write ran: nothing to count or retry. A parked ack is
// dropped only if it is stale too; one of the CURRENT deployment is started (unless its node is already
// writing for it), never discarded on an older deployment's outcome.
if (_pendingBehind.TryGetValue(node, out var parked))
{
if (!IsForCurrent(parked))
{
_pendingBehind.Remove(node);
}
else if (!_persisting.ContainsKey(node))
{
_pendingBehind.Remove(node);
StartAckPersist(parked);
}
}
return;
}
@@ -733,7 +757,7 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU
// A deadline that was deferred on unpersisted acks decides as soon as the last write lands, rather than
// waiting out its re-armed delay.
if (_deadlineDeferredSinceUtc is not null && _unpersisted.Count == 0 && _persisting.Count == 0)
if (_deadlineDeferredSinceUtc is not null && _unpersisted.Count == 0 && InFlightForCurrent() == 0)
{
Timers.Cancel(DeadlineTimerKey);
Self.Tell(new DeadlineElapsed(_current.Value));
@@ -838,8 +862,9 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU
private void HandleRetryAckPersist(RetryAckPersist msg)
{
if (!_unpersisted.TryGetValue(msg.Ack.NodeId, out var pending) || !ReferenceEquals(pending.Ack, msg.Ack)) return;
// A write for this node is already in flight (e.g. kicked by the deadline): its outcome re-arms the retry itself.
if (_persisting.ContainsKey(msg.Ack.NodeId)) return;
// A write for this node and deployment is already in flight (e.g. kicked by the deadline): its outcome re-arms
// the retry itself.
if (_persisting.TryGetValue(msg.Ack.NodeId, out var inflight) && inflight.DeploymentId == msg.Ack.DeploymentId) return;
HandleAck(msg.Ack);
}
@@ -943,7 +968,7 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU
}
// Review M2: an ack that ARRIVED but is not yet persisted must never be timed out as "no ack from" its node.
// Persist the backlog now; if the DB still refuses, defer the decision (the terminal write needs it too).
if (_unpersisted.Count > 0 || _persisting.Count > 0)
if (_unpersisted.Count > 0 || InFlightForCurrent() > 0)
{
// #996 / H-6: kick the whole backlog off-thread at once (the connect timeouts overlap, they no longer
// serialise on this thread); the deadline is re-armed below and also fires early once the last write lands.
@@ -964,15 +989,18 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU
_memoryOnlyAcks[pending.Ack.NodeId] = pending.Ack;
CountAck(pending.Ack);
}
// A write still in flight at the cap is decided from memory too (its late outcome is discarded).
foreach (var inflight in _persisting.Values) CountAck(inflight);
// A write still in flight at the cap is decided from memory too (its late outcome is discarded) - only
// the CURRENT deployment's: an older deployment's ack must never count here. A newer ack parked behind
// that write is the node's latest word, so it is counted after it (newest wins).
foreach (var inflight in _persisting.Values.Where(IsForCurrent)) CountAck(inflight);
foreach (var behind in _pendingBehind.Values.Where(IsForCurrent)) CountAck(behind);
}
else if (_unpersisted.Count > 0 || _persisting.Count > 0)
else if (_unpersisted.Count > 0 || InFlightForCurrent() > 0)
{
var delay = _unpersisted.Count > 0 ? Backoff(_unpersisted.Values.Min(p => p.Attempts)) : Backoff(1);
_log.Warning(
"Deployment {Id} reached its apply deadline with {Count} received ack(s) not yet persisted; deferring " +
"the outcome {Delay} until they are", _current.Value, _unpersisted.Count + _persisting.Count, delay);
"the outcome {Delay} until they are", _current.Value, _unpersisted.Count + InFlightForCurrent(), delay);
Timers.StartSingleTimer(DeadlineTimerKey, msg, delay);
return;
}
@@ -1055,12 +1083,21 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU
}
_memoryOnlyAcks.Clear();
_pendingBehind.Clear();
// #996 x #977 review: in-flight writes are per deployment. One still running for the deployment being closed
// writes that deployment's own row; tracking it on would park the next deployment's ack for that node behind it
// (whose stale outcome then discarded the ack) and block the next deadline's early re-fire.
_persisting.Clear();
_current = null;
_expectedAcks.Clear();
_acks.Clear();
_degraded.Clear();
}
private bool IsForCurrent(ApplyAck ack) => _current is { } current && ack.DeploymentId == current;
/// <summary>In-flight ack writes of the current deployment (the only ones a deadline may wait on or count).</summary>
private int InFlightForCurrent() => _persisting.Values.Count(IsForCurrent);
private const string DeadlineTimerKey = "apply-deadline";
private const string LoadRetryTimerKey = "recovery-load-retry";
@@ -3520,7 +3520,7 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
private void HandleRebuildCompleted(OpcUa.OpcUaPublishActor.RebuildCompleted msg)
{
SeedSkippedDrivers(msg.Correlation, reseed: msg.AddressSpaceRebuilt || msg.Degraded,
msg.Degraded ? "degraded apply" : "full rebuild");
msg.Degraded ? "degraded apply" : "full rebuild, or a repair of a previously degraded apply");
if (!_pendingAcks.Remove(msg.Correlation, out var pending))
{
_log.Debug("DriverHost {Node}: address-space outcome for {Correlation} has no held ack (already timed out or superseded); dropping",
@@ -165,8 +165,11 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
/// Gitea #995 (R-11): <see langword="false"/> only when the apply was a clean NON-rebuild — every node that
/// existed before it still exists with its value. <c>DriverHostActor</c> skips the re-subscribe of a driver
/// whose desired set and fan-out are unchanged, and re-pushes those drivers when this is <see langword="true"/>
/// (a full rebuild recreated their nodes without a value). Defaults to <see langword="true"/> — the
/// conservative answer for any producer that does not know.
/// (a full rebuild recreated their nodes without a value). Also <see langword="true"/> for a REPAIR pass (the
/// empty-plan re-apply of a degraded composition, or the #977 R-4 whole-composition re-ensure) and for any apply
/// following a degraded one: those can create nodes the degraded apply failed to place, valueless, whose drivers
/// the deploy skipped (#995 R-11 x #977 R-4 review). Defaults to <see langword="true"/> — the conservative answer
/// for any producer that does not know.
/// </param>
public sealed record RebuildCompleted(
CorrelationId Correlation, DeploymentId? DeploymentId, bool Degraded, string? DegradedReason,
@@ -331,6 +334,19 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
/// that pass is itself clean.
/// </summary>
private bool _lastAppliedDegraded;
/// <summary>
/// #995 R-11 x #977 R-4 review: the previous apply (of ANY kind, reported or not) was degraded, so nodes it failed
/// to place may be created by the next one — after the driver host's post-degraded re-push already ran against
/// the missing node. The next apply therefore reports <see cref="RebuildCompleted.AddressSpaceRebuilt"/> so the
/// drivers its deploy skipped are re-pushed; otherwise such a node stays BadWaitingForInitialData until its value
/// changes (forever for a constant). Set by <see cref="FinishRebuild"/>.
/// </summary>
private bool _previousApplyDegraded;
/// <summary>The apply in progress ran a REPAIR pass (re-ensured the whole composition after a degraded one): nodes
/// may have been created without a value. Set by <see cref="ApplyPlanCore"/>, consumed by <see cref="FinishRebuild"/>.</summary>
private bool _repairPassRan;
/// <summary>
/// Gitea #977 (R-20): this instance was created by a supervision RESTART, so <see cref="_lastApplied"/> is the
/// empty seed while the sink (the node manager, which outlives the actor) still serves the previous instance's
@@ -1534,8 +1550,11 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
}
// #995 R-11: captured before the replay scope is reset — a rebuild (or the applier-less raw-sink rebuild) recreated
// every node, so the driver host must re-seed values it skipped re-subscribing.
var rebuilt = _applier is null || _replayScope.AllVariables;
// every node, so the driver host must re-seed values it skipped re-subscribing. So may a REPAIR pass, or any apply
// after a degraded one (#995 R-11 x #977 R-4 review): either can create a node the degraded apply failed to place,
// whose driver the deploy skipped because its fingerprint did not change — the node would never get a value.
var rebuilt = _applier is null || _replayScope.AllVariables || _repairPassRan || _previousApplyDegraded;
_repairPassRan = false;
// Land what arrived while the plan was in flight on the nodes the apply just created — before the answer,
// so "applied" means the deferred first values are on the address space too (review fix C1).
@@ -1549,6 +1568,9 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
outcome = (true, "the expected local data catalog could not be activated");
}
// The FINAL outcome (completion and catalog included) decides whether the next apply must re-seed.
_previousApplyDegraded = outcome.Degraded;
if (msg.ReportOutcome)
requester.Tell(new RebuildCompleted(msg.Correlation, msg.DeploymentId, outcome.Degraded, outcome.Reason,
AddressSpaceRebuilt: rebuilt));
@@ -1638,7 +1660,9 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
{
// The composition is unchanged but the last apply of it was a degraded
// rebuild: re-ensure every node (each Ensure* no-ops on a node that stands) so the
// re-deploy actually repairs what that rebuild could not place.
// re-deploy actually repairs what that rebuild could not place. A node it now places has no value
// and its driver's re-subscribe was skipped (nothing it seeds changed): report it for a re-push.
_repairPassRan = true;
var repairFailed = _applier!.MaterialiseHierarchy(composition)
+ MaterialiseNodes(plan, composition, fullComposition: true);
if (repairFailed > 0)
@@ -1687,6 +1711,8 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
// to place is inside _lastApplied and will never appear in a diff again, so a delta-only apply of an unrelated
// change used to clear the degraded flag and report clean over a still-partial address space.
var repairingDegraded = _lastAppliedDegraded && !outcome.RebuildCalled;
// Like the empty-plan repair: what the re-ensure places is valueless, so the skipped drivers must re-push.
if (repairingDegraded) _repairPassRan = true;
failedNodes += MaterialiseNodes(plan, composition, fullComposition: outcome.RebuildCalled || repairingDegraded);
if (outcome.RebuildCalled) _baselineUnknown = outcome.RebuildFailed;