From 6836efaeb9b092982d6636f582a6fc2fe00b78e8 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 24 Nov 2026 09:22:08 -0500 Subject: [PATCH] =?UTF-8?q?feat(grpc-data):=20A1=20origin=20condition=20st?= =?UTF-8?q?ate=20in=20the=20node=20manager=20=E2=80=94=20delta=20callback,?= =?UTF-8?q?=20state=5Fknown,=20activation=20marker,=20sliced=20snapshot,?= =?UTF-8?q?=20MarkConditionsKnown=20sink=20seam,=20IAlarmInitialStateSigna?= =?UTF-8?q?l?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../OpcUa/DeferredAddressSpaceSink.cs | 8 + .../OpcUa/IOpcUaAddressSpaceSink.cs | 31 ++ .../IAlarmInitialStateSignal.cs | 68 ++++ .../ConditionStateRecords.cs | 98 +++++ .../OtOpcUaNodeManager.ConditionState.cs | 310 +++++++++++++++ .../OtOpcUaNodeManager.cs | 48 ++- .../SdkAddressSpaceSink.cs | 8 + .../ConditionStateNodeManagerTests.cs | 374 ++++++++++++++++++ 8 files changed, 934 insertions(+), 11 deletions(-) create mode 100644 src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/IAlarmInitialStateSignal.cs create mode 100644 src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ConditionStateRecords.cs create mode 100644 src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.ConditionState.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/ConditionStateNodeManagerTests.cs diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/OpcUa/DeferredAddressSpaceSink.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/OpcUa/DeferredAddressSpaceSink.cs index c27b54f8d..295506009 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/OpcUa/DeferredAddressSpaceSink.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/OpcUa/DeferredAddressSpaceSink.cs @@ -88,6 +88,14 @@ public sealed class DeferredAddressSpaceSink : IOpcUaAddressSpaceSink, ISurgical /// public void CompleteAddressSpaceApply() => _inner.CompleteAddressSpaceApply(); + /// + public void MarkConditionsKnown(string source, IReadOnlyList conditionIds, AddressSpaceRealm realm) + => _inner.MarkConditionsKnown(source, conditionIds, realm); + + /// + public void MarkConditionsUnknown(string source, IReadOnlyList conditionIds, AddressSpaceRealm realm) + => _inner.MarkConditionsUnknown(source, conditionIds, realm); + /// public void RaiseNodesAddedModelChange(string affectedNodeId, AddressSpaceRealm realm) => _inner.RaiseNodesAddedModelChange(affectedNodeId, realm); diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/OpcUa/IOpcUaAddressSpaceSink.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/OpcUa/IOpcUaAddressSpaceSink.cs index adce29fbc..cf98af301 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/OpcUa/IOpcUaAddressSpaceSink.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/OpcUa/IOpcUaAddressSpaceSink.cs @@ -213,6 +213,31 @@ public interface IOpcUaAddressSpaceSink { } + /// + /// A1 (plan §5.1 T1/T2): the state of has been ESTABLISHED by + /// (a driver's InitialAlarmStateDelivered, its backstop timer, or a scripted + /// alarm whose inputs were all pushed). An SDK-backed sink sets each materialised condition's known flag and + /// raises one state-only condition-state record per newly known condition. OpcUaPublishActor applies it + /// strictly after the alarm projections the source emitted before it (F2). Default: no-op. + /// + /// The source (driver instance id, or the scripted host) — diagnostics only. + /// The condition node ids (RawPath for native, ScriptedAlarmId for scripted). + /// Their realm. + void MarkConditionsKnown(string source, IReadOnlyList conditionIds, AddressSpaceRealm realm) + { + } + + /// + /// A1: withdraw "known" from conditions whose state can no longer be vouched for (a scripted alarm whose input + /// reverted to never-pushed). Raises one state-only record per condition that was known. Default: no-op. + /// + /// The source — diagnostics only. + /// The condition node ids. + /// Their realm. + void MarkConditionsUnknown(string source, IReadOnlyList conditionIds, AddressSpaceRealm realm) + { + } + /// /// Announce that nodes were added at runtime (discovered-node injection) under /// so subscribed clients refresh their browse @@ -316,6 +341,12 @@ public sealed class NullOpcUaAddressSpaceSink : IOpcUaAddressSpaceSink /// public void RebuildAddressSpace() { } + /// + public void MarkConditionsKnown(string source, IReadOnlyList conditionIds, AddressSpaceRealm realm) { } + + /// + public void MarkConditionsUnknown(string source, IReadOnlyList conditionIds, AddressSpaceRealm realm) { } + /// public void RaiseNodesAddedModelChange(string affectedNodeId, AddressSpaceRealm realm) { } diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/IAlarmInitialStateSignal.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/IAlarmInitialStateSignal.cs new file mode 100644 index 000000000..00c5af02d --- /dev/null +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/IAlarmInitialStateSignal.cs @@ -0,0 +1,68 @@ +namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions; + +/// +/// Optional companion to : the driver says when the standing state of a set of its +/// conditions has been established — the initial replay, refresh, poll or walk that covers them has +/// completed and every alarm event it produced has already been raised (plan +/// 2026-11-23-grpc-data-connections-history-alarms §5.1, F1/F2/G1/G5). +/// +/// +/// +/// An ordered callback, never a (F2). Raise +/// synchronously, on the same thread and callback path as +/// , after the last alarm event the completed read covers. The +/// host marshals both onto the same actor mailbox, so the "known" mark it derives is applied after every +/// projection the driver emitted before raising it. A task continuation could overtake queued transitions. +/// +/// +/// Carry what it covers (G1). lists the driver +/// ConditionIds (= the condition's RawPath, the routing key of the alarm event) whose state the +/// completed read established — never "the whole driver". An unreachable device's conditions are simply +/// left out and stay unknown. +/// +/// +/// Raise on every completed read or cycle, not only the first. Repeats are no-ops downstream; they are +/// what makes conditions known again after a reconnect or a deploy that adds conditions. +/// +/// +/// Suppression gate (G5). Obey exactly the gate obeys: raise +/// only while an alarm subscription is live. A refresh / poll / sentinel that completes while events are +/// suppressed raises nothing; the first signal after (re)subscribe follows the post-subscribe replay. +/// +/// +/// A source that cannot signal at all (an OPC UA upstream without ConditionRefresh) raises the event +/// once with set: the host then applies its +/// per-driver-type backstop timer to those conditions instead. No other shipped source should use it. +/// +/// +public interface IAlarmInitialStateSignal +{ + /// The standing state of has been delivered. + event EventHandler? InitialAlarmStateDelivered; +} + +/// Payload of . +public sealed class AlarmInitialStateEventArgs : EventArgs +{ + /// Creates the payload. + /// The driver condition ids (RawPaths) whose state the completed read established. + /// + /// when the source can never signal for these conditions (no refresh upstream); + /// the host's backstop timer applies instead of an immediate mark. + /// + public AlarmInitialStateEventArgs(IReadOnlyList conditionIds, bool unsignalable = false) + { + ArgumentNullException.ThrowIfNull(conditionIds); + ConditionIds = conditionIds; + Unsignalable = unsignalable; + } + + /// The driver condition ids (= RawPaths) the completed read covers. Never "everything". + public IReadOnlyList ConditionIds { get; } + + /// + /// The source reports InitialStateUnsignalable for these conditions: no real signal will ever come, + /// so the per-driver-type backstop timer (OpcUaClient only) decides when they become known. + /// + public bool Unsignalable { get; } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ConditionStateRecords.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ConditionStateRecords.cs new file mode 100644 index 000000000..21b016def --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ConditionStateRecords.cs @@ -0,0 +1,98 @@ +using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; + +namespace ZB.MOM.WW.OtOpcUa.OpcUaServer; + +/// +/// The origin-owned activation marker of one condition (plan §5.6 step 3, T3): (serving incarnation, +/// per-condition sequence). The sequence moves only on a NEW occurrence — an Active false→true edge or any +/// Acked true→false edge — never on a re-projection that leaves Active/Acked unchanged. +/// +/// The node manager's serving incarnation (one per process lifetime). +/// The per-condition occurrence sequence. +public readonly record struct ConditionActivationMarker(string Incarnation, ulong Sequence); + +/// +/// One immutable, SDK-free copy of a live condition's state (plan §5.1), produced by the node manager under its +/// Lock — either as a delta (raised for every condition state change) or inside a +/// . Invisible until A2 puts it on the wire. +/// +/// The condition's realm (Raw = native RawPath, Uns = ScriptedAlarmId). +/// The condition node id within . +/// Driver-fed (native) rather than scripted. +/// The hub version: the delta's own version, or the slice watermark for a snapshot copy. +/// A removal record: the condition left the address space. +/// +/// The condition's state has actually been established (§5.1 T2). A record with false never changes a +/// consumer's last state; it only marks the condition Uncertain. +/// +/// Part 9 ActiveState. +/// Part 9 AckedState. +/// Part 9 ConfirmedState. +/// Part 9 EnabledState. +/// The shelving kind. +/// The node's Part 9 severity (1..1000). +/// The node's message text. +/// The condition's source-data Quality status code. +/// The Part 9 ConditionClassName text, if set. +/// The condition's Time. +/// Part 9 Retain. +/// The origin-owned activation marker (T3). +/// The condition's Comment text, if any. +/// Who left that comment, if recorded. +public sealed record ConditionStateRecord( + AddressSpaceRealm Realm, + string ConditionId, + bool IsNative, + long Version, + bool Removed, + bool StateKnown, + bool Active, + bool Acknowledged, + bool Confirmed, + bool Enabled, + AlarmShelvingKind Shelving, + ushort Severity, + string Message, + uint Quality, + string? ConditionClassName, + DateTime TimeUtc, + bool Retain, + ConditionActivationMarker Activation, + string? Comment = null, + string? ClientUserId = null); + +/// +/// The node manager's SDK-free delta callback (plan §5.1). Implemented by the Runtime's ConditionStateHub. +/// +/// +/// Both members are called under the node manager's Lock, which is what makes a snapshot cut atomic: +/// every delta is either inside a slice or after its watermark. Implementations must therefore only enqueue — +/// no I/O, never block, never call back into the node manager. +/// +public interface IConditionStateSink +{ + /// The version of the last appended record (the snapshot watermark). Read under the node manager's Lock. + long Watermark { get; } + + /// Append one delta record. The sink assigns its version; the record's own Version is ignored. + /// The record. + /// The version assigned. + long Append(ConditionStateRecord record); + + /// + /// The node manager's address-space apply state changed: when a rebuild began (the + /// condition set is being re-created), when CompleteAddressSpaceApply ran. Part of + /// the snapshot_complete readiness (§5.1: apply complete + Primary verdict). + /// + /// Whether the current apply has completed. + void OnApplyStateChanged(bool complete); +} + +/// +/// One Lock hold of : at most MaxConditions +/// records plus the watermark at that instant. A delta for one of these conditions with a version above +/// applies after the slice; one at or below it is already inside. +/// +/// The sink's watermark taken under the same hold. +/// The copied records (each carries as its version). +public sealed record ConditionSnapshotSlice(long Watermark, IReadOnlyList Records); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.ConditionState.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.ConditionState.cs new file mode 100644 index 000000000..b2c0426db --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.ConditionState.cs @@ -0,0 +1,310 @@ +using Microsoft.Extensions.Logging; +using Opc.Ua; +using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; + +namespace ZB.MOM.WW.OtOpcUa.OpcUaServer; + +/// +/// A1 origin condition state (plan §5.1): the SDK-free delta callback, state_known, the activation marker +/// (T3) and the sliced snapshot. Every member that touches these maps runs under Lock; nothing here does +/// I/O or blocks — the sink only enqueues. +/// +public sealed partial class OtOpcUaNodeManager +{ + /// The default most conditions one snapshot Lock hold copies (§5.5 MaxConditions). + public const int DefaultMaxConditionsPerHold = 1000; + + /// Per-condition activation bookkeeping: the occurrence sequence plus the Active/Acked basis it was + /// last compared against. Mutable, only touched under Lock. + private sealed class ActivationEntry + { + public ulong Sequence; + public bool Active; + public bool Acked = true; + public ActivationEntry Clone() => new() { Sequence = Sequence, Active = Active, Acked = Acked }; + } + + private IConditionStateSink? _conditionStateSink; + private readonly HashSet _conditionStateKnown = new(); + private readonly Dictionary _activation = new(); + // Rebuild memory for SCRIPTED conditions (native ones ride NativeConditionCarryOver): their marker basis survives + // the clear-and-re-materialise so the engine's re-assert of an unchanged active alarm is not a new occurrence. + private readonly Dictionary _rebuildScriptedActivation = new(); + // Conditions a rebuild discarded and no materialise has claimed yet; at CompleteAddressSpaceApply the remainder + // gets a removal record. A condition that comes back is never announced as removed (T2: a rebuild must not make + // a consumer retire a condition that is still active at the origin). + private readonly HashSet _rebuildPendingRemoval = new(); + private bool _conditionApplyComplete; + + /// The serving incarnation the activation markers are minted under (one per node-manager lifetime). + internal string ConditionIncarnation { get; set; } = Guid.NewGuid().ToString("N"); + + /// Test seam: invoked after each snapshot Lock hold (outside it) with the records that hold copied. + internal Action? OnConditionSnapshotHold { get; set; } + + /// + /// The SDK-free condition-state delta callback (the Runtime's ConditionStateHub). Null = no hub; the + /// known flags and activation markers are still maintained. Set once at host start. + /// + public IConditionStateSink? ConditionStateSink + { + get => _conditionStateSink; + set + { + lock (Lock) + { + _conditionStateSink = value; + value?.OnApplyStateChanged(_conditionApplyComplete); + } + } + } + + /// Whether the last address-space apply has completed (CompleteAddressSpaceApply ran since the + /// last rebuild began). Part of the snapshot_complete readiness. + public bool IsConditionApplyComplete { get { lock (Lock) return _conditionApplyComplete; } } + + /// Whether the condition's state is known (test + diagnostics read). + /// The condition id. + /// Its realm. + /// when its state has been established. + public bool IsConditionStateKnown(string conditionNodeId, AddressSpaceRealm realm) + { + lock (Lock) return _conditionStateKnown.Contains(MapKey(realm, conditionNodeId)); + } + + /// The condition's current activation marker, or null when no such condition is materialised. + /// The condition id. + /// Its realm. + /// The marker. + public ConditionActivationMarker? GetActivationMarker(string conditionNodeId, AddressSpaceRealm realm) + { + lock (Lock) + { + var key = MapKey(realm, conditionNodeId); + return _alarmConditions.ContainsKey(key) && _activation.TryGetValue(key, out var e) + ? new ConditionActivationMarker(ConditionIncarnation, e.Sequence) : null; + } + } + + /// + /// Mark conditions whose state has been established (plan §5.1 T1/T2): sets the flag under Lock and raises + /// one state-only record per NEWLY known condition. Repeats and unmaterialised ids are no-ops. + /// + /// The source (driver instance id, or the scripted host) — diagnostics only. + /// The condition ids. + /// Their realm. + /// How many conditions became known. + public int MarkConditionsKnown(string source, IReadOnlyList conditionIds, AddressSpaceRealm realm) + { + ArgumentNullException.ThrowIfNull(conditionIds); + var marked = 0; + lock (Lock) + { + foreach (var id in conditionIds) + { + if (string.IsNullOrEmpty(id)) continue; + var key = MapKey(realm, id); + if (!_alarmConditions.TryGetValue(key, out var condition) || !_conditionStateKnown.Add(key)) continue; + RaiseConditionRecord(key, condition); + marked++; + } + } + + if (marked > 0) + _logger.LogDebug("OtOpcUaNodeManager: {Source} established the state of {Count} condition(s)", source, marked); + return marked; + } + + /// + /// Withdraw "known" from conditions whose state can no longer be vouched for (a scripted alarm whose input + /// reverted to never-pushed). Raises one state-only record per condition that was known. + /// + /// The source — diagnostics only. + /// The condition ids. + /// Their realm. + /// How many conditions became unknown. + public int MarkConditionsUnknown(string source, IReadOnlyList conditionIds, AddressSpaceRealm realm) + { + ArgumentNullException.ThrowIfNull(conditionIds); + var cleared = 0; + lock (Lock) + { + foreach (var id in conditionIds) + { + if (string.IsNullOrEmpty(id)) continue; + var key = MapKey(realm, id); + if (!_alarmConditions.TryGetValue(key, out var condition) || !_conditionStateKnown.Remove(key)) continue; + RaiseConditionRecord(key, condition); + cleared++; + } + } + + if (cleared > 0) + _logger.LogDebug("OtOpcUaNodeManager: {Source} withdrew the state of {Count} condition(s)", source, cleared); + return cleared; + } + + /// + /// Copy every live condition in (inactive, acknowledged and normal ones too — the + /// snapshot defines the SET), never more than per Lock hold. + /// Each slice carries the sink's watermark taken under the same hold, so a delta is either inside the slice or + /// after its watermark. A consumer must register for deltas before snapshotting. + /// + /// Realm + id filter (an export's root); evaluated outside Lock. + /// The most conditions one hold copies (≥ 1). + /// The slices in ascending (realm, id) order. + public IReadOnlyList SnapshotConditions( + Func scope, int maxConditionsPerHold = DefaultMaxConditionsPerHold) + { + ArgumentNullException.ThrowIfNull(scope); + ArgumentOutOfRangeException.ThrowIfLessThan(maxConditionsPerHold, 1); + + // Key enumeration and the scope filter run OFF Lock (the map is concurrent and keys are immutable); a + // condition added after this point is not in the snapshot but its materialise record is a delta. + var keys = _alarmConditions.Keys.Where(k => scope(k.Realm, k.Id)) + .OrderBy(k => k.Realm).ThenBy(k => k.Id, StringComparer.Ordinal).ToList(); + var slices = new List((keys.Count + maxConditionsPerHold - 1) / maxConditionsPerHold); + for (var start = 0; start < keys.Count; start += maxConditionsPerHold) + { + var end = Math.Min(start + maxConditionsPerHold, keys.Count); + var records = new List(end - start); + long watermark; + lock (Lock) + { + watermark = _conditionStateSink?.Watermark ?? 0; + for (var i = start; i < end; i++) + { + if (_alarmConditions.TryGetValue(keys[i], out var condition)) + records.Add(BuildConditionRecord(keys[i], condition, watermark, removed: false)); + } + } + + OnConditionSnapshotHold?.Invoke(records.Count); + slices.Add(new ConditionSnapshotSlice(watermark, records)); + } + + return slices; + } + + /// Called under Lock when a condition is (re)materialised: clears known, seeds (or restores) its + /// activation basis. The record is raised by . + private void BeginConditionMaterialise(RealmKey key, bool isNative) + { + _conditionStateKnown.Remove(key); + _rebuildPendingRemoval.Remove(key); + _activation[key] = !isNative && _rebuildScriptedActivation.Remove(key, out var kept) ? kept : new ActivationEntry(); + } + + /// Under Lock, after registration and any carry-over restore: raise the condition's first record. + /// It does NOT advance the activation basis: a scripted condition re-created by a rebuild keeps the basis it + /// had, so the engine's re-assert of the same still-active alarm onto the fresh (inactive) node is no new occurrence. + private void FinishConditionMaterialise(RealmKey key, AlarmConditionState alarm) => + _conditionStateSink?.Append(BuildConditionRecord(key, alarm, 0, removed: false)); + + /// Under Lock: a condition left the address space — drop its flags and raise a removal record. + private void ForgetConditionState(RealmKey key, AlarmConditionState condition) + { + _conditionStateKnown.Remove(key); + _activation.Remove(key, out var entry); + _conditionStateSink?.Append(BuildConditionRecord(key, condition, 0, removed: true, entry)); + } + + /// Under Lock, at the start of a full rebuild: remember what must survive the clear. + private void CaptureConditionStateForRebuild() + { + _conditionApplyComplete = false; + _conditionStateSink?.OnApplyStateChanged(false); + _rebuildScriptedActivation.Clear(); + foreach (var key in _alarmConditions.Keys) + { + _rebuildPendingRemoval.Add(key); + if (!_nativeAlarmNodeIds.Contains(key) && _activation.TryGetValue(key, out var e)) + _rebuildScriptedActivation[key] = e.Clone(); + } + + _conditionStateKnown.Clear(); + _activation.Clear(); + } + + /// Under Lock, at CompleteAddressSpaceApply: announce the conditions the rebuild dropped + /// for good, forget the rebuild memory and mark the apply complete. + private void CompleteConditionApply() + { + foreach (var key in _rebuildPendingRemoval) + { + if (_alarmConditions.ContainsKey(key)) continue; + _conditionStateSink?.Append(new ConditionStateRecord(key.Realm, key.Id, false, 0, Removed: true, StateKnown: false, + false, true, true, true, AlarmShelvingKind.Unshelved, 0, string.Empty, StatusCodes.Good.Code, null, UtcNow, false, + new ConditionActivationMarker(ConditionIncarnation, 0))); + } + + _rebuildPendingRemoval.Clear(); + _rebuildScriptedActivation.Clear(); + _conditionApplyComplete = true; + _conditionStateSink?.OnApplyStateChanged(true); + } + + /// Capture a native condition's marker basis + known flag for . + private (ulong Sequence, bool Active, bool Acked, bool Known) CaptureActivation(RealmKey key) + { + var known = _conditionStateKnown.Contains(key); + return _activation.TryGetValue(key, out var e) ? (e.Sequence, e.Active, e.Acked, known) : (0, false, true, known); + } + + /// Restore a carried native condition's marker basis and (T2) its known flag — carried-over state is + /// known at once, but only if it was known before the rebuild. + private void RestoreActivation(RealmKey key, ulong sequence, bool active, bool acked, bool known) + { + _activation[key] = new ActivationEntry { Sequence = sequence, Active = active, Acked = acked }; + if (known) _conditionStateKnown.Add(key); + } + + /// + /// Under Lock: advance the activation marker against the node's current Active/Acked and append one + /// record to the sink. Called for every condition state change — event-firing or silent. + /// + private void RaiseConditionRecord(RealmKey key, AlarmConditionState condition) + { + var entry = AdvanceActivation(key, condition); + _conditionStateSink?.Append(BuildConditionRecord(key, condition, 0, removed: false, entry)); + } + + /// The raise path for a condition known only by instance (ReportConditionEvent). + private void RaiseConditionRecord(AlarmConditionState condition) + { + var key = MapKey(condition.NodeId); + // A stale instance (replaced or removed) is not the live condition: its report never describes the set. + if (!_alarmConditions.TryGetValue(key, out var live) || !ReferenceEquals(live, condition)) return; + RaiseConditionRecord(key, condition); + } + + /// T3: bump on an Active false→true edge or ANY Acked true→false edge; never otherwise. + private ActivationEntry AdvanceActivation(RealmKey key, AlarmConditionState condition) + { + if (!_activation.TryGetValue(key, out var e)) _activation[key] = e = new ActivationEntry(); + var active = condition.ActiveState?.Id?.Value ?? false; + var acked = condition.AckedState?.Id?.Value ?? true; + if ((active && !e.Active) || (e.Acked && !acked)) e.Sequence++; + e.Active = active; + e.Acked = acked; + return e; + } + + private ConditionStateRecord BuildConditionRecord( + RealmKey key, AlarmConditionState c, long version, bool removed, ActivationEntry? entry = null) + { + entry ??= _activation.TryGetValue(key, out var e) ? e : null; + var delta = ReadConditionDelta(c); + return new ConditionStateRecord( + key.Realm, key.Id, _nativeAlarmNodeIds.Contains(key), version, removed, + StateKnown: !removed && _conditionStateKnown.Contains(key), + delta.Active, delta.Acknowledged, delta.Confirmed, delta.Enabled, delta.Shelving, delta.MappedSeverity, + delta.Message, delta.Quality.Code, + c.ConditionClassName?.Value.Text, + c.Time?.Value.ToDateTime() is { } t && t != DateTime.MinValue ? DateTime.SpecifyKind(t, DateTimeKind.Utc) : UtcNow, + c.Retain?.Value == true, + new ConditionActivationMarker(ConditionIncarnation, entry?.Sequence ?? 0), + c.Comment?.Value.Text, + c.ClientUserId?.Value); + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs index fa936fd0e..8ccc45efe 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs @@ -1419,10 +1419,18 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage // WireMethodTransitionReporting) equals the node's current state → no delta → suppress, so // the transition is reported exactly once. ReportConditionEvent // stamps a fresh EventId, ClearChangeMasks, and ReportEvent — all still under this lock. + // A1 (§5.1): a projected snapshot IS an established state. The record is raised by + // ReportConditionEvent when the gate fires, otherwise here as a state-only record (ConditionClass and + // the other silent fields). + _conditionStateKnown.Add(key); if (fire) { ReportConditionEvent(condition, sourceTimestampUtc); } + else + { + RaiseConditionRecord(key, condition); + } } } } @@ -1557,6 +1565,10 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage // the InstanceStateSnapshot captures the just-projected values. alarm.ClearChangeMasks(SystemContext, includeChildren: true); + // A1 (§5.1): the condition-state delta is raised BEFORE the Warm-Standby return, so a standby's hub stays + // current and a promoted Primary starts correct. + RaiseConditionRecord(alarm); + // Gitea #717 spec §4.5: on a Warm Standby only the STAMP half above runs — the condition node is current and a // later refresh carries a valid, ackable EventId — and the DELIVER half below does not. Suppressing here, before // the snapshot and every SDK field projection, covers the Server-object, folder and direct paths, ACL on or @@ -2640,6 +2652,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage AddPredefinedNode(SystemContext, alarm); _alarmConditions[conditionKey] = alarm; + BeginConditionMaterialise(conditionKey, isNative); if (!string.IsNullOrEmpty(equipmentNodeId)) IndexChild(MapKey(realm, equipmentNodeId), conditionKey); // Only the new condition can be missing its unit here, so raise just that one — a full reconcile // walks every condition, which made a deploy of N alarms O(N²) under Lock whenever any Server-object @@ -2659,6 +2672,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage // for a later re-add to resurrect. if (_rebuildCarryOver.Remove(conditionKey, out var carried) && isNative) RestoreCarryOver(alarm, conditionKey, carried); + FinishConditionMaterialise(conditionKey, alarm); } } @@ -2675,7 +2689,8 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage private sealed record NativeConditionCarryOver( AlarmConditionDelta State, DateTime Time, DateTime? ActiveTransitionTime, DateTime? QualityTimestamp, LocalizedText? Comment = null, string? ClientUserId = null, NodeId? ConditionClassId = null, - LocalizedText? ConditionClassName = null); + LocalizedText? ConditionClassName = null, ulong ActivationSequence = 0, bool ActivationActive = false, + bool ActivationAcked = true, bool StateKnown = false); /// /// Read what a native condition node holds right now, so the rebuild can put it back. @@ -2696,15 +2711,20 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage /// /// The live native condition, about to be discarded. /// Its carried state. - private NativeConditionCarryOver CaptureCarryOver(AlarmConditionState condition) => new( - ReadConditionDelta(condition), - condition.Time?.Value.ToDateTime() ?? UtcNow, - condition.ActiveState?.TransitionTime?.Value.ToDateTime(), - condition.Quality?.SourceTimestamp?.Value.ToDateTime(), - condition.Comment?.Value, - condition.ClientUserId?.Value, - condition.ConditionClassId?.Value, - condition.ConditionClassName?.Value); + private NativeConditionCarryOver CaptureCarryOver(RealmKey key, AlarmConditionState condition) + { + var a = CaptureActivation(key); + return new( + ReadConditionDelta(condition), + condition.Time?.Value.ToDateTime() ?? UtcNow, + condition.ActiveState?.TransitionTime?.Value.ToDateTime(), + condition.Quality?.SourceTimestamp?.Value.ToDateTime(), + condition.Comment?.Value, + condition.ClientUserId?.Value, + condition.ConditionClassId?.Value, + condition.ConditionClassName?.Value, + a.Sequence, a.Active, a.Acked, a.Known); + } /// /// Put a carried state back onto the freshly materialised native condition. MUST be called @@ -2733,6 +2753,8 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage private void RestoreCarryOver(AlarmConditionState alarm, RealmKey conditionKey, NativeConditionCarryOver carried) { var state = carried.State; + // A1 (T3, T2): the activation marker and the known flag ride the carry-over, normal conditions included. + RestoreActivation(conditionKey, carried.ActivationSequence, carried.ActivationActive, carried.ActivationAcked, carried.StateKnown); // #839: a driver-assigned ConditionClass is a property of the condition, not of its state — restored whether // or not the condition is off-normal (the materialise default is BaseConditionClass). if (alarm.ConditionClassId is { } classIdNode && carried.ConditionClassId is { } classId && !classId.IsNull) @@ -5583,8 +5605,9 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage _restoredConditionReports.Clear(); foreach (var (key, alarm) in _alarmConditions) { - if (_nativeAlarmNodeIds.Contains(key)) _rebuildCarryOver[key] = CaptureCarryOver(alarm); + if (_nativeAlarmNodeIds.Contains(key)) _rebuildCarryOver[key] = CaptureCarryOver(key, alarm); } + CaptureConditionStateForRebuild(); // tear down every native-alarm→equipment-folder notifier pair bidirectionally // BEFORE the conditions + folders are cleared below, so no inverse-notifier entry leaks across the @@ -5675,6 +5698,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage discarded = _rebuildCarryOver.Count; _restoredConditionReports.Clear(); _rebuildCarryOver.Clear(); + CompleteConditionApply(); } if (reported > 0 || discarded > 0) @@ -5778,6 +5802,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage // the condition drops — the folders (equipment, UNS realm) SURVIVE this scoped remove, so without // this they would keep a dangling inverse-notifier entry to the removed condition. UnwireAlarmNotifiers(key); + ForgetConditionState(key, condition); condition.Parent?.RemoveChild(condition); ForgetPredefinedSubtree(condition); _nativeAlarmNodeIds.Remove(key); @@ -5889,6 +5914,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage UnindexChild(key); TombstoneMonitoredSubtree(c, now); UnwireAlarmNotifiers(key); + ForgetConditionState(key, c); if (c.Parent is { } parent && !removedParents.Contains(parent)) parent.RemoveChild(c); ForgetPredefinedSubtree(c); _nativeAlarmNodeIds.Remove(key); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/SdkAddressSpaceSink.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/SdkAddressSpaceSink.cs index 42965bce1..9d3358267 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/SdkAddressSpaceSink.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/SdkAddressSpaceSink.cs @@ -141,6 +141,14 @@ public sealed class SdkAddressSpaceSink : IOpcUaAddressSpaceSink, ISurgicalAddre /// public void CompleteAddressSpaceApply() => _nodeManager.CompleteAddressSpaceApply(); + /// + public void MarkConditionsKnown(string source, IReadOnlyList conditionIds, AddressSpaceRealm realm) + => _nodeManager.MarkConditionsKnown(source, conditionIds, realm); + + /// + public void MarkConditionsUnknown(string source, IReadOnlyList conditionIds, AddressSpaceRealm realm) + => _nodeManager.MarkConditionsUnknown(source, conditionIds, realm); + /// public void RaiseNodesAddedModelChange(string affectedNodeId, AddressSpaceRealm realm) => _nodeManager.RaiseNodesAddedModelChange(affectedNodeId, realm); diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/ConditionStateNodeManagerTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/ConditionStateNodeManagerTests.cs new file mode 100644 index 000000000..ebe4b28de --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/ConditionStateNodeManagerTests.cs @@ -0,0 +1,374 @@ +using Opc.Ua; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; + +namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests; + +/// +/// A1 origin condition state (plan §5.1) at the node manager: the delta callback, state_known, the activation +/// marker (T3) and the sliced snapshot. The parity cases (a)–(g) assert on NODE state: after each scenario the +/// delta stream folded per condition equals a fresh snapshot of the live nodes. +/// +[Trait("Feature", "GrpcData")] +[Trait("Phase", "A1")] +[Trait("Category", "Unit")] +public sealed class ConditionStateNodeManagerTests : IDisposable +{ + private const string Device = "Plant/Galaxy/dev1"; + private const string Native = "Plant/Galaxy/dev1/TankHi"; + private const string Native2 = "Plant/Galaxy/dev1/TankLo"; + private const string Equipment = "Area/Line/Eq"; + private const string Scripted = "scripted-eq-hi"; + + private static CancellationToken Ct => TestContext.Current.CancellationToken; + private readonly string _pkiRoot = Path.Combine(Path.GetTempPath(), $"otopcua-a1-{Guid.NewGuid():N}"); + + private static AlarmConditionSnapshot State(bool active, bool acked, string message = "hi", uint status = OpcUaStatus.Good, + AlarmConditionClass? cls = null) => new( + Active: active, Acknowledged: acked, Confirmed: true, Enabled: true, Shelving: AlarmShelvingKind.Unshelved, + Severity: 700, Message: message, StatusCode: status, ConditionClass: cls); + + // ---------------------------------------------------------------- parity (a)–(g) + + [Fact] + public async Task a_Cold_start_before_any_publish_lists_every_condition_unknown() + { + var (host, nm, sink) = await BootAsync(); + MaterialiseAll(nm); + nm.CompleteAddressSpaceApply(); + + var snap = Flatten(nm.SnapshotConditions((_, _) => true)); + snap.Count.ShouldBe(3); // the snapshot defines the SET, normal conditions included + snap.ShouldAllBe(r => !r.StateKnown); + // Falsely-normal guard: no record ever claimed known before a source established a state. + sink.Records.ShouldNotContain(r => r.StateKnown); + AssertParity(nm, sink); + await host.DisposeAsync(); + } + + [Fact] + public async Task b_Standby_promotion_with_standing_active_alarms_keeps_the_hub_current() + { + var (host, nm, sink) = await BootAsync(warm: true); + nm.Standby.AlarmsSuppressed = true; // what a Warm OpcUaPublishActor sets while this node is not Primary + nm.Standby.AlarmsSuppressed.ShouldBeTrue(); + MaterialiseAll(nm); + nm.CompleteAddressSpaceApply(); + + // While Warm the event is suppressed, but the delta is raised before that return. + nm.WriteAlarmCondition(Native, State(true, false), DateTime.UtcNow, AddressSpaceRealm.Raw); + sink.Records.Last().ShouldSatisfyAllConditions( + r => r.ConditionId.ShouldBe(Native), r => r.Active.ShouldBeTrue(), r => r.StateKnown.ShouldBeTrue()); + + nm.Standby.AlarmsSuppressed = false; // promotion + AssertParity(nm, sink); + Flatten(nm.SnapshotConditions((_, id) => id == Native)).Single().Active.ShouldBeTrue(); + await host.DisposeAsync(); + } + + [Fact] + public async Task c_Rebuild_with_carried_over_alarms_is_known_at_once_and_never_announced_removed() + { + var (host, nm, sink) = await BootAsync(); + MaterialiseAll(nm); + nm.CompleteAddressSpaceApply(); + nm.WriteAlarmCondition(Native, State(true, false), DateTime.UtcNow, AddressSpaceRealm.Raw); + var marker = nm.GetActivationMarker(Native, AddressSpaceRealm.Raw).ShouldNotBeNull(); + var before = sink.Records.Count; + + nm.RebuildAddressSpace(); + sink.ApplyComplete.ShouldBe(false); + // Native2 (never known) comes back too; the scripted one does NOT come back. + nm.EnsureFolder(Device, null, "dev1", AddressSpaceRealm.Raw); + nm.MaterialiseAlarmCondition(Native, Device, "TankHi", "OffNormalAlarm", 700, AddressSpaceRealm.Raw, isNative: true); + nm.MaterialiseAlarmCondition(Native2, Device, "TankLo", "OffNormalAlarm", 700, AddressSpaceRealm.Raw, isNative: true); + + // Carried over ⇒ known at once, same occurrence marker (T3). + nm.IsConditionStateKnown(Native, AddressSpaceRealm.Raw).ShouldBeTrue(); + nm.GetActivationMarker(Native, AddressSpaceRealm.Raw).ShouldBe(marker); + // A carried NORMAL condition that was never known stays unknown (no falsely-normal known). + nm.IsConditionStateKnown(Native2, AddressSpaceRealm.Raw).ShouldBeFalse(); + + nm.CompleteAddressSpaceApply(); + sink.ApplyComplete.ShouldBe(true); + var rebuild = sink.Records.Skip(before).ToList(); + rebuild.ShouldNotContain(r => r.Removed && r.ConditionId == Native); + rebuild.ShouldContain(r => r.Removed && r.ConditionId == Scripted); + rebuild.Where(r => r.ConditionId == Native).ShouldAllBe(r => r.Active && r.StateKnown); + AssertParity(nm, sink); + await host.DisposeAsync(); + } + + [Fact] + public async Task d_A_local_client_native_ack_applied_by_the_SDK_reaches_the_hub() + { + var (host, nm, sink) = await BootAsync(); + MaterialiseAll(nm); + nm.WriteAlarmCondition(Native, State(true, false), DateTime.UtcNow, AddressSpaceRealm.Raw); + var alarm = nm.TryGetAlarmCondition(Native, AddressSpaceRealm.Raw).ShouldNotBeNull(); + + // The SDK's own Acknowledge handler, behind our method-transition wrapper; the driver route is stubbed Good. + alarm.OnAcknowledge = (_, _, _, _) => ServiceResult.Good; + var result = alarm.Acknowledge!.OnCall!(nm.SystemContext, alarm.Acknowledge, alarm.NodeId, + alarm.EventId!.Value, new LocalizedText("ok")); + ServiceResult.IsGood(result).ShouldBeTrue(result.ToString()); + + alarm.AckedState!.Id!.Value.ShouldBeTrue(); + sink.Records.Last().ShouldSatisfyAllConditions(r => r.ConditionId.ShouldBe(Native), r => r.Acknowledged.ShouldBeTrue()); + AssertParity(nm, sink); + await host.DisposeAsync(); + } + + [Fact] + public async Task e_A_ConditionClass_only_change_raises_a_state_only_record_and_no_event() + { + var (host, nm, sink) = await BootAsync(); + MaterialiseAll(nm); + nm.WriteAlarmCondition(Native, State(true, false), DateTime.UtcNow, AddressSpaceRealm.Raw); + var alarm = nm.TryGetAlarmCondition(Native, AddressSpaceRealm.Raw).ShouldNotBeNull(); + var eventId = alarm.EventId!.Value.ToArray(); + var count = sink.Records.Count; + + nm.WriteAlarmCondition(Native, State(true, false, cls: AlarmConditionClass.Safety), DateTime.UtcNow, AddressSpaceRealm.Raw); + + alarm.EventId!.Value.ToArray().ShouldBe(eventId); // the delta gate fired nothing + sink.Records.Count.ShouldBe(count + 1); + sink.Records.Last().ConditionClassName.ShouldBe("SafetyConditionClass"); + AssertParity(nm, sink); + await host.DisposeAsync(); + } + + [Fact] + public async Task f_An_ack_revert_reaches_the_hub_and_is_a_new_occurrence() + { + var (host, nm, sink) = await BootAsync(); + MaterialiseAll(nm); + nm.WriteAlarmCondition(Native, State(true, false), DateTime.UtcNow, AddressSpaceRealm.Raw); + nm.WriteAlarmCondition(Native, State(true, true), DateTime.UtcNow, AddressSpaceRealm.Raw); // ack applied + var acked = nm.GetActivationMarker(Native, AddressSpaceRealm.Raw)!.Value.Sequence; + + nm.WriteAlarmCondition(Native, State(true, false), DateTime.UtcNow, AddressSpaceRealm.Raw); // #760 revert + + sink.Records.Last().Acknowledged.ShouldBeFalse(); + nm.GetActivationMarker(Native, AddressSpaceRealm.Raw)!.Value.Sequence.ShouldBe(acked + 1); // F4: Acked true→false + AssertParity(nm, sink); + await host.DisposeAsync(); + } + + [Fact] + public async Task g_A_quality_only_update_reaches_the_hub() + { + var (host, nm, sink) = await BootAsync(); + MaterialiseAll(nm); + nm.WriteAlarmCondition(Native, State(false, true), DateTime.UtcNow, AddressSpaceRealm.Raw); + + nm.WriteAlarmQuality(Native, StatusCodes.BadNoCommunication.Code, DateTime.UtcNow, AddressSpaceRealm.Raw); + + sink.Records.Last().Quality.ShouldBe(StatusCodes.BadNoCommunication.Code); + AssertParity(nm, sink); + await host.DisposeAsync(); + } + + // ---------------------------------------------------------------- known / T1 / T3 + + [Fact] + public async Task T1_A_signal_after_the_snapshot_cut_arrives_as_a_state_only_known_record() + { + var (host, nm, sink) = await BootAsync(); + MaterialiseAll(nm); + nm.CompleteAddressSpaceApply(); + var slice = nm.SnapshotConditions((r, _) => r == AddressSpaceRealm.Raw).Single(); + slice.Records.ShouldAllBe(r => !r.StateKnown); + // Negative control: nothing claims known before the signal. + sink.Records.Where(r => r.Version > slice.Watermark).ShouldBeEmpty(); + + nm.MarkConditionsKnown("drv", [Native, Native2], AddressSpaceRealm.Raw).ShouldBe(2); + + var after = sink.Records.Where(r => r.Version > slice.Watermark).ToList(); + after.Count.ShouldBe(2); // positive control: the records arrive with no further origin activity + after.ShouldAllBe(r => r.StateKnown && !r.Active); + // A repeat signal is a no-op. + nm.MarkConditionsKnown("drv", [Native], AddressSpaceRealm.Raw).ShouldBe(0); + sink.Records.Count(r => r.Version > slice.Watermark).ShouldBe(2); + await host.DisposeAsync(); + } + + [Fact] + public async Task Marking_unknown_withdraws_known_and_rematerialise_clears_it() + { + var (host, nm, sink) = await BootAsync(); + MaterialiseAll(nm); + nm.MarkConditionsKnown("scripted", [Scripted], AddressSpaceRealm.Uns); + nm.MarkConditionsUnknown("scripted", [Scripted], AddressSpaceRealm.Uns).ShouldBe(1); + nm.IsConditionStateKnown(Scripted, AddressSpaceRealm.Uns).ShouldBeFalse(); + sink.Records.Last().StateKnown.ShouldBeFalse(); + nm.MarkConditionsUnknown("scripted", [Scripted], AddressSpaceRealm.Uns).ShouldBe(0); + await host.DisposeAsync(); + } + + [Fact] + public async Task T3_The_marker_moves_only_on_a_new_occurrence() + { + var (host, nm, _) = await BootAsync(); + MaterialiseAll(nm); + ulong Seq() => nm.GetActivationMarker(Native, AddressSpaceRealm.Raw)!.Value.Sequence; + Seq().ShouldBe(0ul); + nm.WriteAlarmCondition(Native, State(true, false), DateTime.UtcNow, AddressSpaceRealm.Raw); + Seq().ShouldBe(1ul); + nm.WriteAlarmCondition(Native, State(true, false, message: "changed"), DateTime.UtcNow, AddressSpaceRealm.Raw); + nm.WriteAlarmCondition(Native, State(true, false, message: "changed"), DateTime.UtcNow, AddressSpaceRealm.Raw); + Seq().ShouldBe(1ul); // message-only change and same-state re-projection + nm.WriteAlarmCondition(Native, State(false, true), DateTime.UtcNow, AddressSpaceRealm.Raw); + Seq().ShouldBe(1ul); + nm.WriteAlarmCondition(Native, State(false, false), DateTime.UtcNow, AddressSpaceRealm.Raw); // InactiveUnacknowledged + Seq().ShouldBe(2ul); + await host.DisposeAsync(); + } + + [Fact] + public async Task A_scripted_condition_keeps_its_marker_across_a_rebuild_reassert() + { + var (host, nm, _) = await BootAsync(); + MaterialiseAll(nm); + nm.WriteAlarmCondition(Scripted, State(true, false), DateTime.UtcNow, AddressSpaceRealm.Uns); + var marker = nm.GetActivationMarker(Scripted, AddressSpaceRealm.Uns); + + nm.RebuildAddressSpace(); + MaterialiseAll(nm); + nm.IsConditionStateKnown(Scripted, AddressSpaceRealm.Uns).ShouldBeFalse(); // scripted: re-established by its engine + nm.WriteAlarmCondition(Scripted, State(true, false), DateTime.UtcNow, AddressSpaceRealm.Uns); // the re-assert + nm.CompleteAddressSpaceApply(); + + nm.GetActivationMarker(Scripted, AddressSpaceRealm.Uns).ShouldBe(marker); + await host.DisposeAsync(); + } + + // ---------------------------------------------------------------- snapshot structure + + [Fact] + public async Task A_snapshot_never_copies_more_than_MaxConditions_under_one_Lock_hold() + { + var (host, nm, sink) = await BootAsync(); + nm.EnsureFolder(Device, null, "dev1", AddressSpaceRealm.Raw); + for (var i = 0; i < 25; i++) + nm.MaterialiseAlarmCondition($"{Device}/A{i:00}", Device, $"A{i:00}", "OffNormalAlarm", 500, AddressSpaceRealm.Raw, isNative: true); + + var holds = new List(); + nm.OnConditionSnapshotHold = n => + { + Monitor.IsEntered(nm.Lock).ShouldBeFalse(); // reported after the hold is released + holds.Add(n); + // A delta raised BETWEEN holds: into the second slice (A15) and into the first, already-cut one (A00). + if (holds.Count == 1) + { + nm.WriteAlarmCondition($"{Device}/A15", State(true, false), DateTime.UtcNow, AddressSpaceRealm.Raw); + nm.WriteAlarmCondition($"{Device}/A00", State(true, false), DateTime.UtcNow, AddressSpaceRealm.Raw); + } + }; + + var slices = nm.SnapshotConditions((_, _) => true, maxConditionsPerHold: 10); + + holds.ShouldBe([10, 10, 5]); + slices.Count.ShouldBe(3); + // Atomic cut: A15's change is inside slice 2 (≤ its watermark); A00's is after slice 1's watermark. + slices[1].Records.Single(r => r.ConditionId.EndsWith("A15")).Active.ShouldBeTrue(); + slices[0].Records.Single(r => r.ConditionId.EndsWith("A00")).Active.ShouldBeFalse(); + sink.Records.Single(r => r.ConditionId.EndsWith("A00") && r.Active).Version.ShouldBeGreaterThan(slices[0].Watermark); + sink.Records.Single(r => r.ConditionId.EndsWith("A15") && r.Active).Version.ShouldBeLessThanOrEqualTo(slices[1].Watermark); + await host.DisposeAsync(); + } + + // ---------------------------------------------------------------- helpers + + private static void MaterialiseAll(OtOpcUaNodeManager nm) + { + nm.EnsureFolder(Device, null, "dev1", AddressSpaceRealm.Raw); + nm.MaterialiseAlarmCondition(Native, Device, "TankHi", "OffNormalAlarm", 700, AddressSpaceRealm.Raw, isNative: true); + nm.MaterialiseAlarmCondition(Native2, Device, "TankLo", "OffNormalAlarm", 700, AddressSpaceRealm.Raw, isNative: true); + nm.EnsureFolder(Equipment, null, "Eq", AddressSpaceRealm.Uns); + nm.MaterialiseAlarmCondition(Scripted, Equipment, "Hi", "AlarmCondition", 500, AddressSpaceRealm.Uns); + } + + private static List Flatten(IReadOnlyList slices) => + slices.SelectMany(s => s.Records).ToList(); + + /// Hub snapshot == node state: the delta stream folded per condition equals a fresh snapshot of the nodes. + internal static void AssertParity(OtOpcUaNodeManager nm, RecordingConditionSink sink) + { + var fold = new Dictionary<(AddressSpaceRealm, string), ConditionStateRecord>(); + foreach (var r in sink.Records) + { + if (r.Removed) fold.Remove((r.Realm, r.ConditionId)); + else fold[(r.Realm, r.ConditionId)] = r; + } + + var nodes = nm.SnapshotConditions((_, _) => true).SelectMany(s => s.Records).ToList(); + fold.Count.ShouldBe(nodes.Count); + foreach (var node in nodes) + { + fold.TryGetValue((node.Realm, node.ConditionId), out var folded).ShouldBeTrue(node.ConditionId); + (folded! with { Version = 0 }).ShouldBe(node with { Version = 0 }, node.ConditionId); + } + } + + private async Task<(OpcUaApplicationHost Host, OtOpcUaNodeManager Nm, RecordingConditionSink Sink)> BootAsync(bool warm = false) + { + var applicationUri = $"urn:OtOpcUa.A1Test:{Guid.NewGuid():N}"; + var started = await OpcUaHostStart.StartAsync( + port => new OpcUaApplicationHost( + new OpcUaApplicationHostOptions + { + ApplicationName = "OtOpcUa.A1Test", + ApplicationUri = applicationUri, + OpcUaPort = port, + PublicHostname = "localhost", + PkiStoreRoot = _pkiRoot, + Redundancy = new OpcUaRedundancyOptions { Mode = warm ? "Warm" : "Unset" }, + PeerApplicationUris = warm ? ["urn:peer"] : [], + }, + Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance), + () => new OtOpcUaSdkServer(), Ct); + var nm = started.Server.NodeManager!; + var sink = new RecordingConditionSink(); + nm.ConditionStateSink = sink; + return (started.Host, nm, sink); + } + + /// Cleans up the PKI root directory. + public void Dispose() + { + if (Directory.Exists(_pkiRoot)) + { + try { Directory.Delete(_pkiRoot, recursive: true); } + catch { /* best-effort cleanup */ } + } + } +} + +/// An in-memory that keeps every record with its assigned version. +internal sealed class RecordingConditionSink : IConditionStateSink +{ + private long _version; + + /// Every appended record, in order, with its version. + public List Records { get; } = new(); + + /// The last apply state the node manager reported. + public bool? ApplyComplete { get; private set; } + + /// + public long Watermark => _version; + + /// + public long Append(ConditionStateRecord record) + { + var v = ++_version; + Records.Add(record with { Version = v }); + return v; + } + + /// + public void OnApplyStateChanged(bool complete) => ApplyComplete = complete; +}