diff --git a/docs/DriverLifecycle.md b/docs/DriverLifecycle.md index 51128c219..4504e752a 100644 --- a/docs/DriverLifecycle.md +++ b/docs/DriverLifecycle.md @@ -365,6 +365,7 @@ a fifth (archreview round 3, theme "the stale-Good family"). The seams that impl | Calculation driver | holds on Bad, propagates the worst input status | [`docs/drivers/Calculation.md`](drivers/Calculation.md#input-quality) | | Virtual tags | holds on Bad, inherits the worst input status, reassert carries it | [`docs/ScriptEditor.md`](ScriptEditor.md#input-quality-what-a-script-sees-and-when-it-runs-at-all) | | Scripted alarms | worst-of-input quality annotated out of band; Bad inputs hold the condition | [`docs/ScriptedAlarms.md`](ScriptedAlarms.md) | +| Input **removed** by a deploy (#979) | a raw value ref that leaves the composition (tag deleted/renamed, driver removed) or a VirtualTag output that leaves the deployed set reaches every dependent still naming it (VirtualTags, the Calculation adapter, the scripted-alarm upstream — replay-opting mux subscribers only; the historization recorder is not told) as `BadWaitingForInitialData` — the status it reads after a restart with the same config. Late bursts for a removed ref are withheld from the mux until the next apply | `DriverHostActor.ApplyDesiredSubscriptions` → `DependencyMuxActor.ValueRefsRemoved` / `VirtualTagOutputsRemoved` | ⚠️ **Consumer-visible:** value nodes of a comms-lost driver now go **Bad**, where they used to serve their last value at Good. A consumer that treats a Bad value as "drop the tag" (ScadaBridge's data diff --git a/docs/ReadWriteOperations.md b/docs/ReadWriteOperations.md index 4bb6a53aa..13cf5aded 100644 --- a/docs/ReadWriteOperations.md +++ b/docs/ReadWriteOperations.md @@ -146,6 +146,16 @@ aliases resolve to the same device point. Primary-role admission is checked on t The SDK invokes the callback while holding the node-manager lock. Asynchronous work is dispatched without waiting under that lock. Local optimistic values are corrected through shared fan-out on a confirmed failure. A driver with fire-and-forget semantics cannot provide device confirmation. + +A refused write reverts to the node's last **confirmed** (value, status, source timestamp), not to the +value captured when its own handler ran (#979). Each node tracks an overlap window: the first optimistic +write on a node no attempt owns snapshots the node's tuple as confirmed; an older attempt the device +confirms while a newer one still owns the node advances it; a driver publication, a revert, or the +owner's own success closes the window. So two overlapping writes A then B that the device refuses (in +either completion order) leave the node on its pre-A value and status, never on A at Good, and the +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. `WriteTune` and `WriteConfigure` are not separate tag-classification gates on this Value-write path. ## Remote write outcomes diff --git a/docs/VirtualTags.md b/docs/VirtualTags.md index c914f9847..386cc7cd2 100644 --- a/docs/VirtualTags.md +++ b/docs/VirtualTags.md @@ -309,6 +309,7 @@ Virtual-tag nodes are materialised by `AddressSpaceApplier` and fed by `VirtualT - **VirtualTag → VirtualTag dependencies (lmxopcua#791).** A VirtualTag's key is its UNS NodeId identifier, `{EquipmentId}/{Name}` (VirtualTags have no FolderPath, and no raw-subtree node), and a script reads another VirtualTag with that literal: `ctx.GetTag("EQ-0123456789ab/LineRate")`. It cannot collide with a RawPath in the mux's key space: a key is two segments, a tag's RawPath at least three (Driver/Device/Tag). Until #791 this never worked — VirtualTag outputs were published to their OPC UA node only, the mux carried driver values only, so a dependent sat at `BadWaitingForInitialData` forever (proven by `VirtualTagToVirtualTagFlowTests` failing on the pre-fix code), and the AdminUI completion offered the bare leaf `Name`, which resolved to nothing. Now: - **Routing.** `VirtualTagHostActor.OnResult` publishes each result to the node exactly as before (one publish path, one NodeId — VirtualTags exist only in the UNS realm, so there is no raw NodeId to keep consistent) and *additionally* sends it to the mux as `DependencyMuxActor.VirtualTagOutput` under the same string. A disabled tag's `BadOutOfService` is routed too. A re-assert is not routed (it repeats a state the mux already holds). So `ctx.GetTag()` returns the upstream's current value, status and timestamp, and the dependent inherits a Bad upstream status like any input (02/S14). Calculation tags and scripted alarms read the mux too, so they can read a VirtualTag by its key the same way. - **Retention.** A VirtualTag output is **pinned** in the mux: retained whether or not anyone has registered for it yet (an upstream and its dependent spawn in one apply and register asynchronously, so the upstream may evaluate first), never put into the replay grace, and immune to a driver's `SourceRemoved`. A dependent that registers later — or respawns on a plan edit — is replayed the current value at once. Memory is bounded by the deployed VirtualTag count; the host sends `VirtualTagOutputsRemoved` for keys that leave the deployed set (a removed or renamed tag), which drops them. + - **Removed inputs (#979).** A dependent that survives the removal of its input — a VirtualTag key above, or a raw value ref that left the composition (tag deleted or renamed, driver removed; `DriverHostActor` sends `DependencyMuxActor.ValueRefsRemoved`) — is handed that input as `BadWaitingForInitialData` (`DependencyMuxActor.RemovedInputStatus`), so it holds and publishes that status instead of computing Good from the input's last value. That is also what it reads after a process restart with the same configuration (the input never arrives). Only replay-opting subscribers (VirtualTags, the Calculation adapter, the scripted-alarm host) are told; the historization recorder is not. Re-adding the input recovers on its first value, even an identical one (the dedup is on (value, status)). Disabling an input still routes `BadOutOfService`, as above. - **Cycles are a blocking deploy error** — `VirtualTagDependencyCycle` (`DraftValidator`): A→B→A, a self-read, longer loops, and loops through a Calculation tag (whose output reaches the mux as a driver value), with `{{equip}}/` reads resolved through the same reference map the compose seams use. Only enabled VirtualTags are graph nodes: a disabled one publishes one static `BadOutOfService` and cannot carry a loop. A cycle of Calculation tags alone stays `CalculationDependencyCycle`. **Runtime backstop:** `VirtualTagHostActor` re-detects VirtualTag-only cycles on every apply (Tarjan, `DependencyGraph`) and does not route the outputs of tags on one (logged as an error), so an artifact that bypassed the gate still cannot become a feedback storm — those tags evaluate and publish, they just do not feed the loop. (A loop through a Calculation tag is caught by the deploy gate only.) `ScriptStackGuard` (#779) is unrelated — it bounds recursion inside one evaluation. - **Trigger gate.** `VirtualTagNoEffectiveTrigger` counts literal `ctx.GetTag` reads, so a change-triggered tag whose only dependency is another VirtualTag passes — correctly, now that the upstream's output actually arrives. - **`{{equip}}/` does not resolve a VirtualTag** — that token resolves `UnsTagReference` rows only. `EquipReferenceUnresolved` now says so when the name is a VirtualTag on that equipment and names the key form to use. diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/EquipmentVariableState.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/EquipmentVariableState.cs index 7feea2b09..702bdb51a 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/EquipmentVariableState.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/EquipmentVariableState.cs @@ -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 _windowAttempts = new(); + private NodeTuple? _confirmed; + private long _confirmedToken; + internal readonly record struct WriteStamp(EquipmentVariableState Owner, long Token); + + /// One (value, status, source timestamp) tuple of the node. + internal readonly record struct NodeTuple(Variant Value, StatusCode Status, DateTimeUtc Timestamp); + + /// What a write outcome does to the node (decided under ownerLock). + internal enum WriteOutcomeAction + { + /// Nothing visible: a success, or a failure of an attempt that no longer owns the node. + None, + /// A failure of the attempt that still owns the node: revert to the confirmed tuple. + Revert, + /// A failure superseded by a newer attempt or a driver publication. + Superseded, + } + internal WriteStamp? ActiveWriteStamp => _activeWriteToken is { } token ? new(this, token) : null; internal bool OwnsWrite(WriteStamp stamp) => ReferenceEquals(this, stamp.Owner) && _committedWriteToken == stamp.Token; + /// The tuple a refused or ambiguous write of the current overlap window reverts to; null when no + /// attempt owns the node. Caller holds ownerLock. + 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); + } + + /// + /// Resolves a device-write outcome for (caller holds ownerLock). A failure of + /// the owning attempt returns 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. + /// + 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; } } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs index a5fe47ec7..a6c2eb2db 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs @@ -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 /// /// Off-Lock continuation body for the write-outcome self-correction: re-takes Lock and, when /// 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 + /// ; the captured prior only for legacy stamp-less calls) (same node-update shape as /// ). 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. /// @@ -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. diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs index 54b1f747e..43aa0623c 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs @@ -428,6 +428,11 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn private readonly Dictionary Nodes)>> _valueRefsByDriver = new(StringComparer.Ordinal); + /// Gitea #979 (R-6): the value refs the LAST apply removed from . Their + /// dependents were handed ; a late burst for one is not forwarded + /// to the mux. Replaced on every apply (a re-added ref leaves it). + private readonly HashSet _retiredValueRefs = new(StringComparer.Ordinal); + /// The alarm-side twin of : a secondary index over /// grouping its entries by DriverInstanceId, 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)) diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/VirtualTags/DependencyMuxActor.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/VirtualTags/DependencyMuxActor.cs index 28497bad1..4307fb343 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/VirtualTags/DependencyMuxActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/VirtualTags/DependencyMuxActor.cs @@ -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. DriverHostActor sends 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 (#979). /// /// /// VirtualTag outputs (lmxopcua#791). 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); /// 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. + /// retained output so it is never replayed, and tell every dependent that still names one that the input is gone + /// (, Gitea #979 / R-6). Subscriptions are untouched. /// The keys to release. public sealed record VirtualTagOutputsRemoved(IReadOnlyCollection TagRefs); + /// 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 (), so it stops computing from the + /// input's last Good. Subscriptions are untouched. Sent by DriverHostActor on apply. + /// The refs that left. + public sealed record ValueRefsRemoved(IReadOnlyCollection TagRefs); + + /// 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. + public const uint RemovedInputStatus = ZB.MOM.WW.OtOpcUa.Commons.OpcUa.OpcUaStatus.BadWaitingForInitialData; + /// The LastSource recorded for a VirtualTag output. Not a legal driver instance id (it starts /// with a NUL), so can never evict a VirtualTag's value. internal const string VirtualTagSource = "\0virtual-tag"; @@ -210,6 +224,7 @@ public sealed class DependencyMuxActor : ReceiveActor, IWithTimers Receive(OnProjectedReferenceRetired); Receive(OnVirtualTagOutput); Receive(OnVirtualTagOutputsRemoved); + Receive(OnValueRefsRemoved); Receive(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>? 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>? 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); + } + + /// Gitea #979 (R-6): queue a item for 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. + private void CollectRemovedInput(string tagRef, RefEntry entry, DateTime now, + ref Dictionary>? 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>(); + if (!perSubscriber.TryGetValue(sub, out var list)) perSubscriber[sub] = list = []; + list.Add(gone); + } + } + + private static void SendRemovedInputs(Dictionary>? perSubscriber) + { + if (perSubscriber is null) return; + foreach (var (sub, list) in perSubscriber) sub.Tell(new VirtualTagActor.DependencyValueBatch(list)); } private void ReleaseProjected(RefEntry entry) diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/Engines/VirtualTagToVirtualTagFlowTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/Engines/VirtualTagToVirtualTagFlowTests.cs index 70674ab35..d8d9da552 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/Engines/VirtualTagToVirtualTagFlowTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/Engines/VirtualTagToVirtualTagFlowTests.cs @@ -75,4 +75,38 @@ public sealed class VirtualTagToVirtualTagFlowTests : TestKit NextFor(publish, AKey, m => m.StatusCode == OpcUaStatus.BadOutOfService); NextFor(publish, BKey, m => m.StatusCode == OpcUaStatus.BadOutOfService); } + + /// Gitea #979 (review 2026-12-02 R-6): A is REMOVED (not disabled) while B, unchanged, survives. B used to + /// keep publishing Good computed from A's last value; it now publishes the removed-input status — what it would read + /// after a restart with the same configuration. Re-adding A and replaying the IDENTICAL input brings B back to the + /// identical Good value, so the (value, status) dedup swallows neither transition. + [Fact] + public void A_virtual_tag_whose_upstream_virtual_tag_is_removed_goes_bad_and_recovers_on_the_identical_value() + { + using var evaluator = new RoslynVirtualTagEvaluator( + NullLogger.Instance, new ScriptRootLogger(new LoggerConfiguration().CreateLogger())); + var publish = CreateTestProbe(); + var mux = Sys.ActorOf(DependencyMuxActor.Props()); + var host = Sys.ActorOf(VirtualTagHostActor.Props(publish.Ref, mux, evaluator)); + + host.Tell(new VirtualTagHostActor.ApplyVirtualTags(new[] { PlanA(), PlanB() })); + AwaitAssert(() => + { + mux.Tell(Driver(5)); + publish.FishForMessage( + m => m.NodeId == AKey && Equals(m.Value, 10d), TimeSpan.FromMilliseconds(500)); + }, Budget, TimeSpan.FromMilliseconds(50), TestContext.Current.CancellationToken); + NextFor(publish, BKey, m => Equals(m.Value, 11d) && m.StatusCode == OpcUaStatus.Good); + + host.Tell(new VirtualTagHostActor.ApplyVirtualTags(new[] { PlanB() })); + NextFor(publish, BKey, m => m.StatusCode == DependencyMuxActor.RemovedInputStatus); + + host.Tell(new VirtualTagHostActor.ApplyVirtualTags(new[] { PlanA(), PlanB() })); + AwaitAssert(() => + { + mux.Tell(Driver(5)); + publish.FishForMessage( + m => m.NodeId == BKey && Equals(m.Value, 11d) && m.StatusCode == OpcUaStatus.Good, TimeSpan.FromMilliseconds(500)); + }, Budget, TimeSpan.FromMilliseconds(50), TestContext.Current.CancellationToken); + } } diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/GrpcDataMappedWriteCompletionTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/GrpcDataMappedWriteCompletionTests.cs index c07e159c5..9429b2863 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/GrpcDataMappedWriteCompletionTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/GrpcDataMappedWriteCompletionTests.cs @@ -101,6 +101,25 @@ public sealed class GrpcDataMappedWriteCompletionTests : IAsyncLifetime await _completion!.WaitAsync(TimeSpan.FromSeconds(5), Ct); } + /// Gitea #979 (U-4) on the mapped path: two overlapping writes both refused, newer first — the node + /// returns to the authoritative pre-write tuple, not to the first write's unconfirmed value. + [Fact] + public async Task Overlapping_refused_writes_restore_the_authoritative_value_not_the_first_attempt() + { + var first = InstallWrite(); + Write(41).ShouldBe(ServiceResult.Good); + var firstCompletion = _completion!; + var second = InstallWrite(); + Write(42).ShouldBe(ServiceResult.Good); + second.SetResult(new(DataWriteState.DriverConfirmedFailure, StatusCodes.BadDeviceFailure.Code, "refused")); + await _completion!.WaitAsync(TimeSpan.FromSeconds(5), Ct); + first.SetResult(new(DataWriteState.DriverConfirmedFailure, StatusCodes.BadDeviceFailure.Code, "refused")); + await firstCompletion.WaitAsync(TimeSpan.FromSeconds(5), Ct); + SdkValueBoundary.ToClr(_node.Value).ShouldBe(7); + _node.StatusCode.ShouldBe(StatusCodes.Good); + _node.Timestamp.ToDateTime().ShouldBe(AuthoritativeTimestamp); + } + [Fact] public async Task Old_failure_cannot_overwrite_recreated_node_with_same_id_and_value() { diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/Sdk2EquipmentVariableTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/Sdk2EquipmentVariableTests.cs index 50c463db4..36ee62dca 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/Sdk2EquipmentVariableTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/Sdk2EquipmentVariableTests.cs @@ -317,14 +317,134 @@ public sealed class Sdk2EquipmentVariableTests : IAsyncLifetime SdkValueBoundary.ToClr(node.Value).ShouldBeOfType().ShouldBe([7, 8]); } + // ───────── #979 / review 2026-12-02 U-4: overlapping failed writes revert to the last CONFIRMED tuple ───────── + + /// U-4: write A then B (both in flight), the device refuses both, in either completion order. The node + /// must end on the pre-A value P with P's status and source timestamp — never on A (which the device never + /// accepted) carrying a Good status. Runs on both realms (the raw NodeId and the UNS mirror). + [Theory] + [InlineData(AddressSpaceRealm.Raw, true)] + [InlineData(AddressSpaceRealm.Raw, false)] + [InlineData(AddressSpaceRealm.Uns, true)] + [InlineData(AddressSpaceRealm.Uns, false)] + public async Task Two_overlapping_refused_writes_revert_to_the_last_confirmed_value(AddressSpaceRealm realm, bool newerFailsFirst) + { + var node = Node("Int32", realm: realm); + var pStamp = new DateTime(2026, 12, 1, 8, 0, 0, DateTimeKind.Utc); + _manager.WriteValue("v", 7, StatusCodes.UncertainLastUsableValue.Code, pStamp, realm); + var pending = PendingOutcomes(); + + Write(node, 41).ShouldBe(ServiceResult.Good); // A + Write(node, 42).ShouldBe(ServiceResult.Good); // B + SdkValueBoundary.ToClr(node.Value).ShouldBe(42); + + var (first, second) = newerFailsFirst ? (pending[1], pending[0]) : (pending[0], pending[1]); + first.SetResult(new NodeWriteOutcome(false, "first refusal")); + second.SetResult(new NodeWriteOutcome(false, "second refusal")); + + await WaitUntilAsync(() => Equals(SdkValueBoundary.ToClr(node.Value), 7)); + // Positive control for the absence of a late overwrite: the superseded continuation must have run. + await WaitUntilAsync(() => _outcomeLogger.Superseded >= 1); + _outcomeLogger.Superseded.ShouldBeGreaterThanOrEqualTo(1); + SdkValueBoundary.ToClr(node.Value).ShouldBe(7); + node.StatusCode.ShouldBe(StatusCodes.UncertainLastUsableValue); + node.Timestamp.ToDateTime().ShouldBe(pStamp); + } + + /// U-4 positive control: A is confirmed by the device while B (newer) is still in flight; when B is then + /// refused the node reverts to A — the last confirmed value — not to the pre-A value. + [Fact] + public async Task A_refused_write_reverts_to_an_older_write_the_device_confirmed_meanwhile() + { + 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[0].SetResult(new NodeWriteOutcome(true, null)); + await WaitUntilAsync(() => _outcomeLogger.Confirmed >= 1); + _outcomeLogger.Confirmed.ShouldBe(1); + SdkValueBoundary.ToClr(node.Value).ShouldBe(42); // B still owns the node + pending[1].SetResult(new NodeWriteOutcome(false, "B refused")); + + await WaitUntilAsync(() => Equals(SdkValueBoundary.ToClr(node.Value), 41)); + SdkValueBoundary.ToClr(node.Value).ShouldBe(41); + node.StatusCode.ShouldBe(StatusCodes.Good); + } + + /// 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). + [Fact] + public async Task Interleaved_refused_writes_through_raw_and_uns_nodeids_both_revert_to_the_fanned_value() + { + var raw = Node("Int32", realm: AddressSpaceRealm.Raw); + var uns = Node("Int32", realm: AddressSpaceRealm.Uns); + var pStamp = new DateTime(2026, 12, 1, 9, 0, 0, DateTimeKind.Utc); + _manager.WriteValue("v", 7, OpcUaStatus.Good, pStamp, AddressSpaceRealm.Raw); + _manager.WriteValue("v", 7, OpcUaStatus.Good, pStamp, AddressSpaceRealm.Uns); + var pending = PendingOutcomes(); + + Write(raw, 41).ShouldBe(ServiceResult.Good); // A + Write(uns, 42).ShouldBe(ServiceResult.Good); // B + Write(uns, 43).ShouldBe(ServiceResult.Good); // C + Write(raw, 44).ShouldBe(ServiceResult.Good); // D + foreach (var i in new[] { 3, 1, 0, 2 }) pending[i].SetResult(new NodeWriteOutcome(false, $"refused {i}")); + + await WaitUntilAsync(() => Equals(SdkValueBoundary.ToClr(raw.Value), 7) && Equals(SdkValueBoundary.ToClr(uns.Value), 7)); + await WaitUntilAsync(() => _outcomeLogger.Superseded >= 2); + _outcomeLogger.Superseded.ShouldBeGreaterThanOrEqualTo(2); + foreach (var n in new[] { raw, uns }) + { + SdkValueBoundary.ToClr(n.Value).ShouldBe(7); + n.StatusCode.ShouldBe(StatusCodes.Good); + n.Timestamp.ToDateTime().ShouldBe(pStamp); + } + + var fresh = pStamp.AddMinutes(1); + _manager.WriteValue("v", 8, OpcUaStatus.Good, fresh, AddressSpaceRealm.Raw); + _manager.WriteValue("v", 8, OpcUaStatus.Good, fresh, AddressSpaceRealm.Uns); + SdkValueBoundary.ToClr(raw.Value).ShouldBe(8); + SdkValueBoundary.ToClr(uns.Value).ShouldBe(8); + } + + private List> PendingOutcomes() + { + var pending = new List>(); + _manager.NodeWriteGateway = new OutcomeGateway(_ => + { + var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + pending.Add(tcs); + return tcs.Task; + }); + return pending; + } + + private static async Task WaitUntilAsync(Func condition) + { + var deadline = DateTime.UtcNow.AddSeconds(5); + while (!condition() && DateTime.UtcNow < deadline) await Task.Delay(10, Ct); + } + private sealed class OutcomeLogger : ILogger { + private int _superseded; + private int _confirmed; internal TaskCompletionSource Ignored { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal int Superseded => Volatile.Read(ref _superseded); + internal int Confirmed => Volatile.Read(ref _confirmed); public IDisposable? BeginScope(TState state) where TState : notnull => null; public bool IsEnabled(LogLevel level) => true; public void Log(LogLevel level, EventId id, TState state, Exception? exception, Func formatter) { - if (formatter(state, exception).Contains("ignored superseded write outcome", StringComparison.Ordinal)) Ignored.TrySetResult(); + var text = formatter(state, exception); + if (text.Contains("ignored superseded write outcome", StringComparison.Ordinal)) + { + Interlocked.Increment(ref _superseded); + Ignored.TrySetResult(); + } + if (text.Contains("device confirmed write", StringComparison.Ordinal)) Interlocked.Increment(ref _confirmed); } } diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostActorSourceRemovedTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostActorSourceRemovedTests.cs index 0eab7f6f0..0b4d3afc6 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostActorSourceRemovedTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostActorSourceRemovedTests.cs @@ -137,6 +137,34 @@ public sealed class DriverHostActorSourceRemovedTests : RuntimeActorTestBase PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); } + /// + /// Gitea #979 (review 2026-12-02 R-6): a dependent still naming a ref the deploy removed is told + /// () instead of keeping the ref's last Good; a kept ref is + /// not. A late burst for the removed ref from a publisher the host has not retired is withheld from the mux, so + /// it cannot restore the stale Good; the kept driver's next value (the positive control / fence) still flows. + /// + [Fact] + public void A_deploy_that_removes_a_value_ref_tells_its_dependents_and_withholds_late_bursts_for_it() + { + ArrangeTwoDriversWithRetainedValues(); + + var revB = V3ArtifactSeeder.SeedV3Deployment(_db, RevB, [("DI-2", "Modbus2", "dev2", "flow", "Double", false)], NoRefs, enabled: true); + V3ArtifactSeeder.Dispatch(_host, _coordinator, revB, RevB); + + var removed = _holder.FishForMessage( + b => b.Items.Any(i => i.TagId == Path1 && i.StatusCode == DependencyMuxActor.RemovedInputStatus), PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + removed.Items.ShouldNotContain(i => i.TagId == Path2, "DI-2's ref is still deployed"); + + // A late Good burst for the removed ref, from a publisher the host never retired. + _host.Tell(ValuePublishes.Single("DI-1", Path1, 11.0, OpcUaStatus.Good, DateTime.UtcNow), CreateTestProbe().Ref); + Driver("DI-2").FireDataChange(Path2, 23.0); + _holder.FishForMessage(b => + { + b.Items.ShouldNotContain(i => i.TagId == Path1, "a late burst restored the removed ref's last Good"); + return b.Items.Any(i => i.TagId == Path2 && Equals(i.Value, 23.0)); + }, PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + } + /// Review I-1: a burst the removed child sent after the eviction (it stops asynchronously, so it keeps /// publishing through the rest of the apply) must be dropped by the host, not forwarded to re-retain the value. /// diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/VirtualTags/RemovedInputQualityTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/VirtualTags/RemovedInputQualityTests.cs new file mode 100644 index 000000000..a9c038817 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/VirtualTags/RemovedInputQualityTests.cs @@ -0,0 +1,136 @@ +using Akka.Actor; +using Serilog; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Commons.Engines; +using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; +using ZB.MOM.WW.OtOpcUa.OpcUaServer; +using ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms; +using ZB.MOM.WW.OtOpcUa.Core.Scripting; +using ZB.MOM.WW.OtOpcUa.Runtime.ScriptedAlarms; +using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness; +using ZB.MOM.WW.OtOpcUa.Runtime.VirtualTags; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.VirtualTags; + +/// +/// Gitea #979 (review 2026-12-02 R-6): an input that leaves the deployed set — a raw value ref +/// () or a VirtualTag output +/// () — reaches every dependent still naming it as +/// , instead of leaving it computing Good from the input's last +/// value. Before the fix the mux only forgot its retained copy; nothing was sent to current subscribers. +/// +public sealed class RemovedInputQualityTests : RuntimeActorTestBase +{ + private static CancellationToken Ct => TestContext.Current.CancellationToken; + + [Fact] + public void A_removed_value_ref_reaches_its_dependents_as_removed_and_the_identical_value_recovers_them() + { + var mux = Sys.ActorOf(DependencyMuxActor.Props()); + var dependent = CreateTestProbe(); + var recorder = CreateTestProbe(); // a non-replay subscriber, as the historization recorder registers + mux.Tell(new DependencyMuxActor.RegisterInterest(new[] { "Plant/Modbus/dev1/a" }, dependent.Ref, ReplayRetained: true)); + mux.Tell(new DependencyMuxActor.RegisterInterest(new[] { "Plant/Modbus/dev1/a" }, recorder.Ref)); + mux.Tell(ValuePublishes.Single("drv-1", "Plant/Modbus/dev1/a", 5d, OpcUaStatus.Good, DateTime.UtcNow)); + dependent.ExpectMsg(PresenceBudget, cancellationToken: Ct); + recorder.ExpectMsg(PresenceBudget, cancellationToken: Ct); + + mux.Tell(new DependencyMuxActor.ValueRefsRemoved(new[] { "Plant/Modbus/dev1/a", "never/subscribed" })); + + var gone = dependent.ExpectMsg(PresenceBudget, cancellationToken: Ct).Items.ShouldHaveSingleItem(); + gone.TagId.ShouldBe("Plant/Modbus/dev1/a"); + gone.Value.ShouldBeNull(); + gone.StatusCode.ShouldBe(DependencyMuxActor.RemovedInputStatus); + + // The retained copy is gone too: a returning replay registration is replayed nothing. + var late = CreateTestProbe(); + mux.Tell(new DependencyMuxActor.RegisterInterest(new[] { "Plant/Modbus/dev1/a" }, late.Ref, ReplayRetained: true)); + + // The IDENTICAL value re-published (the ref re-added) reaches everyone again — positive control for the + // recorder's absence below, and proof the removal did not leave the ref muted. + mux.Tell(ValuePublishes.Single("drv-1", "Plant/Modbus/dev1/a", 5d, OpcUaStatus.Good, DateTime.UtcNow)); + var back = dependent.ExpectMsg(PresenceBudget, cancellationToken: Ct).Items.ShouldHaveSingleItem(); + back.Value.ShouldBe(5d); + back.StatusCode.ShouldBe(OpcUaStatus.Good); + late.ExpectMsg(PresenceBudget, cancellationToken: Ct).Items.ShouldHaveSingleItem().Value.ShouldBe(5d); + // The recorder (non-replay) got the live value but never a synthetic removal sample. + recorder.ExpectMsg(PresenceBudget, cancellationToken: Ct).Items.ShouldHaveSingleItem() + .StatusCode.ShouldBe(OpcUaStatus.Good); + recorder.ExpectNoMsg(TimeSpan.FromMilliseconds(200), Ct); + } + + [Fact] + public void A_removed_virtual_tag_output_reaches_its_dependents_as_removed() + { + var mux = Sys.ActorOf(DependencyMuxActor.Props()); + var dependent = CreateTestProbe(); + mux.Tell(new DependencyMuxActor.RegisterInterest(new[] { "EQ-1/A" }, dependent.Ref, ReplayRetained: true)); + mux.Tell(new DependencyMuxActor.VirtualTagOutput("EQ-1/A", 10d, DateTime.UtcNow, OpcUaStatus.Good)); + dependent.ExpectMsg(PresenceBudget, cancellationToken: Ct); + + mux.Tell(new DependencyMuxActor.VirtualTagOutputsRemoved(new[] { "EQ-1/A" })); + + var gone = dependent.ExpectMsg(PresenceBudget, cancellationToken: Ct).Items.ShouldHaveSingleItem(); + gone.TagId.ShouldBe("EQ-1/A"); + gone.StatusCode.ShouldBe(DependencyMuxActor.RemovedInputStatus); + } + + /// A VirtualTag actor whose input is removed publishes the removed status, and the IDENTICAL value + /// re-arriving afterwards publishes Good again — the (value, status) dedup does not swallow either transition. + [Fact] + public void A_virtual_tag_whose_input_is_removed_publishes_bad_and_recovers_on_the_identical_value() + { + var mux = Sys.ActorOf(DependencyMuxActor.Props()); + var parent = CreateTestProbe(); + var vt = parent.ChildActorOf(VirtualTagActor.Props("vt-b", "passthrough", new PassthroughEvaluator(), + dependencyRefs: new[] { "EQ-1/A" }, mux: mux), cancellationToken: Ct); + AwaitAssert(() => + { + mux.Tell(new DependencyMuxActor.VirtualTagOutput("EQ-1/A", 10d, DateTime.UtcNow, OpcUaStatus.Good)); + parent.FishForMessage(r => Equals(r.Value, 10d) && r.StatusCode == OpcUaStatus.Good, + TimeSpan.FromMilliseconds(500), cancellationToken: Ct); + }, PresenceBudget, TimeSpan.FromMilliseconds(50), Ct); + + mux.Tell(new DependencyMuxActor.VirtualTagOutputsRemoved(new[] { "EQ-1/A" })); + parent.FishForMessage(r => r.StatusCode == DependencyMuxActor.RemovedInputStatus, PresenceBudget, cancellationToken: Ct); + + mux.Tell(new DependencyMuxActor.VirtualTagOutput("EQ-1/A", 10d, DateTime.UtcNow, OpcUaStatus.Good)); + parent.FishForMessage(r => Equals(r.Value, 10d) && r.StatusCode == OpcUaStatus.Good, PresenceBudget, cancellationToken: Ct); + vt.ShouldNotBeNull(); + } + + /// The scripted-alarm upstream a removed input feeds goes to the removed status instead of keeping the + /// input's last Good frozen in its cache. + [Fact] + public void A_scripted_alarm_upstream_reading_a_removed_input_goes_bad() + { + var mux = Sys.ActorOf(DependencyMuxActor.Props()); + var upstream = new DependencyMuxTagUpstreamSource(); + var logger = new LoggerConfiguration().CreateLogger(); + var engine = new ScriptedAlarmEngine(upstream, new InMemoryAlarmStateStore(), new ScriptLoggerFactory(logger), logger); + var host = Sys.ActorOf(ScriptedAlarmHostActor.Props(CreateTestProbe().Ref, mux, upstream, engine, null)); + host.Tell(new ScriptedAlarmHostActor.ApplyScriptedAlarms([new EquipmentScriptedAlarmPlan( + ScriptedAlarmId: "alm-1", EquipmentId: "Plant/Line1/M", Name: "HighTemp", AlarmType: "AlarmCondition", + Severity: 800, MessageTemplate: "condition", PredicateScriptId: "alm-1-script", + PredicateSource: "return (int)ctx.GetTag(\"M.T\").Value > 90;", DependencyRefs: ["M.T"], + HistorizeToAveva: false, Retain: true, Enabled: true)])); + + AwaitAssert(() => + { + mux.Tell(ValuePublishes.Single("drv-1", "M.T", 50, OpcUaStatus.Good, DateTime.UtcNow)); + upstream.ReadTag("M.T").StatusCode.ShouldBe(OpcUaStatus.Good); + }, PresenceBudget, TimeSpan.FromMilliseconds(50), Ct); + + mux.Tell(new DependencyMuxActor.ValueRefsRemoved(new[] { "M.T" })); + + AwaitAssert(() => upstream.ReadTag("M.T").StatusCode.ShouldBe(DependencyMuxActor.RemovedInputStatus), + PresenceBudget, cancellationToken: Ct); + } + + private sealed class PassthroughEvaluator : IVirtualTagEvaluator + { + public VirtualTagEvalResult Evaluate(string virtualTagId, string expression, IReadOnlyDictionary dependencies) => + VirtualTagEvalResult.Ok(dependencies.Values.FirstOrDefault()); + } +}