Merge #979: refused write reverts to last confirmed value (raw+UNS); dependents of a removed input go BadWaitingForInitialData

This commit is contained in:
Joseph Doherty
2026-12-03 10:30:00 -05:00
12 changed files with 577 additions and 17 deletions
@@ -18,19 +18,110 @@ internal sealed class EquipmentVariableState(NodeState? parent, object ownerLock
private long? _activeWriteToken;
private long? _committedWriteToken;
// Gitea #979 (review 2026-12-02 U-4): the last CONFIRMED tuple a refused write reverts to. It is snapshotted
// when the first optimistic commit of an overlap window lands on a node no attempt owns (so it is the driver's
// last publication, or a tuple an earlier window already settled), and advanced while the window is open by any
// older attempt the device confirms. `_windowAttempts` holds the optimistic tuple of every attempt committed in
// the open window; it is cleared whenever the window closes (a driver mutation, a revert, or the owner's success),
// so a late outcome from a closed window can never move the confirmed tuple.
private const int MaxWindowAttempts = 256;
private readonly SortedDictionary<long, NodeTuple> _windowAttempts = new();
private NodeTuple? _confirmed;
private long _confirmedToken;
internal readonly record struct WriteStamp(EquipmentVariableState Owner, long Token);
/// <summary>One (value, status, source timestamp) tuple of the node.</summary>
internal readonly record struct NodeTuple(Variant Value, StatusCode Status, DateTimeUtc Timestamp);
/// <summary>What a write outcome does to the node (decided under <c>ownerLock</c>).</summary>
internal enum WriteOutcomeAction
{
/// <summary>Nothing visible: a success, or a failure of an attempt that no longer owns the node.</summary>
None,
/// <summary>A failure of the attempt that still owns the node: revert to the confirmed tuple.</summary>
Revert,
/// <summary>A failure superseded by a newer attempt or a driver publication.</summary>
Superseded,
}
internal WriteStamp? ActiveWriteStamp => _activeWriteToken is { } token ? new(this, token) : null;
internal bool OwnsWrite(WriteStamp stamp) => ReferenceEquals(this, stamp.Owner) && _committedWriteToken == stamp.Token;
/// <summary>The tuple a refused or ambiguous write of the current overlap window reverts to; null when no
/// attempt owns the node. Caller holds <c>ownerLock</c>.</summary>
internal NodeTuple? ConfirmedTuple => _committedWriteToken is null ? null : _confirmed;
internal void InvalidateWriteOwnership()
{
_mutationRevision++;
_committedWriteToken = null;
_windowAttempts.Clear();
_confirmed = null;
_confirmedToken = 0;
}
internal void PublishValue(Variant value, StatusCode status, DateTimeUtc timestamp)
{
InvalidateWriteOwnership();
SetTuple(value, status, timestamp);
}
/// <summary>
/// Resolves a device-write outcome for <paramref name="stamp"/> (caller holds <c>ownerLock</c>). A failure of
/// the owning attempt returns <see cref="WriteOutcomeAction.Revert"/> with the last confirmed tuple — never the
/// value a still-pending older attempt optimistically applied (U-4). A success of the owner closes the window
/// (the node now shows a confirmed value); a success of an older attempt while a newer one still owns the node
/// advances the confirmed tuple, so a later refusal of the newer attempt lands on it.
/// </summary>
internal WriteOutcomeAction ResolveWriteOutcome(WriteStamp stamp, bool success, out NodeTuple confirmed)
{
confirmed = default;
if (!ReferenceEquals(this, stamp.Owner)) return success ? WriteOutcomeAction.None : WriteOutcomeAction.Superseded;
var owner = _committedWriteToken == stamp.Token;
var inWindow = _windowAttempts.Remove(stamp.Token, out var attempted);
if (success)
{
if (owner)
{
_committedWriteToken = null;
_windowAttempts.Clear();
_confirmed = null;
_confirmedToken = 0;
}
else if (inWindow && stamp.Token > _confirmedToken)
{
_confirmed = attempted;
_confirmedToken = stamp.Token;
}
return WriteOutcomeAction.None;
}
if (!owner || _confirmed is not { } settled) return WriteOutcomeAction.Superseded;
confirmed = settled;
return WriteOutcomeAction.Revert;
}
private void CommitOptimistic(long token, Variant value, StatusCode status, DateTimeUtc timestamp)
{
// Opening a window: the node's current tuple is what nothing in flight has touched — the confirmed state.
if (_committedWriteToken is null)
{
_windowAttempts.Clear();
_confirmed = new NodeTuple(Value, StatusCode, Timestamp);
_confirmedToken = 0;
}
_mutationRevision++;
SetTuple(value, status, timestamp);
_committedWriteToken = token;
// Bound the window against outcomes that never arrive; the evicted (oldest) attempt can then no longer
// advance the confirmed tuple, which only makes a later revert more conservative.
if (_windowAttempts.Count >= MaxWindowAttempts) _windowAttempts.Remove(_windowAttempts.Keys.First());
_windowAttempts[token] = new NodeTuple(value, status, timestamp);
}
private void SetTuple(Variant value, StatusCode status, DateTimeUtc timestamp)
{
// Value's first-touch setter can reset status. Commit in this order, under the shared lock.
Value = value;
StatusCode = status;
Timestamp = timestamp;
@@ -73,9 +164,7 @@ internal sealed class EquipmentVariableState(NodeState? parent, object ownerLock
// A reentrant driver update is newer than this attempt. Do not overwrite its tuple.
if (_mutationRevision != mutationBefore) return result;
// Value's first-touch setter can reset status. Commit in this order, under the shared lock.
PublishValue(value, statusCode, sourceTimestamp == DateTimeUtc.MinValue ? DateTimeUtc.Now : sourceTimestamp);
_committedWriteToken = token;
CommitOptimistic(token, value, statusCode, sourceTimestamp == DateTimeUtc.MinValue ? DateTimeUtc.Now : sourceTimestamp);
return result;
}
}
@@ -3611,15 +3611,24 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
optimisticValue, priorValue, priorStatus, null, realm, stamp, priorSourceTimestamp);
return;
}
if (outcome?.State == DataWriteState.DriverConfirmedSuccess) return;
if (outcome?.State == DataWriteState.DriverConfirmedSuccess)
{
// Gitea #979: a confirmed success advances the node's confirmed tuple (or closes its overlap window).
RevertOptimisticWriteIfNeeded(nodeId, new NodeWriteOutcome(true, null),
optimisticValue, priorValue, priorStatus, null, realm, stamp, priorSourceTimestamp);
return;
}
lock (Lock)
{
if (!_variables.TryGetValue(MapKey(realm, nodeId), out var variable) ||
variable is not EquipmentVariableState equipment || !equipment.OwnsWrite(stamp)) return;
variable.Value = SdkValueBoundary.FromClr(priorValue,
// Gitea #979 (U-4): an overlapping attempt's captured prior is the previous attempt's unconfirmed value.
var confirmed = equipment.ConfirmedTuple;
variable.Value = confirmed?.Value ?? SdkValueBoundary.FromClr(priorValue,
variable.DataType == DataTypeIds.Byte && variable.ValueRank == ValueRanks.OneDimension);
variable.StatusCode = StatusCodes.UncertainLastUsableValue;
variable.Timestamp = priorSourceTimestamp;
if (confirmed is { } c) variable.Timestamp = c.Timestamp;
else variable.Timestamp = priorSourceTimestamp;
variable.ClearChangeMasks(SystemContext, includeChildren: false);
}
}, CancellationToken.None, TaskContinuationOptions.RunContinuationsAsynchronously, TaskScheduler.Default);
@@ -3966,7 +3975,8 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
/// <summary>
/// Off-Lock continuation body for the write-outcome self-correction: re-takes <c>Lock</c> and, when
/// <see cref="ShouldRevert"/> says so, surfaces the device-write rejection to subscribed clients in three
/// ways, then leaves the node holding its captured pre-write value/status (same node-update shape as
/// ways, then leaves the node holding its last CONFIRMED value/status (#979 — tracked per overlap window by
/// <see cref="EquipmentVariableState"/>; the captured prior only for legacy stamp-less calls) (same node-update shape as
/// <see cref="WriteValue"/>). A no-op when the node was rebuilt/removed in the interim, when the outcome
/// succeeded, or when a fresh poll already moved the node off the optimistic value.
/// <list type="number">
@@ -4020,16 +4030,33 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
lock (Lock)
{
if (!_variables.TryGetValue(key, out var variable)) return; // rebuilt/removed ⇒ no-op
if (outcome.Success) return;
Variant? restoreValue = null;
DateTime? restoreTimestamp = priorSourceTimestamp;
if (writeStamp is { } stamp)
{
if (variable is not EquipmentVariableState equipment || !equipment.OwnsWrite(stamp))
// Gitea #979 (U-4): the revert target is the node's last CONFIRMED tuple, tracked per overlap window
// by the node itself — never the value captured at handler entry, which for an overlapping write is
// the still-unconfirmed optimistic value of the attempt before it.
EquipmentVariableState.NodeTuple confirmed = default;
var action = variable is EquipmentVariableState equipment
? equipment.ResolveWriteOutcome(stamp, outcome.Success, out confirmed)
: outcome.Success ? EquipmentVariableState.WriteOutcomeAction.None : EquipmentVariableState.WriteOutcomeAction.Superseded;
if (action == EquipmentVariableState.WriteOutcomeAction.None)
{
_logger.LogDebug("OtOpcUaNodeManager: device confirmed write for {NodeId}", nodeId);
return;
}
if (action == EquipmentVariableState.WriteOutcomeAction.Superseded)
{
_logger.LogDebug("OtOpcUaNodeManager: ignored superseded write outcome for {NodeId}", nodeId);
return;
}
restoreValue = confirmed.Value;
priorValue = SdkValueBoundary.ToClr(confirmed.Value);
priorStatus = confirmed.Status;
restoreTimestamp = confirmed.Timestamp.ToDateTime();
}
else if (!ShouldRevert(outcome, SdkValueBoundary.ToClr(variable.Value), optimisticValue)) return;
else if (outcome.Success || !ShouldRevert(outcome, SdkValueBoundary.ToClr(variable.Value), optimisticValue)) return;
// The value guard above is retained only for legacy direct unit calls. Production writes
// carry exact node-instance/token ownership, so copied arrays and equal newer values are safe.
@@ -4041,11 +4068,11 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
variable.Timestamp = now;
variable.ClearChangeMasks(SystemContext, includeChildren: false); // notify — the Bad blip
var prior = SdkValueBoundary.FromClr(priorValue, variable.DataType == DataTypeIds.Byte && variable.ValueRank == ValueRanks.OneDimension);
var prior = restoreValue ?? SdkValueBoundary.FromClr(priorValue, variable.DataType == DataTypeIds.Byte && variable.ValueRank == ValueRanks.OneDimension);
if (variable is EquipmentVariableState restored) restored.InvalidateWriteOwnership();
variable.Value = prior;
variable.StatusCode = priorStatus;
variable.Timestamp = priorSourceTimestamp ?? now;
variable.Timestamp = restoreTimestamp ?? now;
variable.ClearChangeMasks(SystemContext, includeChildren: false); // notify — restore prior
// Item C: build the audit event-state while we hold the node reference + Lock, but DON'T report yet.
@@ -428,6 +428,11 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
private readonly Dictionary<string, List<(string RawPath, HashSet<NodeRealmRef> Nodes)>> _valueRefsByDriver =
new(StringComparer.Ordinal);
/// <summary>Gitea #979 (R-6): the value refs the LAST apply removed from <see cref="_valueRefsByDriver"/>. Their
/// dependents were handed <see cref="DependencyMuxActor.RemovedInputStatus"/>; a late burst for one is not forwarded
/// to the mux. Replaced on every apply (a re-added ref leaves it).</summary>
private readonly HashSet<string> _retiredValueRefs = new(StringComparer.Ordinal);
/// <summary>The alarm-side twin of <see cref="_valueRefsByDriver"/>: a secondary index over
/// <see cref="_alarmNodeIdByDriverRef"/> grouping its entries by <c>DriverInstanceId</c>, so the
/// connectivity handler annotates one driver's conditions without scanning every condition on the node.
@@ -1916,8 +1921,16 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
return;
}
// One envelope per burst; the mux filters per item (it registered a batch receive).
_dependencyMux?.Tell(msg);
// One envelope per burst; the mux filters per item (it registered a batch receive). Gitea #979: refs the last
// apply removed are withheld, so a late burst cannot undo the removed-input status their dependents were given.
// One Count check in the steady state.
if (_retiredValueRefs.Count == 0) _dependencyMux?.Tell(msg);
else if (_dependencyMux is not null)
{
var kept = msg.Items.Where(i => !_retiredValueRefs.Contains(i.FullReference)).ToArray();
if (kept.Length == msg.Items.Count) _dependencyMux.Tell(msg);
else if (kept.Length > 0) _dependencyMux.Tell(msg with { Items = kept });
}
// 03/S15 recovery audit: clear whatever this burst re-published from the driver's Bad latch. Guarded
// by ONE dictionary probe per burst — with no outage outstanding (the steady state) this is a single
@@ -4097,6 +4110,9 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
// maps are rebuilt below, so a redeploy that keeps an alarm keeps its projected prior state.
// The per-driver secondary indexes are rebuilt WHOLE alongside their primaries below — same pass,
// same clear — so no incremental maintenance exists to get out of step with them.
// Gitea #979 (R-6): the value refs before this reindex, so the ones that leave can be reported to dependents.
var previousValueRefs = _dependencyMux is null ? null
: _valueRefsByDriver.Values.SelectMany(b => b).Select(e => e.RawPath).ToHashSet(StringComparer.Ordinal);
_valueRefsByDriver.Clear();
// A1 review (re-arm F5): each driver's alarm refs before this reindex, so a deploy's added refs can be found.
var previousAlarmRefs = _alarmRefsByDriver.ToDictionary(
@@ -4166,6 +4182,23 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
_dataWriteRuntime.Routes.ReplaceRoutes(mapped);
}
// Gitea #979 (review 2026-12-02 R-6): a value ref that left the composition (raw tag deleted or renamed, or its
// driver removed) used to be only forgotten — a surviving VirtualTag / Calculation tag / scripted alarm that
// still reads it kept computing Good from its last value. Tell the mux, which hands every dependent naming it
// RemovedInputStatus; and stop forwarding late bursts for it (a kept driver can still publish the ref until the
// bulk push below re-subscribes it), which would otherwise restore the stale Good.
_retiredValueRefs.Clear();
if (previousValueRefs is not null)
{
foreach (var bucket in _valueRefsByDriver.Values)
foreach (var e in bucket) previousValueRefs.Remove(e.RawPath);
if (previousValueRefs.Count > 0)
{
_retiredValueRefs.UnionWith(previousValueRefs);
_dependencyMux!.Tell(new DependencyMuxActor.ValueRefsRemoved(previousValueRefs.ToArray()));
}
}
if (previousSourceRefs is not null)
foreach (var previous in previousSourceRefs)
if (!_nodeIdByDriverRef.ContainsKey(previous))
@@ -53,7 +53,8 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.VirtualTags;
/// Good is never replayed as current. A comms-loss fan (a Bad batch) already overwrites the retained
/// value with Bad. <c>DriverHostActor</c> sends <see cref="SourceRemoved"/> wherever a driver object
/// ends (a deploy removal, the stop half of a config-change respawn, an operator Restart), and never
/// on a supervision restart, which re-uses the same driver.
/// on a supervision restart, which re-uses the same driver. Eviction alone tells current subscribers nothing;
/// a ref that leaves the composition is reported to its dependents by <see cref="ValueRefsRemoved"/> (#979).
/// </para>
/// <para>
/// <b>VirtualTag outputs (lmxopcua#791).</b> A VirtualTag's own result is a second ingress:
@@ -116,10 +117,23 @@ public sealed class DependencyMuxActor : ReceiveActor, IWithTimers
public sealed record VirtualTagOutput(string TagRef, object? Value, DateTime TimestampUtc, uint StatusCode);
/// <summary>These VirtualTag keys are no longer deployed (removed, or renamed away): unpin and drop their
/// retained output so it is never replayed. Subscriptions are untouched.</summary>
/// retained output so it is never replayed, and tell every dependent that still names one that the input is gone
/// (<see cref="RemovedInputStatus"/>, Gitea #979 / R-6). Subscriptions are untouched.</summary>
/// <param name="TagRefs">The keys to release.</param>
public sealed record VirtualTagOutputsRemoved(IReadOnlyCollection<string> TagRefs);
/// <summary>Gitea #979 (review 2026-12-02 R-6): these driver value refs (RawPaths) left the deployed composition —
/// the raw tag was deleted or renamed, or its driver was removed. Drop any retained value and tell every dependent
/// that still names one that the input is gone (<see cref="RemovedInputStatus"/>), so it stops computing from the
/// input's last Good. Subscriptions are untouched. Sent by <c>DriverHostActor</c> on apply.</summary>
/// <param name="TagRefs">The refs that left.</param>
public sealed record ValueRefsRemoved(IReadOnlyCollection<string> TagRefs);
/// <summary>The status a dependent is handed for an input that is no longer deployed: the same status the input
/// reads after a process restart with the same configuration (it never arrives), so a dependent behaves the same
/// whether the input was removed under it or was never there.</summary>
public const uint RemovedInputStatus = ZB.MOM.WW.OtOpcUa.Commons.OpcUa.OpcUaStatus.BadWaitingForInitialData;
/// <summary>The <c>LastSource</c> recorded for a VirtualTag output. Not a legal driver instance id (it starts
/// with a NUL), so <see cref="SourceRemoved"/> can never evict a VirtualTag's value.</summary>
internal const string VirtualTagSource = "\0virtual-tag";
@@ -210,6 +224,7 @@ public sealed class DependencyMuxActor : ReceiveActor, IWithTimers
Receive<ProjectedReferenceRetired>(OnProjectedReferenceRetired);
Receive<VirtualTagOutput>(OnVirtualTagOutput);
Receive<VirtualTagOutputsRemoved>(OnVirtualTagOutputsRemoved);
Receive<ValueRefsRemoved>(OnValueRefsRemoved);
Receive<Terminated>(msg => { RemoveSubscriber(msg.ActorRef); if (_projectedSubscribers.Remove(msg.ActorRef, out var mailbox)) mailbox.Dispose(); });
}
@@ -368,13 +383,60 @@ public sealed class DependencyMuxActor : ReceiveActor, IWithTimers
private void OnVirtualTagOutputsRemoved(VirtualTagOutputsRemoved msg)
{
Dictionary<IActorRef, List<VirtualTagActor.DependencyValueChanged>>? removed = null;
var now = DateTime.UtcNow;
foreach (var r in msg.TagRefs)
{
if (!_byRef.TryGetValue(r, out var entry) || !entry.Pinned) continue;
entry.Pinned = false;
Forget(entry);
CollectRemovedInput(r, entry, now, ref removed);
if (entry.IsDead) _byRef.Remove(r);
}
SendRemovedInputs(removed);
}
private void OnValueRefsRemoved(ValueRefsRemoved msg)
{
Dictionary<IActorRef, List<VirtualTagActor.DependencyValueChanged>>? removed = null;
var now = DateTime.UtcNow;
foreach (var r in msg.TagRefs)
{
// A VirtualTag key (pinned) has its own release; a projected (gRPC data) ref is retired through
// ProjectedReferenceRetired with its publication proof.
if (!_byRef.TryGetValue(r, out var entry) || entry.Pinned || entry.Last?.PublicationProof is not null) continue;
Forget(entry);
CollectRemovedInput(r, entry, now, ref removed);
if (entry.IsDead) _byRef.Remove(r);
}
SendRemovedInputs(removed);
if (removed is not null)
_log.Debug("DependencyMux: {Count} removed value ref(s) reported to {Subs} dependent(s)", msg.TagRefs.Count, removed.Count);
}
/// <summary>Gitea #979 (R-6): queue a <see cref="RemovedInputStatus"/> item for <paramref name="tagRef"/> to every
/// DEPENDENT that still names it — the replay-opting subscribers (VirtualTags, the Calculation adapter, the
/// scripted-alarm host). A non-replay subscriber (the continuous-historization recorder) is deliberately not told:
/// it unregisters the ref on the same deploy, and a synthetic Bad there would be recorded as a sample.</summary>
private void CollectRemovedInput(string tagRef, RefEntry entry, DateTime now,
ref Dictionary<IActorRef, List<VirtualTagActor.DependencyValueChanged>>? perSubscriber)
{
if (entry.Subscribers.Count == 0) return;
VirtualTagActor.DependencyValueChanged? gone = null;
foreach (var sub in entry.Subscribers)
{
if (!_bySubscriber.TryGetValue(sub, out var registration) || !registration.Replay) continue;
gone ??= new VirtualTagActor.DependencyValueChanged(tagRef, null, now, RemovedInputStatus);
perSubscriber ??= new Dictionary<IActorRef, List<VirtualTagActor.DependencyValueChanged>>();
if (!perSubscriber.TryGetValue(sub, out var list)) perSubscriber[sub] = list = [];
list.Add(gone);
}
}
private static void SendRemovedInputs(Dictionary<IActorRef, List<VirtualTagActor.DependencyValueChanged>>? perSubscriber)
{
if (perSubscriber is null) return;
foreach (var (sub, list) in perSubscriber) sub.Tell(new VirtualTagActor.DependencyValueBatch(list));
}
private void ReleaseProjected(RefEntry entry)