fix(opcua): #1041 a device confirmation arriving after a newer write's revert lands instead of being dropped

#979 follow-up 1: write A then B, B refused first (node reverts to the pre-A value P), the
device confirms A afterwards. The revert closed the overlap window and A's success was dropped
as an outcome from a closed window, so the node showed P while the device held A until the
next driver publication. EquipmentVariableState.CloseWindowAfterRevert now keeps the window's
still-pending older attempts (bounded like the window, carried across later reverts above the
confirmed floor); a late success of one lands its tuple (LateConfirm) when nothing touched the
node since the revert, or becomes the confirmed tuple of a window opened since. A driver
publication or a newer owner's success discards them.

#979 follow-up 2 (dependents keep last value during operator Restart / config respawn): not a
defect - the stopped child's PostStop comms-loss fan (03/S15) reaches the dependency mux and
hands dependents BadNoCommunication until the new driver object publishes. Pinned by two new
DriverHostActorSourceRemovedTests (identical-value recovery); mutation-checked: removing the
PostStop ConnectivityChanged fails both.
This commit is contained in:
Joseph Doherty
2026-12-03 15:10:17 -05:00
parent cc7155e5e9
commit 186b5d696d
5 changed files with 207 additions and 1 deletions
+7
View File
@@ -156,6 +156,13 @@ either completion order) leave the node on its pre-A value and status, never on
audit event's `OldValue` reports that confirmed value. Each NodeId — the raw node and every UNS mirror —
keeps its own window; a write through one never touches the other, and both receive the next fan-out
publish.
A confirmation that arrives AFTER a newer write's refusal already reverted the node is not dropped (#1041).
The window's older attempts still pending at the revert stay eligible: if the device then confirms one, it
holds that value, so the node shows it (Good, the attempt's timestamp) when nothing has touched the node
since the revert; if a newer write owns the node by then, the confirmation becomes that window's confirmed
tuple, so a refusal of the newer write reverts to it. A driver publication, or the success of a newer
write, discards them — the node then holds something newer than any of them.
`WriteTune` and `WriteConfigure` are not separate tag-classification gates on this Value-write path.
## Remote write outcomes
@@ -29,6 +29,14 @@ internal sealed class EquipmentVariableState(NodeState? parent, object ownerLock
private NodeTuple? _confirmed;
private long _confirmedToken;
// Gitea #1041 (#979 follow-up): attempts still pending when their window closed by a REVERT. A refused newer
// attempt reverts the node to the confirmed tuple, but an older attempt the device has not answered yet may still
// succeed — and then the device holds ITS value. Kept here (bounded like the window) so that late confirmation can
// land: shown on the node when nothing newer touched it since the revert, or advancing the confirmed tuple of a
// window opened since. A driver publication or the owner's success clears them (the node then holds a newer truth).
private readonly SortedDictionary<long, NodeTuple> _revertedAttempts = new();
private long _revertedRevision = -1;
internal readonly record struct WriteStamp(EquipmentVariableState Owner, long Token);
/// <summary>One (value, status, source timestamp) tuple of the node.</summary>
@@ -43,6 +51,10 @@ internal sealed class EquipmentVariableState(NodeState? parent, object ownerLock
Revert,
/// <summary>A failure superseded by a newer attempt or a driver publication.</summary>
Superseded,
/// <summary>#1041: a success of an attempt whose window a newer attempt's refusal already reverted, with nothing
/// newer on the node since — the device holds this attempt's value: show it
/// (<see cref="ApplyLateConfirmation"/>).</summary>
LateConfirm,
}
internal WriteStamp? ActiveWriteStamp => _activeWriteToken is { } token ? new(this, token) : null;
@@ -59,6 +71,40 @@ internal sealed class EquipmentVariableState(NodeState? parent, object ownerLock
_windowAttempts.Clear();
_confirmed = null;
_confirmedToken = 0;
_revertedAttempts.Clear();
}
/// <summary>
/// #1041: closes the window after the owning attempt <paramref name="failedToken"/> was refused and the node reverted
/// (caller holds <c>ownerLock</c> and writes the confirmed tuple to the node next). Every OLDER attempt of the window
/// that the device has not answered yet — and that is newer than what the window already confirmed — stays eligible
/// for a late confirmation (see <see cref="ResolveWriteOutcome"/>), together with such attempts left over from earlier
/// reverts.
/// </summary>
internal void CloseWindowAfterRevert(long failedToken)
{
var floor = _confirmedToken;
var survivors = _windowAttempts.Where(kv => kv.Key < failedToken && kv.Key > floor)
.Concat(_revertedAttempts.Where(kv => kv.Key > floor)).ToArray();
InvalidateWriteOwnership();
foreach (var (token, tuple) in survivors) _revertedAttempts[token] = tuple;
while (_revertedAttempts.Count > MaxWindowAttempts) _revertedAttempts.Remove(_revertedAttempts.Keys.First());
_revertedRevision = _mutationRevision;
}
/// <summary>#1041: lands a <see cref="WriteOutcomeAction.LateConfirm"/> tuple on the node (caller holds
/// <c>ownerLock</c> and notifies subscribers). A still-pending NEWER reverted attempt can follow it the same way.</summary>
internal void ApplyLateConfirmation(NodeTuple confirmed)
{
_mutationRevision++;
SetTuple(confirmed.Value, confirmed.Status, confirmed.Timestamp);
_revertedRevision = _mutationRevision;
}
private void DropRevertedThrough(long token)
{
while (_revertedAttempts.Count > 0 && _revertedAttempts.Keys.First() <= token)
_revertedAttempts.Remove(_revertedAttempts.Keys.First());
}
internal void PublishValue(Variant value, StatusCode status, DateTimeUtc timestamp)
@@ -88,14 +134,37 @@ internal sealed class EquipmentVariableState(NodeState? parent, object ownerLock
_windowAttempts.Clear();
_confirmed = null;
_confirmedToken = 0;
// Every reverted attempt is older than the owner the device just confirmed.
_revertedAttempts.Clear();
}
else if (inWindow && stamp.Token > _confirmedToken)
{
_confirmed = attempted;
_confirmedToken = stamp.Token;
}
else if (_revertedAttempts.Remove(stamp.Token, out var late))
{
// #1041: the device confirmed an attempt after a newer one's refusal reverted the node. Anything older
// still pending can no longer be the device's last accepted write.
DropRevertedThrough(stamp.Token);
if (_committedWriteToken is not null)
{
// A newer attempt owns the node: this is the device's state underneath it, so a refusal of that
// attempt must land here rather than on the pre-revert tuple.
if (stamp.Token > _confirmedToken)
{
_confirmed = late;
_confirmedToken = stamp.Token;
}
return WriteOutcomeAction.None;
}
if (_mutationRevision != _revertedRevision) return WriteOutcomeAction.None;
confirmed = late;
return WriteOutcomeAction.LateConfirm;
}
return WriteOutcomeAction.None;
}
_revertedAttempts.Remove(stamp.Token);
if (!owner || _confirmed is not { } settled) return WriteOutcomeAction.Superseded;
confirmed = settled;
return WriteOutcomeAction.Revert;
@@ -4072,6 +4072,16 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
_logger.LogDebug("OtOpcUaNodeManager: device confirmed write for {NodeId}", nodeId);
return;
}
if (action == EquipmentVariableState.WriteOutcomeAction.LateConfirm && variable is EquipmentVariableState late)
{
// Gitea #1041: a newer attempt's refusal reverted the node before the device confirmed this older
// one, and nothing has touched the node since — the device holds this value, so show it now instead
// of leaving the reverted tuple until the next driver publication.
late.ApplyLateConfirmation(confirmed);
variable.ClearChangeMasks(SystemContext, includeChildren: false);
_logger.LogDebug("OtOpcUaNodeManager: device confirmed write for {NodeId} after a newer write's revert; landed it", nodeId);
return;
}
if (action == EquipmentVariableState.WriteOutcomeAction.Superseded)
{
_logger.LogDebug("OtOpcUaNodeManager: ignored superseded write outcome for {NodeId}", nodeId);
@@ -4095,7 +4105,12 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
variable.ClearChangeMasks(SystemContext, includeChildren: false); // notify — the Bad blip
var prior = restoreValue ?? SdkValueBoundary.FromClr(priorValue, variable.DataType == DataTypeIds.Byte && variable.ValueRank == ValueRanks.OneDimension);
if (variable is EquipmentVariableState restored) restored.InvalidateWriteOwnership();
if (variable is EquipmentVariableState restored)
{
// #1041: a stamped revert keeps the window's still-pending older attempts eligible for a late landing.
if (writeStamp is { } revertedStamp) restored.CloseWindowAfterRevert(revertedStamp.Token);
else restored.InvalidateWriteOwnership();
}
variable.Value = prior;
variable.StatusCode = priorStatus;
variable.Timestamp = restoreTimestamp ?? now;
@@ -373,6 +373,73 @@ public sealed class Sdk2EquipmentVariableTests : IAsyncLifetime
node.StatusCode.ShouldBe(StatusCodes.Good);
}
/// <summary>
/// Gitea #1041 (#979 follow-up): B (newer) is refused FIRST — the node reverts to the pre-A value P — and the
/// device confirms A only afterwards. The device now holds A, so the node must show A (Good), not stay on P until
/// the next driver publication. Before the fix the revert closed the overlap window and A's confirmation was
/// dropped as an outcome "from a closed window".
/// </summary>
[Theory]
[InlineData(AddressSpaceRealm.Raw)]
[InlineData(AddressSpaceRealm.Uns)]
public async Task A_device_confirmation_arriving_after_the_revert_lands_the_confirmed_value(AddressSpaceRealm realm)
{
var node = Node("Int32", realm: realm);
var pStamp = new DateTime(2026, 12, 1, 8, 0, 0, DateTimeKind.Utc);
_manager.WriteValue("v", 7, OpcUaStatus.Good, pStamp, realm);
var pending = PendingOutcomes();
Write(node, 41).ShouldBe(ServiceResult.Good); // A
Write(node, 42).ShouldBe(ServiceResult.Good); // B
pending[1].SetResult(new NodeWriteOutcome(false, "B refused"));
await WaitUntilAsync(() => Equals(SdkValueBoundary.ToClr(node.Value), 7));
SdkValueBoundary.ToClr(node.Value).ShouldBe(7);
pending[0].SetResult(new NodeWriteOutcome(true, null)); // A confirmed late
await WaitUntilAsync(() => Equals(SdkValueBoundary.ToClr(node.Value), 41));
SdkValueBoundary.ToClr(node.Value).ShouldBe(41, "the device confirmed A after B's refusal: it holds A");
node.StatusCode.ShouldBe(StatusCodes.Good);
node.Timestamp.ToDateTime().ShouldBeGreaterThan(pStamp);
// A driver publication still wins afterwards (the late landing leaves no ownership behind).
_manager.WriteValue("v", 8, OpcUaStatus.Good, pStamp.AddMinutes(5), realm);
SdkValueBoundary.ToClr(node.Value).ShouldBe(8);
}
/// <summary>#1041 guards: a late confirmation never overwrites anything NEWER than the revert — a driver publication
/// that landed after it, or a newer write that now owns the node (whose later refusal then reverts to A, the value the
/// device confirmed).</summary>
[Theory]
[InlineData("publication")]
[InlineData("newer-write")]
public async Task A_late_confirmation_never_overwrites_a_newer_tuple(string change)
{
var node = Node("Int32");
_manager.WriteValue("v", 7, OpcUaStatus.Good, DateTime.UtcNow, AddressSpaceRealm.Raw);
var pending = PendingOutcomes();
Write(node, 41).ShouldBe(ServiceResult.Good); // A
Write(node, 42).ShouldBe(ServiceResult.Good); // B
pending[1].SetResult(new NodeWriteOutcome(false, "B refused"));
await WaitUntilAsync(() => Equals(SdkValueBoundary.ToClr(node.Value), 7));
if (change == "publication") _manager.WriteValue("v", 9, OpcUaStatus.Good, DateTime.UtcNow, AddressSpaceRealm.Raw);
else Write(node, 43).ShouldBe(ServiceResult.Good); // C owns the node
var expected = change == "publication" ? 9 : 43;
pending[0].SetResult(new NodeWriteOutcome(true, null)); // A confirmed late
await WaitUntilAsync(() => _outcomeLogger.Confirmed >= 1);
_outcomeLogger.Confirmed.ShouldBe(1, "positive control: A's confirmation was processed");
SdkValueBoundary.ToClr(node.Value).ShouldBe(expected);
if (change == "newer-write")
{
pending[2].SetResult(new NodeWriteOutcome(false, "C refused"));
await WaitUntilAsync(() => Equals(SdkValueBoundary.ToClr(node.Value), 41));
SdkValueBoundary.ToClr(node.Value).ShouldBe(41, "C reverts to A — the last value the device confirmed");
}
}
/// <summary>U-4 dual NodeId: the raw node and its UNS mirror both hold the fanned value P. Interleaved writes
/// through BOTH NodeIds (A raw, B UNS, C UNS, D raw) are all refused in a mixed order; each NodeId reverts to the
/// fanned P with P's status/timestamp, and the next fan-out publish lands on both (ownership released).</summary>
@@ -259,6 +259,54 @@ public sealed class DriverHostActorSourceRemovedTests : RuntimeActorTestBase
Replayed()[Path1].Value.ShouldBe(44.0);
}
/// <summary>
/// Gitea #1041 (#979 follow-up): while an operator Restart rebuilds the driver object, a dependent still naming
/// its refs must not keep computing from the stopped object's last Good. It is told a non-Good status for the
/// restarted driver's ref (never for the untouched driver's), and the new object's first value — the
/// IDENTICAL value, so a (value, status) dedup cannot swallow the recovery — reaches it Good again.
/// </summary>
[Fact]
public void An_operator_restart_tells_dependents_the_ref_is_not_Good_until_the_new_driver_publishes()
{
ArrangeTwoDriversWithRetainedValues();
_host.Tell(new RestartDriver("c1", "DI-1", "tester", Guid.NewGuid()));
var gap = _holder.FishForMessage<VirtualTagActor.DependencyValueBatch>(
b => b.Items.Any(i => i.TagId == Path1 && !OpcUaStatus.IsGood(i.StatusCode)), PresenceBudget,
cancellationToken: TestContext.Current.CancellationToken);
gap.Items.ShouldNotContain(i => i.TagId == Path2, "DI-2 was not restarted");
AwaitAssert(() => _factory.Created.Count.ShouldBe(3), PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
AwaitSubscribed("DI-1", Path1);
Driver("DI-1").FireDataChange(Path1, 11.0);
_holder.FishForMessage<VirtualTagActor.DependencyValueBatch>(
b => b.Items.Any(i => i.TagId == Path1 && Equals(i.Value, 11.0) && OpcUaStatus.IsGood(i.StatusCode)), PresenceBudget,
cancellationToken: TestContext.Current.CancellationToken);
}
/// <summary>Gitea #1041: the config-change respawn (stop + spawn) leg of the same rule.</summary>
[Fact]
public void A_config_change_respawn_tells_dependents_the_ref_is_not_Good_until_the_new_driver_publishes()
{
ArrangeTwoDriversWithRetainedValues();
var revB = V3ArtifactSeeder.SeedV3Deployment(_db, RevB,
[.. BothDrivers, ("DI-1", "Modbus", "dev1", "temp", "Double", false)], NoRefs, enabled: true);
V3ArtifactSeeder.Dispatch(_host, _coordinator, revB, RevB);
var gap = _holder.FishForMessage<VirtualTagActor.DependencyValueBatch>(
b => b.Items.Any(i => i.TagId == Path1 && !OpcUaStatus.IsGood(i.StatusCode)), PresenceBudget,
cancellationToken: TestContext.Current.CancellationToken);
gap.Items.ShouldNotContain(i => i.TagId == Path2, "DI-2 was not respawned");
AwaitAssert(() => _factory.Created.Count.ShouldBe(3), PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
var respawned = Driver("DI-1");
AwaitAssert(() => (respawned.LastSubscribedRefs ?? []).ShouldContain("Plant/Modbus/dev1/temp"), PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
respawned.FireDataChange(Path1, 11.0);
_holder.FishForMessage<VirtualTagActor.DependencyValueBatch>(
b => b.Items.Any(i => i.TagId == Path1 && Equals(i.Value, 11.0) && OpcUaStatus.IsGood(i.StatusCode)), PresenceBudget,
cancellationToken: TestContext.Current.CancellationToken);
}
[Fact]
public void A_supervision_restart_does_not_evict_the_drivers_retained_value()
{